From fac35af0fe88d7005ca0a5ac6b137dcef10dcef3 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:37:30 +0100 Subject: [PATCH 01/38] allow multi-char operators --- key/key.core/src/main/antlr4/KeYLexer.g4 | 160 ++++-------------- key/key.core/src/main/antlr4/KeYParser.g4 | 2 +- .../nparser/builder/ExpressionBuilder.java | 10 +- 3 files changed, 39 insertions(+), 133 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 285c41062ab..3e161b1e64d 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -271,137 +271,45 @@ VOCAB : '\u0003'..'\u0377' ; -SEMI -: ';' - ; - -SLASH -: '/' - ; - -COLON: ':'; - -DOUBLECOLON -: '::' - ; - -ASSIGN -: ':=' - ; - -DOT -: '.' - ; - -DOTRANGE -: '.' '.' - ; - -COMMA -: ',' - ; - -LPAREN -: - '(' - ; - -RPAREN -: ')' - ; - -LBRACE -: '{' - ; - -RBRACE -: '}' - ; - -LBRACKET -: '[' - ; - -RBRACKET -: ']' - ; - -EMPTYBRACKETS -: '[' ']' - ; - -AT -: '@' - ; - -PARALLEL -: '|' '|' - ; - - -OR -: '|' | '\u2228' - ; +fragment OP_SFX: [-+*/&.^]+; + +SEMI: ';'; +SLASH: '/'; +COLON: ':'; +DOUBLECOLON:'::'; +ASSIGN: ':='; +DOT: '.'; +DOTRANGE: '.' '.'; +COMMA: ','; +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACKET: '['; +RBRACKET: ']'; +EMPTYBRACKETS: '[' ']'; +AT: '@'; +PARALLEL: '|' '|'; +OR: '|' | '\u2228'; AND : '&' | '\u2227' ; -NOT -: '!' | '\u00AC' - ; - -IMP -: '->' | '\u2192' - ; - -EQUALS -: '=' - ; - -NOT_EQUALS -: '!=' | '\u2260' - ; - -SEQARROW -: '==>' | '\u27F9' - ; - -EXP -: '^' - ; - -TILDE -: '~' - ; - -PERCENT -: '%' - ; - -STAR -: '*' - ; - -MINUS -: '-' - ; - -PLUS -: '+' - ; - -GREATER -: '>' - ; - -GREATEREQUAL -: '>' '=' | '\u2265' - ; - -RGUILLEMETS - : '>' '>' - ; +NOT: '!' | '\u00AC'; +IMP: '->' | '\u2192'; +EQUALS: '='; +NOT_EQUALS: '!=' | '\u2260'; +SEQARROW: '==>' | '\u27F9'; +EXP: '^' OP_SFX?; +TILDE: '~' OP_SFX?; +PERCENT: '%' OP_SFX?; +STAR : '*' OP_SFX?; +MINUS: '-' OP_SFX?; +PLUS: '+' OP_SFX?; +GREATER: '>' ; +GREATEREQUAL: '>' '=' | '\u2265'; +RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index a2af54cd921..b7261612d95 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -367,7 +367,7 @@ equality_term: a=comparison_term ((NOT_EQUALS|EQUALS) b=comparison_term)?; comparison_term: a=weak_arith_term ((LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; weak_arith_term: a=strong_arith_term_1 (op+=(PLUS|MINUS) b+=strong_arith_term_1)*; strong_arith_term_1: a=strong_arith_term_2 (STAR b+=strong_arith_term_2)*; -strong_arith_term_2: a=atom_prefix ((PERCENT|SLASH) b=strong_arith_term_2)?; +strong_arith_term_2: a=atom_prefix (op=(PERCENT|SLASH) b=strong_arith_term_2)?; update_term: (LBRACE u=term RBRACE) (atom_prefix | unary_formula); substitution_term: LBRACE SUBST bv=one_bound_variable SEMI diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 4e5a4d7c2c7..7a6281dc470 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -308,10 +308,8 @@ public Object visitWeak_arith_term(KeYParser.Weak_arith_termContext ctx) { Term last = termL; for (int i = 0; i < terms.size(); i++) { final String opTok = ctx.op.get(i).getText(); - // it's either + or -. - String opname = opTok.equals("+") ? "add" : "sub"; Term cur = terms.get(i); - last = binaryLDTSpecificTerm(ctx, opname, last, cur); + last = binaryLDTSpecificTerm(ctx, opTok, last, cur); } return last; } @@ -344,7 +342,7 @@ public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) Term last = termL; for (int i = 0; i < terms.size(); i++) { Term cur = terms.get(i); - last = binaryLDTSpecificTerm(ctx, "mul", last, cur); + last = binaryLDTSpecificTerm(ctx, ctx.STAR(i).getText(), last, cur); } return last; } @@ -355,8 +353,8 @@ public Object visitStrong_arith_term_2(KeYParser.Strong_arith_term_2Context ctx) if (ctx.b == null) return termL; Term termR = accept(ctx.b); - String opName = ctx.SLASH() != null ? "div" : "mod"; - return binaryLDTSpecificTerm(ctx, opName, termL, termR); + //String opName = ctx.SLASH() != null ? "div" : "mod"; + return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } protected Term capsulateTf(ParserRuleContext ctx, Supplier termSupplier) { From 9689360e465e8e5ca4e69f91890881b50cae6485 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:42:59 +0100 Subject: [PATCH 02/38] add metadata information to functions and predicates --- key/key.core/src/main/antlr4/KeYLexer.g4 | 7 ++++++- key/key.core/src/main/antlr4/KeYParser.g4 | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 3e161b1e64d..acbaf3d0311 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -233,6 +233,9 @@ PREDICATES : '\\predicates'; FUNCTIONS : '\\functions'; TRANSFORMERS : '\\transformers'; UNIQUE : '\\unique'; +INFIX: '\\infix'; +PREFIX: '\\prefix'; +POSTFIX: '\\postfix'; RULES : '\\rules'; AXIOMS : '\\axioms'; @@ -310,7 +313,9 @@ PLUS: '+' OP_SFX?; GREATER: '>' ; GREATEREQUAL: '>' '=' | '\u2265'; RGUILLEMETS: '>' '>' ; - + + + WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; LESS: '<'; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index b7261612d95..684d870e173 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -230,6 +230,7 @@ pred_decl pred_name = funcpred_name (whereToBind=where_to_bind)? argSorts=arg_sorts + functionMetaData? SEMI ; @@ -246,9 +247,17 @@ func_decl func_name = funcpred_name whereToBind=where_to_bind? argSorts = arg_sorts + functionMetaData? SEMI ; +functionMetaData +: + INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN + | PREFIX LPAREN (MINUS|TILDE) RPAREN + | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN +; + func_decls : FUNCTIONS From 2876402cdeb051d91181894a2f48ef53e6a6eebb Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:54:39 +0100 Subject: [PATCH 03/38] add MixFitInfo to capture information --- .../de/uka/ilkd/key/logic/op/Function.java | 80 ++++++++++++++++--- .../builder/FunctionPredicateBuilder.java | 8 +- 2 files changed, 73 insertions(+), 15 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java index bc4eab03d51..dafd11d9956 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java @@ -19,6 +19,9 @@ import de.uka.ilkd.key.logic.sort.NullSort; import de.uka.ilkd.key.logic.sort.Sort; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Objects of this class represent function and predicate symbols. Note @@ -26,6 +29,7 @@ * of function. */ public class Function extends AbstractSortedOperator { + private final MixFitInfo mixFitInfo; private final boolean unique; private final boolean skolemConstant; @@ -34,6 +38,24 @@ public class Function extends AbstractSortedOperator { //------------------------------------------------------------------------- //constructors //------------------------------------------------------------------------- + Function(Name name, + Sort sort, + ImmutableArray argSorts, + ImmutableArray whereToBind, + boolean unique, + boolean isRigid, + boolean isSkolemConstant, + @Nullable MixFitInfo mixFitInfo) { + super(name, argSorts, sort, whereToBind, isRigid); + + this.unique = unique; + skolemConstant = isSkolemConstant; + assert sort != Sort.UPDATE; + assert !(unique && sort == Sort.FORMULA); + assert !(sort instanceof NullSort) || name.toString().equals("null") + : "Functions with sort \"null\" are not allowed: " + this; + this.mixFitInfo = mixFitInfo; + } Function(Name name, Sort sort, @@ -42,24 +64,20 @@ public class Function extends AbstractSortedOperator { boolean unique, boolean isRigid, boolean isSkolemConstant) { - super(name, argSorts, sort, whereToBind, isRigid); - - this.unique = unique; - skolemConstant = isSkolemConstant; - assert sort != Sort.UPDATE; - assert !(unique && sort == Sort.FORMULA); - assert !(sort instanceof NullSort) || name.toString().equals("null") - : "Functions with sort \"null\" are not allowed: " + this; + this(name, sort, argSorts, whereToBind, unique, isRigid, isSkolemConstant, null); } - public Function(Name name, - Sort sort, - ImmutableArray argSorts, - ImmutableArray whereToBind, + public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, boolean unique) { this(name, sort, argSorts, whereToBind, unique, true, false); } + public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, + boolean unique, MixFitInfo mixFitInfo) { + this(name, sort, argSorts, whereToBind, unique, true, false, mixFitInfo); + } + + public Function(Name name, Sort sort, ImmutableArray argSorts, @@ -81,6 +99,12 @@ public Function(Name name, unique); } + public Function(Name name, Sort sort, Sort[] argSorts, Boolean[] whereToBind, boolean unique, + MixFitInfo mixFitInfo) { + this(name, sort, new ImmutableArray<>(argSorts), + whereToBind == null ? null : new ImmutableArray<>(whereToBind), unique, mixFitInfo); + } + public Function(Name name, Sort sort, Sort[] argSorts, @@ -120,6 +144,8 @@ public Function(Name name, Sort sort, boolean isSkolemConstant) { } + + //------------------------------------------------------------------------- //public interface //------------------------------------------------------------------------- @@ -172,4 +198,32 @@ public final String proofToString() { public Function rename(Name newName) { return new Function(newName, sort(), argSorts(), whereToBind(), unique, skolemConstant); } -} \ No newline at end of file + + public MixFitInfo getMixFitInfo() { + return mixFitInfo; + } + + public static class MixFitInfo { + @Nonnull + public final Kind kind; + @Nonnull + public final String symbol; + + public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { + this.kind = kind; + this.symbol = symbol; + } + + enum Kind {PREFIX, INFIX, POSTFIX} + + @Nonnull + public Kind getKind() { + return kind; + } + + @Nonnull + public String getSymbol() { + return symbol; + } + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java index 9b56adb7c79..5bec61a9817 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java @@ -55,6 +55,8 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Function p = null; + Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + int separatorIndex = pred_name.indexOf("::"); if (separatorIndex > 0) { String sortName = pred_name.substring(0, separatorIndex); @@ -77,7 +79,7 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Sort.FORMULA, argSorts.toArray(new Sort[0]), whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - false); + false, mixFitInfo); } if (lookup(p.name()) == null) { @@ -99,6 +101,8 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { semanticError(ctx, "Where-to-bind list must have same length as argument list"); } + Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + Function f = null; assert func_name != null; int separatorIndex = func_name.indexOf("::"); @@ -121,7 +125,7 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { retSort, argSorts.toArray(new Sort[0]), whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - unique); + unique, mixFitInfo); } if (lookup(f.name()) == null) { From a30b91e99a4c351eaf6cd38aa54252a7f9435fe7 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 5 Feb 2022 00:03:20 +0100 Subject: [PATCH 04/38] change the loopup functions --- .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/DoubleLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/FloatLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/IntegerLDT.java | 4 ++-- .../src/main/java/de/uka/ilkd/key/ldt/LDT.java | 18 ++++++++++++++---- .../java/de/uka/ilkd/key/ldt/LocSetLDT.java | 4 ++-- .../main/java/de/uka/ilkd/key/ldt/SeqLDT.java | 4 ++-- 7 files changed, 26 insertions(+), 16 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 8b9b44ddd01..6634c9fd324 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -267,8 +267,8 @@ public final Type getType(Term t) { @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { // This is not very elegant; but seqConcat is actually in the SeqLDT. case "add": return services.getNamespaces().functions().lookup("seqConcat"); default: return null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java index 2d3b9b65500..165f726f2d8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java @@ -178,8 +178,8 @@ public Term translateLiteral(Literal lit, Services services) { } @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java index 0a74c4aba47..945b7d69c73 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java @@ -188,8 +188,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, } @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java index 4a0775723e0..6129e889ee0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java @@ -502,8 +502,8 @@ public Function getFunctionFor( @Nullable @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index 40206920796..ccb8ae456de 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -248,7 +248,7 @@ public abstract Function getFunctionFor( /** * get the function in this LDT for an operation identified by generic - * operationName. If the LDT does not support this named function, it should + * operatorSymbol. If the LDT does not support this named function, it should * return null. * * This is used to resolve overloaded symbols. @@ -256,13 +256,23 @@ public abstract Function getFunctionFor( * For example: "+" may map to "add" for integers, and to "addFloat" for * floats. * - * @param operationName non-null operationName for a generic function + * @param operatorSymbol non-null operatorSymbol for a generic function * @param services services to use * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public @Nullable Function getFunctionFor(String operationName, Services services) { - // by default an LDT does not support overloaded symbols + public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + for (Operator operator : functions.allElements()) { + if(operator instanceof Function) { + var op = (Function) operator; + if (op.getMixFitInfo() != null) { + var mfi = op.getMixFitInfo(); + if (mfi.symbol.equals(operatorSymbol)) { + return op; + } + } + } + } return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java index b50855dd9d4..1bec475b569 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java @@ -233,8 +233,8 @@ public final Type getType(Term t) { @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "add": return getUnion(); case "sub": return getSetMinus(); case "mul": return getIntersect(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java index 7efae2bfc31..08bc458f734 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java @@ -186,8 +186,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "add": return getSeqConcat(); default: return null; } From 58ab4f0bc3451b0faf1f7c1e6cc4f68697aa06f8 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 5 Feb 2022 00:08:16 +0100 Subject: [PATCH 05/38] remove seq +, use annotation --- .../src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java | 10 ---------- .../main/resources/de/uka/ilkd/key/proof/rules/seq.key | 2 +- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java index 08bc458f734..482a8ac6ce0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java @@ -184,16 +184,6 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, return null; } - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "add": return getSeqConcat(); - default: return null; - } - } - - @Override public boolean hasLiteralFunction(Function f) { return f.equals(seqEmpty); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key index 698796df2fe..036da835c8c 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key @@ -37,7 +37,7 @@ //constructors Seq seqEmpty; Seq seqSingleton(any); - Seq seqConcat(Seq, Seq); + Seq seqConcat(Seq, Seq) \infix(+); Seq seqSub(Seq, int, int); Seq seqReverse(Seq); Seq seqDef{false,false,true}(int, int, any); From 3790027b7c23b293fea033f6f60ddcc1456fff74 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 15:57:41 +0100 Subject: [PATCH 06/38] remove old lookup and add metadata --- key/key.core/src/main/antlr4/KeYLexer.g4 | 1 + key/key.core/src/main/antlr4/KeYParser.g4 | 1 + .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 10 ------ .../java/de/uka/ilkd/key/ldt/DoubleLDT.java | 16 ++-------- .../java/de/uka/ilkd/key/ldt/FloatLDT.java | 17 ++-------- .../java/de/uka/ilkd/key/ldt/IntegerLDT.java | 17 ---------- .../main/java/de/uka/ilkd/key/ldt/LDT.java | 2 +- .../java/de/uka/ilkd/key/ldt/LocSetLDT.java | 12 ------- .../uka/ilkd/key/proof/rules/floatHeader.key | 31 ++++++++++--------- .../ilkd/key/proof/rules/integerHeader.key | 22 ++++++------- .../de/uka/ilkd/key/proof/rules/locSets.key | 10 +++--- 11 files changed, 40 insertions(+), 99 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index acbaf3d0311..60d9375b9ab 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -235,6 +235,7 @@ TRANSFORMERS : '\\transformers'; UNIQUE : '\\unique'; INFIX: '\\infix'; PREFIX: '\\prefix'; +SHORTCUT:'\\shortcut'; POSTFIX: '\\postfix'; RULES : '\\rules'; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 684d870e173..0e185cc9ae6 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -256,6 +256,7 @@ functionMetaData INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN | PREFIX LPAREN (MINUS|TILDE) RPAREN | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN + | SHORTCUT LPAREN IDENT RPAREN ; func_decls diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 6634c9fd324..4a0dc36bc81 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -264,14 +264,4 @@ public final Type getType(Term t) { assert false; return null; } - - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - // This is not very elegant; but seqConcat is actually in the SeqLDT. - case "add": return services.getNamespaces().functions().lookup("seqConcat"); - default: return null; - } - } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java index 165f726f2d8..a0ec2e5821a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java @@ -177,19 +177,9 @@ public Term translateLiteral(Literal lit, Services services) { return services.getTermBuilder().dfpTerm(doubleVal); } - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "neg": return getNeg(); +/* @Override + public Function getFunctionFor(String operatorSymbol, Services services) { // Floating point extensions with "\fp_" case "nan": return getIsNaN(); case "zero": return getIsZero(); @@ -201,7 +191,7 @@ public Function getFunctionFor(String operatorSymbol, Services services) { case "subnormal": return getIsSubnormal(); } return null; - } + }*/ @Override public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java index 945b7d69c73..3a55c5fe2dc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java @@ -187,19 +187,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, } } - @Override +/* @Override public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "neg": return getNeg(); - // Floating point extensions with "\fp_" case "nan": return getIsNaN(); case "zero": return getIsZero(); case "infinite": return getIsInfinite(); @@ -208,9 +197,7 @@ public Function getFunctionFor(String operatorSymbol, Services services) { case "negative": return getIsNegative(); case "positive": return getIsPositive(); case "subnormal": return getIsSubnormal(); - } - return null; - } +*/ @Override public boolean hasLiteralFunction(Function f) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java index 6129e889ee0..45c201a19a8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java @@ -500,23 +500,6 @@ public Function getFunctionFor( } } - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "mod": return getMod(); - case "neg": return getNeg(); - } - return null; - } @Override public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index ccb8ae456de..9b7d102e108 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -261,7 +261,7 @@ public abstract Function getFunctionFor( * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + public final @Nullable Function getFunctionFor(String operatorSymbol, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java index 1bec475b569..6f3c05b7c6f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java @@ -230,16 +230,4 @@ public final Type getType(Term t) { assert false; return null; } - - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "add": return getUnion(); - case "sub": return getSetMinus(); - case "mul": return getIntersect(); - case "le": return getSubset(); - default: return null; - } - } } \ No newline at end of file diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index 4810eb3bf80..fbbc7c63632 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -12,11 +12,12 @@ // \sorts { - + /*! `fp` is the upper sort representing all floating point numbers. */ fp; + /*! */ float \extends fp; + /*! */ double \extends fp; - java.lang.Math \extends java.lang.Object; } @@ -45,11 +46,11 @@ float javaDivFloatForbiddenResult(float, float); // Floating-point arithmetic with IEEE 754 semantics - float addFloat(float, float); - float subFloat(float, float); - float mulFloat(float, float); - float divFloat(float, float); - float negFloat(float); + float addFloat(float, float) \infix(+); + float subFloat(float, float) \infix(-); + float mulFloat(float, float) \infix(*); + float divFloat(float, float) \infix(/); + float negFloat(float) \prefix(-); float absFloat(float); @@ -95,10 +96,10 @@ \predicates { - ltFloat(float, float); - gtFloat(float, float); - leqFloat(float, float); - geqFloat(float, float); + ltFloat(float, float) \infix(<); + gtFloat(float, float) \infix(>); + leqFloat(float, float) \infix(<=); + geqFloat(float, float) \infix(>=); eqFloat(float, float); floatIsNaN(float); @@ -110,10 +111,10 @@ floatIsNegative(float); floatIsNice(float); - ltDouble(double, double); - gtDouble(double, double); - leqDouble(double, double); - geqDouble(double, double); + ltDouble(double, double) \infix(<); + gtDouble(double, double) \infix(>); + leqDouble(double, double) \infix(<=); + geqDouble(double, double) \infix(>=); eqDouble(double, double); doubleIsNaN(double); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index 91a354c1d33..95f5fbcf052 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -35,13 +35,13 @@ int C (numbers); //arithmetic operators on mathematical integers - int add(int,int); - int neg(int); - int sub(int,int); - int mul(int, int); - int div(int, int); - int mod(int, int); - int pow(int, int); + int add(int,int) \infix(+); + int neg(int) \prefix(-); + int sub(int,int) \infix(-); + int mul(int, int) \infix(*); + int div(int, int) \infix(/); + int mod(int, int) \infix(%); + int pow(int, int) \infix(**); // comprehensions int bsum{false,false,true}(int, int, int); @@ -209,10 +209,10 @@ //from the current integer semantics. //---------------------------------------------------------------------------- - leq(int, int); - lt(int, int); - geq(int, int); - gt(int, int); + leq(int, int) \infix(<=); + lt(int, int) \infix(<); + geq(int, int) \infix(>=); + gt(int, int) \infix(>); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key index 6cf833bd56f..bdd9dc0bbcc 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key @@ -12,9 +12,9 @@ // other constructors LocSet singleton(Object, Field); - LocSet union(LocSet, LocSet); - LocSet intersect(LocSet, LocSet); - LocSet setMinus(LocSet, LocSet); + LocSet union(LocSet, LocSet) \infix(+); + LocSet intersect(LocSet, LocSet) \infix(*); + LocSet setMinus(LocSet, LocSet) \infix(-); LocSet infiniteUnion{true}(LocSet); LocSet allFields(Object); LocSet allObjects(Field); @@ -27,8 +27,8 @@ \predicates { elementOf(Object, Field, LocSet); - subset(LocSet, LocSet); - disjoint(LocSet, LocSet); + subset(LocSet, LocSet) \infix(<); + disjoint(LocSet, LocSet) \infix(<|>); createdInHeap(LocSet, Heap); } From 6c4f1a652afc0c534c29eaff035b7065f0b3500f Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 22:12:59 +0100 Subject: [PATCH 07/38] NotationInfo recognizes MixFitInfos more operators are allowed --- key/key.core/src/main/antlr4/KeYLexer.g4 | 27 +- key/key.core/src/main/antlr4/KeYParser.g4 | 6 +- .../de/uka/ilkd/key/java/TypeConverter.java | 84 +++--- .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 6 + .../main/java/de/uka/ilkd/key/ldt/LDT.java | 7 +- .../de/uka/ilkd/key/logic/op/Function.java | 25 -- .../de/uka/ilkd/key/logic/op/MixFitInfo.java | 31 ++ .../nparser/builder/ExpressionBuilder.java | 13 +- .../builder/FunctionPredicateBuilder.java | 13 +- .../java/de/uka/ilkd/key/pp/NotationInfo.java | 282 +++++++++++------- .../uka/ilkd/key/proof/rules/floatHeader.key | 8 +- .../ilkd/key/proof/rules/integerHeader.key | 2 +- .../de/uka/ilkd/key/nparser/ExprTest.java | 4 + .../de/uka/ilkd/key/nparser/exprs.txt | 2 +- 14 files changed, 293 insertions(+), 217 deletions(-) create mode 100644 key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 60d9375b9ab..f6f6f740cff 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -97,6 +97,17 @@ lexer grammar KeYLexer; tokens {MODALITY} +// Comments have precedence over operators // and /*. +SL_COMMENT +: + '//' + (~('\n' | '\uFFFF'))* ('\n' | '\uFFFF' | EOF) -> channel(HIDDEN) +; + +DOC_COMMENT: '/*!' -> more, pushMode(docComment); +ML_COMMENT: '/*' -> more, pushMode(COMMENT); + + SORTS:'\\sorts'; GENERIC : '\\generic'; PROXY : '\\proxy'; @@ -275,10 +286,10 @@ VOCAB : '\u0003'..'\u0377' ; -fragment OP_SFX: [-+*/&.^]+; +fragment OP_SFX: ('-'|'='|'+'|'*'|'/'|'&'|'.'|'|'|'^'|'!'|':'|'>'|'<')+; SEMI: ';'; -SLASH: '/'; +SLASH: '/' OP_SFX?; COLON: ':'; DOUBLECOLON:'::'; ASSIGN: ':='; @@ -319,8 +330,8 @@ RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; -LESS: '<'; LESSEQUAL: '<' '=' | '\u2264'; +LESS: '<' OP_SFX?; LGUILLEMETS: '<' '<'; IMPLICIT_IDENT: '<' (LETTER)+ '>' ('$lmtd')? -> type(IDENT); @@ -339,16 +350,6 @@ CHAR_LITERAL QUOTED_STRING_LITERAL : '"' ('\\' . | '\n' | ~('\n' | '"' | '\\') )* '"' ; -SL_COMMENT -: - '//' - (~('\n' | '\uFFFF'))* ('\n' | '\uFFFF' | EOF) -> channel(HIDDEN) -; - -DOC_COMMENT: '/*!' -> more, pushMode(docComment); -ML_COMMENT: '/*' -> more, pushMode(COMMENT); - - BIN_LITERAL: '0' 'b' ('0' | '1' | '_')+ ('l'|'L')?; HEX_LITERAL: '0' 'x' (DIGIT | 'a'..'f' | 'A'..'F' | '_')+ ('l'|'L')?; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 0e185cc9ae6..76f79b4e54d 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -253,8 +253,8 @@ func_decl functionMetaData : - INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN - | PREFIX LPAREN (MINUS|TILDE) RPAREN + INFIX LPAREN op=(PLUS|STAR|SLASH|MINUS|EXP|PERCENT|LESS|LESSEQUAL|GREATER|GREATEREQUAL|LGUILLEMETS) RPAREN + | PREFIX LPAREN op=(MINUS|TILDE) RPAREN | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN | SHORTCUT LPAREN IDENT RPAREN ; @@ -374,7 +374,7 @@ unary_formula: | MODALITY sub=term60 #modality_term ; equality_term: a=comparison_term ((NOT_EQUALS|EQUALS) b=comparison_term)?; -comparison_term: a=weak_arith_term ((LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; +comparison_term: a=weak_arith_term (op=(LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; weak_arith_term: a=strong_arith_term_1 (op+=(PLUS|MINUS) b+=strong_arith_term_1)*; strong_arith_term_1: a=strong_arith_term_2 (STAR b+=strong_arith_term_2)*; strong_arith_term_2: a=atom_prefix (op=(PERCENT|SLASH) b=strong_arith_term_2)?; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java index c202ef4468a..c78c603c9d3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java @@ -32,13 +32,12 @@ 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import recoder.service.ConstantEvaluator; -import recoder.service.KeYCrossReferenceSourceInfo; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -76,7 +75,7 @@ public LDT getLDTFor(Sort s) { return ldt; } } - LOGGER.debug("No LDT found for ", s); + LOGGER.debug("No LDT found for {}", s); return null; } @@ -166,7 +165,7 @@ private Term translateOperator(de.uka.ilkd.key.java.expression.Operator op, Exec private Term convertReferencePrefix(ReferencePrefix prefix, ExecutionContext ec) { - LOGGER.debug("typeconverter: (prefix, class)", prefix, + LOGGER.debug("typeconverter: (prefix: {}, class: {})", prefix, (prefix != null ? prefix.getClass() : null)); if (prefix instanceof FieldReference) { return convertVariableReference((FieldReference) prefix, ec); @@ -179,8 +178,7 @@ private Term convertReferencePrefix(ReferencePrefix prefix, // the base case: the leftmost item is a local variable return tb.var((ProgramVariable) prefix); } else if (prefix instanceof VariableReference) { - LOGGER.debug("typeconverter: " + - "variablereference:", (((VariableReference) prefix).getProgramVariable())); + LOGGER.debug("variablereference: {}", (((VariableReference) prefix).getProgramVariable())); return tb.var(((VariableReference) prefix).getProgramVariable()); } else if (prefix instanceof ArrayReference) { return convertArrayReference((ArrayReference) prefix, ec); @@ -404,6 +402,7 @@ private Term convertLiteralExpression(Literal lit) { // TODO Adapt for @Reals + /** * performs binary numeric promotion on the argument types */ @@ -453,39 +452,39 @@ else if ((t1 == PrimitiveType.JAVA_BOOLEAN && return type1; } else if (type2.equals(services.getJavaInfo().getKeYJavaType("java.lang.String"))) { return type2; - } else if ((t2 == PrimitiveType.JAVA_FLOAT) && - (t1 == PrimitiveType.JAVA_BYTE|| - t1 == PrimitiveType.JAVA_SHORT|| - t1 == PrimitiveType.JAVA_INT|| - t1 == PrimitiveType.JAVA_CHAR|| - t1 == PrimitiveType.JAVA_LONG|| - t1 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t2 == PrimitiveType.JAVA_FLOAT) && + (t1 == PrimitiveType.JAVA_BYTE || + t1 == PrimitiveType.JAVA_SHORT || + t1 == PrimitiveType.JAVA_INT || + t1 == PrimitiveType.JAVA_CHAR || + t1 == PrimitiveType.JAVA_LONG || + t1 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t1 == PrimitiveType.JAVA_FLOAT) && - (t2 == PrimitiveType.JAVA_BYTE|| - t2 == PrimitiveType.JAVA_SHORT|| - t2 == PrimitiveType.JAVA_INT|| - t2 == PrimitiveType.JAVA_CHAR|| - t2 == PrimitiveType.JAVA_LONG|| - t2 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t1 == PrimitiveType.JAVA_FLOAT) && + (t2 == PrimitiveType.JAVA_BYTE || + t2 == PrimitiveType.JAVA_SHORT || + t2 == PrimitiveType.JAVA_INT || + t2 == PrimitiveType.JAVA_CHAR || + t2 == PrimitiveType.JAVA_LONG || + t2 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && - (t1 == PrimitiveType.JAVA_BYTE|| - t1 == PrimitiveType.JAVA_SHORT|| - t1 == PrimitiveType.JAVA_INT|| - t1 == PrimitiveType.JAVA_CHAR|| - t1 == PrimitiveType.JAVA_LONG|| - t1 == PrimitiveType.JAVA_FLOAT|| - t1 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && + (t1 == PrimitiveType.JAVA_BYTE || + t1 == PrimitiveType.JAVA_SHORT || + t1 == PrimitiveType.JAVA_INT || + t1 == PrimitiveType.JAVA_CHAR || + t1 == PrimitiveType.JAVA_LONG || + t1 == PrimitiveType.JAVA_FLOAT || + t1 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); - } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && - (t2 == PrimitiveType.JAVA_BYTE|| - t2 == PrimitiveType.JAVA_SHORT|| - t2 == PrimitiveType.JAVA_INT|| - t2 == PrimitiveType.JAVA_CHAR|| - t2 == PrimitiveType.JAVA_LONG|| - t2 == PrimitiveType.JAVA_FLOAT|| - t2 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && + (t2 == PrimitiveType.JAVA_BYTE || + t2 == PrimitiveType.JAVA_SHORT || + t2 == PrimitiveType.JAVA_INT || + t2 == PrimitiveType.JAVA_CHAR || + t2 == PrimitiveType.JAVA_LONG || + t2 == PrimitiveType.JAVA_FLOAT || + t2 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); } else { throw new RuntimeException("Could not determine promoted type " @@ -520,10 +519,10 @@ else if (t1 == PrimitiveType.JAVA_BIGINT) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BIGINT); else if (t1 == PrimitiveType.JAVA_REAL) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_REAL); - else if (t1 == PrimitiveType.JAVA_FLOAT) - return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - else if (t1 == PrimitiveType.JAVA_DOUBLE) - return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); + else if (t1 == PrimitiveType.JAVA_FLOAT) + return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); + else if (t1 == PrimitiveType.JAVA_DOUBLE) + return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); else throw new RuntimeException("Could not determine promoted type " + "of " + type1); } @@ -1033,4 +1032,7 @@ private LDT getResponsibleLDT(de.uka.ilkd.key.java.expression.Operator op, Term[ return null; } + public Collection getLDTs() { + return Collections.unmodifiableCollection(LDTs.values()); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 4a0dc36bc81..afb39f1a28a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -264,4 +264,10 @@ public final Type getType(Term t) { assert false; return null; } + + @Nullable + @Override + public Function getFunctionFor(String operatorSymbol, Services services) { + return services.getTypeConverter().getSeqLDT().getFunctionFor(operatorSymbol, services); + } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index 9b7d102e108..c50acdb6fca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -13,6 +13,7 @@ package de.uka.ilkd.key.ldt; +import java.util.Collection; import java.util.Map; import java.util.TreeMap; @@ -261,7 +262,7 @@ public abstract Function getFunctionFor( * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public final @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; @@ -282,4 +283,8 @@ public abstract Function getFunctionFor( public abstract Expression translateTerm(Term t, ExtList children, Services services); public abstract Type getType(Term t); + + public Collection getFunctions() { + return functions.allElements(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java index dafd11d9956..5546743d9c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java @@ -19,7 +19,6 @@ import de.uka.ilkd.key.logic.sort.NullSort; import de.uka.ilkd.key.logic.sort.Sort; -import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -202,28 +201,4 @@ public Function rename(Name newName) { public MixFitInfo getMixFitInfo() { return mixFitInfo; } - - public static class MixFitInfo { - @Nonnull - public final Kind kind; - @Nonnull - public final String symbol; - - public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { - this.kind = kind; - this.symbol = symbol; - } - - enum Kind {PREFIX, INFIX, POSTFIX} - - @Nonnull - public Kind getKind() { - return kind; - } - - @Nonnull - public String getSymbol() { - return symbol; - } - } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java new file mode 100644 index 00000000000..44c019b0b40 --- /dev/null +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java @@ -0,0 +1,31 @@ +package de.uka.ilkd.key.logic.op; + +import javax.annotation.Nonnull; + +/** + * @author Alexander Weigl + * @version 1 (06.02.22) + */ +public class MixFitInfo { + @Nonnull + public final Kind kind; + @Nonnull + public final String symbol; + + public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { + this.kind = kind; + this.symbol = symbol; + } + + public enum Kind {PREFIX, INFIX, SHORTCUT, POSTFIX} + + @Nonnull + public Kind getKind() { + return kind; + } + + @Nonnull + public String getSymbol() { + return symbol; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 7a6281dc470..09b23a2ed0c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -283,18 +283,7 @@ public Object visitComparison_term(KeYParser.Comparison_termContext ctx) { if(termR == null) { return updateOrigin(termL, ctx); } - - String op_name = ""; - if (ctx.LESS() != null) - op_name = "lt"; - if (ctx.LESSEQUAL() != null) - op_name = "leq"; - if (ctx.GREATER() != null) - op_name = "gt"; - if (ctx.GREATEREQUAL() != null) - op_name = "geq"; - return binaryLDTSpecificTerm(ctx, op_name, termL, termR); - + return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java index 5bec61a9817..95b04ed77ca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java @@ -4,6 +4,7 @@ import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.NamespaceSet; import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.MixFitInfo; import de.uka.ilkd.key.logic.op.SortDependingFunction; import de.uka.ilkd.key.logic.op.Transformer; import de.uka.ilkd.key.logic.sort.GenericSort; @@ -44,6 +45,14 @@ public Object visitDecls(KeYParser.DeclsContext ctx) { return null; } + @Override + public Object visitFunctionMetaData(KeYParser.FunctionMetaDataContext ctx) { + MixFitInfo.Kind kind = ctx.PREFIX() != null + ? MixFitInfo.Kind.PREFIX : ctx.INFIX() != null ? MixFitInfo.Kind.INFIX + : MixFitInfo.Kind.POSTFIX != null ? MixFitInfo.Kind.POSTFIX : MixFitInfo.Kind.SHORTCUT; + return new MixFitInfo(kind, ctx.op.getText()); + } + @Override public Object visitPred_decl(KeYParser.Pred_declContext ctx) { String pred_name = accept(ctx.funcpred_name()); @@ -55,7 +64,7 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Function p = null; - Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); int separatorIndex = pred_name.indexOf("::"); if (separatorIndex > 0) { @@ -101,7 +110,7 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { semanticError(ctx, "Where-to-bind list must have same length as argument list"); } - Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); Function f = null; assert func_name != null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java index ec8413656e5..a19920a949b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java @@ -18,94 +18,88 @@ import java.util.Map; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.HeapLDT; -import de.uka.ilkd.key.ldt.IntegerLDT; -import de.uka.ilkd.key.ldt.CharListLDT; -import de.uka.ilkd.key.ldt.DoubleLDT; -import de.uka.ilkd.key.ldt.FloatLDT; -import de.uka.ilkd.key.ldt.LocSetLDT; -import de.uka.ilkd.key.ldt.SeqLDT; +import de.uka.ilkd.key.ldt.*; import de.uka.ilkd.key.logic.label.TermLabel; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.logic.sort.Sort; import de.uka.ilkd.key.util.UnicodeHelper; -/** - *

- * Stores the mapping from operators to {@link Notation}s. Each - * {@link Notation} represents the concrete syntax for some +/** + *

+ * Stores the mapping from operators to {@link Notation}s. Each + * {@link Notation} represents the concrete syntax for some * {@link de.uka.ilkd.key.logic.op.Operator}. The {@link LogicPrinter} * asks the NotationInfo to find out which Notation to use for a given term. *

* The Notation associated with an operator might change. New Notations can * be added. - * + * *

- * The next lines describe a general rule how to determine priorities and + * The next lines describe a general rule how to determine priorities and * associativities: - * + * * One thing we need to know from the pretty printer: - * Given a term t containg s as proper subterm. + * Given a term t containg s as proper subterm. * Then s is printed in parentheses when the priority of the - * top level symbol of s is strict less than the associativity of the + * top level symbol of s is strict less than the associativity of the * position where s occurs. For example: *

- * Let the priority of AND be 30 and the associativities for each - * of its subterms be 40; ORs priority is 20 and the associativites are - * both 30 then + * Let the priority of AND be 30 and the associativities for each + * of its subterms be 40; ORs priority is 20 and the associativites are + * both 30 then *

  • formula (p & q) | r is pretty printed as p & q | r - * as the priority of & is 30 which is (greater or) equal than the + * as the priority of & is 30 which is (greater or) equal than the * associativity of ORs left subterm which is 30.
  • - *
  • In contrast the formula p & (q | r) is pretty printed as - * p & (q | r) as the priority of OR is 20 which is less than + *
  • In contrast the formula p & (q | r) is pretty printed as + * p & (q | r) as the priority of OR is 20 which is less than * the associativity of ANDs left subterm, which is 40.
  • - *
- * - * A general rule to determine the correct priority and associativity is to use: - * - * Grammar rules whose derivation delivers a syntactical correct logic term should follow - * a standard numbering scheme, which is used as indicator for priorities and associativites, - * e.g. - * by simply reading the grammar rule - *
term60 ::= term70 (IMP term70)?
- * we get the priority of IMP, which is 60. The associativities - * of IMPs subterms are not much more difficult to determine, namely - * the left subterm has associativity 70 and in this case its the same + * + * + * A general rule to determine the correct priority and associativity is to use: + * + * Grammar rules whose derivation delivers a syntactical correct logic term should follow + * a standard numbering scheme, which is used as indicator for priorities and associativites, + * e.g. + * by simply reading the grammar rule + *
term60 ::= term70 (IMP term70)?
+ * we get the priority of IMP, which is 60. The associativities + * of IMPs subterms are not much more difficult to determine, namely + * the left subterm has associativity 70 and in this case its the same * for the right subterm (70). *

* There are exceptional cases for *

    - *
  • infix function symbols that are left associative e.g. + *
  • infix function symbols that are left associative e.g. * -, + - *
    + *
    * term90 ::= term100 (PLUS term100)* - *
    - * then the associative for the right subterm is increased by 1, - * i.e. here we have a priority of 90 for PLUS as infix operator, + *
    + * then the associative for the right subterm is increased by 1, + * i.e. here we have a priority of 90 for PLUS as infix operator, * a left associativity of 100 and a right associativity of 101 *
  • - *
  • update and substituition terms: for them their associativity is - * determined dynamically by the pretty printer depending if it is applied on a + *
  • update and substituition terms: for them their associativity is + * determined dynamically by the pretty printer depending if it is applied on a * formula or term. In principal there should be two different - * rules in the parser as then we could reuse the general rule from above, but + * rules in the parser as then we could reuse the general rule from above, but * there are technical reasons which causes this exception. *
  • - *
  • some very few rules do not follow the usual parser design + *
  • some very few rules do not follow the usual parser design * e.g. like *
    R_PRIO ::= SubRule_ASS1 | SubRule_ASS2
    * where - *
    SubRule_ASS2 ::= OP SubRule_ASS1
    + *
    SubRule_ASS2 ::= OP SubRule_ASS1
    * Most of these few rules could in general be rewritten to fit the usual scheme * e.g. as - *
    R_PRIO ::= (OP)? SubRule_ASS1
    - * using the priorities and associativities of the so rewritten rules - * (instead of rewriting them actually) is a way to cope with them. + *
    R_PRIO ::= (OP)? SubRule_ASS1
    + * using the priorities and associativities of the so rewritten rules + * (instead of rewriting them actually) is a way to cope with them. *
  • *
*/ public final class NotationInfo { - + // Priorities of operators (roughly corresponding to the grammatical structure in the parser. @@ -137,28 +131,28 @@ public final class NotationInfo { * are printed. */ public static boolean DEFAULT_UNICODE_ENABLED = false; - + public static boolean DEFAULT_HIDE_PACKAGE_PREFIX = false; - + /** This maps operators and classes of operators to {@link * Notation}s. The idea is that we first look whether the operator has * a Notation registered. Otherwise, we see if there is one for the * class of the operator. */ - private HashMap notationTable; + private Map notationTable; + - /** * Maps terms to abbreviations and reverse. */ private AbbrevMap scm = new AbbrevMap(); - + private boolean prettySyntax = DEFAULT_PRETTY_SYNTAX; - + private boolean unicodeEnabled = DEFAULT_UNICODE_ENABLED; - + private boolean hidePackagePrefix = DEFAULT_HIDE_PACKAGE_PREFIX; - + //------------------------------------------------------------------------- //constructors //------------------------------------------------------------------------- @@ -166,21 +160,21 @@ public final class NotationInfo { public NotationInfo() { this.notationTable = createDefaultNotation(); } - - - + + + //------------------------------------------------------------------------- //internal methods //------------------------------------------------------------------------- - - + + /** Register the standard set of notations (that can be defined without * a services object). */ private HashMap createDefaultNotation() { HashMap tbl = new LinkedHashMap(50); - + tbl.put(Junctor.TRUE ,new Notation.Constant("true", PRIORITY_ATOM)); tbl.put(Junctor.FALSE,new Notation.Constant("false", PRIORITY_ATOM)); tbl.put(Junctor.NOT,new Notation.Prefix("!" ,PRIORITY_NEGATION,PRIORITY_NEGATION)); @@ -200,34 +194,66 @@ private HashMap createDefaultNotation() { tbl.put(IfExThenElse.IF_EX_THEN_ELSE, new Notation.IfThenElse(PRIORITY_ATOM, "\\ifEx")); tbl.put(WarySubstOp.SUBST,new Notation.Subst()); tbl.put(UpdateApplication.UPDATE_APPLICATION, new Notation.UpdateApplicationNotation()); - tbl.put(UpdateJunctor.PARALLEL_UPDATE, new Notation.ParallelUpdateNotation()); - - tbl.put(Function.class, new Notation.FunctionNotation()); + tbl.put(UpdateJunctor.PARALLEL_UPDATE, new Notation.ParallelUpdateNotation()); + + tbl.put(Function.class, new Notation.FunctionNotation()); tbl.put(LogicVariable.class, new Notation.VariableNotation()); tbl.put(LocationVariable.class, new Notation.VariableNotation()); tbl.put(ProgramConstant.class, new Notation.VariableNotation()); - tbl.put(Equality.class, new Notation.Infix("=", PRIORITY_EQUAL, PRIORITY_COMPARISON, PRIORITY_COMPARISON)); + tbl.put(Equality.class, new Notation.Infix("=", PRIORITY_EQUAL, PRIORITY_COMPARISON, PRIORITY_COMPARISON)); tbl.put(ElementaryUpdate.class, new Notation.ElementaryUpdateNotation()); tbl.put(ModalOperatorSV.class, new Notation.ModalSVNotation(PRIORITY_MODALITY, PRIORITY_MODALITY)); tbl.put(SchemaVariable.class, new Notation.SchemaVariableNotation()); - + tbl.put(Sort.CAST_NAME, new Notation.CastFunction("(",")",PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(TermLabel.class, new Notation.LabelNotation("<<", ">>", PRIORITY_LABEL)); return tbl; } - - + + /** - * Adds notations that can only be defined when a services object is + * Adds notations that can only be defined when a services object is * available. */ - private HashMap createPrettyNotation(Services services) { + private Map createPrettyNotation(Services services) { + Map tbl = createDefaultNotation(); + for (LDT ldt : services.getTypeConverter().getLDTs()) { + var funcs = ldt.getFunctions(); + for (Operator op : funcs) { + if (op instanceof Function) { + var func = (Function) op; + var mixFitInfo = func.getMixFitInfo(); + if (mixFitInfo != null) { + final var symbol = mixFitInfo.getSymbol(); + switch (mixFitInfo.getKind()) { + case PREFIX: + tbl.put(op, new Notation.Prefix(symbol, + getPriorityPrefix(symbol), PRIORITY_ATOM)); + break; + case INFIX: + var args = getPriorityInfixArguments(symbol); + tbl.put(op, new Notation.Infix(symbol, getPriorityInfix(symbol), args, args)); + break; + case POSTFIX: + tbl.put(op, new Notation.Postfix(symbol)); + break; + } + } + } + } + } - HashMap tbl = createDefaultNotation(); - + var integerLDT = services.getTypeConverter().getIntegerLDT(); + var floatLDT = services.getTypeConverter().getFloatLDT(); + var doubleLDT = services.getTypeConverter().getDoubleLDT(); + tbl.put(integerLDT.getNumberSymbol(), new Notation.NumLiteral()); + tbl.put(integerLDT.getCharSymbol(), new Notation.CharLiteral()); + tbl.put(floatLDT.getFloatSymbol(), new Notation.FloatLiteral()); + tbl.put(doubleLDT.getDoubleSymbol(), new Notation.DoubleLiteral()); + + /* //arithmetic operators - final IntegerLDT integerLDT - = services.getTypeConverter().getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); tbl.put(integerLDT.getNumberSymbol(), new Notation.NumLiteral()); tbl.put(integerLDT.getCharSymbol(), new Notation.CharLiteral()); tbl.put(integerLDT.getLessThan(), new Notation.Infix("<", PRIORITY_COMPARISON, PRIORITY_ARITH_WEAK, PRIORITY_ARITH_WEAK)); @@ -267,57 +293,85 @@ private HashMap createPrettyNotation(Services services) { tbl.put(doubleLDT.getMul(), new Notation.Infix("*", PRIORITY_ARITH_STRONG, PRIORITY_ARITH_STRONG, PRIORITY_BELOW_ARITH_STRONG)); tbl.put(doubleLDT.getDiv(), new Notation.Infix("/", PRIORITY_ARITH_STRONG, PRIORITY_ARITH_STRONG, PRIORITY_BELOW_ARITH_STRONG)); tbl.put(doubleLDT.getNeg(),new Notation.Prefix("-", PRIORITY_BOTTOM, PRIORITY_ATOM)); + */ - - //heap operators - final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - tbl.put(HeapLDT.SELECT_NAME, new Notation.SelectNotation()); - tbl.put(heapLDT.getStore(), new Notation.StoreNotation()); + //heap operators + final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + tbl.put(HeapLDT.SELECT_NAME, new Notation.SelectNotation()); + tbl.put(heapLDT.getStore(), new Notation.StoreNotation()); tbl.put(heapLDT.getAnon(), new Notation.HeapConstructorNotation()); tbl.put(heapLDT.getCreate(), new Notation.HeapConstructorNotation()); tbl.put(heapLDT.getMemset(), new Notation.HeapConstructorNotation()); - tbl.put(IObserverFunction.class, new Notation.ObserverNotation()); - tbl.put(IProgramMethod.class, new Notation.ObserverNotation()); - tbl.put(heapLDT.getLength(), new Notation.Postfix(".length")); - - // sequence operators - final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); - tbl.put(seqLDT.getSeqLen(), new Notation.Postfix(".length")); - tbl.put(SeqLDT.SEQGET_NAME, new Notation.SeqGetNotation()); - tbl.put(seqLDT.getSeqConcat(), new Notation.SeqConcatNotation(seqLDT.getSeqConcat(), - seqLDT.getSeqSingleton(), integerLDT.getCharSymbol())); - - //set operators - final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); - tbl.put(setLDT.getSingleton(), new Notation.SingletonNotation()); - tbl.put(setLDT.getUnion(), new Notation.Infix("\\cup", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getIntersect(), new Notation.Infix("\\cap", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getSetMinus(), new Notation.Infix("\\setMinus", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getElementOf(), new Notation.ElementOfNotation()); + tbl.put(IObserverFunction.class, new Notation.ObserverNotation()); + tbl.put(IProgramMethod.class, new Notation.ObserverNotation()); + tbl.put(heapLDT.getLength(), new Notation.Postfix(".length")); + + // sequence operators + final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); + tbl.put(seqLDT.getSeqLen(), new Notation.Postfix(".length")); + tbl.put(SeqLDT.SEQGET_NAME, new Notation.SeqGetNotation()); + /*tbl.put(seqLDT.getSeqConcat(), new Notation.SeqConcatNotation(seqLDT.getSeqConcat(), + seqLDT.getSeqSingleton(), integerLDT.getCharSymbol()));*/ + + //set operators + final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); + tbl.put(setLDT.getSingleton(), new Notation.SingletonNotation()); + tbl.put(setLDT.getUnion(), new Notation.Infix("\\cup", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getIntersect(), new Notation.Infix("\\cap", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getSetMinus(), new Notation.Infix("\\setMinus", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getElementOf(), new Notation.ElementOfNotation()); tbl.put(setLDT.getSubset(), new Notation.Infix("\\subset", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); tbl.put(setLDT.getEmpty(), new Notation.Constant("{}", PRIORITY_ATOM)); tbl.put(setLDT.getAllFields(), new Notation.Postfix(".*")); - - return tbl; + + return tbl; + } + + private int getPriorityPrefix(String symbol) { + return PRIORITY_BOTTOM; + } + + private int getPriorityInfixArguments(String symbol) { + return getPriorityInfix(symbol) + 1; + } + + private int getPriorityInfix(String symbol) { + char c = symbol.charAt(0); //first character determines over precedence + switch (c) { + case '<': + case '>': + return PRIORITY_COMPARISON; + case '=': + case '!': + return PRIORITY_EQUAL; + case '+': + case '-': + return PRIORITY_ARITH_WEAK; + case '*': + case '/': + case '%': + return PRIORITY_ARITH_STRONG; + default: + return PRIORITY_ATOM; + } } - + /** * Add notations with Unicode symbols. * @param services */ - private HashMap createUnicodeNotation(Services services){ - - HashMap tbl = createPrettyNotation(services); - - final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + private Map createUnicodeNotation(Services services){ + Map tbl = createPrettyNotation(services); + + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); - + tbl.put(integerLDT.getJavaCastByte(), new Notation.Prefix("(byte)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastShort(), new Notation.Prefix("(short)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastChar(), new Notation.Prefix("(char)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastInt(), new Notation.Prefix("(int)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastLong(), new Notation.Prefix("(long)", PRIORITY_CAST, PRIORITY_BOTTOM)); - + // tbl.put(Junctor.TRUE ,new Notation.Constant(""+UnicodeHelper.TOP, PRIORITY_ATOM)); // tbl.put(Junctor.FALSE,new Notation.Constant(""+UnicodeHelper.BOT, PRIORITY_ATOM)); tbl.put(Junctor.NOT,new Notation.Prefix(""+UnicodeHelper.NEG ,PRIORITY_NEGATION,PRIORITY_NEGATION)); @@ -351,7 +405,7 @@ private HashMap createUnicodeNotation(Services services){ //------------------------------------------------------------------------- //public interface //------------------------------------------------------------------------- - + public void refresh(Services services) { refresh(services, DEFAULT_PRETTY_SYNTAX, DEFAULT_UNICODE_ENABLED); } @@ -372,11 +426,11 @@ public void refresh(Services services, boolean usePrettyPrinting, boolean useUni } hidePackagePrefix = DEFAULT_HIDE_PACKAGE_PREFIX; } - + public AbbrevMap getAbbrevMap(){ return scm; } - + public void setAbbrevMap(AbbrevMap am){ scm = am; @@ -385,8 +439,8 @@ public void setAbbrevMap(AbbrevMap am){ Notation getNotation(Class c) { return notationTable.get(c); } - - /** Get the Notation for a given Operator. + + /** Get the Notation for a given Operator. * If no notation is registered, a Function notation is returned. */ Notation getNotation(Operator op) { @@ -406,7 +460,7 @@ Notation getNotation(Operator op) { return result; } } - + if(op instanceof IProgramMethod) { result = notationTable.get(IProgramMethod.class); if(result != null) { diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index fbbc7c63632..cd58eefbf6b 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -73,10 +73,10 @@ double javaDivDoubleForbiddenResult(double, double); // Double arithmetic with IEEE 754 semantics - double addDouble(double, double); - double subDouble(double, double); - double mulDouble(double, double); - double divDouble(double, double); + double addDouble(double, double) \infix(+); + double subDouble(double, double) \infix(-); + double mulDouble(double, double) \infix(*); + double divDouble(double, double) \infix(/); double negDouble(double); double absDouble(double); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index 95f5fbcf052..ea52de007ba 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -29,7 +29,7 @@ numbers 7 (numbers); numbers 8 (numbers); numbers 9 (numbers); - numbers neglit (numbers); + numbers neglit (numbers) \prefix(-); int Z (numbers); int C (numbers); diff --git a/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java b/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java index 4549986128c..a1e08fdd03c 100644 --- a/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java +++ b/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java @@ -2,6 +2,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.pp.LogicPrinter; import de.uka.ilkd.key.proof.init.JavaProfile; import org.junit.Assert; import org.junit.Assume; @@ -55,6 +56,9 @@ public void parseAndVisit() throws IOException { @Nonnull Term actual = io.parseExpression(expr); Assert.assertNotNull(actual); LOGGER.info("Actual Term: {}", actual); + + LOGGER.warn("Actual Term: {}", + LogicPrinter.quickPrintTerm(actual, io.getServices(), true, true)); } private KeyIO getIo() throws IOException { diff --git a/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt b/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt index ad24f7e2abf..88e431fff62 100644 --- a/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt +++ b/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt @@ -1,3 +1,4 @@ +seqEmpty + seqEmpty (bprod{int y;}(1, 2, y) = 0) 1 = 1 -> 2 = 2 \< { int x = 1; } \> x=1 @@ -25,4 +26,3 @@ aa%bb*cc < -123 1.d + 1d <= 20e+1d * .01d 1f <= 2f 2d > 1d -seqEmpty + seqEmpty \ No newline at end of file From d059b75372b65bf89b86a592a12324bd29379714 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 23:36:56 +0100 Subject: [PATCH 08/38] fix clash with <-> --- key/key.core/src/main/antlr4/KeYLexer.g4 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index f6f6f740cff..a2470b43376 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -330,12 +330,12 @@ RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; + +EQV: '<->' | '\u2194'; LESSEQUAL: '<' '=' | '\u2264'; -LESS: '<' OP_SFX?; LGUILLEMETS: '<' '<'; +LESS: '<' OP_SFX?; IMPLICIT_IDENT: '<' (LETTER)+ '>' ('$lmtd')? -> type(IDENT); - -EQV: '<->' | '\u2194'; PRIMES: ('\'')+; CHAR_LITERAL : '\'' From eecbccf25b6504f775c64998ab56c9b278380efa Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 23:45:12 +0100 Subject: [PATCH 09/38] minors --- .../key/nparser/builder/AbstractBuilder.java | 39 ++++++++++++------- .../nparser/builder/ExpressionBuilder.java | 9 ++--- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java index a9a134d0028..28423107d10 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java @@ -1,13 +1,13 @@ package de.uka.ilkd.key.nparser.builder; +import de.uka.ilkd.key.nparser.KeYParserBaseVisitor; import de.uka.ilkd.key.util.parsing.BuildingException; import de.uka.ilkd.key.util.parsing.BuildingIssue; -import de.uka.ilkd.key.nparser.KeYParserBaseVisitor; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; + import javax.annotation.Nonnull; import javax.annotation.Nullable; - import java.util.*; import java.util.stream.Collectors; @@ -28,22 +28,31 @@ abstract class AbstractBuilder extends KeYParserBaseVisitor { @Nullable private List buildingIssues = null; @Nullable - private Stack parameters = null; + private Deque parameters = null; /** - * Helper function for avoiding cast. + * Helper function for visiting the given context {@code ctx}, mainly for avoiding cast. * - * @param ctx - * @param - * @return + * @param ctx a (parser) rule context or null + * @param object to be cast to + * @return if the ctx is null, this method returns, otherwise the result of the visit method is returned */ - public @Nullable T accept(@Nullable RuleContext ctx) { + @Nullable + public T accept(@Nullable RuleContext ctx) { if (ctx == null) { return null; } return (T) ctx.accept(this); } + /** + * Like {@link #accept(RuleContext)} but throwing an exception on null value. + */ + @Nonnull + public T acceptnn(@Nullable RuleContext ctx) { + return Objects.requireNonNull(accept(ctx)); + } + @Override protected T aggregateResult(T aggregate, T nextResult) { if (nextResult != null) return nextResult; @@ -64,17 +73,18 @@ protected T acceptFirst(Collection seq) { } protected T pop() { - if(parameters==null) throw new IllegalStateException("Stack is empty"); + if (parameters == null) throw new IllegalStateException("Stack is empty"); return (T) parameters.pop(); } protected void push(Object... obj) { - if(parameters == null) parameters = new Stack<>(); + if (parameters == null) parameters = new ArrayDeque<>(); for (Object a : obj) parameters.push(a); } - protected @Nullable T accept(@Nullable RuleContext ctx, Object... args) { - if(parameters == null) parameters = new Stack<>(); + @Nullable + protected T accept(@Nullable RuleContext ctx, Object... args) { + if (parameters == null) parameters = new ArrayDeque<>(); int stackSize = parameters.size(); push(args); T t = accept(ctx); @@ -113,7 +123,8 @@ protected List mapMapOf(List... ctxss) { .collect(Collectors.toList()); } - public @Nonnull List getBuildingIssues() { + public @Nonnull + List getBuildingIssues() { if (buildingIssues == null) buildingIssues = new LinkedList<>(); return buildingIssues; } @@ -147,7 +158,7 @@ protected void semanticError(ParserRuleContext ctx, String format, Object... arg /** * Wraps an exception into a {@link BuildingException} * - * @param e + * @param e the cause of the generated and thrown exception */ protected void throwEx(Throwable e) { throw new BuildingException(e); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 09b23a2ed0c..ac9f666eda5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -323,7 +323,7 @@ private Term binaryLDTSpecificTerm(ParserRuleContext ctx, String opname, Term la @Override public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) { - Term termL = accept(ctx.a); + Term termL = acceptnn(ctx.a); if (ctx.b.isEmpty()) { return updateOrigin(termL, ctx); } @@ -338,11 +338,10 @@ public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) @Override public Object visitStrong_arith_term_2(KeYParser.Strong_arith_term_2Context ctx) { - Term termL = accept(ctx.a); + Term termL = acceptnn(ctx.a); if (ctx.b == null) return termL; Term termR = accept(ctx.b); - //String opName = ctx.SLASH() != null ? "div" : "mod"; return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } @@ -358,9 +357,9 @@ protected Term capsulateTf(ParserRuleContext ctx, Supplier termSupplier) { public Object visitBracket_term(KeYParser.Bracket_termContext ctx) { Term t = accept(ctx.primitive_labeled_term()); for (int i = 0; i < ctx.bracket_suffix_heap().size(); i++) { - KeYParser.Brace_suffixContext brace_suffix = ctx.bracket_suffix_heap(i).brace_suffix(); + KeYParser.Brace_suffixContext braceSuffix = ctx.bracket_suffix_heap(i).brace_suffix(); ParserRuleContext heap = ctx.bracket_suffix_heap(i).heap; - t = accept(brace_suffix, t); + t = accept(braceSuffix, t); if (heap != null) { t = replaceHeap(t, accept(heap), heap); } From 0222157a13e6ca988da5724324dd852f50fbbc02 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 8 Feb 2022 16:37:56 +0100 Subject: [PATCH 10/38] fixes failing tests * do not use relational operator name map * fix priorities in lexer (/** is not an operator) * requests for prefix/postfix operators in LDT --- key/key.core/src/main/antlr4/KeYLexer.g4 | 2 +- key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java | 7 ++++++- .../de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java | 2 +- .../ilkd/key/speclang/translation/JMLArithmeticHelper.java | 2 +- .../java/de/uka/ilkd/key/util/HelperClassForTests.java | 4 +++- 5 files changed, 12 insertions(+), 5 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index a2470b43376..bf4ed5dac5a 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -105,7 +105,7 @@ SL_COMMENT ; DOC_COMMENT: '/*!' -> more, pushMode(docComment); -ML_COMMENT: '/*' -> more, pushMode(COMMENT); +ML_COMMENT: '/*' OP_SFX? -> more, pushMode(COMMENT); SORTS:'\\sorts'; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index c50acdb6fca..bb94535ba7e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.TreeMap; +import de.uka.ilkd.key.logic.op.MixFitInfo; import org.key_project.util.ExtList; import de.uka.ilkd.key.java.Expression; @@ -263,12 +264,16 @@ public abstract Function getFunctionFor( * operation, null if not available */ public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + return getFunctionFor(operatorSymbol, MixFitInfo.Kind.INFIX, services); + + } + public @Nullable Function getFunctionFor(String operatorSymbol, MixFitInfo.Kind kind, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; if (op.getMixFitInfo() != null) { var mfi = op.getMixFitInfo(); - if (mfi.symbol.equals(operatorSymbol)) { + if (kind == mfi.getKind() && mfi.symbol.equals(operatorSymbol)) { return op; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index ac9f666eda5..3e16480efd4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -243,7 +243,7 @@ public Object visitUnary_minus_term(KeYParser.Unary_minus_termContext ctx) { // falling back to integer ldt (for instance for untyped schema variables) ldt = services.getTypeConverter().getIntegerLDT(); } - Function op = ldt.getFunctionFor("neg", services); + Function op = ldt.getFunctionFor("-", MixFitInfo.Kind.PREFIX, services); if(op == null) { semanticError(ctx, "Could not find function symbol 'neg' for sort '%s'.", sort); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/speclang/translation/JMLArithmeticHelper.java b/key/key.core/src/main/java/de/uka/ilkd/key/speclang/translation/JMLArithmeticHelper.java index 3a368a4aaba..67820382014 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/speclang/translation/JMLArithmeticHelper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/speclang/translation/JMLArithmeticHelper.java @@ -247,7 +247,7 @@ else if (isDouble(resultType)) ldt = doubleLDT; else // int, long, or bigint does not matter ldt = integerLDT; - fun = ldt.getFunctionFor(COMPARISON_MAP.get(opStr), services); + fun = ldt.getFunctionFor(opStr, services); if (fun == null) { raiseError("Operator " + opStr + " not defined for " + ldt.name()); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java index 31cd8ee7ebd..51ca6211b98 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java @@ -91,7 +91,9 @@ public ProofAggregate parse(File file, Profile profile) { result = pi.startProver(po, po); - } catch (Exception e) { + }catch (RuntimeException e) { + throw e; + } catch (ProofInputException e) { throw new RuntimeException(e); } return result; From 9baeb5bf96c001a878a4b46ee1558cd3ece97354 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:42:34 +0100 Subject: [PATCH 11/38] remove prefix from neglit --- .../resources/de/uka/ilkd/key/proof/rules/integerHeader.key | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index ea52de007ba..95f5fbcf052 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -29,7 +29,7 @@ numbers 7 (numbers); numbers 8 (numbers); numbers 9 (numbers); - numbers neglit (numbers) \prefix(-); + numbers neglit (numbers); int Z (numbers); int C (numbers); From 4ff4563744d1190710dbf7cd30a0cd22c4579c89 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:46:10 +0100 Subject: [PATCH 12/38] add prefix at negDouble --- .../main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index cd58eefbf6b..6ef9237ed96 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -77,7 +77,7 @@ double subDouble(double, double) \infix(-); double mulDouble(double, double) \infix(*); double divDouble(double, double) \infix(/); - double negDouble(double); + double negDouble(double) \prefix(-); double absDouble(double); From b14b7413e26e8697edbde8c1ef42f479658d98c7 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:54:27 +0100 Subject: [PATCH 13/38] fix tests, add whitepsaces --- .../src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java b/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java index ae6bad7ef53..bdd5c2b5fa2 100644 --- a/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java +++ b/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java @@ -222,7 +222,7 @@ public void testContraposition() { builder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(Sequent.EMPTY_SEQUENT, ImmutableSLList.nil(), - parseFma("!b0->!b"))); + parseFma("!b0 -> !b"))); builder.setName(new Name("contraposition")); Taclet contraposition = builder.getRewriteTaclet(); String contrapositionString = From dda6ea109189b937e7e9e3c07cc8cedcd23e72e9 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:37:30 +0100 Subject: [PATCH 14/38] allow multi-char operators --- key/key.core/src/main/antlr4/KeYLexer.g4 | 160 ++++-------------- key/key.core/src/main/antlr4/KeYParser.g4 | 2 +- .../nparser/builder/ExpressionBuilder.java | 10 +- 3 files changed, 39 insertions(+), 133 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 285c41062ab..3e161b1e64d 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -271,137 +271,45 @@ VOCAB : '\u0003'..'\u0377' ; -SEMI -: ';' - ; - -SLASH -: '/' - ; - -COLON: ':'; - -DOUBLECOLON -: '::' - ; - -ASSIGN -: ':=' - ; - -DOT -: '.' - ; - -DOTRANGE -: '.' '.' - ; - -COMMA -: ',' - ; - -LPAREN -: - '(' - ; - -RPAREN -: ')' - ; - -LBRACE -: '{' - ; - -RBRACE -: '}' - ; - -LBRACKET -: '[' - ; - -RBRACKET -: ']' - ; - -EMPTYBRACKETS -: '[' ']' - ; - -AT -: '@' - ; - -PARALLEL -: '|' '|' - ; - - -OR -: '|' | '\u2228' - ; +fragment OP_SFX: [-+*/&.^]+; + +SEMI: ';'; +SLASH: '/'; +COLON: ':'; +DOUBLECOLON:'::'; +ASSIGN: ':='; +DOT: '.'; +DOTRANGE: '.' '.'; +COMMA: ','; +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACKET: '['; +RBRACKET: ']'; +EMPTYBRACKETS: '[' ']'; +AT: '@'; +PARALLEL: '|' '|'; +OR: '|' | '\u2228'; AND : '&' | '\u2227' ; -NOT -: '!' | '\u00AC' - ; - -IMP -: '->' | '\u2192' - ; - -EQUALS -: '=' - ; - -NOT_EQUALS -: '!=' | '\u2260' - ; - -SEQARROW -: '==>' | '\u27F9' - ; - -EXP -: '^' - ; - -TILDE -: '~' - ; - -PERCENT -: '%' - ; - -STAR -: '*' - ; - -MINUS -: '-' - ; - -PLUS -: '+' - ; - -GREATER -: '>' - ; - -GREATEREQUAL -: '>' '=' | '\u2265' - ; - -RGUILLEMETS - : '>' '>' - ; +NOT: '!' | '\u00AC'; +IMP: '->' | '\u2192'; +EQUALS: '='; +NOT_EQUALS: '!=' | '\u2260'; +SEQARROW: '==>' | '\u27F9'; +EXP: '^' OP_SFX?; +TILDE: '~' OP_SFX?; +PERCENT: '%' OP_SFX?; +STAR : '*' OP_SFX?; +MINUS: '-' OP_SFX?; +PLUS: '+' OP_SFX?; +GREATER: '>' ; +GREATEREQUAL: '>' '=' | '\u2265'; +RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index a2af54cd921..b7261612d95 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -367,7 +367,7 @@ equality_term: a=comparison_term ((NOT_EQUALS|EQUALS) b=comparison_term)?; comparison_term: a=weak_arith_term ((LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; weak_arith_term: a=strong_arith_term_1 (op+=(PLUS|MINUS) b+=strong_arith_term_1)*; strong_arith_term_1: a=strong_arith_term_2 (STAR b+=strong_arith_term_2)*; -strong_arith_term_2: a=atom_prefix ((PERCENT|SLASH) b=strong_arith_term_2)?; +strong_arith_term_2: a=atom_prefix (op=(PERCENT|SLASH) b=strong_arith_term_2)?; update_term: (LBRACE u=term RBRACE) (atom_prefix | unary_formula); substitution_term: LBRACE SUBST bv=one_bound_variable SEMI diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 9b1b2d64f69..ecb03aea87c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -308,10 +308,8 @@ public Object visitWeak_arith_term(KeYParser.Weak_arith_termContext ctx) { Term last = termL; for (int i = 0; i < terms.size(); i++) { final String opTok = ctx.op.get(i).getText(); - // it's either + or -. - String opname = opTok.equals("+") ? "add" : "sub"; Term cur = terms.get(i); - last = binaryLDTSpecificTerm(ctx, opname, last, cur); + last = binaryLDTSpecificTerm(ctx, opTok, last, cur); } return last; } @@ -344,7 +342,7 @@ public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) Term last = termL; for (int i = 0; i < terms.size(); i++) { Term cur = terms.get(i); - last = binaryLDTSpecificTerm(ctx, "mul", last, cur); + last = binaryLDTSpecificTerm(ctx, ctx.STAR(i).getText(), last, cur); } return last; } @@ -355,8 +353,8 @@ public Object visitStrong_arith_term_2(KeYParser.Strong_arith_term_2Context ctx) if (ctx.b == null) return termL; Term termR = accept(ctx.b); - String opName = ctx.SLASH() != null ? "div" : "mod"; - return binaryLDTSpecificTerm(ctx, opName, termL, termR); + //String opName = ctx.SLASH() != null ? "div" : "mod"; + return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } protected Term capsulateTf(ParserRuleContext ctx, Supplier termSupplier) { From b9fd5a62fe4706b39a8932ccd5bb125f58efb47c Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:42:59 +0100 Subject: [PATCH 15/38] add metadata information to functions and predicates --- key/key.core/src/main/antlr4/KeYLexer.g4 | 7 ++++++- key/key.core/src/main/antlr4/KeYParser.g4 | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 3e161b1e64d..acbaf3d0311 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -233,6 +233,9 @@ PREDICATES : '\\predicates'; FUNCTIONS : '\\functions'; TRANSFORMERS : '\\transformers'; UNIQUE : '\\unique'; +INFIX: '\\infix'; +PREFIX: '\\prefix'; +POSTFIX: '\\postfix'; RULES : '\\rules'; AXIOMS : '\\axioms'; @@ -310,7 +313,9 @@ PLUS: '+' OP_SFX?; GREATER: '>' ; GREATEREQUAL: '>' '=' | '\u2265'; RGUILLEMETS: '>' '>' ; - + + + WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; LESS: '<'; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index b7261612d95..684d870e173 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -230,6 +230,7 @@ pred_decl pred_name = funcpred_name (whereToBind=where_to_bind)? argSorts=arg_sorts + functionMetaData? SEMI ; @@ -246,9 +247,17 @@ func_decl func_name = funcpred_name whereToBind=where_to_bind? argSorts = arg_sorts + functionMetaData? SEMI ; +functionMetaData +: + INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN + | PREFIX LPAREN (MINUS|TILDE) RPAREN + | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN +; + func_decls : FUNCTIONS From ab2a6be78b4e9e5e7844480331ffc437e8b9a772 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 4 Feb 2022 23:54:39 +0100 Subject: [PATCH 16/38] add MixFitInfo to capture information --- .../de/uka/ilkd/key/logic/op/Function.java | 80 ++++++++++++++++--- .../builder/FunctionPredicateBuilder.java | 8 +- 2 files changed, 73 insertions(+), 15 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java index bc4eab03d51..dafd11d9956 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java @@ -19,6 +19,9 @@ import de.uka.ilkd.key.logic.sort.NullSort; import de.uka.ilkd.key.logic.sort.Sort; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Objects of this class represent function and predicate symbols. Note @@ -26,6 +29,7 @@ * of function. */ public class Function extends AbstractSortedOperator { + private final MixFitInfo mixFitInfo; private final boolean unique; private final boolean skolemConstant; @@ -34,6 +38,24 @@ public class Function extends AbstractSortedOperator { //------------------------------------------------------------------------- //constructors //------------------------------------------------------------------------- + Function(Name name, + Sort sort, + ImmutableArray argSorts, + ImmutableArray whereToBind, + boolean unique, + boolean isRigid, + boolean isSkolemConstant, + @Nullable MixFitInfo mixFitInfo) { + super(name, argSorts, sort, whereToBind, isRigid); + + this.unique = unique; + skolemConstant = isSkolemConstant; + assert sort != Sort.UPDATE; + assert !(unique && sort == Sort.FORMULA); + assert !(sort instanceof NullSort) || name.toString().equals("null") + : "Functions with sort \"null\" are not allowed: " + this; + this.mixFitInfo = mixFitInfo; + } Function(Name name, Sort sort, @@ -42,24 +64,20 @@ public class Function extends AbstractSortedOperator { boolean unique, boolean isRigid, boolean isSkolemConstant) { - super(name, argSorts, sort, whereToBind, isRigid); - - this.unique = unique; - skolemConstant = isSkolemConstant; - assert sort != Sort.UPDATE; - assert !(unique && sort == Sort.FORMULA); - assert !(sort instanceof NullSort) || name.toString().equals("null") - : "Functions with sort \"null\" are not allowed: " + this; + this(name, sort, argSorts, whereToBind, unique, isRigid, isSkolemConstant, null); } - public Function(Name name, - Sort sort, - ImmutableArray argSorts, - ImmutableArray whereToBind, + public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, boolean unique) { this(name, sort, argSorts, whereToBind, unique, true, false); } + public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, + boolean unique, MixFitInfo mixFitInfo) { + this(name, sort, argSorts, whereToBind, unique, true, false, mixFitInfo); + } + + public Function(Name name, Sort sort, ImmutableArray argSorts, @@ -81,6 +99,12 @@ public Function(Name name, unique); } + public Function(Name name, Sort sort, Sort[] argSorts, Boolean[] whereToBind, boolean unique, + MixFitInfo mixFitInfo) { + this(name, sort, new ImmutableArray<>(argSorts), + whereToBind == null ? null : new ImmutableArray<>(whereToBind), unique, mixFitInfo); + } + public Function(Name name, Sort sort, Sort[] argSorts, @@ -120,6 +144,8 @@ public Function(Name name, Sort sort, boolean isSkolemConstant) { } + + //------------------------------------------------------------------------- //public interface //------------------------------------------------------------------------- @@ -172,4 +198,32 @@ public final String proofToString() { public Function rename(Name newName) { return new Function(newName, sort(), argSorts(), whereToBind(), unique, skolemConstant); } -} \ No newline at end of file + + public MixFitInfo getMixFitInfo() { + return mixFitInfo; + } + + public static class MixFitInfo { + @Nonnull + public final Kind kind; + @Nonnull + public final String symbol; + + public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { + this.kind = kind; + this.symbol = symbol; + } + + enum Kind {PREFIX, INFIX, POSTFIX} + + @Nonnull + public Kind getKind() { + return kind; + } + + @Nonnull + public String getSymbol() { + return symbol; + } + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java index 9b56adb7c79..5bec61a9817 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java @@ -55,6 +55,8 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Function p = null; + Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + int separatorIndex = pred_name.indexOf("::"); if (separatorIndex > 0) { String sortName = pred_name.substring(0, separatorIndex); @@ -77,7 +79,7 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Sort.FORMULA, argSorts.toArray(new Sort[0]), whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - false); + false, mixFitInfo); } if (lookup(p.name()) == null) { @@ -99,6 +101,8 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { semanticError(ctx, "Where-to-bind list must have same length as argument list"); } + Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + Function f = null; assert func_name != null; int separatorIndex = func_name.indexOf("::"); @@ -121,7 +125,7 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { retSort, argSorts.toArray(new Sort[0]), whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - unique); + unique, mixFitInfo); } if (lookup(f.name()) == null) { From 2aa5097c7118a306b6f5e71ecbbb9403e27384ff Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 5 Feb 2022 00:03:20 +0100 Subject: [PATCH 17/38] change the loopup functions --- .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/DoubleLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/FloatLDT.java | 4 ++-- .../java/de/uka/ilkd/key/ldt/IntegerLDT.java | 4 ++-- .../src/main/java/de/uka/ilkd/key/ldt/LDT.java | 18 ++++++++++++++---- .../java/de/uka/ilkd/key/ldt/LocSetLDT.java | 4 ++-- .../main/java/de/uka/ilkd/key/ldt/SeqLDT.java | 4 ++-- 7 files changed, 26 insertions(+), 16 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 8b9b44ddd01..6634c9fd324 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -267,8 +267,8 @@ public final Type getType(Term t) { @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { // This is not very elegant; but seqConcat is actually in the SeqLDT. case "add": return services.getNamespaces().functions().lookup("seqConcat"); default: return null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java index 9d694702bd3..ca749b926d9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java @@ -178,8 +178,8 @@ public Term translateLiteral(Literal lit, Services services) { } @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java index 37c231b93d3..8effd7494d2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java @@ -188,8 +188,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, } @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java index 862e656c63f..f174731a0c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java @@ -499,8 +499,8 @@ public Function getFunctionFor( @Nullable @Override - public Function getFunctionFor(String op, Services services) { - switch (op) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "gt": return getGreaterThan(); case "geq": return getGreaterOrEquals(); case "lt": return getLessThan(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index 40206920796..ccb8ae456de 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -248,7 +248,7 @@ public abstract Function getFunctionFor( /** * get the function in this LDT for an operation identified by generic - * operationName. If the LDT does not support this named function, it should + * operatorSymbol. If the LDT does not support this named function, it should * return null. * * This is used to resolve overloaded symbols. @@ -256,13 +256,23 @@ public abstract Function getFunctionFor( * For example: "+" may map to "add" for integers, and to "addFloat" for * floats. * - * @param operationName non-null operationName for a generic function + * @param operatorSymbol non-null operatorSymbol for a generic function * @param services services to use * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public @Nullable Function getFunctionFor(String operationName, Services services) { - // by default an LDT does not support overloaded symbols + public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + for (Operator operator : functions.allElements()) { + if(operator instanceof Function) { + var op = (Function) operator; + if (op.getMixFitInfo() != null) { + var mfi = op.getMixFitInfo(); + if (mfi.symbol.equals(operatorSymbol)) { + return op; + } + } + } + } return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java index b50855dd9d4..1bec475b569 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java @@ -233,8 +233,8 @@ public final Type getType(Term t) { @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "add": return getUnion(); case "sub": return getSetMinus(); case "mul": return getIntersect(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java index 7efae2bfc31..08bc458f734 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java @@ -186,8 +186,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, @Nullable @Override - public Function getFunctionFor(String operationName, Services services) { - switch (operationName) { + public Function getFunctionFor(String operatorSymbol, Services services) { + switch (operatorSymbol) { case "add": return getSeqConcat(); default: return null; } From 75efea8c1d07830dd65d80769716d4fa7687bbb0 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 5 Feb 2022 00:08:16 +0100 Subject: [PATCH 18/38] remove seq +, use annotation --- .../src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java | 10 ---------- .../main/resources/de/uka/ilkd/key/proof/rules/seq.key | 2 +- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java index 08bc458f734..482a8ac6ce0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java @@ -184,16 +184,6 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, return null; } - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "add": return getSeqConcat(); - default: return null; - } - } - - @Override public boolean hasLiteralFunction(Function f) { return f.equals(seqEmpty); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key index 698796df2fe..036da835c8c 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/seq.key @@ -37,7 +37,7 @@ //constructors Seq seqEmpty; Seq seqSingleton(any); - Seq seqConcat(Seq, Seq); + Seq seqConcat(Seq, Seq) \infix(+); Seq seqSub(Seq, int, int); Seq seqReverse(Seq); Seq seqDef{false,false,true}(int, int, any); From 36efc6b758861c30e956b7a6fce92a0ac03d3c1c Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 15:57:41 +0100 Subject: [PATCH 19/38] remove old lookup and add metadata --- key/key.core/src/main/antlr4/KeYLexer.g4 | 1 + key/key.core/src/main/antlr4/KeYParser.g4 | 1 + .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 10 ------ .../java/de/uka/ilkd/key/ldt/DoubleLDT.java | 16 ++-------- .../java/de/uka/ilkd/key/ldt/FloatLDT.java | 18 ++--------- .../java/de/uka/ilkd/key/ldt/IntegerLDT.java | 17 ---------- .../main/java/de/uka/ilkd/key/ldt/LDT.java | 2 +- .../java/de/uka/ilkd/key/ldt/LocSetLDT.java | 12 ------- .../uka/ilkd/key/proof/rules/floatHeader.key | 31 ++++++++++--------- .../ilkd/key/proof/rules/integerHeader.key | 22 ++++++------- .../de/uka/ilkd/key/proof/rules/locSets.key | 10 +++--- 11 files changed, 40 insertions(+), 100 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index acbaf3d0311..60d9375b9ab 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -235,6 +235,7 @@ TRANSFORMERS : '\\transformers'; UNIQUE : '\\unique'; INFIX: '\\infix'; PREFIX: '\\prefix'; +SHORTCUT:'\\shortcut'; POSTFIX: '\\postfix'; RULES : '\\rules'; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 684d870e173..0e185cc9ae6 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -256,6 +256,7 @@ functionMetaData INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN | PREFIX LPAREN (MINUS|TILDE) RPAREN | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN + | SHORTCUT LPAREN IDENT RPAREN ; func_decls diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 6634c9fd324..4a0dc36bc81 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -264,14 +264,4 @@ public final Type getType(Term t) { assert false; return null; } - - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - // This is not very elegant; but seqConcat is actually in the SeqLDT. - case "add": return services.getNamespaces().functions().lookup("seqConcat"); - default: return null; - } - } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java index ca749b926d9..3ffab20ff99 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java @@ -177,19 +177,9 @@ public Term translateLiteral(Literal lit, Services services) { return services.getTermBuilder().dfpTerm(doubleVal); } - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "neg": return getNeg(); +/* @Override + public Function getFunctionFor(String operatorSymbol, Services services) { // Floating point extensions with "\fp_" case "nan": return getIsNaN(); case "zero": return getIsZero(); @@ -202,7 +192,7 @@ public Function getFunctionFor(String operatorSymbol, Services services) { case "normal": return getIsNormal(); } return null; - } + }*/ @Override public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java index 8effd7494d2..3a55c5fe2dc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java @@ -187,19 +187,8 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, } } - @Override +/* @Override public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "neg": return getNeg(); - // Floating point extensions with "\fp_" case "nan": return getIsNaN(); case "zero": return getIsZero(); case "infinite": return getIsInfinite(); @@ -208,10 +197,7 @@ public Function getFunctionFor(String operatorSymbol, Services services) { case "negative": return getIsNegative(); case "positive": return getIsPositive(); case "subnormal": return getIsSubnormal(); - case "normal": return getIsNormal(); - } - return null; - } +*/ @Override public boolean hasLiteralFunction(Function f) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java index f174731a0c6..747541ff803 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java @@ -497,23 +497,6 @@ public Function getFunctionFor( } } - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "gt": return getGreaterThan(); - case "geq": return getGreaterOrEquals(); - case "lt": return getLessThan(); - case "leq": return getLessOrEquals(); - case "div": return getDiv(); - case "mul": return getMul(); - case "add": return getAdd(); - case "sub": return getSub(); - case "mod": return getMod(); - case "neg": return getNeg(); - } - return null; - } @Override public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index ccb8ae456de..9b7d102e108 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -261,7 +261,7 @@ public abstract Function getFunctionFor( * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + public final @Nullable Function getFunctionFor(String operatorSymbol, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java index 1bec475b569..6f3c05b7c6f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java @@ -230,16 +230,4 @@ public final Type getType(Term t) { assert false; return null; } - - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - switch (operatorSymbol) { - case "add": return getUnion(); - case "sub": return getSetMinus(); - case "mul": return getIntersect(); - case "le": return getSubset(); - default: return null; - } - } } \ No newline at end of file diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index 4810eb3bf80..fbbc7c63632 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -12,11 +12,12 @@ // \sorts { - + /*! `fp` is the upper sort representing all floating point numbers. */ fp; + /*! */ float \extends fp; + /*! */ double \extends fp; - java.lang.Math \extends java.lang.Object; } @@ -45,11 +46,11 @@ float javaDivFloatForbiddenResult(float, float); // Floating-point arithmetic with IEEE 754 semantics - float addFloat(float, float); - float subFloat(float, float); - float mulFloat(float, float); - float divFloat(float, float); - float negFloat(float); + float addFloat(float, float) \infix(+); + float subFloat(float, float) \infix(-); + float mulFloat(float, float) \infix(*); + float divFloat(float, float) \infix(/); + float negFloat(float) \prefix(-); float absFloat(float); @@ -95,10 +96,10 @@ \predicates { - ltFloat(float, float); - gtFloat(float, float); - leqFloat(float, float); - geqFloat(float, float); + ltFloat(float, float) \infix(<); + gtFloat(float, float) \infix(>); + leqFloat(float, float) \infix(<=); + geqFloat(float, float) \infix(>=); eqFloat(float, float); floatIsNaN(float); @@ -110,10 +111,10 @@ floatIsNegative(float); floatIsNice(float); - ltDouble(double, double); - gtDouble(double, double); - leqDouble(double, double); - geqDouble(double, double); + ltDouble(double, double) \infix(<); + gtDouble(double, double) \infix(>); + leqDouble(double, double) \infix(<=); + geqDouble(double, double) \infix(>=); eqDouble(double, double); doubleIsNaN(double); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index 91a354c1d33..95f5fbcf052 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -35,13 +35,13 @@ int C (numbers); //arithmetic operators on mathematical integers - int add(int,int); - int neg(int); - int sub(int,int); - int mul(int, int); - int div(int, int); - int mod(int, int); - int pow(int, int); + int add(int,int) \infix(+); + int neg(int) \prefix(-); + int sub(int,int) \infix(-); + int mul(int, int) \infix(*); + int div(int, int) \infix(/); + int mod(int, int) \infix(%); + int pow(int, int) \infix(**); // comprehensions int bsum{false,false,true}(int, int, int); @@ -209,10 +209,10 @@ //from the current integer semantics. //---------------------------------------------------------------------------- - leq(int, int); - lt(int, int); - geq(int, int); - gt(int, int); + leq(int, int) \infix(<=); + lt(int, int) \infix(<); + geq(int, int) \infix(>=); + gt(int, int) \infix(>); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key index 6cf833bd56f..bdd9dc0bbcc 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/locSets.key @@ -12,9 +12,9 @@ // other constructors LocSet singleton(Object, Field); - LocSet union(LocSet, LocSet); - LocSet intersect(LocSet, LocSet); - LocSet setMinus(LocSet, LocSet); + LocSet union(LocSet, LocSet) \infix(+); + LocSet intersect(LocSet, LocSet) \infix(*); + LocSet setMinus(LocSet, LocSet) \infix(-); LocSet infiniteUnion{true}(LocSet); LocSet allFields(Object); LocSet allObjects(Field); @@ -27,8 +27,8 @@ \predicates { elementOf(Object, Field, LocSet); - subset(LocSet, LocSet); - disjoint(LocSet, LocSet); + subset(LocSet, LocSet) \infix(<); + disjoint(LocSet, LocSet) \infix(<|>); createdInHeap(LocSet, Heap); } From e7d9172d275b85625e950d7e3d3c7d0da9fa3848 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 22:12:59 +0100 Subject: [PATCH 20/38] NotationInfo recognizes MixFitInfos more operators are allowed --- key/key.core/src/main/antlr4/KeYLexer.g4 | 27 +- key/key.core/src/main/antlr4/KeYParser.g4 | 6 +- .../de/uka/ilkd/key/java/TypeConverter.java | 77 ++--- .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 6 + .../main/java/de/uka/ilkd/key/ldt/LDT.java | 7 +- .../de/uka/ilkd/key/logic/op/Function.java | 25 -- .../de/uka/ilkd/key/logic/op/MixFitInfo.java | 31 ++ .../nparser/builder/ExpressionBuilder.java | 13 +- .../builder/FunctionPredicateBuilder.java | 13 +- .../java/de/uka/ilkd/key/pp/NotationInfo.java | 282 +++++++++++------- .../uka/ilkd/key/proof/rules/floatHeader.key | 8 +- .../ilkd/key/proof/rules/integerHeader.key | 2 +- .../de/uka/ilkd/key/nparser/ExprTest.java | 1 + .../de/uka/ilkd/key/nparser/exprs.txt | 2 +- 14 files changed, 287 insertions(+), 213 deletions(-) create mode 100644 key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 60d9375b9ab..f6f6f740cff 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -97,6 +97,17 @@ lexer grammar KeYLexer; tokens {MODALITY} +// Comments have precedence over operators // and /*. +SL_COMMENT +: + '//' + (~('\n' | '\uFFFF'))* ('\n' | '\uFFFF' | EOF) -> channel(HIDDEN) +; + +DOC_COMMENT: '/*!' -> more, pushMode(docComment); +ML_COMMENT: '/*' -> more, pushMode(COMMENT); + + SORTS:'\\sorts'; GENERIC : '\\generic'; PROXY : '\\proxy'; @@ -275,10 +286,10 @@ VOCAB : '\u0003'..'\u0377' ; -fragment OP_SFX: [-+*/&.^]+; +fragment OP_SFX: ('-'|'='|'+'|'*'|'/'|'&'|'.'|'|'|'^'|'!'|':'|'>'|'<')+; SEMI: ';'; -SLASH: '/'; +SLASH: '/' OP_SFX?; COLON: ':'; DOUBLECOLON:'::'; ASSIGN: ':='; @@ -319,8 +330,8 @@ RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; -LESS: '<'; LESSEQUAL: '<' '=' | '\u2264'; +LESS: '<' OP_SFX?; LGUILLEMETS: '<' '<'; IMPLICIT_IDENT: '<' (LETTER)+ '>' ('$lmtd')? -> type(IDENT); @@ -339,16 +350,6 @@ CHAR_LITERAL QUOTED_STRING_LITERAL : '"' ('\\' . | '\n' | ~('\n' | '"' | '\\') )* '"' ; -SL_COMMENT -: - '//' - (~('\n' | '\uFFFF'))* ('\n' | '\uFFFF' | EOF) -> channel(HIDDEN) -; - -DOC_COMMENT: '/*!' -> more, pushMode(docComment); -ML_COMMENT: '/*' -> more, pushMode(COMMENT); - - BIN_LITERAL: '0' 'b' ('0' | '1' | '_')+ ('l'|'L')?; HEX_LITERAL: '0' 'x' (DIGIT | 'a'..'f' | 'A'..'F' | '_')+ ('l'|'L')?; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 0e185cc9ae6..76f79b4e54d 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -253,8 +253,8 @@ func_decl functionMetaData : - INFIX LPAREN (PLUS|STAR|SLASH|MINUS|EXP) RPAREN - | PREFIX LPAREN (MINUS|TILDE) RPAREN + INFIX LPAREN op=(PLUS|STAR|SLASH|MINUS|EXP|PERCENT|LESS|LESSEQUAL|GREATER|GREATEREQUAL|LGUILLEMETS) RPAREN + | PREFIX LPAREN op=(MINUS|TILDE) RPAREN | POSTFIX LPAREN (/*currently no overloaded operator*/) RPAREN | SHORTCUT LPAREN IDENT RPAREN ; @@ -374,7 +374,7 @@ unary_formula: | MODALITY sub=term60 #modality_term ; equality_term: a=comparison_term ((NOT_EQUALS|EQUALS) b=comparison_term)?; -comparison_term: a=weak_arith_term ((LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; +comparison_term: a=weak_arith_term (op=(LESS|LESSEQUAL|GREATER|GREATEREQUAL) b=weak_arith_term)?; weak_arith_term: a=strong_arith_term_1 (op+=(PLUS|MINUS) b+=strong_arith_term_1)*; strong_arith_term_1: a=strong_arith_term_2 (STAR b+=strong_arith_term_2)*; strong_arith_term_2: a=atom_prefix (op=(PERCENT|SLASH) b=strong_arith_term_2)?; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java index ab837a05d81..b3da18302e5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java @@ -32,13 +32,12 @@ 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import recoder.service.ConstantEvaluator; -import recoder.service.KeYCrossReferenceSourceInfo; +import java.util.Collection; +import java.util.Collections; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -408,6 +407,7 @@ private Term convertLiteralExpression(Literal lit) { // TODO Adapt for @Reals + /** * performs binary numeric promotion on the argument types */ @@ -457,39 +457,39 @@ else if ((t1 == PrimitiveType.JAVA_BOOLEAN && return type1; } else if (type2.equals(services.getJavaInfo().getKeYJavaType("java.lang.String"))) { return type2; - } else if ((t2 == PrimitiveType.JAVA_FLOAT) && - (t1 == PrimitiveType.JAVA_BYTE|| - t1 == PrimitiveType.JAVA_SHORT|| - t1 == PrimitiveType.JAVA_INT|| - t1 == PrimitiveType.JAVA_CHAR|| - t1 == PrimitiveType.JAVA_LONG|| - t1 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t2 == PrimitiveType.JAVA_FLOAT) && + (t1 == PrimitiveType.JAVA_BYTE || + t1 == PrimitiveType.JAVA_SHORT || + t1 == PrimitiveType.JAVA_INT || + t1 == PrimitiveType.JAVA_CHAR || + t1 == PrimitiveType.JAVA_LONG || + t1 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t1 == PrimitiveType.JAVA_FLOAT) && - (t2 == PrimitiveType.JAVA_BYTE|| - t2 == PrimitiveType.JAVA_SHORT|| - t2 == PrimitiveType.JAVA_INT|| - t2 == PrimitiveType.JAVA_CHAR|| - t2 == PrimitiveType.JAVA_LONG|| - t2 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t1 == PrimitiveType.JAVA_FLOAT) && + (t2 == PrimitiveType.JAVA_BYTE || + t2 == PrimitiveType.JAVA_SHORT || + t2 == PrimitiveType.JAVA_INT || + t2 == PrimitiveType.JAVA_CHAR || + t2 == PrimitiveType.JAVA_LONG || + t2 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && - (t1 == PrimitiveType.JAVA_BYTE|| - t1 == PrimitiveType.JAVA_SHORT|| - t1 == PrimitiveType.JAVA_INT|| - t1 == PrimitiveType.JAVA_CHAR|| - t1 == PrimitiveType.JAVA_LONG|| - t1 == PrimitiveType.JAVA_FLOAT|| - t1 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && + (t1 == PrimitiveType.JAVA_BYTE || + t1 == PrimitiveType.JAVA_SHORT || + t1 == PrimitiveType.JAVA_INT || + t1 == PrimitiveType.JAVA_CHAR || + t1 == PrimitiveType.JAVA_LONG || + t1 == PrimitiveType.JAVA_FLOAT || + t1 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); - } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && - (t2 == PrimitiveType.JAVA_BYTE|| - t2 == PrimitiveType.JAVA_SHORT|| - t2 == PrimitiveType.JAVA_INT|| - t2 == PrimitiveType.JAVA_CHAR|| - t2 == PrimitiveType.JAVA_LONG|| - t2 == PrimitiveType.JAVA_FLOAT|| - t2 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && + (t2 == PrimitiveType.JAVA_BYTE || + t2 == PrimitiveType.JAVA_SHORT || + t2 == PrimitiveType.JAVA_INT || + t2 == PrimitiveType.JAVA_CHAR || + t2 == PrimitiveType.JAVA_LONG || + t2 == PrimitiveType.JAVA_FLOAT || + t2 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); } else { throw new RuntimeException("Could not determine promoted type " @@ -524,10 +524,10 @@ else if (t1 == PrimitiveType.JAVA_BIGINT) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BIGINT); else if (t1 == PrimitiveType.JAVA_REAL) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_REAL); - else if (t1 == PrimitiveType.JAVA_FLOAT) - return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - else if (t1 == PrimitiveType.JAVA_DOUBLE) - return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); + else if (t1 == PrimitiveType.JAVA_FLOAT) + return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); + else if (t1 == PrimitiveType.JAVA_DOUBLE) + return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); else throw new RuntimeException("Could not determine promoted type " + "of " + type1); } @@ -1037,4 +1037,7 @@ private LDT getResponsibleLDT(de.uka.ilkd.key.java.expression.Operator op, Term[ return null; } + public Collection getLDTs() { + return Collections.unmodifiableCollection(LDTs.values()); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 4a0dc36bc81..afb39f1a28a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -264,4 +264,10 @@ public final Type getType(Term t) { assert false; return null; } + + @Nullable + @Override + public Function getFunctionFor(String operatorSymbol, Services services) { + return services.getTypeConverter().getSeqLDT().getFunctionFor(operatorSymbol, services); + } } \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index 9b7d102e108..c50acdb6fca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -13,6 +13,7 @@ package de.uka.ilkd.key.ldt; +import java.util.Collection; import java.util.Map; import java.util.TreeMap; @@ -261,7 +262,7 @@ public abstract Function getFunctionFor( * @return reference to the respective LDT-specific function for the * operation, null if not available */ - public final @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; @@ -282,4 +283,8 @@ public abstract Function getFunctionFor( public abstract Expression translateTerm(Term t, ExtList children, Services services); public abstract Type getType(Term t); + + public Collection getFunctions() { + return functions.allElements(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java index dafd11d9956..5546743d9c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java @@ -19,7 +19,6 @@ import de.uka.ilkd.key.logic.sort.NullSort; import de.uka.ilkd.key.logic.sort.Sort; -import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -202,28 +201,4 @@ public Function rename(Name newName) { public MixFitInfo getMixFitInfo() { return mixFitInfo; } - - public static class MixFitInfo { - @Nonnull - public final Kind kind; - @Nonnull - public final String symbol; - - public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { - this.kind = kind; - this.symbol = symbol; - } - - enum Kind {PREFIX, INFIX, POSTFIX} - - @Nonnull - public Kind getKind() { - return kind; - } - - @Nonnull - public String getSymbol() { - return symbol; - } - } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java new file mode 100644 index 00000000000..44c019b0b40 --- /dev/null +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java @@ -0,0 +1,31 @@ +package de.uka.ilkd.key.logic.op; + +import javax.annotation.Nonnull; + +/** + * @author Alexander Weigl + * @version 1 (06.02.22) + */ +public class MixFitInfo { + @Nonnull + public final Kind kind; + @Nonnull + public final String symbol; + + public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { + this.kind = kind; + this.symbol = symbol; + } + + public enum Kind {PREFIX, INFIX, SHORTCUT, POSTFIX} + + @Nonnull + public Kind getKind() { + return kind; + } + + @Nonnull + public String getSymbol() { + return symbol; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index ecb03aea87c..ceb60c84412 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -283,18 +283,7 @@ public Object visitComparison_term(KeYParser.Comparison_termContext ctx) { if(termR == null) { return updateOrigin(termL, ctx); } - - String op_name = ""; - if (ctx.LESS() != null) - op_name = "lt"; - if (ctx.LESSEQUAL() != null) - op_name = "leq"; - if (ctx.GREATER() != null) - op_name = "gt"; - if (ctx.GREATEREQUAL() != null) - op_name = "geq"; - return binaryLDTSpecificTerm(ctx, op_name, termL, termR); - + return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java index 5bec61a9817..95b04ed77ca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java @@ -4,6 +4,7 @@ import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.NamespaceSet; import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.MixFitInfo; import de.uka.ilkd.key.logic.op.SortDependingFunction; import de.uka.ilkd.key.logic.op.Transformer; import de.uka.ilkd.key.logic.sort.GenericSort; @@ -44,6 +45,14 @@ public Object visitDecls(KeYParser.DeclsContext ctx) { return null; } + @Override + public Object visitFunctionMetaData(KeYParser.FunctionMetaDataContext ctx) { + MixFitInfo.Kind kind = ctx.PREFIX() != null + ? MixFitInfo.Kind.PREFIX : ctx.INFIX() != null ? MixFitInfo.Kind.INFIX + : MixFitInfo.Kind.POSTFIX != null ? MixFitInfo.Kind.POSTFIX : MixFitInfo.Kind.SHORTCUT; + return new MixFitInfo(kind, ctx.op.getText()); + } + @Override public Object visitPred_decl(KeYParser.Pred_declContext ctx) { String pred_name = accept(ctx.funcpred_name()); @@ -55,7 +64,7 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Function p = null; - Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); int separatorIndex = pred_name.indexOf("::"); if (separatorIndex > 0) { @@ -101,7 +110,7 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { semanticError(ctx, "Where-to-bind list must have same length as argument list"); } - Function.MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); + MixFitInfo mixFitInfo = accept(ctx.functionMetaData()); Function f = null; assert func_name != null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java index ec8413656e5..a19920a949b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java @@ -18,94 +18,88 @@ import java.util.Map; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.HeapLDT; -import de.uka.ilkd.key.ldt.IntegerLDT; -import de.uka.ilkd.key.ldt.CharListLDT; -import de.uka.ilkd.key.ldt.DoubleLDT; -import de.uka.ilkd.key.ldt.FloatLDT; -import de.uka.ilkd.key.ldt.LocSetLDT; -import de.uka.ilkd.key.ldt.SeqLDT; +import de.uka.ilkd.key.ldt.*; import de.uka.ilkd.key.logic.label.TermLabel; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.logic.sort.Sort; import de.uka.ilkd.key.util.UnicodeHelper; -/** - *

- * Stores the mapping from operators to {@link Notation}s. Each - * {@link Notation} represents the concrete syntax for some +/** + *

+ * Stores the mapping from operators to {@link Notation}s. Each + * {@link Notation} represents the concrete syntax for some * {@link de.uka.ilkd.key.logic.op.Operator}. The {@link LogicPrinter} * asks the NotationInfo to find out which Notation to use for a given term. *

* The Notation associated with an operator might change. New Notations can * be added. - * + * *

- * The next lines describe a general rule how to determine priorities and + * The next lines describe a general rule how to determine priorities and * associativities: - * + * * One thing we need to know from the pretty printer: - * Given a term t containg s as proper subterm. + * Given a term t containg s as proper subterm. * Then s is printed in parentheses when the priority of the - * top level symbol of s is strict less than the associativity of the + * top level symbol of s is strict less than the associativity of the * position where s occurs. For example: *

- * Let the priority of AND be 30 and the associativities for each - * of its subterms be 40; ORs priority is 20 and the associativites are - * both 30 then + * Let the priority of AND be 30 and the associativities for each + * of its subterms be 40; ORs priority is 20 and the associativites are + * both 30 then *

  • formula (p & q) | r is pretty printed as p & q | r - * as the priority of & is 30 which is (greater or) equal than the + * as the priority of & is 30 which is (greater or) equal than the * associativity of ORs left subterm which is 30.
  • - *
  • In contrast the formula p & (q | r) is pretty printed as - * p & (q | r) as the priority of OR is 20 which is less than + *
  • In contrast the formula p & (q | r) is pretty printed as + * p & (q | r) as the priority of OR is 20 which is less than * the associativity of ANDs left subterm, which is 40.
  • - *
- * - * A general rule to determine the correct priority and associativity is to use: - * - * Grammar rules whose derivation delivers a syntactical correct logic term should follow - * a standard numbering scheme, which is used as indicator for priorities and associativites, - * e.g. - * by simply reading the grammar rule - *
term60 ::= term70 (IMP term70)?
- * we get the priority of IMP, which is 60. The associativities - * of IMPs subterms are not much more difficult to determine, namely - * the left subterm has associativity 70 and in this case its the same + * + * + * A general rule to determine the correct priority and associativity is to use: + * + * Grammar rules whose derivation delivers a syntactical correct logic term should follow + * a standard numbering scheme, which is used as indicator for priorities and associativites, + * e.g. + * by simply reading the grammar rule + *
term60 ::= term70 (IMP term70)?
+ * we get the priority of IMP, which is 60. The associativities + * of IMPs subterms are not much more difficult to determine, namely + * the left subterm has associativity 70 and in this case its the same * for the right subterm (70). *

* There are exceptional cases for *

    - *
  • infix function symbols that are left associative e.g. + *
  • infix function symbols that are left associative e.g. * -, + - *
    + *
    * term90 ::= term100 (PLUS term100)* - *
    - * then the associative for the right subterm is increased by 1, - * i.e. here we have a priority of 90 for PLUS as infix operator, + *
    + * then the associative for the right subterm is increased by 1, + * i.e. here we have a priority of 90 for PLUS as infix operator, * a left associativity of 100 and a right associativity of 101 *
  • - *
  • update and substituition terms: for them their associativity is - * determined dynamically by the pretty printer depending if it is applied on a + *
  • update and substituition terms: for them their associativity is + * determined dynamically by the pretty printer depending if it is applied on a * formula or term. In principal there should be two different - * rules in the parser as then we could reuse the general rule from above, but + * rules in the parser as then we could reuse the general rule from above, but * there are technical reasons which causes this exception. *
  • - *
  • some very few rules do not follow the usual parser design + *
  • some very few rules do not follow the usual parser design * e.g. like *
    R_PRIO ::= SubRule_ASS1 | SubRule_ASS2
    * where - *
    SubRule_ASS2 ::= OP SubRule_ASS1
    + *
    SubRule_ASS2 ::= OP SubRule_ASS1
    * Most of these few rules could in general be rewritten to fit the usual scheme * e.g. as - *
    R_PRIO ::= (OP)? SubRule_ASS1
    - * using the priorities and associativities of the so rewritten rules - * (instead of rewriting them actually) is a way to cope with them. + *
    R_PRIO ::= (OP)? SubRule_ASS1
    + * using the priorities and associativities of the so rewritten rules + * (instead of rewriting them actually) is a way to cope with them. *
  • *
*/ public final class NotationInfo { - + // Priorities of operators (roughly corresponding to the grammatical structure in the parser. @@ -137,28 +131,28 @@ public final class NotationInfo { * are printed. */ public static boolean DEFAULT_UNICODE_ENABLED = false; - + public static boolean DEFAULT_HIDE_PACKAGE_PREFIX = false; - + /** This maps operators and classes of operators to {@link * Notation}s. The idea is that we first look whether the operator has * a Notation registered. Otherwise, we see if there is one for the * class of the operator. */ - private HashMap notationTable; + private Map notationTable; + - /** * Maps terms to abbreviations and reverse. */ private AbbrevMap scm = new AbbrevMap(); - + private boolean prettySyntax = DEFAULT_PRETTY_SYNTAX; - + private boolean unicodeEnabled = DEFAULT_UNICODE_ENABLED; - + private boolean hidePackagePrefix = DEFAULT_HIDE_PACKAGE_PREFIX; - + //------------------------------------------------------------------------- //constructors //------------------------------------------------------------------------- @@ -166,21 +160,21 @@ public final class NotationInfo { public NotationInfo() { this.notationTable = createDefaultNotation(); } - - - + + + //------------------------------------------------------------------------- //internal methods //------------------------------------------------------------------------- - - + + /** Register the standard set of notations (that can be defined without * a services object). */ private HashMap createDefaultNotation() { HashMap tbl = new LinkedHashMap(50); - + tbl.put(Junctor.TRUE ,new Notation.Constant("true", PRIORITY_ATOM)); tbl.put(Junctor.FALSE,new Notation.Constant("false", PRIORITY_ATOM)); tbl.put(Junctor.NOT,new Notation.Prefix("!" ,PRIORITY_NEGATION,PRIORITY_NEGATION)); @@ -200,34 +194,66 @@ private HashMap createDefaultNotation() { tbl.put(IfExThenElse.IF_EX_THEN_ELSE, new Notation.IfThenElse(PRIORITY_ATOM, "\\ifEx")); tbl.put(WarySubstOp.SUBST,new Notation.Subst()); tbl.put(UpdateApplication.UPDATE_APPLICATION, new Notation.UpdateApplicationNotation()); - tbl.put(UpdateJunctor.PARALLEL_UPDATE, new Notation.ParallelUpdateNotation()); - - tbl.put(Function.class, new Notation.FunctionNotation()); + tbl.put(UpdateJunctor.PARALLEL_UPDATE, new Notation.ParallelUpdateNotation()); + + tbl.put(Function.class, new Notation.FunctionNotation()); tbl.put(LogicVariable.class, new Notation.VariableNotation()); tbl.put(LocationVariable.class, new Notation.VariableNotation()); tbl.put(ProgramConstant.class, new Notation.VariableNotation()); - tbl.put(Equality.class, new Notation.Infix("=", PRIORITY_EQUAL, PRIORITY_COMPARISON, PRIORITY_COMPARISON)); + tbl.put(Equality.class, new Notation.Infix("=", PRIORITY_EQUAL, PRIORITY_COMPARISON, PRIORITY_COMPARISON)); tbl.put(ElementaryUpdate.class, new Notation.ElementaryUpdateNotation()); tbl.put(ModalOperatorSV.class, new Notation.ModalSVNotation(PRIORITY_MODALITY, PRIORITY_MODALITY)); tbl.put(SchemaVariable.class, new Notation.SchemaVariableNotation()); - + tbl.put(Sort.CAST_NAME, new Notation.CastFunction("(",")",PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(TermLabel.class, new Notation.LabelNotation("<<", ">>", PRIORITY_LABEL)); return tbl; } - - + + /** - * Adds notations that can only be defined when a services object is + * Adds notations that can only be defined when a services object is * available. */ - private HashMap createPrettyNotation(Services services) { + private Map createPrettyNotation(Services services) { + Map tbl = createDefaultNotation(); + for (LDT ldt : services.getTypeConverter().getLDTs()) { + var funcs = ldt.getFunctions(); + for (Operator op : funcs) { + if (op instanceof Function) { + var func = (Function) op; + var mixFitInfo = func.getMixFitInfo(); + if (mixFitInfo != null) { + final var symbol = mixFitInfo.getSymbol(); + switch (mixFitInfo.getKind()) { + case PREFIX: + tbl.put(op, new Notation.Prefix(symbol, + getPriorityPrefix(symbol), PRIORITY_ATOM)); + break; + case INFIX: + var args = getPriorityInfixArguments(symbol); + tbl.put(op, new Notation.Infix(symbol, getPriorityInfix(symbol), args, args)); + break; + case POSTFIX: + tbl.put(op, new Notation.Postfix(symbol)); + break; + } + } + } + } + } - HashMap tbl = createDefaultNotation(); - + var integerLDT = services.getTypeConverter().getIntegerLDT(); + var floatLDT = services.getTypeConverter().getFloatLDT(); + var doubleLDT = services.getTypeConverter().getDoubleLDT(); + tbl.put(integerLDT.getNumberSymbol(), new Notation.NumLiteral()); + tbl.put(integerLDT.getCharSymbol(), new Notation.CharLiteral()); + tbl.put(floatLDT.getFloatSymbol(), new Notation.FloatLiteral()); + tbl.put(doubleLDT.getDoubleSymbol(), new Notation.DoubleLiteral()); + + /* //arithmetic operators - final IntegerLDT integerLDT - = services.getTypeConverter().getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); tbl.put(integerLDT.getNumberSymbol(), new Notation.NumLiteral()); tbl.put(integerLDT.getCharSymbol(), new Notation.CharLiteral()); tbl.put(integerLDT.getLessThan(), new Notation.Infix("<", PRIORITY_COMPARISON, PRIORITY_ARITH_WEAK, PRIORITY_ARITH_WEAK)); @@ -267,57 +293,85 @@ private HashMap createPrettyNotation(Services services) { tbl.put(doubleLDT.getMul(), new Notation.Infix("*", PRIORITY_ARITH_STRONG, PRIORITY_ARITH_STRONG, PRIORITY_BELOW_ARITH_STRONG)); tbl.put(doubleLDT.getDiv(), new Notation.Infix("/", PRIORITY_ARITH_STRONG, PRIORITY_ARITH_STRONG, PRIORITY_BELOW_ARITH_STRONG)); tbl.put(doubleLDT.getNeg(),new Notation.Prefix("-", PRIORITY_BOTTOM, PRIORITY_ATOM)); + */ - - //heap operators - final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - tbl.put(HeapLDT.SELECT_NAME, new Notation.SelectNotation()); - tbl.put(heapLDT.getStore(), new Notation.StoreNotation()); + //heap operators + final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + tbl.put(HeapLDT.SELECT_NAME, new Notation.SelectNotation()); + tbl.put(heapLDT.getStore(), new Notation.StoreNotation()); tbl.put(heapLDT.getAnon(), new Notation.HeapConstructorNotation()); tbl.put(heapLDT.getCreate(), new Notation.HeapConstructorNotation()); tbl.put(heapLDT.getMemset(), new Notation.HeapConstructorNotation()); - tbl.put(IObserverFunction.class, new Notation.ObserverNotation()); - tbl.put(IProgramMethod.class, new Notation.ObserverNotation()); - tbl.put(heapLDT.getLength(), new Notation.Postfix(".length")); - - // sequence operators - final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); - tbl.put(seqLDT.getSeqLen(), new Notation.Postfix(".length")); - tbl.put(SeqLDT.SEQGET_NAME, new Notation.SeqGetNotation()); - tbl.put(seqLDT.getSeqConcat(), new Notation.SeqConcatNotation(seqLDT.getSeqConcat(), - seqLDT.getSeqSingleton(), integerLDT.getCharSymbol())); - - //set operators - final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); - tbl.put(setLDT.getSingleton(), new Notation.SingletonNotation()); - tbl.put(setLDT.getUnion(), new Notation.Infix("\\cup", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getIntersect(), new Notation.Infix("\\cap", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getSetMinus(), new Notation.Infix("\\setMinus", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); - tbl.put(setLDT.getElementOf(), new Notation.ElementOfNotation()); + tbl.put(IObserverFunction.class, new Notation.ObserverNotation()); + tbl.put(IProgramMethod.class, new Notation.ObserverNotation()); + tbl.put(heapLDT.getLength(), new Notation.Postfix(".length")); + + // sequence operators + final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); + tbl.put(seqLDT.getSeqLen(), new Notation.Postfix(".length")); + tbl.put(SeqLDT.SEQGET_NAME, new Notation.SeqGetNotation()); + /*tbl.put(seqLDT.getSeqConcat(), new Notation.SeqConcatNotation(seqLDT.getSeqConcat(), + seqLDT.getSeqSingleton(), integerLDT.getCharSymbol()));*/ + + //set operators + final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); + tbl.put(setLDT.getSingleton(), new Notation.SingletonNotation()); + tbl.put(setLDT.getUnion(), new Notation.Infix("\\cup", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getIntersect(), new Notation.Infix("\\cap", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getSetMinus(), new Notation.Infix("\\setMinus", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); + tbl.put(setLDT.getElementOf(), new Notation.ElementOfNotation()); tbl.put(setLDT.getSubset(), new Notation.Infix("\\subset", PRIORITY_ATOM, PRIORITY_TOP, PRIORITY_TOP)); tbl.put(setLDT.getEmpty(), new Notation.Constant("{}", PRIORITY_ATOM)); tbl.put(setLDT.getAllFields(), new Notation.Postfix(".*")); - - return tbl; + + return tbl; + } + + private int getPriorityPrefix(String symbol) { + return PRIORITY_BOTTOM; + } + + private int getPriorityInfixArguments(String symbol) { + return getPriorityInfix(symbol) + 1; + } + + private int getPriorityInfix(String symbol) { + char c = symbol.charAt(0); //first character determines over precedence + switch (c) { + case '<': + case '>': + return PRIORITY_COMPARISON; + case '=': + case '!': + return PRIORITY_EQUAL; + case '+': + case '-': + return PRIORITY_ARITH_WEAK; + case '*': + case '/': + case '%': + return PRIORITY_ARITH_STRONG; + default: + return PRIORITY_ATOM; + } } - + /** * Add notations with Unicode symbols. * @param services */ - private HashMap createUnicodeNotation(Services services){ - - HashMap tbl = createPrettyNotation(services); - - final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + private Map createUnicodeNotation(Services services){ + Map tbl = createPrettyNotation(services); + + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); - + tbl.put(integerLDT.getJavaCastByte(), new Notation.Prefix("(byte)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastShort(), new Notation.Prefix("(short)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastChar(), new Notation.Prefix("(char)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastInt(), new Notation.Prefix("(int)", PRIORITY_CAST, PRIORITY_BOTTOM)); tbl.put(integerLDT.getJavaCastLong(), new Notation.Prefix("(long)", PRIORITY_CAST, PRIORITY_BOTTOM)); - + // tbl.put(Junctor.TRUE ,new Notation.Constant(""+UnicodeHelper.TOP, PRIORITY_ATOM)); // tbl.put(Junctor.FALSE,new Notation.Constant(""+UnicodeHelper.BOT, PRIORITY_ATOM)); tbl.put(Junctor.NOT,new Notation.Prefix(""+UnicodeHelper.NEG ,PRIORITY_NEGATION,PRIORITY_NEGATION)); @@ -351,7 +405,7 @@ private HashMap createUnicodeNotation(Services services){ //------------------------------------------------------------------------- //public interface //------------------------------------------------------------------------- - + public void refresh(Services services) { refresh(services, DEFAULT_PRETTY_SYNTAX, DEFAULT_UNICODE_ENABLED); } @@ -372,11 +426,11 @@ public void refresh(Services services, boolean usePrettyPrinting, boolean useUni } hidePackagePrefix = DEFAULT_HIDE_PACKAGE_PREFIX; } - + public AbbrevMap getAbbrevMap(){ return scm; } - + public void setAbbrevMap(AbbrevMap am){ scm = am; @@ -385,8 +439,8 @@ public void setAbbrevMap(AbbrevMap am){ Notation getNotation(Class c) { return notationTable.get(c); } - - /** Get the Notation for a given Operator. + + /** Get the Notation for a given Operator. * If no notation is registered, a Function notation is returned. */ Notation getNotation(Operator op) { @@ -406,7 +460,7 @@ Notation getNotation(Operator op) { return result; } } - + if(op instanceof IProgramMethod) { result = notationTable.get(IProgramMethod.class); if(result != null) { diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index fbbc7c63632..cd58eefbf6b 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -73,10 +73,10 @@ double javaDivDoubleForbiddenResult(double, double); // Double arithmetic with IEEE 754 semantics - double addDouble(double, double); - double subDouble(double, double); - double mulDouble(double, double); - double divDouble(double, double); + double addDouble(double, double) \infix(+); + double subDouble(double, double) \infix(-); + double mulDouble(double, double) \infix(*); + double divDouble(double, double) \infix(/); double negDouble(double); double absDouble(double); diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index 95f5fbcf052..ea52de007ba 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -29,7 +29,7 @@ numbers 7 (numbers); numbers 8 (numbers); numbers 9 (numbers); - numbers neglit (numbers); + numbers neglit (numbers) \prefix(-); int Z (numbers); int C (numbers); diff --git a/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java b/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java index a8c3df9728e..c972f6c38b3 100644 --- a/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java +++ b/key/key.core/src/test/java/de/uka/ilkd/key/nparser/ExprTest.java @@ -2,6 +2,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.pp.LogicPrinter; import de.uka.ilkd.key.proof.init.JavaProfile; import de.uka.ilkd.key.util.parsing.BuildingException; import org.junit.jupiter.api.Assumptions; diff --git a/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt b/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt index ad24f7e2abf..88e431fff62 100644 --- a/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt +++ b/key/key.core/src/test/resources/de/uka/ilkd/key/nparser/exprs.txt @@ -1,3 +1,4 @@ +seqEmpty + seqEmpty (bprod{int y;}(1, 2, y) = 0) 1 = 1 -> 2 = 2 \< { int x = 1; } \> x=1 @@ -25,4 +26,3 @@ aa%bb*cc < -123 1.d + 1d <= 20e+1d * .01d 1f <= 2f 2d > 1d -seqEmpty + seqEmpty \ No newline at end of file From e59b436336721a06ee30c802902ecfe59150aff7 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 23:36:56 +0100 Subject: [PATCH 21/38] fix clash with <-> --- key/key.core/src/main/antlr4/KeYLexer.g4 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index f6f6f740cff..a2470b43376 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -330,12 +330,12 @@ RGUILLEMETS: '>' '>' ; WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; + +EQV: '<->' | '\u2194'; LESSEQUAL: '<' '=' | '\u2264'; -LESS: '<' OP_SFX?; LGUILLEMETS: '<' '<'; +LESS: '<' OP_SFX?; IMPLICIT_IDENT: '<' (LETTER)+ '>' ('$lmtd')? -> type(IDENT); - -EQV: '<->' | '\u2194'; PRIMES: ('\'')+; CHAR_LITERAL : '\'' From c5abd209e43df7ca15a7a98cd5a50e54572fc3d4 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 6 Feb 2022 23:45:12 +0100 Subject: [PATCH 22/38] minors --- .../key/nparser/builder/AbstractBuilder.java | 39 ++++++++++++------- .../nparser/builder/ExpressionBuilder.java | 9 ++--- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java index a9a134d0028..28423107d10 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java @@ -1,13 +1,13 @@ package de.uka.ilkd.key.nparser.builder; +import de.uka.ilkd.key.nparser.KeYParserBaseVisitor; import de.uka.ilkd.key.util.parsing.BuildingException; import de.uka.ilkd.key.util.parsing.BuildingIssue; -import de.uka.ilkd.key.nparser.KeYParserBaseVisitor; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; + import javax.annotation.Nonnull; import javax.annotation.Nullable; - import java.util.*; import java.util.stream.Collectors; @@ -28,22 +28,31 @@ abstract class AbstractBuilder extends KeYParserBaseVisitor { @Nullable private List buildingIssues = null; @Nullable - private Stack parameters = null; + private Deque parameters = null; /** - * Helper function for avoiding cast. + * Helper function for visiting the given context {@code ctx}, mainly for avoiding cast. * - * @param ctx - * @param - * @return + * @param ctx a (parser) rule context or null + * @param object to be cast to + * @return if the ctx is null, this method returns, otherwise the result of the visit method is returned */ - public @Nullable T accept(@Nullable RuleContext ctx) { + @Nullable + public T accept(@Nullable RuleContext ctx) { if (ctx == null) { return null; } return (T) ctx.accept(this); } + /** + * Like {@link #accept(RuleContext)} but throwing an exception on null value. + */ + @Nonnull + public T acceptnn(@Nullable RuleContext ctx) { + return Objects.requireNonNull(accept(ctx)); + } + @Override protected T aggregateResult(T aggregate, T nextResult) { if (nextResult != null) return nextResult; @@ -64,17 +73,18 @@ protected T acceptFirst(Collection seq) { } protected T pop() { - if(parameters==null) throw new IllegalStateException("Stack is empty"); + if (parameters == null) throw new IllegalStateException("Stack is empty"); return (T) parameters.pop(); } protected void push(Object... obj) { - if(parameters == null) parameters = new Stack<>(); + if (parameters == null) parameters = new ArrayDeque<>(); for (Object a : obj) parameters.push(a); } - protected @Nullable T accept(@Nullable RuleContext ctx, Object... args) { - if(parameters == null) parameters = new Stack<>(); + @Nullable + protected T accept(@Nullable RuleContext ctx, Object... args) { + if (parameters == null) parameters = new ArrayDeque<>(); int stackSize = parameters.size(); push(args); T t = accept(ctx); @@ -113,7 +123,8 @@ protected List mapMapOf(List... ctxss) { .collect(Collectors.toList()); } - public @Nonnull List getBuildingIssues() { + public @Nonnull + List getBuildingIssues() { if (buildingIssues == null) buildingIssues = new LinkedList<>(); return buildingIssues; } @@ -147,7 +158,7 @@ protected void semanticError(ParserRuleContext ctx, String format, Object... arg /** * Wraps an exception into a {@link BuildingException} * - * @param e + * @param e the cause of the generated and thrown exception */ protected void throwEx(Throwable e) { throw new BuildingException(e); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index ceb60c84412..1355352c62c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -323,7 +323,7 @@ private Term binaryLDTSpecificTerm(ParserRuleContext ctx, String opname, Term la @Override public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) { - Term termL = accept(ctx.a); + Term termL = acceptnn(ctx.a); if (ctx.b.isEmpty()) { return updateOrigin(termL, ctx); } @@ -338,11 +338,10 @@ public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) @Override public Object visitStrong_arith_term_2(KeYParser.Strong_arith_term_2Context ctx) { - Term termL = accept(ctx.a); + Term termL = acceptnn(ctx.a); if (ctx.b == null) return termL; Term termR = accept(ctx.b); - //String opName = ctx.SLASH() != null ? "div" : "mod"; return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); } @@ -358,9 +357,9 @@ protected Term capsulateTf(ParserRuleContext ctx, Supplier termSupplier) { public Object visitBracket_term(KeYParser.Bracket_termContext ctx) { Term t = accept(ctx.primitive_labeled_term()); for (int i = 0; i < ctx.bracket_suffix_heap().size(); i++) { - KeYParser.Brace_suffixContext brace_suffix = ctx.bracket_suffix_heap(i).brace_suffix(); + KeYParser.Brace_suffixContext braceSuffix = ctx.bracket_suffix_heap(i).brace_suffix(); ParserRuleContext heap = ctx.bracket_suffix_heap(i).heap; - t = accept(brace_suffix, t); + t = accept(braceSuffix, t); if (heap != null) { t = replaceHeap(t, accept(heap), heap); } From 241cd20d7eeb7caf5bd4446f1e5c43704c96986a Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 8 Feb 2022 16:37:56 +0100 Subject: [PATCH 23/38] fixes failing tests * do not use relational operator name map * fix priorities in lexer (/** is not an operator) * requests for prefix/postfix operators in LDT --- key/key.core/src/main/antlr4/KeYLexer.g4 | 2 +- key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java | 7 ++++++- .../de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java | 2 +- .../java/de/uka/ilkd/key/util/HelperClassForTests.java | 4 +++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index a2470b43376..bf4ed5dac5a 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -105,7 +105,7 @@ SL_COMMENT ; DOC_COMMENT: '/*!' -> more, pushMode(docComment); -ML_COMMENT: '/*' -> more, pushMode(COMMENT); +ML_COMMENT: '/*' OP_SFX? -> more, pushMode(COMMENT); SORTS:'\\sorts'; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index c50acdb6fca..bb94535ba7e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.TreeMap; +import de.uka.ilkd.key.logic.op.MixFitInfo; import org.key_project.util.ExtList; import de.uka.ilkd.key.java.Expression; @@ -263,12 +264,16 @@ public abstract Function getFunctionFor( * operation, null if not available */ public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { + return getFunctionFor(operatorSymbol, MixFitInfo.Kind.INFIX, services); + + } + public @Nullable Function getFunctionFor(String operatorSymbol, MixFitInfo.Kind kind, Services services) { for (Operator operator : functions.allElements()) { if(operator instanceof Function) { var op = (Function) operator; if (op.getMixFitInfo() != null) { var mfi = op.getMixFitInfo(); - if (mfi.symbol.equals(operatorSymbol)) { + if (kind == mfi.getKind() && mfi.symbol.equals(operatorSymbol)) { return op; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 1355352c62c..7acee0459e0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -243,7 +243,7 @@ public Object visitUnary_minus_term(KeYParser.Unary_minus_termContext ctx) { // falling back to integer ldt (for instance for untyped schema variables) ldt = services.getTypeConverter().getIntegerLDT(); } - Function op = ldt.getFunctionFor("neg", services); + Function op = ldt.getFunctionFor("-", MixFitInfo.Kind.PREFIX, services); if(op == null) { semanticError(ctx, "Could not find function symbol 'neg' for sort '%s'.", sort); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java b/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java index 31cd8ee7ebd..51ca6211b98 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/util/HelperClassForTests.java @@ -91,7 +91,9 @@ public ProofAggregate parse(File file, Profile profile) { result = pi.startProver(po, po); - } catch (Exception e) { + }catch (RuntimeException e) { + throw e; + } catch (ProofInputException e) { throw new RuntimeException(e); } return result; From 41c5fb6bda0faf435a58ec730c58645393ce482a Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:42:34 +0100 Subject: [PATCH 24/38] remove prefix from neglit --- .../resources/de/uka/ilkd/key/proof/rules/integerHeader.key | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key index ea52de007ba..95f5fbcf052 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/integerHeader.key @@ -29,7 +29,7 @@ numbers 7 (numbers); numbers 8 (numbers); numbers 9 (numbers); - numbers neglit (numbers) \prefix(-); + numbers neglit (numbers); int Z (numbers); int C (numbers); From b388f4564546a701142806e9e99190654b516b43 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:46:10 +0100 Subject: [PATCH 25/38] add prefix at negDouble --- .../main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key index cd58eefbf6b..6ef9237ed96 100644 --- a/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key +++ b/key/key.core/src/main/resources/de/uka/ilkd/key/proof/rules/floatHeader.key @@ -77,7 +77,7 @@ double subDouble(double, double) \infix(-); double mulDouble(double, double) \infix(*); double divDouble(double, double) \infix(/); - double negDouble(double); + double negDouble(double) \prefix(-); double absDouble(double); From 0f2788b4febcae3e7415f827248e7a07efff33f7 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 13 Feb 2022 15:54:27 +0100 Subject: [PATCH 26/38] fix tests, add whitepsaces --- .../src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java b/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java index 2e0941bb176..493fe4c40d9 100644 --- a/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java +++ b/key/key.core/src/test/java/de/uka/ilkd/key/parser/TestTacletParser.java @@ -216,7 +216,7 @@ public void testContraposition() { builder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(Sequent.EMPTY_SEQUENT, ImmutableSLList.nil(), - parseFma("!b0->!b"))); + parseFma("!b0 -> !b"))); builder.setName(new Name("contraposition")); Taclet contraposition = builder.getRewriteTaclet(); String contrapositionString = From dcdaf04878d2fbaa2b616a28b59f16f7d7ff481b Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 17 Apr 2022 14:48:30 +0200 Subject: [PATCH 27/38] fix merge --- .../src/main/java/de/uka/ilkd/key/java/TypeConverter.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java index b3da18302e5..5e2a962c173 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java @@ -124,10 +124,6 @@ public CharListLDT getCharListLDT() { return (CharListLDT) getLDT(CharListLDT.NAME); } - public Collection getLDTs() { - return LDTs.values(); - } - private Term translateOperator(de.uka.ilkd.key.java.expression.Operator op, ExecutionContext ec) { final Term[] subs = new Term[op.getArity()]; From 9188f0caa9fa0f4611a7747bd8316b341ae3e2a5 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sun, 17 Apr 2022 14:58:36 +0200 Subject: [PATCH 28/38] adts to KeY grammar --- key/key.core/src/main/antlr4/KeYLexer.g4 | 249 ++++++++++++++++++++-- key/key.core/src/main/antlr4/KeYParser.g4 | 36 +++- 2 files changed, 263 insertions(+), 22 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index bf4ed5dac5a..824f053df12 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -108,6 +108,7 @@ DOC_COMMENT: '/*!' -> more, pushMode(docComment); ML_COMMENT: '/*' OP_SFX? -> more, pushMode(COMMENT); +DATATYPES:'\\datatypes'; SORTS:'\\sorts'; GENERIC : '\\generic'; PROXY : '\\proxy'; @@ -273,23 +274,22 @@ CONTAINERTYPE : '\\containerType'; //BIGINT : '\\bigint'; // Unicode symbols for special functions/predicates -UTF_PRECEDES : '\u227A'; +/*UTF_PRECEDES : '\u227A'; UTF_IN : '\u220A'; UTF_EMPTY : '\u2205'; UTF_UNION : '\u222A'; UTF_INTERSECT : '\u2229'; UTF_SUBSET : '\u2286'; UTF_SETMINUS : '\u2216'; +*/ fragment VOCAB : '\u0003'..'\u0377' ; -fragment OP_SFX: ('-'|'='|'+'|'*'|'/'|'&'|'.'|'|'|'^'|'!'|':'|'>'|'<')+; SEMI: ';'; -SLASH: '/' OP_SFX?; COLON: ':'; DOUBLECOLON:'::'; ASSIGN: ':='; @@ -303,21 +303,242 @@ RBRACE: '}'; LBRACKET: '['; RBRACKET: ']'; EMPTYBRACKETS: '[' ']'; -AT: '@'; PARALLEL: '|' '|'; -OR: '|' | '\u2228'; -AND -: '&' | '\u2227' - ; -NOT: '!' | '\u00AC'; -IMP: '->' | '\u2192'; -EQUALS: '='; -NOT_EQUALS: '!=' | '\u2260'; +/* Trailing characters of a + */ +fragment OP_SFX: ('-'|'='|'+'|'*'|'/'|'&'|'.'|'|'|'^'|':'|'>'|'<')+; + +DOT_PLUS : '\u2214'; // ∔ +MINUS_OR_PLUS: '\u2213'; //∓ +SET_MINUS: '\u2216' | '\\setminus' ;// ∖ +ASTERISK: '\u2217';// ∗ +RING: '\u2218'; //∘ +CDOT: '\u2219';// ∙ +DIVIDES: '\u2223';// (8739) ∣ DIVIDES teilt +NOT_DIVIDES: '\u2224';// (8740) ∤ DOES NOT DIVIDE teilt nicht +PARALLEL_TO: '\u2225';//(8741) ∥ PARALLEL TO parallel zu +NOT_PARALLEL_TO: '\u2226' ;//(8742) ∦ NOT PARALLEL TO nicht parallel zu +INTERSECT: '\u2229' ;//(8745) ∩ INTERSECTION Schnittmengenzeichen +UNION: '\u222A' ;//(8746) ∪ UNION Vereinigungsmengenzeichen +THEREFORE: '\u2234' ;//(8756) ∴ THEREFORE folglich +BECAUSE: '\u2235' ;//(8757) ∵ BECAUSE weil +RATION: '\u2236' ;//(8758) ∶ RATIO Verhältniszeichen +PROPORTION: '\u2237' ;//(8759) ∷ PROPORTION Proportionszeichen +DOT_MINUS: '\u2238' ;//(8760) ∸ DOT MINUS Minuszeichen mit Punkt +EXCESS: '\u2239' ;//(8761) ∹ EXCESS Exzess +GEOMETRIC_PROPORTION: '\u223A' ;//(8762) ∺ GEOMETRIC PROPORTION geometrische Proportion +HOMOTHETIC: '\u223B' ;//(8763) ∻ HOMOTHETIC Homothetiezeichen +REVERSE_TILDE: '\u223D' ;//(8765) ∽ REVERSED TILDE umgekehrte Tilde +INVERTED_LAZY_S: '\u223E' ;//(8766) ∾ INVERTED LAZY S invertiertes stummes S +SINE_WAVE: '\u223F' ;//(8767) ∿ SINE WAVE Sinuswelle +WREATH_PRODUCT: '\u2240' ;//(8768) ≀ WREATH PRODUCT Kranzprodukt +NOT_TILDE:'\u2241' ;//(8769) ≁ NOT TILDE durchgestrichene Tilde +MINUS_TILDE: '\u2242' ;//(8770) ≂ MINUS TILDE Minus über Tilde +ASYMP_EQUAL: '\u2243' ;// (8771) ≃ ASYMPTOTICALLY EQUAL TO asymptotisch gleich +NOT_ASYMP_EQUAL: '\u2244' ;// (8772) ≄ NOT ASYMPTOTICALLY EQUAL TO nicht asymptotisch gleich +/* +'\u2245' ;// (8773) ≅ APPROXIMATELY EQUAL TO ungefähr gleich +'\u2246' ;// (8774) ≆ APPROXIMATELY BUT NOT ACTUALLY EQUAL TO ungefähr, aber nicht genau gleich +'\u2247' ;// (8775) ≇ NEITHER APPROXIMATELY NOR ACTUALLY EQUAL TO weder ungefähr noch genau gleich +'\u2248' ;// (8776) ≈ ALMOST EQUAL TO fast gleich +'\u2249' ;// (8777) ≉ NOT ALMOST EQUAL TO nicht fast gleich +'\u224A' ;// (8778) ≊ ALMOST EQUAL OR EQUAL TO fast gleich oder gleich +'\u224B' ;// (8779) ≋ TRIPLE TILDE dreifache Tilde +'\u224C' ;// (8780) ≌ ALL EQUAL TO alles Gleich +'\u224D' ;// (8781) ≍ EQUIVALENT TO äquivalent +'\u224E' ;// (8782) ≎ GEOMETRICALLY EQUIVALENT TO geometrisch äquivalent +'\u224F' ;// (8783) ≏ DIFFERENCE BETWEEN Differenz zwischen +'\u2250' ;// (8784) ≐ APPROACHES THE LIMIT Grenzwertannäherung +'\u2251' ;// (8785) ≑ GEOMETRICALLY EQUAL TO geometrisch gleich +'\u2252' ;// (8786) ≒ APPROXIMATELY EQUAL TO OR THE IMAGE OF ungefähr gleich oder Bild von +'\u2253' ;// (8787) ≓ IMAGE OF OR APPROXIMATELY EQUAL TO Bild oder ungefähr gleich +'\u2254' ;// (8788) ≔ COLON EQUALS Gleichheitszeichen mit vorangestelltem Doppelpunkt' ;// (Definitionszeichen) +'\u2255' ;// (8789) ≕ EQUALS COLON Gleichheitszeichen mit nachfolgendem Doppelpunkt +'\u2256' ;// (8790) ≖ RING IN EQUAL TO Kreis im Gleichheitszeichen +'\u2257' ;// (8791) ≗ RING EQUAL TO Kreis über Gleichheitszeichen' ;// (ungefähr gleich) +'\u2258' ;// (8792) ≘ CORRESPONDS TO Entspricht-Zeichen' ;// (unüblich) +'\u2259' ;// (8793) ≙ ESTIMATES entspricht +'\u225A' ;// (8794) ≚ EQUIANGULAR TO gleichwinklig +'\u225B' ;// (8795) ≛ STAR EQUALS Gleichheitszeichen mit Stern +'\u225C' ;// (8796) ≜ DELTA EQUAL TO Gleichheitszeichen mit Delta +'\u225D' ;// (8797) ≝ EQUAL TO BY DEFINITION gleich nach Definition +'\u225E' ;// (8798) ≞ MEASURED BY gemessen nach +'\u225F' ;// (8799) ≟ QUESTIONED EQUAL TO vielleicht gleich +'\u2260' ;// (8800) ≠ NOT EQUAL TO Ungleichheitszeichen +'\u2261' ;// (8801) ≡ IDENTICAL TO ist kongruent zu +'\u2262' ;// (8802) ≢ NOT IDENTICAL TO ist nicht kongruent zu +'\u2263' ;// (8803) ≣ STRICTLY EQUIVALENT TO genau äquivalent +'\u2264' ;// (8804) ≤ LESS-THAN OR EQUAL TO kleiner/gleich +'\u2265' ;// (8805) ≥ GREATER-THAN OR EQUAL TO größer/gleich +'\u2266' ;// (8806) ≦ LESS-THAN OVER EQUAL TO kleiner als über gleich +'\u2267' ;// (8807) ≧ GREATER-THAN OVER EQUAL TO größer als über gleich +'\u2268' ;// (8808) ≨ LESS-THAN BUT NOT EQUAL TO kleiner als, aber nicht gleich +'\u2269' ;// (8809) ≩ GREATER-THAN BUT NOT EQUAL TO größer als, aber nicht gleich +'\u226A' ;// (8810) ≪ MUCH LESS-THAN viel kleiner als +'\u226B' ;// (8811) ≫ MUCH GREATER-THAN viel größer als +'\u226C' ;// (8812) ≬ BETWEEN zwischen +'\u226D' ;// (8813) ≭ NOT EQUIVALENT TO nicht äquivalent +'\u226E' ;// (8814) ≮ NOT LESS-THAN ist nicht kleiner als +'\u226F' ;// (8815) ≯ NOT GREATER-THAN ist nicht größer als +'\u2270' ;// (8816) ≰ NEITHER LESS-THAN NOR EQUAL TO weder kleiner als noch gleich +'\u2271' ;// (8817) ≱ NEITHER GREATER-THAN NOR EQUAL TO weder größer als noch gleich +'\u2272' ;// (8818) ≲ LESS-THAN OR EQUIVALENT TO kleiner als oder äquivalent +'\u2273' ;// (8819) ≳ GREATER-THAN OR EQUIVALENT TO größer als oder äquivalent +'\u2274' ;// (8820) ≴ NEITHER LESS-THAN NOR EQUIVALENT TO weder kleiner als noch äquivalent +'\u2275' ;// (8821) ≵ NEITHER GREATER-THAN NOR EQUIVALENT TO weder größer als noch äquivalent +'\u2276' ;// (8822) ≶ LESS-THAN OR GREATER-THAN kleiner/größer als +'\u2277' ;// (8823) ≷ GREATER-THAN OR LESS-THAN größer/kleiner als +'\u2278' ;// (8824) ≸ NEITHER LESS-THAN NOR GREATER-THAN weder kleiner noch größer als +'\u2279' ;// (8825) ≹ NEITHER GREATER-THAN NOR LESS-THAN weder größer noch kleiner als +'\u227A' ;// (8826) ≺ PRECEDES vorangehend +'\u227B' ;// (8827) ≻ SUCCEEDS nachfolgend +'\u227C' ;// (8828) ≼ PRECEDES OR EQUAL TO vorangehend oder gleich +'\u227D' ;// (8829) ≽ SUCCEEDS OR EQUAL TO nachfolgend oder gleich +'\u227E' ;// (8830) ≾ PRECEDES OR EQUIVALENT TO vorangehend oder äquivalent +'\u227F' ;// (8831) ≿ SUCCEEDS OR EQUIVALENT TO nachfolgend oder äquivalent +'\u2280' ;// (8832) ⊀ DOES NOT PRECEDE nicht vorangehend +'\u2281' ;// (8833) ⊁ DOES NOT SUCCEED nicht nachfolgend +'\u2282' ;// (8834) ⊂ SUBSET OF ist ;// (echte) Teilmenge von +'\u2283' ;// (8835) ⊃ SUPERSET OF ist ;// (echte) Obermenge von +'\u2284' ;// (8836) ⊄ NOT A SUBSET OF ist keine ;// (echte) Teilmenge von +'\u2285' ;// (8837) ⊅ NOT A SUPERSET OF ist keine ;// (echte) Obermenge von +'\u2286' ;// (8838) ⊆ SUBSET OF OR EQUAL TO Teilmenge oder gleich +'\u2287' ;// (8839) ⊇ SUPERSET OF OR EQUAL TO Obermenge oder gleich +'\u2288' ;// (8840) ⊈ NEITHER A SUBSET OF NOR EQUAL TO weder Teilmenge noch gleich +'\u2289' ;// (8841) ⊉ NEITHER A SUPERSET OF NOR EQUAL TO weder Obermenge noch gleich +'\u228A' ;// (8842) ⊊ SUBSET OF WITH NOT EQUAL TO Teilmenge mit ungleich +'\u228B' ;// (8843) ⊋ SUPERSET OF WITH NOT EQUAL TO Obermenge mit ungleich +'\u228C' ;// (8844) ⊌ MULTISET Multimenge +'\u228D' ;// (8845) ⊍ MULTISET MULTIPLICATION Multimengenmultiplikation +'\u228E' ;// (8846) ⊎ MULTISET UNION Multimengenvereinigung +'\u228F' ;// (8847) ⊏ SQUARE IMAGE OF viereckiges Bild +'\u2290' ;// (8848) ⊐ SQUARE ORIGINAL OF viereckiges Original +'\u2291' ;// (8849) ⊑ SQUARE IMAGE OF OR EQUAL TO viereckiges Bild oder gleich +'\u2292' ;// (8850) ⊒ SQUARE ORIGINAL OF OR EQUAL TO viereckiges Original oder gleich +'\u2293' ;// (8851) ⊓ SQUARE CAP nach unten geöffnetes Viereck +'\u2294' ;// (8852) ⊔ SQUARE CUP nach oben geöffnetes Viereck +'\u2295' ;// (8853) ⊕ CIRCLED PLUS eingekreistes Pluszeichen +'\u2296' ;// (8854) ⊖ CIRCLED MINUS eingekreistes Minuszeichen +'\u2297' ;// (8855) ⊗ CIRCLED TIMES eingekreistes Multiplikationszeichen +'\u2298' ;// (8856) ⊘ CIRCLED DIVISION SLASH eingekreister Divisionsstrich +'\u2299' ;// (8857) ⊙ CIRCLED DOT OPERATOR eingekreister Punktoperator +'\u229A' ;// (8858) ⊚ CIRCLED RING OPERATOR eingekreister Ringoperator +'\u229B' ;// (8859) ⊛ CIRCLED ASTERISK OPERATOR eingekreister Sternoperator +'\u229C' ;// (8860) ⊜ CIRCLED EQUALS eingekreistes Gleichheitszeichen +'\u229D' ;// (8861) ⊝ CIRCLED DASH eingekreister Gedankenstrich +'\u229E' ;// (8862) ⊞ SQUARED PLUS eingerahmtes Pluszeichen +'\u229F' ;// (8863) ⊟ SQUARED MINUS eingerahmtes Minuszeichen +'\u22A0' ;// (8864) ⊠ SQUARED TIMES eingerahmtes Multiplikationszeichen +'\u22A1' ;// (8865) ⊡ SQUARED DOT OPERATOR eingerahmter Punktoperator +'\u22A2' ;// (8866) ⊢ RIGHT TACK ergibt +'\u22A3' ;// (8867) ⊣ LEFT TACK ergibt nicht +'\u22A4' ;// (8868) ⊤ DOWN TACK senkrecht von +'\u22A5' ;// (8869) ⊥ UP TACK senkrecht auf +'\u22A6' ;// (8870) ⊦ ASSERTION Assertion +'\u22A7' ;// (8871) ⊧ MODELS Modelle +'\u22A8' ;// (8872) ⊨ TRUE wahr +'\u22A9' ;// (8873) ⊩ FORCES erzwingen +'\u22AA' ;// (8874) ⊪ TRIPLE VERTICAL BAR RIGHT TURNSTILE dreifache vertikale Leiste mit rechtem Drehkreuz +'\u22AB' ;// (8875) ⊫ DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE doppelte vertikale Leiste mit doppeltem rechtem Drehkreuz +'\u22AC' ;// (8876) ⊬ DOES NOT PROVE beweist nicht +'\u22AD' ;// (8877) ⊭ NOT TRUE nicht wahr +'\u22AE' ;// (8878) ⊮ DOES NOT FORCE nicht erzwingen +'\u22AF' ;// (8879) ⊯ NEGATED DOUBLE VERTICAL BAR DOUBLE RIGHT TURNSTILE negierte doppelte vertikale Leiste mit doppeltem rechten Drehkreuz +'\u22B0' ;// (8880) ⊰ PRECEDES UNDER RELATION vorangehend in Relation +'\u22B1' ;// (8881) ⊱ SUCCEEDS UNDER RELATION nachfolgend in Relation +'\u22B2' ;// (8882) ⊲ NORMAL SUBGROUP OF normale Untergruppe +'\u22B3' ;// (8883) ⊳ CONTAINS AS NORMAL SUBGROUP als normale Untergruppe enthalten +'\u22B4' ;// (8884) ⊴ NORMAL SUBGROUP OF OR EQUAL TO normale Untergruppe oder gleich +'\u22B5' ;// (8885) ⊵ CONTAINS AS NORMAL SUBGROUP OR EQUAL TO als normale Untergruppe enthalten oder gleich +'\u22B6' ;// (8886) ⊶ ORIGINAL OF Original +'\u22B7' ;// (8887) ⊷ IMAGE OF Bild +'\u22B8' ;// (8888) ⊸ MULTIMAP Mehrfachzuordnung +'\u22B9' ;// (8889) ⊹ HERMITIAN CONJUGATE MATRIX hermitesch konjugierte Matrix +'\u22BA' ;// (8890) ⊺ INTERCALATE einschalten +'\u22BB' ;// (8891) ⊻ XOR Ausschließendes Oder +'\u22BC' ;// (8892) ⊼ NAND Nand-verknüpft mit +'\u22BD' ;// (8893) ⊽ NOR Nor +'\u22BE' ;// (8894) ⊾ RIGHT ANGLE WITH ARC rechter Winkel mit Bogen +'\u22BF' ;// (8895) ⊿ RIGHT TRIANGLE rechtes Dreieck +'\u22C0' ;// (8896) ⋀ N-ARY LOGICAL AND N-stufiges logisches Und +'\u22C1' ;// (8897) ⋁ N-ARY LOGICAL OR N-stufiges logisches Oder +'\u22C2' ;// (8898) ⋂ N-ARY INTERSECTION N-stufiger Durchschnitt +'\u22C3' ;// (8899) ⋃ N-ARY UNION N-stufige Vereinigung +'\u22C4' ;// (8900) ⋄ DIAMOND OPERATOR Rautenoperator +'\u22C5' ;// (8901) ⋅ DOT OPERATOR Multiplikationspunkt +'\u22C6' ;// (8902) ⋆ STAR OPERATOR Sternoperator +'\u22C7' ;// (8903) ⋇ DIVISION TIMES Divisionsanzahl +'\u22C8' ;// (8904) ⋈ BOWTIE Schleife +'\u22C9' ;// (8905) ⋉ LEFT NORMAL FACTOR SEMIDIRECT PRODUCT linkes halbdirektes Produkt' ;// (Normalfaktor) +'\u22CA' ;// (8906) ⋊ RIGHT NORMAL FACTOR SEMIDIRECT PRODUCT rechtes halbdirektes Produkt' ;// (Normalfaktor) +'\u22CB' ;// (8907) ⋋ LEFT SEMIDIRECT PRODUCT linkes halbdirektes Produkt +'\u22CC' ;// (8908) ⋌ RIGHT SEMIDIRECT PRODUCT rechtes halbdirektes Produkt +'\u22CD' ;// (8909) ⋍ REVERSED TILDE EQUALS umgekehrte Tilde gleich +'\u22CE' ;// (8910) ⋎ CURLY LOGICAL OR geschweiftes logisches Oder +'\u22CF' ;// (8911) ⋏ CURLY LOGICAL AND geschweiftes logisches Und +'\u22D0' ;// (8912) ⋐ DOUBLE SUBSET doppelte Teilmenge +'\u22D1' ;// (8913) ⋑ DOUBLE SUPERSET doppelte Obermenge +'\u22D2' ;// (8914) ⋒ DOUBLE INTERSECTION doppelter Durchschnitt +'\u22D3' ;// (8915) ⋓ DOUBLE UNION doppelte Vereinigung +'\u22D4' ;// (8916) ⋔ PITCHFORK echter Durchschnitt +'\u22D5' ;// (8917) ⋕ EQUAL AND PARALLEL TO gleich und parallel ;// (ähnlich dem Doppelkreuz) +'\u22D6' ;// (8918) ⋖ LESS-THAN WITH DOT kleiner als mit Punkt +'\u22D7' ;// (8919) ⋗ GREATER-THAN WITH DOT größer als mit Punkt +'\u22D8' ;// (8920) ⋘ VERY MUCH LESS-THAN Sehr viel kleiner als +'\u22D9' ;// (8921) ⋙ VERY MUCH GREATER-THAN sehr viel größer als +'\u22DA' ;// (8922) ⋚ LESS-THAN EQUAL TO OR GREATER-THAN kleiner als, gleich oder größer als +'\u22DB' ;// (8923) ⋛ GREATER-THAN EQUAL TO OR LESS-THAN größer als, gleich oder kleiner als +'\u22DC' ;// (8924) ⋜ EQUAL TO OR LESS-THAN gleich oder kleiner als +'\u22DD' ;// (8925) ⋝ EQUAL TO OR GREATER-THAN gleich oder größer als +'\u22DE' ;// (8926) ⋞ EQUAL TO OR PRECEDES gleich oder vorangehend +'\u22DF' ;// (8927) ⋟ EQUAL TO OR SUCCEEDS gleich oder nachfolgend +'\u22E0' ;// (8928) ⋠ DOES NOT PRECEDE OR EQUAL weder vorangehend oder gleich +'\u22E1' ;// (8929) ⋡ DOES NOT SUCCEED OR EQUAL weder nachfolgend oder gleich +'\u22E2' ;// (8930) ⋢ NOT SQUARE IMAGE OF OR EQUAL TO kein viereckiges Bild oder gleich +'\u22E3' ;// (8931) ⋣ NOT SQUARE ORIGINAL OF OR EQUAL TO kein viereckiges Original oder gleich +'\u22E4' ;// (8932) ⋤ SQUARE IMAGE OF OR NOT EQUAL TO viereckiges Bild oder ungleich +'\u22E5' ;// (8933) ⋥ SQUARE ORIGINAL OF OR NOT EQUAL TO viereckiges Original oder ungleich +'\u22E6' ;// (8934) ⋦ LESS-THAN BUT NOT EQUIVALENT TO kleiner als, aber nicht äquivalent +'\u22E7' ;// (8935) ⋧ GREATER-THAN BUT NOT EQUIVALENT TO größer als, aber nicht äquivalent +'\u22E8' ;// (8936) ⋨ PRECEDES BUT NOT EQUIVALENT TO vorangehend, aber nicht äquivalent +'\u22E9' ;// (8937) ⋩ SUCCEEDS BUT NOT EQUIVALENT TO nachfolgend, aber nicht äquivalent +'\u22EA' ;// (8938) ⋪ NOT NORMAL SUBGROUP OF keine normale Untergruppe +'\u22EB' ;// (8939) ⋫ DOES NOT CONTAIN AS NORMAL SUBGROUP nicht als normale Untergruppe enthalten +'\u22EC' ;// (8940) ⋬ NOT NORMAL SUBGROUP OF OR EQUAL TO keine normale Untergruppe oder gleich +'\u22ED' ;// (8941) ⋭ DOES NOT CONTAIN AS NORMAL SUBGROUP OR EQUAL nicht als normale Untergruppe enthalten oder gleich +'\u22EE' ;// (8942) ⋮ VERTICAL ELLIPSIS Vertikale Ellipse +'\u22EF' ;// (8943) ⋯ MIDLINE HORIZONTAL ELLIPSIS Zentrierte horizontale Ellipse +'\u22F0' ;// (8944) ⋰ UP RIGHT DIAGONAL ELLIPSIS Diagonale Ellipse, unten links nach oben rechts +'\u22F1' ;// (8945) ⋱ DOWN RIGHT DIAGONAL ELLIPSIS Diagonale Ellipse, oben links nach unten rechts +'\u22F2' ;// (8946) ⋲ ELEMENT OF WITH LONG HORIZONTAL STROKE Element mit langem horizontalen Strich +'\u22F3' ;// (8947) ⋳ ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE Element mit vertikalem Strich am Ende des horizontalen Strichs +'\u22F4' ;// (8948) ⋴ SMALL ELEMENT OF WITH VERTICAL BAR AT END OF HORIZONTAL STROKE kleines Element mit vertikalem Strich am Ende des horizontalen Strichs +'\u22F5' ;// (8949) ⋵ ELEMENT OF WITH DOT ABOVE Element mit Punkt ;// (oben) +'\u22F6' ;// (8950) ⋶ ELEMENT OF WITH OVERBAR Element mit Überstrich +'\u22F7' ;// (8951) ⋷ SMALL ELEMENT OF WITH OVERBAR kleines Element mit Überstrich +'\u22F8' ;// (8952) ⋸ ELEMENT OF WITH UNDERBAR Element mit Unterstrich +'\u22F9' ;// (8953) ⋹ ELEMENT OF WITH TWO HORIZONTAL STROKES Element mit 2 horizontalen Strichen +'\u22FA' ;// (8954) ⋺ CONTAINS WITH LONG HORIZONTAL STROKE umgekehrtes Elementzeichen mit langem horizontalen Strich +'\u22FB' ;// (8955) ⋻ CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE umgekehrtes Elementzeichen mit vertikalem Strich am Ende des horizontalen Strichs +'\u22FC' ;// (8956) ⋼ SMALL CONTAINS WITH VERTICAL BAR AT END OF HORIZONTAL STROKE kleines umgekehrtes Elementzeichen mit vertikalem Strich am Ende des horizontalen Strichs +'\u22FD' ;// (8957) ⋽ CONTAINS WITH OVERBAR umgekehrtes Elementzeichen mit Überstrich +'\u22FE' ;// (8958) ⋾ SMALL CONTAINS WITH OVERBAR kleines umgekehrtes Elementzeichen mit Überstrich +'\u22FF' ;// (8959) ⋿ Z NOTATION BAG MEMBERSHIP +*/ + SEQARROW: '==>' | '\u27F9'; +NOT_EQUALS: '!=' OP_SFX? | '\u2260'; +IMP: '->' | '\u2192'; +SLASH: '/' OP_SFX?; +AT: '@' OP_SFX?; +OR: '|' OP_SFX? | '\u2228'; +AND: '&' OP_SFX? | '\u2227'; +NOT: '!' (OP_SFX|'!')? | '\u00AC'; +EQUALS: '=' OP_SFX?; EXP: '^' OP_SFX?; -TILDE: '~' OP_SFX?; +TILDE: ('~'|'\u223C') OP_SFX?; PERCENT: '%' OP_SFX?; STAR : '*' OP_SFX?; MINUS: '-' OP_SFX?; @@ -328,7 +549,7 @@ RGUILLEMETS: '>' '>' ; -WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //U+00A0 = non breakable whitespace +WS: [ \t\n\r\u00a0]+ -> channel(HIDDEN); //'\u00A0 = non breakable whitespace STRING_LITERAL:'"' ('\\' . | ~( '"' | '\\') )* '"' ; EQV: '<->' | '\u2194'; diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 76f79b4e54d..69dd7203510 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -46,6 +46,7 @@ decls | schema_var_decls | pred_decls | func_decls + | adt_decls | transform_decls | ruleset_decls | contracts // for problems @@ -251,6 +252,25 @@ func_decl SEMI ; +/** + \datatypes { + List = Nil | Cons(any, List); + } + */ +adt_decl +: + doc=DOC_COMMENT? (UNIQUE)? + name=funcpred_name + EQUAL + adt_constructor (OR adt_constructor)* +; + +adt_constructor +: + doc=DOC_COMMENT? funcpred_name #adt_constructor_base + | doc=DOC_COMMENT? funcpred_name LPAREN sortId (COMMA sortId)* RPAREN #adt_constructor_recursion +; + functionMetaData : INFIX LPAREN op=(PLUS|STAR|SLASH|MINUS|EXP|PERCENT|LESS|LESSEQUAL|GREATER|GREATEREQUAL|LGUILLEMETS) RPAREN @@ -260,14 +280,14 @@ functionMetaData ; func_decls - : - FUNCTIONS - LBRACE - ( - func_decl - ) * - RBRACE - ; +: + FUNCTIONS LBRACE (func_decl)* RBRACE +; + +adt_decls +: + DATATYPES LBRACE adt_decl* RBRACE +; // like arg_sorts but admits also the keyword "\formula" From 097994af75d3bdaec650cdc92a122c60dd6b7724 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 26 Apr 2022 21:08:22 +0200 Subject: [PATCH 29/38] wip --- key/key.core/src/main/antlr4/KeYParser.g4 | 3 ++- key/test/Test.java | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 69dd7203510..2bc635bf2d7 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -261,8 +261,9 @@ adt_decl : doc=DOC_COMMENT? (UNIQUE)? name=funcpred_name - EQUAL + EQUALS adt_constructor (OR adt_constructor)* + SEMI ; adt_constructor diff --git a/key/test/Test.java b/key/test/Test.java index b3c58d9f9ac..1b2bf229a81 100644 --- a/key/test/Test.java +++ b/key/test/Test.java @@ -1,3 +1,14 @@ class Test { - //@ public instance ghost \dl_int keyInt =0; -} \ No newline at end of file + + /*@ + requires ary.length > 0; + ensures \result == + (\sum int i; pos <= i < ary.length; ary[i]); + measured_by ary.length - pos; + */ + public int sum(int[] ary, int pos) { + if( pos < 0 || pos >= ary.length) + return 0; + return ary[pos] + sum(ary,pos+1); + } +} From 62c5c50a09ba19031f6746621a58084968b42a09 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 7 Feb 2023 21:40:51 +0100 Subject: [PATCH 30/38] spotless apply --- .../src/main/java/org/key_project/Main.java | 196 +- .../proof_references/ProofReferenceUtil.java | 358 +- ...iomAndInvariantProofReferencesAnalyst.java | 160 +- .../ContractProofReferencesAnalyst.java | 39 +- .../analyst/IProofReferencesAnalyst.java | 30 +- ...ethodBodyExpandProofReferencesAnalyst.java | 50 +- .../MethodCallProofReferencesAnalyst.java | 190 +- .../ProgramVariableReferencesAnalyst.java | 131 +- .../reference/DefaultProofReference.java | 265 +- .../reference/IProofReference.java | 198 +- .../AbstractProofReferenceTestCase.java | 802 +- .../testcase/TestKeYTypeUtil.java | 306 +- .../testcase/TestProofReferenceUtil.java | 215 +- ...iomAndInvariantProofReferencesAnalyst.java | 75 +- .../TestContractProofReferencesAnalyst.java | 28 +- ...ethodBodyExpandProofReferencesAnalyst.java | 33 +- .../TestMethodCallProofReferencesAnalyst.java | 282 +- .../TestProgramVariableReferencesAnalyst.java | 1716 ++-- .../java/org/key_project/example/Main.java | 261 +- ...torKeepUpdatesForBreakpointconditions.java | 72 +- .../BlockContractValidityTermLabelUpdate.java | 82 +- .../rule/label/FormulaTermLabelMerger.java | 62 +- .../label/FormulaTermLabelRefactoring.java | 752 +- .../rule/label/FormulaTermLabelUpdate.java | 172 +- .../rule/label/LoopBodyTermLabelUpdate.java | 66 +- ...nvariantNormalBehaviorTermLabelUpdate.java | 62 +- ...veInCheckBranchesTermLabelRefactoring.java | 161 +- .../label/StayOnFormulaTermLabelPolicy.java | 294 +- .../SymbolicExecutionTermLabelUpdate.java | 91 +- .../strategy/IBreakpointStopCondition.java | 47 +- .../AbstractUpdateExtractor.java | 3519 +++---- .../symbolic_execution/AbstractWriter.java | 249 +- .../ExecutionNodePreorderIterator.java | 188 +- .../ExecutionNodeReader.java | 6225 +++++++------ .../ExecutionNodeSymbolicLayoutExtractor.java | 85 +- .../ExecutionNodeWriter.java | 2537 ++--- .../ExecutionVariableExtractor.java | 1409 +-- .../SymbolicExecutionTreeBuilder.java | 3408 +++---- .../SymbolicLayoutExtractor.java | 1692 ++-- .../SymbolicLayoutReader.java | 2117 ++--- .../SymbolicLayoutWriter.java | 532 +- .../TruthValueTracingUtil.java | 2623 +++--- .../model/IExecutionAuxiliaryContract.java | 47 +- .../model/IExecutionBaseMethodReturn.java | 79 +- .../model/IExecutionBlockStartNode.java | 29 +- .../model/IExecutionBranchCondition.java | 127 +- .../model/IExecutionBranchStatement.java | 15 +- .../model/IExecutionConstraint.java | 20 +- .../model/IExecutionElement.java | 154 +- .../IExecutionExceptionalMethodReturn.java | 10 +- .../model/IExecutionJoin.java | 30 +- .../model/IExecutionLink.java | 26 +- .../model/IExecutionLoopCondition.java | 35 +- .../model/IExecutionLoopInvariant.java | 47 +- .../model/IExecutionLoopStatement.java | 16 +- .../model/IExecutionMethodCall.java | 93 +- .../model/IExecutionMethodReturn.java | 70 +- .../model/IExecutionMethodReturnValue.java | 89 +- .../model/IExecutionNode.java | 361 +- .../model/IExecutionOperationContract.java | 203 +- .../model/IExecutionStart.java | 32 +- .../model/IExecutionStatement.java | 14 +- .../model/IExecutionTermination.java | 152 +- .../model/IExecutionValue.java | 218 +- .../model/IExecutionVariable.java | 123 +- .../model/ITreeSettings.java | 72 +- .../impl/AbstractExecutionBlockStartNode.java | 137 +- .../model/impl/AbstractExecutionElement.java | 317 +- .../impl/AbstractExecutionMethodReturn.java | 334 +- .../model/impl/AbstractExecutionNode.java | 1095 +-- .../model/impl/AbstractExecutionValue.java | 405 +- .../model/impl/AbstractExecutionVariable.java | 258 +- .../ExecutionAllArrayIndicesVariable.java | 322 +- .../impl/ExecutionAuxiliaryContract.java | 327 +- .../model/impl/ExecutionBranchCondition.java | 539 +- .../model/impl/ExecutionBranchStatement.java | 105 +- .../model/impl/ExecutionConstraint.java | 107 +- .../ExecutionExceptionalMethodReturn.java | 115 +- .../model/impl/ExecutionJoin.java | 106 +- .../model/impl/ExecutionLink.java | 69 +- .../model/impl/ExecutionLoopCondition.java | 112 +- .../model/impl/ExecutionLoopInvariant.java | 138 +- .../model/impl/ExecutionLoopStatement.java | 134 +- .../model/impl/ExecutionMethodCall.java | 285 +- .../model/impl/ExecutionMethodReturn.java | 681 +- .../impl/ExecutionMethodReturnValue.java | 292 +- .../impl/ExecutionOperationContract.java | 643 +- .../model/impl/ExecutionStart.java | 169 +- .../model/impl/ExecutionStatement.java | 72 +- .../model/impl/ExecutionTermination.java | 277 +- .../model/impl/ExecutionValue.java | 400 +- .../model/impl/ExecutionVariable.java | 635 +- .../model/impl/TreeSettings.java | 171 +- .../object_model/IModelSettings.java | 43 +- .../object_model/ISymbolicAssociation.java | 151 +- .../ISymbolicAssociationValueContainer.java | 91 +- .../object_model/ISymbolicElement.java | 20 +- .../ISymbolicEquivalenceClass.java | 75 +- .../object_model/ISymbolicLayout.java | 51 +- .../object_model/ISymbolicObject.java | 56 +- .../object_model/ISymbolicState.java | 17 +- .../object_model/ISymbolicValue.java | 196 +- .../object_model/impl/AbstractElement.java | 66 +- ...ractSymbolicAssociationValueContainer.java | 172 +- .../object_model/impl/ModelSettings.java | 111 +- .../impl/SymbolicAssociation.java | 506 +- .../impl/SymbolicEquivalenceClass.java | 217 +- .../object_model/impl/SymbolicLayout.java | 131 +- .../object_model/impl/SymbolicObject.java | 122 +- .../object_model/impl/SymbolicState.java | 50 +- .../object_model/impl/SymbolicValue.java | 540 +- .../po/ProgramMethodPO.java | 620 +- .../po/ProgramMethodSubsetPO.java | 664 +- .../po/TruthValuePOExtension.java | 118 +- .../profile/SimplifyTermProfile.java | 187 +- .../profile/SymbolicExecutionJavaProfile.java | 520 +- ...tionJavaProfileDefaultProfileResolver.java | 35 +- .../rule/AbstractSideProofRule.java | 200 +- .../rule/ModalitySideProofRule.java | 374 +- .../rule/QuerySideProofRule.java | 472 +- .../slicing/AbstractBackwardSlicer.java | 314 +- .../slicing/AbstractSlicer.java | 1954 ++-- .../symbolic_execution/slicing/Access.java | 201 +- .../symbolic_execution/slicing/Location.java | 278 +- .../slicing/ThinBackwardSlicer.java | 140 +- .../AbstractCallStackBasedStopCondition.java | 354 +- .../strategy/BreakpointStopCondition.java | 227 +- .../strategy/CompoundStopCondition.java | 235 +- .../strategy/CutHeapObjectsFeature.java | 96 +- .../strategy/CutHeapObjectsTermGenerator.java | 164 +- ...mbolicExecutionTreeNodesStopCondition.java | 502 +- .../strategy/SimplifyTermStrategy.java | 161 +- ...mbolicExecutionTreeNodesStopCondition.java | 51 +- ...mbolicExecutionTreeNodesStopCondition.java | 50 +- ...bolicExecutionBreakpointStopCondition.java | 202 +- .../SymbolicExecutionGoalChooser.java | 282 +- .../SymbolicExecutionGoalChooserBuilder.java | 59 +- .../strategy/SymbolicExecutionStrategy.java | 538 +- .../breakpoint/AbstractBreakpoint.java | 105 +- .../AbstractConditionalBreakpoint.java | 983 +- .../AbstractHitCountBreakpoint.java | 164 +- .../breakpoint/ExceptionBreakpoint.java | 293 +- .../strategy/breakpoint/FieldWatchpoint.java | 225 +- .../strategy/breakpoint/IBreakpoint.java | 80 +- .../strategy/breakpoint/KeYWatchpoint.java | 225 +- .../strategy/breakpoint/LineBreakpoint.java | 341 +- .../strategy/breakpoint/MethodBreakpoint.java | 380 +- .../SymbolicExecutionExceptionBreakpoint.java | 379 +- .../symbolic_execution/util/DefaultEntry.java | 49 +- .../util/EqualsHashCodeResetter.java | 110 +- .../util/SideProofStore.java | 638 +- .../util/SymbolicExecutionEnvironment.java | 229 +- .../util/SymbolicExecutionSideProofUtil.java | 1573 ++-- .../util/SymbolicExecutionUtil.java | 8219 +++++++++-------- .../util/event/ISideProofStoreListener.java | 28 +- .../util/event/SideProofStoreEvent.java | 70 +- .../AbstractSymbolicExecutionTestCase.java | 4324 +++++---- .../testcase/TestConditionalVariables.java | 308 +- .../TestExecutionNodePreorderIterator.java | 562 +- .../TestExecutionNodeWriterAndReader.java | 460 +- .../TestExecutionVariableExtractor.java | 636 +- .../testcase/TestParallelSiteProofs.java | 465 +- .../TestSymbolicExecutionTreeBuilder.java | 7776 +++++----------- .../testcase/TestSymbolicLayoutExtractor.java | 1917 ++-- .../TestSymbolicLayoutWriterAndReader.java | 149 +- .../TestTruthValueEvaluationUtil.java | 2561 ++--- .../testcase/TestTruthValueValue.java | 435 +- .../po/TestFunctionalOperationContractPO.java | 94 +- .../testcase/po/TestProgramMethodPO.java | 77 +- .../po/TestProgramMethodSubsetPO.java | 171 +- .../slicing/TestThinBackwardSlicer.java | 1737 ++-- ...eakpointStopConditionCaughtOrUncaught.java | 118 +- ...onBreakpointStopConditionWithHitCount.java | 114 +- ...BreakpointStopConditionWithSubclasses.java | 128 +- ...vaWatchpointStopConditionWithHitCount.java | 146 +- ...atchpointGlobalVariablesOnSatisfiable.java | 118 +- ...ointGlobalVariablesOnTrueWithHitCount.java | 106 +- ...TestKeYWatchpointMethodsOnSatisfiable.java | 116 +- ...ointStopConditionSimpleWithConditions.java | 223 +- ...kpointStopConditionSimpleWithHitCount.java | 138 +- ...tStopConditionSimpleWithLoopInvariant.java | 125 +- .../TestMethodBreakpointWithConditions.java | 230 +- .../TestMethodBreakpointWithHitCount.java | 132 +- ...mbolicExecutionTreeNodesStopCondition.java | 122 +- ...mbolicExecutionTreeNodesStopCondition.java | 120 +- .../TestSymbolicExecutionStrategy.java | 1130 +-- .../testcase/util/TestDefaultEntry.java | 32 +- .../util/TestEqualsHashCodeResetter.java | 501 +- .../testcase/util/TestSideProofStore.java | 502 +- .../util/TestSymbolicExecutionUtil.java | 56 +- .../key/macros/SemanticsBlastingMacro.java | 317 +- .../de/uka/ilkd/key/macros/TestGenMacro.java | 248 +- .../key/settings/TestGenerationSettings.java | 99 +- .../AbstractCounterExampleGenerator.java | 224 +- ...tractSideProofCounterExampleGenerator.java | 37 +- .../smt/testgen/AbstractTestGenerator.java | 767 +- .../smt/testgen/MemoryTestGenerationLog.java | 85 +- .../uka/ilkd/key/smt/testgen/StopRequest.java | 5 +- .../key/smt/testgen/TestGenerationLog.java | 15 +- .../de/uka/ilkd/key/testgen/Assignment.java | 115 +- .../ilkd/key/testgen/CustomPrettyPrinter.java | 83 +- .../uka/ilkd/key/testgen/ModelGenerator.java | 52 +- .../de/uka/ilkd/key/testgen/ProofInfo.java | 16 +- .../java/de/uka/ilkd/key/testgen/RefEx.java | 52 +- .../key/testgen/ReflectionClassCreator.java | 196 +- .../ilkd/key/testgen/TestCaseGenerator.java | 367 +- .../testgen/oracle/ModifiesSetTranslator.java | 169 +- .../key/testgen/oracle/OracleBinTerm.java | 66 +- .../key/testgen/oracle/OracleConstant.java | 55 +- .../key/testgen/oracle/OracleGenerator.java | 115 +- .../oracle/OracleInvariantTranslator.java | 104 +- .../key/testgen/oracle/OracleLocation.java | 110 +- .../key/testgen/oracle/OracleLocationSet.java | 257 +- .../ilkd/key/testgen/oracle/OracleMethod.java | 14 +- .../key/testgen/oracle/OracleMethodCall.java | 73 +- .../ilkd/key/testgen/oracle/OracleTerm.java | 5 +- .../ilkd/key/testgen/oracle/OracleType.java | 29 +- .../key/testgen/oracle/OracleUnaryTerm.java | 84 +- .../key/testgen/oracle/OracleVariable.java | 111 +- .../util/HelperClassForTestgenTests.java | 3 + .../key/testcase/smt/ce/SMTTestSettings.java | 112 +- .../uka/ilkd/key/testcase/smt/ce/TestCE.java | 21 +- .../ilkd/key/testcase/smt/ce/TestCommons.java | 26 +- .../key/testcase/smt/testgen/TestTestgen.java | 27 +- .../rifl/DefaultSpecificationContainer.java | 167 +- .../uka/ilkd/key/util/rifl/RIFLHandler.java | 80 +- .../ilkd/key/util/rifl/RIFLTransformer.java | 71 +- .../ilkd/key/util/rifl/SecurityLattice.java | 80 +- .../util/rifl/SimpleRIFLExceptionHandler.java | 8 +- .../key/util/rifl/SpecificationContainer.java | 38 +- .../key/util/rifl/SpecificationEntity.java | 54 +- .../key/util/rifl/SpecificationInjector.java | 26 +- .../rifl/blueprint_rifl.key | 3 + key/key.core/src/main/antlr4/JmlLexer.g4 | 4 +- key/key.core/src/main/antlr4/JmlParser.g4 | 3 + key/key.core/src/main/antlr4/KeYLexer.g4 | 3 + key/key.core/src/main/antlr4/KeYParser.g4 | 3 + .../main/java/de/uka/ilkd/key/api/KeYApi.java | 38 +- .../java/de/uka/ilkd/key/api/Matcher.java | 48 +- .../de/uka/ilkd/key/api/ProjectedNode.java | 3 + .../java/de/uka/ilkd/key/api/ProofApi.java | 11 +- .../de/uka/ilkd/key/api/ProofMacroApi.java | 7 +- .../uka/ilkd/key/api/ProofManagementApi.java | 69 +- .../ilkd/key/api/ProofScriptCommandApi.java | 7 +- .../ilkd/key/api/ProofScriptCommandCall.java | 4 +- .../java/de/uka/ilkd/key/api/ScriptApi.java | 71 +- .../de/uka/ilkd/key/api/ScriptResult.java | 17 +- .../de/uka/ilkd/key/api/ScriptResults.java | 100 +- .../java/de/uka/ilkd/key/api/SearchNode.java | 9 +- .../uka/ilkd/key/api/VariableAssignments.java | 92 +- .../de/uka/ilkd/key/api/package-info.java | 2 +- .../AbstractDomainElement.java | 51 +- .../AbstractDomainLattice.java | 125 +- .../axiom_abstraction/PartialComparator.java | 61 +- .../boollattice/BooleanDomainElem.java | 61 +- .../boollattice/BooleanLattice.java | 28 +- .../axiom_abstraction/boollattice/Bottom.java | 32 +- .../axiom_abstraction/boollattice/False.java | 54 +- .../axiom_abstraction/boollattice/Top.java | 54 +- .../axiom_abstraction/boollattice/True.java | 54 +- ...ractPredicateAbstractionDomainElement.java | 61 +- .../AbstractPredicateAbstractionLattice.java | 70 +- .../AbstractionPredicate.java | 157 +- ...tivePredicateAbstractionDomainElement.java | 28 +- ...onjunctivePredicateAbstractionLattice.java | 93 +- ...tivePredicateAbstractionDomainElement.java | 28 +- ...isjunctivePredicateAbstractionLattice.java | 92 +- ...mplePredicateAbstractionDomainElement.java | 34 +- .../SimplePredicateAbstractionLattice.java | 70 +- .../signanalysis/Bottom.java | 72 +- .../axiom_abstraction/signanalysis/Geq.java | 54 +- .../axiom_abstraction/signanalysis/Leq.java | 54 +- .../axiom_abstraction/signanalysis/Neg.java | 54 +- .../axiom_abstraction/signanalysis/Pos.java | 54 +- .../signanalysis/SignAnalysisDomainElem.java | 103 +- .../signanalysis/SignAnalysisLattice.java | 267 +- .../axiom_abstraction/signanalysis/Top.java | 54 +- .../axiom_abstraction/signanalysis/Zero.java | 54 +- .../key/control/AbstractProofControl.java | 455 +- .../control/AbstractUserInterfaceControl.java | 201 +- .../ilkd/key/control/AutoModeListener.java | 11 +- .../ilkd/key/control/CompositePTListener.java | 19 +- .../ilkd/key/control/DefaultProofControl.java | 300 +- .../control/DefaultUserInterfaceControl.java | 304 +- .../key/control/InstantiationFileHandler.java | 276 +- .../ilkd/key/control/InteractionListener.java | 10 +- .../uka/ilkd/key/control/KeYEnvironment.java | 484 +- .../de/uka/ilkd/key/control/ProofControl.java | 299 +- .../key/control/RuleCompletionHandler.java | 44 +- .../control/TermLabelVisibilityManager.java | 27 +- .../key/control/UserInterfaceControl.java | 84 +- .../TermLabelVisibilityManagerEvent.java | 41 +- .../TermLabelVisibilityManagerListener.java | 15 +- .../TacletAssumesModel.java | 18 +- .../instantiation_model/TacletFindModel.java | 64 +- .../TacletInstantiationModel.java | 38 +- ...stractFinishAuxiliaryComputationMacro.java | 39 +- .../AuxiliaryComputationAutoPilotMacro.java | 55 +- .../macros/ExhaustiveProofMacro.java | 84 +- .../FinishAuxiliaryBlockComputationMacro.java | 41 +- .../FinishAuxiliaryComputationMacro.java | 9 +- .../FinishAuxiliaryLoopComputationMacro.java | 26 +- ...FinishAuxiliaryMethodComputationMacro.java | 26 +- .../FullInformationFlowAutoPilotMacro.java | 139 +- .../FullUseInformationFlowContractMacro.java | 24 +- .../SelfcompositionStateExpansionMacro.java | 64 +- .../StartAuxiliaryBlockComputationMacro.java | 61 +- .../StartAuxiliaryComputationMacro.java | 21 +- .../StartAuxiliaryLoopComputationMacro.java | 74 +- .../StartAuxiliaryMethodComputationMacro.java | 56 +- .../macros/StartSideProofMacro.java | 11 +- ...ionAndInfFlowContractApplicationMacro.java | 24 +- .../UseInformationFlowContractMacro.java | 145 +- .../informationflow/po/AbstractInfFlowPO.java | 29 +- .../informationflow/po/BlockExecutionPO.java | 121 +- .../po/IFProofObligationVars.java | 27 +- .../po/InfFlowCompositePO.java | 3 + .../informationflow/po/InfFlowContractPO.java | 106 +- .../key/informationflow/po/InfFlowLeafPO.java | 3 + .../key/informationflow/po/InfFlowPO.java | 13 +- .../po/InfFlowProofSymbols.java | 239 +- .../po/LoopInvExecutionPO.java | 130 +- .../po/SymbolicExecutionPO.java | 108 +- .../snippet/BasicBlockExecutionSnippet.java | 53 +- ...BlockExecutionWithPreconditionSnippet.java | 20 +- .../po/snippet/BasicDependsSnippet.java | 10 +- .../po/snippet/BasicFreeInvSnippet.java | 36 +- .../po/snippet/BasicFreePreSnippet.java | 25 +- .../po/snippet/BasicLoopExecutionSnippet.java | 67 +- ...asicLoopExecutionWithInvariantSnippet.java | 20 +- .../po/snippet/BasicLoopInvariantSnippet.java | 15 +- .../po/snippet/BasicMbyAtPreDefSnippet.java | 18 +- .../po/snippet/BasicModifiesSnippet.java | 10 +- .../po/snippet/BasicPOSnippetFactory.java | 70 +- .../po/snippet/BasicPOSnippetFactoryImpl.java | 66 +- .../po/snippet/BasicParamsOkSnippet.java | 23 +- .../po/snippet/BasicPostconditionSnippet.java | 13 +- .../po/snippet/BasicPreconditionSnippet.java | 15 +- .../po/snippet/BasicSelfCreatedSnippet.java | 15 +- .../po/snippet/BasicSelfExactTypeSnippet.java | 18 +- .../po/snippet/BasicSelfNotNullSnippet.java | 13 +- .../po/snippet/BasicSnippetData.java | 109 +- .../BasicSymbolicExecutionSnippet.java | 119 +- ...bolicExecutionWithPreconditionSnippet.java | 23 +- .../po/snippet/BlockCallPredicateSnippet.java | 19 +- ...kCallWithPreconditionPredicateSnippet.java | 18 +- .../po/snippet/FactoryMethod.java | 6 +- ...nfFlowContractAppInOutRelationSnippet.java | 10 +- .../po/snippet/InfFlowContractAppSnippet.java | 25 +- .../po/snippet/InfFlowFactoryMethod.java | 7 +- .../InfFlowInputOutputRelationSnippet.java | 97 +- .../po/snippet/InfFlowLoopInvAppSnippet.java | 19 +- .../po/snippet/InfFlowPOSnippetFactory.java | 64 +- .../snippet/InfFlowPOSnippetFactoryImpl.java | 65 +- .../po/snippet/LoopCallPredicateSnippet.java | 17 +- ...LoopCallWithInvariantPredicateSnippet.java | 18 +- .../snippet/MethodCallPredicateSnippet.java | 19 +- .../po/snippet/POSnippetFactory.java | 81 +- .../po/snippet/ReplaceAndRegisterMethod.java | 83 +- .../po/snippet/SelfcomposedBlockSnippet.java | 38 +- .../snippet/SelfcomposedExecutionSnippet.java | 35 +- .../po/snippet/SelfcomposedLoopSnippet.java | 41 +- .../TwoStateMethodPredicateSnippet.java | 63 +- .../proof/InfFlowCheckInfo.java | 24 +- .../informationflow/proof/InfFlowProof.java | 51 +- .../proof/SideProofStatistics.java | 153 +- .../informationflow/proof/init/StateVars.java | 261 +- .../rule/InfFlowContractAppTaclet.java | 72 +- .../InfFlowContractAppTacletExecutor.java | 59 +- ...stractInfFlowContractAppTacletBuilder.java | 51 +- .../AbstractInfFlowTacletBuilder.java | 67 +- .../AbstractInfFlowUnfoldTacletBuilder.java | 128 +- .../BlockInfFlowUnfoldTacletBuilder.java | 14 +- .../InfFlowBlockContractTacletBuilder.java | 49 +- .../InfFlowLoopInvariantTacletBuilder.java | 52 +- .../InfFlowMethodContractTacletBuilder.java | 30 +- .../LoopInfFlowUnfoldTacletBuilder.java | 15 +- .../MethodInfFlowUnfoldTacletBuilder.java | 11 +- .../CcatchBreakLabelParameterDeclaration.java | 6 +- .../java/CcatchBreakParameterDeclaration.java | 9 +- ...atchBreakWildcardParameterDeclaration.java | 9 +- ...atchContinueLabelParameterDeclaration.java | 6 +- .../CcatchContinueParameterDeclaration.java | 9 +- ...hContinueWildcardParameterDeclaration.java | 6 +- ...CcatchNonstandardParameterDeclaration.java | 8 +- .../CcatchReturnParameterDeclaration.java | 9 +- .../CcatchReturnValParameterDeclaration.java | 16 +- .../java/de/uka/ilkd/key/java/Comment.java | 73 +- .../de/uka/ilkd/key/java/CompilationUnit.java | 179 +- .../key/java/ConstantExpressionEvaluator.java | 75 +- .../java/de/uka/ilkd/key/java/Context.java | 85 +- .../ilkd/key/java/ContextStatementBlock.java | 330 +- .../uka/ilkd/key/java/ConvertException.java | 66 +- .../key/java/CreateArrayMethodBuilder.java | 330 +- .../de/uka/ilkd/key/java/Declaration.java | 9 +- .../java/de/uka/ilkd/key/java/Dimension.java | 9 +- .../java/de/uka/ilkd/key/java/Expression.java | 13 +- .../ilkd/key/java/ExpressionContainer.java | 28 +- .../java/de/uka/ilkd/key/java/Import.java | 143 +- .../java/de/uka/ilkd/key/java/JavaInfo.java | 611 +- .../java/JavaNonTerminalProgramElement.java | 172 +- .../uka/ilkd/key/java/JavaProgramElement.java | 142 +- .../java/de/uka/ilkd/key/java/JavaReader.java | 5 +- .../key/java/JavaReduxFileCollection.java | 112 +- .../uka/ilkd/key/java/JavaSourceElement.java | 167 +- .../java/de/uka/ilkd/key/java/JavaTools.java | 38 +- .../uka/ilkd/key/java/KeYJavaASTFactory.java | 3017 +++--- .../uka/ilkd/key/java/KeYProgModelInfo.java | 399 +- .../uka/ilkd/key/java/KeYRecoderMapping.java | 149 +- .../main/java/de/uka/ilkd/key/java/Label.java | 7 +- .../de/uka/ilkd/key/java/LoopInitializer.java | 8 +- .../de/uka/ilkd/key/java/ModelElement.java | 11 +- .../ilkd/key/java/NameAbstractionTable.java | 74 +- .../uka/ilkd/key/java/NamedModelElement.java | 9 +- .../ilkd/key/java/NamedProgramElement.java | 13 +- .../key/java/NonTerminalProgramElement.java | 34 +- .../ilkd/key/java/PackageSpecification.java | 59 +- .../uka/ilkd/key/java/ParameterContainer.java | 25 +- .../java/ParentIsInterfaceDeclaration.java | 9 +- .../ilkd/key/java/ParseExceptionInFile.java | 8 +- .../ilkd/key/java/PosConvertException.java | 13 +- .../java/de/uka/ilkd/key/java/Position.java | 150 +- .../de/uka/ilkd/key/java/PositionInfo.java | 52 +- .../de/uka/ilkd/key/java/PrettyPrinter.java | 1988 ++-- .../de/uka/ilkd/key/java/ProgramElement.java | 28 +- .../uka/ilkd/key/java/ProgramPrefixUtil.java | 13 +- .../ilkd/key/java/ProgramVariableName.java | 26 +- .../de/uka/ilkd/key/java/Recoder2KeY.java | 762 +- .../ilkd/key/java/Recoder2KeYConverter.java | 1055 +-- .../key/java/Recoder2KeYTypeConverter.java | 190 +- .../java/de/uka/ilkd/key/java/Reference.java | 12 +- .../uka/ilkd/key/java/SchemaJavaReader.java | 5 +- .../uka/ilkd/key/java/SchemaRecoder2KeY.java | 77 +- .../key/java/SchemaRecoder2KeYConverter.java | 264 +- .../ilkd/key/java/ScopeDefiningElement.java | 9 +- .../de/uka/ilkd/key/java/ServiceCaches.java | 335 +- .../java/de/uka/ilkd/key/java/Services.java | 337 +- .../uka/ilkd/key/java/SingleLineComment.java | 12 +- .../java/de/uka/ilkd/key/java/SourceData.java | 95 +- .../de/uka/ilkd/key/java/SourceElement.java | 107 +- .../java/de/uka/ilkd/key/java/Statement.java | 8 +- .../de/uka/ilkd/key/java/StatementBlock.java | 154 +- .../uka/ilkd/key/java/StatementContainer.java | 28 +- .../ilkd/key/java/TerminalProgramElement.java | 8 +- .../de/uka/ilkd/key/java/TypeConverter.java | 470 +- .../uka/ilkd/key/java/TypeNameTranslator.java | 96 +- .../java/de/uka/ilkd/key/java/TypeScope.java | 10 +- .../key/java/UnknownJavaTypeException.java | 21 +- .../de/uka/ilkd/key/java/VariableScope.java | 10 +- .../ilkd/key/java/abstraction/ArrayType.java | 21 +- .../ilkd/key/java/abstraction/ClassType.java | 124 +- .../java/abstraction/ClassTypeContainer.java | 37 +- .../key/java/abstraction/Constructor.java | 11 +- .../java/abstraction/DefaultConstructor.java | 173 +- .../uka/ilkd/key/java/abstraction/Field.java | 25 +- .../key/java/abstraction/KeYJavaType.java | 122 +- .../uka/ilkd/key/java/abstraction/Member.java | 55 +- .../uka/ilkd/key/java/abstraction/Method.java | 38 +- .../ilkd/key/java/abstraction/NullType.java | 212 +- .../ilkd/key/java/abstraction/Package.java | 52 +- .../key/java/abstraction/PrimitiveType.java | 175 +- .../java/abstraction/ProgramModelElement.java | 23 +- .../uka/ilkd/key/java/abstraction/Type.java | 21 +- .../ilkd/key/java/abstraction/Variable.java | 27 +- .../java/declaration/ArrayDeclaration.java | 186 +- .../java/declaration/ClassDeclaration.java | 260 +- .../java/declaration/ClassInitializer.java | 75 +- .../declaration/ConstructorDeclaration.java | 79 +- .../declaration/EnumClassDeclaration.java | 54 +- .../ilkd/key/java/declaration/Extends.java | 35 +- .../java/declaration/FieldDeclaration.java | 108 +- .../java/declaration/FieldSpecification.java | 96 +- .../ilkd/key/java/declaration/Implements.java | 39 +- .../ImplicitFieldSpecification.java | 29 +- .../declaration/InheritanceSpecification.java | 95 +- .../declaration/InterfaceDeclaration.java | 114 +- .../key/java/declaration/JavaDeclaration.java | 89 +- .../declaration/LocalVariableDeclaration.java | 143 +- .../java/declaration/MemberDeclaration.java | 8 +- .../java/declaration/MethodDeclaration.java | 247 +- .../ilkd/key/java/declaration/Modifier.java | 37 +- .../declaration/ParameterDeclaration.java | 160 +- .../declaration/SuperArrayDeclaration.java | 56 +- .../uka/ilkd/key/java/declaration/Throws.java | 100 +- .../key/java/declaration/TypeDeclaration.java | 206 +- .../declaration/TypeDeclarationContainer.java | 29 +- .../java/declaration/VariableDeclaration.java | 119 +- .../declaration/VariableSpecification.java | 86 +- .../java/declaration/modifier/Abstract.java | 20 +- .../modifier/AnnotationUseSpecification.java | 21 +- .../key/java/declaration/modifier/Final.java | 24 +- .../key/java/declaration/modifier/Ghost.java | 9 +- .../key/java/declaration/modifier/Model.java | 9 +- .../key/java/declaration/modifier/Native.java | 25 +- .../java/declaration/modifier/NoState.java | 9 +- .../java/declaration/modifier/Private.java | 34 +- .../java/declaration/modifier/Protected.java | 36 +- .../key/java/declaration/modifier/Public.java | 37 +- .../key/java/declaration/modifier/Static.java | 25 +- .../java/declaration/modifier/StrictFp.java | 25 +- .../declaration/modifier/Synchronized.java | 25 +- .../java/declaration/modifier/Transient.java | 27 +- .../java/declaration/modifier/TwoState.java | 9 +- .../modifier/VisibilityModifier.java | 60 +- .../java/declaration/modifier/Volatile.java | 22 +- .../key/java/expression/ArrayInitializer.java | 65 +- .../ilkd/key/java/expression/Assignment.java | 81 +- .../java/expression/ExpressionStatement.java | 16 +- .../uka/ilkd/key/java/expression/Literal.java | 56 +- .../ilkd/key/java/expression/Operator.java | 145 +- .../expression/ParenthesizedExpression.java | 80 +- .../java/expression/PassiveExpression.java | 29 +- .../literal/AbstractIntegerLiteral.java | 48 +- .../expression/literal/BooleanLiteral.java | 80 +- .../java/expression/literal/CharLiteral.java | 42 +- .../expression/literal/DoubleLiteral.java | 79 +- .../expression/literal/EmptyMapLiteral.java | 9 +- .../expression/literal/EmptySeqLiteral.java | 20 +- .../expression/literal/EmptySetLiteral.java | 18 +- .../java/expression/literal/FloatLiteral.java | 74 +- .../java/expression/literal/FreeLiteral.java | 7 +- .../java/expression/literal/IntLiteral.java | 55 +- .../java/expression/literal/LongLiteral.java | 63 +- .../java/expression/literal/NullLiteral.java | 20 +- .../java/expression/literal/RealLiteral.java | 69 +- .../expression/literal/StringLiteral.java | 42 +- .../java/expression/operator/BinaryAnd.java | 38 +- .../operator/BinaryAndAssignment.java | 42 +- .../java/expression/operator/BinaryNot.java | 53 +- .../expression/operator/BinaryOperator.java | 35 +- .../java/expression/operator/BinaryOr.java | 36 +- .../operator/BinaryOrAssignment.java | 41 +- .../java/expression/operator/BinaryXOr.java | 36 +- .../operator/BinaryXOrAssignment.java | 41 +- .../operator/ComparativeOperator.java | 34 +- .../java/expression/operator/Conditional.java | 117 +- .../expression/operator/CopyAssignment.java | 39 +- .../operator/DLEmbeddedExpression.java | 79 +- .../key/java/expression/operator/Divide.java | 35 +- .../expression/operator/DivideAssignment.java | 41 +- .../key/java/expression/operator/Equals.java | 33 +- .../expression/operator/ExactInstanceof.java | 71 +- .../expression/operator/GreaterOrEquals.java | 28 +- .../java/expression/operator/GreaterThan.java | 29 +- .../java/expression/operator/Instanceof.java | 75 +- .../java/expression/operator/Intersect.java | 9 +- .../expression/operator/LessOrEquals.java | 28 +- .../java/expression/operator/LessThan.java | 25 +- .../java/expression/operator/LogicalAnd.java | 42 +- .../java/expression/operator/LogicalNot.java | 48 +- .../java/expression/operator/LogicalOr.java | 36 +- .../key/java/expression/operator/Minus.java | 38 +- .../expression/operator/MinusAssignment.java | 38 +- .../key/java/expression/operator/Modulo.java | 30 +- .../expression/operator/ModuloAssignment.java | 38 +- .../java/expression/operator/Negative.java | 52 +- .../key/java/expression/operator/New.java | 168 +- .../java/expression/operator/NewArray.java | 202 +- .../java/expression/operator/NotEquals.java | 28 +- .../key/java/expression/operator/Plus.java | 38 +- .../expression/operator/PlusAssignment.java | 40 +- .../java/expression/operator/Positive.java | 52 +- .../expression/operator/PostDecrement.java | 35 +- .../expression/operator/PostIncrement.java | 40 +- .../expression/operator/PreDecrement.java | 41 +- .../expression/operator/PreIncrement.java | 37 +- .../java/expression/operator/ShiftLeft.java | 57 +- .../operator/ShiftLeftAssignment.java | 52 +- .../java/expression/operator/ShiftRight.java | 60 +- .../operator/ShiftRightAssignment.java | 56 +- .../key/java/expression/operator/Times.java | 52 +- .../expression/operator/TimesAssignment.java | 55 +- .../java/expression/operator/TypeCast.java | 80 +- .../expression/operator/TypeOperator.java | 84 +- .../operator/UnsignedShiftRight.java | 57 +- .../UnsignedShiftRightAssignment.java | 52 +- .../expression/operator/adt/AllFields.java | 13 +- .../expression/operator/adt/AllObjects.java | 13 +- .../expression/operator/adt/SeqConcat.java | 9 +- .../java/expression/operator/adt/SeqGet.java | 8 +- .../expression/operator/adt/SeqIndexOf.java | 8 +- .../expression/operator/adt/SeqLength.java | 10 +- .../expression/operator/adt/SeqReverse.java | 29 +- .../expression/operator/adt/SeqSingleton.java | 15 +- .../java/expression/operator/adt/SeqSub.java | 23 +- .../expression/operator/adt/SetMinus.java | 9 +- .../expression/operator/adt/SetUnion.java | 9 +- .../expression/operator/adt/Singleton.java | 13 +- .../uka/ilkd/key/java/recoderext/Bigint.java | 6 +- .../java/recoderext/CatchAllStatement.java | 152 +- .../key/java/recoderext/CatchSVWrapper.java | 42 +- .../uka/ilkd/key/java/recoderext/Ccatch.java | 122 +- .../CcatchBreakLabelParameterDeclaration.java | 36 +- .../CcatchBreakParameterDeclaration.java | 9 +- ...atchBreakWildcardParameterDeclaration.java | 9 +- ...atchContinueLabelParameterDeclaration.java | 36 +- .../CcatchContinueParameterDeclaration.java | 9 +- ...hContinueWildcardParameterDeclaration.java | 6 +- ...CcatchNonstandardParameterDeclaration.java | 6 +- .../CcatchReturnParameterDeclaration.java | 9 +- .../CcatchReturnValParameterDeclaration.java | 49 +- .../key/java/recoderext/CcatchSVWrapper.java | 14 +- .../ClassFileDeclarationBuilder.java | 258 +- .../ClassFileDeclarationManager.java | 127 +- .../ClassInitializeMethodBuilder.java | 279 +- .../ClassPreparationMethodBuilder.java | 98 +- .../ConstantStringExpressionEvaluator.java | 72 +- .../ConstructorNormalformBuilder.java | 236 +- .../recoderext/ContextStatementBlock.java | 48 +- .../key/java/recoderext/CreateBuilder.java | 47 +- .../java/recoderext/CreateObjectBuilder.java | 82 +- .../java/recoderext/DLEmbeddedExpression.java | 15 +- .../key/java/recoderext/EnumClassBuilder.java | 110 +- .../java/recoderext/EnumClassDeclaration.java | 152 +- .../key/java/recoderext/EscapeExpression.java | 15 +- .../de/uka/ilkd/key/java/recoderext/Exec.java | 80 +- .../java/recoderext/ExecCtxtSVWrapper.java | 28 +- .../key/java/recoderext/ExecutionContext.java | 210 +- .../java/recoderext/ExpressionSVWrapper.java | 98 +- .../java/recoderext/ExtendedIdentifier.java | 26 +- .../uka/ilkd/key/java/recoderext/Ghost.java | 21 +- .../java/recoderext/ImplicitFieldAdder.java | 109 +- .../java/recoderext/ImplicitIdentifier.java | 25 +- .../InstanceAllocationMethodBuilder.java | 32 +- .../key/java/recoderext/JMLTransformer.java | 259 +- .../ilkd/key/java/recoderext/JmlAssert.java | 12 +- .../java/recoderext/JumpLabelSVWrapper.java | 19 +- .../KeYAnnotationUseSpecification.java | 23 +- .../recoderext/KeYCrossReferenceNameInfo.java | 92 +- ...KeYCrossReferenceServiceConfiguration.java | 36 +- ...KeYCrossReferenceSourceFileRepository.java | 38 +- .../java/recoderext/KeYRecoderExtension.java | 5 +- .../key/java/recoderext/LabelSVWrapper.java | 19 +- .../recoderext/LocalClassTransformation.java | 57 +- .../key/java/recoderext/LoopScopeBlock.java | 103 +- .../java/recoderext/MergePointStatement.java | 17 +- .../java/recoderext/MethodBodyStatement.java | 305 +- .../java/recoderext/MethodCallStatement.java | 230 +- .../recoderext/MethodSignatureSVWrapper.java | 21 +- .../uka/ilkd/key/java/recoderext/Model.java | 21 +- .../key/java/recoderext/NewArrayWrapper.java | 23 +- .../ilkd/key/java/recoderext/NewWrapper.java | 23 +- .../uka/ilkd/key/java/recoderext/NoState.java | 9 +- .../java/recoderext/ObjectTypeIdentifier.java | 22 +- .../java/recoderext/PassiveExpression.java | 22 +- .../java/recoderext/PrepareObjectBuilder.java | 103 +- .../recoderext/ProgramVariableSVWrapper.java | 23 +- ...oofCrossReferenceServiceConfiguration.java | 12 +- .../recoderext/ProofJavaProgramFactory.java | 325 +- .../java/recoderext/RKeYMetaConstruct.java | 144 +- .../RKeYMetaConstructExpression.java | 144 +- .../recoderext/RKeYMetaConstructType.java | 120 +- .../java/recoderext/RMethodBodyStatement.java | 196 +- .../java/recoderext/RMethodCallStatement.java | 171 +- .../de/uka/ilkd/key/java/recoderext/Real.java | 6 +- .../recoderext/RecoderModelTransformer.java | 178 +- .../RegisteredEscapeExpression.java | 13 +- .../ilkd/key/java/recoderext/SVWrapper.java | 6 +- ...emaCrossReferenceServiceConfiguration.java | 23 +- .../SchemaCrossReferenceSourceInfo.java | 47 +- .../recoderext/SchemaJavaProgramFactory.java | 466 +- .../recoderext/SourceVisitorExtended.java | 5 +- .../recoderext/SpecialReferenceWrapper.java | 16 +- .../java/recoderext/StatementSVWrapper.java | 87 +- .../java/recoderext/TransactionStatement.java | 34 +- .../ilkd/key/java/recoderext/TwoState.java | 9 +- .../key/java/recoderext/TypeSVWrapper.java | 21 +- .../key/java/recoderext/URLDataLocation.java | 37 +- .../recoderext/adt/ADTPrefixConstruct.java | 35 +- .../key/java/recoderext/adt/AllFields.java | 33 +- .../key/java/recoderext/adt/AllObjects.java | 33 +- .../java/recoderext/adt/EmptyMapLiteral.java | 8 +- .../java/recoderext/adt/EmptySeqLiteral.java | 26 +- .../java/recoderext/adt/EmptySetLiteral.java | 22 +- .../key/java/recoderext/adt/Intersect.java | 37 +- .../java/recoderext/adt/MethodSignature.java | 20 +- .../java/recoderext/adt/RangeExpression.java | 30 +- .../key/java/recoderext/adt/SeqConcat.java | 38 +- .../ilkd/key/java/recoderext/adt/SeqGet.java | 23 +- .../key/java/recoderext/adt/SeqIndexOf.java | 22 +- .../key/java/recoderext/adt/SeqLength.java | 21 +- .../key/java/recoderext/adt/SeqReverse.java | 39 +- .../key/java/recoderext/adt/SeqSingleton.java | 37 +- .../ilkd/key/java/recoderext/adt/SeqSub.java | 49 +- .../key/java/recoderext/adt/SetMinus.java | 31 +- .../key/java/recoderext/adt/SetUnion.java | 31 +- .../key/java/recoderext/adt/Singleton.java | 31 +- .../expression/literal/RealLiteral.java | 24 +- .../java/reference/ArrayLengthReference.java | 77 +- .../key/java/reference/ArrayReference.java | 228 +- .../java/reference/ConstructorReference.java | 13 +- .../key/java/reference/ExecutionContext.java | 63 +- .../key/java/reference/FieldReference.java | 127 +- .../key/java/reference/IExecutionContext.java | 45 +- .../key/java/reference/MemberReference.java | 11 +- .../java/reference/MetaClassReference.java | 109 +- .../ilkd/key/java/reference/MethodName.java | 13 +- .../MethodOrConstructorReference.java | 9 +- .../key/java/reference/MethodReference.java | 349 +- .../key/java/reference/NameReference.java | 8 +- .../key/java/reference/PackageReference.java | 118 +- .../reference/PackageReferenceContainer.java | 15 +- .../key/java/reference/ReferencePrefix.java | 12 +- .../key/java/reference/ReferenceSuffix.java | 21 +- .../java/reference/SchemaTypeReference.java | 57 +- .../reference/SchematicFieldReference.java | 121 +- .../SpecialConstructorReference.java | 99 +- .../reference/SuperConstructorReference.java | 106 +- .../key/java/reference/SuperReference.java | 120 +- .../reference/ThisConstructorReference.java | 52 +- .../key/java/reference/ThisReference.java | 114 +- .../uka/ilkd/key/java/reference/TypeRef.java | 48 +- .../key/java/reference/TypeReference.java | 21 +- .../reference/TypeReferenceContainer.java | 30 +- .../key/java/reference/TypeReferenceImp.java | 182 +- .../java/reference/TypeReferenceInfix.java | 10 +- .../key/java/reference/VariableReference.java | 53 +- .../uka/ilkd/key/java/statement/Assert.java | 29 +- .../uka/ilkd/key/java/statement/Branch.java | 10 +- .../ilkd/key/java/statement/BranchImp.java | 23 +- .../key/java/statement/BranchStatement.java | 42 +- .../de/uka/ilkd/key/java/statement/Break.java | 38 +- .../de/uka/ilkd/key/java/statement/Case.java | 143 +- .../de/uka/ilkd/key/java/statement/Catch.java | 140 +- .../key/java/statement/CatchAllStatement.java | 148 +- .../uka/ilkd/key/java/statement/Ccatch.java | 83 +- .../uka/ilkd/key/java/statement/Continue.java | 36 +- .../uka/ilkd/key/java/statement/Default.java | 90 +- .../ilkd/key/java/statement/Desugarable.java | 5 +- .../de/uka/ilkd/key/java/statement/Do.java | 47 +- .../de/uka/ilkd/key/java/statement/Else.java | 77 +- .../key/java/statement/EmptyStatement.java | 34 +- .../ilkd/key/java/statement/EnhancedFor.java | 55 +- .../de/uka/ilkd/key/java/statement/Exec.java | 85 +- .../statement/ExpressionJumpStatement.java | 76 +- .../uka/ilkd/key/java/statement/Finally.java | 90 +- .../de/uka/ilkd/key/java/statement/For.java | 63 +- .../ilkd/key/java/statement/ForUpdates.java | 61 +- .../de/uka/ilkd/key/java/statement/Guard.java | 31 +- .../ilkd/key/java/statement/IForUpdates.java | 5 +- .../uka/ilkd/key/java/statement/IGuard.java | 5 +- .../ilkd/key/java/statement/ILoopInit.java | 5 +- .../de/uka/ilkd/key/java/statement/If.java | 144 +- .../key/java/statement/JavaStatement.java | 31 +- .../ilkd/key/java/statement/JmlAssert.java | 33 +- .../key/java/statement/JumpStatement.java | 23 +- .../java/statement/LabelJumpStatement.java | 74 +- .../key/java/statement/LabeledStatement.java | 249 +- .../uka/ilkd/key/java/statement/LoopInit.java | 63 +- .../key/java/statement/LoopScopeBlock.java | 90 +- .../key/java/statement/LoopStatement.java | 411 +- .../java/statement/MergePointStatement.java | 49 +- .../java/statement/MethodBodyStatement.java | 283 +- .../ilkd/key/java/statement/MethodFrame.java | 213 +- .../uka/ilkd/key/java/statement/Return.java | 35 +- .../uka/ilkd/key/java/statement/Switch.java | 137 +- .../key/java/statement/SynchronizedBlock.java | 188 +- .../de/uka/ilkd/key/java/statement/Then.java | 72 +- .../de/uka/ilkd/key/java/statement/Throw.java | 27 +- .../java/statement/TransactionStatement.java | 33 +- .../de/uka/ilkd/key/java/statement/Try.java | 155 +- .../de/uka/ilkd/key/java/statement/While.java | 52 +- .../visitor/ContainsStatementVisitor.java | 52 +- .../key/java/visitor/CreatingASTVisitor.java | 136 +- .../DeclarationProgramVariableCollector.java | 57 +- .../key/java/visitor/FieldReplaceVisitor.java | 94 +- .../key/java/visitor/FreeLabelFinder.java | 23 +- .../InnerBreakAndContinueReplacer.java | 20 +- .../key/java/visitor/JavaASTCollector.java | 40 +- .../ilkd/key/java/visitor/JavaASTVisitor.java | 58 +- .../ilkd/key/java/visitor/JavaASTWalker.java | 16 +- .../ilkd/key/java/visitor/LabelCollector.java | 22 +- .../OuterBreakContinueAndReturnCollector.java | 48 +- .../OuterBreakContinueAndReturnReplacer.java | 13 +- .../java/visitor/ProgVarReplaceVisitor.java | 319 +- .../key/java/visitor/ProgramContextAdder.java | 156 +- .../java/visitor/ProgramElementReplacer.java | 17 +- .../java/visitor/ProgramReplaceVisitor.java | 48 +- .../key/java/visitor/ProgramSVCollector.java | 82 +- .../visitor/ProgramVariableCollector.java | 83 +- .../UndeclaredProgramVariableCollector.java | 227 +- .../de/uka/ilkd/key/java/visitor/Visitor.java | 37 +- .../java/de/uka/ilkd/key/ldt/BooleanLDT.java | 152 +- .../java/de/uka/ilkd/key/ldt/CharListLDT.java | 315 +- .../java/de/uka/ilkd/key/ldt/DoubleLDT.java | 152 +- .../java/de/uka/ilkd/key/ldt/FloatLDT.java | 139 +- .../de/uka/ilkd/key/ldt/FloatingPointLDT.java | 28 + .../java/de/uka/ilkd/key/ldt/FreeLDT.java | 32 +- .../java/de/uka/ilkd/key/ldt/HeapLDT.java | 583 +- .../java/de/uka/ilkd/key/ldt/IntegerLDT.java | 808 +- .../main/java/de/uka/ilkd/key/ldt/LDT.java | 241 +- .../java/de/uka/ilkd/key/ldt/LocSetLDT.java | 254 +- .../main/java/de/uka/ilkd/key/ldt/MapLDT.java | 22 +- .../de/uka/ilkd/key/ldt/PermissionLDT.java | 12 +- .../java/de/uka/ilkd/key/ldt/RealLDT.java | 82 +- .../main/java/de/uka/ilkd/key/ldt/SeqLDT.java | 211 +- .../uka/ilkd/key/logic/BooleanContainer.java | 17 +- .../ilkd/key/logic/BoundVariableTools.java | 331 +- .../uka/ilkd/key/logic/BoundVarsVisitor.java | 47 +- .../java/de/uka/ilkd/key/logic/Choice.java | 11 +- .../de/uka/ilkd/key/logic/ClashFreeSubst.java | 228 +- .../de/uka/ilkd/key/logic/DefaultVisitor.java | 13 +- .../uka/ilkd/key/logic/FormulaChangeInfo.java | 27 +- .../ilkd/key/logic/GenericTermReplacer.java | 15 +- .../ilkd/key/logic/InnerVariableNamer.java | 47 +- .../de/uka/ilkd/key/logic/IntIterator.java | 5 +- .../java/de/uka/ilkd/key/logic/JavaBlock.java | 146 +- .../uka/ilkd/key/logic/LabeledTermImpl.java | 19 +- .../uka/ilkd/key/logic/LexPathOrdering.java | 506 +- .../uka/ilkd/key/logic/MethodStackInfo.java | 31 +- .../ilkd/key/logic/MultiRenamingTable.java | 31 +- .../main/java/de/uka/ilkd/key/logic/Name.java | 43 +- .../uka/ilkd/key/logic/NameCreationInfo.java | 5 +- .../java/de/uka/ilkd/key/logic/Named.java | 10 +- .../java/de/uka/ilkd/key/logic/Namespace.java | 136 +- .../de/uka/ilkd/key/logic/NamespaceSet.java | 170 +- .../de/uka/ilkd/key/logic/OpCollector.java | 19 +- .../uka/ilkd/key/logic/PIOPathIterator.java | 39 +- .../uka/ilkd/key/logic/PosInOccurrence.java | 363 +- .../de/uka/ilkd/key/logic/PosInProgram.java | 174 +- .../java/de/uka/ilkd/key/logic/PosInTerm.java | 155 +- .../uka/ilkd/key/logic/ProgramConstruct.java | 18 +- .../ilkd/key/logic/ProgramElementName.java | 203 +- .../de/uka/ilkd/key/logic/ProgramInLogic.java | 9 +- .../de/uka/ilkd/key/logic/ProgramPrefix.java | 35 +- .../de/uka/ilkd/key/logic/RenameTable.java | 201 +- .../de/uka/ilkd/key/logic/RenamingTable.java | 29 +- .../de/uka/ilkd/key/logic/Semisequent.java | 391 +- .../ilkd/key/logic/SemisequentChangeInfo.java | 256 +- .../java/de/uka/ilkd/key/logic/Sequent.java | 237 +- .../uka/ilkd/key/logic/SequentChangeInfo.java | 653 +- .../de/uka/ilkd/key/logic/SequentFormula.java | 55 +- .../ilkd/key/logic/SingleRenamingTable.java | 49 +- .../de/uka/ilkd/key/logic/SortCollector.java | 50 +- .../java/de/uka/ilkd/key/logic/Sorted.java | 5 +- .../main/java/de/uka/ilkd/key/logic/Term.java | 100 +- .../de/uka/ilkd/key/logic/TermBuilder.java | 701 +- .../ilkd/key/logic/TermCreationException.java | 109 +- .../de/uka/ilkd/key/logic/TermFactory.java | 149 +- .../java/de/uka/ilkd/key/logic/TermImpl.java | 262 +- .../de/uka/ilkd/key/logic/TermOrdering.java | 15 +- .../de/uka/ilkd/key/logic/TermServices.java | 29 +- .../de/uka/ilkd/key/logic/VariableNamer.java | 848 +- .../java/de/uka/ilkd/key/logic/Visitor.java | 29 +- .../ilkd/key/logic/WaryClashFreeSubst.java | 203 +- .../label/BlockContractValidityTermLabel.java | 21 +- ...BlockContractValidityTermLabelFactory.java | 22 +- .../key/logic/label/FormulaTermLabel.java | 538 +- .../logic/label/FormulaTermLabelFactory.java | 41 +- .../ilkd/key/logic/label/OriginTermLabel.java | 158 +- .../logic/label/OriginTermLabelFactory.java | 41 +- .../logic/label/ParameterlessTermLabel.java | 214 +- .../logic/label/SingletonLabelFactory.java | 24 +- .../label/SymbolicExecutionTermLabel.java | 136 +- .../SymbolicExecutionTermLabelFactory.java | 19 +- .../uka/ilkd/key/logic/label/TermLabel.java | 219 +- .../key/logic/label/TermLabelException.java | 12 +- .../key/logic/label/TermLabelFactory.java | 37 +- .../key/logic/label/TermLabelManager.java | 3505 ++++--- .../label/TermLabelOperationsInterpreter.java | 60 +- .../ilkd/key/logic/label/TermLabelState.java | 85 +- .../ilkd/key/logic/op/AbstractOperator.java | 108 +- .../de/uka/ilkd/key/logic/op/AbstractSV.java | 62 +- .../key/logic/op/AbstractSortedOperator.java | 227 +- .../key/logic/op/AbstractTermTransformer.java | 23 +- .../ilkd/key/logic/op/ElementaryUpdate.java | 47 +- .../de/uka/ilkd/key/logic/op/Equality.java | 42 +- .../de/uka/ilkd/key/logic/op/FormulaSV.java | 27 +- .../de/uka/ilkd/key/logic/op/Function.java | 118 +- .../ilkd/key/logic/op/IObserverFunction.java | 98 +- .../uka/ilkd/key/logic/op/IProgramMethod.java | 22 +- .../ilkd/key/logic/op/IProgramVariable.java | 11 +- .../uka/ilkd/key/logic/op/IfExThenElse.java | 37 +- .../de/uka/ilkd/key/logic/op/IfThenElse.java | 67 +- .../de/uka/ilkd/key/logic/op/Junctor.java | 74 +- .../ilkd/key/logic/op/LocationVariable.java | 39 +- .../uka/ilkd/key/logic/op/LogicVariable.java | 24 +- .../de/uka/ilkd/key/logic/op/MixFitInfo.java | 7 +- .../ilkd/key/logic/op/ModalOperatorSV.java | 62 +- .../de/uka/ilkd/key/logic/op/Modality.java | 92 +- .../ilkd/key/logic/op/ObserverFunction.java | 244 +- .../de/uka/ilkd/key/logic/op/Operator.java | 34 +- .../ilkd/key/logic/op/ParsableVariable.java | 10 +- .../ilkd/key/logic/op/ProgramConstant.java | 35 +- .../uka/ilkd/key/logic/op/ProgramMethod.java | 144 +- .../de/uka/ilkd/key/logic/op/ProgramSV.java | 128 +- .../ilkd/key/logic/op/ProgramVariable.java | 274 +- .../key/logic/op/QuantifiableVariable.java | 11 +- .../de/uka/ilkd/key/logic/op/Quantifier.java | 35 +- .../uka/ilkd/key/logic/op/SVSubstitute.java | 11 +- .../uka/ilkd/key/logic/op/SchemaVariable.java | 28 +- .../key/logic/op/SchemaVariableFactory.java | 100 +- .../uka/ilkd/key/logic/op/SkolemTermSV.java | 46 +- .../key/logic/op/SortDependingFunction.java | 124 +- .../uka/ilkd/key/logic/op/SortedOperator.java | 11 +- .../de/uka/ilkd/key/logic/op/SubstOp.java | 55 +- .../de/uka/ilkd/key/logic/op/TermLabelSV.java | 5 +- .../java/de/uka/ilkd/key/logic/op/TermSV.java | 34 +- .../ilkd/key/logic/op/TermTransformer.java | 13 +- .../de/uka/ilkd/key/logic/op/Transformer.java | 71 +- .../ilkd/key/logic/op/UpdateApplication.java | 64 +- .../uka/ilkd/key/logic/op/UpdateJunctor.java | 45 +- .../de/uka/ilkd/key/logic/op/UpdateSV.java | 25 +- .../ilkd/key/logic/op/UpdateableOperator.java | 10 +- .../de/uka/ilkd/key/logic/op/VariableSV.java | 31 +- .../de/uka/ilkd/key/logic/op/WarySubstOp.java | 14 +- .../uka/ilkd/key/logic/sort/AbstractSort.java | 22 +- .../de/uka/ilkd/key/logic/sort/ArraySort.java | 156 +- .../uka/ilkd/key/logic/sort/GenericSort.java | 149 +- .../logic/sort/GenericSupersortException.java | 23 +- .../de/uka/ilkd/key/logic/sort/NullSort.java | 153 +- .../ilkd/key/logic/sort/ProgramSVSort.java | 661 +- .../de/uka/ilkd/key/logic/sort/ProxySort.java | 5 +- .../java/de/uka/ilkd/key/logic/sort/Sort.java | 14 +- .../de/uka/ilkd/key/logic/sort/SortImpl.java | 30 +- .../uka/ilkd/key/logic/util/TermHelper.java | 47 +- .../key/macros/AbstractBlastingMacro.java | 15 +- .../ilkd/key/macros/AbstractProofMacro.java | 52 +- .../AbstractPropositionalExpansionMacro.java | 52 +- .../uka/ilkd/key/macros/AlternativeMacro.java | 42 +- .../de/uka/ilkd/key/macros/AutoMacro.java | 37 +- .../macros/AutoPilotPrepareProofMacro.java | 66 +- .../ilkd/key/macros/DoWhileFinallyMacro.java | 53 +- .../uka/ilkd/key/macros/FilterStrategy.java | 7 +- .../macros/FinishSymbolicExecutionMacro.java | 44 +- ...SymbolicExecutionUntilMergePointMacro.java | 237 +- .../key/macros/FullAutoPilotProofMacro.java | 23 +- .../FullPropositionalExpansionMacro.java | 25 +- .../key/macros/HeapSimplificationMacro.java | 241 +- .../macros/IntegerSimplificationMacro.java | 137 +- .../ilkd/key/macros/OneStepProofMacro.java | 25 +- ...repareInfFlowContractPreBranchesMacro.java | 70 +- .../de/uka/ilkd/key/macros/ProofMacro.java | 232 +- .../key/macros/ProofMacroFinishedInfo.java | 92 +- .../ilkd/key/macros/ProofMacroListener.java | 24 +- .../macros/PropositionalExpansionMacro.java | 19 +- ...ionalExpansionWithSimplificationMacro.java | 18 +- .../ilkd/key/macros/SMTPreparationMacro.java | 22 +- .../SequentialOnLastGoalProofMacro.java | 22 +- .../ilkd/key/macros/SequentialProofMacro.java | 51 +- .../de/uka/ilkd/key/macros/SkipMacro.java | 19 +- .../ilkd/key/macros/StrategyProofMacro.java | 69 +- .../macros/TranscendentalFloatSMTMacro.java | 11 +- .../de/uka/ilkd/key/macros/TryCloseMacro.java | 117 +- .../key/macros/UpdateSimplificationMacro.java | 108 +- .../ilkd/key/macros/WellDefinednessMacro.java | 43 +- .../key/macros/scripts/AbstractCommand.java | 9 +- .../key/macros/scripts/ActivateCommand.java | 14 +- .../ilkd/key/macros/scripts/AllCommand.java | 18 +- .../key/macros/scripts/AssertCommand.java | 22 +- .../key/macros/scripts/AssumeCommand.java | 23 +- .../ilkd/key/macros/scripts/AutoCommand.java | 71 +- .../ilkd/key/macros/scripts/AxiomCommand.java | 23 +- .../ilkd/key/macros/scripts/CutCommand.java | 23 +- .../ilkd/key/macros/scripts/EchoCommand.java | 6 +- .../ilkd/key/macros/scripts/EngineState.java | 73 +- .../ilkd/key/macros/scripts/ExitCommand.java | 13 +- .../FocusOnSelectionAndHideCommand.java | 119 +- .../ilkd/key/macros/scripts/HideCommand.java | 25 +- .../macros/scripts/InstantiateCommand.java | 124 +- .../key/macros/scripts/JavascriptCommand.java | 27 +- .../ilkd/key/macros/scripts/LeaveCommand.java | 7 +- .../ilkd/key/macros/scripts/LetCommand.java | 26 +- .../ilkd/key/macros/scripts/MacroCommand.java | 70 +- .../key/macros/scripts/NoArgumentCommand.java | 10 +- .../scripts/ProofAlreadyClosedException.java | 10 +- .../macros/scripts/ProofScriptCommand.java | 34 +- .../key/macros/scripts/ProofScriptEngine.java | 24 +- .../key/macros/scripts/RewriteCommand.java | 82 +- .../ilkd/key/macros/scripts/RuleCommand.java | 178 +- .../ilkd/key/macros/scripts/SMTCommand.java | 50 +- .../key/macros/scripts/SaveInstCommand.java | 46 +- .../macros/scripts/SaveNewNameCommand.java | 59 +- .../key/macros/scripts/SchemaVarCommand.java | 27 +- .../key/macros/scripts/ScriptCommand.java | 25 +- .../key/macros/scripts/ScriptException.java | 3 + .../key/macros/scripts/ScriptLineParser.java | 170 +- .../ilkd/key/macros/scripts/ScriptNode.java | 19 +- .../key/macros/scripts/ScriptTreeParser.java | 28 +- .../key/macros/scripts/SelectCommand.java | 49 +- .../ilkd/key/macros/scripts/SetCommand.java | 16 +- .../key/macros/scripts/SetEchoCommand.java | 17 +- .../scripts/SetFailOnClosedCommand.java | 14 +- .../ilkd/key/macros/scripts/SkipCommand.java | 10 +- .../key/macros/scripts/TryCloseCommand.java | 38 +- .../key/macros/scripts/UnhideCommand.java | 18 +- .../meta/ArgumentRequiredException.java | 4 + .../macros/scripts/meta/ArgumentsLifter.java | 23 +- .../scripts/meta/ConversionException.java | 11 +- .../scripts/meta/DescriptionFacade.java | 16 +- .../ilkd/key/macros/scripts/meta/Flag.java | 9 +- .../scripts/meta/InjectionException.java | 14 +- .../meta/InjectionReflectionException.java | 10 +- .../meta/NoSpecifiedConverterException.java | 19 +- .../ilkd/key/macros/scripts/meta/Option.java | 3 + .../scripts/meta/ProofScriptArgument.java | 7 +- .../macros/scripts/meta/StringConverter.java | 6 +- .../ilkd/key/macros/scripts/meta/Type.java | 3 + .../macros/scripts/meta/ValueInjector.java | 93 +- .../ilkd/key/macros/scripts/meta/Varargs.java | 4 + .../ilkd/key/macros/scripts/package-info.java | 2 +- .../ilkd/key/nparser/ChoiceInformation.java | 11 +- .../uka/ilkd/key/nparser/DebugKeyLexer.java | 29 +- .../java/de/uka/ilkd/key/nparser/KeyAst.java | 26 +- .../java/de/uka/ilkd/key/nparser/KeyIO.java | 37 +- .../uka/ilkd/key/nparser/ParsingFacade.java | 39 +- .../ilkd/key/nparser/ProblemInformation.java | 22 +- .../uka/ilkd/key/nparser/ProofReplayer.java | 104 +- .../key/nparser/builder/AbstractBuilder.java | 49 +- .../key/nparser/builder/BuilderHelpers.java | 13 +- .../key/nparser/builder/ChoiceFinder.java | 20 +- .../builder/ContractsAndInvariantsFinder.java | 7 +- .../nparser/builder/DeclarationBuilder.java | 42 +- .../key/nparser/builder/DefaultBuilder.java | 125 +- .../nparser/builder/ExpressionBuilder.java | 652 +- .../builder/FindProblemInformation.java | 13 +- .../builder/FunctionPredicateBuilder.java | 56 +- .../key/nparser/builder/IncludeFinder.java | 8 +- .../key/nparser/builder/ProblemFinder.java | 11 +- .../key/nparser/builder/TacletPBuilder.java | 177 +- .../varexp/AbstractConditionBuilder.java | 9 +- .../varexp/AbstractTacletBuilderCommand.java | 10 +- .../ilkd/key/nparser/varexp/ArgumentType.java | 13 +- .../key/nparser/varexp/ConditionBuilder.java | 14 +- .../varexp/ConstructorBasedBuilder.java | 16 +- .../nparser/varexp/TacletBuilderCommand.java | 32 +- .../varexp/TacletBuilderManipulators.java | 484 +- .../key/parser/AmbigiousDeclException.java | 46 +- .../ilkd/key/parser/DefaultTermParser.java | 74 +- .../ilkd/key/parser/GenericSortException.java | 60 +- .../de/uka/ilkd/key/parser/IdDeclaration.java | 22 +- .../ilkd/key/parser/InvalidFindException.java | 36 +- .../ilkd/key/parser/JavaParserException.java | 73 +- .../ilkd/key/parser/KeYSemanticException.java | 31 +- .../java/de/uka/ilkd/key/parser/Location.java | 28 +- .../uka/ilkd/key/parser/NotDeclException.java | 7 +- .../de/uka/ilkd/key/parser/ParserConfig.java | 27 +- .../uka/ilkd/key/parser/ParserException.java | 14 +- .../de/uka/ilkd/key/parser/ParserMode.java | 23 +- .../de/uka/ilkd/key/parser/ParserUtil.java | 14 +- .../key/parser/SchemaVariableModifierSet.java | 73 +- .../parser/UnfittingReplacewithException.java | 37 +- .../uka/ilkd/key/parser/WarningException.java | 39 +- .../de/uka/ilkd/key/pp/AbbrevException.java | 21 +- .../java/de/uka/ilkd/key/pp/AbbrevMap.java | 70 +- .../de/uka/ilkd/key/pp/CharListNotation.java | 88 +- .../java/de/uka/ilkd/key/pp/FieldPrinter.java | 69 +- .../ilkd/key/pp/HideSequentPrintFilter.java | 9 +- .../key/pp/IdentitySequentPrintFilter.java | 18 +- .../ilkd/key/pp/IllegalRegexException.java | 9 +- .../uka/ilkd/key/pp/InitialPositionTable.java | 158 +- .../java/de/uka/ilkd/key/pp/LogicPrinter.java | 645 +- .../ilkd/key/pp/ModalityPositionTable.java | 28 +- .../java/de/uka/ilkd/key/pp/Notation.java | 802 +- .../java/de/uka/ilkd/key/pp/NotationInfo.java | 565 +- .../java/de/uka/ilkd/key/pp/PosInSequent.java | 93 +- .../de/uka/ilkd/key/pp/PositionTable.java | 148 +- .../de/uka/ilkd/key/pp/ProgramPrinter.java | 15 +- .../main/java/de/uka/ilkd/key/pp/Range.java | 5 +- .../key/pp/RegroupSequentPrintFilter.java | 10 +- .../ilkd/key/pp/SearchSequentPrintFilter.java | 12 +- .../de/uka/ilkd/key/pp/SelectPrinter.java | 80 +- .../uka/ilkd/key/pp/SequentPrintFilter.java | 26 +- .../ilkd/key/pp/SequentPrintFilterEntry.java | 9 +- .../ilkd/key/pp/SequentViewLogicPrinter.java | 45 +- .../pp/ShowSelectedSequentPrintFilter.java | 9 +- .../java/de/uka/ilkd/key/pp/StorePrinter.java | 33 +- .../de/uka/ilkd/key/pp/VisibleTermLabels.java | 9 +- .../ilkd/key/proof/BuiltInRuleAppIndex.java | 167 +- .../uka/ilkd/key/proof/BuiltInRuleIndex.java | 30 +- .../de/uka/ilkd/key/proof/CompoundProof.java | 91 +- .../java/de/uka/ilkd/key/proof/Counter.java | 29 +- .../de/uka/ilkd/key/proof/FormulaTag.java | 18 +- .../uka/ilkd/key/proof/FormulaTagManager.java | 282 +- .../main/java/de/uka/ilkd/key/proof/Goal.java | 259 +- .../de/uka/ilkd/key/proof/GoalListener.java | 19 +- .../key/proof/ITermTacletAppIndexCache.java | 32 +- .../ilkd/key/proof/IfMismatchException.java | 11 +- .../ilkd/key/proof/InstantiationProposer.java | 19 +- .../InstantiationProposerCollection.java | 35 +- .../java/de/uka/ilkd/key/proof/JavaModel.java | 189 +- .../proof/MissingInstantiationException.java | 37 +- .../ilkd/key/proof/MissingSortException.java | 37 +- .../ilkd/key/proof/ModelChangeListener.java | 11 +- .../de/uka/ilkd/key/proof/ModelEvent.java | 9 +- .../key/proof/MultiThreadedTacletIndex.java | 93 +- .../de/uka/ilkd/key/proof/NameRecorder.java | 5 +- .../uka/ilkd/key/proof/NewRuleListener.java | 13 +- .../main/java/de/uka/ilkd/key/proof/Node.java | 101 +- .../java/de/uka/ilkd/key/proof/NodeInfo.java | 163 +- .../de/uka/ilkd/key/proof/NodeIterator.java | 7 +- .../ilkd/key/proof/NullNewRuleListener.java | 18 +- .../uka/ilkd/key/proof/ObserverWithType.java | 8 +- .../de/uka/ilkd/key/proof/OpReplacer.java | 167 +- .../proof/PrefixTermTacletAppIndexCache.java | 31 +- .../PrefixTermTacletAppIndexCacheImpl.java | 51 +- .../uka/ilkd/key/proof/ProgVarReplacer.java | 233 +- .../java/de/uka/ilkd/key/proof/Proof.java | 478 +- .../de/uka/ilkd/key/proof/ProofAggregate.java | 166 +- .../de/uka/ilkd/key/proof/ProofEvent.java | 32 +- .../key/proof/ProofJavaSourceCollection.java | 33 +- .../uka/ilkd/key/proof/ProofTreeAdapter.java | 101 +- .../de/uka/ilkd/key/proof/ProofTreeEvent.java | 69 +- .../uka/ilkd/key/proof/ProofTreeListener.java | 68 +- .../de/uka/ilkd/key/proof/ProofVisitor.java | 7 +- .../de/uka/ilkd/key/proof/ReplacementMap.java | 27 +- .../de/uka/ilkd/key/proof/RuleAppIndex.java | 503 +- .../uka/ilkd/key/proof/RuleAppListener.java | 5 +- .../key/proof/SVInstantiationException.java | 23 +- .../SVInstantiationExceptionWithPosition.java | 76 +- .../proof/SVInstantiationParserException.java | 41 +- .../ilkd/key/proof/SVRigidnessException.java | 36 +- .../key/proof/SemisequentTacletAppIndex.java | 324 +- .../de/uka/ilkd/key/proof/SingleProof.java | 49 +- .../key/proof/SingleThreadedTacletIndex.java | 43 +- .../ilkd/key/proof/SortMismatchException.java | 42 +- .../de/uka/ilkd/key/proof/Statistics.java | 139 +- .../key/proof/StrategyInfoUndoMethod.java | 3 + .../uka/ilkd/key/proof/SubtreeIterator.java | 10 +- .../de/uka/ilkd/key/proof/TacletAppIndex.java | 484 +- .../de/uka/ilkd/key/proof/TacletIndex.java | 780 +- .../de/uka/ilkd/key/proof/TacletIndexKit.java | 31 +- .../proof/TermProgramVariableCollector.java | 47 +- .../ilkd/key/proof/TermTacletAppIndex.java | 603 +- .../key/proof/TermTacletAppIndexCacheSet.java | 308 +- .../ilkd/key/proof/VariableNameProposer.java | 229 +- .../proof/delayedcut/ApplicationCheck.java | 54 +- .../ilkd/key/proof/delayedcut/DelayedCut.java | 22 +- .../proof/delayedcut/DelayedCutListener.java | 16 +- .../proof/delayedcut/DelayedCutProcessor.java | 211 +- .../key/proof/delayedcut/NodeGoalPair.java | 13 +- .../key/proof/event/ProofDisposedEvent.java | 41 +- .../proof/event/ProofDisposedListener.java | 28 +- .../key/proof/init/AbstractOperationPO.java | 691 +- .../uka/ilkd/key/proof/init/AbstractPO.java | 166 +- .../ilkd/key/proof/init/AbstractProfile.java | 242 +- .../uka/ilkd/key/proof/init/ContractPO.java | 9 +- .../proof/init/DefaultProfileResolver.java | 33 +- .../key/proof/init/DependencyContractPO.java | 433 +- .../proof/init/FunctionalBlockContractPO.java | 264 +- .../proof/init/FunctionalLoopContractPO.java | 220 +- .../init/FunctionalOperationContractPO.java | 251 +- .../ilkd/key/proof/init/IPersistablePO.java | 203 +- .../de/uka/ilkd/key/proof/init/Includes.java | 86 +- .../uka/ilkd/key/proof/init/InitConfig.java | 275 +- .../uka/ilkd/key/proof/init/JavaProfile.java | 166 +- .../JavaProfileDefaultProfileResolver.java | 32 +- ...WithPermissionsDefaultProfileResolver.java | 32 +- .../key/proof/init/KeYUserProblemFile.java | 98 +- .../uka/ilkd/key/proof/init/POExtension.java | 45 +- .../key/proof/init/ProblemInitializer.java | 213 +- .../de/uka/ilkd/key/proof/init/Profile.java | 80 +- .../key/proof/init/ProofInitServiceUtil.java | 211 +- .../key/proof/init/ProofInputException.java | 35 +- .../ilkd/key/proof/init/ProofOblInput.java | 23 +- .../key/proof/init/ProofObligationVars.java | 74 +- .../ilkd/key/proof/init/RuleCollection.java | 8 +- .../key/proof/init/WellDefinednessPO.java | 167 +- .../ilkd/key/proof/io/AbstractEnvInput.java | 85 +- .../key/proof/io/AbstractProblemLoader.java | 349 +- .../de/uka/ilkd/key/proof/io/AutoSaver.java | 104 +- .../key/proof/io/CountingBufferedReader.java | 78 +- .../de/uka/ilkd/key/proof/io/EnvInput.java | 43 +- .../uka/ilkd/key/proof/io/FileRuleSource.java | 12 +- .../ilkd/key/proof/io/GZipFileRuleSource.java | 22 +- .../uka/ilkd/key/proof/io/GZipProofSaver.java | 16 +- .../ilkd/key/proof/io/IProofFileParser.java | 46 +- ...termediatePresentationProofFileParser.java | 154 +- .../proof/io/IntermediateProofReplayer.java | 728 +- .../de/uka/ilkd/key/proof/io/KeYFile.java | 137 +- .../de/uka/ilkd/key/proof/io/LDTInput.java | 156 +- .../key/proof/io/OutputStreamProofSaver.java | 338 +- .../key/proof/io/ProblemLoaderControl.java | 52 +- .../key/proof/io/ProblemLoaderException.java | 15 +- .../ilkd/key/proof/io/ProofBundleSaver.java | 27 +- .../de/uka/ilkd/key/proof/io/ProofSaver.java | 173 +- .../de/uka/ilkd/key/proof/io/RuleSource.java | 10 +- .../ilkd/key/proof/io/RuleSourceFactory.java | 14 +- .../proof/io/SingleThreadProblemLoader.java | 56 +- .../uka/ilkd/key/proof/io/UrlRuleSource.java | 15 +- .../io/consistency/AbstractFileRepo.java | 117 +- .../proof/io/consistency/DiskFileRepo.java | 77 +- .../key/proof/io/consistency/FileRepo.java | 31 +- .../proof/io/consistency/MemoryFileRepo.java | 3 + .../proof/io/consistency/SimpleFileRepo.java | 33 +- .../proof/io/consistency/TrivialFileRepo.java | 8 +- .../key/proof/io/event/ProofSaverEvent.java | 109 +- .../proof/io/event/ProofSaverListener.java | 17 +- .../io/intermediate/AppIntermediate.java | 9 +- .../io/intermediate/AppNodeIntermediate.java | 10 +- .../intermediate/BranchNodeIntermediate.java | 19 +- .../intermediate/BuiltInAppIntermediate.java | 16 +- .../io/intermediate/MergeAppIntermediate.java | 72 +- .../MergePartnerAppIntermediate.java | 22 +- .../io/intermediate/NodeIntermediate.java | 22 +- .../intermediate/TacletAppIntermediate.java | 20 +- .../ilkd/key/proof/join/JoinIsApplicable.java | 65 +- .../ilkd/key/proof/join/JoinProcessor.java | 152 +- .../key/proof/join/LateApplicationCheck.java | 12 +- .../key/proof/join/PredicateEstimator.java | 46 +- .../key/proof/join/ProspectivePartner.java | 23 +- .../key/proof/mgt/AxiomJustification.java | 16 +- .../proof/mgt/ComplexRuleJustification.java | 12 +- .../mgt/ComplexRuleJustificationBySpec.java | 28 +- .../key/proof/mgt/LemmaJustification.java | 16 +- .../key/proof/mgt/ProofCorrectnessMgt.java | 382 +- .../ilkd/key/proof/mgt/ProofEnvironment.java | 285 +- .../key/proof/mgt/ProofEnvironmentEvent.java | 46 +- .../proof/mgt/ProofEnvironmentListener.java | 12 +- .../uka/ilkd/key/proof/mgt/ProofStatus.java | 25 +- .../ilkd/key/proof/mgt/RuleJustification.java | 5 +- .../mgt/RuleJustificationByAddRules.java | 38 +- .../proof/mgt/RuleJustificationBySpec.java | 23 +- .../key/proof/mgt/RuleJustificationInfo.java | 14 +- .../proof/mgt/SpecificationRepository.java | 962 +- .../ilkd/key/proof/proofevent/NodeChange.java | 6 +- .../proof/proofevent/NodeChangeARFormula.java | 20 +- .../proofevent/NodeChangeAddFormula.java | 22 +- .../proof/proofevent/NodeChangeJournal.java | 117 +- .../proofevent/NodeChangeRemoveFormula.java | 20 +- .../proof/proofevent/NodeChangesHolder.java | 21 +- .../proofevent/NodeRedundantAddChange.java | 26 +- .../key/proof/proofevent/NodeReplacement.java | 266 +- .../key/proof/proofevent/RuleAppInfo.java | 59 +- .../key/proof/rulefilter/AndRuleFilter.java | 17 +- .../rulefilter/AnyRuleSetTacletFilter.java | 21 +- .../key/proof/rulefilter/ClassRuleFilter.java | 15 +- .../key/proof/rulefilter/IHTacletFilter.java | 50 +- .../key/proof/rulefilter/NotRuleFilter.java | 17 +- .../ilkd/key/proof/rulefilter/RuleFilter.java | 13 +- .../key/proof/rulefilter/SetRuleFilter.java | 15 +- .../key/proof/rulefilter/TacletFilter.java | 31 +- .../rulefilter/TacletFilterCloseGoal.java | 21 +- .../rulefilter/TacletFilterSplitGoal.java | 20 +- .../de/uka/ilkd/key/prover/GoalChooser.java | 21 +- .../ilkd/key/prover/GoalChooserBuilder.java | 10 +- .../de/uka/ilkd/key/prover/ProverCore.java | 48 +- .../ilkd/key/prover/ProverTaskListener.java | 33 +- .../de/uka/ilkd/key/prover/StopCondition.java | 129 +- .../uka/ilkd/key/prover/TaskFinishedInfo.java | 12 +- .../uka/ilkd/key/prover/TaskStartedInfo.java | 52 +- .../key/prover/impl/AbstractProverCore.java | 26 +- .../prover/impl/AppliedRuleStopCondition.java | 50 +- .../ilkd/key/prover/impl/ApplyStrategy.java | 236 +- .../key/prover/impl/ApplyStrategyInfo.java | 20 +- .../key/prover/impl/DefaultGoalChooser.java | 304 +- .../impl/DefaultGoalChooserBuilder.java | 19 +- .../prover/impl/DefaultTaskFinishedInfo.java | 37 +- .../prover/impl/DefaultTaskStartedInfo.java | 87 +- .../prover/impl/DepthFirstGoalChooser.java | 85 +- .../impl/DepthFirstGoalChooserBuilder.java | 21 +- .../impl/SingleRuleApplicationInfo.java | 9 +- ...stractAuxiliaryContractBuiltInRuleApp.java | 25 +- .../rule/AbstractAuxiliaryContractRule.java | 95 +- .../AbstractBlockContractBuiltInRuleApp.java | 37 +- .../key/rule/AbstractBlockContractRule.java | 179 +- .../ilkd/key/rule/AbstractBuiltInRuleApp.java | 95 +- .../key/rule/AbstractContractRuleApp.java | 26 +- .../AbstractLoopContractBuiltInRuleApp.java | 47 +- .../key/rule/AbstractLoopContractRule.java | 99 +- .../key/rule/AbstractLoopInvariantRule.java | 540 +- .../ilkd/key/rule/AbstractProgramElement.java | 5 +- .../de/uka/ilkd/key/rule/AntecTaclet.java | 79 +- .../key/rule/AuxiliaryContractBuilders.java | 723 +- .../BlockContractExternalBuiltInRuleApp.java | 38 +- .../key/rule/BlockContractExternalRule.java | 114 +- .../BlockContractInternalBuiltInRuleApp.java | 27 +- .../key/rule/BlockContractInternalRule.java | 225 +- .../ilkd/key/rule/BoundUniquenessChecker.java | 66 +- .../de/uka/ilkd/key/rule/BuiltInRule.java | 16 +- .../de/uka/ilkd/key/rule/ContractRuleApp.java | 97 +- .../ilkd/key/rule/DefaultBuiltInRuleApp.java | 21 +- .../java/de/uka/ilkd/key/rule/FindTaclet.java | 202 +- .../java/de/uka/ilkd/key/rule/HasOrigin.java | 3 + .../de/uka/ilkd/key/rule/IBuiltInRuleApp.java | 20 +- .../ilkd/key/rule/IfFormulaInstDirect.java | 46 +- .../uka/ilkd/key/rule/IfFormulaInstSeq.java | 72 +- .../ilkd/key/rule/IfFormulaInstantiation.java | 13 +- .../key/rule/IfFormulaInstantiationCache.java | 18 +- .../de/uka/ilkd/key/rule/IfMatchResult.java | 30 +- .../key/rule/JmlAssertBuiltInRuleApp.java | 15 +- .../de/uka/ilkd/key/rule/JmlAssertRule.java | 28 +- .../LightweightSyntacticalReplaceVisitor.java | 128 +- .../key/rule/LoopApplyHeadBuiltInRuleApp.java | 18 +- .../uka/ilkd/key/rule/LoopApplyHeadRule.java | 25 +- .../LoopContractExternalBuiltInRuleApp.java | 27 +- .../key/rule/LoopContractExternalRule.java | 124 +- .../LoopContractInternalBuiltInRuleApp.java | 38 +- .../key/rule/LoopContractInternalRule.java | 212 +- .../key/rule/LoopInvariantBuiltInRuleApp.java | 332 +- .../ilkd/key/rule/LoopScopeInvariantRule.java | 430 +- .../de/uka/ilkd/key/rule/MatchConditions.java | 53 +- .../de/uka/ilkd/key/rule/NewDependingOn.java | 65 +- .../java/de/uka/ilkd/key/rule/NewVarcond.java | 40 +- .../de/uka/ilkd/key/rule/NoFindTaclet.java | 72 +- .../de/uka/ilkd/key/rule/NoPosTacletApp.java | 500 +- .../java/de/uka/ilkd/key/rule/NotFreeIn.java | 61 +- .../uka/ilkd/key/rule/OneStepSimplifier.java | 648 +- .../key/rule/OneStepSimplifierRuleApp.java | 7 +- .../de/uka/ilkd/key/rule/PosTacletApp.java | 392 +- .../de/uka/ilkd/key/rule/QueryExpand.java | 282 +- .../de/uka/ilkd/key/rule/RewriteTaclet.java | 316 +- .../main/java/de/uka/ilkd/key/rule/Rule.java | 33 +- .../uka/ilkd/key/rule/RuleAbortException.java | 13 +- .../java/de/uka/ilkd/key/rule/RuleApp.java | 23 +- .../java/de/uka/ilkd/key/rule/RuleKey.java | 83 +- .../java/de/uka/ilkd/key/rule/RuleSet.java | 39 +- .../rule/SVNameCorrespondenceCollector.java | 120 +- .../java/de/uka/ilkd/key/rule/SuccTaclet.java | 84 +- .../key/rule/SyntacticalReplaceVisitor.java | 281 +- .../java/de/uka/ilkd/key/rule/Taclet.java | 1140 +-- .../uka/ilkd/key/rule/TacletAnnotation.java | 9 +- .../java/de/uka/ilkd/key/rule/TacletApp.java | 1502 ++- .../de/uka/ilkd/key/rule/TacletApplPart.java | 69 +- .../uka/ilkd/key/rule/TacletAttributes.java | 31 +- .../de/uka/ilkd/key/rule/TacletMatcher.java | 199 +- .../de/uka/ilkd/key/rule/TacletPrefix.java | 98 +- .../rule/TacletSchemaVariableCollector.java | 194 +- .../key/rule/TacletVariableSVCollector.java | 47 +- .../java/de/uka/ilkd/key/rule/Trigger.java | 8 +- .../rule/UninstantiatedNoPosTacletApp.java | 32 +- .../key/rule/UseDependencyContractApp.java | 102 +- .../key/rule/UseDependencyContractRule.java | 284 +- .../key/rule/UseOperationContractRule.java | 494 +- .../uka/ilkd/key/rule/VariableCondition.java | 35 +- .../key/rule/VariableConditionAdapter.java | 37 +- .../uka/ilkd/key/rule/WhileInvariantRule.java | 768 +- .../conditions/AbstractOrInterfaceType.java | 43 +- .../AlternativeVariableCondition.java | 29 +- .../ApplyUpdateOnRigidCondition.java | 97 +- .../ArrayComponentTypeCondition.java | 84 +- .../rule/conditions/ArrayLengthCondition.java | 42 +- .../rule/conditions/ArrayTypeCondition.java | 72 +- .../rule/conditions/ConstantCondition.java | 27 +- .../ContainsAssignmentCondition.java | 59 +- .../key/rule/conditions/DifferentFields.java | 59 +- .../DifferentInstantiationCondition.java | 49 +- .../DropEffectlessElementariesCondition.java | 180 +- .../DropEffectlessStoresCondition.java | 160 +- .../conditions/EnumConstantCondition.java | 36 +- .../rule/conditions/EnumTypeCondition.java | 27 +- .../rule/conditions/EqualUniqueCondition.java | 92 +- .../conditions/FieldTypeToSortCondition.java | 74 +- .../conditions/FinalReferenceCondition.java | 41 +- .../FreeLabelInVariableCondition.java | 44 +- .../conditions/HasLoopInvariantCondition.java | 37 +- .../ilkd/key/rule/conditions/InStrictFp.java | 66 +- .../rule/conditions/IsLabeledCondition.java | 9 +- .../key/rule/conditions/IsThisReference.java | 36 +- .../conditions/JavaTypeToSortCondition.java | 94 +- .../conditions/LocalVariableCondition.java | 33 +- .../LoopFreeInvariantCondition.java | 41 +- .../conditions/LoopInvariantCondition.java | 42 +- .../rule/conditions/LoopVariantCondition.java | 9 +- .../conditions/MayExpandMethodCondition.java | 69 +- .../conditions/MetaDisjointCondition.java | 124 +- .../conditions/NewJumpLabelCondition.java | 79 +- .../rule/conditions/ObserverCondition.java | 59 +- .../conditions/SameObserverCondition.java | 47 +- .../SimplifyIfThenElseUpdateCondition.java | 183 +- .../rule/conditions/StaticFieldCondition.java | 26 +- .../conditions/StaticMethodCondition.java | 121 +- .../conditions/StaticReferenceCondition.java | 61 +- .../rule/conditions/StoreStmtInCondition.java | 18 +- .../rule/conditions/StoreTermInCondition.java | 8 +- .../rule/conditions/SubFormulaCondition.java | 21 +- .../rule/conditions/TermLabelCondition.java | 20 +- .../conditions/TypeComparisonCondition.java | 148 +- .../key/rule/conditions/TypeCondition.java | 75 +- .../key/rule/conditions/TypeResolver.java | 196 +- .../ilkd/key/rule/executor/RuleExecutor.java | 15 +- .../executor/javadl/AntecTacletExecutor.java | 52 +- .../executor/javadl/FindTacletExecutor.java | 109 +- .../executor/javadl/NoFindTacletExecutor.java | 92 +- .../javadl/RewriteTacletExecutor.java | 145 +- .../executor/javadl/SuccTacletExecutor.java | 44 +- .../rule/executor/javadl/TacletExecutor.java | 456 +- .../rule/inst/ContextInstantiationEntry.java | 73 +- .../ContextStatementBlockInstantiation.java | 115 +- .../key/rule/inst/GenericSortCondition.java | 334 +- .../key/rule/inst/GenericSortException.java | 42 +- .../rule/inst/GenericSortInstantiations.java | 930 +- .../inst/IllegalInstantiationException.java | 16 +- .../key/rule/inst/InstantiationEntry.java | 31 +- .../ilkd/key/rule/inst/ListInstantiation.java | 15 +- .../key/rule/inst/NameInstantiationEntry.java | 11 +- .../key/rule/inst/OperatorInstantiation.java | 17 +- .../key/rule/inst/ProgramInstantiation.java | 18 +- .../uka/ilkd/key/rule/inst/ProgramList.java | 19 +- .../rule/inst/ProgramListInstantiation.java | 19 +- .../ilkd/key/rule/inst/ProgramSVEntry.java | 84 +- .../key/rule/inst/ProgramSVInstantiation.java | 188 +- .../key/rule/inst/RigidnessException.java | 17 +- .../ilkd/key/rule/inst/SVInstantiations.java | 693 +- .../uka/ilkd/key/rule/inst/SortException.java | 18 +- .../key/rule/inst/TacletInstantiations.java | 31 +- .../ilkd/key/rule/inst/TermInstantiation.java | 33 +- .../inst/TermLabelInstantiationEntry.java | 9 +- .../key/rule/label/ChildTermLabelPolicy.java | 161 +- .../key/rule/label/OriginTermLabelPolicy.java | 7 +- .../label/OriginTermLabelRefactoring.java | 26 +- .../rule/label/PerpetualTermLabelPolicy.java | 3 + .../ilkd/key/rule/label/RuleSpecificTask.java | 23 +- .../label/StayOnOperatorTermLabelPolicy.java | 42 +- .../ilkd/key/rule/label/TermLabelMerger.java | 49 +- .../ilkd/key/rule/label/TermLabelPolicy.java | 84 +- .../key/rule/label/TermLabelRefactoring.java | 104 +- .../ilkd/key/rule/label/TermLabelUpdate.java | 62 +- .../ilkd/key/rule/match/TacletMatcherKit.java | 33 +- .../key/rule/match/legacy/ElementMatcher.java | 177 +- .../match/legacy/LegacyTacletMatcher.java | 315 +- .../key/rule/match/vm/TacletMatchProgram.java | 118 +- .../ilkd/key/rule/match/vm/TermNavigator.java | 129 +- .../key/rule/match/vm/VMTacletMatcher.java | 264 +- .../BindVariablesInstruction.java | 69 +- .../match/vm/instructions/Instruction.java | 36 +- .../MatchElementaryUpdateInstruction.java | 24 +- .../MatchFormulaSVInstruction.java | 9 +- .../vm/instructions/MatchInstruction.java | 11 +- .../MatchModalOperatorSVInstruction.java | 18 +- .../MatchOpIdentityInstruction.java | 29 +- .../MatchOperatorInstruction.java | 8 +- .../instructions/MatchProgramInstruction.java | 9 +- .../MatchProgramSVInstruction.java | 55 +- .../MatchSchemaVariableInstruction.java | 50 +- ...MatchSortDependingFunctionInstruction.java | 88 +- .../MatchTermLabelInstruction.java | 26 +- .../instructions/MatchTermSVInstruction.java | 9 +- .../MatchUpdateSVInstruction.java | 5 +- .../MatchVariableSVInstruction.java | 11 +- .../UnbindVariablesInstruction.java | 7 +- .../ilkd/key/rule/merge/CloseAfterMerge.java | 204 +- .../CloseAfterMergeRuleBuiltInRuleApp.java | 17 +- .../uka/ilkd/key/rule/merge/MergePartner.java | 14 +- .../ilkd/key/rule/merge/MergeProcedure.java | 92 +- .../de/uka/ilkd/key/rule/merge/MergeRule.java | 398 +- .../rule/merge/MergeRuleBuiltInRuleApp.java | 66 +- .../merge/procedures/MergeByIfThenElse.java | 223 +- .../procedures/MergeIfThenElseAntecedent.java | 97 +- .../merge/procedures/MergeTotalWeakening.java | 28 +- .../MergeWithLatticeAbstraction.java | 96 +- .../MergeWithPredicateAbstraction.java | 96 +- .../MergeWithPredicateAbstractionFactory.java | 37 +- .../procedures/ParametricMergeProcedure.java | 7 +- .../UnparametricMergeProcedure.java | 7 +- .../ilkd/key/rule/metaconstruct/AddCast.java | 23 +- .../metaconstruct/ArrayBaseInstanceOf.java | 32 +- .../key/rule/metaconstruct/ArrayLength.java | 12 +- .../key/rule/metaconstruct/ArrayPostDecl.java | 19 +- .../rule/metaconstruct/BreakToBeReplaced.java | 24 +- .../key/rule/metaconstruct/ConstantValue.java | 28 +- .../rule/metaconstruct/ConstructorCall.java | 95 +- .../metaconstruct/CreateBeforeLoopUpdate.java | 74 +- .../rule/metaconstruct/CreateFrameCond.java | 95 +- .../metaconstruct/CreateHeapAnonUpdate.java | 28 +- .../metaconstruct/CreateLocalAnonUpdate.java | 16 +- .../key/rule/metaconstruct/CreateObject.java | 28 +- .../metaconstruct/CreateWellformedCond.java | 42 +- .../ilkd/key/rule/metaconstruct/DoBreak.java | 35 +- .../metaconstruct/EnhancedForElimination.java | 163 +- .../rule/metaconstruct/EnumConstantValue.java | 46 +- .../key/rule/metaconstruct/EvaluateArgs.java | 53 +- .../rule/metaconstruct/ExpandMethodBody.java | 23 +- .../ExpandQueriesMetaConstruct.java | 75 +- .../ForInitUnfoldTransformer.java | 19 +- .../key/rule/metaconstruct/ForToWhile.java | 36 +- .../ForToWhileTransformation.java | 70 +- .../key/rule/metaconstruct/InitArray.java | 189 +- .../rule/metaconstruct/InitArrayCreation.java | 152 +- .../rule/metaconstruct/IntroAtPreDefsOp.java | 144 +- .../ilkd/key/rule/metaconstruct/IsStatic.java | 12 +- .../rule/metaconstruct/MemberPVToField.java | 42 +- .../key/rule/metaconstruct/MethodCall.java | 279 +- .../rule/metaconstruct/MultipleVarDecl.java | 31 +- .../ObserverEqualityMetaConstruct.java | 115 +- .../ilkd/key/rule/metaconstruct/PostWork.java | 29 +- .../metaconstruct/ProgramTransformer.java | 199 +- .../metaconstruct/ReattachLoopInvariant.java | 24 +- .../rule/metaconstruct/ReplaceWhileLoop.java | 108 +- .../metaconstruct/SpecialConstructorCall.java | 25 +- .../metaconstruct/StaticInitialisation.java | 32 +- .../key/rule/metaconstruct/SwitchToIf.java | 72 +- .../ilkd/key/rule/metaconstruct/TypeOf.java | 13 +- .../ilkd/key/rule/metaconstruct/Unpack.java | 20 +- .../key/rule/metaconstruct/UnwindLoop.java | 31 +- .../WhileInvariantTransformation.java | 238 +- .../WhileInvariantTransformer.java | 395 +- .../WhileLoopTransformation.java | 516 +- .../arith/DivideLCRMonomials.java | 23 +- .../metaconstruct/arith/DivideMonomials.java | 21 +- .../key/rule/metaconstruct/arith/MetaAdd.java | 5 +- .../arith/MetaArithBitMaskOp.java | 43 +- .../metaconstruct/arith/MetaBinaryAnd.java | 17 +- .../metaconstruct/arith/MetaBinaryOr.java | 17 +- .../metaconstruct/arith/MetaBinaryXOr.java | 17 +- .../key/rule/metaconstruct/arith/MetaDiv.java | 92 +- .../rule/metaconstruct/arith/MetaEqual.java | 37 +- .../key/rule/metaconstruct/arith/MetaGeq.java | 35 +- .../rule/metaconstruct/arith/MetaGreater.java | 37 +- .../key/rule/metaconstruct/arith/MetaLeq.java | 35 +- .../rule/metaconstruct/arith/MetaLess.java | 35 +- .../key/rule/metaconstruct/arith/MetaMul.java | 27 +- .../key/rule/metaconstruct/arith/MetaPow.java | 36 +- .../rule/metaconstruct/arith/MetaShift.java | 72 +- .../metaconstruct/arith/MetaShiftLeft.java | 17 +- .../metaconstruct/arith/MetaShiftRight.java | 17 +- .../key/rule/metaconstruct/arith/MetaSub.java | 29 +- .../rule/metaconstruct/arith/Monomial.java | 239 +- .../rule/metaconstruct/arith/Polynomial.java | 19 +- .../AntecSuccTacletGoalTemplate.java | 89 +- .../tacletbuilder/AntecTacletBuilder.java | 128 +- .../rule/tacletbuilder/FindTacletBuilder.java | 38 +- .../tacletbuilder/NoFindTacletBuilder.java | 102 +- .../tacletbuilder/RewriteTacletBuilder.java | 157 +- ...ewriteTacletBuilderSchemaVarCollector.java | 12 +- .../RewriteTacletGoalTemplate.java | 93 +- .../rule/tacletbuilder/SuccTacletBuilder.java | 126 +- .../key/rule/tacletbuilder/TacletBuilder.java | 316 +- .../rule/tacletbuilder/TacletGenerator.java | 825 +- .../tacletbuilder/TacletGoalTemplate.java | 193 +- .../tacletbuilder/TacletPrefixBuilder.java | 94 +- .../settings/AbstractPropertiesSettings.java | 31 +- .../uka/ilkd/key/settings/ChoiceSettings.java | 272 +- .../ilkd/key/settings/DefaultSMTSettings.java | 11 +- .../ilkd/key/settings/GeneralSettings.java | 79 +- .../key/settings/LemmaGeneratorSettings.java | 99 +- .../settings/NewSMTTranslationSettings.java | 33 +- .../de/uka/ilkd/key/settings/PathConfig.java | 33 +- .../settings/ProofDependentSMTSettings.java | 222 +- .../settings/ProofIndependentSMTSettings.java | 44 +- .../settings/ProofIndependentSettings.java | 19 +- .../uka/ilkd/key/settings/ProofSettings.java | 29 +- .../de/uka/ilkd/key/settings/Settings.java | 35 +- .../ilkd/key/settings/SettingsConverter.java | 29 +- .../ilkd/key/settings/SettingsListener.java | 18 +- .../ilkd/key/settings/StrategySettings.java | 269 +- .../ilkd/key/settings/TermLabelSettings.java | 12 +- .../uka/ilkd/key/settings/ViewSettings.java | 79 +- .../ilkd/key/smt/AbstractSMTTranslator.java | 5055 +++++----- .../ilkd/key/smt/AccumulatedException.java | 108 +- .../de/uka/ilkd/key/smt/ContextualBlock.java | 110 +- .../ilkd/key/smt/IllegalFormulaException.java | 9 +- .../ilkd/key/smt/IllegalNumberException.java | 9 +- .../ilkd/key/smt/IllegalResultException.java | 15 +- .../de/uka/ilkd/key/smt/ModelExtractor.java | 90 +- .../uka/ilkd/key/smt/NumberTranslation.java | 82 +- .../de/uka/ilkd/key/smt/OverflowChecker.java | 87 +- .../ilkd/key/smt/ProblemTypeInformation.java | 321 +- .../java/de/uka/ilkd/key/smt/RuleAppSMT.java | 159 +- .../de/uka/ilkd/key/smt/SMTBeautifier.java | 98 +- .../de/uka/ilkd/key/smt/SMTObjTranslator.java | 392 +- .../java/de/uka/ilkd/key/smt/SMTProblem.java | 275 +- .../java/de/uka/ilkd/key/smt/SMTSettings.java | 66 +- .../java/de/uka/ilkd/key/smt/SMTSolver.java | 90 +- .../ilkd/key/smt/SMTSolverImplementation.java | 78 +- .../de/uka/ilkd/key/smt/SMTSolverResult.java | 82 +- .../ilkd/key/smt/SMTTranslationException.java | 40 +- .../de/uka/ilkd/key/smt/SMTTranslator.java | 15 +- .../uka/ilkd/key/smt/SmtLib2Translator.java | 165 +- .../de/uka/ilkd/key/smt/SolverException.java | 67 +- .../de/uka/ilkd/key/smt/SolverLauncher.java | 142 +- .../ilkd/key/smt/SolverLauncherListener.java | 12 +- .../de/uka/ilkd/key/smt/SolverListener.java | 3 + .../de/uka/ilkd/key/smt/SolverTimeout.java | 33 +- .../ilkd/key/smt/SolverTypeCollection.java | 117 +- .../de/uka/ilkd/key/smt/SortHierarchy.java | 29 +- .../de/uka/ilkd/key/smt/VersionChecker.java | 12 +- .../communication/AbstractSolverSocket.java | 26 +- .../communication/BufferedMessageReader.java | 24 +- .../key/smt/communication/CVC4Socket.java | 9 +- .../key/smt/communication/CVC5Socket.java | 9 +- .../ExternalProcessLauncher.java | 25 +- .../key/smt/communication/LegacyPipe.java | 28 +- .../uka/ilkd/key/smt/communication/Pipe.java | 16 +- .../key/smt/communication/SimplePipe.java | 45 +- .../communication/SolverCommunication.java | 33 +- .../ilkd/key/smt/communication/TeeReader.java | 3 + .../ilkd/key/smt/communication/TeeWriter.java | 3 + .../key/smt/communication/Z3CESocket.java | 83 +- .../ilkd/key/smt/communication/Z3Socket.java | 63 +- .../key/smt/communication/package-info.java | 22 +- .../uka/ilkd/key/smt/hierarchy/SortNode.java | 5 +- .../ilkd/key/smt/hierarchy/TypeHierarchy.java | 39 +- .../de/uka/ilkd/key/smt/lang/SMTFile.java | 476 +- .../de/uka/ilkd/key/smt/lang/SMTFunction.java | 229 +- .../uka/ilkd/key/smt/lang/SMTFunctionDef.java | 191 +- .../de/uka/ilkd/key/smt/lang/SMTSort.java | 437 +- .../de/uka/ilkd/key/smt/lang/SMTTerm.java | 1559 ++-- .../uka/ilkd/key/smt/lang/SMTTermBinOp.java | 984 +- .../de/uka/ilkd/key/smt/lang/SMTTermCall.java | 623 +- .../de/uka/ilkd/key/smt/lang/SMTTermITE.java | 297 +- .../uka/ilkd/key/smt/lang/SMTTermMultOp.java | 748 +- .../uka/ilkd/key/smt/lang/SMTTermNumber.java | 373 +- .../uka/ilkd/key/smt/lang/SMTTermQuant.java | 842 +- .../uka/ilkd/key/smt/lang/SMTTermUnaryOp.java | 400 +- .../ilkd/key/smt/lang/SMTTermVariable.java | 330 +- .../de/uka/ilkd/key/smt/lang/SMTTerms.java | 289 +- .../java/de/uka/ilkd/key/smt/lang/Util.java | 42 +- .../java/de/uka/ilkd/key/smt/model/Heap.java | 156 +- .../de/uka/ilkd/key/smt/model/Location.java | 83 +- .../uka/ilkd/key/smt/model/LocationSet.java | 181 +- .../java/de/uka/ilkd/key/smt/model/Model.java | 217 +- .../de/uka/ilkd/key/smt/model/ObjectVal.java | 55 +- .../de/uka/ilkd/key/smt/model/Sequence.java | 100 +- .../smt/newsmt2/BooleanConnectiveHandler.java | 8 +- .../uka/ilkd/key/smt/newsmt2/CastHandler.java | 9 +- .../smt/newsmt2/CastingFunctionsHandler.java | 6 +- .../smt/newsmt2/DefinedSymbolsHandler.java | 80 +- .../key/smt/newsmt2/FieldConstantHandler.java | 36 +- .../ilkd/key/smt/newsmt2/FloatHandler.java | 57 +- .../smt/newsmt2/FloatRemainderHandler.java | 15 +- .../uka/ilkd/key/smt/newsmt2/HandlerUtil.java | 81 +- .../key/smt/newsmt2/InstanceOfHandler.java | 10 +- .../key/smt/newsmt2/IntegerOpHandler.java | 21 +- .../smt/newsmt2/LogicalVariableHandler.java | 9 +- .../ilkd/key/smt/newsmt2/MasterHandler.java | 104 +- .../smt/newsmt2/ModularSMTLib2Translator.java | 61 +- .../smt/newsmt2/NumberConstantsHandler.java | 8 +- .../ilkd/key/smt/newsmt2/PatternHandler.java | 119 +- .../key/smt/newsmt2/PolymorphicHandler.java | 12 +- .../key/smt/newsmt2/QuantifierHandler.java | 28 +- .../de/uka/ilkd/key/smt/newsmt2/SExpr.java | 50 +- .../de/uka/ilkd/key/smt/newsmt2/SExprs.java | 94 +- .../key/smt/newsmt2/SMTFunctionsHandler.java | 247 +- .../uka/ilkd/key/smt/newsmt2/SMTHandler.java | 88 +- .../key/smt/newsmt2/SMTHandlerProperty.java | 59 +- .../newsmt2/SMTHandlerPropertyVisitor.java | 5 +- .../key/smt/newsmt2/SMTHandlerServices.java | 118 +- .../key/smt/newsmt2/SMTTacletTranslator.java | 43 +- .../ilkd/key/smt/newsmt2/SeqDefHandler.java | 56 +- .../ilkd/key/smt/newsmt2/SumProdHandler.java | 14 +- .../uka/ilkd/key/smt/newsmt2/TypeManager.java | 55 +- .../newsmt2/UninterpretedSymbolsHandler.java | 17 +- .../ilkd/key/smt/newsmt2/UpdateHandler.java | 7 +- .../uka/ilkd/key/smt/newsmt2/VerbatimSMT.java | 16 +- .../de/uka/ilkd/key/smt/newsmt2/Writable.java | 10 +- .../solvertypes/SolverPropertiesLoader.java | 77 +- .../ilkd/key/smt/solvertypes/SolverType.java | 62 +- .../solvertypes/SolverTypeImplementation.java | 117 +- .../ilkd/key/smt/solvertypes/SolverTypes.java | 30 +- .../AbstractAuxiliaryContractImpl.java | 542 +- .../ilkd/key/speclang/AuxiliaryContract.java | 583 +- .../uka/ilkd/key/speclang/BlockContract.java | 32 +- .../ilkd/key/speclang/BlockContractImpl.java | 220 +- .../key/speclang/BlockWellDefinedness.java | 59 +- .../de/uka/ilkd/key/speclang/ClassAxiom.java | 41 +- .../uka/ilkd/key/speclang/ClassAxiomImpl.java | 83 +- .../uka/ilkd/key/speclang/ClassInvariant.java | 27 +- .../ilkd/key/speclang/ClassInvariantImpl.java | 92 +- .../key/speclang/ClassWellDefinedness.java | 65 +- .../de/uka/ilkd/key/speclang/Contract.java | 28 +- .../uka/ilkd/key/speclang/ContractAxiom.java | 107 +- .../ilkd/key/speclang/ContractFactory.java | 628 +- .../ilkd/key/speclang/DependencyContract.java | 9 +- .../key/speclang/DependencyContractImpl.java | 337 +- .../speclang/FunctionalAuxiliaryContract.java | 37 +- .../key/speclang/FunctionalBlockContract.java | 12 +- .../key/speclang/FunctionalLoopContract.java | 17 +- .../speclang/FunctionalOperationContract.java | 159 +- .../FunctionalOperationContractImpl.java | 941 +- .../de/uka/ilkd/key/speclang/HeapContext.java | 72 +- .../key/speclang/InformationFlowContract.java | 26 +- .../speclang/InformationFlowContractImpl.java | 423 +- .../ilkd/key/speclang/InitiallyClause.java | 8 +- .../key/speclang/InitiallyClauseImpl.java | 69 +- .../uka/ilkd/key/speclang/LoopContract.java | 81 +- .../ilkd/key/speclang/LoopContractImpl.java | 675 +- .../uka/ilkd/key/speclang/LoopSpecImpl.java | 278 +- .../ilkd/key/speclang/LoopSpecification.java | 163 +- .../key/speclang/LoopWellDefinedness.java | 58 +- .../uka/ilkd/key/speclang/MergeContract.java | 3 + .../key/speclang/MethodWellDefinedness.java | 233 +- .../key/speclang/ModelMethodExecution.java | 57 +- .../ilkd/key/speclang/OperationContract.java | 56 +- .../ilkd/key/speclang/PartialInvAxiom.java | 118 +- .../key/speclang/PositionedLabeledString.java | 90 +- .../ilkd/key/speclang/PositionedString.java | 26 +- .../PredicateAbstractionMergeContract.java | 29 +- .../de/uka/ilkd/key/speclang/QueryAxiom.java | 159 +- .../uka/ilkd/key/speclang/ReplacementMap.java | 34 +- .../ilkd/key/speclang/RepresentsAxiom.java | 138 +- .../de/uka/ilkd/key/speclang/SLEnvInput.java | 176 +- .../uka/ilkd/key/speclang/SpecExtractor.java | 70 +- .../key/speclang/SpecificationElement.java | 13 +- .../speclang/StatementWellDefinedness.java | 90 +- .../ilkd/key/speclang/TermReplacementMap.java | 5 + .../UnparameterizedMergeContract.java | 11 +- .../key/speclang/VariableReplacementMap.java | 4 + .../key/speclang/WellDefinednessCheck.java | 605 +- .../dl/translation/DLSpecFactory.java | 470 +- .../key/speclang/jml/JMLInfoExtractor.java | 281 +- .../key/speclang/jml/JMLSpecExtractor.java | 325 +- .../uka/ilkd/key/speclang/jml/JMLUtils.java | 30 +- .../speclang/jml/pretranslation/Behavior.java | 17 +- .../TextualJMLAssertStatement.java | 13 +- .../pretranslation/TextualJMLClassAxiom.java | 17 +- .../pretranslation/TextualJMLClassInv.java | 8 +- .../pretranslation/TextualJMLConstruct.java | 19 +- .../jml/pretranslation/TextualJMLDepends.java | 12 +- .../pretranslation/TextualJMLFieldDecl.java | 32 +- .../pretranslation/TextualJMLInitially.java | 18 +- .../pretranslation/TextualJMLLoopSpec.java | 104 +- .../TextualJMLMergePointDecl.java | 22 +- .../pretranslation/TextualJMLMethodDecl.java | 39 +- .../pretranslation/TextualJMLRepresents.java | 8 +- .../TextualJMLSetStatement.java | 31 +- .../pretranslation/TextualJMLSpecCase.java | 77 +- .../JMLBuiltInPropertyResolver.java | 17 +- .../jml/translation/JMLResolverManager.java | 17 +- .../jml/translation/JMLSpecFactory.java | 843 +- .../ProgramVariableCollection.java | 59 +- .../key/speclang/njml/ContractClauses.java | 15 +- .../ilkd/key/speclang/njml/DebugJmlLexer.java | 28 +- .../ilkd/key/speclang/njml/DoubleHandler.java | 8 +- .../ilkd/key/speclang/njml/FloatHandler.java | 8 +- .../key/speclang/njml/IntegerHandler.java | 14 +- .../uka/ilkd/key/speclang/njml/JmlCheck.java | 3 + .../uka/ilkd/key/speclang/njml/JmlChecks.java | 27 +- .../uka/ilkd/key/speclang/njml/JmlFacade.java | 46 +- .../de/uka/ilkd/key/speclang/njml/JmlIO.java | 138 +- .../key/speclang/njml/JmlMarkerDecision.java | 69 +- .../key/speclang/njml/JmlTermFactory.java | 581 +- .../ilkd/key/speclang/njml/LDTHandler.java | 11 +- .../njml/LabeledParserRuleContext.java | 12 +- .../njml/OverloadedOperatorHandler.java | 94 +- .../key/speclang/njml/TextualTranslator.java | 104 +- .../ilkd/key/speclang/njml/Translator.java | 622 +- .../ilkd/key/speclang/njml/package-info.java | 10 +- .../JavaIntegerSemanticsHelper.java | 803 +- .../translation/SLAttributeResolver.java | 210 +- .../translation/SLExceptionFactory.java | 125 +- .../speclang/translation/SLExpression.java | 13 +- .../translation/SLExpressionResolver.java | 191 +- .../translation/SLMethodResolver.java | 132 +- .../speclang/translation/SLParameters.java | 23 +- .../translation/SLResolverManager.java | 104 +- .../translation/SLTranslationException.java | 23 +- .../speclang/translation/SLTypeResolver.java | 42 +- .../translation/SLWarningException.java | 13 +- .../key/strategy/AbstractFeatureStrategy.java | 164 +- .../ilkd/key/strategy/ArithTermFeatures.java | 62 +- .../AutomatedRuleApplicationManager.java | 24 +- .../key/strategy/BuiltInRuleAppContainer.java | 169 +- ...nBasedAutomatedRuleApplicationManager.java | 3 + .../uka/ilkd/key/strategy/FIFOStrategy.java | 65 +- .../key/strategy/FindTacletAppContainer.java | 109 +- ...ussedBreakpointRuleApplicationManager.java | 42 +- .../FocussedRuleApplicationManager.java | 56 +- .../key/strategy/FormulaTermFeatures.java | 48 +- .../strategy/IfInstantiationCachePool.java | 61 +- .../uka/ilkd/key/strategy/IfInstantiator.java | 106 +- .../ilkd/key/strategy/IntroducedSymbolBy.java | 65 +- .../ilkd/key/strategy/IsInRangeProvable.java | 136 +- .../ilkd/key/strategy/JavaCardDLStrategy.java | 2314 ++--- .../strategy/JavaCardDLStrategyFactory.java | 804 +- .../strategy/NoFindTacletAppContainer.java | 8 +- .../ilkd/key/strategy/NumberRuleAppCost.java | 98 +- .../strategy/QueueRuleApplicationManager.java | 131 +- .../ilkd/key/strategy/RuleAppContainer.java | 86 +- .../de/uka/ilkd/key/strategy/RuleAppCost.java | 13 +- .../key/strategy/RuleAppCostCollector.java | 10 +- .../uka/ilkd/key/strategy/RuleAppFeature.java | 12 +- .../key/strategy/SimpleFilteredStrategy.java | 95 +- .../key/strategy/StaticFeatureCollection.java | 15 +- .../de/uka/ilkd/key/strategy/Strategy.java | 65 +- .../ilkd/key/strategy/StrategyFactory.java | 25 +- .../ilkd/key/strategy/StrategyProperties.java | 281 +- .../ilkd/key/strategy/TacletAppContainer.java | 276 +- .../uka/ilkd/key/strategy/TopRuleAppCost.java | 27 +- .../ilkd/key/strategy/ValueTermFeature.java | 3 + .../AbstractStrategyPropertyDefinition.java | 143 +- .../IDefaultStrategyPropertiesFactory.java | 42 +- .../OneOfStrategyPropertyDefinition.java | 173 +- .../StrategyPropertyValueDefinition.java | 176 +- .../StrategySettingsDefinition.java | 324 +- .../strategy/feature/AbstractBetaFeature.java | 359 +- .../AbstractMonomialSmallerThanFeature.java | 100 +- .../AbstractNonDuplicateAppFeature.java | 183 +- .../feature/AbstractPolarityFeature.java | 43 +- .../ilkd/key/strategy/feature/AgeFeature.java | 26 +- .../feature/AllowedCutPositionFeature.java | 48 +- .../key/strategy/feature/ApplyTFFeature.java | 48 +- .../feature/AtomsSmallerThanFeature.java | 54 +- .../feature/AutomatedRuleFeature.java | 21 +- .../key/strategy/feature/BinaryFeature.java | 38 +- .../feature/BinaryTacletAppFeature.java | 46 +- .../strategy/feature/CheckApplyEqFeature.java | 75 +- .../strategy/feature/CompareCostsFeature.java | 40 +- .../feature/ComprehendedSumFeature.java | 55 +- .../strategy/feature/ConditionalFeature.java | 96 +- .../key/strategy/feature/ConstFeature.java | 9 +- .../feature/ContainsQuantifierFeature.java | 23 +- .../strategy/feature/ContainsTermFeature.java | 29 +- .../strategy/feature/CountBranchFeature.java | 29 +- .../feature/CountMaxDPathFeature.java | 20 +- .../feature/CountPosDPathFeature.java | 19 +- .../feature/DeleteMergePointRuleFeature.java | 22 +- .../feature/DependencyContractFeature.java | 18 +- .../feature/DiffFindAndIfFeature.java | 30 +- .../DiffFindAndReplacewithFeature.java | 23 +- .../feature/DirectlyBelowFeature.java | 35 +- .../feature/DirectlyBelowSymbolFeature.java | 32 +- .../feature/EqNonDuplicateAppFeature.java | 39 +- .../ilkd/key/strategy/feature/Feature.java | 13 +- .../strategy/feature/FindDepthFeature.java | 23 +- .../strategy/feature/FindRightishFeature.java | 40 +- .../strategy/feature/FocusInAntecFeature.java | 13 +- ...SubFormulaOfInfFlowContractAppFeature.java | 27 +- .../feature/FormulaAddedByRuleFeature.java | 46 +- .../feature/IfThenElseMalusFeature.java | 56 +- .../feature/ImplicitCastNecessary.java | 24 +- .../feature/InEquationMultFeature.java | 91 +- .../feature/InfFlowContractAppFeature.java | 114 +- .../feature/InstantiatedSVFeature.java | 14 +- .../feature/LeftmostNegAtomFeature.java | 54 +- .../ilkd/key/strategy/feature/LetFeature.java | 30 +- .../strategy/feature/MatchedIfFeature.java | 19 +- .../strategy/feature/MergeRuleFeature.java | 15 +- .../feature/MonomialsSmallerThanFeature.java | 170 +- .../feature/NoSelfApplicationFeature.java | 25 +- .../feature/NonDuplicateAppFeature.java | 38 +- .../NonDuplicateAppModPositionFeature.java | 29 +- .../feature/NotBelowBinderFeature.java | 35 +- .../feature/NotBelowQuantifierFeature.java | 36 +- .../feature/NotInScopeOfModalityFeature.java | 42 +- .../OnlyInScopeOfQuantifiersFeature.java | 24 +- .../feature/PolynomialValuesCmpFeature.java | 144 +- .../key/strategy/feature/PrintFeature.java | 57 +- .../strategy/feature/PurePosDPathFeature.java | 24 +- .../key/strategy/feature/QueryExpandCost.java | 96 +- .../feature/ReducibleMonomialsFeature.java | 56 +- .../feature/RuleSetDispatchFeature.java | 62 +- .../feature/SVNeedsInstantiation.java | 13 +- .../key/strategy/feature/ScaleFeature.java | 181 +- .../SeqContainsExecutableCodeFeature.java | 24 +- .../feature/SetsSmallerThanFeature.java | 34 +- .../key/strategy/feature/ShannonFeature.java | 301 +- .../feature/SimplifyBetaCandidateFeature.java | 26 +- .../SimplifyReplaceKnownCandidateFeature.java | 75 +- .../strategy/feature/SmallerThanFeature.java | 39 +- .../feature/SortComparisonFeature.java | 20 +- .../ilkd/key/strategy/feature/SumFeature.java | 41 +- .../TacletRequiringInstantiationFeature.java | 25 +- .../feature/TermSmallerThanFeature.java | 15 +- .../feature/ThrownExceptionFeature.java | 41 +- .../strategy/feature/TopLevelFindFeature.java | 90 +- .../TriggerVarInstantiatedFeature.java | 24 +- .../feature/TrivialMonomialLCRFeature.java | 38 +- .../feature/findprefix/AntecChecker.java | 7 +- .../findprefix/AntecSuccPrefixChecker.java | 41 +- .../strategy/feature/findprefix/Checker.java | 12 +- .../FindPrefixRestrictionFeature.java | 43 +- .../strategy/feature/findprefix/Modifier.java | 9 +- .../RemoveParentUpdateModifier.java | 15 +- .../feature/findprefix/SuccChecker.java | 7 +- .../feature/findprefix/TopLevelChecker.java | 7 +- .../instantiator/BackTrackingManager.java | 192 +- .../feature/instantiator/CPBranch.java | 28 +- .../feature/instantiator/ChoicePoint.java | 19 +- .../feature/instantiator/ForEachCP.java | 86 +- .../feature/instantiator/OneOfCP.java | 45 +- .../instantiator/SVInstantiationCP.java | 96 +- .../quantifierHeuristics/BasicMatching.java | 120 +- .../quantifierHeuristics/ClausesGraph.java | 131 +- .../ClausesSmallerThanFeature.java | 83 +- .../quantifierHeuristics/Constraint.java | 125 +- ...straintAwareSyntacticalReplaceVisitor.java | 45 +- .../EliminableQuantifierTF.java | 36 +- .../EqualityConstraint.java | 1060 +-- ...ExistentiallyConnectedFormulasFeature.java | 20 +- .../quantifierHeuristics/HandleArith.java | 118 +- .../HeuristicInstantiation.java | 60 +- .../quantifierHeuristics/Instantiation.java | 347 +- .../InstantiationCost.java | 46 +- .../InstantiationCostScalerFeature.java | 43 +- .../LiteralsSmallerThanFeature.java | 190 +- .../quantifierHeuristics/Matching.java | 36 +- .../quantifierHeuristics/Metavariable.java | 86 +- .../quantifierHeuristics/MultiTrigger.java | 28 +- .../PredictCostProver.java | 21 +- .../QuanEliminationAnalyser.java | 207 +- ...dExistentiallyConnectedClausesFeature.java | 16 +- ...lacerOfQuanVariablesWithMetavariables.java | 50 +- .../SplittableQuantifiedFormulaFeature.java | 70 +- .../quantifierHeuristics/Substitution.java | 135 +- .../quantifierHeuristics/Trigger.java | 17 +- .../quantifierHeuristics/TriggerUtils.java | 42 +- .../quantifierHeuristics/TriggersSet.java | 219 +- .../TwoSidedMatching.java | 75 +- .../quantifierHeuristics/UniTrigger.java | 118 +- .../AbstractDividePolynomialsProjection.java | 42 +- .../termProjection/AssumptionProjection.java | 32 +- .../termProjection/CoeffGcdProjection.java | 34 +- .../DividePolynomialsProjection.java | 51 +- .../FocusFormulaProjection.java | 19 +- .../termProjection/FocusProjection.java | 28 +- .../termProjection/MonomialColumnOp.java | 21 +- .../termProjection/ProjectionToTerm.java | 14 +- .../ReduceMonomialsProjection.java | 27 +- .../SVInstantiationProjection.java | 39 +- .../termProjection/SubtermProjection.java | 16 +- .../strategy/termProjection/TermBuffer.java | 13 +- .../TermConstructionProjection.java | 38 +- ...riggerVariableInstantiationProjection.java | 18 +- .../termfeature/AnonHeapTermFeature.java | 20 +- .../strategy/termfeature/AtomTermFeature.java | 23 +- .../termfeature/BinarySumTermFeature.java | 18 +- .../termfeature/BinaryTermFeature.java | 21 +- .../ClosedExpressionTermFeature.java | 15 +- .../termfeature/ConstTermFeature.java | 7 +- .../termfeature/ConstantTermFeature.java | 10 +- .../ContainsExecutableCodeTermFeature.java | 43 +- .../termfeature/ContainsLabelFeature.java | 25 +- .../termfeature/ContainsLabelNameFeature.java | 23 +- .../strategy/termfeature/EqTermFeature.java | 25 +- .../IsHeapFunctionTermFeature.java | 6 +- .../termfeature/IsInductionVariable.java | 48 +- .../termfeature/IsNonRigidTermFeature.java | 18 +- .../IsPostConditionTermFeature.java | 12 +- .../IsSelectSkolemConstantTermFeature.java | 17 +- .../strategy/termfeature/OperatorClassTF.java | 12 +- .../key/strategy/termfeature/OperatorTF.java | 12 +- .../termfeature/PrimitiveHeapTermFeature.java | 5 +- .../termfeature/PrintTermFeature.java | 15 +- .../termfeature/RecSubTermFeature.java | 28 +- .../termfeature/ShannonTermFeature.java | 73 +- .../SimplifiedSelectTermFeature.java | 28 +- .../SortExtendsTransTermFeature.java | 19 +- .../strategy/termfeature/SubTermFeature.java | 40 +- .../key/strategy/termfeature/TermFeature.java | 5 +- .../termfeature/TermLabelTermFeature.java | 15 +- .../AllowedCutPositionsGenerator.java | 57 +- .../strategy/termgenerator/HeapGenerator.java | 16 +- .../MultiplesModEquationsGenerator.java | 200 +- .../termgenerator/RootsGenerator.java | 190 +- .../SequentFormulasGenerator.java | 40 +- .../termgenerator/SubtermGenerator.java | 90 +- .../termgenerator/SuperTermGenerator.java | 102 +- .../strategy/termgenerator/TermGenerator.java | 11 +- .../TriggeredInstantiations.java | 97 +- .../DefaultTacletTranslator.java | 353 +- .../IllegalTacletException.java | 9 +- .../taclettranslation/SkeletonGenerator.java | 99 +- .../key/taclettranslation/TacletFormula.java | 34 +- .../taclettranslation/TacletTranslator.java | 5 +- .../key/taclettranslation/TacletVisitor.java | 94 +- .../assumptions/AssumptionFormula.java | 47 +- .../assumptions/AssumptionGenerator.java | 102 +- .../DefaultTacletSetTranslation.java | 379 +- .../assumptions/GenericTranslator.java | 165 +- .../assumptions/SupportedTaclets.java | 1041 +-- .../assumptions/TacletConditions.java | 418 +- .../assumptions/TacletSetTranslation.java | 26 +- .../assumptions/TranslationListener.java | 45 +- .../lemma/AutomaticProver.java | 226 +- .../lemma/DefaultLemmaGenerator.java | 541 +- .../lemma/EmptyEnvInput.java | 7 +- .../lemma/GenericRemovingLemmaGenerator.java | 35 +- .../lemma/LemmaGenerator.java | 69 +- .../lemma/ProofObligationCreator.java | 257 +- .../taclettranslation/lemma/TacletLoader.java | 110 +- .../lemma/TacletProofObligationInput.java | 45 +- .../lemma/TacletSoundnessPOLoader.java | 112 +- .../lemma/UserDefinedSymbols.java | 578 +- .../java/de/uka/ilkd/key/util/Assert.java | 43 +- .../uka/ilkd/key/util/AssertionFailure.java | 12 +- .../main/java/de/uka/ilkd/key/util/Debug.java | 37 +- .../java/de/uka/ilkd/key/util/DebugMBean.java | 34 +- .../key/util/DirectoryFileCollection.java | 127 +- .../ilkd/key/util/EnhancedStringBuffer.java | 100 +- .../key/util/ExceptionHandlerException.java | 19 +- .../de/uka/ilkd/key/util/ExceptionTools.java | 25 +- .../de/uka/ilkd/key/util/FileCollection.java | 110 +- .../ilkd/key/util/HelperClassForTests.java | 361 +- .../ilkd/key/util/InfFlowProgVarRenamer.java | 89 +- .../de/uka/ilkd/key/util/InfFlowSpec.java | 9 +- .../de/uka/ilkd/key/util/KeYConstants.java | 17 +- .../ilkd/key/util/KeYRecoderExcHandler.java | 20 +- .../uka/ilkd/key/util/KeYResourceManager.java | 78 +- .../de/uka/ilkd/key/util/KeYTypeUtil.java | 387 +- .../key/util/LexicographicComparator.java | 38 +- .../de/uka/ilkd/key/util/LinkedHashMap.java | 16 +- .../java/de/uka/ilkd/key/util/MiscTools.java | 246 +- .../ilkd/key/util/NodePreorderIterator.java | 279 +- .../main/java/de/uka/ilkd/key/util/Pair.java | 54 +- .../java/de/uka/ilkd/key/util/Position.java | 8 +- .../de/uka/ilkd/key/util/ProgressMonitor.java | 66 +- .../de/uka/ilkd/key/util/ProofStarter.java | 207 +- .../uka/ilkd/key/util/ProofUserManager.java | 340 +- .../java/de/uka/ilkd/key/util/Quadruple.java | 49 +- .../de/uka/ilkd/key/util/ReferenceLister.java | 22 +- .../key/util/SearchNodePreorderIterator.java | 125 +- .../SearchNodeReversePreorderIterator.java | 142 +- .../de/uka/ilkd/key/util/SideProofUtil.java | 207 +- .../uka/ilkd/key/util/SpecDataLocation.java | 17 +- .../java/de/uka/ilkd/key/util/String8.java | 65 +- .../java/de/uka/ilkd/key/util/Triple.java | 44 +- .../de/uka/ilkd/key/util/UnicodeHelper.java | 22 +- .../key/util/VersionStringComparator.java | 11 +- .../uka/ilkd/key/util/ZipFileCollection.java | 53 +- .../key/util/mergerule/MergeParamsSpec.java | 3 + .../key/util/mergerule/MergeRuleUtils.java | 1321 ++- .../mergerule/SymbolicExecutionState.java | 40 +- .../SymbolicExecutionStateWithProgCnt.java | 61 +- .../uka/ilkd/key/util/net/NetworkUtils.java | 63 +- .../key/util/parsing/BuildingException.java | 22 +- .../key/util/parsing/BuildingExceptions.java | 3 + .../ilkd/key/util/parsing/BuildingIssue.java | 28 +- .../ilkd/key/util/parsing/HasLocation.java | 4 + .../key/util/parsing/LocatableException.java | 7 +- .../key/util/parsing/SyntaxErrorReporter.java | 64 +- .../java/de/uka/ilkd/key/util/pp/Backend.java | 30 +- .../de/uka/ilkd/key/util/pp/Layouter.java | 1027 +- .../java/de/uka/ilkd/key/util/pp/Printer.java | 180 +- .../uka/ilkd/key/util/pp/StringBackend.java | 63 +- .../util/pp/UnbalancedBlocksException.java | 13 +- .../uka/ilkd/key/util/pp/WriterBackend.java | 55 +- .../util/properties/AbstractProperties.java | 15 +- .../key/util/properties/ArrayProperties.java | 14 +- .../key/util/properties/MapProperties.java | 19 +- .../ilkd/key/util/properties/Properties.java | 5 +- .../service/KeYCrossReferenceSourceInfo.java | 403 +- .../key/java/JavaRedux/java/lang/String.key | 217 +- .../de/uka/ilkd/key/proof/rules/activeUse.key | 613 +- .../rules/adtProgramDecompositionRules.key | 303 +- .../uka/ilkd/key/proof/rules/assertions.key | 63 +- .../de/uka/ilkd/key/proof/rules/bigint.key | 292 +- .../uka/ilkd/key/proof/rules/binaryAxioms.key | 147 +- .../uka/ilkd/key/proof/rules/binaryLemmas.key | 55 +- .../de/uka/ilkd/key/proof/rules/boolean.key | 9 +- .../uka/ilkd/key/proof/rules/booleanRules.key | 59 +- .../de/uka/ilkd/key/proof/rules/bprod.key | 228 +- .../de/uka/ilkd/key/proof/rules/bsum.key | 33 +- .../ilkd/key/proof/rules/charListHeader.key | 11 +- .../ilkd/key/proof/rules/charListRules.key | 139 +- .../de/uka/ilkd/key/proof/rules/epsilon.key | 13 +- .../de/uka/ilkd/key/proof/rules/execRules.key | 588 +- .../ilkd/key/proof/rules/firstOrderRules.key | 80 +- .../rules/floatAssignment2UpdateRules.key | 43 +- .../uka/ilkd/key/proof/rules/floatHeader.key | 15 +- .../uka/ilkd/key/proof/rules/floatRules.key | 15 +- .../proof/rules/floatRulesAssumeStrictfp.key | 15 +- .../ilkd/key/proof/rules/floatRulesCommon.key | 17 +- .../proof/rules/floatRulesVerifyNormal.key | 16 +- .../uka/ilkd/key/proof/rules/forLoopRules.key | 17 +- .../proof/rules/formulaNormalisationRules.key | 246 +- .../de/uka/ilkd/key/proof/rules/freeADT.key | 20 +- .../uka/ilkd/key/proof/rules/genericRules.key | 191 +- .../de/uka/ilkd/key/proof/rules/heap.key | 11 +- .../de/uka/ilkd/key/proof/rules/heapRules.key | 602 +- .../ilkd/key/proof/rules/ifThenElseRules.key | 44 +- .../de/uka/ilkd/key/proof/rules/infFlow.key | 251 +- .../key/proof/rules/instanceAllocation.key | 229 +- .../de/uka/ilkd/key/proof/rules/intDiv.key | 79 +- .../de/uka/ilkd/key/proof/rules/intRules.key | 185 +- .../ilkd/key/proof/rules/intRulesArith.key | 172 +- .../proof/rules/intRulesIgnoringOverflow.key | 143 +- .../rules/integerAssignment2UpdateRules.key | 583 +- .../ilkd/key/proof/rules/integerHeader.key | 51 +- .../key/proof/rules/integerRulesCommon.key | 82 +- .../rules/integerSimplificationRules.key | 483 +- .../de/uka/ilkd/key/proof/rules/java5.key | 24 +- .../de/uka/ilkd/key/proof/rules/javaRules.key | 2503 +++-- .../de/uka/ilkd/key/proof/rules/ldt.key | 12 +- .../de/uka/ilkd/key/proof/rules/locSets.key | 10 +- .../uka/ilkd/key/proof/rules/locSetsRules.key | 333 +- .../key/proof/rules/loopInvariantRules.key | 5 +- .../de/uka/ilkd/key/proof/rules/loopRules.key | 53 +- .../ilkd/key/proof/rules/loopScopeRules.key | 185 +- .../de/uka/ilkd/key/proof/rules/map.key | 228 +- .../de/uka/ilkd/key/proof/rules/mapSize.key | 56 +- .../uka/ilkd/key/proof/rules/permission.key | 5 +- .../ilkd/key/proof/rules/permissionRules.key | 28 +- .../de/uka/ilkd/key/proof/rules/precRules.key | 87 +- .../de/uka/ilkd/key/proof/rules/propRule.key | 135 +- .../de/uka/ilkd/key/proof/rules/reach.key | 5 +- .../uka/ilkd/key/proof/rules/reachRules.key | 731 +- .../uka/ilkd/key/proof/rules/regExAxioms.key | 27 +- .../uka/ilkd/key/proof/rules/regExHeader.key | 3 + .../uka/ilkd/key/proof/rules/regExLemma.key | 11 +- .../ilkd/key/proof/rules/regExLemmaProven.key | 81 +- .../uka/ilkd/key/proof/rules/regExTheory.key | 3 + .../key/proof/rules/ruleSetsDeclarations.key | 36 +- .../de/uka/ilkd/key/proof/rules/seq.key | 17 +- .../uka/ilkd/key/proof/rules/seqCoreRules.key | 29 +- .../de/uka/ilkd/key/proof/rules/seqEq.key | 39 +- .../de/uka/ilkd/key/proof/rules/seqPerm.key | 129 +- .../de/uka/ilkd/key/proof/rules/seqPerm2.key | 20 +- .../de/uka/ilkd/key/proof/rules/seqRules.key | 825 +- .../ilkd/key/proof/rules/standardRules.key | 5 +- .../uka/ilkd/key/proof/rules/updateRules.key | 505 +- .../de/uka/ilkd/key/proof/rules/wd.key | 15 +- .../ilkd/key/proof/rules/wdFormulaRules.key | 1181 +-- .../ilkd/key/proof/rules/wdGeneralRules.key | 333 +- .../de/uka/ilkd/key/proof/rules/wdHeader.key | 11 +- .../uka/ilkd/key/proof/rules/wdHeapRules.key | 311 +- .../ilkd/key/proof/rules/wdLocSetRules.key | 551 +- .../ilkd/key/proof/rules/wdNumericalRules.key | 2407 ++--- .../uka/ilkd/key/proof/rules/wdReachRules.key | 49 +- .../uka/ilkd/key/proof/rules/wdRegExRules.key | 183 +- .../uka/ilkd/key/proof/rules/wdSeqRules.key | 305 +- .../ilkd/key/proof/rules/wdStringRules.key | 253 +- .../de/uka/ilkd/key/proof/rules/wellfound.key | 20 +- .../key/java/ProofJavaProgramFactoryTest.java | 38 +- .../de/uka/ilkd/key/java/RecoderExample.java | 95 +- .../key/java/TestContextStatementBlock.java | 66 +- .../java/TestJavaCardDLJavaExtensions.java | 34 +- .../de/uka/ilkd/key/java/TestJavaInfo.java | 73 +- .../ilkd/key/java/TestKeYRecoderMapping.java | 36 +- .../de/uka/ilkd/key/java/TestRecoder2KeY.java | 188 +- .../recoderext/TestEnumClassDeclaration.java | 17 +- ...stDeclarationProgramVariableCollector.java | 42 +- .../ilkd/key/logic/LabeledTermImplTest.java | 65 +- .../ilkd/key/logic/TestClashFreeSubst.java | 436 +- .../uka/ilkd/key/logic/TestLocalSymbols.java | 43 +- .../java/de/uka/ilkd/key/logic/TestName.java | 9 +- .../de/uka/ilkd/key/logic/TestNamespace.java | 68 +- .../de/uka/ilkd/key/logic/TestPosInOcc.java | 155 +- .../de/uka/ilkd/key/logic/TestPosInTerm.java | 86 +- .../uka/ilkd/key/logic/TestSemisequent.java | 453 +- .../logic/TestSyntacticalReplaceVisitor.java | 111 +- .../java/de/uka/ilkd/key/logic/TestTerm.java | 116 +- .../uka/ilkd/key/logic/TestTermBuilder.java | 99 +- .../uka/ilkd/key/logic/TestTermFactory.java | 482 +- .../ilkd/key/logic/TestTermLabelManager.java | 1568 ++-- .../uka/ilkd/key/logic/TestVariableNamer.java | 264 +- .../key/macros/scripts/SMTCommandTest.java | 5 +- .../macros/scripts/ScriptLineParserTest.java | 17 +- .../scripts/TestProofScriptCommand.java | 14 +- .../key/macros/scripts/meta/RewriteTest.java | 29 +- .../scripts/meta/ValueInjectorTest.java | 9 +- .../de/uka/ilkd/key/nparser/ExprTest.java | 16 +- .../ilkd/key/nparser/NamespaceBuilder.java | 8 +- .../key/nparser/ParseAllKeyFilesTest.java | 3 + .../uka/ilkd/key/nparser/ParseLDTsTests.java | 5 +- .../ilkd/key/nparser/TestTacletEquality.java | 56 +- .../key/parser/AbstractTestTermParser.java | 75 +- .../uka/ilkd/key/parser/TestDeclParser.java | 248 +- .../key/parser/TestIntLiteralParsing.java | 157 +- .../parser/TestJMLParserAssociativity.java | 29 +- .../ilkd/key/parser/TestParallelParsing.java | 209 +- .../de/uka/ilkd/key/parser/TestParser.java | 27 +- .../uka/ilkd/key/parser/TestTacletParser.java | 184 +- .../uka/ilkd/key/parser/TestTermParser.java | 267 +- .../ilkd/key/parser/TestTermParserHeap.java | 133 +- .../ilkd/key/parser/TestTermParserSorts.java | 39 +- .../parser/messages/ParserMessageTest.java | 56 +- .../parser/proofjava/TestProofJavaParser.java | 18 +- .../java/de/uka/ilkd/key/proof/TestGoal.java | 119 +- .../de/uka/ilkd/key/proof/TestProofTree.java | 261 +- .../uka/ilkd/key/proof/TestTacletIndex.java | 322 +- .../key/proof/TestTermTacletAppIndex.java | 179 +- .../ilkd/key/proof/io/KeYFileForTests.java | 88 +- .../ilkd/key/proof/io/TestZipProofSaving.java | 8 +- .../io/consistency/TestProofBundleIO.java | 61 +- .../key/proof/proverules/ProveRulesTest.java | 68 +- .../ilkd/key/proof/runallproofs/Function.java | 7 +- .../proof/runallproofs/GenerateUnitTests.java | 129 +- .../ListRunAllProofsTestCases.java | 15 +- .../key/proof/runallproofs/ProveTest.java | 49 +- .../runallproofs/RunAllProofsDirectories.java | 22 +- .../runallproofs/RunAllProofsFunctional.java | 14 +- .../runallproofs/RunAllProofsInfFlow.java | 11 +- .../proof/runallproofs/RunAllProofsTest.java | 132 +- .../runallproofs/RunAllProofsTestUnit.java | 117 +- .../key/proof/runallproofs/TestResult.java | 21 +- .../performance/DataRecordingParser.java | 8 +- .../performance/DataRecordingStrategy.java | 18 +- .../performance/DataRecordingTable.java | 26 +- .../performance/DataRecordingTestFile.java | 14 +- .../performance/FunctionPerformanceData.java | 15 +- .../runallproofs/performance/NodeData.java | 3 + .../performance/ProfilingDirectories.java | 6 +- .../runallproofs/performance/RuleData.java | 3 + .../performance/RuleIndependentData.java | 28 +- ...AllProofsTestWithComputeCostProfiling.java | 26 +- .../proofcollection/ForkMode.java | 70 +- .../proofcollection/ForkedTestFileRunner.java | 83 +- .../GroupedProofCollectionUnit.java | 38 +- .../proofcollection/ProofCollection.java | 117 +- .../ProofCollectionSettings.java | 743 +- .../proofcollection/ProofCollectionUnit.java | 48 +- .../SingletonProofCollectionUnit.java | 47 +- .../proofcollection/StatisticsFile.java | 115 +- .../proofcollection/TestFile.java | 109 +- .../proofcollection/TestProperty.java | 5 +- .../ilkd/key/rule/CreateTacletForTests.java | 476 +- .../de/uka/ilkd/key/rule/TacletForTests.java | 30 +- .../de/uka/ilkd/key/rule/TestApplyTaclet.java | 1037 +-- .../ilkd/key/rule/TestCollisionResolving.java | 670 +- .../de/uka/ilkd/key/rule/TestMatchTaclet.java | 378 +- .../key/rule/TestSchemaModalOperators.java | 402 +- .../TestDropEffectlessElementary.java | 41 +- .../inst/TestGenericSortInstantiations.java | 1093 ++- .../key/rule/loop/LoopScopeInvRuleTests.java | 12 +- .../match/legacy/TestLegacyTacletMatch.java | 226 +- .../rule/match/vm/VMTacletMatcherTest.java | 194 +- .../ilkd/key/rule/merge/MergeRuleTests.java | 131 +- .../PredicateAbstractionLatticeTests.java | 96 +- .../TestProgramMetaConstructs.java | 76 +- .../rule/tacletbuilder/TestTacletBuild.java | 81 +- .../uka/ilkd/key/smt/SMTBeautifierTest.java | 5 +- .../de/uka/ilkd/key/smt/SMTTestSettings.java | 112 +- .../BufferedMessageReaderTest.java | 12 +- .../key/smt/newsmt2/MasterHandlerTest.java | 77 +- .../key/smt/newsmt2/ProveSMTLemmasTest.java | 17 +- .../de/uka/ilkd/key/smt/test/TestCommons.java | 66 +- .../de/uka/ilkd/key/smt/test/TestCvc4.java | 26 +- .../uka/ilkd/key/smt/test/TestSMTSolver.java | 295 +- .../java/de/uka/ilkd/key/smt/test/TestZ3.java | 59 +- .../key/speclang/ContractFactoryTest.java | 85 +- .../ilkd/key/speclang/jml/JMLUtilsTest.java | 5 +- .../speclang/jml/TestJMLPreTranslator.java | 127 +- .../key/speclang/jml/TestJMLTranslator.java | 224 +- .../TextualJMLAssertStatementTest.java | 22 +- .../njml/ClasslevelTranslatorTest.java | 14 +- .../speclang/njml/ContractLoadingTests.java | 9 +- .../njml/ExpressionTranslatorTest.java | 8 +- .../njml/MethodlevelTranslatorTest.java | 8 +- .../speclang/njml/NJmlTranslatorTests.java | 72 +- .../speclang/njml/TextualTranslatorTest.java | 28 +- .../quantifierHeuristics/TestTriggersSet.java | 415 +- .../TestTacletTranslator.java | 114 +- .../TestGenericRemovingLemmaGenerator.java | 5 +- .../de/uka/ilkd/key/util/DesignTests.java | 102 +- .../de/uka/ilkd/key/util/IOForwarder.java | 12 +- .../de/uka/ilkd/key/util/LineProperties.java | 13 +- .../key/util/TestLexicographicComparator.java | 13 +- .../de/uka/ilkd/key/util/TestMiscTools.java | 78 +- .../key/util/TestNodePreorderIterator.java | 517 +- .../uka/ilkd/key/util/TestProofStarter.java | 32 +- .../ilkd/key/util/TestProofUserManager.java | 620 +- .../util/TestSearchNodePreorderIterator.java | 279 +- ...TestSearchNodeReversePreorderIterator.java | 268 +- .../key/util/TestVersionStringComparator.java | 19 +- .../de/uka/ilkd/key/util/pp/TestLayouter.java | 103 +- .../AbstractGenericRemover.java | 214 +- .../util/removegenerics/GenericRemover.java | 101 +- .../GenericResolutionTransformation.java | 54 +- .../ilkd/key/util/removegenerics/Main.java | 75 +- .../removegenerics/PreviewGenericRemover.java | 32 +- .../util/removegenerics/ResolveGenerics.java | 48 +- .../ResolveMemberReference.java | 109 +- .../ResolveMethodDeclaration.java | 18 +- .../ResolveTypeDeclaration.java | 111 +- .../removegenerics/ResolveTypeReference.java | 21 +- .../SingleLineCommentRepairer.java | 19 +- .../monitor/ConsoleGenericRemoverMonitor.java | 19 +- .../monitor/GenericRemoverMonitor.java | 7 +- .../removegenerics/ResolveGenericClass.java | 37 +- .../removegenerics/TestClassDeclaration.java | 61 +- .../key/util/removegenerics/TestComment.java | 21 +- .../removegenerics/TestMemberReference.java | 33 +- .../removegenerics/TestMethodDeclaration.java | 11 +- .../removegenerics/TestMultipleBounds.java | 26 +- .../removegenerics/TestTypeReference.java | 13 +- .../uka/ilkd/key/core/DefaultKeYDesktop.java | 91 +- .../uka/ilkd/key/core/InterruptListener.java | 7 +- .../java/de/uka/ilkd/key/core/KeYDesktop.java | 89 +- .../de/uka/ilkd/key/core/KeYMediator.java | 159 +- .../uka/ilkd/key/core/KeYSelectionEvent.java | 27 +- .../ilkd/key/core/KeYSelectionListener.java | 14 +- .../uka/ilkd/key/core/KeYSelectionModel.java | 31 +- .../main/java/de/uka/ilkd/key/core/Log.java | 41 +- .../main/java/de/uka/ilkd/key/core/Main.java | 150 +- .../de/uka/ilkd/key/core/WebstartMain.java | 26 +- .../uka/ilkd/key/gui/ApplyTacletDialog.java | 138 +- .../uka/ilkd/key/gui/AutoDismissDialog.java | 56 +- .../gui/AuxiliaryContractConfigurator.java | 47 +- .../gui/AuxiliaryContractSelectionPanel.java | 59 +- .../gui/BlockContractExternalCompletion.java | 36 +- .../gui/BlockContractInternalCompletion.java | 40 +- .../key/gui/BlockContractSelectionPanel.java | 28 +- .../java/de/uka/ilkd/key/gui/ClassTree.java | 503 +- .../ilkd/key/gui/ContractConfigurator.java | 133 +- .../ilkd/key/gui/ContractSelectionPanel.java | 344 +- .../key/gui/DependencyContractCompletion.java | 96 +- .../de/uka/ilkd/key/gui/ExampleChooser.java | 126 +- .../de/uka/ilkd/key/gui/ExceptionDialog.java | 42 +- .../uka/ilkd/key/gui/ExceptionalHandler.java | 14 +- .../uka/ilkd/key/gui/FilterMouseAction.java | 3 + ...FunctionalOperationContractCompletion.java | 53 +- .../java/de/uka/ilkd/key/gui/GUIListener.java | 13 +- .../java/de/uka/ilkd/key/gui/GoalList.java | 201 +- .../ilkd/key/gui/HeatmapOptionsDialog.java | 108 +- .../java/de/uka/ilkd/key/gui/InfoTree.java | 7 +- .../de/uka/ilkd/key/gui/InfoTreeModel.java | 42 +- .../de/uka/ilkd/key/gui/InfoTreeNode.java | 19 +- .../java/de/uka/ilkd/key/gui/InfoView.java | 31 +- .../uka/ilkd/key/gui/InfoViewContentPane.java | 3 + .../gui/InspectorForDecisionPredicates.java | 73 +- .../InteractiveRuleApplicationCompletion.java | 20 +- .../ilkd/key/gui/InvariantConfigurator.java | 238 +- .../java/de/uka/ilkd/key/gui/IssueDialog.java | 194 +- .../de/uka/ilkd/key/gui/KeYFileChooser.java | 84 +- .../key/gui/KeYFileChooserBookmarkPanel.java | 18 +- .../java/de/uka/ilkd/key/gui/KeYListener.java | 9 +- .../ilkd/key/gui/KeyboardTacletExtension.java | 123 +- .../java/de/uka/ilkd/key/gui/LogView.java | 38 +- .../ilkd/key/gui/LoopApplyHeadCompletion.java | 19 +- .../gui/LoopContractExternalCompletion.java | 30 +- .../gui/LoopContractInternalCompletion.java | 30 +- .../key/gui/LoopContractSelectionPanel.java | 17 +- .../key/gui/LoopInvariantRuleCompletion.java | 54 +- .../de/uka/ilkd/key/gui/MainStatusLine.java | 53 +- .../java/de/uka/ilkd/key/gui/MainWindow.java | 317 +- .../ilkd/key/gui/MainWindowTabbedPane.java | 25 +- .../de/uka/ilkd/key/gui/MaxRuleAppSlider.java | 12 +- .../uka/ilkd/key/gui/NodeInfoVisualizer.java | 23 +- .../key/gui/NodeInfoVisualizerListener.java | 7 +- .../de/uka/ilkd/key/gui/ProofMacroMenu.java | 43 +- .../de/uka/ilkd/key/gui/ProofMacroWorker.java | 45 +- .../ilkd/key/gui/ProofManagementDialog.java | 262 +- .../uka/ilkd/key/gui/ProofScriptWorker.java | 37 +- .../ilkd/key/gui/ProofSelectionDialog.java | 47 +- .../de/uka/ilkd/key/gui/RecentFileMenu.java | 101 +- .../java/de/uka/ilkd/key/gui/SearchBar.java | 46 +- .../ilkd/key/gui/StrategySelectionView.java | 308 +- .../de/uka/ilkd/key/gui/TableRowResizer.java | 17 +- .../ilkd/key/gui/TacletIfSelectionDialog.java | 38 +- .../key/gui/TacletMatchCompletionDialog.java | 1316 ++- .../java/de/uka/ilkd/key/gui/TaskTree.java | 400 +- .../key/gui/WindowUserInterfaceControl.java | 397 +- .../key/gui/actions/AbandonTaskAction.java | 12 +- .../uka/ilkd/key/gui/actions/AboutAction.java | 43 +- .../ilkd/key/gui/actions/AutoModeAction.java | 214 +- .../de/uka/ilkd/key/gui/actions/AutoSave.java | 12 +- .../gui/actions/CopyToClipboardAction.java | 11 +- .../gui/actions/DecreaseFontSizeAction.java | 18 +- .../gui/actions/EditMostRecentFileAction.java | 71 +- .../key/gui/actions/EditSourceFileAction.java | 48 +- .../EnsureSourceConsistencyToggleAction.java | 20 +- .../ilkd/key/gui/actions/ExitMainAction.java | 96 +- .../ilkd/key/gui/actions/GoalBackAction.java | 48 +- .../gui/actions/GoalSelectAboveAction.java | 13 +- .../gui/actions/GoalSelectBelowAction.java | 11 +- .../gui/actions/HeatmapSettingsAction.java | 3 + .../key/gui/actions/HeatmapToggleAction.java | 11 +- .../HidePackagePrefixToggleAction.java | 58 +- .../gui/actions/IncreaseFontSizeAction.java | 12 +- .../ilkd/key/gui/actions/KeYMenuCheckBox.java | 8 +- .../gui/actions/KeYProjectHomepageAction.java | 10 +- .../uka/ilkd/key/gui/actions/KeyAction.java | 21 +- .../gui/actions/LemmaGenerationAction.java | 404 +- .../LemmaGenerationBatchModeAction.java | 52 +- .../ilkd/key/gui/actions/LicenseAction.java | 12 +- .../ilkd/key/gui/actions/MacroKeyBinding.java | 19 +- .../key/gui/actions/MainWindowAction.java | 3 + .../gui/actions/MenuSendFeedackAction.java | 21 +- .../key/gui/actions/MinimizeInteraction.java | 55 +- .../key/gui/actions/OpenExampleAction.java | 13 +- .../ilkd/key/gui/actions/OpenFileAction.java | 22 +- .../gui/actions/OpenMostRecentFileAction.java | 17 +- .../gui/actions/OpenSingleJavaFileAction.java | 12 +- .../gui/actions/PrettyPrintToggleAction.java | 67 +- .../gui/actions/ProofManagementAction.java | 61 +- .../actions/ProofScriptFromFileAction.java | 9 +- .../gui/actions/ProofScriptInputAction.java | 10 +- .../key/gui/actions/PruneProofAction.java | 61 +- .../ilkd/key/gui/actions/QuickLoadAction.java | 10 +- .../ilkd/key/gui/actions/QuickSaveAction.java | 9 +- .../actions/RightMouseClickToggleAction.java | 12 +- .../key/gui/actions/RunAllProofsAction.java | 35 +- .../ilkd/key/gui/actions/SMTInvokeAction.java | 25 +- .../key/gui/actions/SMTOptionsAction.java | 25 +- .../key/gui/actions/SaveBundleAction.java | 12 +- .../ilkd/key/gui/actions/SaveFileAction.java | 13 +- .../gui/actions/SearchInProofTreeAction.java | 13 +- .../gui/actions/SearchInSequentAction.java | 6 +- .../gui/actions/SearchModeChangeAction.java | 15 +- .../key/gui/actions/SearchNextAction.java | 7 +- .../key/gui/actions/SearchPreviousAction.java | 7 +- .../key/gui/actions/SendFeedbackAction.java | 270 +- .../key/gui/actions/SettingsTreeModel.java | 39 +- .../gui/actions/ShowActiveSettingsAction.java | 25 +- .../ShowActiveTactletOptionsAction.java | 53 +- .../key/gui/actions/ShowKnownTypesAction.java | 14 +- .../key/gui/actions/ShowProofStatistics.java | 102 +- .../gui/actions/ShowUsedContractsAction.java | 38 +- .../SyntaxHighlightingToggleAction.java | 10 +- .../key/gui/actions/SystemInfoAction.java | 72 +- .../key/gui/actions/TacletOptionsAction.java | 15 +- .../ilkd/key/gui/actions/TermLabelMenu.java | 74 +- .../gui/actions/ToggleConfirmExitAction.java | 41 +- .../ToggleSequentViewTooltipAction.java | 7 +- .../ToggleSourceViewTooltipAction.java | 8 +- .../key/gui/actions/ToolTipOptionsAction.java | 11 +- .../key/gui/actions/UnicodeToggleAction.java | 80 +- .../ilkd/key/gui/colors/ColorSettings.java | 18 +- .../key/gui/colors/ColorSettingsProvider.java | 92 +- .../key/gui/configuration/ChoiceSelector.java | 501 +- .../ilkd/key/gui/configuration/Config.java | 100 +- .../configuration/ConfigChangeAdapter.java | 13 +- .../gui/configuration/ConfigChangeEvent.java | 27 +- .../configuration/ConfigChangeListener.java | 9 +- .../key/gui/configuration/ViewSelector.java | 272 +- .../ilkd/key/gui/docking/DockingHelper.java | 44 +- .../ilkd/key/gui/docking/DockingLayout.java | 32 +- .../key/gui/extension/ExtensionManager.java | 77 +- .../gui/extension/api/ContextMenuAdapter.java | 38 +- .../gui/extension/api/ContextMenuKind.java | 3 + .../extension/api/DefaultContextMenuKind.java | 9 +- .../gui/extension/api/KeYGuiExtension.java | 63 +- .../api/KeYToolbarExtensionAdapter.java | 3 + .../api/KeyboardShortcutAdapter.java | 20 +- .../ilkd/key/gui/extension/api/TabPanel.java | 15 +- .../key/gui/extension/impl/Extension.java | 23 +- .../gui/extension/impl/ExtensionSettings.java | 6 +- .../key/gui/extension/impl/HeatmapExt.java | 79 +- .../extension/impl/KeYGuiExtensionFacade.java | 136 +- .../key/gui/extension/impl/TestExtension.java | 38 +- .../de/uka/ilkd/key/gui/fonticons/Entypo.java | 446 +- .../key/gui/fonticons/FontAwesomeBrands.java | 845 +- .../key/gui/fonticons/FontAwesomeRegular.java | 302 +- .../key/gui/fonticons/FontAwesomeSolid.java | 1911 ++-- .../ilkd/key/gui/fonticons/IconFactory.java | 157 +- .../uka/ilkd/key/gui/fonticons/IconFont.java | 6 +- .../key/gui/fonticons/IconFontProvider.java | 3 + .../ilkd/key/gui/fonticons/IconFontSwing.java | 31 +- .../ilkd/key/gui/fonticons/IconProvider.java | 3 + .../gui/fonticons/MaterialDesignRegular.java | 45 +- .../uka/ilkd/key/gui/fonticons/ShowIcons.java | 17 +- .../uka/ilkd/key/gui/fonticons/Typicons.java | 699 +- .../de/uka/ilkd/key/gui/help/HelpFacade.java | 21 +- .../de/uka/ilkd/key/gui/help/HelpInfo.java | 5 +- .../de/uka/ilkd/key/gui/join/JoinDialog.java | 469 +- .../uka/ilkd/key/gui/join/JoinMenuItem.java | 54 +- .../uka/ilkd/key/gui/join/SequentViewer.java | 56 +- .../gui/keyshortcuts/KeyStrokeManager.java | 40 +- .../gui/keyshortcuts/KeyStrokeSettings.java | 96 +- .../gui/keyshortcuts/ShortcutSettings.java | 110 +- .../key/gui/lemmatagenerator/InfoDialog.java | 104 +- .../key/gui/lemmatagenerator/ItemChooser.java | 866 +- .../LemmaSelectionDialog.java | 272 +- .../LemmataAutoModeOptions.java | 38 +- .../gui/lemmatagenerator/LemmataHandler.java | 323 +- .../LoadUserTacletsDialog.java | 86 +- .../MergePartnerSelectionDialog.java | 268 +- .../mergerule/MergeProcedureCompletion.java | 35 +- .../gui/mergerule/MergeRuleCompletion.java | 37 +- .../key/gui/mergerule/MergeRuleMenuItem.java | 44 +- .../AbstractDomainElemChoice.java | 21 +- .../AbstractionPredicatesChoiceDialog.java | 310 +- .../ObservableArrayList.java | 5 +- .../PredicateAbstractionCompletion.java | 154 +- .../gui/nodeviews/BuiltInRuleMenuItem.java | 5 +- .../key/gui/nodeviews/CurrentGoalView.java | 69 +- .../nodeviews/CurrentGoalViewListener.java | 66 +- .../gui/nodeviews/CurrentGoalViewMenu.java | 143 +- .../nodeviews/DefaultBuiltInRuleMenuItem.java | 23 +- .../gui/nodeviews/DefaultTacletMenuItem.java | 122 +- .../gui/nodeviews/DragNDropInstantiator.java | 525 +- .../ilkd/key/gui/nodeviews/EmptySequent.java | 8 +- .../gui/nodeviews/HTMLSyntaxHighlighter.java | 218 +- .../ilkd/key/gui/nodeviews/InnerNodeView.java | 62 +- .../gui/nodeviews/InnerNodeViewListener.java | 15 +- .../key/gui/nodeviews/InnerNodeViewMenu.java | 14 +- .../nodeviews/InsertHiddenTacletMenuItem.java | 45 +- .../InsertSystemInvariantTacletMenuItem.java | 70 +- .../InsertionTacletBrowserMenuItem.java | 129 +- .../uka/ilkd/key/gui/nodeviews/MainFrame.java | 19 +- .../nodeviews/MenuItemForTwoModeRules.java | 69 +- .../nodeviews/PosInSequentTransferable.java | 93 +- .../nodeviews/SequentHideWarningBorder.java | 24 +- .../ilkd/key/gui/nodeviews/SequentView.java | 311 +- .../nodeviews/SequentViewChangeListener.java | 23 +- .../key/gui/nodeviews/SequentViewDock.java | 9 +- .../nodeviews/SequentViewInputListener.java | 65 +- .../gui/nodeviews/SequentViewListener.java | 10 +- .../key/gui/nodeviews/SequentViewMenu.java | 32 +- .../key/gui/nodeviews/SequentViewPanel.java | 7 +- .../gui/nodeviews/SequentViewSearchBar.java | 56 +- .../gui/nodeviews/ShowHashcodesExtension.java | 3 + .../nodeviews/SimpleTacletSelectionMenu.java | 58 +- .../key/gui/nodeviews/TacletDescriber.java | 54 +- .../key/gui/nodeviews/TacletInfoToggle.java | 24 +- .../key/gui/nodeviews/TacletMenuItem.java | 18 +- .../gui/notification/AbandonNotification.java | 28 +- .../ExceptionFailureNotification.java | 24 +- .../gui/notification/ExitKeYNotification.java | 104 +- .../GeneralFailureNotification.java | 22 +- .../GeneralInformationNotification.java | 21 +- .../gui/notification/NotificationAction.java | 16 +- .../gui/notification/NotificationEventID.java | 36 +- .../gui/notification/NotificationManager.java | 234 +- .../gui/notification/NotificationTask.java | 75 +- .../notification/ProofClosedNotification.java | 32 +- .../ExceptionFailureNotificationDialog.java | 26 +- .../GeneralFailureJTextPaneDisplay.java | 40 +- .../GeneralInformationJTextPaneDisplay.java | 34 +- .../actions/ProofClosedJTextPaneDisplay.java | 30 +- .../notification/actions/ShowDisplayPane.java | 25 +- .../notification/events/AbandonTaskEvent.java | 11 +- .../events/ExceptionFailureEvent.java | 11 +- .../gui/notification/events/ExitKeYEvent.java | 11 +- .../events/GeneralFailureEvent.java | 27 +- .../events/GeneralInformationEvent.java | 45 +- .../events/NotificationEvent.java | 24 +- .../events/ProofClosedNotificationEvent.java | 24 +- .../OriginTermLabelVisualizer.java | 104 +- .../gui/originlabels/OriginTermLabelsExt.java | 33 +- .../gui/originlabels/ShowOriginAction.java | 28 +- .../ToggleOriginHighlightAction.java | 23 +- .../ToggleTermOriginTrackingAction.java | 53 +- .../key/gui/proofdiff/ProofDiffFrame.java | 143 +- .../key/gui/proofdiff/ProofDifference.java | 61 +- .../gui/proofdiff/ProofDifferenceView.java | 81 +- .../key/gui/proofdiff/diff_match_patch.java | 4587 +++++---- .../ilkd/key/gui/prooftree/DisableGoal.java | 33 +- .../gui/prooftree/GUIAbstractTreeNode.java | 128 +- .../ilkd/key/gui/prooftree/GUIBranchNode.java | 139 +- .../prooftree/GUIOneStepChildTreeNode.java | 41 +- .../key/gui/prooftree/GUIProofTreeModel.java | 450 +- .../key/gui/prooftree/GUIProofTreeNode.java | 56 +- .../prooftree/ProofTreeExpansionState.java | 247 +- .../gui/prooftree/ProofTreePopupFactory.java | 144 +- .../key/gui/prooftree/ProofTreeSearchBar.java | 58 +- .../ilkd/key/gui/prooftree/ProofTreeView.java | 188 +- .../gui/prooftree/ProofTreeViewFilter.java | 458 +- .../de/uka/ilkd/key/gui/prooftree/Style.java | 6 +- .../de/uka/ilkd/key/gui/prooftree/Styler.java | 11 +- .../gui/settings/DefaultSettingsProvider.java | 9 +- .../ilkd/key/gui/settings/FontSizeFacade.java | 65 +- .../InvalidSettingsInputException.java | 15 +- .../ilkd/key/gui/settings/SettingsDialog.java | 6 +- .../key/gui/settings/SettingsManager.java | 25 +- .../ilkd/key/gui/settings/SettingsPanel.java | 77 +- .../key/gui/settings/SettingsProvider.java | 33 +- .../uka/ilkd/key/gui/settings/SettingsUi.java | 38 +- .../key/gui/settings/SimpleSettingsPanel.java | 55 +- .../key/gui/settings/StandardUISettings.java | 42 +- .../gui/settings/TacletOptionsSettings.java | 74 +- .../uka/ilkd/key/gui/settings/Validator.java | 3 + .../ilkd/key/gui/settings/package-info.java | 10 +- .../java/de/uka/ilkd/key/gui/smt/CETree.java | 658 +- .../key/gui/smt/DropdownSelectionButton.java | 179 +- .../ilkd/key/gui/smt/InformationWindow.java | 27 +- .../ilkd/key/gui/smt/OptionContentNode.java | 11 +- .../uka/ilkd/key/gui/smt/ProgressDialog.java | 759 +- .../uka/ilkd/key/gui/smt/ProgressModel.java | 330 +- .../de/uka/ilkd/key/gui/smt/SMTMenuItem.java | 21 +- .../uka/ilkd/key/gui/smt/SolverListener.java | 950 +- .../gui/smt/TacletTranslationSelection.java | 562 +- .../smt/settings/NewTranslationOptions.java | 49 +- .../gui/smt/settings/SMTSettingsProvider.java | 64 +- .../key/gui/smt/settings/SolverOptions.java | 40 +- .../settings/TacletTranslationOptions.java | 35 +- .../gui/smt/settings/TranslationOptions.java | 56 +- .../ilkd/key/gui/sourceview/JavaDocument.java | 297 +- .../ilkd/key/gui/sourceview/SourceView.java | 379 +- .../key/gui/sourceview/SourceViewFrame.java | 24 +- .../key/gui/sourceview/TextLineNumber.java | 35 +- .../utilities/BracketMatchingTextArea.java | 162 +- .../key/gui/utilities/CheckedUserInput.java | 295 +- .../gui/utilities/ClickableMessageBox.java | 146 +- .../gui/utilities/ClosableTabComponent.java | 3 + .../ilkd/key/gui/utilities/GuiUtilities.java | 28 +- .../gui/utilities/InspectorForFormulas.java | 28 +- .../utilities/SquigglyUnderlinePainter.java | 7 +- .../uka/ilkd/key/gui/utilities/StdDialog.java | 99 +- .../ilkd/key/gui/utilities/TrafficLight.java | 116 +- .../ilkd/key/gui/utilities/WrapLayout.java | 338 +- .../uka/ilkd/key/proof/io/ProblemLoader.java | 48 +- .../de/uka/ilkd/key/proof/mgt/BasicTask.java | 66 +- .../de/uka/ilkd/key/proof/mgt/EnvNode.java | 30 +- .../key/proof/mgt/ProofAggregateTask.java | 38 +- .../uka/ilkd/key/proof/mgt/TaskTreeModel.java | 138 +- .../uka/ilkd/key/proof/mgt/TaskTreeNode.java | 9 +- .../AbstractMediatorUserInterfaceControl.java | 501 +- .../ui/ConsoleProofObligationSelector.java | 31 +- .../key/ui/ConsoleUserInterfaceControl.java | 74 +- .../uka/ilkd/key/ui/MediatorProofControl.java | 53 +- .../ilkd/key/ui/ProofObligationSelector.java | 3 + .../java/de/uka/ilkd/key/ui/Verbosity.java | 13 +- .../de/uka/ilkd/key/util/CommandLine.java | 223 +- .../ilkd/key/util/CommandLineException.java | 17 +- .../de/uka/ilkd/key/util/PreferenceSaver.java | 74 +- .../de/uka/ilkd/key/util/ThreadUtilities.java | 55 +- .../de/uka/ilkd/key/util/XMLResources.java | 16 +- .../uka/ilkd/key/gui/KeyboardTacletTest.java | 8 +- .../gui/proofdiff/ProofDifferenceTest.java | 16 +- .../java/org/key_project/util/ExtList.java | 73 +- .../java/org/key_project/util/Filenames.java | 64 +- .../java/org/key_project/util/LRUCache.java | 17 +- .../java/org/key_project/util/RandomName.java | 444 +- .../java/org/key_project/util/Streams.java | 3 + .../java/org/key_project/util/Strings.java | 41 +- .../java/org/key_project/util/bean/Bean.java | 57 +- .../java/org/key_project/util/bean/IBean.java | 41 +- .../bitops/ImmutableFixedLengthBitSet.java | 53 +- .../util/collection/DefaultImmutableMap.java | 650 +- .../util/collection/DefaultImmutableSet.java | 47 +- .../util/collection/ImmutableArray.java | 152 +- .../util/collection/ImmutableHeap.java | 70 +- .../util/collection/ImmutableLeftistHeap.java | 657 +- .../util/collection/ImmutableList.java | 26 +- .../util/collection/ImmutableMap.java | 36 +- .../util/collection/ImmutableMapEntry.java | 13 +- .../util/collection/ImmutableSLList.java | 767 +- .../util/collection/ImmutableSet.java | 16 +- .../util/collection/Immutables.java | 61 +- .../util/collection/KeYCollections.java | 55 +- .../util/collection/NotUniqueException.java | 9 +- .../util/collection/PropertiesUtil.java | 13 +- .../util/helper/FindResources.java | 52 +- .../helper/HelperClassForUtilityTests.java | 61 +- .../org/key_project/util/java/ArrayUtil.java | 1206 +-- .../key_project/util/java/CollectionUtil.java | 841 +- .../org/key_project/util/java/IFilter.java | 7 +- .../util/java/IFilterWithException.java | 11 +- .../org/key_project/util/java/IOUtil.java | 170 +- .../key_project/util/java/IntegerUtil.java | 48 +- .../org/key_project/util/java/MapUtil.java | 27 +- .../org/key_project/util/java/NumberUtil.java | 321 +- .../org/key_project/util/java/ObjectUtil.java | 901 +- .../org/key_project/util/java/StringUtil.java | 809 +- .../org/key_project/util/java/WrapUtils.java | 227 +- .../org/key_project/util/java/XMLUtil.java | 590 +- .../thread/AbstractRunnableWithException.java | 49 +- .../thread/AbstractRunnableWithResult.java | 52 +- .../java/thread/IRunnableWithException.java | 17 +- .../util/java/thread/IRunnableWithResult.java | 30 +- .../org/key_project/util/lookup/Inject.java | 7 +- .../util/lookup/InjectionException.java | 8 +- .../org/key_project/util/lookup/Lookup.java | 60 +- .../util/lookup/LookupListener.java | 3 + .../util/reflection/ClassLoaderUtil.java | 153 +- .../util/reflection/IClassLoader.java | 46 +- .../JavaApplicationClassLoader.java | 36 +- .../util/testcategories/Interactive.java | 3 + .../util/testcategories/Performance.java | 3 + .../key_project/util/testcategories/Slow.java | 6 +- .../util/collection/TestImmutables.java | 94 +- .../org/key_project/util/model/ClassA.java | 95 +- .../org/key_project/util/model/ClassB.java | 63 +- .../bitops/TestFixedLengthBitSet.java | 3 + .../collection/TestLeftistHeapOfInteger.java | 49 +- .../TestMapAsListFromIntegerToString.java | 24 +- .../collection/TestSLListOfString.java | 80 +- .../collection/TestSetAsListOfString.java | 15 +- .../util/testcase/java/ArrayUtilTest.java | 218 +- .../testcase/java/CollectionUtilTest.java | 51 +- .../util/testcase/java/IOUtilTest.java | 904 +- .../util/testcase/java/IntegerUtilTest.java | 36 +- .../util/testcase/java/NumberUtilTest.java | 305 +- .../util/testcase/java/ObjectUtilTest.java | 151 +- .../util/testcase/java/StringUtilTest.java | 50 +- .../util/testcase/java/XMLUtilTest.java | 41 +- .../exploration/ExplorationExtension.java | 45 +- .../exploration/ExplorationModeModel.java | 27 +- .../exploration/ExplorationNodeData.java | 24 +- .../org/key_project/exploration/Icons.java | 10 +- .../exploration/ProofExplorationService.java | 76 +- .../actions/AddFormulaToAntecedentAction.java | 9 +- .../actions/AddFormulaToSuccedentAction.java | 11 +- .../actions/DeleteFormulaAction.java | 12 +- .../actions/EditFormulaAction.java | 11 +- .../actions/ExplorationAction.java | 22 +- .../ShowInteractiveBranchesAction.java | 17 +- .../actions/ToggleExplorationAction.java | 29 +- .../exploration/ui/ExplorationStepsList.java | 70 +- .../ProofExplorationServiceTest.java | 56 +- .../key/gui/testgen/CounterExampleAction.java | 55 +- .../ilkd/key/gui/testgen/TGInfoDialog.java | 30 +- .../de/uka/ilkd/key/gui/testgen/TGWorker.java | 26 +- .../key/gui/testgen/TestGenerationAction.java | 19 +- .../key/gui/testgen/TestgenExtension.java | 13 +- .../key/gui/testgen/TestgenOptionsPanel.java | 138 +- .../ilkd/key/gui/testgen/package-info.java | 2 +- .../main/java/recoder/AbstractService.java | 15 +- .../CrossReferenceServiceConfiguration.java | 11 +- .../recoder/DefaultServiceConfiguration.java | 3 + .../IllegalTransformationException.java | 16 +- .../src/main/java/recoder/ModelElement.java | 12 +- .../src/main/java/recoder/ModelException.java | 5 +- .../main/java/recoder/NamedModelElement.java | 12 +- .../main/java/recoder/ParserException.java | 5 +- .../src/main/java/recoder/ProgramFactory.java | 95 +- .../src/main/java/recoder/Service.java | 12 +- .../java/recoder/ServiceConfiguration.java | 13 +- .../main/java/recoder/TuningParameters.java | 9 +- .../abstraction/AnnotationProperty.java | 17 +- .../recoder/abstraction/AnnotationUse.java | 8 +- .../java/recoder/abstraction/ArrayType.java | 20 +- .../java/recoder/abstraction/ClassType.java | 53 +- .../abstraction/ClassTypeContainer.java | 17 +- .../java/recoder/abstraction/Constructor.java | 9 +- .../abstraction/DefaultConstructor.java | 26 +- .../recoder/abstraction/ElementValuePair.java | 22 +- .../recoder/abstraction/EnumConstant.java | 9 +- .../main/java/recoder/abstraction/Field.java | 5 +- .../abstraction/ImplicitEnumMethod.java | 96 +- .../abstraction/ImplicitEnumValueOf.java | 13 +- .../abstraction/ImplicitEnumValues.java | 13 +- .../recoder/abstraction/IntersectionType.java | 28 +- .../main/java/recoder/abstraction/Member.java | 8 +- .../main/java/recoder/abstraction/Method.java | 7 +- .../java/recoder/abstraction/NullType.java | 23 +- .../java/recoder/abstraction/Package.java | 28 +- .../abstraction/ParameterizedType.java | 45 +- .../recoder/abstraction/PrimitiveType.java | 11 +- .../abstraction/ProgramModelElement.java | 24 +- .../main/java/recoder/abstraction/Type.java | 3 + .../recoder/abstraction/TypeArgument.java | 17 +- .../recoder/abstraction/TypeParameter.java | 16 +- .../java/recoder/abstraction/Variable.java | 5 +- .../java/recoder/bytecode/AccessFlags.java | 5 +- .../bytecode/AnnotationPropertyInfo.java | 15 +- .../recoder/bytecode/AnnotationUseInfo.java | 8 +- .../recoder/bytecode/ByteCodeElement.java | 9 +- .../bytecode/ByteCodeFormatException.java | 5 +- .../java/recoder/bytecode/ByteCodeParser.java | 819 +- .../main/java/recoder/bytecode/ClassFile.java | 10 +- .../recoder/bytecode/ConstructorInfo.java | 11 +- .../bytecode/ElementValuePairInfo.java | 9 +- .../bytecode/EnumConstantReferenceInfo.java | 13 +- .../main/java/recoder/bytecode/FieldInfo.java | 8 +- .../java/recoder/bytecode/MemberInfo.java | 3 + .../java/recoder/bytecode/MethodInfo.java | 9 +- .../recoder/bytecode/ReflectionImport.java | 26 +- .../recoder/bytecode/TypeArgumentInfo.java | 18 +- .../bytecode/TypeNameReferenceInfo.java | 3 + .../recoder/bytecode/TypeParameterInfo.java | 38 +- .../java/recoder/convenience/ASTIterator.java | 58 +- .../convenience/ASTIteratorAdapter.java | 15 +- .../convenience/ASTIteratorListener.java | 39 +- .../convenience/AbstractTreeWalker.java | 17 +- .../recoder/convenience/CustomTreeWalker.java | 31 +- .../recoder/convenience/ForestWalker.java | 8 +- .../main/java/recoder/convenience/Format.java | 326 +- .../java/recoder/convenience/Formats.java | 21 +- .../convenience/ModelElementFilter.java | 5 +- .../recoder/convenience/NameGenerator.java | 43 +- .../convenience/NamedModelElementFilter.java | 13 +- .../main/java/recoder/convenience/Naming.java | 91 +- .../convenience/ProgramElementWalker.java | 9 +- .../java/recoder/convenience/Relations.java | 62 +- .../recoder/convenience/TaggedComment.java | 43 +- .../java/recoder/convenience/TreeWalker.java | 11 +- .../java/recoder/io/ArchiveDataLocation.java | 38 +- .../java/recoder/io/ClassFileRepository.java | 16 +- .../java/recoder/io/DataFileLocation.java | 55 +- .../main/java/recoder/io/DataLocation.java | 59 +- .../io/DefaultClassFileRepository.java | 16 +- .../java/recoder/io/DefaultProjectFileIO.java | 23 +- .../io/DefaultSourceFileRepository.java | 37 +- .../src/main/java/recoder/io/PathList.java | 40 +- .../main/java/recoder/io/ProjectFileIO.java | 14 +- .../main/java/recoder/io/ProjectSettings.java | 49 +- .../main/java/recoder/io/PropertyNames.java | 102 +- .../java/recoder/io/SourceFileRepository.java | 71 +- .../src/main/java/recoder/java/Comment.java | 35 +- .../java/recoder/java/CompilationUnit.java | 59 +- .../main/java/recoder/java/Declaration.java | 7 +- .../main/java/recoder/java/DocComment.java | 8 +- .../main/java/recoder/java/Expression.java | 9 +- .../recoder/java/ExpressionContainer.java | 12 +- .../main/java/recoder/java/Identifier.java | 10 +- .../src/main/java/recoder/java/Import.java | 46 +- .../java/JavaNonTerminalProgramElement.java | 23 +- .../java/recoder/java/JavaProgramElement.java | 5 +- .../java/recoder/java/JavaProgramFactory.java | 254 +- .../java/recoder/java/JavaSourceElement.java | 67 +- .../java/recoder/java/LoopInitializer.java | 5 +- .../recoder/java/NamedProgramElement.java | 5 +- .../java/NonTerminalProgramElement.java | 62 +- .../recoder/java/PackageSpecification.java | 20 +- .../java/recoder/java/ParameterContainer.java | 17 +- .../main/java/recoder/java/PrettyPrinter.java | 224 +- .../recoder/java/PrettyPrintingException.java | 8 +- .../java/recoder/java/ProgramElement.java | 68 +- .../src/main/java/recoder/java/Reference.java | 9 +- .../recoder/java/ScopeDefiningElement.java | 14 +- .../java/recoder/java/SingleLineComment.java | 5 +- .../main/java/recoder/java/SourceElement.java | 111 +- .../main/java/recoder/java/SourceVisitor.java | 247 +- .../src/main/java/recoder/java/Statement.java | 5 +- .../java/recoder/java/StatementBlock.java | 38 +- .../java/recoder/java/StatementContainer.java | 12 +- .../src/main/java/recoder/java/TagInfo.java | 41 +- .../recoder/java/TerminalProgramElement.java | 5 +- .../src/main/java/recoder/java/TypeScope.java | 5 +- .../main/java/recoder/java/VariableScope.java | 8 +- .../declaration/AnnotationDeclaration.java | 18 +- .../AnnotationElementValuePair.java | 87 +- .../AnnotationPropertyDeclaration.java | 27 +- .../AnnotationUseSpecification.java | 74 +- .../java/declaration/ClassDeclaration.java | 32 +- .../java/declaration/ClassInitializer.java | 29 +- .../declaration/ConstructorDeclaration.java | 20 +- .../declaration/DeclarationSpecifier.java | 8 +- .../declaration/EnumConstantDeclaration.java | 32 +- .../EnumConstantSpecification.java | 19 +- .../java/declaration/EnumDeclaration.java | 48 +- .../recoder/java/declaration/Extends.java | 5 +- .../java/declaration/FieldDeclaration.java | 46 +- .../java/declaration/FieldSpecification.java | 15 +- .../recoder/java/declaration/Implements.java | 5 +- .../declaration/InheritanceSpecification.java | 27 +- .../declaration/InterfaceDeclaration.java | 26 +- .../java/declaration/JavaDeclaration.java | 20 +- .../declaration/LocalVariableDeclaration.java | 34 +- .../java/declaration/MemberDeclaration.java | 5 +- .../java/declaration/MethodDeclaration.java | 131 +- .../recoder/java/declaration/Modifier.java | 6 +- .../declaration/ParameterDeclaration.java | 30 +- .../java/recoder/java/declaration/Throws.java | 24 +- .../declaration/TypeArgumentDeclaration.java | 59 +- .../java/declaration/TypeDeclaration.java | 39 +- .../declaration/TypeDeclarationContainer.java | 15 +- .../declaration/TypeParameterDeclaration.java | 55 +- .../java/declaration/VariableDeclaration.java | 22 +- .../declaration/VariableSpecification.java | 41 +- .../java/declaration/modifier/Abstract.java | 5 +- .../java/declaration/modifier/Final.java | 5 +- .../java/declaration/modifier/Native.java | 5 +- .../java/declaration/modifier/Private.java | 5 +- .../java/declaration/modifier/Protected.java | 5 +- .../java/declaration/modifier/Public.java | 5 +- .../java/declaration/modifier/Static.java | 5 +- .../java/declaration/modifier/StrictFp.java | 5 +- .../declaration/modifier/Synchronized.java | 5 +- .../java/declaration/modifier/Transient.java | 5 +- .../modifier/VisibilityModifier.java | 5 +- .../java/declaration/modifier/Volatile.java | 5 +- .../java/expression/ArrayInitializer.java | 34 +- .../recoder/java/expression/Assignment.java | 15 +- .../ElementValueArrayInitializer.java | 60 +- .../java/expression/ExpressionStatement.java | 14 +- .../java/recoder/java/expression/Literal.java | 8 +- .../recoder/java/expression/Operator.java | 68 +- .../expression/ParenthesizedExpression.java | 12 +- .../expression/literal/BooleanLiteral.java | 5 +- .../java/expression/literal/CharLiteral.java | 5 +- .../expression/literal/DoubleLiteral.java | 5 +- .../java/expression/literal/FloatLiteral.java | 5 +- .../java/expression/literal/IntLiteral.java | 5 +- .../java/expression/literal/LongLiteral.java | 5 +- .../java/expression/literal/NullLiteral.java | 5 +- .../expression/literal/StringLiteral.java | 5 +- .../java/expression/operator/BinaryAnd.java | 5 +- .../operator/BinaryAndAssignment.java | 5 +- .../java/expression/operator/BinaryNot.java | 9 +- .../java/expression/operator/BinaryOr.java | 5 +- .../operator/BinaryOrAssignment.java | 5 +- .../java/expression/operator/BinaryXOr.java | 5 +- .../operator/BinaryXOrAssignment.java | 5 +- .../operator/ComparativeOperator.java | 5 +- .../java/expression/operator/Conditional.java | 10 +- .../expression/operator/CopyAssignment.java | 5 +- .../java/expression/operator/Divide.java | 5 +- .../expression/operator/DivideAssignment.java | 5 +- .../java/expression/operator/Equals.java | 5 +- .../expression/operator/GreaterOrEquals.java | 5 +- .../java/expression/operator/GreaterThan.java | 5 +- .../java/expression/operator/Instanceof.java | 10 +- .../expression/operator/LessOrEquals.java | 5 +- .../java/expression/operator/LessThan.java | 5 +- .../java/expression/operator/LogicalAnd.java | 5 +- .../java/expression/operator/LogicalNot.java | 9 +- .../java/expression/operator/LogicalOr.java | 5 +- .../java/expression/operator/Minus.java | 5 +- .../expression/operator/MinusAssignment.java | 5 +- .../java/expression/operator/Modulo.java | 5 +- .../expression/operator/ModuloAssignment.java | 5 +- .../java/expression/operator/Negative.java | 9 +- .../recoder/java/expression/operator/New.java | 55 +- .../java/expression/operator/NewArray.java | 44 +- .../java/expression/operator/NotEquals.java | 5 +- .../java/expression/operator/Plus.java | 5 +- .../expression/operator/PlusAssignment.java | 5 +- .../java/expression/operator/Positive.java | 9 +- .../expression/operator/PostDecrement.java | 5 +- .../expression/operator/PostIncrement.java | 5 +- .../expression/operator/PreDecrement.java | 5 +- .../expression/operator/PreIncrement.java | 5 +- .../java/expression/operator/ShiftLeft.java | 5 +- .../operator/ShiftLeftAssignment.java | 5 +- .../java/expression/operator/ShiftRight.java | 5 +- .../operator/ShiftRightAssignment.java | 5 +- .../java/expression/operator/Times.java | 5 +- .../expression/operator/TimesAssignment.java | 5 +- .../java/expression/operator/TypeCast.java | 17 +- .../expression/operator/TypeOperator.java | 27 +- .../operator/UnsignedShiftRight.java | 5 +- .../UnsignedShiftRightAssignment.java | 5 +- .../AnnotationPropertyReference.java | 24 +- .../java/reference/ArrayLengthReference.java | 24 +- .../java/reference/ArrayReference.java | 37 +- .../java/reference/ConstructorReference.java | 5 +- .../reference/EnumConstructorReference.java | 28 +- .../java/reference/FieldReference.java | 37 +- .../java/reference/MemberReference.java | 5 +- .../java/reference/MetaClassReference.java | 28 +- .../java/reference/MethodReference.java | 47 +- .../recoder/java/reference/NameReference.java | 5 +- .../java/reference/PackageReference.java | 23 +- .../reference/PackageReferenceContainer.java | 5 +- .../java/reference/ReferencePrefix.java | 5 +- .../java/reference/ReferenceSuffix.java | 13 +- .../SpecialConstructorReference.java | 32 +- .../reference/SuperConstructorReference.java | 10 +- .../java/reference/SuperReference.java | 35 +- .../reference/ThisConstructorReference.java | 5 +- .../recoder/java/reference/ThisReference.java | 32 +- .../recoder/java/reference/TypeReference.java | 50 +- .../reference/TypeReferenceContainer.java | 12 +- .../java/reference/TypeReferenceInfix.java | 5 +- .../UncollatedReferenceQualifier.java | 49 +- .../java/reference/VariableReference.java | 21 +- .../java/recoder/java/statement/Assert.java | 26 +- .../java/recoder/java/statement/Branch.java | 5 +- .../java/statement/BranchStatement.java | 12 +- .../java/recoder/java/statement/Break.java | 5 +- .../java/recoder/java/statement/Case.java | 36 +- .../java/recoder/java/statement/Catch.java | 35 +- .../java/recoder/java/statement/Continue.java | 5 +- .../java/recoder/java/statement/Default.java | 27 +- .../main/java/recoder/java/statement/Do.java | 7 +- .../java/recoder/java/statement/Else.java | 24 +- .../java/statement/EmptyStatement.java | 8 +- .../recoder/java/statement/EnhancedFor.java | 59 +- .../statement/ExpressionJumpStatement.java | 24 +- .../java/recoder/java/statement/Finally.java | 24 +- .../main/java/recoder/java/statement/For.java | 16 +- .../main/java/recoder/java/statement/If.java | 39 +- .../recoder/java/statement/JavaStatement.java | 5 +- .../recoder/java/statement/JumpStatement.java | 5 +- .../java/statement/LabelJumpStatement.java | 17 +- .../java/statement/LabeledStatement.java | 25 +- .../recoder/java/statement/LoopStatement.java | 34 +- .../java/recoder/java/statement/Return.java | 5 +- .../java/recoder/java/statement/Switch.java | 39 +- .../java/statement/SynchronizedBlock.java | 36 +- .../java/recoder/java/statement/Then.java | 24 +- .../java/recoder/java/statement/Throw.java | 5 +- .../main/java/recoder/java/statement/Try.java | 33 +- .../java/recoder/java/statement/While.java | 7 +- .../src/main/java/recoder/kit/Ambiguity.java | 11 +- .../main/java/recoder/kit/BrokenContract.java | 10 +- .../src/main/java/recoder/kit/CommentKit.java | 100 +- .../src/main/java/recoder/kit/Conflict.java | 8 +- .../kit/DifferentReturnTypeOverwrite.java | 8 +- .../main/java/recoder/kit/Equivalence.java | 13 +- .../main/java/recoder/kit/ExpressionKit.java | 90 +- .../main/java/recoder/kit/FinalOverwrite.java | 9 +- .../src/main/java/recoder/kit/Identity.java | 11 +- .../recoder/kit/IllegalInterfaceMember.java | 8 +- .../main/java/recoder/kit/IllegalName.java | 6 +- .../src/main/java/recoder/kit/MethodKit.java | 355 +- .../src/main/java/recoder/kit/MiscKit.java | 226 +- .../main/java/recoder/kit/MissingSources.java | 8 +- .../recoder/kit/MissingTypeDeclarations.java | 8 +- .../main/java/recoder/kit/ModifierKit.java | 278 +- .../recoder/kit/MorePrivateOverwrite.java | 8 +- .../java/recoder/kit/NameClashException.java | 5 +- .../main/java/recoder/kit/NameConflict.java | 10 +- .../main/java/recoder/kit/NameGenerator.java | 43 +- .../src/main/java/recoder/kit/NoProblem.java | 13 +- .../java/recoder/kit/NonStaticOverwrite.java | 8 +- .../src/main/java/recoder/kit/PackageKit.java | 23 +- .../src/main/java/recoder/kit/Problem.java | 11 +- .../main/java/recoder/kit/ProblemReport.java | 10 +- .../main/java/recoder/kit/StatementKit.java | 158 +- .../main/java/recoder/kit/Transformation.java | 685 +- .../recoder/kit/TwoPassTransformation.java | 74 +- .../src/main/java/recoder/kit/TypeKit.java | 277 +- .../kit/UncoveredExceptionsOverwrite.java | 7 +- .../src/main/java/recoder/kit/UnitKit.java | 123 +- .../main/java/recoder/kit/VariableKit.java | 152 +- .../recoder/kit/pattern/DesignPattern.java | 5 +- .../java/recoder/kit/pattern/Factory.java | 24 +- .../recoder/kit/pattern/FactoryMethod.java | 27 +- .../pattern/InconsistentPatternException.java | 5 +- .../java/recoder/kit/pattern/Property.java | 39 +- .../kit/transformation/AppendMember.java | 35 +- .../recoder/kit/transformation/Modify.java | 163 +- .../transformation/PrepareStatementList.java | 60 +- .../PrependExpressionWithStatements.java | 45 +- .../RemoveRedundantTypeReferences.java | 39 +- .../transformation/RemoveUnusedImports.java | 20 +- .../kit/transformation/RenameMethod.java | 52 +- .../kit/transformation/RenamePackage.java | 29 +- .../kit/transformation/RenameType.java | 38 +- .../kit/transformation/RenameVariable.java | 30 +- .../ShiftPreceedingStatementExpressions.java | 130 +- .../java5to4/EnhancedFor2For.java | 126 +- .../java5to4/MakeConditionalCompatible.java | 29 +- .../java5to4/RemoveAnnotations.java | 33 +- .../java5to4/RemoveCoVariantReturnTypes.java | 68 +- .../java5to4/RemoveStaticImports.java | 25 +- .../transformation/java5to4/ReplaceEnums.java | 136 +- .../java5to4/ResolveBoxing.java | 39 +- .../java5to4/ResolveGenerics.java | 123 +- .../java5to4/ResolveVarArgs.java | 38 +- .../transformation/java5to4/package-info.java | 7 +- .../recoder/list/generic/ASTArrayList.java | 3 + .../java/recoder/list/generic/ASTList.java | 3 + .../recoder/list/generic/package-info.java | 13 +- .../parser/ASCII_UCodeESC_CharStream.java | 194 +- .../java/recoder/parser/JavaCCParser.java | 8042 ++++++++-------- .../recoder/parser/JavaCCParserConstants.java | 150 +- .../parser/JavaCCParserTokenManager.java | 2956 +++--- .../java/recoder/parser/JavaCharStream.java | 197 +- .../java/recoder/parser/ParseException.java | 162 +- .../src/main/java/recoder/parser/Token.java | 67 +- .../java/recoder/parser/TokenMgrError.java | 121 +- .../AmbiguousDeclarationException.java | 17 +- .../service/AmbiguousImportException.java | 21 +- .../service/AmbiguousReferenceException.java | 26 +- .../AmbiguousStaticFieldImportException.java | 21 +- .../java/recoder/service/AttachChange.java | 5 +- .../java/recoder/service/ByteCodeInfo.java | 27 +- .../java/recoder/service/ChangeHistory.java | 1213 ++- .../recoder/service/ChangeHistoryEvent.java | 8 +- .../service/ChangeHistoryListener.java | 9 +- .../recoder/service/ClassTypeTopSort.java | 5 +- .../recoder/service/ConstantEvaluator.java | 88 +- .../service/CrossReferenceSourceInfo.java | 27 +- .../service/CyclicInheritanceException.java | 7 +- .../recoder/service/DefaultByteCodeInfo.java | 76 +- .../service/DefaultConstantEvaluator.java | 1285 +-- .../DefaultCrossReferenceSourceInfo.java | 156 +- .../recoder/service/DefaultErrorHandler.java | 42 +- .../service/DefaultImplicitElementInfo.java | 39 +- .../java/recoder/service/DefaultNameInfo.java | 107 +- .../service/DefaultProgramModelInfo.java | 248 +- .../recoder/service/DefaultSourceInfo.java | 742 +- .../java/recoder/service/DetachChange.java | 12 +- .../java/recoder/service/ErrorHandler.java | 39 +- .../service/IllegalChangeReportException.java | 5 +- .../service/IllegalModifierException.java | 9 +- .../recoder/service/ImplicitElementInfo.java | 17 +- .../service/MissingClassFileException.java | 11 +- .../recoder/service/ModelUpdateListener.java | 15 +- .../main/java/recoder/service/NameInfo.java | 138 +- .../NoSuchTransformationException.java | 3 + .../recoder/service/ProgramModelInfo.java | 280 +- .../main/java/recoder/service/SourceInfo.java | 148 +- .../main/java/recoder/service/TreeChange.java | 33 +- .../recoder/service/TypeImportException.java | 7 +- .../java/recoder/service/TypingException.java | 5 +- .../service/UnresolvedReferenceException.java | 8 +- .../main/java/recoder/util/AbstractIndex.java | 10 +- .../java/recoder/util/CommandLineProgram.java | 73 +- .../src/main/java/recoder/util/Debug.java | 42 +- .../src/main/java/recoder/util/Equality.java | 22 +- .../main/java/recoder/util/FileCollector.java | 51 +- .../src/main/java/recoder/util/FileUtils.java | 24 +- .../src/main/java/recoder/util/HashCode.java | 24 +- .../main/java/recoder/util/IdentityIndex.java | 5 +- .../util/IllegalOptionValueException.java | 5 +- .../src/main/java/recoder/util/Index.java | 35 +- .../src/main/java/recoder/util/Marker.java | 10 +- .../util/MissingArgumentException.java | 5 +- .../util/MissingOptionValueException.java | 5 +- .../main/java/recoder/util/NaturalIndex.java | 5 +- .../java/recoder/util/ObjectIDAssignment.java | 18 +- .../java/recoder/util/OptionException.java | 5 +- .../main/java/recoder/util/OptionManager.java | 112 +- .../util/OptionMultiplicityException.java | 5 +- .../src/main/java/recoder/util/Order.java | 103 +- .../main/java/recoder/util/ProgressEvent.java | 5 +- .../java/recoder/util/ProgressListener.java | 5 +- .../recoder/util/ProgressListenerManager.java | 10 +- .../src/main/java/recoder/util/Queue.java | 12 +- .../src/main/java/recoder/util/Sorting.java | 48 +- .../main/java/recoder/util/StringUtils.java | 16 +- .../recoder/util/UnknownOptionException.java | 5 +- .../src/main/java/recoder/util/Worklist.java | 29 +- .../testsuite/basic/BasicTestsSuite.java | 11 +- .../testsuite/basic/ParseFilesTest.java | 5 +- .../testsuite/basic/SetupModelTest.java | 3 + .../basic/analysis/AnalysisReportTest.java | 38 +- .../analysis/GetAllRelatedMethodsTest.java | 10 +- ...calVariableXReferenceCompletenessTest.java | 5 +- .../MemberXReferenceCompletenessTest.java | 5 +- .../basic/analysis/ModelRebuildTest.java | 12 +- .../PackageXReferenceCompletenessTest.java | 5 +- .../analysis/ReferenceCompletenessTest.java | 12 +- .../TypeXReferenceCompletenessTest.java | 5 +- .../analysis/XReferenceCompletenessTest.java | 12 +- .../testsuite/basic/syntax/CloneTest.java | 8 +- .../basic/syntax/ParserPrinterTest.java | 5 +- .../basic/syntax/WalkPositionTest.java | 10 +- .../testsuite/fixedbugs/FixedBugs.java | 24 +- .../testsuite/java5test/Java5Test.java | 178 +- .../transformation/TransformationTests.java | 35 +- 3088 files changed, 195250 insertions(+), 201278 deletions(-) diff --git a/key/key.core.example/src/main/java/org/key_project/Main.java b/key/key.core.example/src/main/java/org/key_project/Main.java index a8b062c0da0..b52591c4ae8 100644 --- a/key/key.core.example/src/main/java/org/key_project/Main.java +++ b/key/key.core.example/src/main/java/org/key_project/Main.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package org.key_project; import java.io.File; @@ -24,95 +27,118 @@ import org.slf4j.LoggerFactory; /** - * Example application which proves all proof obligations of - * the source folder 'example' using KeY. + * Example application which proves all proof obligations of the source folder 'example' using KeY. + * * @author Martin Hentschel */ public class Main { - private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); - /** - * The program entry point. - * @param args The start parameters. - */ - public static void main(String[] args) { - File location = args.length == 1 ? - new File(args[0]) : - new File("example"); // Path to the source code folder/file or to a *.proof file - List classPaths = null; // Optionally: Additional specifications for API classes - File bootClassPath = null; // Optionally: Different default specifications for Java API - List includes = null; // Optionally: Additional includes to consider - try { - // Ensure that Taclets are parsed - if (!ProofSettings.isChoiceSettingInitialised()) { - KeYEnvironment env = KeYEnvironment.load(location, classPaths, bootClassPath, includes); - env.dispose(); - } - // Set Taclet options - ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); - HashMap oldSettings = choiceSettings.getDefaultChoices(); - HashMap newSettings = new HashMap<>(oldSettings); - newSettings.putAll(MiscTools.getDefaultTacletOptions()); - choiceSettings.setDefaultChoices(newSettings); - // Load source code - KeYEnvironment env = KeYEnvironment.load(location, classPaths, bootClassPath, includes); // env.getLoadedProof() returns performed proof if a *.proof file is loaded - try { - // List all specifications of all types in the source location (not classPaths and bootClassPath) - final List proofContracts = new LinkedList<>(); - Set kjts = env.getJavaInfo().getAllKeYJavaTypes(); - for (KeYJavaType type : kjts) { - if (!KeYTypeUtil.isLibraryClass(type)) { - ImmutableSet targets = env.getSpecificationRepository().getContractTargets(type); - for (IObserverFunction target : targets) { - ImmutableSet contracts = env.getSpecificationRepository().getContracts(type, target); - for (Contract contract : contracts) { - proofContracts.add(contract); - } - } - } + /** + * The program entry point. + * + * @param args The start parameters. + */ + public static void main(String[] args) { + File location = args.length == 1 ? new File(args[0]) : new File("example"); // Path to the + // source code + // folder/file + // or to a + // *.proof file + List classPaths = null; // Optionally: Additional specifications for API classes + File bootClassPath = null; // Optionally: Different default specifications for Java API + List includes = null; // Optionally: Additional includes to consider + try { + // Ensure that Taclets are parsed + if (!ProofSettings.isChoiceSettingInitialised()) { + KeYEnvironment env = + KeYEnvironment.load(location, classPaths, bootClassPath, includes); + env.dispose(); } - // Perform proofs - for (Contract contract : proofContracts) { - Proof proof = null; - try { - // Create proof - proof = env.createProof(contract.createProofObl(env.getInitConfig(), contract)); - // Set proof strategy options - StrategyProperties sp = proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_CONTRACT); - sp.setProperty(StrategyProperties.DEP_OPTIONS_KEY, StrategyProperties.DEP_ON); - sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, StrategyProperties.QUERY_ON); - sp.setProperty(StrategyProperties.NON_LIN_ARITH_OPTIONS_KEY, StrategyProperties.NON_LIN_ARITH_DEF_OPS); - sp.setProperty(StrategyProperties.STOPMODE_OPTIONS_KEY, StrategyProperties.STOPMODE_NONCLOSE); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); - // Make sure that the new options are used - int maxSteps = 10000; - ProofSettings.DEFAULT_SETTINGS.getStrategySettings().setMaxSteps(maxSteps); - ProofSettings.DEFAULT_SETTINGS.getStrategySettings().setActiveStrategyProperties(sp); - proof.getSettings().getStrategySettings().setMaxSteps(maxSteps); - proof.setActiveStrategy(proof.getServices().getProfile().getDefaultStrategyFactory().create(proof, sp)); - // Start auto mode - env.getUi().getProofControl().startAndWaitForAutoMode(proof); - // Show proof result - boolean closed = proof.openGoals().isEmpty(); - LOGGER.info("Contract '" + contract.getDisplayName() + "' of " + contract.getTarget() + " is " + (closed ? "verified" : "still open") + "."); - } - catch (ProofInputException e) { - LOGGER.error("Exception at {} of {}", contract.getDisplayName(), contract.getTarget()); - } - finally { - if (proof != null) { - proof.dispose(); // Ensure always that all instances of Proof are disposed - } - } + // Set Taclet options + ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); + HashMap oldSettings = choiceSettings.getDefaultChoices(); + HashMap newSettings = new HashMap<>(oldSettings); + newSettings.putAll(MiscTools.getDefaultTacletOptions()); + choiceSettings.setDefaultChoices(newSettings); + // Load source code + KeYEnvironment env = + KeYEnvironment.load(location, classPaths, bootClassPath, includes); // env.getLoadedProof() + // returns + // performed + // proof if + // a *.proof + // file is + // loaded + try { + // List all specifications of all types in the source location (not classPaths and + // bootClassPath) + final List proofContracts = new LinkedList<>(); + Set kjts = env.getJavaInfo().getAllKeYJavaTypes(); + for (KeYJavaType type : kjts) { + if (!KeYTypeUtil.isLibraryClass(type)) { + ImmutableSet targets = + env.getSpecificationRepository().getContractTargets(type); + for (IObserverFunction target : targets) { + ImmutableSet contracts = + env.getSpecificationRepository().getContracts(type, target); + for (Contract contract : contracts) { + proofContracts.add(contract); + } + } + } + } + // Perform proofs + for (Contract contract : proofContracts) { + Proof proof = null; + try { + // Create proof + proof = env.createProof( + contract.createProofObl(env.getInitConfig(), contract)); + // Set proof strategy options + StrategyProperties sp = proof.getSettings().getStrategySettings() + .getActiveStrategyProperties(); + sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, + StrategyProperties.METHOD_CONTRACT); + sp.setProperty(StrategyProperties.DEP_OPTIONS_KEY, + StrategyProperties.DEP_ON); + sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, + StrategyProperties.QUERY_ON); + sp.setProperty(StrategyProperties.NON_LIN_ARITH_OPTIONS_KEY, + StrategyProperties.NON_LIN_ARITH_DEF_OPS); + sp.setProperty(StrategyProperties.STOPMODE_OPTIONS_KEY, + StrategyProperties.STOPMODE_NONCLOSE); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); + // Make sure that the new options are used + int maxSteps = 10000; + ProofSettings.DEFAULT_SETTINGS.getStrategySettings().setMaxSteps(maxSteps); + ProofSettings.DEFAULT_SETTINGS.getStrategySettings() + .setActiveStrategyProperties(sp); + proof.getSettings().getStrategySettings().setMaxSteps(maxSteps); + proof.setActiveStrategy(proof.getServices().getProfile() + .getDefaultStrategyFactory().create(proof, sp)); + // Start auto mode + env.getUi().getProofControl().startAndWaitForAutoMode(proof); + // Show proof result + boolean closed = proof.openGoals().isEmpty(); + LOGGER.info("Contract '" + contract.getDisplayName() + "' of " + + contract.getTarget() + " is " + + (closed ? "verified" : "still open") + "."); + } catch (ProofInputException e) { + LOGGER.error("Exception at {} of {}", contract.getDisplayName(), + contract.getTarget()); + } finally { + if (proof != null) { + proof.dispose(); // Ensure always that all instances of Proof are + // disposed + } + } + } + } finally { + env.dispose(); // Ensure always that all instances of KeYEnvironment are disposed } - } - finally { - env.dispose(); // Ensure always that all instances of KeYEnvironment are disposed - } - } - catch (ProblemLoaderException e) { - LOGGER.info("Exception at '{}'", location, e); - } - } + } catch (ProblemLoaderException e) { + LOGGER.info("Exception at '{}'", location, e); + } + } } diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/ProofReferenceUtil.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/ProofReferenceUtil.java index e1965ed47b5..8f0cc45b4b6 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/ProofReferenceUtil.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/ProofReferenceUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references; import java.util.LinkedHashSet; @@ -21,189 +24,202 @@ /** *

- * This class provides static methods to compute proof references. - * A proof reference is a source code member used during proof like - * methods, instance or class variables or operation contracts. + * This class provides static methods to compute proof references. A proof reference is a source + * code member used during proof like methods, instance or class variables or operation contracts. *

*

* A found proof reference is an instance of {@link IProofReference}. *

*

- * Proof references are computed for each {@link Node} separately based - * on the applied rule. Instances of {@link IProofReferencesAnalyst} are used - * to implement the rule specific extraction of such references. + * Proof references are computed for each {@link Node} separately based on the applied rule. + * Instances of {@link IProofReferencesAnalyst} are used to implement the rule specific extraction + * of such references. *

*

* This functionality is used by the Eclipse Projects like Visual DbC. *

+ * * @author Martin Hentschel * @see IProofReference * @see IProofReferencesAnalyst. */ public final class ProofReferenceUtil { - /** - * The default {@link IProofReferencesAnalyst}s. - */ - public static final ImmutableList DEFAULT_ANALYSTS = ImmutableSLList.nil().append(new MethodBodyExpandProofReferencesAnalyst(), - new MethodCallProofReferencesAnalyst(), - new ContractProofReferencesAnalyst(), - new ProgramVariableReferencesAnalyst(), - new ClassAxiomAndInvariantProofReferencesAnalyst()); - - /** - * Forbid instances. - */ - private ProofReferenceUtil() { - } - - /** - *

- * Computes all proof references in the given {@link Proof} by - * iterating over all {@link Node}s in breath first order. - *

- *

- * Changes during computation of the proof tree are not detected - * and should be avoided. Otherwise it is possible that the result is wrong. - *

- * @param proof The {@link Proof} to compute its references. - * @return The found {@link IProofReference}s. - */ - public static LinkedHashSet> computeProofReferences(Proof proof) { - return computeProofReferences(proof, DEFAULT_ANALYSTS); - } - - /** - *

- * Computes all proof references in the given {@link Proof} by - * iterating over all {@link Node}s in breath first order. - *

- *

- * Changes during computation of the proof tree are not detected - * and should be avoided. Otherwise it is possible that the result is wrong. - *

- * @param proof The {@link Proof} to compute its references. - * @param analysts The {@link IProofReferencesAnalyst} to use. - * @return The found {@link IProofReference}s. - */ - public static LinkedHashSet> computeProofReferences(Proof proof, - ImmutableList analysts) { - if (proof != null) { - Services services = proof.getServices(); - ReferenceAnalaystProofVisitor visitor = new ReferenceAnalaystProofVisitor(services, analysts); - proof.breadthFirstSearch(proof.root(), visitor); - return visitor.getResult(); - } - else { - return new LinkedHashSet>(); - } - } - - /** - * Utility class used by {@link KeyProofReferenceUtil#analyzeProof(KeyConnection, Services, Proof)}. - * @author Martin Hentschel - */ - private static class ReferenceAnalaystProofVisitor implements ProofVisitor { - /** - * The {@link Services} to use. - */ - private Services services; - - /** - * The {@link IProofReferencesAnalyst}s to use. - */ - private ImmutableList analysts; - - /** - * The result. - */ - private LinkedHashSet> result = new LinkedHashSet>(); - - /** - * Constructor. - * @param services The {@link Services} to use. - * @param analysts The {@link IProofReferencesAnalyst}s to use. - */ - public ReferenceAnalaystProofVisitor(Services services, ImmutableList analysts) { - this.services = services; - this.analysts = analysts; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Proof proof, Node visitedNode) { - merge(result, computeProofReferences(visitedNode, services, analysts)); - } - - /** - * Returns the result. - * @return The result. - */ - public LinkedHashSet> getResult() { - return result; - } - } - - /** - * Computes the {@link IProofReference} of the given {@link Node}. - * @param node The {@link Node} to compute its {@link IProofReference}s. - * @param services The {@link Services} to use. - * @return The found {@link IProofReference}s. - */ - public static LinkedHashSet> computeProofReferences(Node node, - Services services) { - return computeProofReferences(node, services, DEFAULT_ANALYSTS); - } - - /** - * Computes the {@link IProofReference} of the given {@link Node}. - * @param node The {@link Node} to compute its {@link IProofReference}s. - * @param services The {@link Services} to use. - * @param analysts The {@link IProofReferencesAnalyst} to use. - * @return The found {@link IProofReference}s. - */ - public static LinkedHashSet> computeProofReferences(Node node, - Services services, - ImmutableList analysts) { - LinkedHashSet> result = new LinkedHashSet>(); - if (node != null && analysts != null) { - for (IProofReferencesAnalyst analyst : analysts) { - LinkedHashSet> analystResult = analyst.computeReferences(node, services); - if (analystResult != null) { - merge(result, analystResult); - } - } - } - return result; - } - - /** - * Merges the {@link IProofReference}s to add into the target. - * @param target The target to add to. - * @param toAdd The {@link IProofReference}s to add. - */ - public static void merge(LinkedHashSet> target, LinkedHashSet> toAdd) { - for (IProofReference reference : toAdd) { - merge(target, reference); - } - } - - /** - * Merges the {@link IProofReference} into the target: - * @param target The target to add to. - * @param reference The {@link IProofReference} to add. - */ - public static void merge(LinkedHashSet> target, final IProofReference reference) { - if (!target.add(reference)) { - // Reference exist before, so merge nodes of both references. - IProofReference existingFirst = CollectionUtil.search(target, new IFilter>() { - @Override - public boolean select(IProofReference element) { - return element.equals(reference); + /** + * The default {@link IProofReferencesAnalyst}s. + */ + public static final ImmutableList DEFAULT_ANALYSTS = ImmutableSLList + .nil().append(new MethodBodyExpandProofReferencesAnalyst(), + new MethodCallProofReferencesAnalyst(), new ContractProofReferencesAnalyst(), + new ProgramVariableReferencesAnalyst(), + new ClassAxiomAndInvariantProofReferencesAnalyst()); + + /** + * Forbid instances. + */ + private ProofReferenceUtil() {} + + /** + *

+ * Computes all proof references in the given {@link Proof} by iterating over all {@link Node}s + * in breath first order. + *

+ *

+ * Changes during computation of the proof tree are not detected and should be avoided. + * Otherwise it is possible that the result is wrong. + *

+ * + * @param proof The {@link Proof} to compute its references. + * @return The found {@link IProofReference}s. + */ + public static LinkedHashSet> computeProofReferences(Proof proof) { + return computeProofReferences(proof, DEFAULT_ANALYSTS); + } + + /** + *

+ * Computes all proof references in the given {@link Proof} by iterating over all {@link Node}s + * in breath first order. + *

+ *

+ * Changes during computation of the proof tree are not detected and should be avoided. + * Otherwise it is possible that the result is wrong. + *

+ * + * @param proof The {@link Proof} to compute its references. + * @param analysts The {@link IProofReferencesAnalyst} to use. + * @return The found {@link IProofReference}s. + */ + public static LinkedHashSet> computeProofReferences(Proof proof, + ImmutableList analysts) { + if (proof != null) { + Services services = proof.getServices(); + ReferenceAnalaystProofVisitor visitor = + new ReferenceAnalaystProofVisitor(services, analysts); + proof.breadthFirstSearch(proof.root(), visitor); + return visitor.getResult(); + } else { + return new LinkedHashSet>(); + } + } + + /** + * Utility class used by + * {@link KeyProofReferenceUtil#analyzeProof(KeyConnection, Services, Proof)}. + * + * @author Martin Hentschel + */ + private static class ReferenceAnalaystProofVisitor implements ProofVisitor { + /** + * The {@link Services} to use. + */ + private Services services; + + /** + * The {@link IProofReferencesAnalyst}s to use. + */ + private ImmutableList analysts; + + /** + * The result. + */ + private LinkedHashSet> result = new LinkedHashSet>(); + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param analysts The {@link IProofReferencesAnalyst}s to use. + */ + public ReferenceAnalaystProofVisitor(Services services, + ImmutableList analysts) { + this.services = services; + this.analysts = analysts; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Proof proof, Node visitedNode) { + merge(result, computeProofReferences(visitedNode, services, analysts)); + } + + /** + * Returns the result. + * + * @return The result. + */ + public LinkedHashSet> getResult() { + return result; + } + } + + /** + * Computes the {@link IProofReference} of the given {@link Node}. + * + * @param node The {@link Node} to compute its {@link IProofReference}s. + * @param services The {@link Services} to use. + * @return The found {@link IProofReference}s. + */ + public static LinkedHashSet> computeProofReferences(Node node, + Services services) { + return computeProofReferences(node, services, DEFAULT_ANALYSTS); + } + + /** + * Computes the {@link IProofReference} of the given {@link Node}. + * + * @param node The {@link Node} to compute its {@link IProofReference}s. + * @param services The {@link Services} to use. + * @param analysts The {@link IProofReferencesAnalyst} to use. + * @return The found {@link IProofReference}s. + */ + public static LinkedHashSet> computeProofReferences(Node node, + Services services, ImmutableList analysts) { + LinkedHashSet> result = new LinkedHashSet>(); + if (node != null && analysts != null) { + for (IProofReferencesAnalyst analyst : analysts) { + LinkedHashSet> analystResult = + analyst.computeReferences(node, services); + if (analystResult != null) { + merge(result, analystResult); + } } - }); - existingFirst.addNodes(reference.getNodes()); - } - } -} \ No newline at end of file + } + return result; + } + + /** + * Merges the {@link IProofReference}s to add into the target. + * + * @param target The target to add to. + * @param toAdd The {@link IProofReference}s to add. + */ + public static void merge(LinkedHashSet> target, + LinkedHashSet> toAdd) { + for (IProofReference reference : toAdd) { + merge(target, reference); + } + } + + /** + * Merges the {@link IProofReference} into the target: + * + * @param target The target to add to. + * @param reference The {@link IProofReference} to add. + */ + public static void merge(LinkedHashSet> target, + final IProofReference reference) { + if (!target.add(reference)) { + // Reference exist before, so merge nodes of both references. + IProofReference existingFirst = + CollectionUtil.search(target, new IFilter>() { + @Override + public boolean select(IProofReference element) { + return element.equals(reference); + } + }); + existingFirst.addNodes(reference.getNodes()); + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ClassAxiomAndInvariantProofReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ClassAxiomAndInvariantProofReferencesAnalyst.java index ddb5498cb03..e0cf10f4ef1 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ClassAxiomAndInvariantProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ClassAxiomAndInvariantProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.Iterator; @@ -25,83 +28,92 @@ /** * Extracts used {@link ClassAxiom} and {@link ClassInvariant}s. + * * @author Martin Hentschel */ public class ClassAxiomAndInvariantProofReferencesAnalyst implements IProofReferencesAnalyst { - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet> computeReferences(Node node, Services services) { - String name = MiscTools.getRuleName(node); - if (name != null && - (name.toLowerCase().contains("axiom_for") || name.toLowerCase().contains("represents_clause_for")) && - node.getAppliedRuleApp() instanceof PosTacletApp) { - // Get KeYJavaType which provides the proof obligation because only for its ClassAxioms are taclets generated and used during proof. - KeYJavaType proofKjt = findProofsKeYJavaType(services); - if (proofKjt != null) { - // Get applied taclet name - Name tacletName = ((PosTacletApp)node.getAppliedRuleApp()).taclet().name(); - // Search ClassAxiom which provides the applied taclet - ImmutableSet axioms = services.getSpecificationRepository().getClassAxioms(proofKjt); - ClassAxiom found = null; - Iterator axiomsIterator = axioms.iterator(); - while (found == null && axiomsIterator.hasNext()) { - ClassAxiom ca = axiomsIterator.next(); - ImmutableSet> toLimit = DefaultImmutableSet.nil(); - ImmutableSet taclets = ca.getTaclets(toLimit, services); - Iterator tacletIterator = taclets.iterator(); - while (found == null && tacletIterator.hasNext()) { - Taclet t = tacletIterator.next(); - if (t.name().equals(tacletName)) { - found = ca; - } - } + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet> computeReferences(Node node, Services services) { + String name = MiscTools.getRuleName(node); + if (name != null + && (name.toLowerCase().contains("axiom_for") + || name.toLowerCase().contains("represents_clause_for")) + && node.getAppliedRuleApp() instanceof PosTacletApp) { + // Get KeYJavaType which provides the proof obligation because only for its ClassAxioms + // are taclets generated and used during proof. + KeYJavaType proofKjt = findProofsKeYJavaType(services); + if (proofKjt != null) { + // Get applied taclet name + Name tacletName = ((PosTacletApp) node.getAppliedRuleApp()).taclet().name(); + // Search ClassAxiom which provides the applied taclet + ImmutableSet axioms = + services.getSpecificationRepository().getClassAxioms(proofKjt); + ClassAxiom found = null; + Iterator axiomsIterator = axioms.iterator(); + while (found == null && axiomsIterator.hasNext()) { + ClassAxiom ca = axiomsIterator.next(); + ImmutableSet> toLimit = DefaultImmutableSet.nil(); + ImmutableSet taclets = ca.getTaclets(toLimit, services); + Iterator tacletIterator = taclets.iterator(); + while (found == null && tacletIterator.hasNext()) { + Taclet t = tacletIterator.next(); + if (t.name().equals(tacletName)) { + found = ca; + } + } + } + if (found instanceof PartialInvAxiom) { + // Invariant was applied + PartialInvAxiom axiom = (PartialInvAxiom) found; + DefaultProofReference reference = + new DefaultProofReference(IProofReference.USE_INVARIANT, + node, axiom.getInv()); + LinkedHashSet> result = + new LinkedHashSet>(); + result.add(reference); + return result; + } else if (found != null) { + // ClassAxiom was applied + DefaultProofReference reference = + new DefaultProofReference(IProofReference.USE_AXIOM, node, + found); + LinkedHashSet> result = + new LinkedHashSet>(); + result.add(reference); + return result; + } else { + throw new IllegalStateException("ClassAxiom for taclet \"" + name + + "\" was not found applied in node \"" + node.serialNr() + "\"."); + } + } else { + return null; // Proof might be disposed. } - if (found instanceof PartialInvAxiom) { - // Invariant was applied - PartialInvAxiom axiom = (PartialInvAxiom)found; - DefaultProofReference reference = new DefaultProofReference(IProofReference.USE_INVARIANT, node, axiom.getInv()); - LinkedHashSet> result = new LinkedHashSet>(); - result.add(reference); - return result; - } - else if (found != null) { - // ClassAxiom was applied - DefaultProofReference reference = new DefaultProofReference(IProofReference.USE_AXIOM, node, found); - LinkedHashSet> result = new LinkedHashSet>(); - result.add(reference); - return result; - } - else { - throw new IllegalStateException("ClassAxiom for taclet \"" + name + "\" was not found applied in node \"" + node.serialNr() + "\"."); + } else { + return null; + } + } + + /** + * Returns the {@link KeYJavaType} which provides the proof obligation of the current proof. + * + * @param services The {@link Services} to use. + * @return The {@link KeYJavaType} which provides the proof obligation or {@code null} if it was + * not possible to compute it. + */ + protected KeYJavaType findProofsKeYJavaType(Services services) { + ProofOblInput problem = + services.getSpecificationRepository().getProofOblInput(services.getProof()); + if (problem != null) { + KeYJavaType type = problem.getContainerType(); + if (type == null) { + throw new IllegalStateException("Problem \"" + problem + "\" is not supported."); } - } - else { + return type; + } else { return null; // Proof might be disposed. - } - } - else { - return null; - } - } - - /** - * Returns the {@link KeYJavaType} which provides the proof obligation of the current proof. - * @param services The {@link Services} to use. - * @return The {@link KeYJavaType} which provides the proof obligation or {@code null} if it was not possible to compute it. - */ - protected KeYJavaType findProofsKeYJavaType(Services services) { - ProofOblInput problem = services.getSpecificationRepository().getProofOblInput(services.getProof()); - if (problem != null) { - KeYJavaType type = problem.getContainerType(); - if (type == null) { - throw new IllegalStateException("Problem \"" + problem + "\" is not supported."); - } - return type; - } - else { - return null; // Proof might be disposed. - } - } -} \ No newline at end of file + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ContractProofReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ContractProofReferencesAnalyst.java index cbc0c0a29dc..9939b3a9ae3 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ContractProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ContractProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.LinkedHashSet; @@ -11,23 +14,25 @@ /** * Extracts used contracts. + * * @author Martin Hentschel */ public class ContractProofReferencesAnalyst implements IProofReferencesAnalyst { - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet> computeReferences(Node node, Services services) { - if (node.getAppliedRuleApp() instanceof AbstractContractRuleApp) { - AbstractContractRuleApp contractRuleApp = (AbstractContractRuleApp)node.getAppliedRuleApp(); - DefaultProofReference reference = new DefaultProofReference(IProofReference.USE_CONTRACT, node, contractRuleApp.getInstantiation()); - LinkedHashSet> result = new LinkedHashSet>(); - result.add(reference); - return result; - } - else { - return null; - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet> computeReferences(Node node, Services services) { + if (node.getAppliedRuleApp() instanceof AbstractContractRuleApp) { + AbstractContractRuleApp contractRuleApp = + (AbstractContractRuleApp) node.getAppliedRuleApp(); + DefaultProofReference reference = new DefaultProofReference( + IProofReference.USE_CONTRACT, node, contractRuleApp.getInstantiation()); + LinkedHashSet> result = new LinkedHashSet>(); + result.add(reference); + return result; + } else { + return null; + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/IProofReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/IProofReferencesAnalyst.java index 69bac0131fc..5d3db59c6ca 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/IProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/IProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.LinkedHashSet; @@ -9,24 +12,27 @@ /** *

- * Instances of this class are used to compute {@link IProofReference} for - * a given {@link Node} based on the applied rule. Each instance of this class - * has the knowledge to extract the references for a single rule or a group of similar rules. + * Instances of this class are used to compute {@link IProofReference} for a given {@link Node} + * based on the applied rule. Each instance of this class has the knowledge to extract the + * references for a single rule or a group of similar rules. *

*

* The complete extraction is done via static methods of {@link ProofReferenceUtil}. *

+ * * @author Martin Hentschel * @see ProofReferenceUtil * @see IProofReference */ public interface IProofReferencesAnalyst { - /** - * Computes the {@link IProofReference} for the given {@link Node} which - * can be {@code null} or an empty set if the applied rule is not supported by this {@link IProofReferencesAnalyst}. - * @param node The {@link Node} to compute its {@link IProofReference}s. - * @param services The {@link Services} to use. - * @return The found {@link IProofReference} or {@code null}/empty set if the applied rule is not supported. - */ - public LinkedHashSet> computeReferences(Node node, Services services); -} \ No newline at end of file + /** + * Computes the {@link IProofReference} for the given {@link Node} which can be {@code null} or + * an empty set if the applied rule is not supported by this {@link IProofReferencesAnalyst}. + * + * @param node The {@link Node} to compute its {@link IProofReference}s. + * @param services The {@link Services} to use. + * @return The found {@link IProofReference} or {@code null}/empty set if the applied rule is + * not supported. + */ + public LinkedHashSet> computeReferences(Node node, Services services); +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodBodyExpandProofReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodBodyExpandProofReferencesAnalyst.java index a278a677e16..a1fe34f0199 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodBodyExpandProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodBodyExpandProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.LinkedHashSet; @@ -12,30 +15,31 @@ /** * Extracts inlined methods. + * * @author Martin Hentschel */ public class MethodBodyExpandProofReferencesAnalyst implements IProofReferencesAnalyst { - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet> computeReferences(Node node, Services services) { - if (node.getAppliedRuleApp() != null && node.getNodeInfo() != null) { - NodeInfo info = node.getNodeInfo(); - if (info.getActiveStatement() instanceof MethodBodyStatement) { - MethodBodyStatement mbs = (MethodBodyStatement)info.getActiveStatement(); - IProgramMethod pm = mbs.getProgramMethod(services); - DefaultProofReference reference = new DefaultProofReference(IProofReference.INLINE_METHOD, node, pm); - LinkedHashSet> result = new LinkedHashSet>(); - result.add(reference); - return result; - } - else { + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet> computeReferences(Node node, Services services) { + if (node.getAppliedRuleApp() != null && node.getNodeInfo() != null) { + NodeInfo info = node.getNodeInfo(); + if (info.getActiveStatement() instanceof MethodBodyStatement) { + MethodBodyStatement mbs = (MethodBodyStatement) info.getActiveStatement(); + IProgramMethod pm = mbs.getProgramMethod(services); + DefaultProofReference reference = + new DefaultProofReference(IProofReference.INLINE_METHOD, + node, pm); + LinkedHashSet> result = new LinkedHashSet>(); + result.add(reference); + return result; + } else { + return null; + } + } else { return null; - } - } - else { - return null; - } - } -} \ No newline at end of file + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodCallProofReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodCallProofReferencesAnalyst.java index 43083805bd3..82e162ffdb5 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodCallProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/MethodCallProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.LinkedHashSet; @@ -32,98 +35,107 @@ /** * Extracts called methods. + * * @author Martin Hentschel */ public class MethodCallProofReferencesAnalyst implements IProofReferencesAnalyst { - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet> computeReferences(Node node, Services services) { - String name = MiscTools.getRuleName(node); - if (name != null && name.toLowerCase().contains("methodcall")) { - NodeInfo info = node.getNodeInfo(); - if (info != null) { - if (info.getActiveStatement() instanceof MethodReference) { - ExecutionContext context = extractContext(node, services); - IProofReference reference = createReference(node, services, context, (MethodReference)info.getActiveStatement()); - LinkedHashSet> result = new LinkedHashSet>(); - result.add(reference); - return result; + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet> computeReferences(Node node, Services services) { + String name = MiscTools.getRuleName(node); + if (name != null && name.toLowerCase().contains("methodcall")) { + NodeInfo info = node.getNodeInfo(); + if (info != null) { + if (info.getActiveStatement() instanceof MethodReference) { + ExecutionContext context = extractContext(node, services); + IProofReference reference = createReference(node, services, + context, (MethodReference) info.getActiveStatement()); + LinkedHashSet> result = + new LinkedHashSet>(); + result.add(reference); + return result; + } else if (info.getActiveStatement() instanceof Assignment) { + Assignment assignment = (Assignment) info.getActiveStatement(); + ExecutionContext context = extractContext(node, services); + LinkedHashSet> result = + new LinkedHashSet>(); + for (int i = 0; i < assignment.getChildCount(); i++) { + ProgramElement child = assignment.getChildAt(i); + if (child instanceof MethodReference) { + IProofReference reference = createReference(node, + services, context, (MethodReference) child); + ProofReferenceUtil.merge(result, reference); + } + } + return result; + } else { + return null; + } + } else { + return null; } - else if (info.getActiveStatement() instanceof Assignment) { - Assignment assignment = (Assignment)info.getActiveStatement(); - ExecutionContext context = extractContext(node, services); - LinkedHashSet> result = new LinkedHashSet>(); - for (int i = 0; i < assignment.getChildCount(); i++) { - ProgramElement child = assignment.getChildAt(i); - if (child instanceof MethodReference) { - IProofReference reference = createReference(node, services, context, (MethodReference)child); - ProofReferenceUtil.merge(result, reference); - } - } - return result; + } else { + return null; + } + } + + /** + * Extracts the {@link ExecutionContext}. + * + * @param node The {@link Node} to extract {@link ExecutionContext} from. + * @param services The {@link Services} to use. + * @return The found {@link ExecutionContext} or {@code null} if not available. + */ + protected ExecutionContext extractContext(Node node, Services services) { + RuleApp app = node.getAppliedRuleApp(); + PosInOccurrence pio = app.posInOccurrence(); + JavaBlock jb = TermBuilder.goBelowUpdates(pio.subTerm()).javaBlock(); + return JavaTools.getInnermostExecutionContext(jb, services); + } + + /** + * Creates an {@link IProofReference} to the called {@link IProgramMethod}. + * + * @param node The {@link Node} which caused the reference. + * @param services The {@link Services} to use. + * @param context The {@link ExecutionContext} to use. + * @param mr The {@link MethodReference}. + * @return The created {@link IProofReference}. + */ + protected IProofReference createReference(Node node, Services services, + ExecutionContext context, MethodReference mr) { + if (context != null) { + KeYJavaType refPrefixType = mr.determineStaticPrefixType(services, context); + IProgramMethod pm = mr.method(services, refPrefixType, context); + return new DefaultProofReference(IProofReference.CALL_METHOD, node, pm); + } else { + if (!(node.getAppliedRuleApp() instanceof PosTacletApp)) { + throw new IllegalArgumentException("PosTacletApp expected."); } - else { - return null; + if (!"staticMethodCallStaticWithAssignmentViaTypereference" + .equals(MiscTools.getRuleName(node))) { + throw new IllegalArgumentException( + "Rule \"staticMethodCallStaticWithAssignmentViaTypereference\" expected, but is \"" + + MiscTools.getRuleName(node) + "\"."); } - } - else { - return null; - } - } - else { - return null; - } - } - - /** - * Extracts the {@link ExecutionContext}. - * @param node The {@link Node} to extract {@link ExecutionContext} from. - * @param services The {@link Services} to use. - * @return The found {@link ExecutionContext} or {@code null} if not available. - */ - protected ExecutionContext extractContext(Node node, Services services) { - RuleApp app = node.getAppliedRuleApp(); - PosInOccurrence pio = app.posInOccurrence(); - JavaBlock jb = TermBuilder.goBelowUpdates(pio.subTerm()).javaBlock(); - return JavaTools.getInnermostExecutionContext(jb, services); - } - - /** - * Creates an {@link IProofReference} to the called {@link IProgramMethod}. - * @param node The {@link Node} which caused the reference. - * @param services The {@link Services} to use. - * @param context The {@link ExecutionContext} to use. - * @param mr The {@link MethodReference}. - * @return The created {@link IProofReference}. - */ - protected IProofReference createReference(Node node, Services services, ExecutionContext context, MethodReference mr) { - if (context != null) { - KeYJavaType refPrefixType = mr.determineStaticPrefixType(services, context); - IProgramMethod pm = mr.method(services, refPrefixType, context); - return new DefaultProofReference(IProofReference.CALL_METHOD, node, pm); - } - else { - if (!(node.getAppliedRuleApp() instanceof PosTacletApp)) { - throw new IllegalArgumentException("PosTacletApp expected."); - } - if (!"staticMethodCallStaticWithAssignmentViaTypereference".equals(MiscTools.getRuleName(node))) { - throw new IllegalArgumentException("Rule \"staticMethodCallStaticWithAssignmentViaTypereference\" expected, but is \"" + MiscTools.getRuleName(node) + "\"."); - } - PosTacletApp app = (PosTacletApp)node.getAppliedRuleApp(); - SchemaVariable methodSV = app.instantiations().lookupVar(new Name("#mn")); - SchemaVariable typeSV = app.instantiations().lookupVar(new Name("#t")); - SchemaVariable argsSV = app.instantiations().lookupVar(new Name("#elist")); - - ProgramElementName method = (ProgramElementName)app.instantiations().getInstantiation(methodSV); - TypeRef type = (TypeRef)app.instantiations().getInstantiation(typeSV); - ImmutableArray args = (ImmutableArray)app.instantiations().getInstantiation(argsSV); - if (!args.isEmpty()) { - throw new IllegalArgumentException("Empty argument list expected."); - } - IProgramMethod pm = services.getJavaInfo().getProgramMethod(type.getKeYJavaType(), method.toString(), ImmutableSLList.nil(), type.getKeYJavaType()); - return new DefaultProofReference(IProofReference.CALL_METHOD, node, pm); - } - } -} \ No newline at end of file + PosTacletApp app = (PosTacletApp) node.getAppliedRuleApp(); + SchemaVariable methodSV = app.instantiations().lookupVar(new Name("#mn")); + SchemaVariable typeSV = app.instantiations().lookupVar(new Name("#t")); + SchemaVariable argsSV = app.instantiations().lookupVar(new Name("#elist")); + + ProgramElementName method = + (ProgramElementName) app.instantiations().getInstantiation(methodSV); + TypeRef type = (TypeRef) app.instantiations().getInstantiation(typeSV); + ImmutableArray args = + (ImmutableArray) app.instantiations().getInstantiation(argsSV); + if (!args.isEmpty()) { + throw new IllegalArgumentException("Empty argument list expected."); + } + IProgramMethod pm = services.getJavaInfo().getProgramMethod(type.getKeYJavaType(), + method.toString(), ImmutableSLList.nil(), type.getKeYJavaType()); + return new DefaultProofReference(IProofReference.CALL_METHOD, node, pm); + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ProgramVariableReferencesAnalyst.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ProgramVariableReferencesAnalyst.java index e7f2fe679ec..6fb4f2c16c2 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ProgramVariableReferencesAnalyst.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/analyst/ProgramVariableReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.analyst; import java.util.LinkedHashSet; @@ -19,69 +22,73 @@ /** * Extracts read and write access to fields ({@link IProgramVariable}) via assignments. + * * @author Martin Hentschel */ public class ProgramVariableReferencesAnalyst implements IProofReferencesAnalyst { - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet> computeReferences(Node node, Services services) { - if (node.getAppliedRuleApp() != null && node.getNodeInfo() != null) { - SourceElement statement = node.getNodeInfo().getActiveStatement(); - if (statement instanceof CopyAssignment) { - LinkedHashSet> result = new LinkedHashSet>(); - listReferences(node, (CopyAssignment)statement, services.getJavaInfo().getArrayLength(), result, true); - return result; - } - else if (statement instanceof If) { - LinkedHashSet> result = new LinkedHashSet>(); - listReferences(node, ((If)statement).getExpression(), services.getJavaInfo().getArrayLength(), result, false); - return result; - } - else { + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet> computeReferences(Node node, Services services) { + if (node.getAppliedRuleApp() != null && node.getNodeInfo() != null) { + SourceElement statement = node.getNodeInfo().getActiveStatement(); + if (statement instanceof CopyAssignment) { + LinkedHashSet> result = new LinkedHashSet>(); + listReferences(node, (CopyAssignment) statement, + services.getJavaInfo().getArrayLength(), result, true); + return result; + } else if (statement instanceof If) { + LinkedHashSet> result = new LinkedHashSet>(); + listReferences(node, ((If) statement).getExpression(), + services.getJavaInfo().getArrayLength(), result, false); + return result; + } else { + return null; + } + } else { return null; - } - } - else { - return null; - } - } - - /** - * Extracts the proof references recursive. - * @param node The node. - * @param pe The current {@link ProgramElement}. - * @param arrayLength The {@link ProgramVariable} used for array length which is ignored. - * @param toFill The {@link LinkedHashSet} to fill. - * @param includeExpressionContainer Include {@link ExpressionContainer}? - */ - protected void listReferences(Node node, ProgramElement pe, ProgramVariable arrayLength, LinkedHashSet> toFill, boolean includeExpressionContainer) { - if (pe instanceof ProgramVariable) { - ProgramVariable pv = (ProgramVariable) pe; - if (pv.isMember()) { - DefaultProofReference reference = new DefaultProofReference(IProofReference.ACCESS, node, (ProgramVariable)pe); - ProofReferenceUtil.merge(toFill, reference); - } - } - else if (pe instanceof FieldReference) { - FieldReference fr = (FieldReference) pe; - ReferencePrefix ref = fr.getReferencePrefix(); - if (ref != null) { - listReferences(node, ref, arrayLength, toFill, includeExpressionContainer); - } - ProgramVariable pv = fr.getProgramVariable(); - if (pv != arrayLength) { - DefaultProofReference reference = new DefaultProofReference(IProofReference.ACCESS, node, pv); - ProofReferenceUtil.merge(toFill, reference); - } - } - else if (includeExpressionContainer && pe instanceof ExpressionContainer) { - ExpressionContainer ec = (ExpressionContainer) pe; - for (int i = ec.getChildCount() - 1; i >= 0; i--) { - ProgramElement element = ec.getChildAt(i); - listReferences(node, element, arrayLength, toFill, includeExpressionContainer); - } - } - } -} \ No newline at end of file + } + } + + /** + * Extracts the proof references recursive. + * + * @param node The node. + * @param pe The current {@link ProgramElement}. + * @param arrayLength The {@link ProgramVariable} used for array length which is ignored. + * @param toFill The {@link LinkedHashSet} to fill. + * @param includeExpressionContainer Include {@link ExpressionContainer}? + */ + protected void listReferences(Node node, ProgramElement pe, ProgramVariable arrayLength, + LinkedHashSet> toFill, boolean includeExpressionContainer) { + if (pe instanceof ProgramVariable) { + ProgramVariable pv = (ProgramVariable) pe; + if (pv.isMember()) { + DefaultProofReference reference = + new DefaultProofReference(IProofReference.ACCESS, node, + (ProgramVariable) pe); + ProofReferenceUtil.merge(toFill, reference); + } + } else if (pe instanceof FieldReference) { + FieldReference fr = (FieldReference) pe; + ReferencePrefix ref = fr.getReferencePrefix(); + if (ref != null) { + listReferences(node, ref, arrayLength, toFill, includeExpressionContainer); + } + ProgramVariable pv = fr.getProgramVariable(); + if (pv != arrayLength) { + DefaultProofReference reference = + new DefaultProofReference(IProofReference.ACCESS, node, + pv); + ProofReferenceUtil.merge(toFill, reference); + } + } else if (includeExpressionContainer && pe instanceof ExpressionContainer) { + ExpressionContainer ec = (ExpressionContainer) pe; + for (int i = ec.getChildCount() - 1; i >= 0; i--) { + ProgramElement element = ec.getChildAt(i); + listReferences(node, element, arrayLength, toFill, includeExpressionContainer); + } + } + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/DefaultProofReference.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/DefaultProofReference.java index d2851dc6ca4..7f307d2f621 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/DefaultProofReference.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/DefaultProofReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.reference; import java.util.Collection; @@ -10,138 +13,138 @@ /** * Default implementation of {@link IProofReference}. + * * @author Martin Hentschel */ public class DefaultProofReference implements IProofReference { - /** - * The reference kind as human readable {@link String}. - */ - private String kind; - - /** - * The source {@link Proof}. - */ - private Proof source; - - /** - * The target source member. - */ - private T target; - - /** - * The {@link Node} in which the reference was found. - */ - private LinkedHashSet nodes = new LinkedHashSet(); - - /** - * Constructor - * @param kind The reference kind as human readable {@link String}. - * @param source The source {@link Proof}. - * @param target The target source member. - */ - public DefaultProofReference(String kind, Node node, T target) { - this.kind = kind; - this.source = node != null ? node.proof() : null; - this.target = target; - this.nodes.add(node); - } - - /** - * {@inheritDoc} - */ - @Override - public T getTarget() { - return target; - } - - /** - * {@inheritDoc} - */ - @Override - public LinkedHashSet getNodes() { - return nodes; - } - - /** - * {@inheritDoc} - */ - @Override - public void addNodes(Collection nodes) { - this.nodes.addAll(nodes); - } - - /** - * {@inheritDoc} - */ - @Override - public String getKind() { - return kind; - } - - /** - * {@inheritDoc} - */ - @Override - public Proof getSource() { - return source; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof IProofReference) { - IProofReference other = (IProofReference)obj; - return ObjectUtil.equals(getKind(), other.getKind()) && - ObjectUtil.equals(getSource(), other.getSource()) && - ObjectUtil.equals(getTarget(), other.getTarget()); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (getKind() != null ? getKind().hashCode() : 0); - result = 31 * result + (getSource() != null ? getSource().hashCode() : 0); - result = 31 * result + (getTarget() != null ? getTarget().hashCode() : 0); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(getKind()); - sb.append( " Proof Reference to \""); - sb.append(getTarget()); - sb.append("\""); - if (!getNodes().isEmpty()) { - sb.append(" at node(s) "); - boolean afterFirst = false; - for (Node node : getNodes()) { - if (afterFirst) { - sb.append(", "); - } - else { - afterFirst = true; + /** + * The reference kind as human readable {@link String}. + */ + private String kind; + + /** + * The source {@link Proof}. + */ + private Proof source; + + /** + * The target source member. + */ + private T target; + + /** + * The {@link Node} in which the reference was found. + */ + private LinkedHashSet nodes = new LinkedHashSet(); + + /** + * Constructor + * + * @param kind The reference kind as human readable {@link String}. + * @param source The source {@link Proof}. + * @param target The target source member. + */ + public DefaultProofReference(String kind, Node node, T target) { + this.kind = kind; + this.source = node != null ? node.proof() : null; + this.target = target; + this.nodes.add(node); + } + + /** + * {@inheritDoc} + */ + @Override + public T getTarget() { + return target; + } + + /** + * {@inheritDoc} + */ + @Override + public LinkedHashSet getNodes() { + return nodes; + } + + /** + * {@inheritDoc} + */ + @Override + public void addNodes(Collection nodes) { + this.nodes.addAll(nodes); + } + + /** + * {@inheritDoc} + */ + @Override + public String getKind() { + return kind; + } + + /** + * {@inheritDoc} + */ + @Override + public Proof getSource() { + return source; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof IProofReference) { + IProofReference other = (IProofReference) obj; + return ObjectUtil.equals(getKind(), other.getKind()) + && ObjectUtil.equals(getSource(), other.getSource()) + && ObjectUtil.equals(getTarget(), other.getTarget()); + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (getKind() != null ? getKind().hashCode() : 0); + result = 31 * result + (getSource() != null ? getSource().hashCode() : 0); + result = 31 * result + (getTarget() != null ? getTarget().hashCode() : 0); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(getKind()); + sb.append(" Proof Reference to \""); + sb.append(getTarget()); + sb.append("\""); + if (!getNodes().isEmpty()) { + sb.append(" at node(s) "); + boolean afterFirst = false; + for (Node node : getNodes()) { + if (afterFirst) { + sb.append(", "); + } else { + afterFirst = true; + } + sb.append(node.serialNr()); } - sb.append(node.serialNr()); - } - } - if (getSource() != null) { - sb.append(" of proof \""); - sb.append(getSource()); - sb.append("\""); - } - return sb.toString(); - } -} \ No newline at end of file + } + if (getSource() != null) { + sb.append(" of proof \""); + sb.append(getSource()); + sb.append("\""); + } + return sb.toString(); + } +} diff --git a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/IProofReference.java b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/IProofReference.java index 223af630126..a74402ca689 100644 --- a/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/IProofReference.java +++ b/key/key.core.proof_references/src/main/java/de/uka/ilkd/key/proof_references/reference/IProofReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.reference; import java.util.Collection; @@ -14,102 +17,113 @@ import de.uka.ilkd.key.speclang.Contract; /** - * A proof reference which points to a source member used during proof. - * By default, instances are created via {@link IProofReferencesAnalyst}s - * during reference computation via static methods of {@link ProofReferenceUtil}. + * A proof reference which points to a source member used during proof. By default, instances are + * created via {@link IProofReferencesAnalyst}s during reference computation via static methods of + * {@link ProofReferenceUtil}. + * * @author Martin Hentschel * @see ProofReferenceUtil * @see IProofReferencesAnalyst. */ public interface IProofReference { - /** - *

- * A method call which determines the possible implementations of a called method. - *

- *

- * References of this kind should provide an {@link IProgramMethod} as target ({@link #getTarget()}). - *

- */ - public static final String CALL_METHOD = "Call Method"; - - /** - *

- * The proof step "methodBodyExpand" that inlines methods. - *

- *

- * References of this kind should provide an {@link IProgramMethod} as target ({@link #getTarget()}). - *

- */ - public static final String INLINE_METHOD = "Inline Method"; + /** + *

+ * A method call which determines the possible implementations of a called method. + *

+ *

+ * References of this kind should provide an {@link IProgramMethod} as target + * ({@link #getTarget()}). + *

+ */ + public static final String CALL_METHOD = "Call Method"; - /** - *

- * The proof step "Use Operation Contract" which approximates a method call via its method contract - * and also the usage of dependency contracts. - *

- *

- * References of this kind should provide a {@link Contract} as target ({@link #getTarget()}). - *

- */ - public static final String USE_CONTRACT = "Use Contract"; - - /** - *

- * Read/Write access of a field like instance or class variables during proof. - *

- *

- * References of this kind should provide an {@link IProgramVariable} as target ({@link #getTarget()}). - *

- */ - public static final String ACCESS = "Access"; - - /** - *

- * Used invariants during proof. - *

- *

- * References of this kind should provide an {@link ClassInvariant} as target ({@link #getTarget()}). - *

- */ - public static final String USE_INVARIANT = "Use Invariant"; - - /** - *

- * Used axioms during proof. - *

- *

- * References of this kind should provide an {@link ClassAxiom} as target ({@link #getTarget()}). - *

- */ - public static final String USE_AXIOM = "Use Axiom"; - - /** - * Returns the reference kind which is a human readable {@link String}. - * @return The reference kind as human readable {@link String}. - */ - public String getKind(); - - /** - * Returns the {@link Node}s in which the reference was found. - * @return The {@link Node}s in which the reference was found. - */ - public LinkedHashSet getNodes(); + /** + *

+ * The proof step "methodBodyExpand" that inlines methods. + *

+ *

+ * References of this kind should provide an {@link IProgramMethod} as target + * ({@link #getTarget()}). + *

+ */ + public static final String INLINE_METHOD = "Inline Method"; - /** - * Adds the given {@link Node}s to the own {@link Node}s. - * @param nodes The {@link Node}s to add. - */ - public void addNodes(Collection nodes); - - /** - * Returns the target source member. - * @return The target source member. - */ - public T getTarget(); - - /** - * Returns the source {@link Proof}. - * @return The source {@link Proof}. - */ - public Proof getSource(); -} \ No newline at end of file + /** + *

+ * The proof step "Use Operation Contract" which approximates a method call via its method + * contract and also the usage of dependency contracts. + *

+ *

+ * References of this kind should provide a {@link Contract} as target ({@link #getTarget()}). + *

+ */ + public static final String USE_CONTRACT = "Use Contract"; + + /** + *

+ * Read/Write access of a field like instance or class variables during proof. + *

+ *

+ * References of this kind should provide an {@link IProgramVariable} as target + * ({@link #getTarget()}). + *

+ */ + public static final String ACCESS = "Access"; + + /** + *

+ * Used invariants during proof. + *

+ *

+ * References of this kind should provide an {@link ClassInvariant} as target + * ({@link #getTarget()}). + *

+ */ + public static final String USE_INVARIANT = "Use Invariant"; + + /** + *

+ * Used axioms during proof. + *

+ *

+ * References of this kind should provide an {@link ClassAxiom} as target + * ({@link #getTarget()}). + *

+ */ + public static final String USE_AXIOM = "Use Axiom"; + + /** + * Returns the reference kind which is a human readable {@link String}. + * + * @return The reference kind as human readable {@link String}. + */ + public String getKind(); + + /** + * Returns the {@link Node}s in which the reference was found. + * + * @return The {@link Node}s in which the reference was found. + */ + public LinkedHashSet getNodes(); + + /** + * Adds the given {@link Node}s to the own {@link Node}s. + * + * @param nodes The {@link Node}s to add. + */ + public void addNodes(Collection nodes); + + /** + * Returns the target source member. + * + * @return The target source member. + */ + public T getTarget(); + + /** + * Returns the source {@link Proof}. + * + * @return The source {@link Proof}. + */ + public Proof getSource(); +} diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/AbstractProofReferenceTestCase.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/AbstractProofReferenceTestCase.java index 4dcdaf1acbd..95b106d51c2 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/AbstractProofReferenceTestCase.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/AbstractProofReferenceTestCase.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase; import de.uka.ilkd.key.control.KeYEnvironment; @@ -35,418 +38,437 @@ /** * Provides the basic functionality to test the proof reference API. + * * @author Martin Hentschel */ public abstract class AbstractProofReferenceTestCase { public static final File TESTCASE_DIRECTORY = FindResources.getTestCasesDirectory(); static { - assertNotNull(TESTCASE_DIRECTORY, "Could not find test case directory"); - } + assertNotNull(TESTCASE_DIRECTORY, "Could not find test case directory"); + } - /** - * Executes the test steps of test methods. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param targetName The target name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param analyst The {@link IProofReferencesAnalyst} to use. - * @param expectedReferences The expected proof references. - * @throws Exception Occurred Exception. - */ - protected void doReferenceFunctionTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String targetName, - boolean useContracts, - IProofReferencesAnalyst analyst, - ExpectedProofReferences... expectedReferences) throws Exception { - doReferenceFunctionTest(baseDir, javaPathInBaseDir, containerTypeName, targetName, useContracts, analyst, null, expectedReferences); - } + /** + * Executes the test steps of test methods. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param targetName The target name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param analyst The {@link IProofReferencesAnalyst} to use. + * @param expectedReferences The expected proof references. + * @throws Exception Occurred Exception. + */ + protected void doReferenceFunctionTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, String targetName, boolean useContracts, + IProofReferencesAnalyst analyst, ExpectedProofReferences... expectedReferences) + throws Exception { + doReferenceFunctionTest(baseDir, javaPathInBaseDir, containerTypeName, targetName, + useContracts, analyst, null, expectedReferences); + } - /** - * Executes the test steps of test methods. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param targetName The target name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param analyst The {@link IProofReferencesAnalyst} to use. - * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. - * @param expectedReferences The expected proof references. - * @throws Exception Occurred Exception. - */ - protected void doReferenceFunctionTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String targetName, - boolean useContracts, - IProofReferencesAnalyst analyst, - IFilter> currentReferenceFilter, - ExpectedProofReferences... expectedReferences) throws Exception { - IProofTester tester = createReferenceMethodTester(analyst, currentReferenceFilter, expectedReferences); - doProofFunctionTest(baseDir, javaPathInBaseDir, containerTypeName, targetName, useContracts, tester); - } + /** + * Executes the test steps of test methods. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param targetName The target name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param analyst The {@link IProofReferencesAnalyst} to use. + * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. + * @param expectedReferences The expected proof references. + * @throws Exception Occurred Exception. + */ + protected void doReferenceFunctionTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, String targetName, boolean useContracts, + IProofReferencesAnalyst analyst, IFilter> currentReferenceFilter, + ExpectedProofReferences... expectedReferences) throws Exception { + IProofTester tester = + createReferenceMethodTester(analyst, currentReferenceFilter, expectedReferences); + doProofFunctionTest(baseDir, javaPathInBaseDir, containerTypeName, targetName, useContracts, + tester); + } - /** - * Executes the test steps of test methods. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param analyst The {@link IProofReferencesAnalyst} to use. - * @param expectedReferences The expected proof references. - * @throws Exception Occurred Exception. - */ - protected void doReferenceMethodTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - boolean useContracts, - IProofReferencesAnalyst analyst, - ExpectedProofReferences... expectedReferences) throws Exception { - doReferenceMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, useContracts, analyst, null, expectedReferences); - } + /** + * Executes the test steps of test methods. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param analyst The {@link IProofReferencesAnalyst} to use. + * @param expectedReferences The expected proof references. + * @throws Exception Occurred Exception. + */ + protected void doReferenceMethodTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, String methodFullName, boolean useContracts, + IProofReferencesAnalyst analyst, ExpectedProofReferences... expectedReferences) + throws Exception { + doReferenceMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, + useContracts, analyst, null, expectedReferences); + } - /** - * Executes the test steps of test methods. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param analyst The {@link IProofReferencesAnalyst} to use. - * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. - * @param expectedReferences The expected proof references. - * @throws Exception Occurred Exception. - */ - protected void doReferenceMethodTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - boolean useContracts, - IProofReferencesAnalyst analyst, - IFilter> currentReferenceFilter, - ExpectedProofReferences... expectedReferences) throws Exception { - IProofTester tester = createReferenceMethodTester(analyst, currentReferenceFilter, expectedReferences); - doProofMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, useContracts, tester); - } + /** + * Executes the test steps of test methods. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param analyst The {@link IProofReferencesAnalyst} to use. + * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. + * @param expectedReferences The expected proof references. + * @throws Exception Occurred Exception. + */ + protected void doReferenceMethodTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, String methodFullName, boolean useContracts, + IProofReferencesAnalyst analyst, IFilter> currentReferenceFilter, + ExpectedProofReferences... expectedReferences) throws Exception { + IProofTester tester = + createReferenceMethodTester(analyst, currentReferenceFilter, expectedReferences); + doProofMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, + useContracts, tester); + } - /** - * Creates the {@link IProofTester} used by {@link #doProofFunctionTest(File, String, String, String, boolean, IProofTester)} - * and {@link #doProofMethodTest(File, String, String, String, boolean, IProofTester)}. - * @param analyst The {@link IProofReferencesAnalyst} to use. - * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. - * @param expectedReferences The expected proof references. - * @return The created {@link IProofTester}. - */ - protected IProofTester createReferenceMethodTester(final IProofReferencesAnalyst analyst, - final IFilter> currentReferenceFilter, - final ExpectedProofReferences... expectedReferences) { - return (environment, proof) -> { - // Compute proof references - ImmutableList analysts = ImmutableSLList.nil(); - if (analyst != null) { - analysts = analysts.append(analyst); - } - LinkedHashSet> references = ProofReferenceUtil.computeProofReferences(proof, analysts); - // Filter references - if (currentReferenceFilter != null) { - LinkedHashSet> filteredReferences = new LinkedHashSet>(); - for (IProofReference reference : references) { - if (currentReferenceFilter.select(reference)) { - filteredReferences.add(reference); - } + /** + * Creates the {@link IProofTester} used by + * {@link #doProofFunctionTest(File, String, String, String, boolean, IProofTester)} and + * {@link #doProofMethodTest(File, String, String, String, boolean, IProofTester)}. + * + * @param analyst The {@link IProofReferencesAnalyst} to use. + * @param currentReferenceFilter An optional {@link IFilter} to limit the references to test. + * @param expectedReferences The expected proof references. + * @return The created {@link IProofTester}. + */ + protected IProofTester createReferenceMethodTester(final IProofReferencesAnalyst analyst, + final IFilter> currentReferenceFilter, + final ExpectedProofReferences... expectedReferences) { + return (environment, proof) -> { + // Compute proof references + ImmutableList analysts = ImmutableSLList.nil(); + if (analyst != null) { + analysts = analysts.append(analyst); } - references = filteredReferences; - } - // Assert proof references - assertReferences(references, expectedReferences); - }; - } + LinkedHashSet> references = + ProofReferenceUtil.computeProofReferences(proof, analysts); + // Filter references + if (currentReferenceFilter != null) { + LinkedHashSet> filteredReferences = + new LinkedHashSet>(); + for (IProofReference reference : references) { + if (currentReferenceFilter.select(reference)) { + filteredReferences.add(reference); + } + } + references = filteredReferences; + } + // Assert proof references + assertReferences(references, expectedReferences); + }; + } - /** - * Extracts all {@link IProofReference}s of the given once which are extracted from the given {@link Node}. - * @param references The {@link IProofReference}s to search in. - * @param node The {@link Node} to look for. - * @return The contained {@link IProofReference}s with the given node. - */ - protected LinkedHashSet> findReferences(LinkedHashSet> references, Node node) { - LinkedHashSet> result = new LinkedHashSet>(); - for (IProofReference reference : references) { - if (reference.getNodes().contains(node)) { - result.add(reference); - } - } - return result; - } + /** + * Extracts all {@link IProofReference}s of the given once which are extracted from the given + * {@link Node}. + * + * @param references The {@link IProofReference}s to search in. + * @param node The {@link Node} to look for. + * @return The contained {@link IProofReference}s with the given node. + */ + protected LinkedHashSet> findReferences( + LinkedHashSet> references, Node node) { + LinkedHashSet> result = new LinkedHashSet>(); + for (IProofReference reference : references) { + if (reference.getNodes().contains(node)) { + result.add(reference); + } + } + return result; + } - /** - * Tests the given {@link IProofReference}s. - * @param expected The expected {@link IProofReference}s. - * @param current The current {@link IProofReference}s. - */ - protected void assertReferences(LinkedHashSet> expected, LinkedHashSet> current) { - assertNotNull(current); - assertNotNull(expected); - assertEquals(current.size(), expected.size()); - Iterator> expectedIter = expected.iterator(); - Iterator> currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - IProofReference expectedReference = expectedIter.next(); - IProofReference currentReference = currentIter.next(); - assertEquals(expectedReference.getKind(), currentReference.getKind()); - if (expectedReference.getTarget() instanceof ClassAxiom) { - assertTrue(currentReference.getTarget() instanceof ClassAxiom); - assertEquals(expectedReference.getTarget().toString(), currentReference.getTarget().toString()); // Instances might be different. - } - else { - assertEquals(expectedReference.getTarget(), currentReference.getTarget()); - } - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } + /** + * Tests the given {@link IProofReference}s. + * + * @param expected The expected {@link IProofReference}s. + * @param current The current {@link IProofReference}s. + */ + protected void assertReferences(LinkedHashSet> expected, + LinkedHashSet> current) { + assertNotNull(current); + assertNotNull(expected); + assertEquals(current.size(), expected.size()); + Iterator> expectedIter = expected.iterator(); + Iterator> currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + IProofReference expectedReference = expectedIter.next(); + IProofReference currentReference = currentIter.next(); + assertEquals(expectedReference.getKind(), currentReference.getKind()); + if (expectedReference.getTarget() instanceof ClassAxiom) { + assertTrue(currentReference.getTarget() instanceof ClassAxiom); + assertEquals(expectedReference.getTarget().toString(), + currentReference.getTarget().toString()); // Instances might be different. + } else { + assertEquals(expectedReference.getTarget(), currentReference.getTarget()); + } + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } - /** - * Tests the given {@link IProofReference}s. - * @param current The current {@link IProofReference}s. - * @param expected The expected {@link ExpectedProofReferences}s. - */ - protected void assertReferences(LinkedHashSet> current, ExpectedProofReferences... expected) { - assertNotNull(current); - assertNotNull(expected); - assertEquals(expected.length, current.size(), "Computed References: " + current); - int i = 0; - for (IProofReference currentReference : current) { - ExpectedProofReferences expectedReference = expected[i]; - assertEquals(expectedReference.getKind(), currentReference.getKind()); - if (expectedReference.getTarget() != null) { - assertNotNull(currentReference.getTarget()); - assertEquals(expectedReference.getTarget(), currentReference.getTarget().toString()); - } - else { - assertNull(currentReference.getTarget()); - } - i++; - } - } + /** + * Tests the given {@link IProofReference}s. + * + * @param current The current {@link IProofReference}s. + * @param expected The expected {@link ExpectedProofReferences}s. + */ + protected void assertReferences(LinkedHashSet> current, + ExpectedProofReferences... expected) { + assertNotNull(current); + assertNotNull(expected); + assertEquals(expected.length, current.size(), "Computed References: " + current); + int i = 0; + for (IProofReference currentReference : current) { + ExpectedProofReferences expectedReference = expected[i]; + assertEquals(expectedReference.getKind(), currentReference.getKind()); + if (expectedReference.getTarget() != null) { + assertNotNull(currentReference.getTarget()); + assertEquals(expectedReference.getTarget(), + currentReference.getTarget().toString()); + } else { + assertNull(currentReference.getTarget()); + } + i++; + } + } - /** - * Defines the values of an expected proof reference. - * @author Martin Hentschel - */ - protected static class ExpectedProofReferences { - /** - * The expected kind. - */ - private final String kind; + /** + * Defines the values of an expected proof reference. + * + * @author Martin Hentschel + */ + protected static class ExpectedProofReferences { + /** + * The expected kind. + */ + private final String kind; - /** - * The expected target. - */ - private final String target; + /** + * The expected target. + */ + private final String target; - /** - * Constructor. - * @param kind The expected kind. - * @param target The expected target. - */ - public ExpectedProofReferences(String kind, String target) { - this.kind = kind; - this.target = target; - } + /** + * Constructor. + * + * @param kind The expected kind. + * @param target The expected target. + */ + public ExpectedProofReferences(String kind, String target) { + this.kind = kind; + this.target = target; + } - /** - * Returns the expected kind. - * @return The expected kind. - */ - public String getKind() { - return kind; - } + /** + * Returns the expected kind. + * + * @return The expected kind. + */ + public String getKind() { + return kind; + } - /** - * Returns the expected target. - * @return The expected target. - */ - public String getTarget() { - return target; - } - } + /** + * Returns the expected target. + * + * @return The expected target. + */ + public String getTarget() { + return target; + } + } - /** - * Does some test steps with a {@link Proof}. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param targetName The target name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param tester The {@link IProofTester} which executes the test steps. - * @throws Exception Occurred Exception. - */ - protected void doProofFunctionTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - final String targetName, - boolean useContracts, - IProofTester tester) throws Exception { - assertNotNull(tester); - KeYEnvironment environment = null; - Proof proof = null; - HashMap originalTacletOptions = null; - boolean usePrettyPrinting = ProofIndependentSettings.isUsePrettyPrinting(); - try { - // Disable pretty printing to make tests more robust against different term representations - ProofIndependentSettings.setUsePrettyPrinting(false); - // Make sure that required files exists - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - // Make sure that the correct taclet options are defined. - originalTacletOptions = HelperClassForTests.setDefaultTacletOptionsForTarget(javaFile, containerTypeName, targetName); - if (!useContracts) { - // set non modular reasoning - ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); - ImmutableSet cs = DefaultImmutableSet.nil(); - cs = cs.add(new Choice("noRestriction", "methodExpansion")); - choiceSettings.updateWith(cs); - } - // Load java file - environment = KeYEnvironment.load(javaFile, null, null, null); - // Search type - KeYJavaType containerKJT = environment.getJavaInfo().getTypeByClassName(containerTypeName, null); - assertNotNull(containerKJT); - // Search observer function - ImmutableSet targets = environment.getSpecificationRepository().getContractTargets(containerKJT); - IObserverFunction target = CollectionUtil.search(targets, element -> targetName.equals(element.toString())); - assertNotNull(target); - // Find first contract. - ImmutableSet contracts = environment.getSpecificationRepository().getContracts(containerKJT, target); - assertFalse(contracts.isEmpty()); - Contract contract = contracts.iterator().next(); - // Start proof - proof = environment.createProof(contract.createProofObl(environment.getInitConfig(), contract)); - assertNotNull(proof); - // Start auto mode - doProofTest(environment, proof, useContracts, tester); - } - finally { - ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); - // Restore taclet options - HelperClassForTests.restoreTacletOptions(originalTacletOptions); - // Dispose proof and environment - if (proof != null) { - proof.dispose(); - } - if (environment != null) { - environment.dispose(); - } - } - } + /** + * Does some test steps with a {@link Proof}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param targetName The target name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param tester The {@link IProofTester} which executes the test steps. + * @throws Exception Occurred Exception. + */ + protected void doProofFunctionTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, final String targetName, boolean useContracts, + IProofTester tester) throws Exception { + assertNotNull(tester); + KeYEnvironment environment = null; + Proof proof = null; + HashMap originalTacletOptions = null; + boolean usePrettyPrinting = ProofIndependentSettings.isUsePrettyPrinting(); + try { + // Disable pretty printing to make tests more robust against different term + // representations + ProofIndependentSettings.setUsePrettyPrinting(false); + // Make sure that required files exists + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + // Make sure that the correct taclet options are defined. + originalTacletOptions = HelperClassForTests.setDefaultTacletOptionsForTarget(javaFile, + containerTypeName, targetName); + if (!useContracts) { + // set non modular reasoning + ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); + ImmutableSet cs = DefaultImmutableSet.nil(); + cs = cs.add(new Choice("noRestriction", "methodExpansion")); + choiceSettings.updateWith(cs); + } + // Load java file + environment = KeYEnvironment.load(javaFile, null, null, null); + // Search type + KeYJavaType containerKJT = + environment.getJavaInfo().getTypeByClassName(containerTypeName, null); + assertNotNull(containerKJT); + // Search observer function + ImmutableSet targets = + environment.getSpecificationRepository().getContractTargets(containerKJT); + IObserverFunction target = CollectionUtil.search(targets, + element -> targetName.equals(element.toString())); + assertNotNull(target); + // Find first contract. + ImmutableSet contracts = + environment.getSpecificationRepository().getContracts(containerKJT, target); + assertFalse(contracts.isEmpty()); + Contract contract = contracts.iterator().next(); + // Start proof + proof = environment + .createProof(contract.createProofObl(environment.getInitConfig(), contract)); + assertNotNull(proof); + // Start auto mode + doProofTest(environment, proof, useContracts, tester); + } finally { + ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); + // Restore taclet options + HelperClassForTests.restoreTacletOptions(originalTacletOptions); + // Dispose proof and environment + if (proof != null) { + proof.dispose(); + } + if (environment != null) { + environment.dispose(); + } + } + } + + /** + * Does some test steps with a {@link Proof}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param useContracts Use contracts or inline method bodies instead. + * @param tester The {@link IProofTester} which executes the test steps. + * @throws Exception Occurred Exception. + */ + protected void doProofMethodTest(File baseDir, String javaPathInBaseDir, + String containerTypeName, String methodFullName, boolean useContracts, + IProofTester tester) throws Exception { + assertNotNull(tester); + KeYEnvironment environment = null; + Proof proof = null; + HashMap originalTacletOptions = null; + boolean usePrettyPrinting = ProofIndependentSettings.isUsePrettyPrinting(); + try { + // Disable pretty printing to make tests more robust against different term + // representations + ProofIndependentSettings.setUsePrettyPrinting(false); + // Make sure that required files exists + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + // Make sure that the correct taclet options are defined. + originalTacletOptions = + HelperClassForTests.setDefaultTacletOptions(baseDir, javaPathInBaseDir); - /** - * Does some test steps with a {@link Proof}. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param useContracts Use contracts or inline method bodies instead. - * @param tester The {@link IProofTester} which executes the test steps. - * @throws Exception Occurred Exception. - */ - protected void doProofMethodTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - boolean useContracts, - IProofTester tester) throws Exception { - assertNotNull(tester); - KeYEnvironment environment = null; - Proof proof = null; - HashMap originalTacletOptions = null; - boolean usePrettyPrinting = ProofIndependentSettings.isUsePrettyPrinting(); - try { - // Disable pretty printing to make tests more robust against different term representations - ProofIndependentSettings.setUsePrettyPrinting(false); - // Make sure that required files exists - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - // Make sure that the correct taclet options are defined. - originalTacletOptions = HelperClassForTests.setDefaultTacletOptions(baseDir, javaPathInBaseDir); - - if (!useContracts) { - // set non modular reasoning - ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); - ImmutableSet cs = DefaultImmutableSet.nil(); - cs = cs.add(new Choice("noRestriction", "methodExpansion")); - choiceSettings.updateWith(cs); - } - // Load java file - environment = KeYEnvironment.load(javaFile, null, null, null); - // Search method to proof - IProgramMethod pm = HelperClassForTests.searchProgramMethod(environment.getServices(), containerTypeName, methodFullName); - // Find first contract. - ImmutableSet operationContracts = environment.getSpecificationRepository().getOperationContracts(pm.getContainerType(), pm); - assertFalse(operationContracts.isEmpty()); - FunctionalOperationContract foc = operationContracts.iterator().next(); - // Start proof - proof = environment.createProof(foc.createProofObl(environment.getInitConfig(), foc)); - assertNotNull(proof); - // Start auto mode - doProofTest(environment, proof, useContracts, tester); - } - finally { - ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); - // Restore taclet options - HelperClassForTests.restoreTacletOptions(originalTacletOptions); - // Dispose proof and environment - if (proof != null) { - proof.dispose(); - } - if (environment != null) { - environment.dispose(); - } - } - } + if (!useContracts) { + // set non modular reasoning + ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); + ImmutableSet cs = DefaultImmutableSet.nil(); + cs = cs.add(new Choice("noRestriction", "methodExpansion")); + choiceSettings.updateWith(cs); + } + // Load java file + environment = KeYEnvironment.load(javaFile, null, null, null); + // Search method to proof + IProgramMethod pm = HelperClassForTests.searchProgramMethod(environment.getServices(), + containerTypeName, methodFullName); + // Find first contract. + ImmutableSet operationContracts = environment + .getSpecificationRepository().getOperationContracts(pm.getContainerType(), pm); + assertFalse(operationContracts.isEmpty()); + FunctionalOperationContract foc = operationContracts.iterator().next(); + // Start proof + proof = environment.createProof(foc.createProofObl(environment.getInitConfig(), foc)); + assertNotNull(proof); + // Start auto mode + doProofTest(environment, proof, useContracts, tester); + } finally { + ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); + // Restore taclet options + HelperClassForTests.restoreTacletOptions(originalTacletOptions); + // Dispose proof and environment + if (proof != null) { + proof.dispose(); + } + if (environment != null) { + environment.dispose(); + } + } + } - /** - * Does some test steps with a {@link Proof}. - * @param environment The {@link KeYEnvironment} which provides the {@link Proof}. - * @param proof The {@link Proof} to test. - * @param useContracts Use contracts or inline method bodies instead. - * @param tester The {@link IProofTester} which executes the test steps. - * @throws Exception Occurred Exception. - */ - protected void doProofTest(KeYEnvironment environment, - Proof proof, - boolean useContracts, - IProofTester tester) throws Exception { - // Test parameters - assertNotNull(environment); - assertNotNull(proof); - assertNotNull(tester); - // Start auto mode - StrategyProperties sp = new StrategyProperties(); - StrategyProperties.setDefaultStrategyProperties(sp, true, useContracts, false, false, false, false); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); - proof.getSettings().getStrategySettings().setMaxSteps(1000); - environment.getProofControl().startAndWaitForAutoMode(proof); - // Do test - tester.doTest(environment, proof); - } + /** + * Does some test steps with a {@link Proof}. + * + * @param environment The {@link KeYEnvironment} which provides the {@link Proof}. + * @param proof The {@link Proof} to test. + * @param useContracts Use contracts or inline method bodies instead. + * @param tester The {@link IProofTester} which executes the test steps. + * @throws Exception Occurred Exception. + */ + protected void doProofTest(KeYEnvironment environment, Proof proof, boolean useContracts, + IProofTester tester) throws Exception { + // Test parameters + assertNotNull(environment); + assertNotNull(proof); + assertNotNull(tester); + // Start auto mode + StrategyProperties sp = new StrategyProperties(); + StrategyProperties.setDefaultStrategyProperties(sp, true, useContracts, false, false, false, + false); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); + proof.getSettings().getStrategySettings().setMaxSteps(1000); + environment.getProofControl().startAndWaitForAutoMode(proof); + // Do test + tester.doTest(environment, proof); + } - /** - * Executes some proof steps with on given {@link Proof}. - * @author Martin Hentschel - */ - protected interface IProofTester { - /** - * Execute the test. - * @param environment The {@link KeYEnvironment} to test. - * @param proof The {@link Proof} to test. - * @throws Exception Occurred Exception. - */ - void doTest(KeYEnvironment environment, Proof proof) throws Exception; - } + /** + * Executes some proof steps with on given {@link Proof}. + * + * @author Martin Hentschel + */ + protected interface IProofTester { + /** + * Execute the test. + * + * @param environment The {@link KeYEnvironment} to test. + * @param proof The {@link Proof} to test. + * @throws Exception Occurred Exception. + */ + void doTest(KeYEnvironment environment, Proof proof) throws Exception; + } } diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestKeYTypeUtil.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestKeYTypeUtil.java index 0eb012db81a..7811c1e84bd 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestKeYTypeUtil.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestKeYTypeUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase; import java.io.File; @@ -13,148 +16,167 @@ /** * Tests {@link KeYTypeUtil}. + * * @author Martin Hentschel */ public class TestKeYTypeUtil extends AbstractProofReferenceTestCase { - /** - * Tests {@link KeYTypeUtil#isInnerType(Services, KeYJavaType)}. - */ - @Test - public void testIsInnerType() throws Exception { - KeYEnvironment environment = KeYEnvironment.load(new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, null, null); - try { - Services services = environment.getServices(); - assertNotNull(services); - // Get KeYJavaTypes to test - KeYJavaType typeWithoutPackage = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); - assertNotNull(typeWithoutPackage); - KeYJavaType typeWithPackage = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); - assertNotNull(typeWithPackage); - KeYJavaType innerTypeWithoutPackage = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); - assertNotNull(innerTypeWithoutPackage); - KeYJavaType innerTypeWithPackage = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); - assertNotNull(innerTypeWithPackage); - // Test null - assertFalse(KeYTypeUtil.isInnerType(services, null)); - assertFalse(KeYTypeUtil.isInnerType(null, typeWithoutPackage)); - assertFalse(KeYTypeUtil.isInnerType(null, null)); - // Test class without package - assertFalse(KeYTypeUtil.isInnerType(services, typeWithoutPackage)); - // Test class with package - assertFalse(KeYTypeUtil.isInnerType(services, typeWithPackage)); - // Test inner class without package - Assertions.assertTrue(KeYTypeUtil.isInnerType(services, innerTypeWithoutPackage)); - // Test inner class with package - Assertions.assertTrue(KeYTypeUtil.isInnerType(services, innerTypeWithPackage)); - } - finally { - environment.dispose(); - } - } - - /** - * Tests {@link KeYTypeUtil#getParentName(Services, KeYJavaType)}. - */ - @Test - public void testGetParentName() throws Exception { - KeYEnvironment environment = KeYEnvironment.load(new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, null, null); - try { - Services services = environment.getServices(); - assertNotNull(services); - // Get KeYJavaTypes to test - KeYJavaType typeWithoutPackage = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); - assertNotNull(typeWithoutPackage); - KeYJavaType typeWithPackage = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); - assertNotNull(typeWithPackage); - KeYJavaType innerTypeWithoutPackage = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); - assertNotNull(innerTypeWithoutPackage); - KeYJavaType innerTypeWithPackage = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); - assertNotNull(innerTypeWithPackage); - // Test null - Assertions.assertNull(KeYTypeUtil.getParentName(services, null)); - Assertions.assertNull(KeYTypeUtil.getParentName(null, typeWithoutPackage)); - Assertions.assertNull(KeYTypeUtil.getParentName(null, null)); - // Test class without package - Assertions.assertNull(KeYTypeUtil.getParentName(services, typeWithoutPackage)); - // Test class with package - assertEquals("model", KeYTypeUtil.getParentName(services, typeWithPackage)); - // Test inner class without package - assertEquals("InnerAndAnonymousTypeTest", KeYTypeUtil.getParentName(services, innerTypeWithoutPackage)); - // Test inner class with package - assertEquals("model.InnerAndAnonymousTypeTest", KeYTypeUtil.getParentName(services, innerTypeWithPackage)); - } - finally { - environment.dispose(); - } - } - - /** - * Tests {@link KeYTypeUtil#isType(Services, String)}. - */ - @Test - public void testIsType() throws Exception { - KeYEnvironment environment = KeYEnvironment.load(new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, null, null); - try { - Services services = environment.getServices(); - assertNotNull(services); - // Test null - assertFalse(KeYTypeUtil.isType(services, null)); - assertFalse(KeYTypeUtil.isType(null, "InnerAndAnonymousTypeTest")); - assertFalse(KeYTypeUtil.isType(null, null)); - // Test invalid names - assertFalse(KeYTypeUtil.isType(services, "Invalid")); - assertFalse(KeYTypeUtil.isType(services, "model.Invalid")); - assertFalse(KeYTypeUtil.isType(services, "invalid.Invalid")); - assertFalse(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest.Invalid")); - assertFalse(KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest.Invalid")); - // Test class without package - Assertions.assertTrue(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest")); - // Test class with package - Assertions.assertTrue(KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest")); - // Test inner class without package - Assertions.assertTrue(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest.IGetter")); - // Test inner class with package - Assertions.assertTrue(KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest.IGetter")); - } - finally { - environment.dispose(); - } - } - - /** - * Tests {@link KeYTypeUtil#getType(de.uka.ilkd.key.java.Services, String)}. - */ - @Test - public void testGetType() throws Exception { - KeYEnvironment environment = KeYEnvironment.load(new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, null, null); - try { - Services services = environment.getServices(); - assertNotNull(services); - // Test null - Assertions.assertNull(KeYTypeUtil.getType(services, null)); - Assertions.assertNull(KeYTypeUtil.getType(null, "InnerAndAnonymousTypeTest")); - Assertions.assertNull(KeYTypeUtil.getType(null, null)); - // Test invalid names - Assertions.assertNull(KeYTypeUtil.getType(services, "Invalid")); - Assertions.assertNull(KeYTypeUtil.getType(services, "model.Invalid")); - Assertions.assertNull(KeYTypeUtil.getType(services, "invalid.Invalid")); - Assertions.assertNull(KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.Invalid")); - Assertions.assertNull(KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.Invalid")); - // Test class without package - KeYJavaType kjt = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); - assertEquals("InnerAndAnonymousTypeTest", kjt.getFullName()); - // Test class with package - kjt = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); - assertEquals("model.InnerAndAnonymousTypeTest", kjt.getFullName()); - // Test inner class without package - kjt = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); - assertEquals("InnerAndAnonymousTypeTest.IGetter", kjt.getFullName()); - // Test inner class with package - kjt = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); - assertEquals("model.InnerAndAnonymousTypeTest.IGetter", kjt.getFullName()); - } - finally { - environment.dispose(); - } - } -} \ No newline at end of file + /** + * Tests {@link KeYTypeUtil#isInnerType(Services, KeYJavaType)}. + */ + @Test + public void testIsInnerType() throws Exception { + KeYEnvironment environment = KeYEnvironment.load( + new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, + null, null); + try { + Services services = environment.getServices(); + assertNotNull(services); + // Get KeYJavaTypes to test + KeYJavaType typeWithoutPackage = + KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); + assertNotNull(typeWithoutPackage); + KeYJavaType typeWithPackage = + KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); + assertNotNull(typeWithPackage); + KeYJavaType innerTypeWithoutPackage = + KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); + assertNotNull(innerTypeWithoutPackage); + KeYJavaType innerTypeWithPackage = + KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); + assertNotNull(innerTypeWithPackage); + // Test null + assertFalse(KeYTypeUtil.isInnerType(services, null)); + assertFalse(KeYTypeUtil.isInnerType(null, typeWithoutPackage)); + assertFalse(KeYTypeUtil.isInnerType(null, null)); + // Test class without package + assertFalse(KeYTypeUtil.isInnerType(services, typeWithoutPackage)); + // Test class with package + assertFalse(KeYTypeUtil.isInnerType(services, typeWithPackage)); + // Test inner class without package + Assertions.assertTrue(KeYTypeUtil.isInnerType(services, innerTypeWithoutPackage)); + // Test inner class with package + Assertions.assertTrue(KeYTypeUtil.isInnerType(services, innerTypeWithPackage)); + } finally { + environment.dispose(); + } + } + + /** + * Tests {@link KeYTypeUtil#getParentName(Services, KeYJavaType)}. + */ + @Test + public void testGetParentName() throws Exception { + KeYEnvironment environment = KeYEnvironment.load( + new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, + null, null); + try { + Services services = environment.getServices(); + assertNotNull(services); + // Get KeYJavaTypes to test + KeYJavaType typeWithoutPackage = + KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); + assertNotNull(typeWithoutPackage); + KeYJavaType typeWithPackage = + KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); + assertNotNull(typeWithPackage); + KeYJavaType innerTypeWithoutPackage = + KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); + assertNotNull(innerTypeWithoutPackage); + KeYJavaType innerTypeWithPackage = + KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); + assertNotNull(innerTypeWithPackage); + // Test null + Assertions.assertNull(KeYTypeUtil.getParentName(services, null)); + Assertions.assertNull(KeYTypeUtil.getParentName(null, typeWithoutPackage)); + Assertions.assertNull(KeYTypeUtil.getParentName(null, null)); + // Test class without package + Assertions.assertNull(KeYTypeUtil.getParentName(services, typeWithoutPackage)); + // Test class with package + assertEquals("model", KeYTypeUtil.getParentName(services, typeWithPackage)); + // Test inner class without package + assertEquals("InnerAndAnonymousTypeTest", + KeYTypeUtil.getParentName(services, innerTypeWithoutPackage)); + // Test inner class with package + assertEquals("model.InnerAndAnonymousTypeTest", + KeYTypeUtil.getParentName(services, innerTypeWithPackage)); + } finally { + environment.dispose(); + } + } + + /** + * Tests {@link KeYTypeUtil#isType(Services, String)}. + */ + @Test + public void testIsType() throws Exception { + KeYEnvironment environment = KeYEnvironment.load( + new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, + null, null); + try { + Services services = environment.getServices(); + assertNotNull(services); + // Test null + assertFalse(KeYTypeUtil.isType(services, null)); + assertFalse(KeYTypeUtil.isType(null, "InnerAndAnonymousTypeTest")); + assertFalse(KeYTypeUtil.isType(null, null)); + // Test invalid names + assertFalse(KeYTypeUtil.isType(services, "Invalid")); + assertFalse(KeYTypeUtil.isType(services, "model.Invalid")); + assertFalse(KeYTypeUtil.isType(services, "invalid.Invalid")); + assertFalse(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest.Invalid")); + assertFalse(KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest.Invalid")); + // Test class without package + Assertions.assertTrue(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest")); + // Test class with package + Assertions.assertTrue(KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest")); + // Test inner class without package + Assertions + .assertTrue(KeYTypeUtil.isType(services, "InnerAndAnonymousTypeTest.IGetter")); + // Test inner class with package + Assertions.assertTrue( + KeYTypeUtil.isType(services, "model.InnerAndAnonymousTypeTest.IGetter")); + } finally { + environment.dispose(); + } + } + + /** + * Tests {@link KeYTypeUtil#getType(de.uka.ilkd.key.java.Services, String)}. + */ + @Test + public void testGetType() throws Exception { + KeYEnvironment environment = KeYEnvironment.load( + new File(TESTCASE_DIRECTORY, "/proofReferences/InnerAndAnonymousTypeTest"), null, + null, null); + try { + Services services = environment.getServices(); + assertNotNull(services); + // Test null + Assertions.assertNull(KeYTypeUtil.getType(services, null)); + Assertions.assertNull(KeYTypeUtil.getType(null, "InnerAndAnonymousTypeTest")); + Assertions.assertNull(KeYTypeUtil.getType(null, null)); + // Test invalid names + Assertions.assertNull(KeYTypeUtil.getType(services, "Invalid")); + Assertions.assertNull(KeYTypeUtil.getType(services, "model.Invalid")); + Assertions.assertNull(KeYTypeUtil.getType(services, "invalid.Invalid")); + Assertions + .assertNull(KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.Invalid")); + Assertions.assertNull( + KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.Invalid")); + // Test class without package + KeYJavaType kjt = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest"); + assertEquals("InnerAndAnonymousTypeTest", kjt.getFullName()); + // Test class with package + kjt = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest"); + assertEquals("model.InnerAndAnonymousTypeTest", kjt.getFullName()); + // Test inner class without package + kjt = KeYTypeUtil.getType(services, "InnerAndAnonymousTypeTest.IGetter"); + assertEquals("InnerAndAnonymousTypeTest.IGetter", kjt.getFullName()); + // Test inner class with package + kjt = KeYTypeUtil.getType(services, "model.InnerAndAnonymousTypeTest.IGetter"); + assertEquals("model.InnerAndAnonymousTypeTest.IGetter", kjt.getFullName()); + } finally { + environment.dispose(); + } + } +} diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestProofReferenceUtil.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestProofReferenceUtil.java index a09d832eb43..505ab1b8440 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestProofReferenceUtil.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/TestProofReferenceUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase; import de.uka.ilkd.key.proof.Node; @@ -16,120 +19,118 @@ /** * Tests for {@link ProofReferenceUtil}. + * * @author Martin Hentschel */ public class TestProofReferenceUtil extends AbstractProofReferenceTestCase { - /** - * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and - * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. - */ - @Test - public void testReferenceComputation_ExpandAndContract() throws Exception { - doAPITest(TESTCASE_DIRECTORY, + /** + * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and + * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. + */ + @Test + public void testReferenceComputation_ExpandAndContract() throws Exception { + doAPITest(TESTCASE_DIRECTORY, "/proofReferences/UseOperationContractTest/UseOperationContractTest.java", - "UseOperationContractTest", - "main", - true, - ImmutableSLList.nil().append(new MethodBodyExpandProofReferencesAnalyst(), new ContractProofReferencesAnalyst()), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "UseOperationContractTest::main"), - new ExpectedProofReferences(IProofReference.USE_CONTRACT, "pre: {heap=java.lang.Object::(heap,self)<>}; mby: null; post: {heap=and(and(equals(result_magic42,Z(2(4(#))))<>,java.lang.Object::(heap,self)<>)<>,equals(exc<>,null)<>)}; mods: {heap=allLocs, savedHeap=null}; hasMod: {heap=true, savedHeap=true}; termination: diamond; transaction: false")); - } + "UseOperationContractTest", "main", true, + ImmutableSLList.nil().append( + new MethodBodyExpandProofReferencesAnalyst(), + new ContractProofReferencesAnalyst()), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "UseOperationContractTest::main"), + new ExpectedProofReferences(IProofReference.USE_CONTRACT, + "pre: {heap=java.lang.Object::(heap,self)<>}; mby: null; post: {heap=and(and(equals(result_magic42,Z(2(4(#))))<>,java.lang.Object::(heap,self)<>)<>,equals(exc<>,null)<>)}; mods: {heap=allLocs, savedHeap=null}; hasMod: {heap=true, savedHeap=true}; termination: diamond; transaction: false")); + } - /** - * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and - * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. - */ - @Test - public void testReferenceComputation_NoAnalysts() throws Exception { - doAPITest(TESTCASE_DIRECTORY, - "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", - "MethodBodyExpand", - "main", - false, - ImmutableSLList.nil()); - } + /** + * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and + * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. + */ + @Test + public void testReferenceComputation_NoAnalysts() throws Exception { + doAPITest(TESTCASE_DIRECTORY, "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", + "MethodBodyExpand", "main", false, ImmutableSLList.nil()); + } - /** - * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and - * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. - */ - @Test - public void testReferenceComputation_ContractOnly() throws Exception { - doAPITest(TESTCASE_DIRECTORY, - "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", - "MethodBodyExpand", - "main", - false, - ImmutableSLList.nil().append(new ContractProofReferencesAnalyst())); - } + /** + * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and + * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. + */ + @Test + public void testReferenceComputation_ContractOnly() throws Exception { + doAPITest(TESTCASE_DIRECTORY, "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", + "MethodBodyExpand", "main", false, ImmutableSLList.nil() + .append(new ContractProofReferencesAnalyst())); + } - /** - * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and - * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. - */ - @Test - public void testReferenceComputation_ExpandOnly() throws Exception { - doAPITest(TESTCASE_DIRECTORY, - "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", - "MethodBodyExpand", - "main", - false, - ImmutableSLList.nil().append(new MethodBodyExpandProofReferencesAnalyst()), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::main"), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::magic42")); - } + /** + * Tests {@link ProofReferenceUtil#computeProofReferences(Proof, ImmutableList)} and + * {@link ProofReferenceUtil#computeProofReferences(Node, ImmutableList)}. + */ + @Test + public void testReferenceComputation_ExpandOnly() throws Exception { + doAPITest(TESTCASE_DIRECTORY, "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", + "MethodBodyExpand", "main", false, + ImmutableSLList.nil() + .append(new MethodBodyExpandProofReferencesAnalyst()), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::main"), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::magic42")); + } - /** - * Tests {@link ProofReferenceUtil#computeProofReferences(Proof)} and - * {@link ProofReferenceUtil#computeProofReferences(Node)}. - */ - @Test - public void testReferenceComputation_DefaultAnalysts() throws Exception { - doAPITest(TESTCASE_DIRECTORY, - "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", - "MethodBodyExpand", - "main", - false, - null, - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),true)"), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::main"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "MethodBodyExpand::magic42"), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::magic42")); - } + /** + * Tests {@link ProofReferenceUtil#computeProofReferences(Proof)} and + * {@link ProofReferenceUtil#computeProofReferences(Node)}. + */ + @Test + public void testReferenceComputation_DefaultAnalysts() throws Exception { + doAPITest(TESTCASE_DIRECTORY, "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", + "MethodBodyExpand", "main", false, null, + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),true)"), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::main"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "MethodBodyExpand::magic42"), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::magic42")); + } - /** - * Executes the test steps of test methods. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param useContracts Use method contracts or inline method bodies instead? - * @param analysts The {@link IProofReferencesAnalyst} to use. - * @param expectedReferences The expected proof references. - * @throws Exception Occurred Exception. - */ - protected void doAPITest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - boolean useContracts, - final ImmutableList analysts, - final ExpectedProofReferences... expectedReferences) throws Exception { - IProofTester tester = (environment, proof) -> { - // Extract and assert proof references - final LinkedHashSet> references = analysts != null ? - ProofReferenceUtil.computeProofReferences(proof, analysts) : - ProofReferenceUtil.computeProofReferences(proof); - assertReferences(references, expectedReferences); - // Test references of each node individually - proof.breadthFirstSearch(proof.root(), (proof1, visitedNode) -> { - LinkedHashSet> expectedNodeRefs = findReferences(references, visitedNode); - LinkedHashSet> currentNodeRefs = analysts != null ? - ProofReferenceUtil.computeProofReferences(visitedNode, proof1.getServices(), analysts) : - ProofReferenceUtil.computeProofReferences(visitedNode, proof1.getServices()); - assertReferences(expectedNodeRefs, currentNodeRefs); - }); - }; - doProofMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, useContracts, tester); - } + /** + * Executes the test steps of test methods. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param useContracts Use method contracts or inline method bodies instead? + * @param analysts The {@link IProofReferencesAnalyst} to use. + * @param expectedReferences The expected proof references. + * @throws Exception Occurred Exception. + */ + protected void doAPITest(File baseDir, String javaPathInBaseDir, String containerTypeName, + String methodFullName, boolean useContracts, + final ImmutableList analysts, + final ExpectedProofReferences... expectedReferences) throws Exception { + IProofTester tester = (environment, proof) -> { + // Extract and assert proof references + final LinkedHashSet> references = + analysts != null ? ProofReferenceUtil.computeProofReferences(proof, analysts) + : ProofReferenceUtil.computeProofReferences(proof); + assertReferences(references, expectedReferences); + // Test references of each node individually + proof.breadthFirstSearch(proof.root(), (proof1, visitedNode) -> { + LinkedHashSet> expectedNodeRefs = + findReferences(references, visitedNode); + LinkedHashSet> currentNodeRefs = analysts != null + ? ProofReferenceUtil.computeProofReferences(visitedNode, + proof1.getServices(), analysts) + : ProofReferenceUtil.computeProofReferences(visitedNode, + proof1.getServices()); + assertReferences(expectedNodeRefs, currentNodeRefs); + }); + }; + doProofMethodTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, + useContracts, tester); + } } diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestClassAxiomAndInvariantProofReferencesAnalyst.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestClassAxiomAndInvariantProofReferencesAnalyst.java index 6dbaa0a0e11..13acb43d5c8 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestClassAxiomAndInvariantProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestClassAxiomAndInvariantProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase.analyst; import de.uka.ilkd.key.proof_references.analyst.ClassAxiomAndInvariantProofReferencesAnalyst; @@ -10,7 +13,8 @@ * * @author Martin Hentschel */ -public class TestClassAxiomAndInvariantProofReferencesAnalyst extends AbstractProofReferenceTestCase { +public class TestClassAxiomAndInvariantProofReferencesAnalyst + extends AbstractProofReferenceTestCase { /** * Tests "InvariantInOperationContractOfArgument". */ @@ -18,12 +22,11 @@ public class TestClassAxiomAndInvariantProofReferencesAnalyst extends AbstractPr public void testInvariantInOperationContractOfArgument() throws Exception { doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/InvariantInOperationContractOfArgument/InvariantInOperationContractOfArgument.java", - "InvariantInOperationContractOfArgument", - "main", - false, + "InvariantInOperationContractOfArgument", "main", false, new ClassAxiomAndInvariantProofReferencesAnalyst(), element -> IProofReference.USE_INVARIANT.equals(element.getKind()), - new ExpectedProofReferences(IProofReference.USE_INVARIANT, "and(geq(int::select(heap,self,Child::$x),Z(0(#))),leq(int::select(heap,self,Child::$x),Z(0(1(#)))))<>")); + new ExpectedProofReferences(IProofReference.USE_INVARIANT, + "and(geq(int::select(heap,self,Child::$x),Z(0(#))),leq(int::select(heap,self,Child::$x),Z(0(1(#)))))<>")); } /** @@ -33,12 +36,11 @@ public void testInvariantInOperationContractOfArgument() throws Exception { public void testInvariantInOperationContract() throws Exception { doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/InvariantInOperationContract/InvariantInOperationContract.java", - "InvariantInOperationContract", - "main", - false, + "InvariantInOperationContract", "main", false, new ClassAxiomAndInvariantProofReferencesAnalyst(), element -> IProofReference.USE_AXIOM.equals(element.getKind()), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),not(equals(Child::select(heap,self,InvariantInOperationContract::$child),null)))")); + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),not(equals(Child::select(heap,self,InvariantInOperationContract::$child),null)))")); } /** @@ -48,12 +50,11 @@ public void testInvariantInOperationContract() throws Exception { public void testNestedInvariantInOperationContract() throws Exception { doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/NestedInvariantInOperationContract/NestedInvariantInOperationContract.java", - "NestedInvariantInOperationContract", - "main", - false, + "NestedInvariantInOperationContract", "main", false, new ClassAxiomAndInvariantProofReferencesAnalyst(), element -> IProofReference.USE_AXIOM.equals(element.getKind()), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),not(equals(ChildContainer::select(heap,self,NestedInvariantInOperationContract::$cc),null)))")); + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),not(equals(ChildContainer::select(heap,self,NestedInvariantInOperationContract::$cc),null)))")); } /** @@ -62,13 +63,12 @@ public void testNestedInvariantInOperationContract() throws Exception { @Test public void testModelFieldTest_doubleX() throws Exception { doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ModelFieldTest/ModelFieldTest.java", - "test.ModelFieldTest", - "doubleX", - false, - new ClassAxiomAndInvariantProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),true)"), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equals(test.ModelFieldTest::$f(heap,self),javaMulInt(Z(2(#)),int::select(heap,self,test.ModelFieldTest::$x)))")); + "/proofReferences/ModelFieldTest/ModelFieldTest.java", "test.ModelFieldTest", + "doubleX", false, new ClassAxiomAndInvariantProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),true)"), + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equals(test.ModelFieldTest::$f(heap,self),javaMulInt(Z(2(#)),int::select(heap,self,test.ModelFieldTest::$x)))")); } /** @@ -77,25 +77,24 @@ public void testModelFieldTest_doubleX() throws Exception { @Test public void testModelFieldTest_f() throws Exception { doReferenceFunctionTest(TESTCASE_DIRECTORY, - "/proofReferences/ModelFieldTest/ModelFieldTest.java", - "test.ModelFieldTest", - "test.ModelFieldTest::$f", - false, + "/proofReferences/ModelFieldTest/ModelFieldTest.java", "test.ModelFieldTest", + "test.ModelFieldTest::$f", false, new ClassAxiomAndInvariantProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),true)"), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equals(test.ModelFieldTest::$f(heap,self),javaMulInt(Z(2(#)),int::select(heap,self,test.ModelFieldTest::$x)))")); + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),true)"), + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equals(test.ModelFieldTest::$f(heap,self),javaMulInt(Z(2(#)),int::select(heap,self,test.ModelFieldTest::$x)))")); } - /** - * Tests "AccessibleTest". - */ - public void testAccessibleTest() throws Exception { - doReferenceFunctionTest(TESTCASE_DIRECTORY, - "/proofReferences/AccessibleTest/AccessibleTest.java", - "test.B", - "java.lang.Object::", - false, - new ClassAxiomAndInvariantProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.USE_AXIOM, "equiv(java.lang.Object::(heap,self),java.lang.Object::(heap,test.AccessibleTest::select(heap,self,test.B::$c)))")); - } + /** + * Tests "AccessibleTest". + */ + public void testAccessibleTest() throws Exception { + doReferenceFunctionTest(TESTCASE_DIRECTORY, + "/proofReferences/AccessibleTest/AccessibleTest.java", "test.B", + "java.lang.Object::", false, + new ClassAxiomAndInvariantProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.USE_AXIOM, + "equiv(java.lang.Object::(heap,self),java.lang.Object::(heap,test.AccessibleTest::select(heap,self,test.B::$c)))")); + } } diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestContractProofReferencesAnalyst.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestContractProofReferencesAnalyst.java index 0b1dd13b083..99237b60137 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestContractProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestContractProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase.analyst; import de.uka.ilkd.key.proof_references.analyst.ContractProofReferencesAnalyst; @@ -7,20 +10,19 @@ /** * Tests for {@link ContractProofReferencesAnalyst}. + * * @author Martin Hentschel */ public class TestContractProofReferencesAnalyst extends AbstractProofReferenceTestCase { - /** - * Tests "UseOperationContractTest". - */ - @Test - public void testUseOperationContracts() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/UseOperationContractTest/UseOperationContractTest.java", - "UseOperationContractTest", - "main", - true, - new ContractProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.USE_CONTRACT, "pre: {heap=java.lang.Object::(heap,self)<>}; mby: null; post: {heap=and(and(equals(result_magic42,Z(2(4(#))))<>,java.lang.Object::(heap,self)<>)<>,equals(exc<>,null)<>)}; mods: {heap=allLocs, savedHeap=null}; hasMod: {heap=true, savedHeap=true}; termination: diamond; transaction: false")); - } + /** + * Tests "UseOperationContractTest". + */ + @Test + public void testUseOperationContracts() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/UseOperationContractTest/UseOperationContractTest.java", + "UseOperationContractTest", "main", true, new ContractProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.USE_CONTRACT, + "pre: {heap=java.lang.Object::(heap,self)<>}; mby: null; post: {heap=and(and(equals(result_magic42,Z(2(4(#))))<>,java.lang.Object::(heap,self)<>)<>,equals(exc<>,null)<>)}; mods: {heap=allLocs, savedHeap=null}; hasMod: {heap=true, savedHeap=true}; termination: diamond; transaction: false")); + } } diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodBodyExpandProofReferencesAnalyst.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodBodyExpandProofReferencesAnalyst.java index 88d814c2fea..06785d445f5 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodBodyExpandProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodBodyExpandProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase.analyst; import de.uka.ilkd.key.proof_references.analyst.MethodBodyExpandProofReferencesAnalyst; @@ -7,21 +10,21 @@ /** * Tests for {@link MethodBodyExpandProofReferencesAnalyst}. + * * @author Martin Hentschel */ public class TestMethodBodyExpandProofReferencesAnalyst extends AbstractProofReferenceTestCase { - /** - * Tests "MethodBodyExpand". - */ - @Test - public void testMethodBodyExpand() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", - "MethodBodyExpand", - "main", - false, - new MethodBodyExpandProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::main"), - new ExpectedProofReferences(IProofReference.INLINE_METHOD, "MethodBodyExpand::magic42")); - } -} \ No newline at end of file + /** + * Tests "MethodBodyExpand". + */ + @Test + public void testMethodBodyExpand() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/MethodBodyExpand/MethodBodyExpand.java", "MethodBodyExpand", + "main", false, new MethodBodyExpandProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::main"), + new ExpectedProofReferences(IProofReference.INLINE_METHOD, + "MethodBodyExpand::magic42")); + } +} diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodCallProofReferencesAnalyst.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodCallProofReferencesAnalyst.java index 6470656dec1..53ce7d7fb0c 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodCallProofReferencesAnalyst.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestMethodCallProofReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase.analyst; import de.uka.ilkd.key.proof_references.analyst.MethodCallProofReferencesAnalyst; @@ -7,152 +10,139 @@ /** * Tests for {@link MethodCallProofReferencesAnalyst}. + * * @author Martin Hentschel */ public class TestMethodCallProofReferencesAnalyst extends AbstractProofReferenceTestCase { - /** - * Tests "constructorTest". - */ - @Test - public void testConstructorTest() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/constructorTest/ConstructorTest.java", - "ConstructorTest", - "ConstructorTest", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "ConstructorTest::"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "ConstructorTest::"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "ConstructorTest::"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "java.lang.Object::"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "java.lang.Object::"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "A::magic"), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "B::staticMagic")); - } - - /** - * Tests "methodCall". - */ - @Test - public void testMethodCall() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCall/MethodCall.java", - "methodCall.MethodCall", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCall.Class::a")); - } - - /** - * Tests "methodCallSuper". - */ - @Test - public void testMethodCallSuper() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCallSuper/MethodCallSuper.java", - "methodCallSuper.MethodCallSuper", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCallSuper.Super::a")); - } - - /** - * Tests "methodCallWithAssignment". - */ - @Test - public void testMethodCallWithAssignment() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCallWithAssignment/MethodCall.java", - "methodCallWithAssignment.MethodCall", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCallWithAssignment.Class::a")); - } - - /** - * Tests "methodCallWithAssignmentSuper". - */ - @Test - public void testMethodCallWithAssignmentSuper() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCallWithAssignmentSuper/MethodCallWithAssignmentSuper.java", - "methodCallWithAssignmentSuper.MethodCallWithAssignmentSuper", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCallWithAssignmentSuper.Super::a")); - } - - /** - * Tests "methodCallWithAssignmentWithinClass". - */ - @Test - public void testMethodCallWithAssignmentWithinClass() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCallWithAssignmentWithinClass/MethodCallWithAssignmentWithinClass.java", - "methodCallWithAssignmentWithinClass.MethodCallWithAssignmentWithinClass", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCallWithAssignmentWithinClass.MethodCallWithAssignmentWithinClass::callme")); - } - - /** - * Tests "methodCallWithinClass". - */ - @Test - public void testMethodCallWithinClass() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/methodCallWithinClass/MethodCallWithinClass.java", - "methodCallWithinClass.MethodCallWithinClass", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCallWithinClass.MethodCallWithinClass::callme")); - } - - /** - * Tests "staticMethodCall". - */ - @Test - public void testStaticMethodCall() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/staticMethodCall/StaticMethodCall.java", - "staticMethodCall.StaticMethodCall", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "staticMethodCall.StaticClass::callMe")); - } - - /** - * Tests "staticMethodCallStaticViaTypereference". - */ - @Test - public void testStaticMethodCallStaticViaTypereference() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/staticMethodCallStaticViaTypereference/StaticMethodCallStaticViaTypereference.java", - "staticMethodCallStaticViaTypereference.StaticMethodCallStaticViaTypereference", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "staticMethodCallStaticViaTypereference.StaticClass::callMe")); - } - - /** - * Tests "staticMethodCallStaticWithAssignmentViaTypereference". - */ - @Test - public void testStaticMethodCallStaticWithAssignmentViaTypereference() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/staticMethodCallStaticWithAssignmentViaTypereference/StaticMethodCallStaticWithAssignmentViaTypereference.java", - "staticMethodCallStaticWithAssignmentViaTypereference.StaticMethodCallStaticWithAssignmentViaTypereference", - "caller", - false, - new MethodCallProofReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.CALL_METHOD, "staticMethodCallStaticWithAssignmentViaTypereference.StaticClass::callMe")); - } -} \ No newline at end of file + /** + * Tests "constructorTest". + */ + @Test + public void testConstructorTest() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/constructorTest/ConstructorTest.java", "ConstructorTest", + "ConstructorTest", false, new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "ConstructorTest::"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "ConstructorTest::"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "ConstructorTest::"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "java.lang.Object::"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "java.lang.Object::"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, "A::magic"), + new ExpectedProofReferences(IProofReference.CALL_METHOD, "B::staticMagic")); + } + + /** + * Tests "methodCall". + */ + @Test + public void testMethodCall() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/methodCall/MethodCall.java", + "methodCall.MethodCall", "caller", false, new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, "methodCall.Class::a")); + } + + /** + * Tests "methodCallSuper". + */ + @Test + public void testMethodCallSuper() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/methodCallSuper/MethodCallSuper.java", + "methodCallSuper.MethodCallSuper", "caller", false, + new MethodCallProofReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.CALL_METHOD, "methodCallSuper.Super::a")); + } + + /** + * Tests "methodCallWithAssignment". + */ + @Test + public void testMethodCallWithAssignment() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/methodCallWithAssignment/MethodCall.java", + "methodCallWithAssignment.MethodCall", "caller", false, + new MethodCallProofReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.CALL_METHOD, "methodCallWithAssignment.Class::a")); + } + + /** + * Tests "methodCallWithAssignmentSuper". + */ + @Test + public void testMethodCallWithAssignmentSuper() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/methodCallWithAssignmentSuper/MethodCallWithAssignmentSuper.java", + "methodCallWithAssignmentSuper.MethodCallWithAssignmentSuper", "caller", false, + new MethodCallProofReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.CALL_METHOD, "methodCallWithAssignmentSuper.Super::a")); + } + + /** + * Tests "methodCallWithAssignmentWithinClass". + */ + @Test + public void testMethodCallWithAssignmentWithinClass() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/methodCallWithAssignmentWithinClass/MethodCallWithAssignmentWithinClass.java", + "methodCallWithAssignmentWithinClass.MethodCallWithAssignmentWithinClass", "caller", + false, new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "methodCallWithAssignmentWithinClass.MethodCallWithAssignmentWithinClass::callme")); + } + + /** + * Tests "methodCallWithinClass". + */ + @Test + public void testMethodCallWithinClass() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/methodCallWithinClass/MethodCallWithinClass.java", + "methodCallWithinClass.MethodCallWithinClass", "caller", false, + new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "methodCallWithinClass.MethodCallWithinClass::callme")); + } + + /** + * Tests "staticMethodCall". + */ + @Test + public void testStaticMethodCall() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/staticMethodCall/StaticMethodCall.java", + "staticMethodCall.StaticMethodCall", "caller", false, + new MethodCallProofReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.CALL_METHOD, "staticMethodCall.StaticClass::callMe")); + } + + /** + * Tests "staticMethodCallStaticViaTypereference". + */ + @Test + public void testStaticMethodCallStaticViaTypereference() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/staticMethodCallStaticViaTypereference/StaticMethodCallStaticViaTypereference.java", + "staticMethodCallStaticViaTypereference.StaticMethodCallStaticViaTypereference", + "caller", false, new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "staticMethodCallStaticViaTypereference.StaticClass::callMe")); + } + + /** + * Tests "staticMethodCallStaticWithAssignmentViaTypereference". + */ + @Test + public void testStaticMethodCallStaticWithAssignmentViaTypereference() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/staticMethodCallStaticWithAssignmentViaTypereference/StaticMethodCallStaticWithAssignmentViaTypereference.java", + "staticMethodCallStaticWithAssignmentViaTypereference.StaticMethodCallStaticWithAssignmentViaTypereference", + "caller", false, new MethodCallProofReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.CALL_METHOD, + "staticMethodCallStaticWithAssignmentViaTypereference.StaticClass::callMe")); + } +} diff --git a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestProgramVariableReferencesAnalyst.java b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestProgramVariableReferencesAnalyst.java index a608233a304..fd1d9af93a3 100644 --- a/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestProgramVariableReferencesAnalyst.java +++ b/key/key.core.proof_references/src/test/java/de/uka/ilkd/key/proof_references/testcase/analyst/TestProgramVariableReferencesAnalyst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof_references.testcase.analyst; import de.uka.ilkd.key.proof_references.analyst.ProgramVariableReferencesAnalyst; @@ -7,940 +10,785 @@ /** * Tests for {@link ProgramVariableReferencesAnalyst}. + * * @author Martin Hentschel */ public class TestProgramVariableReferencesAnalyst extends AbstractProofReferenceTestCase { - /** - * Tests "ConditionalsAndOther#forEquals". - */ - @Test - public void testConditionalsAndOther_forEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "forEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#forBoolean". - */ - @Test - public void testConditionalsAndOther_forBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "forBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#doWhileEquals". - */ - @Test - public void testConditionalsAndOther_doWhileEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "doWhileEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#doWhileBoolean". - */ - @Test - public void testConditionalsAndOther_doWhileBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "doWhileBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#whileEquals". - */ - @Test - public void testConditionalsAndOther_whileEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "whileEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#whileBoolean". - */ - @Test - public void testConditionalsAndOther_whileBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "whileBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#throwsNestedException". - */ - @Test - public void testConditionalsAndOther_throwsNestedException() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "throwsNestedException", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::ew"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther.ExceptionWrapper::wrapped")); - } - - /** - * Tests "ConditionalsAndOther#throwsException". - */ - @Test - public void testConditionalsAndOther_throwsException() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "throwsException", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::e")); - } - - /** - * Tests "ConditionalsAndOther#methodCallCondtional". - */ - @Test - public void testConditionalsAndOther_methodCallConditional() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "methodCallCondtional", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#methodCallAssignment". - */ - @Test - public void testConditionalsAndOther_methodCallAssignment() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "methodCallAssignment", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#methodCall". - */ - @Test - public void testConditionalsAndOther_methodCall() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "methodCall", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#returnComplex". - */ - @Test - public void testConditionalsAndOther_returnComplex() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "returnComplex", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#returnEquals". - */ - @Test - public void testConditionalsAndOther_returnEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "returnEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#returnBoolean". - */ - @Test - public void testConditionalsAndOther_returnBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "returnBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#questionIncrementsAndDecrements". - */ - @Test - public void testConditionalsAndOther_questionIncrementsAndDecrements() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionIncrementsAndDecrements", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y")); - } - - /** - * Tests "ConditionalsAndOther#ifIncrementsAndDecrements". - */ - @Test - public void testConditionalsAndOther_ifIncrementsAndDecrements() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifIncrementsAndDecrements", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y")); - } - - /** - * Tests "ConditionalsAndOther#questionGreater". - */ - @Test - public void testConditionalsAndOther_questionGreater() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionGreater", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionGreaterEquals". - */ - @Test - public void testConditionalsAndOther_questionGreaterEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionGreaterEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionNotEquals". - */ - @Test - public void testConditionalsAndOther_questionNotEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionNotEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionEquals". - */ - @Test - public void testConditionalsAndOther_questionEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionLessEquals". - */ - @Test - public void testConditionalsAndOther_questionLessEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionLessEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionLess". - */ - @Test - public void testConditionalsAndOther_questionLess() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionLess", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#questionBoolean". - */ - @Test - public void testConditionalsAndOther_questionBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "questionBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#ifGreater". - */ - @Test - public void testConditionalsAndOther_ifGreater() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifGreater", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifGreaterEquals". - */ - @Test - public void testConditionalsAndOther_ifGreaterEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifGreaterEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifNotEquals". - */ - @Test - public void testConditionalsAndOther_ifNotEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifNotEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifEquals". - */ - @Test - public void testConditionalsAndOther_ifEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifLessEquals". - */ - @Test - public void testConditionalsAndOther_ifLessEquals() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifLessEquals", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifLess". - */ - @Test - public void testConditionalsAndOther_ifLess() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifLess", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ConditionalsAndOther#ifBoolean". - */ - @Test - public void testConditionalsAndOther_ifBoolean() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "ifBoolean", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); - } - - /** - * Tests "ConditionalsAndOther#switchInt". - */ - @Test - public void testConditionalsAndOther_switchInt() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", - "ConditionalsAndOther", - "switchInt", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); - } - - /** - * Tests "ArrayLength". - */ - @Test - public void testArrayLength() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/ArrayLength/ArrayLength.java", - "ArrayLength", - "main", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::length"), - new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::array"), - new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::my"), - new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength.MyClass::length"), - new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength.MyClass::array")); - } - - /** - * Tests "Assignments#assignmentWithSelf". - */ - @Test - public void testAssignments_assignmentWithSelf() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "assignmentWithSelf", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::next")); - } - - /** - * Tests "Assignments#nestedArray". - */ - @Test - public void testAssignments_nestedArray() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "nestedArray", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::childArray")); - } - - /** - * Tests "Assignments#nestedValueAdd". - */ - @Test - public void testAssignments_nestedValueAdd() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "nestedValueAdd", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::thirdChildValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::anotherChildValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::childValue")); - } - - /** - * Tests "Assignments#nestedValue". - */ - @Test - public void testAssignments_nestedValue() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "nestedValue", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::anotherChildValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyChildClass::childValue")); - } - - /** - * Tests "Assignments#assign". - */ - @Test - public void testAssignments_assign() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "assign", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#mod". - */ - @Test - public void testAssignments_mod() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "mod", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#div". - */ - @Test - public void testAssignments_div() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "div", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#mul". - */ - @Test - public void testAssignments_mul() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "mul", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#sub". - */ - @Test - public void testAssignments_sub() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "sub", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#add". - */ - @Test - public void testAssignments_add() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "add", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#decrementArrayBegin". - */ - @Test - public void testAssignments_decrementArrayBegin() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "decrementArrayBegin", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue")); - } - - /** - * Tests "Assignments#decrementArrayEnd". - */ - @Test - public void testAssignments_decrementArrayEnd() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "decrementArrayEnd", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array"), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue")); - } - - /** - * Tests "Assignments#incrementArrayBegin". - */ - @Test - public void testAssignments_incrementArrayBegin() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "incrementArrayBegin", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array")); - } - - /** - * Tests "Assignments#incrementArrayEnd". - */ - @Test - public void testAssignments_incrementArrayEnd() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "incrementArrayEnd", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array")); - } - - /** - * Tests "Assignments#decrementBegin". - */ - @Test - public void testAssignments_decrementBegin() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "decrementBegin", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#decrementEnd". - */ - @Test - public void testAssignments_decrementEnd() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "decrementEnd", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#incrementBegin". - */ - @Test - public void testAssignments_incrementBegin() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "incrementBegin", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "Assignments#incrementEnd". - */ - @Test - public void testAssignments_incrementEnd() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/Assignments/Assignments.java", - "Assignments", - "incrementEnd", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); - } - - /** - * Tests "assignment". - */ - @Test - public void testAssignment() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment/Assignment.java", - "assignment.Assignment", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment.Assignment::b"), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment.Enum::b")); - } - - /** - * Tests "assignment_array2". - */ - @Test - public void testAssignment_array2() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_array2/Assignment_array2.java", - "assignment_array2.Assignment_array2", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_array2.Assignment_array2::index"), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_array2.Assignment_array2::as"), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_array2.Assignment_array2::val")); - } - - /** - * Tests "assignment_read_attribute". - */ - @Test - public void testAssignment_read_attribute() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_read_attribute/Assignment_read_attribute.java", - "assignment_read_attribute.Assignment_read_attribute", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_read_attribute.Class::b"), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_read_attribute.Class::a")); - } - - /** - * Tests "assignment_read_length". - */ - @Test - public void testAssignment_read_length() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_read_length/Assignment_read_length.java", - "assignment_read_length.Assignment_read_length", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_read_length.Assignment_read_length::b")); - } - - /** - * Tests "assignment_to_primitive_array_component". - */ - @Test - public void testAssignment_to_primitive_array_component() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_to_primitive_array_component/Assignment_to_primitive_array_component.java", - "assignment_to_primitive_array_component.Assignment_to_primitive_array_component", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_to_primitive_array_component.Assignment_to_primitive_array_component::index"), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_to_primitive_array_component.Assignment_to_primitive_array_component::bs")); - } - - /** - * Tests "assignment_to_reference_array_component". - */ - @Test - public void testAssignment_to_reference_array_component() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_to_reference_array_component/Assignment_to_reference_array_component.java", - "assignment_to_reference_array_component.Assignment_to_reference_array_component", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_to_reference_array_component.Assignment_to_reference_array_component::bs")); - } - - /** - * Tests "assignment_write_attribute". - */ - @Test - public void testAssignment_write_attribute() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_write_attribute/Assignment_write_attribute.java", - "assignment_write_attribute.Assignment_write_attribute", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_write_attribute.Class::a")); - } - - /** - * Tests "assignment_write_static_attribute". - */ - @Test - public void testAssignment_write_static_attribute() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/assignment_write_static_attribute/Assignment_write_static_attribute.java", - "assignment_write_static_attribute.Assignment_write_static_attribute", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "assignment_write_static_attribute.Assignment_write_static_attribute::b")); - } - - /** - * Tests "activeUseStaticFieldReadAccess2". - */ - @Test - public void testActiveUseStaticFieldReadAccess2() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/activeUseStaticFieldReadAccess2/ActiveUseStaticFieldReadAccess2.java", - "activeUseStaticFieldReadAccess2.ActiveUseStaticFieldReadAccess2", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "activeUseStaticFieldReadAccess2.Class::i")); - } - - /** - * Tests "activeUseStaticFieldWriteAccess2". - */ - @Test - public void testActiveUseStaticFieldWriteAccess2() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/activeUseStaticFieldWriteAccess2/ActiveUseStaticFieldWriteAccess2.java", - "activeUseStaticFieldWriteAccess2.ActiveUseStaticFieldWriteAccess2", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "activeUseStaticFieldWriteAccess2.Class::a")); - } - - /** - * Tests "eval_order_access4". - */ - @Test - public void testEval_order_access4() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/eval_order_access4/Eval_order_access4.java", - "eval_order_access4.Eval_order_access4", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "eval_order_access4.Class::a")); - } - - /** - * Tests "eval_order_array_access5". - */ - @Test - public void testEval_order_array_access5() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/eval_order_array_access5/Eval_order_array_access5.java", - "eval_order_array_access5.Eval_order_array_access5", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "eval_order_array_access5.Class::a")); - } - - /** - * Tests "variableDeclarationAssign". - */ - @Test - public void testVariableDeclarationAssign() throws Exception { - doReferenceMethodTest(TESTCASE_DIRECTORY, - "/proofReferences/variableDeclarationAssign/VariableDeclarationAssign.java", - "variableDeclarationAssign.VariableDeclarationAssign", - "caller", - false, - new ProgramVariableReferencesAnalyst(), - new ExpectedProofReferences(IProofReference.ACCESS, "variableDeclarationAssign.VariableDeclarationAssign::a")); - } -} \ No newline at end of file + /** + * Tests "ConditionalsAndOther#forEquals". + */ + @Test + public void testConditionalsAndOther_forEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "forEquals", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#forBoolean". + */ + @Test + public void testConditionalsAndOther_forBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "forBoolean", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#doWhileEquals". + */ + @Test + public void testConditionalsAndOther_doWhileEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "doWhileEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#doWhileBoolean". + */ + @Test + public void testConditionalsAndOther_doWhileBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "doWhileBoolean", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#whileEquals". + */ + @Test + public void testConditionalsAndOther_whileEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "whileEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#whileBoolean". + */ + @Test + public void testConditionalsAndOther_whileBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "whileBoolean", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#throwsNestedException". + */ + @Test + public void testConditionalsAndOther_throwsNestedException() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "throwsNestedException", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::ew"), + new ExpectedProofReferences(IProofReference.ACCESS, + "ConditionalsAndOther.ExceptionWrapper::wrapped")); + } + + /** + * Tests "ConditionalsAndOther#throwsException". + */ + @Test + public void testConditionalsAndOther_throwsException() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "throwsException", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::e")); + } + + /** + * Tests "ConditionalsAndOther#methodCallCondtional". + */ + @Test + public void testConditionalsAndOther_methodCallConditional() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "methodCallCondtional", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#methodCallAssignment". + */ + @Test + public void testConditionalsAndOther_methodCallAssignment() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "methodCallAssignment", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#methodCall". + */ + @Test + public void testConditionalsAndOther_methodCall() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "methodCall", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#returnComplex". + */ + @Test + public void testConditionalsAndOther_returnComplex() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "returnComplex", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#returnEquals". + */ + @Test + public void testConditionalsAndOther_returnEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "returnEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#returnBoolean". + */ + @Test + public void testConditionalsAndOther_returnBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "returnBoolean", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#questionIncrementsAndDecrements". + */ + @Test + public void testConditionalsAndOther_questionIncrementsAndDecrements() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionIncrementsAndDecrements", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y")); + } + + /** + * Tests "ConditionalsAndOther#ifIncrementsAndDecrements". + */ + @Test + public void testConditionalsAndOther_ifIncrementsAndDecrements() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifIncrementsAndDecrements", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y")); + } + + /** + * Tests "ConditionalsAndOther#questionGreater". + */ + @Test + public void testConditionalsAndOther_questionGreater() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionGreater", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionGreaterEquals". + */ + @Test + public void testConditionalsAndOther_questionGreaterEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionGreaterEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionNotEquals". + */ + @Test + public void testConditionalsAndOther_questionNotEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionNotEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionEquals". + */ + @Test + public void testConditionalsAndOther_questionEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionLessEquals". + */ + @Test + public void testConditionalsAndOther_questionLessEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionLessEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionLess". + */ + @Test + public void testConditionalsAndOther_questionLess() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionLess", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#questionBoolean". + */ + @Test + public void testConditionalsAndOther_questionBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "questionBoolean", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#ifGreater". + */ + @Test + public void testConditionalsAndOther_ifGreater() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifGreater", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifGreaterEquals". + */ + @Test + public void testConditionalsAndOther_ifGreaterEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifGreaterEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifNotEquals". + */ + @Test + public void testConditionalsAndOther_ifNotEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifNotEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifEquals". + */ + @Test + public void testConditionalsAndOther_ifEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifEquals", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifLessEquals". + */ + @Test + public void testConditionalsAndOther_ifLessEquals() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifLessEquals", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifLess". + */ + @Test + public void testConditionalsAndOther_ifLess() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifLess", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::y"), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ConditionalsAndOther#ifBoolean". + */ + @Test + public void testConditionalsAndOther_ifBoolean() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "ifBoolean", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::b")); + } + + /** + * Tests "ConditionalsAndOther#switchInt". + */ + @Test + public void testConditionalsAndOther_switchInt() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/ConditionalsAndOther/ConditionalsAndOther.java", + "ConditionalsAndOther", "switchInt", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ConditionalsAndOther::x")); + } + + /** + * Tests "ArrayLength". + */ + @Test + public void testArrayLength() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/ArrayLength/ArrayLength.java", + "ArrayLength", "main", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::length"), + new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::array"), + new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength::my"), + new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength.MyClass::length"), + new ExpectedProofReferences(IProofReference.ACCESS, "ArrayLength.MyClass::array")); + } + + /** + * Tests "Assignments#assignmentWithSelf". + */ + @Test + public void testAssignments_assignmentWithSelf() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "assignmentWithSelf", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::next")); + } + + /** + * Tests "Assignments#nestedArray". + */ + @Test + public void testAssignments_nestedArray() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "nestedArray", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::childArray")); + } + + /** + * Tests "Assignments#nestedValueAdd". + */ + @Test + public void testAssignments_nestedValueAdd() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "nestedValueAdd", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::thirdChildValue"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::anotherChildValue"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::childValue")); + } + + /** + * Tests "Assignments#nestedValue". + */ + @Test + public void testAssignments_nestedValue() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "nestedValue", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::myClass"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments.MyClass::child"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::anotherChildValue"), + new ExpectedProofReferences(IProofReference.ACCESS, + "Assignments.MyChildClass::childValue")); + } + + /** + * Tests "Assignments#assign". + */ + @Test + public void testAssignments_assign() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "assign", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#mod". + */ + @Test + public void testAssignments_mod() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "mod", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#div". + */ + @Test + public void testAssignments_div() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "div", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#mul". + */ + @Test + public void testAssignments_mul() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "mul", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#sub". + */ + @Test + public void testAssignments_sub() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "sub", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#add". + */ + @Test + public void testAssignments_add() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "add", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#decrementArrayBegin". + */ + @Test + public void testAssignments_decrementArrayBegin() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "decrementArrayBegin", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue")); + } + + /** + * Tests "Assignments#decrementArrayEnd". + */ + @Test + public void testAssignments_decrementArrayEnd() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "decrementArrayEnd", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array"), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::anotherValue")); + } + + /** + * Tests "Assignments#incrementArrayBegin". + */ + @Test + public void testAssignments_incrementArrayBegin() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "incrementArrayBegin", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array")); + } + + /** + * Tests "Assignments#incrementArrayEnd". + */ + @Test + public void testAssignments_incrementArrayEnd() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "incrementArrayEnd", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::array")); + } + + /** + * Tests "Assignments#decrementBegin". + */ + @Test + public void testAssignments_decrementBegin() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "decrementBegin", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#decrementEnd". + */ + @Test + public void testAssignments_decrementEnd() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "decrementEnd", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#incrementBegin". + */ + @Test + public void testAssignments_incrementBegin() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "incrementBegin", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "Assignments#incrementEnd". + */ + @Test + public void testAssignments_incrementEnd() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/Assignments/Assignments.java", + "Assignments", "incrementEnd", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "Assignments::value")); + } + + /** + * Tests "assignment". + */ + @Test + public void testAssignment() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, "/proofReferences/assignment/Assignment.java", + "assignment.Assignment", "caller", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "assignment.Assignment::b"), + new ExpectedProofReferences(IProofReference.ACCESS, "assignment.Enum::b")); + } + + /** + * Tests "assignment_array2". + */ + @Test + public void testAssignment_array2() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_array2/Assignment_array2.java", + "assignment_array2.Assignment_array2", "caller", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_array2.Assignment_array2::index"), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_array2.Assignment_array2::as"), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_array2.Assignment_array2::val")); + } + + /** + * Tests "assignment_read_attribute". + */ + @Test + public void testAssignment_read_attribute() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_read_attribute/Assignment_read_attribute.java", + "assignment_read_attribute.Assignment_read_attribute", "caller", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_read_attribute.Class::b"), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_read_attribute.Class::a")); + } + + /** + * Tests "assignment_read_length". + */ + @Test + public void testAssignment_read_length() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_read_length/Assignment_read_length.java", + "assignment_read_length.Assignment_read_length", "caller", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_read_length.Assignment_read_length::b")); + } + + /** + * Tests "assignment_to_primitive_array_component". + */ + @Test + public void testAssignment_to_primitive_array_component() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_to_primitive_array_component/Assignment_to_primitive_array_component.java", + "assignment_to_primitive_array_component.Assignment_to_primitive_array_component", + "caller", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_to_primitive_array_component.Assignment_to_primitive_array_component::index"), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_to_primitive_array_component.Assignment_to_primitive_array_component::bs")); + } + + /** + * Tests "assignment_to_reference_array_component". + */ + @Test + public void testAssignment_to_reference_array_component() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_to_reference_array_component/Assignment_to_reference_array_component.java", + "assignment_to_reference_array_component.Assignment_to_reference_array_component", + "caller", false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_to_reference_array_component.Assignment_to_reference_array_component::bs")); + } + + /** + * Tests "assignment_write_attribute". + */ + @Test + public void testAssignment_write_attribute() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_write_attribute/Assignment_write_attribute.java", + "assignment_write_attribute.Assignment_write_attribute", "caller", false, + new ProgramVariableReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.ACCESS, "assignment_write_attribute.Class::a")); + } + + /** + * Tests "assignment_write_static_attribute". + */ + @Test + public void testAssignment_write_static_attribute() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/assignment_write_static_attribute/Assignment_write_static_attribute.java", + "assignment_write_static_attribute.Assignment_write_static_attribute", "caller", + false, new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "assignment_write_static_attribute.Assignment_write_static_attribute::b")); + } + + /** + * Tests "activeUseStaticFieldReadAccess2". + */ + @Test + public void testActiveUseStaticFieldReadAccess2() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/activeUseStaticFieldReadAccess2/ActiveUseStaticFieldReadAccess2.java", + "activeUseStaticFieldReadAccess2.ActiveUseStaticFieldReadAccess2", "caller", false, + new ProgramVariableReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.ACCESS, "activeUseStaticFieldReadAccess2.Class::i")); + } + + /** + * Tests "activeUseStaticFieldWriteAccess2". + */ + @Test + public void testActiveUseStaticFieldWriteAccess2() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/activeUseStaticFieldWriteAccess2/ActiveUseStaticFieldWriteAccess2.java", + "activeUseStaticFieldWriteAccess2.ActiveUseStaticFieldWriteAccess2", "caller", + false, new ProgramVariableReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.ACCESS, "activeUseStaticFieldWriteAccess2.Class::a")); + } + + /** + * Tests "eval_order_access4". + */ + @Test + public void testEval_order_access4() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/eval_order_access4/Eval_order_access4.java", + "eval_order_access4.Eval_order_access4", "caller", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, "eval_order_access4.Class::a")); + } + + /** + * Tests "eval_order_array_access5". + */ + @Test + public void testEval_order_array_access5() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/eval_order_array_access5/Eval_order_array_access5.java", + "eval_order_array_access5.Eval_order_array_access5", "caller", false, + new ProgramVariableReferencesAnalyst(), new ExpectedProofReferences( + IProofReference.ACCESS, "eval_order_array_access5.Class::a")); + } + + /** + * Tests "variableDeclarationAssign". + */ + @Test + public void testVariableDeclarationAssign() throws Exception { + doReferenceMethodTest(TESTCASE_DIRECTORY, + "/proofReferences/variableDeclarationAssign/VariableDeclarationAssign.java", + "variableDeclarationAssign.VariableDeclarationAssign", "caller", false, + new ProgramVariableReferencesAnalyst(), + new ExpectedProofReferences(IProofReference.ACCESS, + "variableDeclarationAssign.VariableDeclarationAssign::a")); + } +} diff --git a/key/key.core.symbolic_execution.example/src/main/java/org/key_project/example/Main.java b/key/key.core.symbolic_execution.example/src/main/java/org/key_project/example/Main.java index 66fedfc4626..f2c81bf8240 100644 --- a/key/key.core.symbolic_execution.example/src/main/java/org/key_project/example/Main.java +++ b/key/key.core.symbolic_execution.example/src/main/java/org/key_project/example/Main.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package org.key_project.example; import java.io.File; @@ -33,119 +36,153 @@ import org.slf4j.LoggerFactory; /** - * Example application which symbolically executes - * {@code example/Number#equals(Number)} + * Example application which symbolically executes {@code example/Number#equals(Number)} + * * @author Martin Hentschel */ public class Main { - private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); - /** - * The program entry point. - * @param args The start parameters. - */ - public static void main(String[] args) { - File location = new File("example"); // Path to the source code folder/file or to a *.proof file - List classPaths = null; // Optionally: Additional specifications for API classes - File bootClassPath = null; // Optionally: Different default specifications for Java API - List includes = null; // Optionally: Additional includes to consider - try { - // Ensure that Taclets are parsed - if (!ProofSettings.isChoiceSettingInitialised()) { - KeYEnvironment env = KeYEnvironment.load(location, classPaths, bootClassPath, includes); - env.dispose(); - } - // Set Taclet options - ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); - HashMap oldSettings = choiceSettings.getDefaultChoices(); - HashMap newSettings = new HashMap<>(oldSettings); - newSettings.putAll(MiscTools.getDefaultTacletOptions()); - newSettings.put("methodExpansion", "methodExpansion:noRestriction"); - choiceSettings.setDefaultChoices(newSettings); - // Load source code - KeYEnvironment env = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), location, classPaths, bootClassPath, includes, true); // env.getLoadedProof() returns performed proof if a *.proof file is loaded - try { - // Find method to symbolically execute - KeYJavaType classType = env.getJavaInfo().getKeYJavaType("Number"); - IProgramMethod pm = env.getJavaInfo().getProgramMethod(classType, - "equals", - ImmutableSLList.nil().append(classType), - classType); - // Instantiate proof for symbolic execution of the program method (Java semantics) - AbstractOperationPO po = new ProgramMethodPO(env.getInitConfig(), - "Symbolic Execution of: " + pm, - pm, - null, // An optional precondition - true, // Needs to be true for symbolic execution! - true); // Needs to be true for symbolic execution! - // po = new ProgramMethodSubsetPO(...); // PO for symbolic execution of some statements within a method (Java semantics) - // po = new FunctionalOperationContractPO(...) // PO for verification (JML semantics) - Proof proof = env.createProof(po); - // Create symbolic execution tree builder - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, - false, // Merge branch conditions - false, // Use Unicode? - true, // Use Pretty Printing? - true, // Variables are collected from updates instead of the visible type structure - true); // Simplify conditions - builder.analyse(); - // Optionally, create an SymbolicExecutionEnvironment which provides access to all relevant objects for symbolic execution - SymbolicExecutionEnvironment symbolicEnv = new SymbolicExecutionEnvironment<>(env, builder); - printSymbolicExecutionTree("Initial State", builder); - // Configure strategy for full exploration - SymbolicExecutionUtil.initializeStrategy(builder); - SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, - 100, - false, // true to apply method contracts instead of inlining, - false, // true to apply loop invariants instead of unrolling, - false, // true to apply block contracts instead of expanding. - false, // true to hide branch conditions caused by symbolic execution within modalities not of interest, - false); // true to perform alias checks during symbolic execution - // Optionally, add a more advanced stop conditions like breakpoints - CompoundStopCondition stopCondition = new CompoundStopCondition(); - stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition(100)); // Stop after 100 nodes have been explored on each branch. -// stopCondition.addChildren(new StepOverSymbolicExecutionTreeNodesStopCondition()); // Perform only a step over -// stopCondition.addChildren(new StepReturnSymbolicExecutionTreeNodesStopCondition()); // Perform only a step return - IBreakpoint breakpoint = new ExceptionBreakpoint(proof, "java.lang.NullPointerException", true, true, true, true, 1); - stopCondition.addChildren(new SymbolicExecutionBreakpointStopCondition(breakpoint)); // Stop at specified breakpoints - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Perform strategy which will stop at breakpoint - symbolicEnv.getProofControl().startAndWaitForAutoMode(proof); - builder.analyse(); - printSymbolicExecutionTree("Stopped at Breakpoint", builder); - // Perform strategy again to complete symbolic execution tree - symbolicEnv.getProofControl().startAndWaitForAutoMode(proof); - builder.analyse(); - printSymbolicExecutionTree("Stopped at Breakpoint", builder); - } - finally { - env.dispose(); // Ensure always that all instances of KeYEnvironment are disposed - } - } - catch (Exception e) { - LOGGER.debug("Exception at '{}':", location, e); - } - } - - /** - * Prints the symbolic execution tree as flat list into the console. - * @param title The title. - * @param builder The {@link SymbolicExecutionTreeBuilder} providing the root of the symbolic execution tree. - */ - protected static void printSymbolicExecutionTree(String title, SymbolicExecutionTreeBuilder builder) { - System.out.println(title); - System.out.println(StringUtil.repeat("=", title.length())); - ExecutionNodePreorderIterator iterator = new ExecutionNodePreorderIterator(builder.getStartNode()); - while (iterator.hasNext()) { - IExecutionNode next = iterator.next(); - System.out.println(next); -// next.getVariables(); // Access the symbolic state. -// next.getCallStack(); // Access the call stack. -// next.getPathCondition(); // Access the path condition. -// next.getFormatedPathCondition(); // Access the formated path condition. -// next... // Additional methods provide access to additional information. - // Check also the specific sub types of IExecutionNode like IExecutionTermination. - } - System.out.println(); - } -} \ No newline at end of file + /** + * The program entry point. + * + * @param args The start parameters. + */ + public static void main(String[] args) { + File location = new File("example"); // Path to the source code folder/file or to a *.proof + // file + List classPaths = null; // Optionally: Additional specifications for API classes + File bootClassPath = null; // Optionally: Different default specifications for Java API + List includes = null; // Optionally: Additional includes to consider + try { + // Ensure that Taclets are parsed + if (!ProofSettings.isChoiceSettingInitialised()) { + KeYEnvironment env = + KeYEnvironment.load(location, classPaths, bootClassPath, includes); + env.dispose(); + } + // Set Taclet options + ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); + HashMap oldSettings = choiceSettings.getDefaultChoices(); + HashMap newSettings = new HashMap<>(oldSettings); + newSettings.putAll(MiscTools.getDefaultTacletOptions()); + newSettings.put("methodExpansion", "methodExpansion:noRestriction"); + choiceSettings.setDefaultChoices(newSettings); + // Load source code + KeYEnvironment env = + KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), location, + classPaths, bootClassPath, includes, true); // env.getLoadedProof() + // returns performed proof + // if a *.proof file is + // loaded + try { + // Find method to symbolically execute + KeYJavaType classType = env.getJavaInfo().getKeYJavaType("Number"); + IProgramMethod pm = env.getJavaInfo().getProgramMethod(classType, "equals", + ImmutableSLList.nil().append(classType), classType); + // Instantiate proof for symbolic execution of the program method (Java semantics) + AbstractOperationPO po = new ProgramMethodPO(env.getInitConfig(), + "Symbolic Execution of: " + pm, pm, null, // An optional precondition + true, // Needs to be true for symbolic execution! + true); // Needs to be true for symbolic execution! + // po = new ProgramMethodSubsetPO(...); // PO for symbolic execution of some + // statements within a method (Java semantics) + // po = new FunctionalOperationContractPO(...) // PO for verification (JML + // semantics) + Proof proof = env.createProof(po); + // Create symbolic execution tree builder + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, false, // Merge branch conditions + false, // Use Unicode? + true, // Use Pretty Printing? + true, // Variables are collected from updates instead of the visible + // type structure + true); // Simplify conditions + builder.analyse(); + // Optionally, create an SymbolicExecutionEnvironment which provides access to all + // relevant objects for symbolic execution + SymbolicExecutionEnvironment symbolicEnv = + new SymbolicExecutionEnvironment<>(env, builder); + printSymbolicExecutionTree("Initial State", builder); + // Configure strategy for full exploration + SymbolicExecutionUtil.initializeStrategy(builder); + SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, 100, false, // true + // to + // apply + // method + // contracts + // instead + // of + // inlining, + false, // true to apply loop invariants instead of unrolling, + false, // true to apply block contracts instead of expanding. + false, // true to hide branch conditions caused by symbolic execution within + // modalities not of interest, + false); // true to perform alias checks during symbolic execution + // Optionally, add a more advanced stop conditions like breakpoints + CompoundStopCondition stopCondition = new CompoundStopCondition(); + stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition(100)); // Stop + // after + // 100 + // nodes + // have + // been + // explored + // on + // each + // branch. + // stopCondition.addChildren(new StepOverSymbolicExecutionTreeNodesStopCondition()); + // // Perform only a step over + // stopCondition.addChildren(new + // StepReturnSymbolicExecutionTreeNodesStopCondition()); // Perform only a step + // return + IBreakpoint breakpoint = new ExceptionBreakpoint(proof, + "java.lang.NullPointerException", true, true, true, true, 1); + stopCondition.addChildren(new SymbolicExecutionBreakpointStopCondition(breakpoint)); // Stop + // at + // specified + // breakpoints + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Perform strategy which will stop at breakpoint + symbolicEnv.getProofControl().startAndWaitForAutoMode(proof); + builder.analyse(); + printSymbolicExecutionTree("Stopped at Breakpoint", builder); + // Perform strategy again to complete symbolic execution tree + symbolicEnv.getProofControl().startAndWaitForAutoMode(proof); + builder.analyse(); + printSymbolicExecutionTree("Stopped at Breakpoint", builder); + } finally { + env.dispose(); // Ensure always that all instances of KeYEnvironment are disposed + } + } catch (Exception e) { + LOGGER.debug("Exception at '{}':", location, e); + } + } + + /** + * Prints the symbolic execution tree as flat list into the console. + * + * @param title The title. + * @param builder The {@link SymbolicExecutionTreeBuilder} providing the root of the symbolic + * execution tree. + */ + protected static void printSymbolicExecutionTree(String title, + SymbolicExecutionTreeBuilder builder) { + System.out.println(title); + System.out.println(StringUtil.repeat("=", title.length())); + ExecutionNodePreorderIterator iterator = + new ExecutionNodePreorderIterator(builder.getStartNode()); + while (iterator.hasNext()) { + IExecutionNode next = iterator.next(); + System.out.println(next); + // next.getVariables(); // Access the symbolic state. + // next.getCallStack(); // Access the call stack. + // next.getPathCondition(); // Access the path condition. + // next.getFormatedPathCondition(); // Access the formated path condition. + // next... // Additional methods provide access to additional information. + // Check also the specific sub types of IExecutionNode like IExecutionTermination. + } + System.out.println(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/proof/TermProgramVariableCollectorKeepUpdatesForBreakpointconditions.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/proof/TermProgramVariableCollectorKeepUpdatesForBreakpointconditions.java index 02f71c0f8ea..cf9f9529bb8 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/proof/TermProgramVariableCollectorKeepUpdatesForBreakpointconditions.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/proof/TermProgramVariableCollectorKeepUpdatesForBreakpointconditions.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.proof; import de.uka.ilkd.key.java.Services; @@ -9,37 +12,40 @@ import de.uka.ilkd.key.symbolic_execution.strategy.breakpoint.AbstractConditionalBreakpoint; import de.uka.ilkd.key.symbolic_execution.strategy.breakpoint.IBreakpoint; -public class TermProgramVariableCollectorKeepUpdatesForBreakpointconditions extends TermProgramVariableCollector { - private IBreakpointStopCondition breakpointStopCondition; - - public TermProgramVariableCollectorKeepUpdatesForBreakpointconditions(Services services, IBreakpointStopCondition breakpointStopCondition) { - super(services); - this.breakpointStopCondition = breakpointStopCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Term t) { - super.visit(t); - if (t.op() instanceof Modality) { - addVarsToKeep(); - } - } - - private void addVarsToKeep() { - for(IBreakpoint breakpoint : breakpointStopCondition.getBreakpoints()){ - if(breakpoint instanceof AbstractConditionalBreakpoint){ - AbstractConditionalBreakpoint conditionalBreakpoint = (AbstractConditionalBreakpoint) breakpoint; - if(conditionalBreakpoint.getToKeep() != null){ - for(SVSubstitute sub : conditionalBreakpoint.getToKeep()){ - if(sub instanceof LocationVariable){ - super.result().add((LocationVariable)sub); - } - } +public class TermProgramVariableCollectorKeepUpdatesForBreakpointconditions + extends TermProgramVariableCollector { + private IBreakpointStopCondition breakpointStopCondition; + + public TermProgramVariableCollectorKeepUpdatesForBreakpointconditions(Services services, + IBreakpointStopCondition breakpointStopCondition) { + super(services); + this.breakpointStopCondition = breakpointStopCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Term t) { + super.visit(t); + if (t.op() instanceof Modality) { + addVarsToKeep(); + } + } + + private void addVarsToKeep() { + for (IBreakpoint breakpoint : breakpointStopCondition.getBreakpoints()) { + if (breakpoint instanceof AbstractConditionalBreakpoint) { + AbstractConditionalBreakpoint conditionalBreakpoint = + (AbstractConditionalBreakpoint) breakpoint; + if (conditionalBreakpoint.getToKeep() != null) { + for (SVSubstitute sub : conditionalBreakpoint.getToKeep()) { + if (sub instanceof LocationVariable) { + super.result().add((LocationVariable) sub); + } + } + } } - } - } - } -} \ No newline at end of file + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/BlockContractValidityTermLabelUpdate.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/BlockContractValidityTermLabelUpdate.java index 36a9c842314..c5e682af9c3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/BlockContractValidityTermLabelUpdate.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/BlockContractValidityTermLabelUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Set; @@ -25,50 +28,43 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * Makes sure that {@link BlockContractValidityTermLabel} is introduced - * when a {@link BlockContractInternalRule} is applied. + * Makes sure that {@link BlockContractValidityTermLabel} is introduced when a + * {@link BlockContractInternalRule} is applied. + * * @author Martin Hentschel */ public class BlockContractValidityTermLabelUpdate implements TermLabelUpdate { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return ImmutableSLList.nil().append(BlockContractInternalRule.INSTANCE.name()); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return ImmutableSLList.nil().append(BlockContractInternalRule.INSTANCE.name()); + } - /** - * {@inheritDoc} - */ - @Override - public void updateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Set labels) { - if ((rule instanceof BlockContractInternalRule - || rule instanceof LoopContractInternalRule) - && ((BlockContractInternalRule.BlockContractHint)hint).getExceptionalVariable() - != null - && SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { - if (CollectionUtil.search(labels, new IFilter() { - @Override - public boolean select(TermLabel element) { - return element instanceof BlockContractValidityTermLabel; - } - }) == null) { - labels.add(new BlockContractValidityTermLabel(((BlockContractInternalRule.BlockContractHint)hint).getExceptionalVariable())); - } - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void updateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, Set labels) { + if ((rule instanceof BlockContractInternalRule || rule instanceof LoopContractInternalRule) + && ((BlockContractInternalRule.BlockContractHint) hint) + .getExceptionalVariable() != null + && SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { + if (CollectionUtil.search(labels, new IFilter() { + @Override + public boolean select(TermLabel element) { + return element instanceof BlockContractValidityTermLabel; + } + }) == null) { + labels.add(new BlockContractValidityTermLabel( + ((BlockContractInternalRule.BlockContractHint) hint) + .getExceptionalVariable())); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelMerger.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelMerger.java index e6d5beb1520..70e04e5da95 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelMerger.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelMerger.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.LinkedList; @@ -12,38 +15,35 @@ /** * The {@link TermLabelMerger} used to merge {@link FormulaTermLabel}s. + * * @author Martin Hentschel */ public class FormulaTermLabelMerger implements TermLabelMerger { - /** - * {@inheritDoc} - */ - @Override - public boolean mergeLabels(SequentFormula existingSF, - Term existingTerm, - TermLabel existingLabel, - SequentFormula rejectedSF, - Term rejectedTerm, - TermLabel rejectedLabel, - List mergedLabels) { - if (existingLabel != null) { - FormulaTermLabel fExisting = (FormulaTermLabel) existingLabel; - FormulaTermLabel fRejected = (FormulaTermLabel) rejectedLabel; - // Compute new label - List newBeforeIds = new LinkedList(); - CollectionUtil.addAll(newBeforeIds, fExisting.getBeforeIds()); - CollectionUtil.addAll(newBeforeIds, fRejected.getId()); - CollectionUtil.addAll(newBeforeIds, fRejected.getBeforeIds()); - FormulaTermLabel newLabel = new FormulaTermLabel(fExisting.getMajorId(), fExisting.getMinorId(), newBeforeIds); - // Remove existing label - mergedLabels.remove(existingLabel); - // Add new label - mergedLabels.add(newLabel); - return true; - } - else { - mergedLabels.add(rejectedLabel); - return true; - } - } + /** + * {@inheritDoc} + */ + @Override + public boolean mergeLabels(SequentFormula existingSF, Term existingTerm, + TermLabel existingLabel, SequentFormula rejectedSF, Term rejectedTerm, + TermLabel rejectedLabel, List mergedLabels) { + if (existingLabel != null) { + FormulaTermLabel fExisting = (FormulaTermLabel) existingLabel; + FormulaTermLabel fRejected = (FormulaTermLabel) rejectedLabel; + // Compute new label + List newBeforeIds = new LinkedList(); + CollectionUtil.addAll(newBeforeIds, fExisting.getBeforeIds()); + CollectionUtil.addAll(newBeforeIds, fRejected.getId()); + CollectionUtil.addAll(newBeforeIds, fRejected.getBeforeIds()); + FormulaTermLabel newLabel = new FormulaTermLabel(fExisting.getMajorId(), + fExisting.getMinorId(), newBeforeIds); + // Remove existing label + mergedLabels.remove(existingLabel); + // Add new label + mergedLabels.add(newLabel); + return true; + } else { + mergedLabels.add(rejectedLabel); + return true; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelRefactoring.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelRefactoring.java index 9642e57043d..e15f8e564b0 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelRefactoring.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelRefactoring.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Collections; @@ -28,405 +31,404 @@ import de.uka.ilkd.key.symbolic_execution.TruthValueTracingUtil; /** - * The {@link TermLabelRefactoring} used to label predicates with a - * {@link FormulaTermLabel} on applied loop invariants or operation contracts. + * The {@link TermLabelRefactoring} used to label predicates with a {@link FormulaTermLabel} on + * applied loop invariants or operation contracts. + * * @author Martin Hentschel */ public class FormulaTermLabelRefactoring implements TermLabelRefactoring { - /** - * Key prefix used in {@link TermLabelState} to store that the inner most - * label was already refactored on a given {@link Goal}. - */ - private static final String INNER_MOST_PARENT_REFACTORED_PREFIX = "innerMostParentRefactoredAtGoal_"; + /** + * Key prefix used in {@link TermLabelState} to store that the inner most label was already + * refactored on a given {@link Goal}. + */ + private static final String INNER_MOST_PARENT_REFACTORED_PREFIX = + "innerMostParentRefactoredAtGoal_"; - /** - * Key used in {@link TermLabelState} by the {@link StayOnOperatorTermLabelPolicy} - * to indicate that a refactoring below an update - * ({@link RefactoringScope#APPLICATION_BELOW_UPDATES}) - * is required performed by - * {@link #refactorBewlowUpdates(PosInOccurrence, Term, List)}. - *

- * This is for instance required for the following rules: - *

    - *
  • {@code concrete_and_1}
  • - *
  • {@code concrete_and_2}
  • - *
  • {@code concrete_and_3}
  • - *
  • {@code concrete_and_4}
  • - *
  • {@code concrete_eq_1}
  • - *
  • {@code concrete_eq_2}
  • - *
  • {@code concrete_eq_3}
  • - *
  • {@code concrete_eq_4}
  • - *
  • {@code concrete_impl_1}
  • - *
  • {@code concrete_impl_2}
  • - *
  • {@code concrete_impl_3}
  • - *
  • {@code concrete_impl_4}
  • - *
  • {@code concrete_not_1}
  • - *
  • {@code concrete_not_2}
  • - *
  • {@code concrete_or_1}
  • - *
  • {@code concrete_or_2}
  • - *
  • {@code concrete_or_3}
  • - *
  • {@code concrete_or_4}
  • - *
- */ - private static final String UPDATE_REFACTORING_REQUIRED = "updateRefactroingRequired"; + /** + * Key used in {@link TermLabelState} by the {@link StayOnOperatorTermLabelPolicy} to indicate + * that a refactoring below an update ({@link RefactoringScope#APPLICATION_BELOW_UPDATES}) is + * required performed by {@link #refactorBewlowUpdates(PosInOccurrence, Term, List)}. + *

+ * This is for instance required for the following rules: + *

    + *
  • {@code concrete_and_1}
  • + *
  • {@code concrete_and_2}
  • + *
  • {@code concrete_and_3}
  • + *
  • {@code concrete_and_4}
  • + *
  • {@code concrete_eq_1}
  • + *
  • {@code concrete_eq_2}
  • + *
  • {@code concrete_eq_3}
  • + *
  • {@code concrete_eq_4}
  • + *
  • {@code concrete_impl_1}
  • + *
  • {@code concrete_impl_2}
  • + *
  • {@code concrete_impl_3}
  • + *
  • {@code concrete_impl_4}
  • + *
  • {@code concrete_not_1}
  • + *
  • {@code concrete_not_2}
  • + *
  • {@code concrete_or_1}
  • + *
  • {@code concrete_or_2}
  • + *
  • {@code concrete_or_3}
  • + *
  • {@code concrete_or_4}
  • + *
+ */ + private static final String UPDATE_REFACTORING_REQUIRED = "updateRefactroingRequired"; - /** - * Key used in {@link TermLabelState} by the {@link FormulaTermLabelUpdate} - * to indicate that a refactoring of parents - * ({@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}) - * is required performed by - * {@link #refactorInCaseOfNewIdRequired(TermLabelState, Goal, Term, Services, List)}. - *

- * This is for instance required if a rule is applied on a sub term without - * a {@link FormulaTermLabel} of a parent which has a {@link FormulaTermLabel}. - * Example rules are: - *

    - *
  • {@code ifthenelse_split}
  • - *
  • {@code arrayLengthNotNegative}
  • - *
- */ - private static final String PARENT_REFACTORING_REQUIRED = "parentRefactoringRequired"; + /** + * Key used in {@link TermLabelState} by the {@link FormulaTermLabelUpdate} to indicate that a + * refactoring of parents + * ({@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}) is + * required performed by + * {@link #refactorInCaseOfNewIdRequired(TermLabelState, Goal, Term, Services, List)}. + *

+ * This is for instance required if a rule is applied on a sub term without a + * {@link FormulaTermLabel} of a parent which has a {@link FormulaTermLabel}. Example rules are: + *

    + *
  • {@code ifthenelse_split}
  • + *
  • {@code arrayLengthNotNegative}
  • + *
+ */ + private static final String PARENT_REFACTORING_REQUIRED = "parentRefactoringRequired"; - /** - * Key used in {@link TermLabelState} by the {@link FormulaTermLabelUpdate} - * to indicate that a refactoring of specified {@link SequentFormula}s - * ({@link RefactoringScope#SEQUENT}) - * is required performed by - * {@link #refactorSequentFormulas(TermLabelState, Services, Term, List)}. - *

- * This is for instance required if the assumes clause of a rule has - * a {@link FormulaTermLabel} but the application does not have it. - * Example rules are: - *

    - *
  • {@code inEqSimp_contradInEq1}
  • - *
- */ - private static final String SEQUENT_FORMULA_REFACTORING_REQUIRED = "sequentFormulaRefactoringRequired"; + /** + * Key used in {@link TermLabelState} by the {@link FormulaTermLabelUpdate} to indicate that a + * refactoring of specified {@link SequentFormula}s ({@link RefactoringScope#SEQUENT}) is + * required performed by {@link #refactorSequentFormulas(TermLabelState, Services, Term, List)}. + *

+ * This is for instance required if the assumes clause of a rule has a {@link FormulaTermLabel} + * but the application does not have it. Example rules are: + *

    + *
  • {@code inEqSimp_contradInEq1}
  • + *
+ */ + private static final String SEQUENT_FORMULA_REFACTORING_REQUIRED = + "sequentFormulaRefactoringRequired"; - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return null; // Support all rules - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return null; // Support all rules + } - /** - * {@inheritDoc} - */ - @Override - public RefactoringScope defineRefactoringScope(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - if (shouldRefactorSpecificationApplication(rule, goal, hint)) { - return RefactoringScope.APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE; - } - else if (isParentRefactroingRequired(state)) { - return RefactoringScope.APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS; - } - else if (isUpdateRefactroingRequired(state)) { - return RefactoringScope.APPLICATION_BELOW_UPDATES; - } - else if (containsSequentFormulasToRefactor(state)) { - return RefactoringScope.SEQUENT; - } - else if (SyntacticalReplaceVisitor.SUBSTITUTION_WITH_LABELS_HINT.equals(hint)) { - return RefactoringScope.APPLICATION_BELOW_UPDATES; - } - else { - return RefactoringScope.NONE; - } - } + /** + * {@inheritDoc} + */ + @Override + public RefactoringScope defineRefactoringScope(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + if (shouldRefactorSpecificationApplication(rule, goal, hint)) { + return RefactoringScope.APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE; + } else if (isParentRefactroingRequired(state)) { + return RefactoringScope.APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS; + } else if (isUpdateRefactroingRequired(state)) { + return RefactoringScope.APPLICATION_BELOW_UPDATES; + } else if (containsSequentFormulasToRefactor(state)) { + return RefactoringScope.SEQUENT; + } else if (SyntacticalReplaceVisitor.SUBSTITUTION_WITH_LABELS_HINT.equals(hint)) { + return RefactoringScope.APPLICATION_BELOW_UPDATES; + } else { + return RefactoringScope.NONE; + } + } - /** - * Checks if the given hint requires a refactoring. - * @param rule The applied {@link Rule}. - * @param goal The {@link Goal}. - * @param hint The hint to check. - * @return {@code true} perform refactoring, {@code false} do not perform refactoring. - */ - protected boolean shouldRefactorSpecificationApplication(Rule rule, Goal goal, Object hint) { - return TermLabelRefactoring.shouldRefactorOnBuiltInRule(rule, goal, hint); - } + /** + * Checks if the given hint requires a refactoring. + * + * @param rule The applied {@link Rule}. + * @param goal The {@link Goal}. + * @param hint The hint to check. + * @return {@code true} perform refactoring, {@code false} do not perform refactoring. + */ + protected boolean shouldRefactorSpecificationApplication(Rule rule, Goal goal, Object hint) { + return TermLabelRefactoring.shouldRefactorOnBuiltInRule(rule, goal, hint); + } - /** - * {@inheritDoc} - */ - @Override - public void refactorLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Term term, - List labels) { - if (shouldRefactorSpecificationApplication(rule, goal, hint)) { - refactorSpecificationApplication(term, goal, services, labels, hint); - } - else if (isParentRefactroingRequired(state)) { - refactorInCaseOfNewIdRequired(state, goal, term, services, labels); - } - else if (isUpdateRefactroingRequired(state)) { - refactorBewlowUpdates(applicationPosInOccurrence, term, labels); - } - else if (containsSequentFormulasToRefactor(state)) { - refactorSequentFormulas(state, services, term, labels); - } - else if (SyntacticalReplaceVisitor.SUBSTITUTION_WITH_LABELS_HINT.equals(hint)) { - refactorSubstitution(term, tacletTerm, labels); - } - } + /** + * {@inheritDoc} + */ + @Override + public void refactorLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Term term, List labels) { + if (shouldRefactorSpecificationApplication(rule, goal, hint)) { + refactorSpecificationApplication(term, goal, services, labels, hint); + } else if (isParentRefactroingRequired(state)) { + refactorInCaseOfNewIdRequired(state, goal, term, services, labels); + } else if (isUpdateRefactroingRequired(state)) { + refactorBewlowUpdates(applicationPosInOccurrence, term, labels); + } else if (containsSequentFormulasToRefactor(state)) { + refactorSequentFormulas(state, services, term, labels); + } else if (SyntacticalReplaceVisitor.SUBSTITUTION_WITH_LABELS_HINT.equals(hint)) { + refactorSubstitution(term, tacletTerm, labels); + } + } - /** - * Refactors a specification application. - * @param term The {@link Term} which is now refactored. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param labels The new labels the {@link Term} will have after the refactoring. - */ - protected void refactorSpecificationApplication(Term term, - Goal goal, - Services services, - List labels, - Object hint) { - if (TruthValueTracingUtil.isPredicate(term) - || (CloseAfterMerge.FINAL_WEAKENING_TERM_HINT.equals(hint) && TruthValueTracingUtil.isLogicOperator(term))) { - TermLabel existingLabel = term.getLabel(FormulaTermLabel.NAME); - if (existingLabel == null) { - int labelID = services.getCounter(FormulaTermLabel.PROOF_COUNTER_NAME).getCountPlusPlus(); - int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); - labels.add(new FormulaTermLabel(labelID, labelSubID)); - } - } - } - - /** - * Refactors in case that the inner most label needs a new ID. - * @param state The {@link TermLabelState} of the current rule application. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param term The {@link Term} which is now refactored. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param labels The new labels the {@link Term} will have after the refactoring. - */ - protected void refactorInCaseOfNewIdRequired(TermLabelState state, - Goal goal, - Term term, - Services services, - List labels) { - if (goal != null && !isInnerMostParentRefactored(state, goal)) { - TermLabel existingLabel = term.getLabel(FormulaTermLabel.NAME); - if (existingLabel instanceof FormulaTermLabel) { - FormulaTermLabel pLabel = (FormulaTermLabel) existingLabel; - int labelID = pLabel.getMajorId(); - int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); - labels.remove(existingLabel); - labels.add(new FormulaTermLabel(labelID, labelSubID, Collections.singletonList(pLabel.getId()))); - setInnerMostParentRefactored(state, goal, true); - } - } - } + /** + * Refactors a specification application. + * + * @param term The {@link Term} which is now refactored. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param labels The new labels the {@link Term} will have after the refactoring. + */ + protected void refactorSpecificationApplication(Term term, Goal goal, Services services, + List labels, Object hint) { + if (TruthValueTracingUtil.isPredicate(term) + || (CloseAfterMerge.FINAL_WEAKENING_TERM_HINT.equals(hint) + && TruthValueTracingUtil.isLogicOperator(term))) { + TermLabel existingLabel = term.getLabel(FormulaTermLabel.NAME); + if (existingLabel == null) { + int labelID = + services.getCounter(FormulaTermLabel.PROOF_COUNTER_NAME).getCountPlusPlus(); + int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); + labels.add(new FormulaTermLabel(labelID, labelSubID)); + } + } + } - /** - * Refactors the {@link Term} below its update. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param term The {@link Term} which is now refactored. - * @param labels The new labels the {@link Term} will have after the refactoring. - */ - protected void refactorBewlowUpdates(PosInOccurrence applicationPosInOccurrence, - Term term, - List labels) { - Term applicationTerm = applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; - FormulaTermLabel applicationLabel = applicationTerm != null ? (FormulaTermLabel) applicationTerm.getLabel(FormulaTermLabel.NAME) : null; - if (applicationLabel != null) { - FormulaTermLabel termLabel = (FormulaTermLabel)term.getLabel(FormulaTermLabel.NAME); - if (termLabel == null) { - labels.add(applicationLabel); - } - else { - labels.remove(termLabel); - Set beforeIds = new LinkedHashSet(); - CollectionUtil.addAll(beforeIds, termLabel.getBeforeIds()); - beforeIds.add(applicationLabel.getId()); - labels.add(new FormulaTermLabel(termLabel.getMajorId(), termLabel.getMinorId(), beforeIds)); - } - } - } + /** + * Refactors in case that the inner most label needs a new ID. + * + * @param state The {@link TermLabelState} of the current rule application. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param term The {@link Term} which is now refactored. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param labels The new labels the {@link Term} will have after the refactoring. + */ + protected void refactorInCaseOfNewIdRequired(TermLabelState state, Goal goal, Term term, + Services services, List labels) { + if (goal != null && !isInnerMostParentRefactored(state, goal)) { + TermLabel existingLabel = term.getLabel(FormulaTermLabel.NAME); + if (existingLabel instanceof FormulaTermLabel) { + FormulaTermLabel pLabel = (FormulaTermLabel) existingLabel; + int labelID = pLabel.getMajorId(); + int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); + labels.remove(existingLabel); + labels.add(new FormulaTermLabel(labelID, labelSubID, + Collections.singletonList(pLabel.getId()))); + setInnerMostParentRefactored(state, goal, true); + } + } + } - /** - * Refactors the specified {@link SequentFormula}s. - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param term The {@link Term} which is now refactored. - * @param labels The new labels the {@link Term} will have after the refactoring. - */ - protected void refactorSequentFormulas(TermLabelState state, - Services services, - final Term term, - List labels) { - Set sequentFormulas = getSequentFormulasToRefactor(state); - if (CollectionUtil.search(sequentFormulas, new IFilter() { - @Override - public boolean select(SequentFormula element) { - return element.formula() == term; - } - }) != null) { - FormulaTermLabel termLabel = (FormulaTermLabel)term.getLabel(FormulaTermLabel.NAME); - if (termLabel != null) { - labels.remove(termLabel); - Set beforeIds = new LinkedHashSet(); - beforeIds.add(termLabel.getId()); - int labelSubID = FormulaTermLabel.newLabelSubID(services, termLabel); - labels.add(new FormulaTermLabel(termLabel.getMajorId(), labelSubID, beforeIds)); - } - } - } + /** + * Refactors the {@link Term} below its update. + * + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param term The {@link Term} which is now refactored. + * @param labels The new labels the {@link Term} will have after the refactoring. + */ + protected void refactorBewlowUpdates(PosInOccurrence applicationPosInOccurrence, Term term, + List labels) { + Term applicationTerm = + applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; + FormulaTermLabel applicationLabel = applicationTerm != null + ? (FormulaTermLabel) applicationTerm.getLabel(FormulaTermLabel.NAME) + : null; + if (applicationLabel != null) { + FormulaTermLabel termLabel = (FormulaTermLabel) term.getLabel(FormulaTermLabel.NAME); + if (termLabel == null) { + labels.add(applicationLabel); + } else { + labels.remove(termLabel); + Set beforeIds = new LinkedHashSet(); + CollectionUtil.addAll(beforeIds, termLabel.getBeforeIds()); + beforeIds.add(applicationLabel.getId()); + labels.add(new FormulaTermLabel(termLabel.getMajorId(), termLabel.getMinorId(), + beforeIds)); + } + } + } - /** - * Refactors the given {@link Term} after a substitiution. - * @param term The {@link Term} to refactor. - * @param tacletTerm The taclet {@link Term} which provides additional labels to be merged with the other {@link Term}. - * @param labels The new labels the {@link Term} will have after the refactoring. - */ - protected void refactorSubstitution(Term term, - Term tacletTerm, - List labels) { - FormulaTermLabel tacletLabel = (FormulaTermLabel) tacletTerm.getLabel(FormulaTermLabel.NAME); - if (tacletLabel != null) { - FormulaTermLabel existingLabel = (FormulaTermLabel) term.getLabel(FormulaTermLabel.NAME); - if (existingLabel == null) { - labels.add(tacletLabel); - } - else { - List beforeIds = new LinkedList(); - CollectionUtil.addAll(beforeIds, existingLabel.getBeforeIds()); - boolean changed = true; - if (!beforeIds.contains(tacletLabel.getId())) { - changed = true; - beforeIds.add(tacletLabel.getId()); + /** + * Refactors the specified {@link SequentFormula}s. + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param term The {@link Term} which is now refactored. + * @param labels The new labels the {@link Term} will have after the refactoring. + */ + protected void refactorSequentFormulas(TermLabelState state, Services services, final Term term, + List labels) { + Set sequentFormulas = getSequentFormulasToRefactor(state); + if (CollectionUtil.search(sequentFormulas, new IFilter() { + @Override + public boolean select(SequentFormula element) { + return element.formula() == term; } - for (String id : tacletLabel.getBeforeIds()) { - if (!beforeIds.contains(id)) { - changed = true; - beforeIds.add(id); - } + }) != null) { + FormulaTermLabel termLabel = (FormulaTermLabel) term.getLabel(FormulaTermLabel.NAME); + if (termLabel != null) { + labels.remove(termLabel); + Set beforeIds = new LinkedHashSet(); + beforeIds.add(termLabel.getId()); + int labelSubID = FormulaTermLabel.newLabelSubID(services, termLabel); + labels.add(new FormulaTermLabel(termLabel.getMajorId(), labelSubID, beforeIds)); } - if (changed) { - labels.remove(existingLabel); - labels.add(new FormulaTermLabel(existingLabel.getMajorId(), existingLabel.getMinorId(), beforeIds)); + } + } + + /** + * Refactors the given {@link Term} after a substitiution. + * + * @param term The {@link Term} to refactor. + * @param tacletTerm The taclet {@link Term} which provides additional labels to be merged with + * the other {@link Term}. + * @param labels The new labels the {@link Term} will have after the refactoring. + */ + protected void refactorSubstitution(Term term, Term tacletTerm, List labels) { + FormulaTermLabel tacletLabel = + (FormulaTermLabel) tacletTerm.getLabel(FormulaTermLabel.NAME); + if (tacletLabel != null) { + FormulaTermLabel existingLabel = + (FormulaTermLabel) term.getLabel(FormulaTermLabel.NAME); + if (existingLabel == null) { + labels.add(tacletLabel); + } else { + List beforeIds = new LinkedList(); + CollectionUtil.addAll(beforeIds, existingLabel.getBeforeIds()); + boolean changed = true; + if (!beforeIds.contains(tacletLabel.getId())) { + changed = true; + beforeIds.add(tacletLabel.getId()); + } + for (String id : tacletLabel.getBeforeIds()) { + if (!beforeIds.contains(id)) { + changed = true; + beforeIds.add(id); + } + } + if (changed) { + labels.remove(existingLabel); + labels.add(new FormulaTermLabel(existingLabel.getMajorId(), + existingLabel.getMinorId(), beforeIds)); + } } - } - } - } + } + } - /** - * Checks if the inner most parent was already refactored on the given {@link Goal}. - * @param state The {@link TermLabelState} to read from. - * @param goal The {@link Goal} to check. - * @return {@code true} already refactored, {@code false} not refactored yet. - */ - public static boolean isInnerMostParentRefactored(TermLabelState state, Goal goal) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - return labelState.containsKey(INNER_MOST_PARENT_REFACTORED_PREFIX + goal.node().serialNr()); - } + /** + * Checks if the inner most parent was already refactored on the given {@link Goal}. + * + * @param state The {@link TermLabelState} to read from. + * @param goal The {@link Goal} to check. + * @return {@code true} already refactored, {@code false} not refactored yet. + */ + public static boolean isInnerMostParentRefactored(TermLabelState state, Goal goal) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + return labelState.containsKey(INNER_MOST_PARENT_REFACTORED_PREFIX + goal.node().serialNr()); + } - /** - * Defines if the inner most parent was already refactored on the given {@link Goal}. - * @param state The {@link TermLabelState} to read from. - * @param goal The {@link Goal} to check. - * @param refactored {@code true} already refactored, {@code false} not refactored yet. - */ - public static void setInnerMostParentRefactored(TermLabelState state, Goal goal, boolean refactored) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - labelState.put(INNER_MOST_PARENT_REFACTORED_PREFIX + goal.node().serialNr(), Boolean.valueOf(refactored)); - } + /** + * Defines if the inner most parent was already refactored on the given {@link Goal}. + * + * @param state The {@link TermLabelState} to read from. + * @param goal The {@link Goal} to check. + * @param refactored {@code true} already refactored, {@code false} not refactored yet. + */ + public static void setInnerMostParentRefactored(TermLabelState state, Goal goal, + boolean refactored) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + labelState.put(INNER_MOST_PARENT_REFACTORED_PREFIX + goal.node().serialNr(), + Boolean.valueOf(refactored)); + } - /** - * Checks if a refactoring below the updates is required. - * @param state The {@link TermLabelState} to read from. - * @return {@code true} refactoring required, {@code false} refactoring is not required. - */ - public static boolean isUpdateRefactroingRequired(TermLabelState state) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - Object value = labelState.get(UPDATE_REFACTORING_REQUIRED); - return value instanceof Boolean && ((Boolean) value).booleanValue(); - } + /** + * Checks if a refactoring below the updates is required. + * + * @param state The {@link TermLabelState} to read from. + * @return {@code true} refactoring required, {@code false} refactoring is not required. + */ + public static boolean isUpdateRefactroingRequired(TermLabelState state) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + Object value = labelState.get(UPDATE_REFACTORING_REQUIRED); + return value instanceof Boolean && ((Boolean) value).booleanValue(); + } - /** - * Defines if a refactoring below the updates is required. - * @param state The {@link TermLabelState} to modify. - * @param required {@code true} refactoring required, {@code false} refactoring is not required. - */ - public static void setUpdateRefactroingRequired(TermLabelState state, boolean required) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - labelState.put(UPDATE_REFACTORING_REQUIRED, Boolean.valueOf(required)); - } + /** + * Defines if a refactoring below the updates is required. + * + * @param state The {@link TermLabelState} to modify. + * @param required {@code true} refactoring required, {@code false} refactoring is not required. + */ + public static void setUpdateRefactroingRequired(TermLabelState state, boolean required) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + labelState.put(UPDATE_REFACTORING_REQUIRED, Boolean.valueOf(required)); + } - /** - * Checks if a refactoring of parents is required. - * @param state The {@link TermLabelState} to read from. - * @return {@code true} refactoring required, {@code false} refactoring is not required. - */ - public static boolean isParentRefactroingRequired(TermLabelState state) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - Object value = labelState.get(PARENT_REFACTORING_REQUIRED); - return value instanceof Boolean && ((Boolean) value).booleanValue(); - } + /** + * Checks if a refactoring of parents is required. + * + * @param state The {@link TermLabelState} to read from. + * @return {@code true} refactoring required, {@code false} refactoring is not required. + */ + public static boolean isParentRefactroingRequired(TermLabelState state) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + Object value = labelState.get(PARENT_REFACTORING_REQUIRED); + return value instanceof Boolean && ((Boolean) value).booleanValue(); + } - /** - * Defines if a refactoring of parents is required. - * @param state The {@link TermLabelState} to modify. - * @param required {@code true} refactoring required, {@code false} refactoring is not required. - */ - public static void setParentRefactroingRequired(TermLabelState state, boolean required) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - labelState.put(PARENT_REFACTORING_REQUIRED, Boolean.valueOf(required)); - } + /** + * Defines if a refactoring of parents is required. + * + * @param state The {@link TermLabelState} to modify. + * @param required {@code true} refactoring required, {@code false} refactoring is not required. + */ + public static void setParentRefactroingRequired(TermLabelState state, boolean required) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + labelState.put(PARENT_REFACTORING_REQUIRED, Boolean.valueOf(required)); + } - /** - * Checks if {@link SequentFormula}s to refactor are specified. - * @param state The {@link TermLabelState} to read from. - * @return {@code true} at least one {@link SequentFormula} needs to be refactored, {@code false} refactoring is not required. - */ - public static boolean containsSequentFormulasToRefactor(TermLabelState state) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - @SuppressWarnings("unchecked") - Set sfSet = (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); - return !CollectionUtil.isEmpty(sfSet); - } + /** + * Checks if {@link SequentFormula}s to refactor are specified. + * + * @param state The {@link TermLabelState} to read from. + * @return {@code true} at least one {@link SequentFormula} needs to be refactored, + * {@code false} refactoring is not required. + */ + public static boolean containsSequentFormulasToRefactor(TermLabelState state) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + @SuppressWarnings("unchecked") + Set sfSet = + (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); + return !CollectionUtil.isEmpty(sfSet); + } - /** - * Returns the {@link SequentFormula}s to refactor. - * @param state The {@link TermLabelState} to read from. - * @return The {@link SequentFormula}s to refactor. - */ - public static Set getSequentFormulasToRefactor(TermLabelState state) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - @SuppressWarnings("unchecked") - Set sfSet = (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); - return sfSet; - } + /** + * Returns the {@link SequentFormula}s to refactor. + * + * @param state The {@link TermLabelState} to read from. + * @return The {@link SequentFormula}s to refactor. + */ + public static Set getSequentFormulasToRefactor(TermLabelState state) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + @SuppressWarnings("unchecked") + Set sfSet = + (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); + return sfSet; + } - /** - * Adds the given {@link SequentFormula} for refactoring purpose. - * @param state The {@link TermLabelState} to modify. - * @param sf The {@link SequentFormula} to add. - */ - public static void addSequentFormulaToRefactor(TermLabelState state, SequentFormula sf) { - Map labelState = state.getLabelState(FormulaTermLabel.NAME); - @SuppressWarnings("unchecked") - Set sfSet = (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); - if (sfSet == null) { - sfSet = new LinkedHashSet(); - labelState.put(SEQUENT_FORMULA_REFACTORING_REQUIRED, sfSet); - } - sfSet.add(sf); - } + /** + * Adds the given {@link SequentFormula} for refactoring purpose. + * + * @param state The {@link TermLabelState} to modify. + * @param sf The {@link SequentFormula} to add. + */ + public static void addSequentFormulaToRefactor(TermLabelState state, SequentFormula sf) { + Map labelState = state.getLabelState(FormulaTermLabel.NAME); + @SuppressWarnings("unchecked") + Set sfSet = + (Set) labelState.get(SEQUENT_FORMULA_REFACTORING_REQUIRED); + if (sfSet == null) { + sfSet = new LinkedHashSet(); + labelState.put(SEQUENT_FORMULA_REFACTORING_REQUIRED, sfSet); + } + sfSet.add(sf); + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelUpdate.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelUpdate.java index 5ad5820c653..565cf3a7cce 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelUpdate.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/FormulaTermLabelUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Collections; @@ -32,95 +35,96 @@ import de.uka.ilkd.key.symbolic_execution.TruthValueTracingUtil; /** - * The {@link TermLabelUpdate} used to label predicates with a - * {@link FormulaTermLabel} of add clauses which were not labeled before. + * The {@link TermLabelUpdate} used to label predicates with a {@link FormulaTermLabel} of add + * clauses which were not labeled before. + * * @author Martin Hentschel */ public class FormulaTermLabelUpdate implements TermLabelUpdate { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return null; // Support all rules. - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return null; // Support all rules. + } - /** - * {@inheritDoc} - */ - @Override - public void updateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Set labels) { - if (hint instanceof TacletLabelHint) { - TacletLabelHint tacletHint = (TacletLabelHint) hint; - if ((TacletOperation.ADD_ANTECEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.ADD_SUCCEDENT.equals(tacletHint.getTacletOperation())) && - (TruthValueTracingUtil.isPredicate(newTermOp) || - TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs))) { - if (getTermLabel(labels, FormulaTermLabel.NAME) == null) { - TermLabel label = TermLabelManager.findInnerMostParentLabel(applicationPosInOccurrence, FormulaTermLabel.NAME); - if (label instanceof FormulaTermLabel) { - FormulaTermLabel oldLabel = (FormulaTermLabel) label; - int labelSubID = FormulaTermLabel.newLabelSubID(services, oldLabel); - FormulaTermLabel newLabel = new FormulaTermLabel(oldLabel.getMajorId(), labelSubID, Collections.singletonList(oldLabel.getId())); - labels.add(newLabel); - // Let the PredicateTermLabelRefactoring perform the refactoring, see also PredicateTermLabelRefactoring#PARENT_REFACTORING_REQUIRED - FormulaTermLabelRefactoring.setParentRefactroingRequired(state, true); - } + /** + * {@inheritDoc} + */ + @Override + public void updateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, Set labels) { + if (hint instanceof TacletLabelHint) { + TacletLabelHint tacletHint = (TacletLabelHint) hint; + if ((TacletOperation.ADD_ANTECEDENT.equals(tacletHint.getTacletOperation()) + || TacletOperation.ADD_SUCCEDENT.equals(tacletHint.getTacletOperation())) + && (TruthValueTracingUtil.isPredicate(newTermOp) + || TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs))) { + if (getTermLabel(labels, FormulaTermLabel.NAME) == null) { + TermLabel label = TermLabelManager.findInnerMostParentLabel( + applicationPosInOccurrence, FormulaTermLabel.NAME); + if (label instanceof FormulaTermLabel) { + FormulaTermLabel oldLabel = (FormulaTermLabel) label; + int labelSubID = FormulaTermLabel.newLabelSubID(services, oldLabel); + FormulaTermLabel newLabel = new FormulaTermLabel(oldLabel.getMajorId(), + labelSubID, Collections.singletonList(oldLabel.getId())); + labels.add(newLabel); + // Let the PredicateTermLabelRefactoring perform the refactoring, see also + // PredicateTermLabelRefactoring#PARENT_REFACTORING_REQUIRED + FormulaTermLabelRefactoring.setParentRefactroingRequired(state, true); + } + } } - } - } - if (ruleApp instanceof TacletApp) { - TacletApp ta = (TacletApp) ruleApp; - if (ta.ifInstsComplete() && ta.ifFormulaInstantiations() != null) { - Map ifLabels = new LinkedHashMap(); - for (IfFormulaInstantiation ifInst : ta.ifFormulaInstantiations()) { - FormulaTermLabel ifLabel = StayOnFormulaTermLabelPolicy.searchFormulaTermLabel(ifInst.getConstrainedFormula().formula().getLabels()); - if (ifLabel != null) { - ifLabels.put(ifInst.getConstrainedFormula(), ifLabel); - } + } + if (ruleApp instanceof TacletApp) { + TacletApp ta = (TacletApp) ruleApp; + if (ta.ifInstsComplete() && ta.ifFormulaInstantiations() != null) { + Map ifLabels = + new LinkedHashMap(); + for (IfFormulaInstantiation ifInst : ta.ifFormulaInstantiations()) { + FormulaTermLabel ifLabel = StayOnFormulaTermLabelPolicy.searchFormulaTermLabel( + ifInst.getConstrainedFormula().formula().getLabels()); + if (ifLabel != null) { + ifLabels.put(ifInst.getConstrainedFormula(), ifLabel); + } + } + if (!ifLabels.isEmpty()) { + if (TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs) + // || TruthValueEvaluationUtil.isPredicate(newTermOp) + ) { + for (Entry ifEntry : ifLabels + .entrySet()) { + FormulaTermLabel ifLabel = ifEntry.getValue(); + int labelSubID = FormulaTermLabel.newLabelSubID(services, ifLabel); + FormulaTermLabel newLabel = new FormulaTermLabel(ifLabel.getMajorId(), + labelSubID, Collections.singletonList(ifLabel.getId())); + labels.add(newLabel); + FormulaTermLabelRefactoring.addSequentFormulaToRefactor(state, + ifEntry.getKey()); + } + } + } } - if (!ifLabels.isEmpty()) { - if (TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs) -// || TruthValueEvaluationUtil.isPredicate(newTermOp) - ) { - for (Entry ifEntry : ifLabels.entrySet()) { - FormulaTermLabel ifLabel = ifEntry.getValue(); - int labelSubID = FormulaTermLabel.newLabelSubID(services, ifLabel); - FormulaTermLabel newLabel = new FormulaTermLabel(ifLabel.getMajorId(), labelSubID, Collections.singletonList(ifLabel.getId())); - labels.add(newLabel); - FormulaTermLabelRefactoring.addSequentFormulaToRefactor(state, ifEntry.getKey()); - } - } - } - } - } - } + } + } - /** - * Returns the {@link TermLabel} with the given {@link Name}. - * @param labels the {@link TermLabel}s to search in. - * @param name The {@link Name} of the {@link TermLabel} to search. - * @return The found {@link TermLabel} or {@code} null if no element was found. - */ - protected TermLabel getTermLabel(Set labels, final Name name) { - return CollectionUtil.search(labels, new IFilter() { - @Override - public boolean select(TermLabel element) { - return element != null && element.name().equals(name); - } - }); - } + /** + * Returns the {@link TermLabel} with the given {@link Name}. + * + * @param labels the {@link TermLabel}s to search in. + * @param name The {@link Name} of the {@link TermLabel} to search. + * @return The found {@link TermLabel} or {@code} null if no element was found. + */ + protected TermLabel getTermLabel(Set labels, final Name name) { + return CollectionUtil.search(labels, new IFilter() { + @Override + public boolean select(TermLabel element) { + return element != null && element.name().equals(name); + } + }); + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopBodyTermLabelUpdate.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopBodyTermLabelUpdate.java index c4fb116beaa..1ad22635b49 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopBodyTermLabelUpdate.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopBodyTermLabelUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Set; @@ -21,43 +24,34 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * Makes sure that {@link SymbolicExecutionUtil#LOOP_BODY_LABEL} is introduced - * when a {@link WhileInvariantRule} is applied. + * Makes sure that {@link SymbolicExecutionUtil#LOOP_BODY_LABEL} is introduced when a + * {@link WhileInvariantRule} is applied. + * * @author Martin Hentschel */ public class LoopBodyTermLabelUpdate implements TermLabelUpdate { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return ImmutableSLList.nil().append(WhileInvariantRule.INSTANCE.name()); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return ImmutableSLList.nil().append(WhileInvariantRule.INSTANCE.name()); + } - /** - * {@inheritDoc} - */ - @Override - public void updateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Set labels) { - if (rule instanceof WhileInvariantRule && - "LoopBodyModality".equals(hint) && - SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { - if (!labels.contains(SymbolicExecutionUtil.LOOP_BODY_LABEL)) { - labels.add(SymbolicExecutionUtil.LOOP_BODY_LABEL); - } - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void updateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, Set labels) { + if (rule instanceof WhileInvariantRule && "LoopBodyModality".equals(hint) + && SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { + if (!labels.contains(SymbolicExecutionUtil.LOOP_BODY_LABEL)) { + labels.add(SymbolicExecutionUtil.LOOP_BODY_LABEL); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopInvariantNormalBehaviorTermLabelUpdate.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopInvariantNormalBehaviorTermLabelUpdate.java index be3d560cd88..0f5d3539091 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopInvariantNormalBehaviorTermLabelUpdate.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/LoopInvariantNormalBehaviorTermLabelUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Set; @@ -23,41 +26,32 @@ /** * Makes sure that {@link SymbolicExecutionUtil#LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL} is introduced * when a {@link WhileInvariantRule} is applied. + * * @author Martin Hentschel */ public class LoopInvariantNormalBehaviorTermLabelUpdate implements TermLabelUpdate { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return ImmutableSLList.nil().append(WhileInvariantRule.INSTANCE.name()); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return ImmutableSLList.nil().append(WhileInvariantRule.INSTANCE.name()); + } - /** - * {@inheritDoc} - */ - @Override - public void updateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Set labels) { - if (rule instanceof WhileInvariantRule && - "LoopBodyImplication".equals(hint) && - SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { - if (!labels.contains(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL)) { - labels.add(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL); - } - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void updateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, Set labels) { + if (rule instanceof WhileInvariantRule && "LoopBodyImplication".equals(hint) + && SymbolicExecutionUtil.hasSymbolicExecutionLabel(modalityTerm)) { + if (!labels.contains(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL)) { + labels.add(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/RemoveInCheckBranchesTermLabelRefactoring.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/RemoveInCheckBranchesTermLabelRefactoring.java index 456436e3ef8..8dde076ca7b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/RemoveInCheckBranchesTermLabelRefactoring.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/RemoveInCheckBranchesTermLabelRefactoring.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Iterator; @@ -23,99 +26,85 @@ import de.uka.ilkd.key.rule.WhileInvariantRule; /** - * This {@link TermLabelRefactoring} removes the supported {@link TermLabel} - * in check branches. These are: + * This {@link TermLabelRefactoring} removes the supported {@link TermLabel} in check branches. + * These are: *
    - *
  • {@link AbstractAuxiliaryContractRule}: Pre
  • - *
  • {@link UseOperationContractRule}: Pre
  • - *
  • {@link UseOperationContractRule}: Null reference
  • - *
  • {@link WhileInvariantRule}: Invariant Initially Valid
  • + *
  • {@link AbstractAuxiliaryContractRule}: Pre
  • + *
  • {@link UseOperationContractRule}: Pre
  • + *
  • {@link UseOperationContractRule}: Null reference
  • + *
  • {@link WhileInvariantRule}: Invariant Initially Valid
  • *
+ * * @author Martin Hentschel */ public class RemoveInCheckBranchesTermLabelRefactoring implements TermLabelRefactoring { - /** - * The {@link Name} of the supported {@link TermLabel}. - */ - private final Name termLabelNameToRemove; + /** + * The {@link Name} of the supported {@link TermLabel}. + */ + private final Name termLabelNameToRemove; - /** - * Constructor. - * @param termLabelNameToRemove The {@link Name} of the supported {@link TermLabel}. - */ - public RemoveInCheckBranchesTermLabelRefactoring(Name termLabelNameToRemove) { - assert termLabelNameToRemove != null; - this.termLabelNameToRemove = termLabelNameToRemove; - } + /** + * Constructor. + * + * @param termLabelNameToRemove The {@link Name} of the supported {@link TermLabel}. + */ + public RemoveInCheckBranchesTermLabelRefactoring(Name termLabelNameToRemove) { + assert termLabelNameToRemove != null; + this.termLabelNameToRemove = termLabelNameToRemove; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return ImmutableSLList.nil().prepend(UseOperationContractRule.INSTANCE.name()) - .prepend(WhileInvariantRule.INSTANCE.name()) - .prepend(BlockContractInternalRule.INSTANCE.name()) - .prepend(BlockContractExternalRule.INSTANCE.name()) - .prepend(LoopContractInternalRule.INSTANCE.name()) - .prepend(LoopContractExternalRule.INSTANCE.name()); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return ImmutableSLList.nil().prepend(UseOperationContractRule.INSTANCE.name()) + .prepend(WhileInvariantRule.INSTANCE.name()) + .prepend(BlockContractInternalRule.INSTANCE.name()) + .prepend(BlockContractExternalRule.INSTANCE.name()) + .prepend(LoopContractInternalRule.INSTANCE.name()) + .prepend(LoopContractExternalRule.INSTANCE.name()); + } - /** - * {@inheritDoc} - */ - @Override - public RefactoringScope defineRefactoringScope(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - if (goal != null) { - if (rule instanceof UseOperationContractRule && - (goal.node().getNodeInfo().getBranchLabel().startsWith("Pre") || - goal.node().getNodeInfo().getBranchLabel().startsWith("Null reference"))) { - return RefactoringScope.SEQUENT; - } - else if (rule instanceof WhileInvariantRule && - goal.node().getNodeInfo().getBranchLabel().startsWith("Invariant Initially Valid")) { - return RefactoringScope.SEQUENT; - } - else if (rule instanceof AbstractAuxiliaryContractRule && - goal.node().getNodeInfo().getBranchLabel().startsWith("Precondition")) { - return RefactoringScope.SEQUENT; - } - else { + /** + * {@inheritDoc} + */ + @Override + public RefactoringScope defineRefactoringScope(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + if (goal != null) { + if (rule instanceof UseOperationContractRule + && (goal.node().getNodeInfo().getBranchLabel().startsWith("Pre") || goal.node() + .getNodeInfo().getBranchLabel().startsWith("Null reference"))) { + return RefactoringScope.SEQUENT; + } else if (rule instanceof WhileInvariantRule && goal.node().getNodeInfo() + .getBranchLabel().startsWith("Invariant Initially Valid")) { + return RefactoringScope.SEQUENT; + } else if (rule instanceof AbstractAuxiliaryContractRule + && goal.node().getNodeInfo().getBranchLabel().startsWith("Precondition")) { + return RefactoringScope.SEQUENT; + } else { + return RefactoringScope.NONE; + } + } else { return RefactoringScope.NONE; - } - } - else { - return RefactoringScope.NONE; - } - } + } + } - /** - * {@inheritDoc} - */ - @Override - public void refactorLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Term term, - List labels) { - Iterator iter = labels.iterator(); - while (iter.hasNext()) { - TermLabel next = iter.next(); - if (termLabelNameToRemove.equals(next.name())) { - iter.remove(); - } - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void refactorLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Term term, List labels) { + Iterator iter = labels.iterator(); + while (iter.hasNext()) { + TermLabel next = iter.next(); + if (termLabelNameToRemove.equals(next.name())) { + iter.remove(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/StayOnFormulaTermLabelPolicy.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/StayOnFormulaTermLabelPolicy.java index f527c0373f1..f919d22cac6 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/StayOnFormulaTermLabelPolicy.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/StayOnFormulaTermLabelPolicy.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Deque; @@ -28,160 +31,159 @@ /** * This {@link TermLabelPolicy} maintains a {@link FormulaTermLabel} on predicates. + * * @author Martin Hentschel */ public class StayOnFormulaTermLabelPolicy implements TermLabelPolicy { - /** - * {@inheritDoc} - */ - @Override - public TermLabel keepLabel(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels, - TermLabel label) { - // Maintain label if new Term is a predicate - if (TruthValueTracingUtil.isPredicate(newTermOp) || - TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs)) { - assert label instanceof FormulaTermLabel; - FormulaTermLabel formulaLabel = (FormulaTermLabel) label; - FormulaTermLabel originalLabel = searchFormulaTermLabel(newTermOriginalLabels); - FormulaTermLabel mostImportantLabel = originalLabel != null ? originalLabel : formulaLabel; - // May change sub ID if logical operators like junctors are used - boolean newLabelIdRequired = false; - Set originalLabelIds = new LinkedHashSet(); - if (hint instanceof TacletLabelHint) { - TacletLabelHint tacletHint = (TacletLabelHint) hint; - if (isBelowIfThenElse(tacletHint.getTacletTermStack())) { - return null; // Do not label children of if-then-else. They are labeled when a rule rewrites them outside of the if-then-else. + /** + * {@inheritDoc} + */ + @Override + public TermLabel keepLabel(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + ImmutableArray newTermOriginalLabels, TermLabel label) { + // Maintain label if new Term is a predicate + if (TruthValueTracingUtil.isPredicate(newTermOp) + || TruthValueTracingUtil.isLogicOperator(newTermOp, newTermSubs)) { + assert label instanceof FormulaTermLabel; + FormulaTermLabel formulaLabel = (FormulaTermLabel) label; + FormulaTermLabel originalLabel = searchFormulaTermLabel(newTermOriginalLabels); + FormulaTermLabel mostImportantLabel = + originalLabel != null ? originalLabel : formulaLabel; + // May change sub ID if logical operators like junctors are used + boolean newLabelIdRequired = false; + Set originalLabelIds = new LinkedHashSet(); + if (hint instanceof TacletLabelHint) { + TacletLabelHint tacletHint = (TacletLabelHint) hint; + if (isBelowIfThenElse(tacletHint.getTacletTermStack())) { + return null; // Do not label children of if-then-else. They are labeled when a + // rule rewrites them outside of the if-then-else. + } + if (TacletOperation.ADD_ANTECEDENT.equals(tacletHint.getTacletOperation()) + || TacletOperation.ADD_SUCCEDENT.equals(tacletHint.getTacletOperation()) + || TacletOperation.REPLACE_TO_ANTECEDENT + .equals(tacletHint.getTacletOperation()) + || TacletOperation.REPLACE_TO_SUCCEDENT + .equals(tacletHint.getTacletOperation()) + || TacletOperation.REPLACE_AT_ANTECEDENT + .equals(tacletHint.getTacletOperation()) + || TacletOperation.REPLACE_AT_SUCCEDENT + .equals(tacletHint.getTacletOperation())) { + if (originalLabel == null) { // Do not give a new ID if the term has already one + // (see rule: impRight) + newLabelIdRequired = true; + originalLabelIds.add(mostImportantLabel.getId()); + } + } + if (tacletHint.getSequentFormula() != null) { + if (!TruthValueTracingUtil.isPredicate(tacletHint.getSequentFormula())) { + newLabelIdRequired = true; + } + } else if (tacletHint.getTerm() != null) { + boolean topLevel = isTopLevel(tacletHint, tacletTerm); + if (!topLevel && !TruthValueTracingUtil.isPredicate(tacletHint.getTerm())) { + newLabelIdRequired = true; + } + } + if (mostImportantLabel != formulaLabel || newLabelIdRequired) { // Without support + // of quantors '&& + // topLevel' can be + // added. + originalLabelIds.add(formulaLabel.getId()); + } } - if (TacletOperation.ADD_ANTECEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.ADD_SUCCEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.REPLACE_TO_ANTECEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.REPLACE_TO_SUCCEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.REPLACE_AT_ANTECEDENT.equals(tacletHint.getTacletOperation()) || - TacletOperation.REPLACE_AT_SUCCEDENT.equals(tacletHint.getTacletOperation())) { - if (originalLabel == null) { // Do not give a new ID if the term has already one (see rule: impRight) - newLabelIdRequired = true; - originalLabelIds.add(mostImportantLabel.getId()); - } + // Replace label with a new one with increased sub ID. + if (newLabelIdRequired) { + if (originalLabel != null) { + originalLabelIds.add(originalLabel.getId()); + } + int labelSubID = FormulaTermLabel.newLabelSubID(services, mostImportantLabel); + if (!originalLabelIds.isEmpty()) { + return new FormulaTermLabel(mostImportantLabel.getMajorId(), labelSubID, + originalLabelIds); + } else { + return new FormulaTermLabel(mostImportantLabel.getMajorId(), labelSubID); + } + } else { + if (!originalLabelIds.isEmpty()) { + return new FormulaTermLabel(mostImportantLabel.getMajorId(), + mostImportantLabel.getMinorId(), originalLabelIds); + } else { + return label; + } } - if (tacletHint.getSequentFormula() != null) { - if (!TruthValueTracingUtil.isPredicate(tacletHint.getSequentFormula())) { - newLabelIdRequired = true; - } + } else if (UpdateApplication.UPDATE_APPLICATION.equals(newTermOp)) { + Term target = newTermSubs.get(UpdateApplication.targetPos()); + TermLabel targetLabel = target.getLabel(FormulaTermLabel.NAME); + if (targetLabel instanceof FormulaTermLabel) { + if (applicationPosInOccurrence != null) { + Term appliationTerm = applicationPosInOccurrence.subTerm(); + TermLabel applicationLabel = appliationTerm.getLabel(FormulaTermLabel.NAME); + if (applicationLabel instanceof FormulaTermLabel) { + // Let the PredicateTermLabelRefactoring perform the refactoring, see also + // PredicateTermLabelRefactoring#UPDATE_REFACTORING_REQUIRED + FormulaTermLabelRefactoring.setUpdateRefactroingRequired(state, true); + } + } } - else if (tacletHint.getTerm() != null) { - boolean topLevel = isTopLevel(tacletHint, tacletTerm); - if (!topLevel && !TruthValueTracingUtil.isPredicate(tacletHint.getTerm())) { - newLabelIdRequired = true; - } - } - if (mostImportantLabel != formulaLabel || newLabelIdRequired) { // Without support of quantors '&& topLevel' can be added. - originalLabelIds.add(formulaLabel.getId()); - } - } - // Replace label with a new one with increased sub ID. - if (newLabelIdRequired) { - if (originalLabel != null) { - originalLabelIds.add(originalLabel.getId()); - } - int labelSubID = FormulaTermLabel.newLabelSubID(services, mostImportantLabel); - if (!originalLabelIds.isEmpty()) { - return new FormulaTermLabel(mostImportantLabel.getMajorId(), labelSubID, originalLabelIds); - } - else { - return new FormulaTermLabel(mostImportantLabel.getMajorId(), labelSubID); - } - } - else { - if (!originalLabelIds.isEmpty()) { - return new FormulaTermLabel(mostImportantLabel.getMajorId(), mostImportantLabel.getMinorId(), originalLabelIds); - } - else { - return label; - } - } - } - else if (UpdateApplication.UPDATE_APPLICATION.equals(newTermOp)) { - Term target = newTermSubs.get(UpdateApplication.targetPos()); - TermLabel targetLabel = target.getLabel(FormulaTermLabel.NAME); - if (targetLabel instanceof FormulaTermLabel) { - if (applicationPosInOccurrence != null) { - Term appliationTerm = applicationPosInOccurrence.subTerm(); - TermLabel applicationLabel = appliationTerm.getLabel(FormulaTermLabel.NAME); - if (applicationLabel instanceof FormulaTermLabel) { - // Let the PredicateTermLabelRefactoring perform the refactoring, see also PredicateTermLabelRefactoring#UPDATE_REFACTORING_REQUIRED - FormulaTermLabelRefactoring.setUpdateRefactroingRequired(state, true); - } - } - } - return null; - } - else if (newTermOp instanceof SubstOp) { // Such operations perform for instance skolemization (e.g. rule allRight) - return label; - } - else { - return null; - } - } + return null; + } else if (newTermOp instanceof SubstOp) { // Such operations perform for instance + // skolemization (e.g. rule allRight) + return label; + } else { + return null; + } + } - /** - * Checks if the currently treated taclet {@link Term} is a child - * of an if-then-else operation. - * @param visitStack The taclet {@link Term} stack. - * @return {@code true} is below if-then-else, {@code false} otherwise. - */ - protected boolean isBelowIfThenElse(Deque visitStack) { - if (visitStack != null) { - return CollectionUtil.search(visitStack, new IFilter() { + /** + * Checks if the currently treated taclet {@link Term} is a child of an if-then-else operation. + * + * @param visitStack The taclet {@link Term} stack. + * @return {@code true} is below if-then-else, {@code false} otherwise. + */ + protected boolean isBelowIfThenElse(Deque visitStack) { + if (visitStack != null) { + return CollectionUtil.search(visitStack, new IFilter() { + @Override + public boolean select(Term element) { + return element.op() == IfThenElse.IF_THEN_ELSE; + } + }) != null; + } else { + return false; + } + } + + /** + * Searches the {@link FormulaTermLabel} in the given {@link TermLabel}s. + * + * @param labels The {@link TermLabel}s to search in. + * @return The found {@link FormulaTermLabel} or {@code null} if not available. + */ + public static FormulaTermLabel searchFormulaTermLabel(ImmutableArray labels) { + TermLabel result = CollectionUtil.search(labels, new IFilter() { @Override - public boolean select(Term element) { - return element.op() == IfThenElse.IF_THEN_ELSE; + public boolean select(TermLabel element) { + return element instanceof FormulaTermLabel; } - }) != null; - } - else { - return false; - } - } - - /** - * Searches the {@link FormulaTermLabel} in the given {@link TermLabel}s. - * @param labels The {@link TermLabel}s to search in. - * @return The found {@link FormulaTermLabel} or {@code null} if not available. - */ - public static FormulaTermLabel searchFormulaTermLabel(ImmutableArray labels) { - TermLabel result = CollectionUtil.search(labels, new IFilter() { - @Override - public boolean select(TermLabel element) { - return element instanceof FormulaTermLabel; - } - }); - return (FormulaTermLabel)result; - } + }); + return (FormulaTermLabel) result; + } - /** - * Checks if the given taclet {@link Term} is top level. - * @param tacletHint The {@link TacletLabelHint} to use. - * @param tacletTerm The taclet {@link Term} to check. - * @return {@code true} is top level, {@code false} is not top level. - */ - protected boolean isTopLevel(TacletLabelHint tacletHint, Term tacletTerm) { - if (TacletOperation.REPLACE_TERM.equals(tacletHint.getTacletOperation())) { - return tacletHint.getTerm() == tacletTerm; - } - else { - return tacletHint.getSequentFormula().formula() == tacletTerm; - } - } + /** + * Checks if the given taclet {@link Term} is top level. + * + * @param tacletHint The {@link TacletLabelHint} to use. + * @param tacletTerm The taclet {@link Term} to check. + * @return {@code true} is top level, {@code false} is not top level. + */ + protected boolean isTopLevel(TacletLabelHint tacletHint, Term tacletTerm) { + if (TacletOperation.REPLACE_TERM.equals(tacletHint.getTacletOperation())) { + return tacletHint.getTerm() == tacletTerm; + } else { + return tacletHint.getSequentFormula().formula() == tacletTerm; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/SymbolicExecutionTermLabelUpdate.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/SymbolicExecutionTermLabelUpdate.java index 8f5882f586e..8493d443e02 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/SymbolicExecutionTermLabelUpdate.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/rule/label/SymbolicExecutionTermLabelUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.rule.label; import java.util.Set; @@ -29,56 +32,48 @@ import de.uka.ilkd.key.rule.WhileInvariantRule; /** - * Makes sure that the ID of {@link SymbolicExecutionTermLabel}s is increased - * when a {@link WhileInvariantRule} is applied. + * Makes sure that the ID of {@link SymbolicExecutionTermLabel}s is increased when a + * {@link WhileInvariantRule} is applied. + * * @author Martin Hentschel */ public class SymbolicExecutionTermLabelUpdate implements TermLabelUpdate { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getSupportedRuleNames() { - return ImmutableSLList.nil() - .prepend(WhileInvariantRule.INSTANCE.name()) - .prepend(BlockContractInternalRule.INSTANCE.name()) - .prepend(BlockContractExternalRule.INSTANCE.name()) - .prepend(LoopContractInternalRule.INSTANCE.name()) - .prepend(LoopContractExternalRule.INSTANCE.name()); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getSupportedRuleNames() { + return ImmutableSLList.nil().prepend(WhileInvariantRule.INSTANCE.name()) + .prepend(BlockContractInternalRule.INSTANCE.name()) + .prepend(BlockContractExternalRule.INSTANCE.name()) + .prepend(LoopContractInternalRule.INSTANCE.name()) + .prepend(LoopContractExternalRule.INSTANCE.name()); + } - /** - * {@inheritDoc} - */ - @Override - public void updateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Set labels) { - if (rule instanceof WhileInvariantRule && "LoopBodyModality".equals(hint) || - ( rule instanceof AbstractAuxiliaryContractRule && - ((AbstractBlockContractRule.BlockContractHint)hint).getExceptionalVariable() != null) - ) { - TermLabel label = CollectionUtil.searchAndRemove(labels, new IFilter() { - @Override - public boolean select(TermLabel element) { - return element instanceof SymbolicExecutionTermLabel; + /** + * {@inheritDoc} + */ + @Override + public void updateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, Set labels) { + if (rule instanceof WhileInvariantRule && "LoopBodyModality".equals(hint) + || (rule instanceof AbstractAuxiliaryContractRule + && ((AbstractBlockContractRule.BlockContractHint) hint) + .getExceptionalVariable() != null)) { + TermLabel label = CollectionUtil.searchAndRemove(labels, new IFilter() { + @Override + public boolean select(TermLabel element) { + return element instanceof SymbolicExecutionTermLabel; + } + }); + if (label instanceof SymbolicExecutionTermLabel) { + int labelID = services.getCounter(SymbolicExecutionTermLabel.PROOF_COUNTER_NAME) + .getCountPlusPlus(); + labels.add(new SymbolicExecutionTermLabel(labelID)); } - }); - if (label instanceof SymbolicExecutionTermLabel) { - int labelID = services.getCounter(SymbolicExecutionTermLabel.PROOF_COUNTER_NAME).getCountPlusPlus(); - labels.add(new SymbolicExecutionTermLabel(labelID)); - } - } - } -} \ No newline at end of file + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/strategy/IBreakpointStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/strategy/IBreakpointStopCondition.java index c6ecc211ad2..cd6670fb5d9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/strategy/IBreakpointStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/strategy/IBreakpointStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.strategy; import java.util.Set; @@ -6,26 +9,30 @@ import de.uka.ilkd.key.symbolic_execution.strategy.breakpoint.IBreakpoint; /** - * Defines the basic functionality of an {@link StopCondition} which - * stops applying rules when at least one {@link IBreakpoint} is hit. + * Defines the basic functionality of an {@link StopCondition} which stops applying rules when at + * least one {@link IBreakpoint} is hit. + * * @author Martin Hentschel */ public interface IBreakpointStopCondition extends StopCondition { - /** - * Adds a new {@link IBreakpoint}. - * @param breakpoint The {@link IBreakpoint} to add. - */ - public void addBreakpoint(IBreakpoint breakpoint); - - /** - * Removes an {@link IBreakpoint}. - * @param breakpoint The {@link IBreakpoint} to remove. - */ - public void removeBreakpoint(IBreakpoint breakpoint); - - /** - * Returns all available {@link IBreakpoint}s. - * @return The available {@link IBreakpoint}s. - */ - public Set getBreakpoints(); -} \ No newline at end of file + /** + * Adds a new {@link IBreakpoint}. + * + * @param breakpoint The {@link IBreakpoint} to add. + */ + public void addBreakpoint(IBreakpoint breakpoint); + + /** + * Removes an {@link IBreakpoint}. + * + * @param breakpoint The {@link IBreakpoint} to remove. + */ + public void removeBreakpoint(IBreakpoint breakpoint); + + /** + * Returns all available {@link IBreakpoint}s. + * + * @return The available {@link IBreakpoint}s. + */ + public Set getBreakpoints(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractUpdateExtractor.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractUpdateExtractor.java index 1298932a353..b0988d95cad 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractUpdateExtractor.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractUpdateExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.Collections; @@ -52,1741 +55,1845 @@ /** * Provides the basic functionality to extract values from updates. + * * @author Martin Hentschel */ public abstract class AbstractUpdateExtractor { - /** - * Contains the {@link Node} of KeY's proof tree to compute memory layouts for. - */ - protected final Node node; - - /** - * The {@link PosInOccurrence} of the modality or its updates. - */ - protected final PosInOccurrence modalityPio; - - /** - * An incremented number used to give each pre value an unique name. - */ - private int preVariableIndex = 0; - - /** - * Constructor. - * @param node The {@link Node} of KeY's proof tree to compute memory layouts for. - * @param modalityPio The {@link PosInOccurrence} of the modality or its updates. - */ - public AbstractUpdateExtractor(Node node, - PosInOccurrence modalityPio) { - assert node != null; - assert modalityPio != null; - this.node = node; - this.modalityPio = modalityPio; - } - - /** - * Removes all conditions from the given path condition which contains - * implicit {@link IProgramVariable}s. - * @param pathCondition The path condition to check. - * @return The new path condition without conditions which uses implicit {@link IProgramVariable}s. - */ - protected Term removeImplicitSubTermsFromPathCondition(Term pathCondition) { - if (Junctor.AND == pathCondition.op()) { - // Path condition with multiple terms combined via AND - List newTerms = new LinkedList(); - for (Term sub : pathCondition.subs()) { - if (!containsImplicitProgramVariable(sub)) { - newTerms.add(sub); + /** + * Contains the {@link Node} of KeY's proof tree to compute memory layouts for. + */ + protected final Node node; + + /** + * The {@link PosInOccurrence} of the modality or its updates. + */ + protected final PosInOccurrence modalityPio; + + /** + * An incremented number used to give each pre value an unique name. + */ + private int preVariableIndex = 0; + + /** + * Constructor. + * + * @param node The {@link Node} of KeY's proof tree to compute memory layouts for. + * @param modalityPio The {@link PosInOccurrence} of the modality or its updates. + */ + public AbstractUpdateExtractor(Node node, PosInOccurrence modalityPio) { + assert node != null; + assert modalityPio != null; + this.node = node; + this.modalityPio = modalityPio; + } + + /** + * Removes all conditions from the given path condition which contains implicit + * {@link IProgramVariable}s. + * + * @param pathCondition The path condition to check. + * @return The new path condition without conditions which uses implicit + * {@link IProgramVariable}s. + */ + protected Term removeImplicitSubTermsFromPathCondition(Term pathCondition) { + if (Junctor.AND == pathCondition.op()) { + // Path condition with multiple terms combined via AND + List newTerms = new LinkedList(); + for (Term sub : pathCondition.subs()) { + if (!containsImplicitProgramVariable(sub)) { + newTerms.add(sub); + } } - } - return getServices().getTermBuilder().and(newTerms); - } - else { - // Only one term in path condition - if (!containsImplicitProgramVariable(pathCondition)) { - return pathCondition; - } - else { - return getServices().getTermBuilder().tt(); - } - } - } - - /** - * Checks if the given {@link Term} contains an implicit {@link IProgramVariable}. - * @param term The {@link Term} to check. - * @return {@code true} {@link Term} contains implicit {@link IProgramVariable}, {@code false} {@link Term} contains no implicit {@link IProgramVariable}. - */ - protected boolean containsImplicitProgramVariable(Term term) { - if (term.op() instanceof ProgramVariable && isImplicitProgramVariable((ProgramVariable)term.op())) { - return true; - } - for (int i = 0; i < term.arity(); i++) { - if (containsImplicitProgramVariable(term.sub(i))) { + return getServices().getTermBuilder().and(newTerms); + } else { + // Only one term in path condition + if (!containsImplicitProgramVariable(pathCondition)) { + return pathCondition; + } else { + return getServices().getTermBuilder().tt(); + } + } + } + + /** + * Checks if the given {@link Term} contains an implicit {@link IProgramVariable}. + * + * @param term The {@link Term} to check. + * @return {@code true} {@link Term} contains implicit {@link IProgramVariable}, {@code false} + * {@link Term} contains no implicit {@link IProgramVariable}. + */ + protected boolean containsImplicitProgramVariable(Term term) { + if (term.op() instanceof ProgramVariable + && isImplicitProgramVariable((ProgramVariable) term.op())) { return true; - } - } - return false; - } - - /** - * Checks if the given {@link ProgramVariable} is implicit. - * @param var The {@link ProgramVariable} to check. - * @return {@code true} {@link ProgramVariable} is implicit, {@code false} {@link ProgramVariable} is not implicit or {@code null}. - */ - protected boolean isImplicitProgramVariable(ProgramVariable var) { - return var != null && var.isImplicit(); - } - - /** - *

- * Computes objects which should be ignored in the state because - * they are part of the proof obligation and not of the source code. - *

- *

- * By default the set will contain the exc variable and the backup - * of arguments and the heap. - *

- * @param ignoreExceptionVariable Ignore exception variable? - * @param ignoreOldStateVariables Ignore old state variables? - * @return The objects to ignore. - */ - protected Set computeInitialObjectsToIgnore(boolean ignoreExceptionVariable, - boolean ignoreOldStateVariables) { - Set result = new LinkedHashSet(); - if (ignoreExceptionVariable) { - // Add exception variable to the ignore list because it is not part of the source code. - IProgramVariable excVar = SymbolicExecutionUtil.extractExceptionVariable(getProof()); - if (excVar instanceof ProgramVariable) { - result.add(getServices().getTermBuilder().var((ProgramVariable)excVar)); - } - } - if (ignoreOldStateVariables) { - // Add initial updates which are used as backup of the heap and method arguments. They are not part of the source code and should be ignored. - Sequent sequent = getRoot().sequent(); - for (SequentFormula sf : sequent.succedent()) { - Term term = sf.formula(); - if (Junctor.IMP.equals(term.op())) { - fillInitialObjectsToIgnoreRecursively(term.sub(1), result); + } + for (int i = 0; i < term.arity(); i++) { + if (containsImplicitProgramVariable(term.sub(i))) { + return true; } - } - } - return result; - } - - /** - * Utility method of {@link #computeInitialObjectsToIgnore()} which - * computes the objects to ignore recursively. - * @param term The current {@link Term}. - * @param toFill The {@link Set} with {@link Term}s to ignore to fill. - */ - protected void fillInitialObjectsToIgnoreRecursively(Term term, Set toFill) { - if (term.op() instanceof UpdateApplication) { - Term updateTerm = UpdateApplication.getUpdate(term); - fillInitialObjectsToIgnoreRecursively(updateTerm, toFill); - } - else if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { - for (int i = 0; i < term.arity(); i++) { - fillInitialObjectsToIgnoreRecursively(term.sub(i), toFill); - } - } - else if (term.op() instanceof ElementaryUpdate) { - ElementaryUpdate eu = (ElementaryUpdate)term.op(); - if (eu.lhs() instanceof ProgramVariable) { - toFill.add(term.sub(0)); - } - } - } - - /** - *

- * Computes for each location (value/association of an object) used in the - * updates of the given {@link Sequent} the {@link Term}s which allows to compute the object - * itself and the value of the value/association. The result is a {@link Set} - * of {@link ExtractLocationParameter} which contains the computed {@link Term}s. - *

- *

- * Objects which are created in the heap during symbolic execution and - * all objects which are used on the right side of associations are also - * collected and stored in the {@link Set}s {@code updateCreatedObjectsToFill}/ - * {@code updateValueObjectsToFill}. - *

- * @param sequent The {@link Sequent} which provides the updates to extract locations from. - * @param locationsToFill The location {@link Set} to fill. - * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. - * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to fill. - * @param objectsToIgnore The objects to ignore. - * @throws ProofInputException Occurred Exception. - */ - protected void collectLocationsFromUpdates(Sequent sequent, - Set locationsToFill, - Set updateCreatedObjectsToFill, - Set updateValueObjectsToFill, - Set objectsToIgnore) throws ProofInputException { - // Go up in parent hierarchy and collect updates on all update applications - PosInOccurrence pio = modalityPio; - while (pio != null) { - Term updateApplication = pio.subTerm(); - if (updateApplication.op() == UpdateApplication.UPDATE_APPLICATION) { - Term topUpdate = UpdateApplication.getUpdate(updateApplication); - collectLocationsFromTerm(topUpdate, locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill, objectsToIgnore); - } - if (!pio.isTopLevel()) { - pio = pio.up(); - } - else { - pio = null; - } - } - } - - /** - *

- * Computes for each location (value/association of an object) used in the - * the given {@link Term} the {@link Term}s which allows to compute the object - * itself and the value of the value/association. The result is a {@link Set} - * of {@link ExtractLocationParameter} which contains the computed {@link Term}s. - *

- *

- * Objects which are created in the heap during symbolic execution and - * all objects which are used on the right side of associations are also - * collected and stored in the {@link Set}s {@code updateCreatedObjectsToFill}/ - * {@code updateValueObjectsToFill}. - *

- * @param updateTerm The {@link Term} which provides the update to extract locations from. - * @param locationsToFill The location {@link Set} to fill. - * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. - * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to fill. - * @param objectsToIgnore The objects to ignore. - * @throws ProofInputException Occurred Exception. - */ - protected void collectLocationsFromTerm(Term updateTerm, - Set locationsToFill, - Set updateCreatedObjectsToFill, - Set updateValueObjectsToFill, - Set objectsToIgnore) throws ProofInputException { - if (updateTerm.op() instanceof UpdateJunctor) { - for (Term sub : updateTerm.subs()) { - collectLocationsFromTerm(sub, locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill, objectsToIgnore); - } - } - else if (updateTerm.op() instanceof ElementaryUpdate) { - ElementaryUpdate eu = (ElementaryUpdate)updateTerm.op(); - if (SymbolicExecutionUtil.isHeapUpdate(getServices(), updateTerm)) { - collectLocationsFromHeapUpdate(updateTerm.sub(0), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); - } - else if (eu.lhs() instanceof ProgramVariable) { - final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); - ProgramVariable var = (ProgramVariable)eu.lhs(); - if (!SymbolicExecutionUtil.isHeap(var, heapLDT)) { - if (!isImplicitProgramVariable(var) && - !objectsToIgnore.contains(getServices().getTermBuilder().var(var)) && - !hasFreeVariables(updateTerm)) { - locationsToFill.add(new ExtractLocationParameter(var, true)); - } - if (SymbolicExecutionUtil.hasReferenceSort(getServices(), updateTerm.sub(0))) { - Term objectTerm = updateTerm.sub(0); - objectTerm = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), objectTerm, getServices()); - updateValueObjectsToFill.add(OriginTermLabel.removeOriginLabels(objectTerm, getServices())); - } + } + return false; + } + + /** + * Checks if the given {@link ProgramVariable} is implicit. + * + * @param var The {@link ProgramVariable} to check. + * @return {@code true} {@link ProgramVariable} is implicit, {@code false} + * {@link ProgramVariable} is not implicit or {@code null}. + */ + protected boolean isImplicitProgramVariable(ProgramVariable var) { + return var != null && var.isImplicit(); + } + + /** + *

+ * Computes objects which should be ignored in the state because they are part of the proof + * obligation and not of the source code. + *

+ *

+ * By default the set will contain the exc variable and the backup of arguments and the heap. + *

+ * + * @param ignoreExceptionVariable Ignore exception variable? + * @param ignoreOldStateVariables Ignore old state variables? + * @return The objects to ignore. + */ + protected Set computeInitialObjectsToIgnore(boolean ignoreExceptionVariable, + boolean ignoreOldStateVariables) { + Set result = new LinkedHashSet(); + if (ignoreExceptionVariable) { + // Add exception variable to the ignore list because it is not part of the source code. + IProgramVariable excVar = SymbolicExecutionUtil.extractExceptionVariable(getProof()); + if (excVar instanceof ProgramVariable) { + result.add(getServices().getTermBuilder().var((ProgramVariable) excVar)); } - } - else { - throw new ProofInputException("Unsupported update operator \"" + eu.lhs() + "\"."); - } - } - else { - throw new ProofInputException("Unsupported update operator \"" + updateTerm.op() + "\"."); - } - } - - /** - *

- * Computes for each location (value/association of an object) used in the - * the given heap update {@link Term} the {@link Term}s which allows to compute the object - * itself and the value of the value/association. The result is a {@link Set} - * of {@link ExtractLocationParameter} which contains the computed {@link Term}s. - *

- *

- * Objects which are created in the heap during symbolic execution and - * all objects which are used on the right side of associations are also - * collected and stored in the {@link Set}s {@code updateCreatedObjectsToFill}/ - * {@code updateValueObjectsToFill}. - *

- * @param term The {@link Term} which provides the heap update to extract locations from. - * @param locationsToFill The location {@link Set} to fill. - * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. - * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to fill. - * @throws ProofInputException Occurred Exception. - */ - protected void collectLocationsFromHeapUpdate(Term term, - Set locationsToFill, - Set updateCreatedObjectsToFill, - Set updateValueObjectsToFill) throws ProofInputException { - final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); - if (term.op() == heapLDT.getStore()) { - // Add select object term to result - Term selectArgument = term.sub(1); - if (heapLDT.getSortOfSelect(selectArgument.op()) != null) { - ProgramVariable var = SymbolicExecutionUtil.getProgramVariable(getServices(), heapLDT, selectArgument.sub(2)); - if (var != null) { - if (!isImplicitProgramVariable(var) && - !hasFreeVariables(selectArgument.sub(2))) { - locationsToFill.add(new ExtractLocationParameter(var, selectArgument.sub(1))); - } + } + if (ignoreOldStateVariables) { + // Add initial updates which are used as backup of the heap and method arguments. They + // are not part of the source code and should be ignored. + Sequent sequent = getRoot().sequent(); + for (SequentFormula sf : sequent.succedent()) { + Term term = sf.formula(); + if (Junctor.IMP.equals(term.op())) { + fillInitialObjectsToIgnoreRecursively(term.sub(1), result); + } } - else { - Term arrayIndex = SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, selectArgument.sub(2)); - if (arrayIndex != null) { - if (!hasFreeVariables(arrayIndex)) { - locationsToFill.add(new ExtractLocationParameter(arrayIndex, selectArgument.sub(1))); - } - } - else { - throw new ProofInputException("Unsupported select statement \"" + term + "\"."); - } + } + return result; + } + + /** + * Utility method of {@link #computeInitialObjectsToIgnore()} which computes the objects to + * ignore recursively. + * + * @param term The current {@link Term}. + * @param toFill The {@link Set} with {@link Term}s to ignore to fill. + */ + protected void fillInitialObjectsToIgnoreRecursively(Term term, Set toFill) { + if (term.op() instanceof UpdateApplication) { + Term updateTerm = UpdateApplication.getUpdate(term); + fillInitialObjectsToIgnoreRecursively(updateTerm, toFill); + } else if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { + for (int i = 0; i < term.arity(); i++) { + fillInitialObjectsToIgnoreRecursively(term.sub(i), toFill); } - } - else if (selectArgument.op() instanceof IProgramVariable) { - ProgramVariable var = (ProgramVariable)selectArgument.op(); - if (!isImplicitProgramVariable(var) && - !hasFreeVariables(selectArgument)) { - locationsToFill.add(new ExtractLocationParameter(var, false)); + } else if (term.op() instanceof ElementaryUpdate) { + ElementaryUpdate eu = (ElementaryUpdate) term.op(); + if (eu.lhs() instanceof ProgramVariable) { + toFill.add(term.sub(0)); } - } - else if (heapLDT.getNull() == selectArgument.op()) { - // Static fields have a null term as select argument. - } - else { - for (int i = 0; i < selectArgument.arity(); i++) { - collectLocationsFromHeapUpdate(selectArgument.sub(i), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); + } + } + + /** + *

+ * Computes for each location (value/association of an object) used in the updates of the given + * {@link Sequent} the {@link Term}s which allows to compute the object itself and the value of + * the value/association. The result is a {@link Set} of {@link ExtractLocationParameter} which + * contains the computed {@link Term}s. + *

+ *

+ * Objects which are created in the heap during symbolic execution and all objects which are + * used on the right side of associations are also collected and stored in the {@link Set}s + * {@code updateCreatedObjectsToFill}/ {@code updateValueObjectsToFill}. + *

+ * + * @param sequent The {@link Sequent} which provides the updates to extract locations from. + * @param locationsToFill The location {@link Set} to fill. + * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. + * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to + * fill. + * @param objectsToIgnore The objects to ignore. + * @throws ProofInputException Occurred Exception. + */ + protected void collectLocationsFromUpdates(Sequent sequent, + Set locationsToFill, Set updateCreatedObjectsToFill, + Set updateValueObjectsToFill, Set objectsToIgnore) + throws ProofInputException { + // Go up in parent hierarchy and collect updates on all update applications + PosInOccurrence pio = modalityPio; + while (pio != null) { + Term updateApplication = pio.subTerm(); + if (updateApplication.op() == UpdateApplication.UPDATE_APPLICATION) { + Term topUpdate = UpdateApplication.getUpdate(updateApplication); + collectLocationsFromTerm(topUpdate, locationsToFill, updateCreatedObjectsToFill, + updateValueObjectsToFill, objectsToIgnore); } - } - // Add select value term to result - ProgramVariable var = SymbolicExecutionUtil.getProgramVariable(getServices(), heapLDT, term.sub(2)); - if (var != null) { - if (!isImplicitProgramVariable(var) && !hasFreeVariables(term.sub(2))) { - if (var.isStatic()) { - locationsToFill.add(new ExtractLocationParameter(var, true)); - } - else { - locationsToFill.add(new ExtractLocationParameter(var, term.sub(1))); - } + if (!pio.isTopLevel()) { + pio = pio.up(); + } else { + pio = null; } - } - else { - Term arrayIndex = SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, term.sub(2)); - if (arrayIndex != null && !hasFreeVariables(arrayIndex)) { - locationsToFill.add(new ExtractLocationParameter(arrayIndex, term.sub(1))); + } + } + + /** + *

+ * Computes for each location (value/association of an object) used in the the given + * {@link Term} the {@link Term}s which allows to compute the object itself and the value of the + * value/association. The result is a {@link Set} of {@link ExtractLocationParameter} which + * contains the computed {@link Term}s. + *

+ *

+ * Objects which are created in the heap during symbolic execution and all objects which are + * used on the right side of associations are also collected and stored in the {@link Set}s + * {@code updateCreatedObjectsToFill}/ {@code updateValueObjectsToFill}. + *

+ * + * @param updateTerm The {@link Term} which provides the update to extract locations from. + * @param locationsToFill The location {@link Set} to fill. + * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. + * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to + * fill. + * @param objectsToIgnore The objects to ignore. + * @throws ProofInputException Occurred Exception. + */ + protected void collectLocationsFromTerm(Term updateTerm, + Set locationsToFill, Set updateCreatedObjectsToFill, + Set updateValueObjectsToFill, Set objectsToIgnore) + throws ProofInputException { + if (updateTerm.op() instanceof UpdateJunctor) { + for (Term sub : updateTerm.subs()) { + collectLocationsFromTerm(sub, locationsToFill, updateCreatedObjectsToFill, + updateValueObjectsToFill, objectsToIgnore); } - else { - throw new ProofInputException("Unsupported select statement \"" + term + "\"."); + } else if (updateTerm.op() instanceof ElementaryUpdate) { + ElementaryUpdate eu = (ElementaryUpdate) updateTerm.op(); + if (SymbolicExecutionUtil.isHeapUpdate(getServices(), updateTerm)) { + collectLocationsFromHeapUpdate(updateTerm.sub(0), locationsToFill, + updateCreatedObjectsToFill, updateValueObjectsToFill); + } else if (eu.lhs() instanceof ProgramVariable) { + final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); + ProgramVariable var = (ProgramVariable) eu.lhs(); + if (!SymbolicExecutionUtil.isHeap(var, heapLDT)) { + if (!isImplicitProgramVariable(var) + && !objectsToIgnore.contains(getServices().getTermBuilder().var(var)) + && !hasFreeVariables(updateTerm)) { + locationsToFill.add(new ExtractLocationParameter(var, true)); + } + if (SymbolicExecutionUtil.hasReferenceSort(getServices(), updateTerm.sub(0))) { + Term objectTerm = updateTerm.sub(0); + objectTerm = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), + objectTerm, getServices()); + updateValueObjectsToFill + .add(OriginTermLabel.removeOriginLabels(objectTerm, getServices())); + } + } + } else { + throw new ProofInputException("Unsupported update operator \"" + eu.lhs() + "\"."); } - } - if (SymbolicExecutionUtil.hasReferenceSort(getServices(), term.sub(3)) && term.sub(3).op() instanceof ProgramVariable) { - Term objectTerm = term.sub(3); - objectTerm = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), objectTerm, getServices()); - updateValueObjectsToFill.add(OriginTermLabel.removeOriginLabels(objectTerm, getServices())); - } - // Iterate over child heap modifications - collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); - } - else if (term.op() == heapLDT.getCreate()) { - Term newObject = term.sub(1); - newObject = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), newObject, getServices()); - updateCreatedObjectsToFill.add(OriginTermLabel.removeOriginLabels(newObject, getServices())); - // Iterate over child heap modifications - collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); - } - else if (term.op() == heapLDT.getHeap()) { - // Initial Heap, nothing to do - } - else if (term.op() == heapLDT.getMemset()) { - // Check modified array range. - Term arrayRange = term.sub(1); - if (arrayRange.op() == getServices().getTypeConverter().getLocSetLDT().getArrayRange()) { - Term array = arrayRange.sub(0); - Term startIndex = arrayRange.sub(1); - Term endIndex = arrayRange.sub(2); - locationsToFill.add(new ExtractLocationParameter(startIndex, endIndex, array)); - } - // Iterate over child heap modifications - collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); - } - else { - for (int i = 0; i < term.arity(); i++) { - collectLocationsFromHeapUpdate(term.sub(i), locationsToFill, updateCreatedObjectsToFill, updateValueObjectsToFill); - } - } - } - - /** - * Checks if the given {@link Term} has free variables. - * @param term The {@link Term} to check. - * @return {@code true} has free variables, {@code false} does not have free variables. - */ - protected boolean hasFreeVariables(Term term) { - return term != null && !term.freeVars().isEmpty(); - } - - /** - * Computes for each location (value/association of an object) used in the - * given {@link Sequent} the {@link Term}s which allows to compute the object - * itself and the value of the value/association. The result is a {@link Set} - * of {@link ExtractLocationParameter} which contains the computed {@link Term}s. - * @param sequent The {@link Sequent} to extract locations from. - * @param objectsToIgnore The objects to ignore. - * @return The found locations. - * @throws ProofInputException Occurred Exception. - */ - protected Set extractLocationsFromSequent(Sequent sequent, - Set objectsToIgnore) throws ProofInputException { - Set result = new LinkedHashSet(); - for (SequentFormula sf : sequent) { - result.addAll(extractLocationsFromTerm(OriginTermLabel.removeOriginLabels(sf.formula(), getServices()), objectsToIgnore)); - } - return result; - } - - /** - * Computes for each location (value/association of an object) used in the - * given {@link Term} the {@link Term}s which allows to compute the object - * itself and the value of the value/association. The result is a {@link Set} - * of {@link ExtractLocationParameter} which contains the computed {@link Term}s. - * @param term The {@link Term} to extract locations from. - * @param objectsToIgnore The objects to ignore. - * @return The found locations. - * @throws ProofInputException Occurred Exception. - */ - protected Set extractLocationsFromTerm(Term term, - Set objectsToIgnore) throws ProofInputException { - Set result = new LinkedHashSet(); - collectLocationsFromTerm(result, term, objectsToIgnore); - return result; - } - - /** - * Utility method of {@link #extractLocationsFromTerm(Term, Set)} which - * recursively extracts the locations. - * @param toFill The result {@link Set} to fill. - * @param term The current {@link Term}. - * @param objectsToIgnore The objects to ignore. - * @throws ProofInputException Occurred Exception. - */ - protected void collectLocationsFromTerm(Set toFill, - Term term, - Set objectsToIgnore) throws ProofInputException { - term = OriginTermLabel.removeOriginLabels(term, getServices()); - final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); - if (term.op() instanceof ProgramVariable) { - ProgramVariable var = (ProgramVariable)term.op(); - if (!SymbolicExecutionUtil.isHeap(var, heapLDT) && - !isImplicitProgramVariable(var) && - !objectsToIgnore.contains(term) && - !hasFreeVariables(term)) { - toFill.add(new ExtractLocationParameter(var, true)); - } - } - else { - Sort sort = heapLDT.getSortOfSelect(term.op()); - if (sort != null) { - collectLocationsFromHeapTerms(term.sub(1), term.sub(2), heapLDT, toFill, objectsToIgnore); - } - else if (heapLDT.getStore() == term.op()) { - collectLocationsFromHeapTerms(term.sub(1), term.sub(2), heapLDT, toFill, objectsToIgnore); - } - else if (heapLDT.getLength() == term.op()) { - if (!objectsToIgnore.contains(term.sub(0)) && - !hasFreeVariables(term)) { - ProgramVariable var = getServices().getJavaInfo().getArrayLength(); - toFill.add(new ExtractLocationParameter(var, term.sub(0))); + } else { + throw new ProofInputException( + "Unsupported update operator \"" + updateTerm.op() + "\"."); + } + } + + /** + *

+ * Computes for each location (value/association of an object) used in the the given heap update + * {@link Term} the {@link Term}s which allows to compute the object itself and the value of the + * value/association. The result is a {@link Set} of {@link ExtractLocationParameter} which + * contains the computed {@link Term}s. + *

+ *

+ * Objects which are created in the heap during symbolic execution and all objects which are + * used on the right side of associations are also collected and stored in the {@link Set}s + * {@code updateCreatedObjectsToFill}/ {@code updateValueObjectsToFill}. + *

+ * + * @param term The {@link Term} which provides the heap update to extract locations from. + * @param locationsToFill The location {@link Set} to fill. + * @param updateCreatedObjectsToFill The new created object {@link Set} to fill. + * @param updateValueObjectsToFill The {@link Set} with objects used on right side of updates to + * fill. + * @throws ProofInputException Occurred Exception. + */ + protected void collectLocationsFromHeapUpdate(Term term, + Set locationsToFill, Set updateCreatedObjectsToFill, + Set updateValueObjectsToFill) throws ProofInputException { + final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); + if (term.op() == heapLDT.getStore()) { + // Add select object term to result + Term selectArgument = term.sub(1); + if (heapLDT.getSortOfSelect(selectArgument.op()) != null) { + ProgramVariable var = SymbolicExecutionUtil.getProgramVariable(getServices(), + heapLDT, selectArgument.sub(2)); + if (var != null) { + if (!isImplicitProgramVariable(var) + && !hasFreeVariables(selectArgument.sub(2))) { + locationsToFill + .add(new ExtractLocationParameter(var, selectArgument.sub(1))); + } + } else { + Term arrayIndex = SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, + selectArgument.sub(2)); + if (arrayIndex != null) { + if (!hasFreeVariables(arrayIndex)) { + locationsToFill.add(new ExtractLocationParameter(arrayIndex, + selectArgument.sub(1))); + } + } else { + throw new ProofInputException( + "Unsupported select statement \"" + term + "\"."); + } + } + } else if (selectArgument.op() instanceof IProgramVariable) { + ProgramVariable var = (ProgramVariable) selectArgument.op(); + if (!isImplicitProgramVariable(var) && !hasFreeVariables(selectArgument)) { + locationsToFill.add(new ExtractLocationParameter(var, false)); + } + } else if (heapLDT.getNull() == selectArgument.op()) { + // Static fields have a null term as select argument. + } else { + for (int i = 0; i < selectArgument.arity(); i++) { + collectLocationsFromHeapUpdate(selectArgument.sub(i), locationsToFill, + updateCreatedObjectsToFill, updateValueObjectsToFill); + } + } + // Add select value term to result + ProgramVariable var = + SymbolicExecutionUtil.getProgramVariable(getServices(), heapLDT, term.sub(2)); + if (var != null) { + if (!isImplicitProgramVariable(var) && !hasFreeVariables(term.sub(2))) { + if (var.isStatic()) { + locationsToFill.add(new ExtractLocationParameter(var, true)); + } else { + locationsToFill.add(new ExtractLocationParameter(var, term.sub(1))); + } + } + } else { + Term arrayIndex = + SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, term.sub(2)); + if (arrayIndex != null && !hasFreeVariables(arrayIndex)) { + locationsToFill.add(new ExtractLocationParameter(arrayIndex, term.sub(1))); + } else { + throw new ProofInputException("Unsupported select statement \"" + term + "\"."); + } + } + if (SymbolicExecutionUtil.hasReferenceSort(getServices(), term.sub(3)) + && term.sub(3).op() instanceof ProgramVariable) { + Term objectTerm = term.sub(3); + objectTerm = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), + objectTerm, getServices()); + updateValueObjectsToFill + .add(OriginTermLabel.removeOriginLabels(objectTerm, getServices())); } - } - else { - for (Term sub : term.subs()) { - collectLocationsFromTerm(toFill, sub, objectsToIgnore); + // Iterate over child heap modifications + collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, + updateValueObjectsToFill); + } else if (term.op() == heapLDT.getCreate()) { + Term newObject = term.sub(1); + newObject = SymbolicExecutionUtil.replaceSkolemConstants(node.sequent(), newObject, + getServices()); + updateCreatedObjectsToFill + .add(OriginTermLabel.removeOriginLabels(newObject, getServices())); + // Iterate over child heap modifications + collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, + updateValueObjectsToFill); + } else if (term.op() == heapLDT.getHeap()) { + // Initial Heap, nothing to do + } else if (term.op() == heapLDT.getMemset()) { + // Check modified array range. + Term arrayRange = term.sub(1); + if (arrayRange.op() == getServices().getTypeConverter().getLocSetLDT() + .getArrayRange()) { + Term array = arrayRange.sub(0); + Term startIndex = arrayRange.sub(1); + Term endIndex = arrayRange.sub(2); + locationsToFill.add(new ExtractLocationParameter(startIndex, endIndex, array)); } - } - } - } - - /** - * Collects the {@link ExtractLocationParameter} location from the heap {@link Term}s. - * @param selectTerm The parent {@link Term}. - * @param variableTerm The {@link Term} with the {@link ProgramVariable}. - * @param heapLDT The {@link HeapLDT} to use. - * @param toFill The result {@link Set} to fill. - * @param objectsToIgnore The objects to ignore. - * @throws ProofInputException Occurred Exception. - */ - protected void collectLocationsFromHeapTerms(Term selectTerm, - Term variableTerm, - HeapLDT heapLDT, - Set toFill, - Set objectsToIgnore) throws ProofInputException { - if (!objectsToIgnore.contains(selectTerm) && - !SymbolicExecutionUtil.isSkolemConstant(selectTerm)) { - ProgramVariable var = SymbolicExecutionUtil.getProgramVariable(getServices(), heapLDT, variableTerm); - if (var != null) { - if (!isImplicitProgramVariable(var) && - !hasFreeVariables(variableTerm)) { - if (var.isStatic()) { - toFill.add(new ExtractLocationParameter(var, true)); - } - else { + // Iterate over child heap modifications + collectLocationsFromHeapUpdate(term.sub(0), locationsToFill, updateCreatedObjectsToFill, + updateValueObjectsToFill); + } else { + for (int i = 0; i < term.arity(); i++) { + collectLocationsFromHeapUpdate(term.sub(i), locationsToFill, + updateCreatedObjectsToFill, updateValueObjectsToFill); + } + } + } + + /** + * Checks if the given {@link Term} has free variables. + * + * @param term The {@link Term} to check. + * @return {@code true} has free variables, {@code false} does not have free variables. + */ + protected boolean hasFreeVariables(Term term) { + return term != null && !term.freeVars().isEmpty(); + } + + /** + * Computes for each location (value/association of an object) used in the given {@link Sequent} + * the {@link Term}s which allows to compute the object itself and the value of the + * value/association. The result is a {@link Set} of {@link ExtractLocationParameter} which + * contains the computed {@link Term}s. + * + * @param sequent The {@link Sequent} to extract locations from. + * @param objectsToIgnore The objects to ignore. + * @return The found locations. + * @throws ProofInputException Occurred Exception. + */ + protected Set extractLocationsFromSequent(Sequent sequent, + Set objectsToIgnore) throws ProofInputException { + Set result = new LinkedHashSet(); + for (SequentFormula sf : sequent) { + result.addAll(extractLocationsFromTerm( + OriginTermLabel.removeOriginLabels(sf.formula(), getServices()), + objectsToIgnore)); + } + return result; + } + + /** + * Computes for each location (value/association of an object) used in the given {@link Term} + * the {@link Term}s which allows to compute the object itself and the value of the + * value/association. The result is a {@link Set} of {@link ExtractLocationParameter} which + * contains the computed {@link Term}s. + * + * @param term The {@link Term} to extract locations from. + * @param objectsToIgnore The objects to ignore. + * @return The found locations. + * @throws ProofInputException Occurred Exception. + */ + protected Set extractLocationsFromTerm(Term term, + Set objectsToIgnore) throws ProofInputException { + Set result = new LinkedHashSet(); + collectLocationsFromTerm(result, term, objectsToIgnore); + return result; + } + + /** + * Utility method of {@link #extractLocationsFromTerm(Term, Set)} which recursively extracts the + * locations. + * + * @param toFill The result {@link Set} to fill. + * @param term The current {@link Term}. + * @param objectsToIgnore The objects to ignore. + * @throws ProofInputException Occurred Exception. + */ + protected void collectLocationsFromTerm(Set toFill, Term term, + Set objectsToIgnore) throws ProofInputException { + term = OriginTermLabel.removeOriginLabels(term, getServices()); + final HeapLDT heapLDT = getServices().getTypeConverter().getHeapLDT(); + if (term.op() instanceof ProgramVariable) { + ProgramVariable var = (ProgramVariable) term.op(); + if (!SymbolicExecutionUtil.isHeap(var, heapLDT) && !isImplicitProgramVariable(var) + && !objectsToIgnore.contains(term) && !hasFreeVariables(term)) { + toFill.add(new ExtractLocationParameter(var, true)); + } + } else { + Sort sort = heapLDT.getSortOfSelect(term.op()); + if (sort != null) { + collectLocationsFromHeapTerms(term.sub(1), term.sub(2), heapLDT, toFill, + objectsToIgnore); + } else if (heapLDT.getStore() == term.op()) { + collectLocationsFromHeapTerms(term.sub(1), term.sub(2), heapLDT, toFill, + objectsToIgnore); + } else if (heapLDT.getLength() == term.op()) { + if (!objectsToIgnore.contains(term.sub(0)) && !hasFreeVariables(term)) { + ProgramVariable var = getServices().getJavaInfo().getArrayLength(); + toFill.add(new ExtractLocationParameter(var, term.sub(0))); + } + } else { + for (Term sub : term.subs()) { + collectLocationsFromTerm(toFill, sub, objectsToIgnore); + } + } + } + } + + /** + * Collects the {@link ExtractLocationParameter} location from the heap {@link Term}s. + * + * @param selectTerm The parent {@link Term}. + * @param variableTerm The {@link Term} with the {@link ProgramVariable}. + * @param heapLDT The {@link HeapLDT} to use. + * @param toFill The result {@link Set} to fill. + * @param objectsToIgnore The objects to ignore. + * @throws ProofInputException Occurred Exception. + */ + protected void collectLocationsFromHeapTerms(Term selectTerm, Term variableTerm, + HeapLDT heapLDT, Set toFill, Set objectsToIgnore) + throws ProofInputException { + if (!objectsToIgnore.contains(selectTerm) + && !SymbolicExecutionUtil.isSkolemConstant(selectTerm)) { + ProgramVariable var = + SymbolicExecutionUtil.getProgramVariable(getServices(), heapLDT, variableTerm); + if (var != null) { + if (!isImplicitProgramVariable(var) && !hasFreeVariables(variableTerm)) { + if (var.isStatic()) { + toFill.add(new ExtractLocationParameter(var, true)); + } else { + if (selectTerm.op() instanceof ProgramVariable) { + toFill.add(new ExtractLocationParameter( + (ProgramVariable) selectTerm.op(), true)); + } + toFill.add(new ExtractLocationParameter(var, selectTerm)); + } + } + } else { + Term arrayIndex = + SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, variableTerm); + if (arrayIndex != null && !hasFreeVariables(arrayIndex)) { if (selectTerm.op() instanceof ProgramVariable) { - toFill.add(new ExtractLocationParameter((ProgramVariable)selectTerm.op(), true)); + toFill.add(new ExtractLocationParameter((ProgramVariable) selectTerm.op(), + true)); } - toFill.add(new ExtractLocationParameter(var, selectTerm)); - } - } - } - else { - Term arrayIndex = SymbolicExecutionUtil.getArrayIndex(getServices(), heapLDT, variableTerm); - if (arrayIndex != null && !hasFreeVariables(arrayIndex)) { - if (selectTerm.op() instanceof ProgramVariable) { - toFill.add(new ExtractLocationParameter((ProgramVariable)selectTerm.op(), true)); - } - toFill.add(new ExtractLocationParameter(arrayIndex, selectTerm)); - } - else { - // Nothing to do, since program variable and array index is undefined. - } - } - } - } - - /** - * Creates a predicate and a {@link Term} which can be used to compute the - * values defined by the given {@link ExtractLocationParameter}s. - * @param valueSelectParameter The {@link ExtractLocationParameter}s to compute in the created {@link Term}. - * @return The created {@link Term} which computes the values of the given {@link ExtractLocationParameter}s. - */ - protected Term createLocationPredicateAndTerm(Set valueSelectParameter) { - List argumentsList = new LinkedList(); - int argumentIndex = -1; - for (ExtractLocationParameter param : valueSelectParameter) { - argumentsList.add(param.createPreParentTerm()); - param.setParentTermIndexInStatePredicate(++argumentIndex); - argumentsList.add(param.createPreValueTerm()); - param.setValueTermIndexInStatePredicate(++argumentIndex); - } - Term[] arguments = argumentsList.toArray(new Term[argumentsList.size()]); - Sort[] sorts = new Sort[arguments.length]; - for (int i = 0; i < sorts.length; i++) { - sorts[i] = arguments[i].sort(); - } - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(getServices().getTermBuilder().newName("LayoutPredicate")), Sort.FORMULA, sorts); - // Create formula which contains the value interested in. - Term newTerm = getServices().getTermBuilder().func(newPredicate, arguments); - return newTerm; - } - - /** - * Returns the {@link Proof} of the analyzed {@link Node}. - * @return The {@link Proof} of the analyzed {@link Node}. - */ - protected Proof getProof() { - return node.proof(); - } - - /** - * Returns the root {@link Node} of the proof. - * @return The root {@link Node} of the proof. - */ - protected Node getRoot() { - return getProof().root(); - } - - /** - * Returns the {@link Services} of the analyzed {@link Node}. - * @return The {@link Services} of the analyzed {@link Node}. - */ - protected Services getServices() { - return getProof().getServices(); - } - - /** - *

- * Instances of this class provides the {@link Term} which are required - * to compute a location (value or association of a given object/state). - *

- *

- * Instances of this class can be used to compute the values in each memory layout. - * So they are instantiated during the analyzation phase - * {@link SymbolicLayoutExtractor#analyse()} once for initial and current memory layout. - *

- * @author Martin Hentschel - */ - public class ExtractLocationParameter { - /** - * The {@link ProgramVariable} or {@code null} if an array index is used instead. - */ - private final ProgramVariable programVariable; - - /** - * The array index or {@code null} if not used. - */ - private final Term arrayIndex; - - /** - * The array start index or {@code null} if not used. - */ - private final Term arrayStartIndex; - - /** - * The array end index or {@code null} if not used. - */ - private final Term arrayEndIndex; - - /** - * An optional parent object represented as {@link Term}. If it is {@code null} an {@link IProgramVariable} of the state is represented. - */ - private final Term parentTerm; - - /** - * The index of the parent argument in the predicate used in side proof to compute the values. - */ - private int parentTermIndexInStatePredicate; - - /** - * The index of the value argument in the predicate used in side proof to compute the values. - */ - private int valueTermIndexInStatePredicate; - - /** - * The {@link LocationVariable} which is used to make sure that the defined parent object - * of the initial state is used, because the expression (e.g. {@code x.next}) might refer - * to different objects in the current state. - */ - private final LocationVariable preVariable; - - /** - * Defines if this location should explicitly be shown on the state. - */ - private final boolean stateMember; - - /** - * The constant used to query an array range. - */ - private final Term arrayRangeConstant; - - /** - * The constant representing the fact that no value is available. - */ - private final Term notAValue; - - /** - * Constructor for cloning purpose. - * @param original The original {@link ExtractLocationParameter} to clone. - * @param newParent The new parent {@link Term} to be used instead of the original one. - */ - public ExtractLocationParameter(ExtractLocationParameter original, Term newParent) { - this.programVariable = original.programVariable; - this.arrayIndex = original.arrayIndex; - this.parentTerm = OriginTermLabel.removeOriginLabels(newParent, getServices()); - this.parentTermIndexInStatePredicate = original.parentTermIndexInStatePredicate; - this.valueTermIndexInStatePredicate = original.valueTermIndexInStatePredicate; - this.preVariable = original.preVariable; - this.stateMember = original.stateMember; - this.arrayStartIndex = original.arrayStartIndex; - this.arrayEndIndex = original.arrayEndIndex; - this.arrayRangeConstant = original.arrayRangeConstant; - this.notAValue = original.notAValue; - } - - /** - * Constructor. - * @param programVariable The {@link ProgramVariable}. - * @param stateMember Defines if this location should explicitly be shown on the state. - * @throws ProofInputException Occurred Exception. - */ - public ExtractLocationParameter(ProgramVariable programVariable, - boolean stateMember) throws ProofInputException { - this(programVariable, null, stateMember); - } - - /** - * Constructor. - * @param programVariable The {@link ProgramVariable}. - * @param parentTerm The parent object represented as {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public ExtractLocationParameter(ProgramVariable programVariable, - Term parentTerm) throws ProofInputException { - this(programVariable, parentTerm, false); - } - - /** - * Constructor. - * @param programVariable The {@link ProgramVariable}. - * @param parentTerm The parent object represented as {@link Term}. - * @param stateMember Defines if this location should explicitly be shown on the state. - * @throws ProofInputException Occurred Exception. - */ - protected ExtractLocationParameter(ProgramVariable programVariable, - Term parentTerm, - boolean stateMember) throws ProofInputException { - assert programVariable != null; - this.programVariable = programVariable; - this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); - this.preVariable = createLocationVariable("Pre" + preVariableIndex++, parentTerm != null ? parentTerm.sort() : programVariable.sort()); - this.arrayIndex = null; - this.stateMember = stateMember; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - this.arrayRangeConstant = null; - this.notAValue = null; - } - - /** - * Constructor. - * @param arrayIndex The array index. - * @param parentTerm The parent object represented as {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public ExtractLocationParameter(Term arrayIndex, - Term parentTerm) throws ProofInputException { - assert parentTerm != null; - this.programVariable = null; - this.arrayIndex = OriginTermLabel.removeOriginLabels(arrayIndex, getServices()); - this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); - this.preVariable = createLocationVariable("Pre" + preVariableIndex++, parentTerm.sort()); - this.stateMember = false; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - this.arrayRangeConstant = null; - this.notAValue = null; - } - - /** - * Constructor. - * @param arrayStartIndex The array start index. - * @param arrayEndIndex The array end index. - * @param parentTerm The parent object represented as {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public ExtractLocationParameter(Term arrayStartIndex, - Term arrayEndIndex, - Term parentTerm) throws ProofInputException { - assert arrayStartIndex != null; - assert arrayEndIndex != null; - assert parentTerm != null; - this.programVariable = null; - this.arrayIndex = null; - this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); - this.preVariable = createLocationVariable("Pre" + preVariableIndex++, parentTerm.sort()); - this.stateMember = false; - this.arrayStartIndex = OriginTermLabel.removeOriginLabels(arrayStartIndex, getServices()); - this.arrayEndIndex = OriginTermLabel.removeOriginLabels(arrayEndIndex, getServices()); - TermBuilder tb = getServices().getTermBuilder(); - Function constantFunction = new Function(new Name(tb.newName(ExecutionAllArrayIndicesVariable.ARRAY_INDEX_CONSTANT_NAME)), getServices().getTypeConverter().getIntegerLDT().targetSort()); - this.arrayRangeConstant = tb.func(constantFunction); - Function notAValueFunction = new Function(new Name(tb.newName(ExecutionAllArrayIndicesVariable.NOT_A_VALUE_NAME)), Sort.ANY); - this.notAValue = tb.func(notAValueFunction); - } - - /** - * Creates a new {@link LocationVariable} with the given name and {@link Sort}. - * @param name The name of the new variable. - * @param sort The {@link Sort} of the new variable. - * @return The created {@link LocationVariable}. - * @throws ProofInputException Occurred Exception. - */ - protected LocationVariable createLocationVariable(String name, Sort sort) throws ProofInputException { - return new LocationVariable(new ProgramElementName(name), sort); - } - - /** - * Checks if this location should explicitly be shown on the state. - * @return Show location on state? - */ - public boolean isStateMember() { - return stateMember; - } - - /** - * Checks if an array index is represented. - * @return {@code true} is array index, {@code false} is something else. - */ - public boolean isArrayIndex() { - return arrayIndex != null; - } - - /** - * Checks if an array range is represented. - * @return {@code true} is array range, {@code false} is something else. - */ - public boolean isArrayRange() { - return arrayStartIndex != null && arrayEndIndex != null; - } - - /** - * Returns the array index. - * @return The array index. - */ - public Term getArrayIndex() { - return arrayIndex; - } - - /** - * Returns the array start index. - * @return The array start index. - */ - public Term getArrayStartIndex() { - return arrayStartIndex; - } - - /** - * Returns the array end index. - * @return The array end index. - */ - public Term getArrayEndIndex() { - return arrayEndIndex; - } - - /** - * Returns the constant used to query an array range. - * @return The constant used to query an array range. - */ - public Term getArrayRangeConstant() { - return arrayRangeConstant; - } - - /** - * Returns the constant representing the fact that no value is available. - * @return The constant representing the fact that no value is available. - */ - public Term getNotAValue() { - return notAValue; - } - - /** - * Returns the pre variable. - * @return The pre variable. - */ - public LocationVariable getPreVariable() { - return preVariable; - } - - /** - * Returns the right side of the update created by {@link #createPreUpdate()}. - * @return The right side of the update created by {@link #createPreUpdate()}. - */ - public Term getPreUpdateTarget() { - return parentTerm != null ? parentTerm : getServices().getTermBuilder().var(programVariable); - } - - /** - * Creates the pre update to make sure that the parent object defined - * by the expression is evaluated on the initial state because it might - * be changed in the current state due to updates. - * @return The created {@link Term} with the pre update. - */ - public Term createPreUpdate() { - Term originalTerm = getPreUpdateTarget(); - return getServices().getTermBuilder().elementary(preVariable, originalTerm); - } - - /** - * Creates the {@link Term} to compute the parent object with help of the pre update. - * @return The {@link Term} to compute the parent object with help of the pre update. - */ - public Term createPreParentTerm() { - return getServices().getTermBuilder().var(preVariable); - } - - /** - * Computes the {@link Term} to compute the value with help of the pre update. - * @return The {@link Term} to compute the value with help of the pre update. - */ - public Term createPreValueTerm() { - final TermBuilder tb = getServices().getTermBuilder(); - if (parentTerm != null) { - if (isArrayRange()) { - Term arrayRange = tb.and(tb.geq(arrayRangeConstant, arrayStartIndex), - tb.leq(arrayRangeConstant, arrayEndIndex)); - return tb.ife(arrayRange, tb.dotArr(parentTerm, arrayRangeConstant), notAValue); + toFill.add(new ExtractLocationParameter(arrayIndex, selectTerm)); + } else { + // Nothing to do, since program variable and array index is undefined. + } } - else if (isArrayIndex()) { - return tb.dotArr(parentTerm, arrayIndex); - } - else { - if (getServices().getJavaInfo().getArrayLength() == programVariable) { - // Special handling for length attribute of arrays - Function function = getServices().getTypeConverter().getHeapLDT().getLength(); - return tb.func(function, createPreParentTerm()); - } - else { - Function function = getServices().getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)programVariable, getServices()); - return tb.dot(programVariable.sort(), createPreParentTerm(), function); - } + } + } + + /** + * Creates a predicate and a {@link Term} which can be used to compute the values defined by the + * given {@link ExtractLocationParameter}s. + * + * @param valueSelectParameter The {@link ExtractLocationParameter}s to compute in the created + * {@link Term}. + * @return The created {@link Term} which computes the values of the given + * {@link ExtractLocationParameter}s. + */ + protected Term createLocationPredicateAndTerm( + Set valueSelectParameter) { + List argumentsList = new LinkedList(); + int argumentIndex = -1; + for (ExtractLocationParameter param : valueSelectParameter) { + argumentsList.add(param.createPreParentTerm()); + param.setParentTermIndexInStatePredicate(++argumentIndex); + argumentsList.add(param.createPreValueTerm()); + param.setValueTermIndexInStatePredicate(++argumentIndex); + } + Term[] arguments = argumentsList.toArray(new Term[argumentsList.size()]); + Sort[] sorts = new Sort[arguments.length]; + for (int i = 0; i < sorts.length; i++) { + sorts[i] = arguments[i].sort(); + } + // Create predicate which will be used in formulas to store the value interested in. + Function newPredicate = + new Function(new Name(getServices().getTermBuilder().newName("LayoutPredicate")), + Sort.FORMULA, sorts); + // Create formula which contains the value interested in. + Term newTerm = getServices().getTermBuilder().func(newPredicate, arguments); + return newTerm; + } + + /** + * Returns the {@link Proof} of the analyzed {@link Node}. + * + * @return The {@link Proof} of the analyzed {@link Node}. + */ + protected Proof getProof() { + return node.proof(); + } + + /** + * Returns the root {@link Node} of the proof. + * + * @return The root {@link Node} of the proof. + */ + protected Node getRoot() { + return getProof().root(); + } + + /** + * Returns the {@link Services} of the analyzed {@link Node}. + * + * @return The {@link Services} of the analyzed {@link Node}. + */ + protected Services getServices() { + return getProof().getServices(); + } + + /** + *

+ * Instances of this class provides the {@link Term} which are required to compute a location + * (value or association of a given object/state). + *

+ *

+ * Instances of this class can be used to compute the values in each memory layout. So they are + * instantiated during the analyzation phase {@link SymbolicLayoutExtractor#analyse()} once for + * initial and current memory layout. + *

+ * + * @author Martin Hentschel + */ + public class ExtractLocationParameter { + /** + * The {@link ProgramVariable} or {@code null} if an array index is used instead. + */ + private final ProgramVariable programVariable; + + /** + * The array index or {@code null} if not used. + */ + private final Term arrayIndex; + + /** + * The array start index or {@code null} if not used. + */ + private final Term arrayStartIndex; + + /** + * The array end index or {@code null} if not used. + */ + private final Term arrayEndIndex; + + /** + * An optional parent object represented as {@link Term}. If it is {@code null} an + * {@link IProgramVariable} of the state is represented. + */ + private final Term parentTerm; + + /** + * The index of the parent argument in the predicate used in side proof to compute the + * values. + */ + private int parentTermIndexInStatePredicate; + + /** + * The index of the value argument in the predicate used in side proof to compute the + * values. + */ + private int valueTermIndexInStatePredicate; + + /** + * The {@link LocationVariable} which is used to make sure that the defined parent object of + * the initial state is used, because the expression (e.g. {@code x.next}) might refer to + * different objects in the current state. + */ + private final LocationVariable preVariable; + + /** + * Defines if this location should explicitly be shown on the state. + */ + private final boolean stateMember; + + /** + * The constant used to query an array range. + */ + private final Term arrayRangeConstant; + + /** + * The constant representing the fact that no value is available. + */ + private final Term notAValue; + + /** + * Constructor for cloning purpose. + * + * @param original The original {@link ExtractLocationParameter} to clone. + * @param newParent The new parent {@link Term} to be used instead of the original one. + */ + public ExtractLocationParameter(ExtractLocationParameter original, Term newParent) { + this.programVariable = original.programVariable; + this.arrayIndex = original.arrayIndex; + this.parentTerm = OriginTermLabel.removeOriginLabels(newParent, getServices()); + this.parentTermIndexInStatePredicate = original.parentTermIndexInStatePredicate; + this.valueTermIndexInStatePredicate = original.valueTermIndexInStatePredicate; + this.preVariable = original.preVariable; + this.stateMember = original.stateMember; + this.arrayStartIndex = original.arrayStartIndex; + this.arrayEndIndex = original.arrayEndIndex; + this.arrayRangeConstant = original.arrayRangeConstant; + this.notAValue = original.notAValue; + } + + /** + * Constructor. + * + * @param programVariable The {@link ProgramVariable}. + * @param stateMember Defines if this location should explicitly be shown on the state. + * @throws ProofInputException Occurred Exception. + */ + public ExtractLocationParameter(ProgramVariable programVariable, boolean stateMember) + throws ProofInputException { + this(programVariable, null, stateMember); + } + + /** + * Constructor. + * + * @param programVariable The {@link ProgramVariable}. + * @param parentTerm The parent object represented as {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public ExtractLocationParameter(ProgramVariable programVariable, Term parentTerm) + throws ProofInputException { + this(programVariable, parentTerm, false); + } + + /** + * Constructor. + * + * @param programVariable The {@link ProgramVariable}. + * @param parentTerm The parent object represented as {@link Term}. + * @param stateMember Defines if this location should explicitly be shown on the state. + * @throws ProofInputException Occurred Exception. + */ + protected ExtractLocationParameter(ProgramVariable programVariable, Term parentTerm, + boolean stateMember) throws ProofInputException { + assert programVariable != null; + this.programVariable = programVariable; + this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); + this.preVariable = createLocationVariable("Pre" + preVariableIndex++, + parentTerm != null ? parentTerm.sort() : programVariable.sort()); + this.arrayIndex = null; + this.stateMember = stateMember; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + this.arrayRangeConstant = null; + this.notAValue = null; + } + + /** + * Constructor. + * + * @param arrayIndex The array index. + * @param parentTerm The parent object represented as {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public ExtractLocationParameter(Term arrayIndex, Term parentTerm) + throws ProofInputException { + assert parentTerm != null; + this.programVariable = null; + this.arrayIndex = OriginTermLabel.removeOriginLabels(arrayIndex, getServices()); + this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); + this.preVariable = + createLocationVariable("Pre" + preVariableIndex++, parentTerm.sort()); + this.stateMember = false; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + this.arrayRangeConstant = null; + this.notAValue = null; + } + + /** + * Constructor. + * + * @param arrayStartIndex The array start index. + * @param arrayEndIndex The array end index. + * @param parentTerm The parent object represented as {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public ExtractLocationParameter(Term arrayStartIndex, Term arrayEndIndex, Term parentTerm) + throws ProofInputException { + assert arrayStartIndex != null; + assert arrayEndIndex != null; + assert parentTerm != null; + this.programVariable = null; + this.arrayIndex = null; + this.parentTerm = OriginTermLabel.removeOriginLabels(parentTerm, getServices()); + this.preVariable = + createLocationVariable("Pre" + preVariableIndex++, parentTerm.sort()); + this.stateMember = false; + this.arrayStartIndex = + OriginTermLabel.removeOriginLabels(arrayStartIndex, getServices()); + this.arrayEndIndex = OriginTermLabel.removeOriginLabels(arrayEndIndex, getServices()); + TermBuilder tb = getServices().getTermBuilder(); + Function constantFunction = new Function( + new Name( + tb.newName(ExecutionAllArrayIndicesVariable.ARRAY_INDEX_CONSTANT_NAME)), + getServices().getTypeConverter().getIntegerLDT().targetSort()); + this.arrayRangeConstant = tb.func(constantFunction); + Function notAValueFunction = new Function( + new Name(tb.newName(ExecutionAllArrayIndicesVariable.NOT_A_VALUE_NAME)), + Sort.ANY); + this.notAValue = tb.func(notAValueFunction); + } + + /** + * Creates a new {@link LocationVariable} with the given name and {@link Sort}. + * + * @param name The name of the new variable. + * @param sort The {@link Sort} of the new variable. + * @return The created {@link LocationVariable}. + * @throws ProofInputException Occurred Exception. + */ + protected LocationVariable createLocationVariable(String name, Sort sort) + throws ProofInputException { + return new LocationVariable(new ProgramElementName(name), sort); + } + + /** + * Checks if this location should explicitly be shown on the state. + * + * @return Show location on state? + */ + public boolean isStateMember() { + return stateMember; + } + + /** + * Checks if an array index is represented. + * + * @return {@code true} is array index, {@code false} is something else. + */ + public boolean isArrayIndex() { + return arrayIndex != null; + } + + /** + * Checks if an array range is represented. + * + * @return {@code true} is array range, {@code false} is something else. + */ + public boolean isArrayRange() { + return arrayStartIndex != null && arrayEndIndex != null; + } + + /** + * Returns the array index. + * + * @return The array index. + */ + public Term getArrayIndex() { + return arrayIndex; + } + + /** + * Returns the array start index. + * + * @return The array start index. + */ + public Term getArrayStartIndex() { + return arrayStartIndex; + } + + /** + * Returns the array end index. + * + * @return The array end index. + */ + public Term getArrayEndIndex() { + return arrayEndIndex; + } + + /** + * Returns the constant used to query an array range. + * + * @return The constant used to query an array range. + */ + public Term getArrayRangeConstant() { + return arrayRangeConstant; + } + + /** + * Returns the constant representing the fact that no value is available. + * + * @return The constant representing the fact that no value is available. + */ + public Term getNotAValue() { + return notAValue; + } + + /** + * Returns the pre variable. + * + * @return The pre variable. + */ + public LocationVariable getPreVariable() { + return preVariable; + } + + /** + * Returns the right side of the update created by {@link #createPreUpdate()}. + * + * @return The right side of the update created by {@link #createPreUpdate()}. + */ + public Term getPreUpdateTarget() { + return parentTerm != null ? parentTerm + : getServices().getTermBuilder().var(programVariable); + } + + /** + * Creates the pre update to make sure that the parent object defined by the expression is + * evaluated on the initial state because it might be changed in the current state due to + * updates. + * + * @return The created {@link Term} with the pre update. + */ + public Term createPreUpdate() { + Term originalTerm = getPreUpdateTarget(); + return getServices().getTermBuilder().elementary(preVariable, originalTerm); + } + + /** + * Creates the {@link Term} to compute the parent object with help of the pre update. + * + * @return The {@link Term} to compute the parent object with help of the pre update. + */ + public Term createPreParentTerm() { + return getServices().getTermBuilder().var(preVariable); + } + + /** + * Computes the {@link Term} to compute the value with help of the pre update. + * + * @return The {@link Term} to compute the value with help of the pre update. + */ + public Term createPreValueTerm() { + final TermBuilder tb = getServices().getTermBuilder(); + if (parentTerm != null) { + if (isArrayRange()) { + Term arrayRange = tb.and(tb.geq(arrayRangeConstant, arrayStartIndex), + tb.leq(arrayRangeConstant, arrayEndIndex)); + return tb.ife(arrayRange, tb.dotArr(parentTerm, arrayRangeConstant), notAValue); + } else if (isArrayIndex()) { + return tb.dotArr(parentTerm, arrayIndex); + } else { + if (getServices().getJavaInfo().getArrayLength() == programVariable) { + // Special handling for length attribute of arrays + Function function = + getServices().getTypeConverter().getHeapLDT().getLength(); + return tb.func(function, createPreParentTerm()); + } else { + Function function = + getServices().getTypeConverter().getHeapLDT().getFieldSymbolForPV( + (LocationVariable) programVariable, getServices()); + return tb.dot(programVariable.sort(), createPreParentTerm(), function); + } + } + } else { + if (programVariable.isStatic()) { + Function function = getServices().getTypeConverter().getHeapLDT() + .getFieldSymbolForPV((LocationVariable) programVariable, getServices()); + return tb.staticDot(programVariable.sort(), function); + } else { + return tb.var(programVariable); + } } - } - else { - if (programVariable.isStatic()) { - Function function = getServices().getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)programVariable, getServices()); - return tb.staticDot(programVariable.sort(), function); + } + + /** + * Returns the {@link ProgramVariable} or {@code null} if an array index is used instead. + * + * @return The {@link ProgramVariable} or {@code null} if an array index is used instead. + */ + public ProgramVariable getProgramVariable() { + return programVariable; + } + + /** + * Returns the optional parent object represented as {@link Term}. If it is {@code null} an + * {@link IProgramVariable} of the state is represented. + * + * @return The optional parent object represented as {@link Term}. If it is {@code null} an + * {@link IProgramVariable} of the state is represented. + */ + public Term getParentTerm() { + return parentTerm; + } + + /** + * Returns the index of the parent argument in the predicate used in side proof to compute + * the values. + * + * @return The index of the parent argument in the predicate used in side proof to compute + * the values. + */ + public int getParentTermIndexInStatePredicate() { + return parentTermIndexInStatePredicate; + } + + /** + * Sets the index of the parent argument in the predicate used in side proof to compute the + * values. + * + * @param selectParentTermIndexInStatePredicate The index of the parent argument in the + * predicate used in side proof to compute the values. + */ + public void setParentTermIndexInStatePredicate(int selectParentTermIndexInStatePredicate) { + this.parentTermIndexInStatePredicate = selectParentTermIndexInStatePredicate; + } + + /** + * Returns the index of the value argument in the predicate used in side proof to compute + * the values. + * + * @return The index of the value argument in the predicate used in side proof to compute + * the values. + */ + public int getValueTermIndexInStatePredicate() { + return valueTermIndexInStatePredicate; + } + + /** + * Sets the index of the value argument in the predicate used in side proof to compute the + * values. + * + * @param selectValueTermIndexInStatePredicate The index of the value argument in the + * predicate used in side proof to compute the values. + */ + public void setValueTermIndexInStatePredicate(int selectValueTermIndexInStatePredicate) { + this.valueTermIndexInStatePredicate = selectValueTermIndexInStatePredicate; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + if (isArrayRange()) { + return "[" + arrayStartIndex + " to " + arrayEndIndex + "] " + + (parentTerm != null ? " of " + parentTerm : ""); + } else if (isArrayIndex()) { + return "[" + arrayIndex + "] " + (parentTerm != null ? " of " + parentTerm : ""); + } else { + return programVariable + (parentTerm != null ? " of " + parentTerm : ""); } - else { - return tb.var(programVariable); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ExtractLocationParameter) { + ExtractLocationParameter other = (ExtractLocationParameter) obj; + return ObjectUtil.equals(arrayIndex, other.arrayIndex) + && stateMember == other.stateMember + && ObjectUtil.equals(parentTerm, other.parentTerm) + && ObjectUtil.equals(programVariable, other.programVariable); + } else { + return false; } - } - } - - /** - * Returns the {@link ProgramVariable} or {@code null} if an array index is used instead. - * @return The {@link ProgramVariable} or {@code null} if an array index is used instead. - */ - public ProgramVariable getProgramVariable() { - return programVariable; - } - - /** - * Returns the optional parent object represented as {@link Term}. If it is {@code null} an {@link IProgramVariable} of the state is represented. - * @return The optional parent object represented as {@link Term}. If it is {@code null} an {@link IProgramVariable} of the state is represented. - */ - public Term getParentTerm() { - return parentTerm; - } - - /** - * Returns the index of the parent argument in the predicate used in side proof to compute the values. - * @return The index of the parent argument in the predicate used in side proof to compute the values. - */ - public int getParentTermIndexInStatePredicate() { - return parentTermIndexInStatePredicate; - } - - /** - * Sets the index of the parent argument in the predicate used in side proof to compute the values. - * @param selectParentTermIndexInStatePredicate The index of the parent argument in the predicate used in side proof to compute the values. - */ - public void setParentTermIndexInStatePredicate(int selectParentTermIndexInStatePredicate) { - this.parentTermIndexInStatePredicate = selectParentTermIndexInStatePredicate; - } - - /** - * Returns the index of the value argument in the predicate used in side proof to compute the values. - * @return The index of the value argument in the predicate used in side proof to compute the values. - */ - public int getValueTermIndexInStatePredicate() { - return valueTermIndexInStatePredicate; - } - - /** - * Sets the index of the value argument in the predicate used in side proof to compute the values. - * @param selectValueTermIndexInStatePredicate The index of the value argument in the predicate used in side proof to compute the values. - */ - public void setValueTermIndexInStatePredicate(int selectValueTermIndexInStatePredicate) { - this.valueTermIndexInStatePredicate = selectValueTermIndexInStatePredicate; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - if (isArrayRange()) { - return "[" + arrayStartIndex + " to " + arrayEndIndex + "] " + (parentTerm != null ? " of " + parentTerm : ""); - } - else if (isArrayIndex()) { - return "[" + arrayIndex + "] " + (parentTerm != null ? " of " + parentTerm : ""); - } - else { - return programVariable + (parentTerm != null ? " of " + parentTerm : ""); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof ExtractLocationParameter) { - ExtractLocationParameter other = (ExtractLocationParameter)obj; - return ObjectUtil.equals(arrayIndex, other.arrayIndex) && - stateMember == other.stateMember && - ObjectUtil.equals(parentTerm, other.parentTerm) && - ObjectUtil.equals(programVariable, other.programVariable); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (arrayIndex != null ? arrayIndex.hashCode() : 0); - result = 31 * result + (stateMember ? 1 : 0); - result = 31 * result + (parentTerm != null ? parentTerm.hashCode() : 0); - result = 31 * result + (programVariable != null ? programVariable.hashCode() : 0); - return result; - } - } - - /** - *

- * The method starts a side proof with the given arguments to compute - * the values and objects of the requested memory layout. The - * {@link ExecutionVariableValuePair} together with the memory layout term - * defines how to access the side proof result. - *

- *

- * The next step is the result extraction from side proof which results - * in a {@link Set} of {@link ExecutionVariableValuePair} instances. Each - * instance defines a value or association of a parent object or the state itself. - *

- * @param layoutCondition An optional condition to consider. - * @param layoutTerm The result term to use in side proof. - * @param locations The locations to compute in side proof. - * @param currentLayout {@code true} current layout, {@code false} initial layout. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The computed {@link ExecutionVariableValuePair}s. - * @throws ProofInputException Occurred Exception. - */ - protected Set computeVariableValuePairs(Term layoutCondition, - Term layoutTerm, - Set locations, - boolean currentLayout, - boolean simplifyConditions) throws ProofInputException { - // Get original updates - ImmutableList originalUpdates = computeOriginalUpdates(modalityPio, currentLayout); - // Combine memory layout with original updates - Map preUpdateMap = new HashMap(); - ImmutableList additionalUpdates = ImmutableSLList.nil(); - for (ExtractLocationParameter evp : locations) { - additionalUpdates = additionalUpdates.append(evp.createPreUpdate()); - preUpdateMap.put(evp.getPreVariable(), evp.getPreUpdateTarget()); - } - // Apply array range conditions - TermBuilder tb = getServices().getTermBuilder(); - // Apply updates - Term updateLayoutTerm = tb.applyParallel(originalUpdates, layoutTerm); - updateLayoutTerm = tb.applyParallel(additionalUpdates, updateLayoutTerm); - for (Term additionalUpdate : collectAdditionalUpdates()) { - updateLayoutTerm = tb.apply(additionalUpdate, updateLayoutTerm); - } - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, modalityPio, layoutCondition, updateLayoutTerm, null, false); - // Instantiate and run proof - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), - sideProofEnv, - sequent, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_NORMAL); - try { - if (!info.getProof().closed()) { - @SuppressWarnings("unchecked") - Map>[] paramValueMap = new Map[locations.size()]; - // Group equal values as precondition of computeValueConditions(...) - for (Goal goal : info.getProof().openGoals()) { - Term resultTerm = SymbolicExecutionSideProofUtil.extractOperatorTerm(goal, layoutTerm.op()); - int i = 0; - for (ExtractLocationParameter param : locations) { - Map> valueMap = paramValueMap[i]; - if (valueMap == null) { - valueMap = new LinkedHashMap>(); - paramValueMap[i] = valueMap; - } - Term value = resultTerm.sub(param.getValueTermIndexInStatePredicate()); - value = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), value, getServices()); - // Replace pre variable with original target - if (value.op() instanceof LocationVariable) { - Term originalTarget = preUpdateMap.get(value.op()); - if (originalTarget != null) { - value = originalTarget; - } - } - else if (SymbolicExecutionUtil.isSelect(goal.proof().getServices(), value)) { - Term object = value.sub(1); - if (object.op() instanceof LocationVariable) { - Term originalTarget = preUpdateMap.get(object.op()); - if (originalTarget != null) { - value = goal.proof().getServices().getTermBuilder().select(value.sort(), value.sub(0), originalTarget, value.sub(2)); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (arrayIndex != null ? arrayIndex.hashCode() : 0); + result = 31 * result + (stateMember ? 1 : 0); + result = 31 * result + (parentTerm != null ? parentTerm.hashCode() : 0); + result = 31 * result + (programVariable != null ? programVariable.hashCode() : 0); + return result; + } + } + + /** + *

+ * The method starts a side proof with the given arguments to compute the values and objects of + * the requested memory layout. The {@link ExecutionVariableValuePair} together with the memory + * layout term defines how to access the side proof result. + *

+ *

+ * The next step is the result extraction from side proof which results in a {@link Set} of + * {@link ExecutionVariableValuePair} instances. Each instance defines a value or association of + * a parent object or the state itself. + *

+ * + * @param layoutCondition An optional condition to consider. + * @param layoutTerm The result term to use in side proof. + * @param locations The locations to compute in side proof. + * @param currentLayout {@code true} current layout, {@code false} initial layout. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The computed {@link ExecutionVariableValuePair}s. + * @throws ProofInputException Occurred Exception. + */ + protected Set computeVariableValuePairs(Term layoutCondition, + Term layoutTerm, Set locations, boolean currentLayout, + boolean simplifyConditions) throws ProofInputException { + // Get original updates + ImmutableList originalUpdates = computeOriginalUpdates(modalityPio, currentLayout); + // Combine memory layout with original updates + Map preUpdateMap = new HashMap(); + ImmutableList additionalUpdates = ImmutableSLList.nil(); + for (ExtractLocationParameter evp : locations) { + additionalUpdates = additionalUpdates.append(evp.createPreUpdate()); + preUpdateMap.put(evp.getPreVariable(), evp.getPreUpdateTarget()); + } + // Apply array range conditions + TermBuilder tb = getServices().getTermBuilder(); + // Apply updates + Term updateLayoutTerm = tb.applyParallel(originalUpdates, layoutTerm); + updateLayoutTerm = tb.applyParallel(additionalUpdates, updateLayoutTerm); + for (Term additionalUpdate : collectAdditionalUpdates()) { + updateLayoutTerm = tb.apply(additionalUpdate, updateLayoutTerm); + } + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New + // OneStepSimplifier + // is required + // because it has + // an internal + // state and the + // default + // instance can't + // be used + // parallel. + Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, + modalityPio, layoutCondition, updateLayoutTerm, null, false); + // Instantiate and run proof + ApplyStrategyInfo info = + SymbolicExecutionSideProofUtil.startSideProof(getProof(), sideProofEnv, sequent, + StrategyProperties.METHOD_CONTRACT, StrategyProperties.LOOP_INVARIANT, + StrategyProperties.QUERY_ON, StrategyProperties.SPLITTING_NORMAL); + try { + if (!info.getProof().closed()) { + @SuppressWarnings("unchecked") + Map>[] paramValueMap = new Map[locations.size()]; + // Group equal values as precondition of computeValueConditions(...) + for (Goal goal : info.getProof().openGoals()) { + Term resultTerm = SymbolicExecutionSideProofUtil.extractOperatorTerm(goal, + layoutTerm.op()); + int i = 0; + for (ExtractLocationParameter param : locations) { + Map> valueMap = paramValueMap[i]; + if (valueMap == null) { + valueMap = new LinkedHashMap>(); + paramValueMap[i] = valueMap; + } + Term value = resultTerm.sub(param.getValueTermIndexInStatePredicate()); + value = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), value, + getServices()); + // Replace pre variable with original target + if (value.op() instanceof LocationVariable) { + Term originalTarget = preUpdateMap.get(value.op()); + if (originalTarget != null) { + value = originalTarget; + } + } else if (SymbolicExecutionUtil.isSelect(goal.proof().getServices(), + value)) { + Term object = value.sub(1); + if (object.op() instanceof LocationVariable) { + Term originalTarget = preUpdateMap.get(object.op()); + if (originalTarget != null) { + value = goal.proof().getServices().getTermBuilder().select( + value.sort(), value.sub(0), originalTarget, + value.sub(2)); + } + } + } + // Update value list + Set valueList = valueMap.get(value); + if (valueList == null) { + valueList = new LinkedHashSet(); + valueMap.put(value, valueList); + } + valueList.add(goal); + i++; + } + } + // Compute values including conditions + Map branchConditionCache = new HashMap(); + Set pairs = + new LinkedHashSet(); + int i = 0; + for (ExtractLocationParameter param : locations) { + for (Entry> valueEntry : paramValueMap[i].entrySet()) { + Map conditionsMap = computeValueConditions( + valueEntry.getValue(), branchConditionCache, simplifyConditions); + if (param.isArrayRange()) { + for (Goal goal : valueEntry.getValue()) { + if (valueEntry.getKey() != param.getNotAValue()) { + ExecutionVariableValuePair pair = + new ExecutionVariableValuePair( + OriginTermLabel.removeOriginLabels( + param.getArrayStartIndex(), + getServices()), + OriginTermLabel.removeOriginLabels( + param.getArrayEndIndex(), + getServices()), + OriginTermLabel.removeOriginLabels( + param.getArrayRangeConstant(), + getServices()), + OriginTermLabel.removeOriginLabels( + param.getParentTerm(), getServices()), + OriginTermLabel.removeOriginLabels( + valueEntry.getKey(), getServices()), + OriginTermLabel.removeOriginLabels( + conditionsMap.get(goal), getServices()), + param.isStateMember(), goal.node()); + pairs.add(pair); + } + } + } else if (param.isArrayIndex()) { + for (Goal goal : valueEntry.getValue()) { + ExecutionVariableValuePair pair = new ExecutionVariableValuePair( + OriginTermLabel.removeOriginLabels(param.getArrayIndex(), + getServices()), + OriginTermLabel.removeOriginLabels(param.getParentTerm(), + getServices()), + OriginTermLabel.removeOriginLabels(valueEntry.getKey(), + getServices()), + OriginTermLabel.removeOriginLabels(conditionsMap.get(goal), + getServices()), + param.isStateMember(), goal.node()); + pairs.add(pair); + } + } else { + for (Goal goal : valueEntry.getValue()) { + ExecutionVariableValuePair pair = new ExecutionVariableValuePair( + param.getProgramVariable(), + OriginTermLabel.removeOriginLabels(param.getParentTerm(), + getServices()), + OriginTermLabel.removeOriginLabels(valueEntry.getKey(), + getServices()), + OriginTermLabel.removeOriginLabels(conditionsMap.get(goal), + getServices()), + param.isStateMember(), goal.node()); + pairs.add(pair); + } } - } - } - // Update value list - Set valueList = valueMap.get(value); - if (valueList == null) { - valueList = new LinkedHashSet(); - valueMap.put(value, valueList); - } - valueList.add(goal); - i++; - } + } + i++; + } + return pairs; + } else { + // Proof is closed, something went wrong, continuation impossible + return null; + } + } finally { + SymbolicExecutionSideProofUtil + .disposeOrStore( + "Layout computation on node " + node.serialNr() + " with layout term " + + ProofSaver.printAnything(layoutTerm, getServices()) + ".", + info); + } + } + + /** + * Collects additional updates. + * + * @return The additional updates. + */ + protected List collectAdditionalUpdates() { + return Collections.emptyList(); + } + + /** + * Computes the original updates. + * + * @param pio The {@link PosInOccurrence}. + * @param currentLayout Is current layout? + * @return The original updates. + */ + protected ImmutableList computeOriginalUpdates(PosInOccurrence pio, + boolean currentLayout) { + ImmutableList originalUpdates; + if (!currentLayout) { + originalUpdates = ImmutableSLList.nil(); + } else { + if (node.proof().root() == node) { + originalUpdates = SymbolicExecutionUtil.computeRootElementaryUpdates(node); + } else { + Term originalModifiedFormula = pio.subTerm(); + originalUpdates = TermBuilder.goBelowUpdates2(originalModifiedFormula).first; + } + } + return originalUpdates; + } + + /** + * This method computes for all given {@link Goal}s representing the same value their path + * conditions. A computed path condition consists only of the branch conditions which contribute + * to the value. Branch conditions of splits which does not contribute to the value are ignored. + *

+ * The implemented algorithm works as follows: + *

    + *
  1. The given {@link Goal}s have to be all {@link Goal}s of the side proof providing the same + * value. This means that other branches/goals of the side proof result in different branches. + *
  2. + *
  3. A backward iteration on the parent {@link Node}s starting at the {@link Goal}s is + * performed until the first parent with at least two open children has been found. The + * iteration is only performed on one goal (or the {@link Node} it stops last) at a time. The + * iteration is always performed on the {@link Node} with the highest serial number to ensure + * that different {@link Goal}s will meet at their common parents.
  4. + *
  5. When the iteration of all children of a {@link Node} has met, the branch conditions are + * computed if the split contributes to the value. A split contributes to a value if at least + * one branch is not reached by backward iteration meaning that its {@link Goal}s provide + * different values.
  6. + *
  7. The backward iteration ends when the root is reached.
  8. + *
  9. Finally, for each {@link Goal} is the path condition computed. The path condition is the + * conjunction over all found branch conditions contributing to the value.
  10. + *
+ * + * @param valueGoals All {@link Goal}s of the side proof which provide the same value (result). + * @param branchConditionCache A cache of already computed branch conditions. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return A {@link Map} which contains for each {@link Goal} the computed path condition + * consisting of only required splits. + * @throws ProofInputException Occurred Exception + */ + protected Map computeValueConditions(Set valueGoals, + Map branchConditionCache, boolean simplifyConditions) + throws ProofInputException { + Comparator comparator = new Comparator() { + @Override + public int compare(NodeGoal o1, NodeGoal o2) { + return o2.getSerialNr() - o1.getSerialNr(); // Descending order } - // Compute values including conditions - Map branchConditionCache = new HashMap(); - Set pairs = new LinkedHashSet(); - int i = 0; - for (ExtractLocationParameter param : locations) { - for (Entry> valueEntry : paramValueMap[i].entrySet()) { - Map conditionsMap = computeValueConditions(valueEntry.getValue(), branchConditionCache, simplifyConditions); - if (param.isArrayRange()) { - for (Goal goal : valueEntry.getValue()) { - if (valueEntry.getKey() != param.getNotAValue()) { - ExecutionVariableValuePair pair = new ExecutionVariableValuePair( - OriginTermLabel.removeOriginLabels(param.getArrayStartIndex(), getServices()), - OriginTermLabel.removeOriginLabels(param.getArrayEndIndex(), getServices()), - OriginTermLabel.removeOriginLabels(param.getArrayRangeConstant(), getServices()), - OriginTermLabel.removeOriginLabels(param.getParentTerm(), getServices()), - OriginTermLabel.removeOriginLabels(valueEntry.getKey(), getServices()), - OriginTermLabel.removeOriginLabels(conditionsMap.get(goal), getServices()), - param.isStateMember(), - goal.node()); - pairs.add(pair); + }; + // Initialize condition for each goal with true + Set untriedRealGoals = new HashSet(); + Map> goalConditions = new HashMap>(); + List sortedBranchLeafs = new LinkedList(); + for (Goal goal : valueGoals) { + CollectionUtil.binaryInsert(sortedBranchLeafs, new NodeGoal(goal), comparator); + goalConditions.put(goal, new LinkedHashSet()); + untriedRealGoals.add(goal.node()); + } + // Compute branch conditions + List waitingBranchLeafs = new LinkedList(); + Map> splitMap = new HashMap>(); + while (!sortedBranchLeafs.isEmpty()) { + // Go back to parent with at least two open goals on maximum outer leaf + NodeGoal maximumOuterLeaf = sortedBranchLeafs.remove(0); // List is sorted in descending + // order + NodeGoal childGoal = iterateBackOnParents(maximumOuterLeaf, + !untriedRealGoals.remove(maximumOuterLeaf.getCurrentNode())); + if (childGoal != null) { // Root is not reached + waitingBranchLeafs.add(childGoal); + List childGoals = splitMap.get(childGoal.getParent()); + if (childGoals == null) { + childGoals = new LinkedList(); + splitMap.put(childGoal.getParent(), childGoals); + } + childGoals.add(childGoal); + // Check if parent is reached on all child nodes + if (isParentReachedOnAllChildGoals(childGoal.getParent(), sortedBranchLeafs)) { + // Check if the split contributes to the path condition which is the case if at + // least one branch is not present (because it has a different value) + if (childGoals.size() != childGoal.getParent().childrenCount()) { + // Add branch condition to conditions of all child goals + for (NodeGoal nodeGoal : childGoals) { + Term branchCondition = computeBranchCondition(nodeGoal.getCurrentNode(), + branchConditionCache, simplifyConditions); + for (Goal goal : nodeGoal.getStartingGoals()) { + Set conditions = goalConditions.get(goal); + conditions.add(branchCondition); + } } - } - } - else if (param.isArrayIndex()) { - for (Goal goal : valueEntry.getValue()) { - ExecutionVariableValuePair pair = new ExecutionVariableValuePair( - OriginTermLabel.removeOriginLabels(param.getArrayIndex(), getServices()), - OriginTermLabel.removeOriginLabels(param.getParentTerm(), getServices()), - OriginTermLabel.removeOriginLabels(valueEntry.getKey(), getServices()), - OriginTermLabel.removeOriginLabels(conditionsMap.get(goal), getServices()), - param.isStateMember(), - goal.node()); - pairs.add(pair); - } - } - else { - for (Goal goal : valueEntry.getValue()) { - ExecutionVariableValuePair pair = new ExecutionVariableValuePair( - param.getProgramVariable(), - OriginTermLabel.removeOriginLabels(param.getParentTerm(), getServices()), - OriginTermLabel.removeOriginLabels(valueEntry.getKey(), getServices()), - OriginTermLabel.removeOriginLabels(conditionsMap.get(goal), getServices()), - param.isStateMember(), - goal.node()); - pairs.add(pair); - } - } - } - i++; + } + // Add waiting NodeGoals to working list + for (NodeGoal nodeGoal : childGoals) { + waitingBranchLeafs.remove(nodeGoal); + CollectionUtil.binaryInsert(sortedBranchLeafs, nodeGoal, comparator); + } + } } - return pairs; - } - else { - // Proof is closed, something went wrong, continuation impossible + } + // Compute final condition (redundant path conditions are avoided) + Map pathConditionsMap = new LinkedHashMap(); + for (Entry> entry : goalConditions.entrySet()) { + Term pathCondition = getServices().getTermBuilder().and(entry.getValue()); + pathConditionsMap.put(entry.getKey(), pathCondition); + } + return pathConditionsMap; + } + + /** + * Checks if parent backward iteration on all given {@link NodeGoal} has reached the given + * {@link Node}. + * + * @param currentNode The current {@link Node} to check. + * @param branchLeafs The {@link NodeGoal} on which backward iteration was performed. + * @return {@code true} All {@link NodeGoal}s have passed the given {@link Node}, {@code false} + * if at least one {@link NodeGoal} has not passed the given {@link Node}. + */ + protected boolean isParentReachedOnAllChildGoals(Node currentNode, List branchLeafs) { + if (!branchLeafs.isEmpty()) { + return branchLeafs.get(0).getSerialNr() <= currentNode.serialNr(); + } else { + return true; + } + } + + /** + * Performs a backward iteration on the parents starting at the given {@link NodeGoal} until the + * first parent with at least two open branches has been found. + * + * @param nodeToStartAt The {@link NodeGoal} to start parent backward iteration at. + * @param force {@code true} first parent is not checked, {@code false} also first parent is + * checked. + * @return The first found parent with at least two open child branches or {@code null} if the + * root has been reached. + */ + protected NodeGoal iterateBackOnParents(NodeGoal nodeToStartAt, boolean force) { + // Go back to parent with at least two open branches + Node child = force ? nodeToStartAt.getParent() : nodeToStartAt.getCurrentNode(); + Node parent = child.parent(); + while (parent != null && countOpenChildren(parent) == 1) { + child = parent; + parent = child.parent(); + } + // Store result + if (parent != null) { + return new NodeGoal(child, nodeToStartAt.getStartingGoals()); + } else { return null; - } - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Layout computation on node " + node.serialNr() + " with layout term " + ProofSaver.printAnything(layoutTerm, getServices()) + ".", info); - } - } - - /** - * Collects additional updates. - * @return The additional updates. - */ - protected List collectAdditionalUpdates() { - return Collections.emptyList(); - } - - /** - * Computes the original updates. - * @param pio The {@link PosInOccurrence}. - * @param currentLayout Is current layout? - * @return The original updates. - */ - protected ImmutableList computeOriginalUpdates(PosInOccurrence pio, boolean currentLayout) { - ImmutableList originalUpdates; - if (!currentLayout) { - originalUpdates = ImmutableSLList.nil(); - } - else { - if (node.proof().root() == node) { - originalUpdates = SymbolicExecutionUtil.computeRootElementaryUpdates(node); - } - else { - Term originalModifiedFormula = pio.subTerm(); - originalUpdates = TermBuilder.goBelowUpdates2(originalModifiedFormula).first; - } - } - return originalUpdates; - } - - /** - * This method computes for all given {@link Goal}s representing the same - * value their path conditions. A computed path condition consists only - * of the branch conditions which contribute to the value. Branch conditions - * of splits which does not contribute to the value are ignored. - *

- * The implemented algorithm works as follows: - *

    - *
  1. - * The given {@link Goal}s have to be all {@link Goal}s of the side - * proof providing the same value. This means that other branches/goals - * of the side proof result in different branches. - *
  2. - *
  3. - * A backward iteration on the parent {@link Node}s starting at the - * {@link Goal}s is performed until the first parent with at least - * two open children has been found. - * The iteration is only performed on one - * goal (or the {@link Node} it stops last) at a time. The iteration - * is always performed on the {@link Node} with the highest serial - * number to ensure that different {@link Goal}s will meet at their - * common parents. - *
  4. - *
  5. - * When the iteration of all children of a {@link Node} has met, - * the branch conditions are computed if the split contributes to - * the value. - * A split contributes to a value if at least one branch is not - * reached by backward iteration meaning that its {@link Goal}s - * provide different values. - *
  6. - *
  7. The backward iteration ends when the root is reached.
  8. - *
  9. - * Finally, for each {@link Goal} is the path condition computed. - * The path condition is the conjunction over all found branch - * conditions contributing to the value. - *
  10. - *
- * @param valueGoals All {@link Goal}s of the side proof which provide the same value (result). - * @param branchConditionCache A cache of already computed branch conditions. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return A {@link Map} which contains for each {@link Goal} the computed path condition consisting of only required splits. - * @throws ProofInputException Occurred Exception - */ - protected Map computeValueConditions(Set valueGoals, - Map branchConditionCache, - boolean simplifyConditions) throws ProofInputException { - Comparator comparator = new Comparator() { - @Override - public int compare(NodeGoal o1, NodeGoal o2) { - return o2.getSerialNr() - o1.getSerialNr(); // Descending order - } - }; - // Initialize condition for each goal with true - Set untriedRealGoals = new HashSet(); - Map> goalConditions = new HashMap>(); - List sortedBranchLeafs = new LinkedList(); - for (Goal goal : valueGoals) { - CollectionUtil.binaryInsert(sortedBranchLeafs, new NodeGoal(goal), comparator); - goalConditions.put(goal, new LinkedHashSet()); - untriedRealGoals.add(goal.node()); - } - // Compute branch conditions - List waitingBranchLeafs = new LinkedList(); - Map> splitMap = new HashMap>(); - while (!sortedBranchLeafs.isEmpty()) { - // Go back to parent with at least two open goals on maximum outer leaf - NodeGoal maximumOuterLeaf = sortedBranchLeafs.remove(0); // List is sorted in descending order - NodeGoal childGoal = iterateBackOnParents(maximumOuterLeaf, !untriedRealGoals.remove(maximumOuterLeaf.getCurrentNode())); - if (childGoal != null) { // Root is not reached - waitingBranchLeafs.add(childGoal); - List childGoals = splitMap.get(childGoal.getParent()); - if (childGoals == null) { - childGoals = new LinkedList(); - splitMap.put(childGoal.getParent(), childGoals); + } + } + + /** + * Counts the number of open child {@link Node}s. + * + * @param node The {@link Node} to count its open children. + * @return The number of open child {@link Node}s. + */ + protected int countOpenChildren(Node node) { + int openChildCount = 0; + for (int i = 0; i < node.childrenCount(); i++) { + Node child = node.child(i); + if (!child.isClosed()) { + openChildCount++; } - childGoals.add(childGoal); - // Check if parent is reached on all child nodes - if (isParentReachedOnAllChildGoals(childGoal.getParent(), sortedBranchLeafs)) { - // Check if the split contributes to the path condition which is the case if at least one branch is not present (because it has a different value) - if (childGoals.size() != childGoal.getParent().childrenCount()) { - // Add branch condition to conditions of all child goals - for (NodeGoal nodeGoal : childGoals) { - Term branchCondition = computeBranchCondition(nodeGoal.getCurrentNode(), branchConditionCache, simplifyConditions); - for (Goal goal : nodeGoal.getStartingGoals()) { - Set conditions = goalConditions.get(goal); - conditions.add(branchCondition); - } - } - } - // Add waiting NodeGoals to working list - for (NodeGoal nodeGoal : childGoals) { - waitingBranchLeafs.remove(nodeGoal); - CollectionUtil.binaryInsert(sortedBranchLeafs, nodeGoal, comparator); - } + } + return openChildCount; + } + + /** + * Utility class used by {@link AbstractUpdateExtractor#computeValueConditions(Set, Map)}. + * Instances of this class store the current {@link Node} and the {@link Goal}s at which + * backward iteration on parents has started. + * + * @author Martin Hentschel + */ + protected static class NodeGoal { + /** + * The current {@link Node}. + */ + private final Node currentNode; + + /** + * The {@link Goal}s at which backward iteration has started. + */ + private final ImmutableList startingGoals; + + /** + * Constructor. + * + * @param goal The current {@link Goal} to start backward iteration at. + */ + public NodeGoal(Goal goal) { + this(goal.node(), ImmutableSLList.nil().prepend(goal)); + } + + /** + * A reached child node during backward iteration. + * + * @param currentNode The current {@link Node}. + * @param startingGoals The {@link Goal}s at which backward iteration has started. + */ + public NodeGoal(Node currentNode, ImmutableList startingGoals) { + this.currentNode = currentNode; + this.startingGoals = startingGoals; + } + + /** + * Returns the current {@link Node}. + * + * @return The current {@link Node}. + */ + public Node getCurrentNode() { + return currentNode; + } + + /** + * Returns the parent of {@link #getCurrentNode()}. + * + * @return The parent of {@link #getCurrentNode()}. + */ + public Node getParent() { + return currentNode.parent(); + } + + /** + * Returns the serial number of {@link #getCurrentNode()}. + * + * @return The serial number of {@link #getCurrentNode()}. + */ + public int getSerialNr() { + return currentNode.serialNr(); + } + + /** + * Returns the {@link Goal}s at which backward iteration has started. + * + * @return The {@link Goal}s at which backward iteration has started. + */ + public ImmutableList getStartingGoals() { + return startingGoals; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(currentNode.serialNr()); + sb.append(" starting from goals "); + boolean afterFirst = false; + for (Goal goal : startingGoals) { + if (afterFirst) { + sb.append(", "); + } else { + afterFirst = true; + } + sb.append(goal.node().serialNr()); + } + return sb.toString(); + } + } + + /** + * Computes the branch condition if not already present in the cache and stores it in the cache. + * If the condition is already present in the cache it is returned from it. + * + * @param node The {@link Node} to compute its branch condition. + * @param branchConditionCache The cache of already computed branch conditions. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + protected Term computeBranchCondition(Node node, Map branchConditionCache, + boolean simplifyConditions) throws ProofInputException { + Term result = branchConditionCache.get(node); + if (result == null) { + result = SymbolicExecutionUtil.computeBranchCondition(node, simplifyConditions, true); + branchConditionCache.put(node, result); + } + return result; + } + + /** + *

+ * Represents a location (value or association of a given object/state) in a concrete memory + * layout of the initial or current state. + *

+ *

+ * They are instantiated lazily when a concrete memory layout is requested the first during + * lazily computation + * {@link SymbolicLayoutExtractor#lazyComputeLayout(Node, ImmutableSet, Term, Set, ImmutableList, Term, String)}. + * The instances exists only temporary until the concrete {@link ISymbolicLayout} was created + * from them. + *

+ * + * @author Martin Hentschel + */ + public static class ExecutionVariableValuePair { + /** + * The {@link ProgramVariable} or {@code null} if an array index is used instead. + */ + private final ProgramVariable programVariable; + + /** + * The array index or {@code null} if not used. + */ + private final Term arrayIndex; + + /** + * The array start index or {@code null} if not used. + */ + private final Term arrayStartIndex; + + /** + * The array end index or {@code null} if not used. + */ + private final Term arrayEndIndex; + + /** + * An optional parent object or {@code null} if it is a value/association of the state. + */ + private final Term parent; + + /** + * The value or association target. + */ + private final Term value; + + /** + * Defines if this location should explicitly be shown on the state. + */ + private final boolean stateMember; + + /** + * An optional condition under which the value is valid. + */ + private final Term condition; + + /** + * The {@link Node} on which this result is based on. + */ + private final Node goalNode; + + /** + * Constructor. + * + * @param programVariable The {@link ProgramVariable}. + * @param parent An optional parent object or {@code null} if it is a value/association of + * the state. + * @param value The value or association target. + * @param condition An optional condition under which the value is valid. + * @param stateMember Defines if this location should explicitly be shown on the state. + */ + public ExecutionVariableValuePair(ProgramVariable programVariable, Term parent, Term value, + Term condition, boolean stateMember, Node goalNode) { + assert programVariable != null; + assert value != null; + this.programVariable = programVariable; + this.parent = parent; + this.value = value; + this.condition = condition; + this.arrayIndex = null; + this.stateMember = stateMember; + this.goalNode = goalNode; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * Constructor. + * + * @param arrayIndex The array index. + * @param parent The parent object. + * @param value The value or association target. + * @param condition An optional condition under which the value is valid. + * @param stateMember Defines if this location should explicitly be shown on the state. + */ + public ExecutionVariableValuePair(Term arrayIndex, Term parent, Term value, Term condition, + boolean stateMember, Node goalNode) { + assert parent != null; + assert value != null; + this.programVariable = null; + this.arrayIndex = arrayIndex; + this.parent = parent; + this.value = value; + this.condition = condition; + this.stateMember = stateMember; + this.goalNode = goalNode; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * Constructor. + * + * @param arrayStartIndex The array start index. + * @param arrayEndIndex The array end index. + * @param arrayRangeConstant The constant used to query an array range. + * @param parent The parent object. + * @param value The value or association target. + * @param condition An optional condition under which the value is valid. + * @param stateMember Defines if this location should explicitly be shown on the state. + */ + public ExecutionVariableValuePair(Term arrayStartIndex, Term arrayEndIndex, + Term arrayRangeConstant, Term parent, Term value, Term condition, + boolean stateMember, Node goalNode) { + assert parent != null; + assert value != null; + this.programVariable = null; + this.arrayIndex = arrayRangeConstant; + this.parent = parent; + this.value = value; + this.condition = condition; + this.stateMember = stateMember; + this.goalNode = goalNode; + this.arrayStartIndex = arrayStartIndex; + this.arrayEndIndex = arrayEndIndex; + } + + /** + * Returns the {@link ProgramVariable} or {@code null} if an array index is used instead. + * + * @return The {@link ProgramVariable} or {@code null} if an array index is used instead. + */ + public ProgramVariable getProgramVariable() { + return programVariable; + } + + /** + * Returns the optional parent object or {@code null} if it is a value/association of the + * state. + * + * @return The optional parent object or {@code null} if it is a value/association of the + * state. + */ + public Term getParent() { + return parent; + } + + /** + * Returns the value or association target. + * + * @return The value or association target. + */ + public Term getValue() { + return value; + } + + /** + * Checks if an array index is represented. + * + * @return {@code true} is array index, {@code false} is something else. + */ + public boolean isArrayIndex() { + return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); + } + + /** + * Checks if an array range is represented. + * + * @return {@code true} is array range, {@code false} is something else. + */ + public boolean isArrayRange() { + return arrayStartIndex != null && arrayEndIndex != null; + } + + /** + * Returns the array index. + * + * @return The array index. + */ + public Term getArrayIndex() { + return arrayIndex; + } + + /** + * Returns the array start index. + * + * @return The array start index. + */ + public Term getArrayStartIndex() { + return arrayStartIndex; + } + + /** + * Returns the array end index. + * + * @return The array end index. + */ + public Term getArrayEndIndex() { + return arrayEndIndex; + } + + /** + * Checks if this location should explicitly be shown on the state. + * + * @return Show location on state? + */ + public boolean isStateMember() { + return stateMember; + } + + /** + * Returns the optional condition under which the value is valid. + * + * @return The optional condition under which the value is valid. + */ + public Term getCondition() { + return condition; + } + + /** + * Returns the {@link Node} on which this result is based on. + * + * @return The {@link Node} on which this result is based on. + */ + public Node getGoalNode() { + return goalNode; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ExecutionVariableValuePair) { + ExecutionVariableValuePair other = (ExecutionVariableValuePair) obj; + return isArrayRange() + ? (getArrayStartIndex().equals(other.getArrayStartIndex()) + && getArrayEndIndex().equals(other.getArrayEndIndex())) + : (isArrayIndex() ? getArrayIndex().equals(other.getArrayIndex()) + : getProgramVariable().equals(other.getProgramVariable())) + && getParent() != null + ? getParent().equals(other.getParent()) + : other.getParent() == null && getCondition() != null + ? getCondition().equals(other.getCondition()) + : other.getCondition() == null + && getValue().equals(other.getValue()) + && getGoalNode() + .equals(other.getGoalNode()); + } else { + return false; } - } - } - // Compute final condition (redundant path conditions are avoided) - Map pathConditionsMap = new LinkedHashMap(); - for (Entry> entry : goalConditions.entrySet()) { - Term pathCondition = getServices().getTermBuilder().and(entry.getValue()); - pathConditionsMap.put(entry.getKey(), pathCondition); - } - return pathConditionsMap; - } - - /** - * Checks if parent backward iteration on all given {@link NodeGoal} has - * reached the given {@link Node}. - * @param currentNode The current {@link Node} to check. - * @param branchLeafs The {@link NodeGoal} on which backward iteration was performed. - * @return {@code true} All {@link NodeGoal}s have passed the given {@link Node}, {@code false} if at least one {@link NodeGoal} has not passed the given {@link Node}. - */ - protected boolean isParentReachedOnAllChildGoals(Node currentNode, List branchLeafs) { - if (!branchLeafs.isEmpty()) { - return branchLeafs.get(0).getSerialNr() <= currentNode.serialNr(); - } - else { - return true; - } - } - - /** - * Performs a backward iteration on the parents starting at the given - * {@link NodeGoal} until the first parent with at least two open - * branches has been found. - * @param nodeToStartAt The {@link NodeGoal} to start parent backward iteration at. - * @param force {@code true} first parent is not checked, {@code false} also first parent is checked. - * @return The first found parent with at least two open child branches or {@code null} if the root has been reached. - */ - protected NodeGoal iterateBackOnParents(NodeGoal nodeToStartAt, boolean force) { - // Go back to parent with at least two open branches - Node child = force ? nodeToStartAt.getParent() : nodeToStartAt.getCurrentNode(); - Node parent = child.parent(); - while (parent != null && countOpenChildren(parent) == 1) { - child = parent; - parent = child.parent(); - } - // Store result - if (parent != null) { - return new NodeGoal(child, nodeToStartAt.getStartingGoals()); - } - else { - return null; - } - } - - /** - * Counts the number of open child {@link Node}s. - * @param node The {@link Node} to count its open children. - * @return The number of open child {@link Node}s. - */ - protected int countOpenChildren(Node node) { - int openChildCount = 0; - for (int i = 0; i < node.childrenCount(); i++) { - Node child = node.child(i); - if (!child.isClosed()) { - openChildCount++; - } - } - return openChildCount; - } - - /** - * Utility class used by {@link AbstractUpdateExtractor#computeValueConditions(Set, Map)}. - * Instances of this class store the current {@link Node} and the {@link Goal}s at which backward iteration on parents has started. - * @author Martin Hentschel - */ - protected static class NodeGoal { - /** - * The current {@link Node}. - */ - private final Node currentNode; - - /** - * The {@link Goal}s at which backward iteration has started. - */ - private final ImmutableList startingGoals; - - /** - * Constructor. - * @param goal The current {@link Goal} to start backward iteration at. - */ - public NodeGoal(Goal goal) { - this(goal.node(), ImmutableSLList.nil().prepend(goal)); - } - - /** - * A reached child node during backward iteration. - * @param currentNode The current {@link Node}. - * @param startingGoals The {@link Goal}s at which backward iteration has started. - */ - public NodeGoal(Node currentNode, ImmutableList startingGoals) { - this.currentNode = currentNode; - this.startingGoals = startingGoals; - } - - /** - * Returns the current {@link Node}. - * @return The current {@link Node}. - */ - public Node getCurrentNode() { - return currentNode; - } - - /** - * Returns the parent of {@link #getCurrentNode()}. - * @return The parent of {@link #getCurrentNode()}. - */ - public Node getParent() { - return currentNode.parent(); - } - - /** - * Returns the serial number of {@link #getCurrentNode()}. - * @return The serial number of {@link #getCurrentNode()}. - */ - public int getSerialNr() { - return currentNode.serialNr(); - } - - /** - * Returns the {@link Goal}s at which backward iteration has started. - * @return The {@link Goal}s at which backward iteration has started. - */ - public ImmutableList getStartingGoals() { - return startingGoals; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append(currentNode.serialNr()); - sb.append(" starting from goals "); - boolean afterFirst = false; - for (Goal goal : startingGoals) { - if (afterFirst) { - sb.append(", "); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = 17; + if (isArrayRange()) { + result = 31 * result + getArrayStartIndex().hashCode(); + result = 31 * result + getArrayEndIndex().hashCode(); + } else if (isArrayIndex()) { + result = 31 * result + getArrayIndex().hashCode(); + } else { + result = 31 * result + getProgramVariable().hashCode(); } - else { - afterFirst = true; + result = 31 * result + (getParent() != null ? getParent().hashCode() : 0); + result = 31 * result + (getCondition() != null ? getCondition().hashCode() : 0); + result = 31 * result + getValue().hashCode(); + result = 31 * result + getGoalNode().hashCode(); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + if (isArrayRange()) { + return "[" + getArrayIndex() + "]" + " between " + getArrayStartIndex() + " and " + + getArrayEndIndex() + (getParent() != null ? " of " + getParent() : "") + + " is " + getValue() + + (getCondition() != null ? " under condition " + getCondition() : "") + + " at goal " + goalNode.serialNr(); + } else if (isArrayIndex()) { + return "[" + getArrayIndex() + "]" + + (getParent() != null ? " of " + getParent() : "") + " is " + getValue() + + (getCondition() != null ? " under condition " + getCondition() : "") + + " at goal " + goalNode.serialNr(); + } else { + return getProgramVariable() + (getParent() != null ? " of " + getParent() : "") + + " is " + getValue() + + (getCondition() != null ? " under condition " + getCondition() : "") + + " at goal " + goalNode.serialNr(); } - sb.append(goal.node().serialNr()); - } - return sb.toString(); - } - } - - /** - * Computes the branch condition if not already present in the cache - * and stores it in the cache. If the condition is already present in the - * cache it is returned from it. - * @param node The {@link Node} to compute its branch condition. - * @param branchConditionCache The cache of already computed branch conditions. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - protected Term computeBranchCondition(Node node, - Map branchConditionCache, - boolean simplifyConditions) throws ProofInputException { - Term result = branchConditionCache.get(node); - if (result == null) { - result = SymbolicExecutionUtil.computeBranchCondition(node, simplifyConditions, true); - branchConditionCache.put(node, result); - } - return result; - } - - /** - *

- * Represents a location (value or association of a given object/state) - * in a concrete memory layout of the initial or current state. - *

- *

- * They are instantiated lazily when a concrete memory layout is requested - * the first during lazily computation - * {@link SymbolicLayoutExtractor#lazyComputeLayout(Node, ImmutableSet, Term, Set, ImmutableList, Term, String)}. - * The instances exists only temporary until the concrete {@link ISymbolicLayout} was created from them. - *

- * @author Martin Hentschel - */ - public static class ExecutionVariableValuePair { - /** - * The {@link ProgramVariable} or {@code null} if an array index is used instead. - */ - private final ProgramVariable programVariable; - - /** - * The array index or {@code null} if not used. - */ - private final Term arrayIndex; - - /** - * The array start index or {@code null} if not used. - */ - private final Term arrayStartIndex; - - /** - * The array end index or {@code null} if not used. - */ - private final Term arrayEndIndex; - - /** - * An optional parent object or {@code null} if it is a value/association of the state. - */ - private final Term parent; - - /** - * The value or association target. - */ - private final Term value; - - /** - * Defines if this location should explicitly be shown on the state. - */ - private final boolean stateMember; - - /** - * An optional condition under which the value is valid. - */ - private final Term condition; - - /** - * The {@link Node} on which this result is based on. - */ - private final Node goalNode; - - /** - * Constructor. - * @param programVariable The {@link ProgramVariable}. - * @param parent An optional parent object or {@code null} if it is a value/association of the state. - * @param value The value or association target. - * @param condition An optional condition under which the value is valid. - * @param stateMember Defines if this location should explicitly be shown on the state. - */ - public ExecutionVariableValuePair(ProgramVariable programVariable, - Term parent, - Term value, - Term condition, - boolean stateMember, - Node goalNode) { - assert programVariable != null; - assert value != null; - this.programVariable = programVariable; - this.parent = parent; - this.value = value; - this.condition = condition; - this.arrayIndex = null; - this.stateMember = stateMember; - this.goalNode = goalNode; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } - - /** - * Constructor. - * @param arrayIndex The array index. - * @param parent The parent object. - * @param value The value or association target. - * @param condition An optional condition under which the value is valid. - * @param stateMember Defines if this location should explicitly be shown on the state. - */ - public ExecutionVariableValuePair(Term arrayIndex, - Term parent, - Term value, - Term condition, - boolean stateMember, - Node goalNode) { - assert parent != null; - assert value != null; - this.programVariable = null; - this.arrayIndex = arrayIndex; - this.parent = parent; - this.value = value; - this.condition = condition; - this.stateMember = stateMember; - this.goalNode = goalNode; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } - - /** - * Constructor. - * @param arrayStartIndex The array start index. - * @param arrayEndIndex The array end index. - * @param arrayRangeConstant The constant used to query an array range. - * @param parent The parent object. - * @param value The value or association target. - * @param condition An optional condition under which the value is valid. - * @param stateMember Defines if this location should explicitly be shown on the state. - */ - public ExecutionVariableValuePair(Term arrayStartIndex, - Term arrayEndIndex, - Term arrayRangeConstant, - Term parent, - Term value, - Term condition, - boolean stateMember, - Node goalNode) { - assert parent != null; - assert value != null; - this.programVariable = null; - this.arrayIndex = arrayRangeConstant; - this.parent = parent; - this.value = value; - this.condition = condition; - this.stateMember = stateMember; - this.goalNode = goalNode; - this.arrayStartIndex = arrayStartIndex; - this.arrayEndIndex = arrayEndIndex; - } - - /** - * Returns the {@link ProgramVariable} or {@code null} if an array index is used instead. - * @return The {@link ProgramVariable} or {@code null} if an array index is used instead. - */ - public ProgramVariable getProgramVariable() { - return programVariable; - } - - /** - * Returns the optional parent object or {@code null} if it is a value/association of the state. - * @return The optional parent object or {@code null} if it is a value/association of the state. - */ - public Term getParent() { - return parent; - } - - /** - * Returns the value or association target. - * @return The value or association target. - */ - public Term getValue() { - return value; - } - - /** - * Checks if an array index is represented. - * @return {@code true} is array index, {@code false} is something else. - */ - public boolean isArrayIndex() { - return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); - } - - /** - * Checks if an array range is represented. - * @return {@code true} is array range, {@code false} is something else. - */ - public boolean isArrayRange() { - return arrayStartIndex != null && arrayEndIndex != null; - } - - /** - * Returns the array index. - * @return The array index. - */ - public Term getArrayIndex() { - return arrayIndex; - } - - /** - * Returns the array start index. - * @return The array start index. - */ - public Term getArrayStartIndex() { - return arrayStartIndex; - } - - /** - * Returns the array end index. - * @return The array end index. - */ - public Term getArrayEndIndex() { - return arrayEndIndex; - } - - /** - * Checks if this location should explicitly be shown on the state. - * @return Show location on state? - */ - public boolean isStateMember() { - return stateMember; - } - - /** - * Returns the optional condition under which the value is valid. - * @return The optional condition under which the value is valid. - */ - public Term getCondition() { - return condition; - } - - /** - * Returns the {@link Node} on which this result is based on. - * @return The {@link Node} on which this result is based on. - */ - public Node getGoalNode() { - return goalNode; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof ExecutionVariableValuePair) { - ExecutionVariableValuePair other = (ExecutionVariableValuePair)obj; - return isArrayRange() ? (getArrayStartIndex().equals(other.getArrayStartIndex()) && getArrayEndIndex().equals(other.getArrayEndIndex())) : - (isArrayIndex() ? getArrayIndex().equals(other.getArrayIndex()) : getProgramVariable().equals(other.getProgramVariable())) && - getParent() != null ? getParent().equals(other.getParent()) : other.getParent() == null && - getCondition() != null ? getCondition().equals(other.getCondition()) : other.getCondition() == null && - getValue().equals(other.getValue()) && - getGoalNode().equals(other.getGoalNode()); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - if (isArrayRange()) { - result = 31 * result + getArrayStartIndex().hashCode(); - result = 31 * result + getArrayEndIndex().hashCode(); - } - else if (isArrayIndex()) { - result = 31 * result + getArrayIndex().hashCode(); - } - else { - result = 31 * result + getProgramVariable().hashCode(); - } - result = 31 * result + (getParent() != null ? getParent().hashCode() : 0); - result = 31 * result + (getCondition() != null ? getCondition().hashCode() : 0); - result = 31 * result + getValue().hashCode(); - result = 31 * result + getGoalNode().hashCode(); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - if (isArrayRange()) { - return "[" + getArrayIndex() + "]" + - " between " + getArrayStartIndex() + " and " + getArrayEndIndex() + - (getParent() != null ? " of " + getParent() : "") + - " is " + getValue() + (getCondition() != null ? " under condition " + getCondition() : "") + - " at goal " + goalNode.serialNr(); - } - else if (isArrayIndex()) { - return "[" + getArrayIndex() + "]" + - (getParent() != null ? " of " + getParent() : "") + - " is " + getValue() + (getCondition() != null ? " under condition " + getCondition() : "") + - " at goal " + goalNode.serialNr(); - } - else { - return getProgramVariable() + - (getParent() != null ? " of " + getParent() : "") + - " is " + getValue() + (getCondition() != null ? " under condition " + getCondition() : "") + - " at goal " + goalNode.serialNr(); - } - } - } + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractWriter.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractWriter.java index a0327bb00dd..c6285ba3b84 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractWriter.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/AbstractWriter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.Map; @@ -7,130 +10,140 @@ import org.key_project.util.java.XMLUtil; /** - * Provides the basic functionality for classes like {@link ExecutionNodeWriter} - * and {@link SymbolicLayoutWriter} which encodes an object structure as XML. + * Provides the basic functionality for classes like {@link ExecutionNodeWriter} and + * {@link SymbolicLayoutWriter} which encodes an object structure as XML. + * * @author Martin Hentschel */ public abstract class AbstractWriter { - /** - * New line. - */ - public static final String NEW_LINE = StringUtil.NEW_LINE; - - /** - * The used leading white space in each level. - */ - public static final String LEADING_WHITE_SPACE_PER_LEVEL = " "; - - /** - * The default enconding. - */ - public static final String DEFAULT_ENCODING = "UTF-8"; + /** + * New line. + */ + public static final String NEW_LINE = StringUtil.NEW_LINE; - /** - * Attribute name to store encodings. - */ - public static final String ATTRIBUTE_ENCODING = "encoding"; + /** + * The used leading white space in each level. + */ + public static final String LEADING_WHITE_SPACE_PER_LEVEL = " "; - /** - * Attribute name to store the XML ID. - */ - public static final String ATTRIBUTE_XML_ID = "xml:id"; + /** + * The default enconding. + */ + public static final String DEFAULT_ENCODING = "UTF-8"; - /** - * Appends an empty tag to the given {@link StringBuffer}. - * @param level The level. - * @param tagName The tag name. - * @param attributeValues The attributes. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendEmptyTag(int level, String tagName, Map attributeValues, StringBuffer sb) { - appendWhiteSpace(level, sb); - sb.append("<"); - sb.append(tagName); - for (Entry entry : attributeValues.entrySet()) { - appendAttribute(entry.getKey(), entry.getValue(), sb); - } - sb.append("/>"); - appendNewLine(sb); - } + /** + * Attribute name to store encodings. + */ + public static final String ATTRIBUTE_ENCODING = "encoding"; - /** - * Appends a start tag to the given {@link StringBuffer}. - * @param level The level. - * @param tagName The tag name. - * @param attributeValues The attributes. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendStartTag(int level, String tagName, Map attributeValues, StringBuffer sb) { - appendWhiteSpace(level, sb); - sb.append("<"); - sb.append(tagName); - for (Entry entry : attributeValues.entrySet()) { - appendAttribute(entry.getKey(), entry.getValue(), sb); - } - sb.append(">"); - appendNewLine(sb); - } + /** + * Attribute name to store the XML ID. + */ + public static final String ATTRIBUTE_XML_ID = "xml:id"; - /** - * Appends an end tag to the given {@link StringBuffer}. - * @param level The level. - * @param tagName The tag name. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendEndTag(int level, String tagName, StringBuffer sb) { - appendWhiteSpace(level, sb); - sb.append(""); - appendNewLine(sb); - } - - /** - * Adds leading white space to the {@link StringBuffer}. - * @param level The level in the tree used for leading white space (formating). - * @param sb The {@link StringBuffer} to write to. - */ - protected void appendWhiteSpace(int level, StringBuffer sb) { - for (int i = 0; i < level; i++) { - sb.append(LEADING_WHITE_SPACE_PER_LEVEL); - } - } + /** + * Appends an empty tag to the given {@link StringBuffer}. + * + * @param level The level. + * @param tagName The tag name. + * @param attributeValues The attributes. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendEmptyTag(int level, String tagName, Map attributeValues, + StringBuffer sb) { + appendWhiteSpace(level, sb); + sb.append("<"); + sb.append(tagName); + for (Entry entry : attributeValues.entrySet()) { + appendAttribute(entry.getKey(), entry.getValue(), sb); + } + sb.append("/>"); + appendNewLine(sb); + } - /** - * Adds an XML attribute to the given {@link StringBuffer}. - * @param attributeName The attribute name. - * @param value The attribute value. - * @param sb The {@link StringBuffer} to write to. - */ - protected void appendAttribute(String attributeName, String value, StringBuffer sb) { - if (attributeName != null && value != null) { - sb.append(" "); - sb.append(attributeName); - sb.append("=\""); - sb.append(XMLUtil.encodeText(value)); - sb.append("\""); - } - } - - /** - * Adds an XML header to the given {@link StringBuffer}. - * @param encoding The encoding to use. - * @param sb The {@link StringBuffer} to write to. - */ - protected void appendXmlHeader(String encoding, StringBuffer sb) { - sb.append(""); - appendNewLine(sb); - } - - /** - * Adds a line break to the given {@link StringBuffer}. - * @param sb The {@link StringBuffer} to write to. - */ - protected void appendNewLine(StringBuffer sb) { - sb.append(NEW_LINE); - } -} \ No newline at end of file + /** + * Appends a start tag to the given {@link StringBuffer}. + * + * @param level The level. + * @param tagName The tag name. + * @param attributeValues The attributes. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendStartTag(int level, String tagName, Map attributeValues, + StringBuffer sb) { + appendWhiteSpace(level, sb); + sb.append("<"); + sb.append(tagName); + for (Entry entry : attributeValues.entrySet()) { + appendAttribute(entry.getKey(), entry.getValue(), sb); + } + sb.append(">"); + appendNewLine(sb); + } + + /** + * Appends an end tag to the given {@link StringBuffer}. + * + * @param level The level. + * @param tagName The tag name. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendEndTag(int level, String tagName, StringBuffer sb) { + appendWhiteSpace(level, sb); + sb.append(""); + appendNewLine(sb); + } + + /** + * Adds leading white space to the {@link StringBuffer}. + * + * @param level The level in the tree used for leading white space (formating). + * @param sb The {@link StringBuffer} to write to. + */ + protected void appendWhiteSpace(int level, StringBuffer sb) { + for (int i = 0; i < level; i++) { + sb.append(LEADING_WHITE_SPACE_PER_LEVEL); + } + } + + /** + * Adds an XML attribute to the given {@link StringBuffer}. + * + * @param attributeName The attribute name. + * @param value The attribute value. + * @param sb The {@link StringBuffer} to write to. + */ + protected void appendAttribute(String attributeName, String value, StringBuffer sb) { + if (attributeName != null && value != null) { + sb.append(" "); + sb.append(attributeName); + sb.append("=\""); + sb.append(XMLUtil.encodeText(value)); + sb.append("\""); + } + } + + /** + * Adds an XML header to the given {@link StringBuffer}. + * + * @param encoding The encoding to use. + * @param sb The {@link StringBuffer} to write to. + */ + protected void appendXmlHeader(String encoding, StringBuffer sb) { + sb.append(""); + appendNewLine(sb); + } + + /** + * Adds a line break to the given {@link StringBuffer}. + * + * @param sb The {@link StringBuffer} to write to. + */ + protected void appendNewLine(StringBuffer sb) { + sb.append(NEW_LINE); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodePreorderIterator.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodePreorderIterator.java index 700cbdc2823..7bcd7e5b624 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodePreorderIterator.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodePreorderIterator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import de.uka.ilkd.key.symbolic_execution.model.IExecutionNode; @@ -7,103 +10,108 @@ * Iterates preorder over the whole sub tree of a given {@link IExecutionNode}. *

*

- * Instances of this class should always be used instead of recursive method - * calls because they cause {@link StackOverflowError}s even in small programs. + * Instances of this class should always be used instead of recursive method calls because they + * cause {@link StackOverflowError}s even in small programs. *

*

- * Attention: The iteration process does not take care of changes in - * the model. If the containment hierarchy changes during iteration it is possible - * that elements are left or visited multiple times. For this reason it is forbidden - * to change the model during iteration. But the developer has to take care about it. + * Attention: The iteration process does not take care of changes in the model. If the + * containment hierarchy changes during iteration it is possible that elements are left or visited + * multiple times. For this reason it is forbidden to change the model during iteration. But the + * developer has to take care about it. *

+ * * @author Martin Hentschel */ public class ExecutionNodePreorderIterator { - /** - * The element at that the iteration has started used as end condition - * to make sure that only over the subtree of the element is iterated. - */ - private IExecutionNode start; + /** + * The element at that the iteration has started used as end condition to make sure that only + * over the subtree of the element is iterated. + */ + private IExecutionNode start; - /** - * The next element or {@code null} if no more elements exists. - */ - private IExecutionNode next; - - /** - * Constructor. - * @param start The {@link IExecutionNode} to iterate over its sub tree. - */ - public ExecutionNodePreorderIterator(IExecutionNode start) { - this.start = start; - this.next = start; - } - - /** - * Checks if more elements are available. - * @return {@code true} has more elements, {@code false} has not more elements. - */ - public boolean hasNext() { - return next != null; - } - - /** - * Returns the next {@link IExecutionNode} in the containment hierarchy. - * @return The next {@link IExecutionNode}. - */ - public IExecutionNode next() { - IExecutionNode oldNext = next; - updateNext(); - return oldNext; - } + /** + * The next element or {@code null} if no more elements exists. + */ + private IExecutionNode next; - /** - * Computes the next element and updates {@link #next()}. - */ - protected void updateNext() { - IExecutionNode newNext = null; - IExecutionNode[] children = next.getChildren(); - if (children.length >= 1) { - newNext = children[0]; - } - else { - newNext = getNextOnParent(next); - } - this.next = newNext; - } - - /** - * Returns the next element to select if all children of the given - * {@link IExecutionNode} are visited. - * @param node The visited {@link IExecutionNode}. - * @return The next {@link IExecutionNode} to visit. - */ - protected IExecutionNode getNextOnParent(IExecutionNode node) { - IExecutionNode parent = node.getParent(); - while (parent != null) { - boolean IExecutionNodeFound = false; // Indicates that IExecutionNode was found on the parent. - IExecutionNode[] children = parent.getChildren(); - IExecutionNode nextChildOnParent = null; // The next child on the parent or the last child after iteration has finished - for (int i = 0; i < children.length; i++) { - nextChildOnParent = children[i]; - if (nextChildOnParent == start) { - return null; - } - if (IExecutionNodeFound) { - return nextChildOnParent; + /** + * Constructor. + * + * @param start The {@link IExecutionNode} to iterate over its sub tree. + */ + public ExecutionNodePreorderIterator(IExecutionNode start) { + this.start = start; + this.next = start; + } + + /** + * Checks if more elements are available. + * + * @return {@code true} has more elements, {@code false} has not more elements. + */ + public boolean hasNext() { + return next != null; + } + + /** + * Returns the next {@link IExecutionNode} in the containment hierarchy. + * + * @return The next {@link IExecutionNode}. + */ + public IExecutionNode next() { + IExecutionNode oldNext = next; + updateNext(); + return oldNext; + } + + /** + * Computes the next element and updates {@link #next()}. + */ + protected void updateNext() { + IExecutionNode newNext = null; + IExecutionNode[] children = next.getChildren(); + if (children.length >= 1) { + newNext = children[0]; + } else { + newNext = getNextOnParent(next); + } + this.next = newNext; + } + + /** + * Returns the next element to select if all children of the given {@link IExecutionNode} are + * visited. + * + * @param node The visited {@link IExecutionNode}. + * @return The next {@link IExecutionNode} to visit. + */ + protected IExecutionNode getNextOnParent(IExecutionNode node) { + IExecutionNode parent = node.getParent(); + while (parent != null) { + boolean IExecutionNodeFound = false; // Indicates that IExecutionNode was found on the + // parent. + IExecutionNode[] children = parent.getChildren(); + IExecutionNode nextChildOnParent = null; // The next child on the parent or the last + // child after iteration has finished + for (int i = 0; i < children.length; i++) { + nextChildOnParent = children[i]; + if (nextChildOnParent == start) { + return null; + } + if (IExecutionNodeFound) { + return nextChildOnParent; + } + if (nextChildOnParent == node) { + IExecutionNodeFound = true; + } } - if (nextChildOnParent == node) { - IExecutionNodeFound = true; + if (nextChildOnParent != start) { + node = parent; // Continue search on parent without recursive call! + parent = parent.getParent(); + } else { + return null; } - } - if (nextChildOnParent != start) { - node = parent; // Continue search on parent without recursive call! - parent = parent.getParent(); - } - else { - return null; - } - } - return null; // No more parents available. - } -} \ No newline at end of file + } + return null; // No more parents available. + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeReader.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeReader.java index 49899304d82..01ab6a9f2e9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeReader.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeReader.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.io.File; @@ -81,3049 +84,3207 @@ import de.uka.ilkd.key.util.Pair; /** - * Allows to read XML files which contains an symbolic execution tree - * written via an {@link ExecutionNodeWriter}. + * Allows to read XML files which contains an symbolic execution tree written via an + * {@link ExecutionNodeWriter}. + * * @author Martin Hentschel * @see ExecutionNodeWriter */ public class ExecutionNodeReader { - /** - * Reads the given {@link File}. - * @param file The {@link File} to read. - * @return The root of the read symbolic execution tree. - * @throws ParserConfigurationException Occurred Exception. - * @throws SAXException Occurred Exception. - * @throws IOException Occurred Exception. - */ - public IExecutionNode read(File file) throws ParserConfigurationException, SAXException, IOException { - return read(new FileInputStream(file)); - } - - /** - * Reads from the given {@link InputStream} and closes it. - * @param in The {@link InputStream} to read from. - * @return The root of the read symbolic execution tree. - * @throws ParserConfigurationException Occurred Exception. - * @throws SAXException Occurred Exception. - * @throws IOException Occurred Exception. - */ - public IExecutionNode read(InputStream in) throws ParserConfigurationException, SAXException, IOException { - if (in != null) { - try { - // Parse XML file - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setNamespaceAware(true); - SAXParser saxParser = factory.newSAXParser(); - SEDSAXHandler handler = new SEDSAXHandler(); - saxParser.parse(in, handler); - // Get root - IExecutionNode root = handler.getRoot(); - // Construct call stacks - Set, List>> entries = handler.getCallStackPathEntries().entrySet(); - for (Entry, List> entry : entries) { - for (String path : entry.getValue()) { - IExecutionNode stackEntry = findNode(root, path); - if (stackEntry == null) { - throw new SAXException("Can't find call stack entry \"" + path + "\" in parsed symbolic execution tree."); - } - entry.getKey().addCallStackEntry(stackEntry); - } - } - // Construct method returns - Set>> methodReturnEntries = handler.getMethodReturnPathEntries().entrySet(); - for (Entry> entry : methodReturnEntries) { - for (String path : entry.getValue()) { - IExecutionNode returnEntry = findNode(root, path); - if (returnEntry == null) { - throw new SAXException("Can't find method return entry \"" + path + "\" in parsed symbolic execution tree."); - } - if (!(returnEntry instanceof IExecutionBaseMethodReturn)) { - throw new SAXException("Expected basemethod return on \"" + path + "\" but is " + returnEntry.getElementType() + "."); - } - entry.getKey().addMethodReturn((IExecutionBaseMethodReturn)returnEntry); - } - } - // Construct completed blocks - Set, List>>> completedBlockEntries = handler.getCompletedBlockEntries().entrySet(); - for (Entry, List>> entry : completedBlockEntries) { - for (Pair pair : entry.getValue()) { - IExecutionNode returnEntry = findNode(root, pair.first); - if (returnEntry == null) { - throw new SAXException("Can't find completed block entry \"" + pair.first + "\" in parsed symbolic execution tree."); - } - else if (!(returnEntry instanceof IExecutionBlockStartNode)) { - throw new SAXException("Found completed block entry is not an instance of IExecutionBlockStartNode."); - } - entry.getKey().addCompletedBlock((IExecutionBlockStartNode)returnEntry, pair.second); - } - } - // Construct block completions - Set, List>> blockCompletionEntries = handler.getBlockCompletionEntries().entrySet(); - for (Entry, List> entry : blockCompletionEntries) { - for (String path : entry.getValue()) { - IExecutionNode returnEntry = findNode(root, path); - if (returnEntry == null) { - throw new SAXException("Can't find block completion entry \"" + path + "\" in parsed symbolic execution tree."); - } - entry.getKey().addBlockCompletion(returnEntry); - } - } - // Construct links - Set, List>> outgoingLinks = handler.getOutgoingLinks().entrySet(); - for (Entry, List> entry : outgoingLinks) { - for (String path : entry.getValue()) { - IExecutionNode target = findNode(root, path); - if (target == null) { - throw new SAXException("Can't find link targets \"" + path + "\" in parsed symbolic execution tree."); - } - KeYLessLink link = new KeYLessLink(); - link.setSource(entry.getKey()); - link.setTarget(target); - entry.getKey().addOutgoingLink(link); - ((AbstractKeYlessExecutionNode) target).addIncomingLink(link); - } - } - // Construct terminations - Set>> terminationEntries = handler.getTerminationPathEntries().entrySet(); - for (Entry> entry : terminationEntries) { - for (String path : entry.getValue()) { - IExecutionNode terminationEntry = findNode(root, path); - if (terminationEntry == null) { - throw new SAXException("Can't find termination entry \"" + path + "\" in parsed symbolic execution tree."); - } - if (!(terminationEntry instanceof IExecutionTermination)) { - throw new SAXException("Expected termination on \"" + path + "\" but is " + terminationEntry.getElementType() + "."); - } - entry.getKey().addTermination((IExecutionTermination)terminationEntry); - } - } - // Return result - return root; - } - finally { - in.close(); - } - } - else { - return null; - } - } - - /** - * Searches the {@link IExecutionNode} starting at the given root - * which is defined by the path. - * @param root The {@link IExecutionNode} to start search. - * @param path The path. - * @return The found {@link IExecutionNode}. - * @throws SAXException If it was not possible to find the node. - */ - protected IExecutionNode findNode(IExecutionNode root, String path) throws SAXException { - if (path != null && !path.isEmpty()) { - StringTokenizer tokenizer = new StringTokenizer(path, ExecutionNodeWriter.PATH_SEPARATOR + ""); - while (tokenizer.hasMoreTokens()) { - String next = tokenizer.nextToken(); + /** + * Reads the given {@link File}. + * + * @param file The {@link File} to read. + * @return The root of the read symbolic execution tree. + * @throws ParserConfigurationException Occurred Exception. + * @throws SAXException Occurred Exception. + * @throws IOException Occurred Exception. + */ + public IExecutionNode read(File file) + throws ParserConfigurationException, SAXException, IOException { + return read(new FileInputStream(file)); + } + + /** + * Reads from the given {@link InputStream} and closes it. + * + * @param in The {@link InputStream} to read from. + * @return The root of the read symbolic execution tree. + * @throws ParserConfigurationException Occurred Exception. + * @throws SAXException Occurred Exception. + * @throws IOException Occurred Exception. + */ + public IExecutionNode read(InputStream in) + throws ParserConfigurationException, SAXException, IOException { + if (in != null) { try { - int childIndex = Integer.parseInt(next); - if (childIndex < 0) { - throw new SAXException("Path segment \"" + next + "\" of path \"" + path + "\" is a negative integer."); - } - IExecutionNode[] children = root.getChildren(); - if (childIndex >= children.length) { - throw new SAXException("Path segment \"" + next + "\" of path \"" + path + "\" is outside of the child array range."); - } - root = children[childIndex]; - } - catch (NumberFormatException e) { - throw new SAXException("Path segment \"" + next + "\" of path \"" + path + "\" is no valid integer.", e); - } - } - } - return root; - } - - /** - * {@link DefaultHandler} implementation used in {@link ExecutionNodeReader#read(InputStream)}. - * @author Martin Hentschel - */ - private class SEDSAXHandler extends DefaultHandler { - /** - * The root of the read symbolic execution tree. - */ - private IExecutionNode root; - - /** - * The parent hierarchy filled by {@link #startElement(String, String, String, Attributes)} - * and emptied by {@link #endElement(String, String, String)}. - */ - private final Deque> parentNodeStack = new LinkedList>(); - - /** - * The parent hierarchy of {@link IExecutionVariable} and {@link IExecutionValue} filled by {@link #startElement(String, String, String, Attributes)} - * and emptied by {@link #endElement(String, String, String)}. - */ - private final Deque parentVariableValueStack = new LinkedList(); - - /** - * Maps an {@link AbstractKeYlessExecutionNode} to the path entries of its call stack. - */ - private final Map, List> callStackPathEntries = new LinkedHashMap, List>(); - - /** - * Maps an {@link KeYlessMethodCall} to the path entries of its method returns. - */ - private final Map> methodReturnPathEntries = new LinkedHashMap>(); - - /** - * Maps an {@link AbstractKeYlessExecutionNode} to its completed block entries - */ - private final Map, List>> completedBlockEntries = new LinkedHashMap, List>>(); - - /** - * Maps an {@link AbstractKeYlessExecutionBlockStartNode} to the path entries of its block completions. - */ - private final Map, List> blockCompletionEntries = new LinkedHashMap, List>(); - - /** - * Maps an {@link AbstractKeYlessExecutionNode} to the path entries of its outgoing links. - */ - private final Map, List> outgoingLinks = new LinkedHashMap, List>(); - - /** - * Maps an {@link KeYlessStart} to the path entries of its terminations. - */ - private final Map> terminationPathEntries = new LinkedHashMap>(); - - /** - * {@inheritDoc} - */ - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - AbstractKeYlessExecutionNode parent = parentNodeStack.peekFirst(); - if (isConstraint(uri, localName, qName)) { - Object parentValue = parentVariableValueStack.peekFirst(); - if (parentValue != null) { - if (!(parentValue instanceof KeYlessValue)) { - throw new SAXException("Can't add constraint to variable."); - } - KeYlessConstraint constraint = new KeYlessConstraint(getName(attributes)); - ((KeYlessValue) parentValue).addConstraint(constraint); - } - else { - if (!(parent instanceof AbstractKeYlessExecutionNode)) { - throw new SAXException("Can't add constraint to non execution node."); - } - KeYlessConstraint constraint = new KeYlessConstraint(getName(attributes)); - ((AbstractKeYlessExecutionNode) parent).addConstraint(constraint); + // Parse XML file + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + SAXParser saxParser = factory.newSAXParser(); + SEDSAXHandler handler = new SEDSAXHandler(); + saxParser.parse(in, handler); + // Get root + IExecutionNode root = handler.getRoot(); + // Construct call stacks + Set, List>> entries = + handler.getCallStackPathEntries().entrySet(); + for (Entry, List> entry : entries) { + for (String path : entry.getValue()) { + IExecutionNode stackEntry = findNode(root, path); + if (stackEntry == null) { + throw new SAXException("Can't find call stack entry \"" + path + + "\" in parsed symbolic execution tree."); + } + entry.getKey().addCallStackEntry(stackEntry); + } + } + // Construct method returns + Set>> methodReturnEntries = + handler.getMethodReturnPathEntries().entrySet(); + for (Entry> entry : methodReturnEntries) { + for (String path : entry.getValue()) { + IExecutionNode returnEntry = findNode(root, path); + if (returnEntry == null) { + throw new SAXException("Can't find method return entry \"" + path + + "\" in parsed symbolic execution tree."); + } + if (!(returnEntry instanceof IExecutionBaseMethodReturn)) { + throw new SAXException("Expected basemethod return on \"" + path + + "\" but is " + returnEntry.getElementType() + "."); + } + entry.getKey().addMethodReturn((IExecutionBaseMethodReturn) returnEntry); + } + } + // Construct completed blocks + Set, List>>> completedBlockEntries = + handler.getCompletedBlockEntries().entrySet(); + for (Entry, List>> entry : completedBlockEntries) { + for (Pair pair : entry.getValue()) { + IExecutionNode returnEntry = findNode(root, pair.first); + if (returnEntry == null) { + throw new SAXException("Can't find completed block entry \"" + + pair.first + "\" in parsed symbolic execution tree."); + } else if (!(returnEntry instanceof IExecutionBlockStartNode)) { + throw new SAXException( + "Found completed block entry is not an instance of IExecutionBlockStartNode."); + } + entry.getKey().addCompletedBlock((IExecutionBlockStartNode) returnEntry, + pair.second); + } + } + // Construct block completions + Set, List>> blockCompletionEntries = + handler.getBlockCompletionEntries().entrySet(); + for (Entry, List> entry : blockCompletionEntries) { + for (String path : entry.getValue()) { + IExecutionNode returnEntry = findNode(root, path); + if (returnEntry == null) { + throw new SAXException("Can't find block completion entry \"" + path + + "\" in parsed symbolic execution tree."); + } + entry.getKey().addBlockCompletion(returnEntry); + } + } + // Construct links + Set, List>> outgoingLinks = + handler.getOutgoingLinks().entrySet(); + for (Entry, List> entry : outgoingLinks) { + for (String path : entry.getValue()) { + IExecutionNode target = findNode(root, path); + if (target == null) { + throw new SAXException("Can't find link targets \"" + path + + "\" in parsed symbolic execution tree."); + } + KeYLessLink link = new KeYLessLink(); + link.setSource(entry.getKey()); + link.setTarget(target); + entry.getKey().addOutgoingLink(link); + ((AbstractKeYlessExecutionNode) target).addIncomingLink(link); + } + } + // Construct terminations + Set>> terminationEntries = + handler.getTerminationPathEntries().entrySet(); + for (Entry> entry : terminationEntries) { + for (String path : entry.getValue()) { + IExecutionNode terminationEntry = findNode(root, path); + if (terminationEntry == null) { + throw new SAXException("Can't find termination entry \"" + path + + "\" in parsed symbolic execution tree."); + } + if (!(terminationEntry instanceof IExecutionTermination)) { + throw new SAXException("Expected termination on \"" + path + + "\" but is " + terminationEntry.getElementType() + "."); + } + entry.getKey().addTermination((IExecutionTermination) terminationEntry); + } + } + // Return result + return root; + } finally { + in.close(); } - } - else if (isCallStateVariable(uri, localName, qName)) { - Object parentValue = parentVariableValueStack.peekFirst(); - KeYlessVariable variable = createVariable(parentValue instanceof KeYlessValue ? (KeYlessValue)parentValue : null, uri, localName, qName, attributes); - if (parentValue != null) { - throw new SAXException("Can't add initial state variable to parent variable or value."); + } else { + return null; + } + } + + /** + * Searches the {@link IExecutionNode} starting at the given root which is defined by the path. + * + * @param root The {@link IExecutionNode} to start search. + * @param path The path. + * @return The found {@link IExecutionNode}. + * @throws SAXException If it was not possible to find the node. + */ + protected IExecutionNode findNode(IExecutionNode root, String path) throws SAXException { + if (path != null && !path.isEmpty()) { + StringTokenizer tokenizer = + new StringTokenizer(path, ExecutionNodeWriter.PATH_SEPARATOR + ""); + while (tokenizer.hasMoreTokens()) { + String next = tokenizer.nextToken(); + try { + int childIndex = Integer.parseInt(next); + if (childIndex < 0) { + throw new SAXException("Path segment \"" + next + "\" of path \"" + path + + "\" is a negative integer."); + } + IExecutionNode[] children = root.getChildren(); + if (childIndex >= children.length) { + throw new SAXException("Path segment \"" + next + "\" of path \"" + path + + "\" is outside of the child array range."); + } + root = children[childIndex]; + } catch (NumberFormatException e) { + throw new SAXException("Path segment \"" + next + "\" of path \"" + path + + "\" is no valid integer.", e); + } } - if (parent instanceof AbstractKeYlessBaseExecutionNode) { - ((AbstractKeYlessBaseExecutionNode) parent).addCallStateVariable(variable); + } + return root; + } + + /** + * {@link DefaultHandler} implementation used in {@link ExecutionNodeReader#read(InputStream)}. + * + * @author Martin Hentschel + */ + private class SEDSAXHandler extends DefaultHandler { + /** + * The root of the read symbolic execution tree. + */ + private IExecutionNode root; + + /** + * The parent hierarchy filled by {@link #startElement(String, String, String, Attributes)} + * and emptied by {@link #endElement(String, String, String)}. + */ + private final Deque> parentNodeStack = + new LinkedList>(); + + /** + * The parent hierarchy of {@link IExecutionVariable} and {@link IExecutionValue} filled by + * {@link #startElement(String, String, String, Attributes)} and emptied by + * {@link #endElement(String, String, String)}. + */ + private final Deque parentVariableValueStack = new LinkedList(); + + /** + * Maps an {@link AbstractKeYlessExecutionNode} to the path entries of its call stack. + */ + private final Map, List> callStackPathEntries = + new LinkedHashMap, List>(); + + /** + * Maps an {@link KeYlessMethodCall} to the path entries of its method returns. + */ + private final Map> methodReturnPathEntries = + new LinkedHashMap>(); + + /** + * Maps an {@link AbstractKeYlessExecutionNode} to its completed block entries + */ + private final Map, List>> completedBlockEntries = + new LinkedHashMap, List>>(); + + /** + * Maps an {@link AbstractKeYlessExecutionBlockStartNode} to the path entries of its block + * completions. + */ + private final Map, List> blockCompletionEntries = + new LinkedHashMap, List>(); + + /** + * Maps an {@link AbstractKeYlessExecutionNode} to the path entries of its outgoing links. + */ + private final Map, List> outgoingLinks = + new LinkedHashMap, List>(); + + /** + * Maps an {@link KeYlessStart} to the path entries of its terminations. + */ + private final Map> terminationPathEntries = + new LinkedHashMap>(); + + /** + * {@inheritDoc} + */ + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { + AbstractKeYlessExecutionNode parent = parentNodeStack.peekFirst(); + if (isConstraint(uri, localName, qName)) { + Object parentValue = parentVariableValueStack.peekFirst(); + if (parentValue != null) { + if (!(parentValue instanceof KeYlessValue)) { + throw new SAXException("Can't add constraint to variable."); + } + KeYlessConstraint constraint = new KeYlessConstraint(getName(attributes)); + ((KeYlessValue) parentValue).addConstraint(constraint); + } else { + if (!(parent instanceof AbstractKeYlessExecutionNode)) { + throw new SAXException("Can't add constraint to non execution node."); + } + KeYlessConstraint constraint = new KeYlessConstraint(getName(attributes)); + ((AbstractKeYlessExecutionNode) parent).addConstraint(constraint); + } + } else if (isCallStateVariable(uri, localName, qName)) { + Object parentValue = parentVariableValueStack.peekFirst(); + KeYlessVariable variable = createVariable( + parentValue instanceof KeYlessValue ? (KeYlessValue) parentValue : null, + uri, localName, qName, attributes); + if (parentValue != null) { + throw new SAXException( + "Can't add initial state variable to parent variable or value."); + } + if (parent instanceof AbstractKeYlessBaseExecutionNode) { + ((AbstractKeYlessBaseExecutionNode) parent).addCallStateVariable(variable); + } else { + throw new SAXException( + "Can't add call state variable to parent execution node."); + } + parentVariableValueStack.addFirst(variable); + } else if (isVariable(uri, localName, qName)) { + Object parentValue = parentVariableValueStack.peekFirst(); + KeYlessVariable variable = createVariable( + parentValue instanceof KeYlessValue ? (KeYlessValue) parentValue : null, + uri, localName, qName, attributes); + if (parentValue != null) { + ((KeYlessValue) parentValue).addChildVariable(variable); + } else { + if (parent != null) { + parent.addVariable(variable); + } else { + throw new SAXException("Can't add variable to parent execution node."); + } + } + parentVariableValueStack.addFirst(variable); + } else if (isValue(uri, localName, qName)) { + Object parentValue = parentVariableValueStack.peekFirst(); + if (!(parentValue instanceof KeYlessVariable)) { + throw new SAXException("Can't add value to parent variable."); + } + KeYlessValue value = createValue((KeYlessVariable) parentValue, uri, localName, + qName, attributes); + ((KeYlessVariable) parentValue).addValue(value); + parentVariableValueStack.addFirst(value); + } else if (isCallStackEntry(uri, localName, qName)) { + List callStackEntries = callStackPathEntries.get(parent); + if (callStackEntries == null) { + callStackEntries = new LinkedList(); + callStackPathEntries.put(parent, callStackEntries); + } + callStackEntries.add(getPathInTree(attributes)); + } else if (isMethodReturnEntry(uri, localName, qName)) { + List methodReturnEntries = methodReturnPathEntries.get(parent); + if (methodReturnEntries == null) { + methodReturnEntries = new LinkedList(); + methodReturnPathEntries.put((KeYlessMethodCall) parent, methodReturnEntries); + } + methodReturnEntries.add(0, getPathInTree(attributes)); + } else if (isCompletedBlockEntry(uri, localName, qName)) { + List> completedBlocks = completedBlockEntries.get(parent); + if (completedBlocks == null) { + completedBlocks = new LinkedList>(); + completedBlockEntries.put(parent, completedBlocks); + } + completedBlocks.add(new Pair(getPathInTree(attributes), + getConditionString(attributes))); + } else if (isBlockCompletionEntry(uri, localName, qName)) { + List blockCompletionPathEntries = blockCompletionEntries.get(parent); + if (blockCompletionPathEntries == null) { + blockCompletionPathEntries = new LinkedList(); + blockCompletionEntries.put((AbstractKeYlessExecutionBlockStartNode) parent, + blockCompletionPathEntries); + } + blockCompletionPathEntries.add(getPathInTree(attributes)); + } else if (isOutgoingLink(uri, localName, qName)) { + List linkPaths = outgoingLinks.get(parent); + if (linkPaths == null) { + linkPaths = new LinkedList(); + outgoingLinks.put((AbstractKeYlessExecutionNode) parent, linkPaths); + } + linkPaths.add(getPathInTree(attributes)); + } else if (isTerminationEntry(uri, localName, qName)) { + List terminationEntries = terminationPathEntries.get(parent); + if (terminationEntries == null) { + terminationEntries = new LinkedList(); + terminationPathEntries.put((KeYlessStart) parent, terminationEntries); + } + terminationEntries.add(0, getPathInTree(attributes)); + } else if (isMethodReturnValue(uri, localName, qName)) { + Object parentValue = parentNodeStack.peekFirst(); + if (!(parentValue instanceof KeYlessMethodReturn)) { + throw new SAXException("Can't add method return value to parent."); + } + KeYlessMethodReturnValue returnValue = + createMethodReturnValue(uri, localName, qName, attributes); + ((KeYlessMethodReturn) parentValue).addReturnValue(returnValue); + } else { + AbstractKeYlessExecutionNode child = + createExecutionNode(parent, uri, localName, qName, attributes); + if (root == null) { + root = child; + } + if (parent != null) { + parent.addChild(child); + } + parentNodeStack.addFirst(child); } - else { - throw new SAXException("Can't add call state variable to parent execution node."); + } + + /** + * {@inheritDoc} + */ + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + if (isConstraint(uri, localName, qName)) { + // Nothing to do. + } else if (isCallStateVariable(uri, localName, qName)) { + parentVariableValueStack.removeFirst(); + } else if (isVariable(uri, localName, qName)) { + parentVariableValueStack.removeFirst(); + } else if (isValue(uri, localName, qName)) { + parentVariableValueStack.removeFirst(); + } else if (isCallStackEntry(uri, localName, qName)) { + // Nothing to do. + } else if (isMethodReturnEntry(uri, localName, qName)) { + // Nothing to do. + } else if (isCompletedBlockEntry(uri, localName, qName)) { + // Nothing to do. + } else if (isBlockCompletionEntry(uri, localName, qName)) { + // Nothing to do. + } else if (isOutgoingLink(uri, localName, qName)) { + // Nothing to do. + } else if (isTerminationEntry(uri, localName, qName)) { + // Nothing to do. + } else if (isMethodReturnValue(uri, localName, qName)) { + // Nothing to do. + } else { + parentNodeStack.removeFirst(); } - parentVariableValueStack.addFirst(variable); - } - else if (isVariable(uri, localName, qName)) { - Object parentValue = parentVariableValueStack.peekFirst(); - KeYlessVariable variable = createVariable(parentValue instanceof KeYlessValue ? (KeYlessValue)parentValue : null, uri, localName, qName, attributes); - if (parentValue != null) { - ((KeYlessValue)parentValue).addChildVariable(variable); - } - else { - if (parent != null) { - parent.addVariable(variable); - } - else { - throw new SAXException("Can't add variable to parent execution node."); - } - } - parentVariableValueStack.addFirst(variable); - } - else if (isValue(uri, localName, qName)) { - Object parentValue = parentVariableValueStack.peekFirst(); - if (!(parentValue instanceof KeYlessVariable)) { - throw new SAXException("Can't add value to parent variable."); - } - KeYlessValue value = createValue((KeYlessVariable)parentValue, uri, localName, qName, attributes); - ((KeYlessVariable)parentValue).addValue(value); - parentVariableValueStack.addFirst(value); - } - else if (isCallStackEntry(uri, localName, qName)) { - List callStackEntries = callStackPathEntries.get(parent); - if (callStackEntries == null) { - callStackEntries = new LinkedList(); - callStackPathEntries.put(parent, callStackEntries); - } - callStackEntries.add(getPathInTree(attributes)); - } - else if (isMethodReturnEntry(uri, localName, qName)) { - List methodReturnEntries = methodReturnPathEntries.get(parent); - if (methodReturnEntries == null) { - methodReturnEntries = new LinkedList(); - methodReturnPathEntries.put((KeYlessMethodCall)parent, methodReturnEntries); - } - methodReturnEntries.add(0, getPathInTree(attributes)); - } - else if (isCompletedBlockEntry(uri, localName, qName)) { - List> completedBlocks = completedBlockEntries.get(parent); - if (completedBlocks == null) { - completedBlocks = new LinkedList>(); - completedBlockEntries.put(parent, completedBlocks); - } - completedBlocks.add(new Pair(getPathInTree(attributes), getConditionString(attributes))); - } - else if (isBlockCompletionEntry(uri, localName, qName)) { - List blockCompletionPathEntries = blockCompletionEntries.get(parent); - if (blockCompletionPathEntries == null) { - blockCompletionPathEntries = new LinkedList(); - blockCompletionEntries.put((AbstractKeYlessExecutionBlockStartNode)parent, blockCompletionPathEntries); - } - blockCompletionPathEntries.add(getPathInTree(attributes)); - } - else if (isOutgoingLink(uri, localName, qName)) { - List linkPaths = outgoingLinks.get(parent); - if (linkPaths == null) { - linkPaths = new LinkedList(); - outgoingLinks.put((AbstractKeYlessExecutionNode)parent, linkPaths); - } - linkPaths.add(getPathInTree(attributes)); - } - else if (isTerminationEntry(uri, localName, qName)) { - List terminationEntries = terminationPathEntries.get(parent); - if (terminationEntries == null) { - terminationEntries = new LinkedList(); - terminationPathEntries.put((KeYlessStart)parent, terminationEntries); - } - terminationEntries.add(0, getPathInTree(attributes)); - } - else if (isMethodReturnValue(uri, localName, qName)) { - Object parentValue = parentNodeStack.peekFirst(); - if (!(parentValue instanceof KeYlessMethodReturn)) { - throw new SAXException("Can't add method return value to parent."); + } + + /** + * Returns the root of the read symbolic execution tree. + * + * @return The root of the read symbolic execution tree. + */ + public IExecutionNode getRoot() { + return root; + } + + /** + * Returns the mapping of an {@link AbstractKeYlessExecutionNode} to its call stack entries. + * + * @return The mapping of an {@link AbstractKeYlessExecutionNode} to its call stack entries. + */ + public Map, List> getCallStackPathEntries() { + return callStackPathEntries; + } + + /** + * Returns the mapping of a {@link KeYlessMethodCall} to its method return entries. + * + * @return The mapping of a {@link KeYlessMethodCall} to its method return entries. + */ + public Map> getMethodReturnPathEntries() { + return methodReturnPathEntries; + } + + /** + * Returns the mapping of {@link AbstractKeYlessExecutionNode} to its completed block + * entries. + * + * @return The mapping of {@link AbstractKeYlessExecutionNode} to its completed block + * entries. + */ + public Map, List>> getCompletedBlockEntries() { + return completedBlockEntries; + } + + /** + * Returns the mapping of an {@link AbstractKeYlessExecutionBlockStartNode} to its block + * completion entries. + * + * @return The mapping of an {@link AbstractKeYlessExecutionBlockStartNode} to its block + * completion entries. + */ + public Map, List> getBlockCompletionEntries() { + return blockCompletionEntries; + } + + /** + * Returns the mapping of a {@link KeYlessStart} to its termination entries. + * + * @return The mapping of a {@link KeYlessStart} to its termination entries. + */ + public Map> getTerminationPathEntries() { + return terminationPathEntries; + } + + /** + * Returns the mapping of an {@link AbstractKeYlessExecutionNode} to its outgoing links. + * + * @return The mapping of an {@link AbstractKeYlessExecutionNode} to its outgoing links. + */ + public Map, List> getOutgoingLinks() { + return outgoingLinks; + } + } + + /** + * Checks if the currently parsed tag represents an {@link IExecutionConstraint}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link IExecutionConstraint}, {@code false} is something + * else. + */ + protected boolean isConstraint(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_CONSTRAINT.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link IExecutionVariable}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link IExecutionVariable}, {@code false} is something + * else. + */ + protected boolean isVariable(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_VARIABLE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link IExecutionVariable}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link IExecutionVariable}, {@code false} is something + * else. + */ + protected boolean isCallStateVariable(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_CALL_STATE_VARIABLE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link IExecutionMethodReturnValue}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link IExecutionMethodReturnValue}, {@code false} is + * something else. + */ + protected boolean isMethodReturnValue(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_METHOD_RETURN_VALUE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link IExecutionValue}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link IExecutionValue}, {@code false} is something else. + */ + protected boolean isValue(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_VALUE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionNode#getCallStack()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents call stack entry, {@code false} is something else. + */ + protected boolean isCallStackEntry(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_CALL_STACK_ENTRY.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionMethodCall#getMethodReturns()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents method return entry, {@code false} is something else. + */ + protected boolean isMethodReturnEntry(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_METHOD_RETURN_ENTRY.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionNode#getCompletedBlocks()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents completed block entry, {@code false} is something else. + */ + protected boolean isCompletedBlockEntry(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_COMPLETED_BLOCK_ENTRY.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionNode#getOutgoingLinks()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents block completion entry, {@code false} is something else. + */ + protected boolean isOutgoingLink(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_OUTGOING_LINK.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionBranchStatement#getBlockCompletions()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents block completion entry, {@code false} is something else. + */ + protected boolean isBlockCompletionEntry(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_BLOCK_COMPLETION_ENTRY.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an entry of + * {@link IExecutionStart#getTerminations()}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents termination entry, {@code false} is something else. + */ + protected boolean isTerminationEntry(String uri, String localName, String qName) { + return ExecutionNodeWriter.TAG_TERMINATION_ENTRY.equals(qName); + } + + /** + * Creates a new {@link IExecutionVariable} with the given content. + * + * @param parentValue The parent {@link IExecutionValue}. + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @param attributes The attributes. + * @return The created {@link IExecutionVariable}. + */ + protected KeYlessVariable createVariable(IExecutionValue parentValue, String uri, + String localName, String qName, Attributes attributes) { + return new KeYlessVariable(parentValue, isArrayIndex(attributes), + getArrayIndexString(attributes), getName(attributes)); + } + + /** + * Creates a new {@link IExecutionMethodReturnValue} with the given content. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @param attributes The attributes. + * @return The created {@link IExecutionMethodReturnValue}. + */ + public KeYlessMethodReturnValue createMethodReturnValue(String uri, String localName, + String qName, Attributes attributes) { + return new KeYlessMethodReturnValue(getName(attributes), getReturnValueString(attributes), + getHasCondition(attributes), getConditionString(attributes)); + } + + /** + * Creates a new {@link IExecutionValue} with the given content. + * + * @param parentVariable The parent {@link IExecutionVariable}. + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @param attributes The attributes. + * @return The created {@link IExecutionValue}. + */ + protected KeYlessValue createValue(IExecutionVariable parentVariable, String uri, + String localName, String qName, Attributes attributes) { + return new KeYlessValue(parentVariable, getTypeString(attributes), + getValueString(attributes), getName(attributes), isValueUnknown(attributes), + isValueAnObject(attributes), getConditionString(attributes)); + } + + /** + * Creates a new {@link IExecutionNode} with the given content. + * + * @param parent The parent {@link IExecutionNode}. + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @param attributes The attributes. + * @return The created {@link IExecutionNode}. + * @throws SAXException Occurred Exception. + */ + protected AbstractKeYlessExecutionNode createExecutionNode(IExecutionNode parent, + String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (ExecutionNodeWriter.TAG_BRANCH_CONDITION.equals(qName)) { + return new KeYlessBranchCondition(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + getBranchCondition(attributes), isMergedBranchCondition(attributes), + isBranchConditionComputed(attributes), getAdditionalBranchLabel(attributes)); + } else if (ExecutionNodeWriter.TAG_BRANCH_STATEMENT.equals(qName)) { + return new KeYlessBranchStatement(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isBlockOpened(attributes)); + } else if (ExecutionNodeWriter.TAG_LOOP_CONDITION.equals(qName)) { + return new KeYlessLoopCondition(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isBlockOpened(attributes)); + } else if (ExecutionNodeWriter.TAG_LOOP_STATEMENT.equals(qName)) { + return new KeYlessLoopStatement(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isBlockOpened(attributes)); + } else if (ExecutionNodeWriter.TAG_METHOD_CALL.equals(qName)) { + return new KeYlessMethodCall(parent, getName(attributes), getPathCondition(attributes), + isPathConditionChanged(attributes)); + } else if (ExecutionNodeWriter.TAG_METHOD_RETURN.equals(qName)) { + return new KeYlessMethodReturn(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + getNameIncludingReturnValue(attributes), getSignature(attributes), + getSignatureIncludingReturnValue(attributes), isReturnValueComputed(attributes), + getMethodReturnCondition(attributes)); + } else if (ExecutionNodeWriter.TAG_EXCEPTIONAL_METHOD_RETURN.equals(qName)) { + return new KeYlessExceptionalMethodReturn(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + getSignature(attributes), getMethodReturnCondition(attributes)); + } else if (ExecutionNodeWriter.TAG_START.equals(qName)) { + return new KeYlessStart(getName(attributes), getPathCondition(attributes), + isPathConditionChanged(attributes)); + } else if (ExecutionNodeWriter.TAG_STATEMENT.equals(qName)) { + return new KeYlessStatement(parent, getName(attributes), getPathCondition(attributes), + isPathConditionChanged(attributes)); + } else if (ExecutionNodeWriter.TAG_TERMINATION.equals(qName)) { + return new KeYlessTermination(parent, getName(attributes), getPathCondition(attributes), + isPathConditionChanged(attributes), getTerminationKind(attributes), + getBranchVerified(attributes)); + } else if (ExecutionNodeWriter.TAG_OPERATION_CONTRACT.equals(qName)) { + return new KeYlessOperationContract(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isPreconditionComplied(attributes), isHasNotNullCheck(attributes), + isNotNullCheckComplied(attributes), getResultTerm(attributes), + getExceptionTerm(attributes), getSelfTerm(attributes), + getContractParameters(attributes)); + } else if (ExecutionNodeWriter.TAG_LOOP_INVARIANT.equals(qName)) { + return new KeYlessLoopInvariant(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isInitiallyValid(attributes)); + } else if (ExecutionNodeWriter.TAG_BLOCK_CONTRACT.equals(qName)) { + return new KeYlessBlockContract(parent, getName(attributes), + getPathCondition(attributes), isPathConditionChanged(attributes), + isPreconditionComplied(attributes)); + } else if (ExecutionNodeWriter.TAG_JOIN.equals(qName)) { + return new KeYlessJoin(parent, getName(attributes), getPathCondition(attributes), + isPathConditionChanged(attributes), isWeakeningVerified(attributes)); + } else { + throw new SAXException("Unknown tag \"" + qName + "\"."); + } + } + + /** + * Returns the additional branch label value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getAdditionalBranchLabel(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_ADDITIONAL_BRANCH_LABEL); + } + + /** + * Returns the path in tree value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getPathInTree(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_IN_TREE); + } + + /** + * Returns the name value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getName(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NAME); + } + + /** + * Returns the name value including return value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getNameIncludingReturnValue(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE); + } + + /** + * Returns the signature value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getSignature(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SIGNATURE); + } + + /** + * Returns the signature value including return value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getSignatureIncludingReturnValue(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE); + } + + /** + * Returns the termination kind value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected TerminationKind getTerminationKind(Attributes attributes) { + return TerminationKind + .valueOf(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_TERMINATION_KIND)); + } + + /** + * Returns the precondition complied value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isPreconditionComplied(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PRECONDITION_COMPLIED)); + } + + /** + * Returns the has not null check value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isHasNotNullCheck(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_HAS_NOT_NULL_CHECK)); + } + + /** + * Returns the block opened value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isBlockOpened(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BLOCK_OPENED)); + } + + /** + * Returns the is return value computed value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isReturnValueComputed(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RETURN_VALUE_COMPUTED)); + } + + /** + * Returns the is branch condition computed value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isBranchConditionComputed(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_CONDITION_COMPUTED)); + } + + /** + * Returns the not null check complied value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isNotNullCheckComplied(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NOT_NULL_CHECK_COMPLIED)); + } + + /** + * Returns the initially valid value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isInitiallyValid(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_INITIALLY_VALID)); + } + + /** + * Returns the is value an object value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isValueAnObject(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_VALUE_AN_OBJECT)); + } + + /** + * Returns if the weakening is verified. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isWeakeningVerified(Attributes attributes) { + return Boolean.parseBoolean( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_WEAKENING_VERIFIED)); + } + + /** + * Returns the is value unknown value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isValueUnknown(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_VALUE_UNKNOWN)); + } + + /** + * Returns the value string value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getValueString(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_VALUE_STRING); + } + + /** + * Returns the value condition string value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getConditionString(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_CONDITION_STRING); + } + + /** + * Returns the is has condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean getHasCondition(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_HAS_CONDITION)); + } + + /** + * Returns the is branch verified value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean getBranchVerified(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_VERIFIED)); + } + + /** + * Returns the return value string value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getReturnValueString(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RETURN_VALUE_STRING); + } + + /** + * Returns the type string value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getTypeString(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_TYPE_STRING); + } + + /** + * Returns the exception term value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getExceptionTerm(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_EXCEPTION_TERM); + } + + /** + * Returns the result term value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getResultTerm(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RESULT_TERM); + } + + /** + * Returns the self term value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getSelfTerm(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SELF_TERM); + } + + /** + * Returns the contract parameters value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getContractParameters(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_CONTRACT_PARAMETERS); + } + + /** + * Returns the array index value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getArrayIndexString(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_ARRAY_INDEX); + } + + /** + * Returns the is array index value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isArrayIndex(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_ARRAY_INDEX)); + } + + /** + * Returns the branch condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getBranchCondition(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_CONDITION); + } + + /** + * Returns the path condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getPathCondition(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_CONDITION); + } + + /** + * Returns the method return condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getMethodReturnCondition(Attributes attributes) { + return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_METHOD_RETURN_CONDITION); + } + + /** + * Returns the path condition changed value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isPathConditionChanged(Attributes attributes) { + return Boolean + .valueOf(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_CONDITION_CHANGED)); + } + + /** + * Returns the merged branch condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isMergedBranchCondition(Attributes attributes) { + return Boolean.valueOf( + attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_MERGED_BRANCH_CONDITION)); + } + + /** + * An abstract implementation of {@link IExecutionElement} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessExecutionElement implements IExecutionElement { + /** + * The name. + */ + private final String name; + + /** + * Constructor. + * + * @param name The name of this node. + */ + public AbstractKeYlessExecutionElement(String name) { + this.name = name; + } + + /** + * {@inheritDoc} + */ + @Override + public Services getServices() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public InitConfig getInitConfig() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Proof getProof() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public RuleApp getAppliedRuleApp() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Node getProofNode() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public NodeInfo getProofNodeInfo() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return getElementType() + " " + getName(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDisposed() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public ITreeSettings getSettings() { + return null; + } + } + + /** + * An abstract implementation of {@link IExecutionNode} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessExecutionNode + extends AbstractKeYlessExecutionElement implements IExecutionNode { + /** + * The parent {@link IExecutionNode}. + */ + private final IExecutionNode parent; + + /** + * The children. + */ + private final List> children = new LinkedList>(); + + /** + * The formated path condition. + */ + private final String formatedPathCondition; + + /** + * Is the path condition changed compared to parent? + */ + private final boolean pathConditionChanged; + + /** + * The call stack. + */ + private final List> callStack = new LinkedList>(); + + /** + * The contained constraints. + */ + private final List constraints = + new LinkedList(); + + /** + * The contained variables. + */ + private final List variables = new LinkedList(); + + /** + * The completed blocks. + */ + private ImmutableList> completedBlocks = ImmutableSLList.nil(); + + /** + * The formated conditions under which a block is completed. + */ + private final Map, String> formatedCompletedBlockConditions = + new LinkedHashMap, String>(); + + /** + * The contained outgoing links. + */ + private ImmutableList outgoingLinks = ImmutableSLList.nil(); + + /** + * The contained incoming links. + */ + private ImmutableList incomingLinks = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + */ + public AbstractKeYlessExecutionNode(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged) { + super(name); + this.parent = parent; + this.formatedPathCondition = formatedPathCondition; + this.pathConditionChanged = pathConditionChanged; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode getParent() { + return parent; + } + + /** + * Adds the given child. + * + * @param child The child to add. + */ + public void addChild(IExecutionNode child) { + children.add(child); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode[] getChildren() { + return children.toArray(new IExecutionNode[children.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public Term getPathCondition() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedPathCondition() throws ProofInputException { + return formatedPathCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPathConditionChanged() { + return pathConditionChanged; + } + + /** + * Adds the given entry to the call stack. + * + * @param entry The entry to add to the call stack. + */ + public void addCallStackEntry(IExecutionNode entry) { + callStack.add(entry); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode[] getCallStack() { + return callStack.isEmpty() ? null + : callStack.toArray(new IExecutionNode[callStack.size()]); + } + + /** + * Adds the given {@link IExecutionConstraint}. + * + * @param constraint The {@link IExecutionConstraint} to add. + */ + public void addConstraint(IExecutionConstraint constraint) { + constraints.add(constraint); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionConstraint[] getConstraints() { + return constraints.toArray(new IExecutionConstraint[constraints.size()]); + } + + /** + * Adds the given {@link IExecutionVariable}. + * + * @param variable The {@link IExecutionVariable} to add. + */ + public void addVariable(IExecutionVariable variable) { + variables.add(variable); + } + + /** + * {@inheritDoc} + */ + @Override + public S getActiveStatement() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PositionInfo getActivePositionInfo() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getVariables() { + return variables.toArray(new IExecutionVariable[variables.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getVariables(Term condition) { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public int getLayoutsCount() throws ProofInputException { + return 0; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicLayout getInitialLayout(int configurationIndex) throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicLayout getCurrentLayout(int configurationIndex) throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getLayoutsEquivalenceClasses( + int configurationIndex) throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getCompletedBlocks() { + return completedBlocks; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException { + return formatedCompletedBlockConditions.get(completedNode); + } + + /** + * Adds the given completed block. + * + * @param completedBlock The completed block. + * @param formatedCondition The formated condition under which the block is completed. + */ + public void addCompletedBlock(IExecutionBlockStartNode completedBlock, + String formatedCondition) { + if (completedBlock != null) { + completedBlocks = completedBlocks.append(completedBlock); + formatedCompletedBlockConditions.put(completedBlock, formatedCondition); } - KeYlessMethodReturnValue returnValue = createMethodReturnValue(uri, localName, qName, attributes); - ((KeYlessMethodReturn)parentValue).addReturnValue(returnValue); - } - else { - AbstractKeYlessExecutionNode child = createExecutionNode(parent, uri, localName, qName, attributes); - if (root == null) { - root = child; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionLink getOutgoingLink(final IExecutionNode target) { + return CollectionUtil.search(outgoingLinks, new IFilter() { + @Override + public boolean select(IExecutionLink element) { + return element.getTarget() == target; + } + }); + } + + /** + * Adds the outgoing {@link IExecutionLink}. + * + * @param link The outgoing {@link IExecutionLink} to add. + */ + public void addOutgoingLink(IExecutionLink link) { + outgoingLinks = outgoingLinks.append(link); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getOutgoingLinks() { + return outgoingLinks; + } + + /** + * Adds the incoming {@link IExecutionLink}. + * + * @param link The incoming {@link IExecutionLink} to add. + */ + public void addIncomingLink(IExecutionLink link) { + incomingLinks = incomingLinks.append(link); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionLink getIncomingLink(final IExecutionNode source) { + return CollectionUtil.search(incomingLinks, new IFilter() { + @Override + public boolean select(IExecutionLink element) { + return element.getSource() == source; + } + }); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getIncomingLinks() { + return incomingLinks; + } + } + + /** + * An abstract implementation of {@link IExecutionBlockStartNode} which is independent from KeY + * and provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessExecutionBlockStartNode + extends AbstractKeYlessExecutionNode implements IExecutionBlockStartNode { + /** + * The block completions. + */ + private ImmutableList> blockCompletions = ImmutableSLList.nil(); + + /** + * Is a block opened? + */ + private final boolean blockOpened; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param blockOpened {@code false} block is definitively not opened, {@code true} block is + * or might be opened. + */ + public AbstractKeYlessExecutionBlockStartNode(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, boolean blockOpened) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.blockOpened = blockOpened; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getBlockCompletions() { + return blockCompletions; + } + + /** + * Adds the given block completion. + * + * @param blockCompletion The block completion to add. + */ + public void addBlockCompletion(IExecutionNode blockCompletion) { + if (blockCompletion != null) { + blockCompletions = blockCompletions.append(blockCompletion); } - if (parent != null) { - parent.addChild(child); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBlockOpened() { + return blockOpened; + } + } + + /** + * An implementation of {@link IExecutionLoopCondition} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessBranchCondition extends AbstractKeYlessExecutionNode + implements IExecutionBranchCondition { + /** + * The formated branch condition. + */ + private final String formatedBranchCondition; + + /** + * Merged branch condition? + */ + private final boolean mergedBranchCondition; + + /** + * Indicates if branch condition is computed or not. + */ + private final boolean branchConditionComputed; + + /** + * The optional additional branch label. + */ + private final String additionalBranchLabel; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedBranchCondition The formated branch condition. + * @param mergedBranchCondition Merged branch condition? + * @param branchConditionComputed Is branch condition computed? + * @param additionalBranchLabel The optional additional branch label. + */ + public KeYlessBranchCondition(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + String formatedBranchCondition, boolean mergedBranchCondition, + boolean branchConditionComputed, String additionalBranchLabel) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.formatedBranchCondition = formatedBranchCondition; + this.mergedBranchCondition = mergedBranchCondition; + this.branchConditionComputed = branchConditionComputed; + this.additionalBranchLabel = additionalBranchLabel; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Branch Condition"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getBranchCondition() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedBranchCondition() { + return formatedBranchCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isMergedBranchCondition() { + return mergedBranchCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public Node[] getMergedProofNodes() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term[] getMergedBranchCondtions() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBranchConditionComputed() { + return branchConditionComputed; + } + + /** + * {@inheritDoc} + */ + @Override + public String getAdditionalBranchLabel() { + return additionalBranchLabel; + } + } + + /** + * An implementation of {@link IExecutionStart} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessStart extends AbstractKeYlessExecutionNode + implements IExecutionStart { + /** + * The up to now discovered {@link IExecutionTermination}s. + */ + private ImmutableList terminations = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + */ + public KeYlessStart(String name, String formatedPathCondition, + boolean pathConditionChanged) { + super(null, name, formatedPathCondition, pathConditionChanged); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Start"; + } + + /** + * Adds the given {@link IExecutionTermination}. + * + * @param termination The {@link IExecutionTermination} to add. + */ + public void addTermination(IExecutionTermination termination) { + if (termination != null) { + terminations = terminations.prepend(termination); } - parentNodeStack.addFirst(child); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - if (isConstraint(uri, localName, qName)) { - // Nothing to do. - } - else if (isCallStateVariable(uri, localName, qName)) { - parentVariableValueStack.removeFirst(); - } - else if (isVariable(uri, localName, qName)) { - parentVariableValueStack.removeFirst(); - } - else if (isValue(uri, localName, qName)) { - parentVariableValueStack.removeFirst(); - } - else if (isCallStackEntry(uri, localName, qName)) { - // Nothing to do. - } - else if (isMethodReturnEntry(uri, localName, qName)) { - // Nothing to do. - } - else if (isCompletedBlockEntry(uri, localName, qName)) { - // Nothing to do. - } - else if (isBlockCompletionEntry(uri, localName, qName)) { - // Nothing to do. - } - else if (isOutgoingLink(uri, localName, qName)) { - // Nothing to do. - } - else if (isTerminationEntry(uri, localName, qName)) { - // Nothing to do. - } - else if (isMethodReturnValue(uri, localName, qName)) { - // Nothing to do. - } - else { - parentNodeStack.removeFirst(); - } - } - - /** - * Returns the root of the read symbolic execution tree. - * @return The root of the read symbolic execution tree. - */ - public IExecutionNode getRoot() { - return root; - } - - /** - * Returns the mapping of an {@link AbstractKeYlessExecutionNode} to its call stack entries. - * @return The mapping of an {@link AbstractKeYlessExecutionNode} to its call stack entries. - */ - public Map, List> getCallStackPathEntries() { - return callStackPathEntries; - } - - /** - * Returns the mapping of a {@link KeYlessMethodCall} to its method return entries. - * @return The mapping of a {@link KeYlessMethodCall} to its method return entries. - */ - public Map> getMethodReturnPathEntries() { - return methodReturnPathEntries; - } - - /** - * Returns the mapping of {@link AbstractKeYlessExecutionNode} to its completed block entries. - * @return The mapping of {@link AbstractKeYlessExecutionNode} to its completed block entries. - */ - public Map, List>> getCompletedBlockEntries() { - return completedBlockEntries; - } - - /** - * Returns the mapping of an {@link AbstractKeYlessExecutionBlockStartNode} to its block completion entries. - * @return The mapping of an {@link AbstractKeYlessExecutionBlockStartNode} to its block completion entries. - */ - public Map, List> getBlockCompletionEntries() { - return blockCompletionEntries; - } - - /** - * Returns the mapping of a {@link KeYlessStart} to its termination entries. - * @return The mapping of a {@link KeYlessStart} to its termination entries. - */ - public Map> getTerminationPathEntries() { - return terminationPathEntries; - } - - /** - * Returns the mapping of an {@link AbstractKeYlessExecutionNode} to its outgoing links. - * @return The mapping of an {@link AbstractKeYlessExecutionNode} to its outgoing links. - */ - public Map, List> getOutgoingLinks() { - return outgoingLinks; - } - } - - /** - * Checks if the currently parsed tag represents an {@link IExecutionConstraint}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link IExecutionConstraint}, {@code false} is something else. - */ - protected boolean isConstraint(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_CONSTRAINT.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link IExecutionVariable}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link IExecutionVariable}, {@code false} is something else. - */ - protected boolean isVariable(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_VARIABLE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link IExecutionVariable}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link IExecutionVariable}, {@code false} is something else. - */ - protected boolean isCallStateVariable(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_CALL_STATE_VARIABLE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link IExecutionMethodReturnValue}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link IExecutionMethodReturnValue}, {@code false} is something else. - */ - protected boolean isMethodReturnValue(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_METHOD_RETURN_VALUE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link IExecutionValue}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link IExecutionValue}, {@code false} is something else. - */ - protected boolean isValue(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_VALUE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionNode#getCallStack()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents call stack entry, {@code false} is something else. - */ - protected boolean isCallStackEntry(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_CALL_STACK_ENTRY.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionMethodCall#getMethodReturns()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents method return entry, {@code false} is something else. - */ - protected boolean isMethodReturnEntry(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_METHOD_RETURN_ENTRY.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionNode#getCompletedBlocks()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents completed block entry, {@code false} is something else. - */ - protected boolean isCompletedBlockEntry(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_COMPLETED_BLOCK_ENTRY.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionNode#getOutgoingLinks()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents block completion entry, {@code false} is something else. - */ - protected boolean isOutgoingLink(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_OUTGOING_LINK.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionBranchStatement#getBlockCompletions()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents block completion entry, {@code false} is something else. - */ - protected boolean isBlockCompletionEntry(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_BLOCK_COMPLETION_ENTRY.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an entry of {@link IExecutionStart#getTerminations()}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents termination entry, {@code false} is something else. - */ - protected boolean isTerminationEntry(String uri, String localName, String qName) { - return ExecutionNodeWriter.TAG_TERMINATION_ENTRY.equals(qName); - } - - /** - * Creates a new {@link IExecutionVariable} with the given content. - * @param parentValue The parent {@link IExecutionValue}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @param attributes The attributes. - * @return The created {@link IExecutionVariable}. - */ - protected KeYlessVariable createVariable(IExecutionValue parentValue, - String uri, - String localName, - String qName, - Attributes attributes) { - return new KeYlessVariable(parentValue, - isArrayIndex(attributes), - getArrayIndexString(attributes), - getName(attributes)); - } - - /** - * Creates a new {@link IExecutionMethodReturnValue} with the given content. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @param attributes The attributes. - * @return The created {@link IExecutionMethodReturnValue}. - */ - public KeYlessMethodReturnValue createMethodReturnValue(String uri, - String localName, - String qName, - Attributes attributes) { - return new KeYlessMethodReturnValue(getName(attributes), - getReturnValueString(attributes), - getHasCondition(attributes), - getConditionString(attributes)); - } - - /** - * Creates a new {@link IExecutionValue} with the given content. - * @param parentVariable The parent {@link IExecutionVariable}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @param attributes The attributes. - * @return The created {@link IExecutionValue}. - */ - protected KeYlessValue createValue(IExecutionVariable parentVariable, - String uri, - String localName, - String qName, - Attributes attributes) { - return new KeYlessValue(parentVariable, - getTypeString(attributes), - getValueString(attributes), - getName(attributes), - isValueUnknown(attributes), - isValueAnObject(attributes), - getConditionString(attributes)); - } - - /** - * Creates a new {@link IExecutionNode} with the given content. - * @param parent The parent {@link IExecutionNode}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @param attributes The attributes. - * @return The created {@link IExecutionNode}. - * @throws SAXException Occurred Exception. - */ - protected AbstractKeYlessExecutionNode createExecutionNode(IExecutionNode parent, String uri, String localName, String qName, Attributes attributes) throws SAXException { - if (ExecutionNodeWriter.TAG_BRANCH_CONDITION.equals(qName)) { - return new KeYlessBranchCondition(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), getBranchCondition(attributes), isMergedBranchCondition(attributes), isBranchConditionComputed(attributes), getAdditionalBranchLabel(attributes)); - } - else if (ExecutionNodeWriter.TAG_BRANCH_STATEMENT.equals(qName)) { - return new KeYlessBranchStatement(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isBlockOpened(attributes)); - } - else if (ExecutionNodeWriter.TAG_LOOP_CONDITION.equals(qName)) { - return new KeYlessLoopCondition(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isBlockOpened(attributes)); - } - else if (ExecutionNodeWriter.TAG_LOOP_STATEMENT.equals(qName)) { - return new KeYlessLoopStatement(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isBlockOpened(attributes)); - } - else if (ExecutionNodeWriter.TAG_METHOD_CALL.equals(qName)) { - return new KeYlessMethodCall(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes)); - } - else if (ExecutionNodeWriter.TAG_METHOD_RETURN.equals(qName)) { - return new KeYlessMethodReturn(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), getNameIncludingReturnValue(attributes), getSignature(attributes), getSignatureIncludingReturnValue(attributes), isReturnValueComputed(attributes), getMethodReturnCondition(attributes)); - } - else if (ExecutionNodeWriter.TAG_EXCEPTIONAL_METHOD_RETURN.equals(qName)) { - return new KeYlessExceptionalMethodReturn(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), getSignature(attributes), getMethodReturnCondition(attributes)); - } - else if (ExecutionNodeWriter.TAG_START.equals(qName)) { - return new KeYlessStart(getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes)); - } - else if (ExecutionNodeWriter.TAG_STATEMENT.equals(qName)) { - return new KeYlessStatement(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes)); - } - else if (ExecutionNodeWriter.TAG_TERMINATION.equals(qName)) { - return new KeYlessTermination(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), getTerminationKind(attributes), getBranchVerified(attributes)); - } - else if (ExecutionNodeWriter.TAG_OPERATION_CONTRACT.equals(qName)) { - return new KeYlessOperationContract(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isPreconditionComplied(attributes), isHasNotNullCheck(attributes), isNotNullCheckComplied(attributes), getResultTerm(attributes), getExceptionTerm(attributes), getSelfTerm(attributes), getContractParameters(attributes)); - } - else if (ExecutionNodeWriter.TAG_LOOP_INVARIANT.equals(qName)) { - return new KeYlessLoopInvariant(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isInitiallyValid(attributes)); - } - else if (ExecutionNodeWriter.TAG_BLOCK_CONTRACT.equals(qName)) { - return new KeYlessBlockContract(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isPreconditionComplied(attributes)); - } - else if (ExecutionNodeWriter.TAG_JOIN.equals(qName)) { - return new KeYlessJoin(parent, getName(attributes), getPathCondition(attributes), isPathConditionChanged(attributes), isWeakeningVerified(attributes)); - } - else { - throw new SAXException("Unknown tag \"" + qName + "\"."); - } - } - - /** - * Returns the additional branch label value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getAdditionalBranchLabel(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_ADDITIONAL_BRANCH_LABEL); - } - - /** - * Returns the path in tree value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getPathInTree(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_IN_TREE); - } - - /** - * Returns the name value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getName(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NAME); - } - - /** - * Returns the name value including return value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getNameIncludingReturnValue(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE); - } - - /** - * Returns the signature value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getSignature(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SIGNATURE); - } - - /** - * Returns the signature value including return value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getSignatureIncludingReturnValue(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE); - } - - /** - * Returns the termination kind value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected TerminationKind getTerminationKind(Attributes attributes) { - return TerminationKind.valueOf(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_TERMINATION_KIND)); - } - - /** - * Returns the precondition complied value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isPreconditionComplied(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PRECONDITION_COMPLIED)); - } - - /** - * Returns the has not null check value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isHasNotNullCheck(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_HAS_NOT_NULL_CHECK)); - } - - /** - * Returns the block opened value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isBlockOpened(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BLOCK_OPENED)); - } - - /** - * Returns the is return value computed value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isReturnValueComputed(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RETURN_VALUE_COMPUTED)); - } - - /** - * Returns the is branch condition computed value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isBranchConditionComputed(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_CONDITION_COMPUTED)); - } - - /** - * Returns the not null check complied value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isNotNullCheckComplied(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_NOT_NULL_CHECK_COMPLIED)); - } - - /** - * Returns the initially valid value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isInitiallyValid(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_INITIALLY_VALID)); - } - - /** - * Returns the is value an object value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isValueAnObject(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_VALUE_AN_OBJECT)); - } - - /** - * Returns if the weakening is verified. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isWeakeningVerified(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_WEAKENING_VERIFIED)); - } - - /** - * Returns the is value unknown value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isValueUnknown(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_VALUE_UNKNOWN)); - } - - /** - * Returns the value string value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getValueString(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_VALUE_STRING); - } - - /** - * Returns the value condition string value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getConditionString(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_CONDITION_STRING); - } - - /** - * Returns the is has condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean getHasCondition(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_HAS_CONDITION)); - } - - /** - * Returns the is branch verified value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean getBranchVerified(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_VERIFIED)); - } - - /** - * Returns the return value string value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getReturnValueString(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RETURN_VALUE_STRING); - } - - /** - * Returns the type string value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getTypeString(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_TYPE_STRING); - } - - /** - * Returns the exception term value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getExceptionTerm(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_EXCEPTION_TERM); - } - - /** - * Returns the result term value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getResultTerm(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_RESULT_TERM); - } - - /** - * Returns the self term value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getSelfTerm(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_SELF_TERM); - } - - /** - * Returns the contract parameters value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getContractParameters(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_CONTRACT_PARAMETERS); - } - - /** - * Returns the array index value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getArrayIndexString(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_ARRAY_INDEX); - } - - /** - * Returns the is array index value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isArrayIndex(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_IS_ARRAY_INDEX)); - } - - /** - * Returns the branch condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getBranchCondition(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_BRANCH_CONDITION); - } - - /** - * Returns the path condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getPathCondition(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_CONDITION); - } - - /** - * Returns the method return condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getMethodReturnCondition(Attributes attributes) { - return attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_METHOD_RETURN_CONDITION); - } - - /** - * Returns the path condition changed value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isPathConditionChanged(Attributes attributes) { - return Boolean.valueOf(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_PATH_CONDITION_CHANGED)); - } - - /** - * Returns the merged branch condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isMergedBranchCondition(Attributes attributes) { - return Boolean.valueOf(attributes.getValue(ExecutionNodeWriter.ATTRIBUTE_MERGED_BRANCH_CONDITION)); - } - - /** - * An abstract implementation of {@link IExecutionElement} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessExecutionElement implements IExecutionElement { - /** - * The name. - */ - private final String name; - - /** - * Constructor. - * @param name The name of this node. - */ - public AbstractKeYlessExecutionElement(String name) { - this.name = name; - } - - /** - * {@inheritDoc} - */ - @Override - public Services getServices() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public InitConfig getInitConfig() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Proof getProof() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public RuleApp getAppliedRuleApp() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Node getProofNode() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public NodeInfo getProofNodeInfo() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return name; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return getElementType() + " " + getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isDisposed() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public ITreeSettings getSettings() { - return null; - } - } - - /** - * An abstract implementation of {@link IExecutionNode} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessExecutionNode extends AbstractKeYlessExecutionElement implements IExecutionNode { - /** - * The parent {@link IExecutionNode}. - */ - private final IExecutionNode parent; - - /** - * The children. - */ - private final List> children = new LinkedList>(); - - /** - * The formated path condition. - */ - private final String formatedPathCondition; - - /** - * Is the path condition changed compared to parent? - */ - private final boolean pathConditionChanged; - - /** - * The call stack. - */ - private final List> callStack = new LinkedList>(); - - /** - * The contained constraints. - */ - private final List constraints = new LinkedList(); - - /** - * The contained variables. - */ - private final List variables = new LinkedList(); - - /** - * The completed blocks. - */ - private ImmutableList> completedBlocks = ImmutableSLList.nil(); - - /** - * The formated conditions under which a block is completed. - */ - private final Map, String> formatedCompletedBlockConditions = new LinkedHashMap, String>(); - - /** - * The contained outgoing links. - */ - private ImmutableList outgoingLinks = ImmutableSLList.nil(); - - /** - * The contained incoming links. - */ - private ImmutableList incomingLinks = ImmutableSLList.nil(); - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - */ - public AbstractKeYlessExecutionNode(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged) { - super(name); - this.parent = parent; - this.formatedPathCondition = formatedPathCondition; - this.pathConditionChanged = pathConditionChanged; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode getParent() { - return parent; - } - - /** - * Adds the given child. - * @param child The child to add. - */ - public void addChild(IExecutionNode child) { - children.add(child); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode[] getChildren() { - return children.toArray(new IExecutionNode[children.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public Term getPathCondition() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedPathCondition() throws ProofInputException { - return formatedPathCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isPathConditionChanged() { - return pathConditionChanged; - } - - /** - * Adds the given entry to the call stack. - * @param entry The entry to add to the call stack. - */ - public void addCallStackEntry(IExecutionNode entry) { - callStack.add(entry); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode[] getCallStack() { - return callStack.isEmpty() ? null : callStack.toArray(new IExecutionNode[callStack.size()]); - } - - /** - * Adds the given {@link IExecutionConstraint}. - * @param constraint The {@link IExecutionConstraint} to add. - */ - public void addConstraint(IExecutionConstraint constraint) { - constraints.add(constraint); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionConstraint[] getConstraints() { - return constraints.toArray(new IExecutionConstraint[constraints.size()]); - } - - /** - * Adds the given {@link IExecutionVariable}. - * @param variable The {@link IExecutionVariable} to add. - */ - public void addVariable(IExecutionVariable variable) { - variables.add(variable); - } - - /** - * {@inheritDoc} - */ - @Override - public S getActiveStatement() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public PositionInfo getActivePositionInfo() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getVariables() { - return variables.toArray(new IExecutionVariable[variables.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getVariables(Term condition) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public int getLayoutsCount() throws ProofInputException { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicLayout getInitialLayout(int configurationIndex) throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicLayout getCurrentLayout(int configurationIndex) throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getLayoutsEquivalenceClasses(int configurationIndex) throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getCompletedBlocks() { - return completedBlocks; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException { - return formatedCompletedBlockConditions.get(completedNode); - } - - /** - * Adds the given completed block. - * @param completedBlock The completed block. - * @param formatedCondition The formated condition under which the block is completed. - */ - public void addCompletedBlock(IExecutionBlockStartNode completedBlock, String formatedCondition) { - if (completedBlock != null) { - completedBlocks = completedBlocks.append(completedBlock); - formatedCompletedBlockConditions.put(completedBlock, formatedCondition); - } - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionLink getOutgoingLink(final IExecutionNode target) { - return CollectionUtil.search(outgoingLinks, new IFilter() { - @Override - public boolean select(IExecutionLink element) { - return element.getTarget() == target; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTerminations() { + return terminations; + } + } + + /** + * An implementation of {@link IExecutionTermination} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessTermination extends AbstractKeYlessExecutionNode + implements IExecutionTermination { + /** + * The {@link TerminationKind}. + */ + private final TerminationKind terminationKind; + + /** + * The branch verified flag. + */ + private final boolean branchVerified; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param exceptionalTermination Exceptional termination? + * @param branchVerified The branch verified flag. + */ + public KeYlessTermination(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + TerminationKind terminationKind, boolean branchVerified) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.terminationKind = terminationKind; + this.branchVerified = branchVerified; + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getExceptionVariable() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Sort getExceptionSort() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + switch (getTerminationKind()) { + case EXCEPTIONAL: + return "Exceptional Termination"; + case LOOP_BODY: + return "Loop Body Termination"; + case BLOCK_CONTRACT_EXCEPTIONAL: + return "Block Contract Exceptional Termination"; + case BLOCK_CONTRACT_NORMAL: + return "Block Contract Termination"; + default: + return "Termination"; } - }); - } - - /** - * Adds the outgoing {@link IExecutionLink}. - * @param link The outgoing {@link IExecutionLink} to add. - */ - public void addOutgoingLink(IExecutionLink link) { - outgoingLinks = outgoingLinks.append(link); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getOutgoingLinks() { - return outgoingLinks; - } - - /** - * Adds the incoming {@link IExecutionLink}. - * @param link The incoming {@link IExecutionLink} to add. - */ - public void addIncomingLink(IExecutionLink link) { - incomingLinks = incomingLinks.append(link); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionLink getIncomingLink(final IExecutionNode source) { - return CollectionUtil.search(incomingLinks, new IFilter() { - @Override - public boolean select(IExecutionLink element) { - return element.getSource() == source; + } + + /** + * {@inheritDoc} + */ + @Override + public TerminationKind getTerminationKind() { + return terminationKind; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBranchVerified() { + return branchVerified; + } + } + + /** + * An implementation of {@link IExecutionBranchStatement} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessBranchStatement + extends AbstractKeYlessExecutionBlockStartNode + implements IExecutionBranchStatement { + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param blockOpened {@code false} block is definitively not opened, {@code true} block is + * or might be opened. + */ + public KeYlessBranchStatement(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, boolean blockOpened) { + super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Branch Statement"; + } + } + + /** + * An implementation of {@link IExecutionLoopCondition} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessLoopCondition + extends AbstractKeYlessExecutionBlockStartNode + implements IExecutionLoopCondition { + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param blockOpened {@code false} block is definitively not opened, {@code true} block is + * or might be opened. + */ + public KeYlessLoopCondition(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, boolean blockOpened) { + super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); + } + + /** + * {@inheritDoc} + */ + @Override + public Expression getGuardExpression() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PositionInfo getGuardExpressionPositionInfo() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Condition"; + } + } + + /** + * An implementation of {@link IExecutionLoopStatement} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessLoopStatement + extends AbstractKeYlessExecutionBlockStartNode + implements IExecutionLoopStatement { + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param blockOpened {@code false} block is definitively not opened, {@code true} block is + * or might be opened. + */ + public KeYlessLoopStatement(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, boolean blockOpened) { + super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Statement"; + } + } + + /** + * An implementation of {@link IExecutionMethodCall} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessMethodCall extends AbstractKeYlessExecutionNode + implements IExecutionMethodCall { + /** + * The up to now discovered {@link IExecutionBaseMethodReturn}s. + */ + private ImmutableList> methodReturns = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + */ + public KeYlessMethodCall(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged) { + super(parent, name, formatedPathCondition, pathConditionChanged); + } + + /** + * {@inheritDoc} + */ + @Override + public MethodReference getMethodReference() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getProgramMethod() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Method Call"; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isImplicitConstructor() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public MethodReference getExplicitConstructorMethodReference() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getExplicitConstructorProgramMethod() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getMethodReturns() { + return methodReturns; + } + + /** + * Adds the given {@link IExecutionBaseMethodReturn}. + * + * @param methodReturn The {@link IExecutionBaseMethodReturn} to add. + */ + public void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { + if (methodReturn != null) { + methodReturns = methodReturns.prepend(methodReturn); } - }); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getIncomingLinks() { - return incomingLinks; - } - } - - /** - * An abstract implementation of {@link IExecutionBlockStartNode} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessExecutionBlockStartNode extends AbstractKeYlessExecutionNode implements IExecutionBlockStartNode { - /** - * The block completions. - */ - private ImmutableList> blockCompletions = ImmutableSLList.nil(); - - /** - * Is a block opened? - */ - private final boolean blockOpened; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public AbstractKeYlessExecutionBlockStartNode(IExecutionNode parent, String name, String formatedPathCondition, boolean pathConditionChanged, boolean blockOpened) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.blockOpened = blockOpened; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getBlockCompletions() { - return blockCompletions; - } - - /** - * Adds the given block completion. - * @param blockCompletion The block completion to add. - */ - public void addBlockCompletion(IExecutionNode blockCompletion) { - if (blockCompletion != null) { - blockCompletions = blockCompletions.append(blockCompletion); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBlockOpened() { - return blockOpened; - } - } - - /** - * An implementation of {@link IExecutionLoopCondition} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessBranchCondition extends AbstractKeYlessExecutionNode implements IExecutionBranchCondition { - /** - * The formated branch condition. - */ - private final String formatedBranchCondition; - - /** - * Merged branch condition? - */ - private final boolean mergedBranchCondition; - - /** - * Indicates if branch condition is computed or not. - */ - private final boolean branchConditionComputed; - - /** - * The optional additional branch label. - */ - private final String additionalBranchLabel; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedBranchCondition The formated branch condition. - * @param mergedBranchCondition Merged branch condition? - * @param branchConditionComputed Is branch condition computed? - * @param additionalBranchLabel The optional additional branch label. - */ - public KeYlessBranchCondition(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - String formatedBranchCondition, - boolean mergedBranchCondition, - boolean branchConditionComputed, - String additionalBranchLabel) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.formatedBranchCondition = formatedBranchCondition; - this.mergedBranchCondition = mergedBranchCondition; - this.branchConditionComputed = branchConditionComputed; - this.additionalBranchLabel = additionalBranchLabel; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Branch Condition"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getBranchCondition() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedBranchCondition() { - return formatedBranchCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isMergedBranchCondition() { - return mergedBranchCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public Node[] getMergedProofNodes() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Term[] getMergedBranchCondtions() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBranchConditionComputed() { - return branchConditionComputed; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdditionalBranchLabel() { - return additionalBranchLabel; - } - } - - /** - * An implementation of {@link IExecutionStart} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessStart extends AbstractKeYlessExecutionNode implements IExecutionStart { - /** - * The up to now discovered {@link IExecutionTermination}s. - */ - private ImmutableList terminations = ImmutableSLList.nil(); - - /** - * Constructor. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - */ - public KeYlessStart(String name, - String formatedPathCondition, - boolean pathConditionChanged) { - super(null, name, formatedPathCondition, pathConditionChanged); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Start"; - } - - /** - * Adds the given {@link IExecutionTermination}. - * @param termination The {@link IExecutionTermination} to add. - */ - public void addTermination(IExecutionTermination termination) { - if (termination != null) { - terminations = terminations.prepend(termination); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTerminations() { - return terminations; - } - } - - /** - * An implementation of {@link IExecutionTermination} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessTermination extends AbstractKeYlessExecutionNode implements IExecutionTermination { - /** - * The {@link TerminationKind}. - */ - private final TerminationKind terminationKind; - - /** - * The branch verified flag. - */ - private final boolean branchVerified; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param exceptionalTermination Exceptional termination? - * @param branchVerified The branch verified flag. - */ - public KeYlessTermination(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - TerminationKind terminationKind, - boolean branchVerified) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.terminationKind = terminationKind; - this.branchVerified = branchVerified; - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getExceptionVariable() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Sort getExceptionSort() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - switch (getTerminationKind()) { - case EXCEPTIONAL : return "Exceptional Termination"; - case LOOP_BODY : return "Loop Body Termination"; - case BLOCK_CONTRACT_EXCEPTIONAL : return "Block Contract Exceptional Termination"; - case BLOCK_CONTRACT_NORMAL : return "Block Contract Termination"; - default : return "Termination"; - } - } - - /** - * {@inheritDoc} - */ - @Override - public TerminationKind getTerminationKind() { - return terminationKind; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBranchVerified() { - return branchVerified; - } - } - - /** - * An implementation of {@link IExecutionBranchStatement} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessBranchStatement extends AbstractKeYlessExecutionBlockStartNode implements IExecutionBranchStatement { - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public KeYlessBranchStatement(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean blockOpened) { - super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Branch Statement"; - } - } - - /** - * An implementation of {@link IExecutionLoopCondition} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessLoopCondition extends AbstractKeYlessExecutionBlockStartNode implements IExecutionLoopCondition { - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public KeYlessLoopCondition(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean blockOpened) { - super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); - } - - /** - * {@inheritDoc} - */ - @Override - public Expression getGuardExpression() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public PositionInfo getGuardExpressionPositionInfo() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Condition"; - } - } - - /** - * An implementation of {@link IExecutionLoopStatement} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessLoopStatement extends AbstractKeYlessExecutionBlockStartNode implements IExecutionLoopStatement { - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public KeYlessLoopStatement(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean blockOpened) { - super(parent, name, formatedPathCondition, pathConditionChanged, blockOpened); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Statement"; - } - } - - /** - * An implementation of {@link IExecutionMethodCall} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessMethodCall extends AbstractKeYlessExecutionNode implements IExecutionMethodCall { - /** - * The up to now discovered {@link IExecutionBaseMethodReturn}s. - */ - private ImmutableList> methodReturns = ImmutableSLList.nil(); - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - */ - public KeYlessMethodCall(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged) { - super(parent, name, formatedPathCondition, pathConditionChanged); - } - - /** - * {@inheritDoc} - */ - @Override - public MethodReference getMethodReference() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getProgramMethod() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Method Call"; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isImplicitConstructor() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public MethodReference getExplicitConstructorMethodReference() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getExplicitConstructorProgramMethod() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getMethodReturns() { - return methodReturns; - } - - /** - * Adds the given {@link IExecutionBaseMethodReturn}. - * @param methodReturn The {@link IExecutionBaseMethodReturn} to add. - */ - public void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { - if (methodReturn != null) { - methodReturns = methodReturns.prepend(methodReturn); - } - } - } - - /** - * An implementation of {@link IExecutionBaseMethodReturn} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessBaseExecutionNode extends AbstractKeYlessExecutionNode implements IExecutionBaseMethodReturn { - /** - * The contained call state variables. - */ - private final List callStateVariables = new LinkedList(); - - /** - * The signature. - */ - private final String signature; - - /** - * The formated method return condition. - */ - private final String formatedMethodReturn; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param signature The signature. - * @param formatedMethodReturn The formated method return condition. - */ - public AbstractKeYlessBaseExecutionNode(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - String signature, - String formatedMethodReturn) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.signature = signature; - this.formatedMethodReturn = formatedMethodReturn; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getCallStateVariables() { - return callStateVariables.toArray(new IExecutionVariable[callStateVariables.size()]); - } - - /** - * Adds the given {@link IExecutionVariable}. - * @param variable The {@link IExecutionVariable} to add. - */ - public void addCallStateVariable(IExecutionVariable variable) { - callStateVariables.add(variable); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionMethodCall getMethodCall() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignature() throws ProofInputException { - return signature; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getMethodReturnCondition() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedMethodReturnCondition() throws ProofInputException { - return formatedMethodReturn; - } - } - - /** - * An implementation of {@link IExecutionExceptionalMethodReturn} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessExceptionalMethodReturn extends AbstractKeYlessBaseExecutionNode implements IExecutionExceptionalMethodReturn { - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param signature The signature. - * @param formatedMethodReturn The formated method return condition. - */ - public KeYlessExceptionalMethodReturn(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - String signature, - String formatedMethodReturn) { - super(parent, name, formatedPathCondition, pathConditionChanged, signature, formatedMethodReturn); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Exceptional Method Return"; - } - } - - /** - * An implementation of {@link IExecutionMethodReturn} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessMethodReturn extends AbstractKeYlessBaseExecutionNode implements IExecutionMethodReturn { - /** - * The name including the return value. - */ - private final String nameIncludingReturnValue; - - /** - * The signature including the return value. - */ - private final String signatureIncludingReturnValue; - - /** - * Defines if the return value is computed or not. - */ - private final boolean returnValueComputed; - - /** - * The possible return values. - */ - private final List returnValues = new LinkedList(); - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param formatedPathCondition The formated path condition. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param nameIncludingReturnValue The name including the return value. - * @param signature The signature. - * @param signatureIncludingReturnValue The signature including return value. - * @param returnValueComputed Is the return value computed? - * @param formatedMethodReturn The formated method return condition. - */ - public KeYlessMethodReturn(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - String nameIncludingReturnValue, - String signature, - String signatureIncludingReturnValue, - boolean returnValueComputed, - String formatedMethodReturn) { - super(parent, name, formatedPathCondition, pathConditionChanged, signature, formatedMethodReturn); - this.nameIncludingReturnValue = nameIncludingReturnValue; - this.signatureIncludingReturnValue = signatureIncludingReturnValue; - this.returnValueComputed = returnValueComputed; - } - - /** - * {@inheritDoc} - */ - @Override - public String getNameIncludingReturnValue() throws ProofInputException { - return nameIncludingReturnValue; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignatureIncludingReturnValue() throws ProofInputException { - return signatureIncludingReturnValue; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Method Return"; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isReturnValuesComputed() { - return returnValueComputed; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException { - return returnValues.toArray(new IExecutionMethodReturnValue[returnValues.size()]); - } - - /** - * Adds the given {@link IExecutionMethodReturnValue}. - * @param returnValue The {@link IExecutionMethodReturnValue} to add. - */ - public void addReturnValue(IExecutionMethodReturnValue returnValue) { - returnValues.add(returnValue); - } - } - - /** - * An implementation of {@link IExecutionMethodReturn} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessMethodReturnValue extends AbstractKeYlessExecutionElement implements IExecutionMethodReturnValue { - /** - * The human readable return value. - */ - private final String returnValueString; - - /** - * Is a condition available? - */ - private final boolean hasCondition; - - /** - * The optional human readable condition. - */ - private final String conditionString; - - /** - * Constructor. - * @param name The name of this node. - * @param returnValueString The human readable return value. - * @param hasCondition Is a condition available? - * @param conditionString The optional human readable condition. - */ - public KeYlessMethodReturnValue(String name, - String returnValueString, - boolean hasCondition, - String conditionString) { - super(name); - this.returnValueString = returnValueString; - this.hasCondition = hasCondition; - this.conditionString = conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Return Value"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getReturnValue() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getReturnValueString() throws ProofInputException { - return returnValueString; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasCondition() throws ProofInputException { - return hasCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() throws ProofInputException { - return conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return null; - } - } - - /** - * An implementation of {@link IExecutionStatement} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessStatement extends AbstractKeYlessExecutionNode implements IExecutionStatement { - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedPathCondition The formated path condition. - */ - public KeYlessStatement(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged) { - super(parent, name, formatedPathCondition, pathConditionChanged); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Statement"; - } - } - - /** - * An implementation of {@link IExecutionJoin} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessJoin extends AbstractKeYlessExecutionNode implements IExecutionJoin { - /** - * Is the weakening verified? - */ - private final boolean weakeningVerified; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedPathCondition The formated path condition. - * @param weakeningVerified Is the weakening verified? - */ - public KeYlessJoin(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean weakeningVerified) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.weakeningVerified = weakeningVerified; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Join"; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isWeakeningVerified() { - return weakeningVerified; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isWeakeningVerificationSupported() { - return true; - } - } - - /** - * An implementation of {@link IExecutionOperationContract} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessOperationContract extends AbstractKeYlessExecutionNode implements IExecutionOperationContract { - /** - * Is precondition complied? - */ - private final boolean preconditionComplied; - - /** - * Has not null check? - */ - private final boolean hasNotNullCheck; - - /** - * Is not null check complied? - */ - private final boolean notNullCheckComplied; - - /** - * The formated result term. - */ - private final String formatedResultTerm; - - /** - * The formated exception term. - */ - private final String formatedExceptionTerm; - - /** - * The formated self term. - */ - private final String formatedSelfTerm; - - /** - * The formated contract parameters. - */ - private final String formatedContractParams; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedPathCondition The formated path condition. - * @param preconditionComplied Is precondition complied? - * @param hasNotNullCheck Has not null check? - * @param notNullCheckComplied Is not null check complied? - * @param formatedResultTerm The formated result term. - * @param formatedExceptionTerm The formated exception term. - * @param formatedSelfTerm The formated self term. - * @param formatedContractParams The formated contract parameters. - */ - public KeYlessOperationContract(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean preconditionComplied, - boolean hasNotNullCheck, - boolean notNullCheckComplied, - String formatedResultTerm, - String formatedExceptionTerm, - String formatedSelfTerm, - String formatedContractParams) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.preconditionComplied = preconditionComplied; - this.hasNotNullCheck = hasNotNullCheck; - this.notNullCheckComplied = notNullCheckComplied; - this.formatedResultTerm = formatedResultTerm; - this.formatedExceptionTerm = formatedExceptionTerm; - this.formatedSelfTerm = formatedSelfTerm; - this.formatedContractParams = formatedContractParams; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Operation Contract"; - } - - /** - * {@inheritDoc} - */ - @Override - public Contract getContract() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getContractProgramMethod() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isPreconditionComplied() { - return preconditionComplied; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasNotNullCheck() { - return hasNotNullCheck; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isNotNullCheckComplied() { - return notNullCheckComplied; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getResultTerm() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getExceptionTerm() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedResultTerm() throws ProofInputException { - return formatedResultTerm; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedExceptionTerm() throws ProofInputException { - return formatedExceptionTerm; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getSelfTerm() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getContractParams() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedSelfTerm() throws ProofInputException { - return formatedSelfTerm; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedContractParams() throws ProofInputException { - return formatedContractParams; - } - } - - /** - * An implementation of {@link IExecutionLoopInvariant} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessLoopInvariant extends AbstractKeYlessExecutionNode implements IExecutionLoopInvariant { - /** - * Initially valid? - */ - private final boolean initiallyValid; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedPathCondition The formated path condition. - * @param initiallyValid Initially valid? - */ - public KeYlessLoopInvariant(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean initiallyValid) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.initiallyValid = initiallyValid; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Invariant"; - } - - /** - * {@inheritDoc} - */ - @Override - public LoopSpecification getLoopInvariant() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public While getLoopStatement() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isInitiallyValid() { - return initiallyValid; - } - } - - /** - * An implementation of {@link IExecutionAuxiliaryContract} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessBlockContract extends AbstractKeYlessExecutionNode implements IExecutionAuxiliaryContract { - /** - * Precondition complied? - */ - private final boolean preconditionComplied; - - /** - * Constructor. - * @param parent The parent {@link IExecutionNode}. - * @param name The name of this node. - * @param pathConditionChanged Is the path condition changed compared to parent? - * @param formatedPathCondition The formated path condition. - * @param preconditionComplied Precondition complied? - */ - public KeYlessBlockContract(IExecutionNode parent, - String name, - String formatedPathCondition, - boolean pathConditionChanged, - boolean preconditionComplied) { - super(parent, name, formatedPathCondition, pathConditionChanged); - this.preconditionComplied = preconditionComplied; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Block Contract"; - } - - /** - * {@inheritDoc} - */ - @Override - public BlockContract getContract() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public StatementBlock getBlock() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isPreconditionComplied() { - return preconditionComplied; - } - } - - /** - * An implementation of {@link IExecutionConstraint} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessConstraint extends AbstractKeYlessExecutionElement implements IExecutionConstraint { - /** - * Constructor. - * @param name The name. - */ - public KeYlessConstraint(String name) { - super(name); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Constraint"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getTerm() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return null; - } - } - - /** - * An implementation of {@link IExecutionVariable} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessVariable extends AbstractKeYlessExecutionElement implements IExecutionVariable { - /** - * The parent {@link IExecutionValue} if available. - */ - private final IExecutionValue parentValue; - - /** - * The is array flag. - */ - private final boolean isArrayIndex; - - /** - * The array index. - */ - private final String arrayIndexString; - - /** - * The contained values. - */ - private final List values = new LinkedList(); - - /** - * Constructor. - * @param parentVariable The parent {@link IExecutionValue} if available. - * @param isArrayIndex The is array flag. - * @param arrayIndexString The array index. - * @param name The name. - */ - public KeYlessVariable(IExecutionValue parentValue, - boolean isArrayIndex, - String arrayIndexString, - String name) { - super(name); - this.parentValue = parentValue; - this.isArrayIndex = isArrayIndex; - this.arrayIndexString = arrayIndexString; - } - - /** - * Adds the given child {@link IExecutionValue}. - * @param variable The child {@link IExecutionValue} to add. - */ - public void addValue(IExecutionValue variable) { - values.add(variable); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionValue getParentValue() { - return parentValue; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionValue[] getValues() { - return values.toArray(new IExecutionValue[values.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndexString; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isArrayIndex() { - return isArrayIndex; - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Variable"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getAdditionalCondition() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Term createSelectTerm() { - return null; - } - } - - /** - * An implementation of {@link IExecutionLink} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYLessLink implements IExecutionLink { - /** - * The source. - */ - private IExecutionNode source; - - /** - * The target. - */ - private IExecutionNode target; - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode getSource() { - return source; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode getTarget() { - return target; - } - - /** - * Sets the source. - * @param target The source to set. - */ - public void setSource(IExecutionNode source) { - this.source = source; - } - - /** - * Sets the target. - * @param target The target to set. - */ - public void setTarget(IExecutionNode target) { - this.target = target; - } - } - - /** - * An implementation of {@link IExecutionValue} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessValue extends AbstractKeYlessExecutionElement implements IExecutionValue { - /** - * The parent {@link IExecutionVariable} if available. - */ - private final IExecutionVariable variable; - - /** - * The type string. - */ - private final String typeString; - - /** - * The value string. - */ - private final String valueString; - - /** - * Is the value unknown? - */ - private final boolean valueUnknown; - - /** - * Is the value an object? - */ - private final boolean valueAnObject; - - /** - * The child variables. - */ - private final List childVariables = new LinkedList(); - - /** - * The condition as {@link String}. - */ - private final String conditionString; - - /** - * The related {@link IExecutionConstraint}s. - */ - private final List constraints = new LinkedList(); - - /** - * Constructor. - * @param variable The parent {@link IExecutionVariable}. - * @param typeString The type string. - * @param valueString The value string. - * @param name The name. - * @param valueUnknown Is the value unknown? - * @param valueAnObject Is the value an object? - * @param conditionString The condition as human readable {@link String}. - */ - public KeYlessValue(IExecutionVariable variable, - String typeString, - String valueString, - String name, - boolean valueUnknown, - boolean valueAnObject, - String conditionString) { - super(name); - this.variable = variable; - this.typeString = typeString; - this.valueString = valueString; - this.valueUnknown = valueUnknown; - this.valueAnObject = valueAnObject; - this.conditionString = conditionString; - } - - /** - * Adds the given child {@link IExecutionVariable}. - * @param variable The child {@link IExecutionVariable} to add. - */ - public void addChildVariable(IExecutionVariable variable) { - childVariables.add(variable); - } - - /** - * {@inheritDoc} - */ - @Override - public String getValueString() throws ProofInputException { - return valueString; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() { - return typeString; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() throws ProofInputException { - return conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable getVariable() { - return variable; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getChildVariables() throws ProofInputException { - return childVariables.toArray(new IExecutionVariable[childVariables.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isValueUnknown() throws ProofInputException { - return valueUnknown; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isValueAnObject() throws ProofInputException { - return valueAnObject; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getValue() throws ProofInputException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Value"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() throws ProofInputException { - return null; - } - - /** - * Adds the given {@link IExecutionConstraint}. - * @param constraint The {@link IExecutionConstraint} to add. - */ - public void addConstraint(IExecutionConstraint constraint) { - constraints.add(constraint); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionConstraint[] getConstraints() throws ProofInputException { - return constraints.toArray(new IExecutionConstraint[constraints.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return null; - } - } -} \ No newline at end of file + } + } + + /** + * An implementation of {@link IExecutionBaseMethodReturn} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessBaseExecutionNode + extends AbstractKeYlessExecutionNode implements IExecutionBaseMethodReturn { + /** + * The contained call state variables. + */ + private final List callStateVariables = + new LinkedList(); + + /** + * The signature. + */ + private final String signature; + + /** + * The formated method return condition. + */ + private final String formatedMethodReturn; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param signature The signature. + * @param formatedMethodReturn The formated method return condition. + */ + public AbstractKeYlessBaseExecutionNode(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, String signature, + String formatedMethodReturn) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.signature = signature; + this.formatedMethodReturn = formatedMethodReturn; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getCallStateVariables() { + return callStateVariables.toArray(new IExecutionVariable[callStateVariables.size()]); + } + + /** + * Adds the given {@link IExecutionVariable}. + * + * @param variable The {@link IExecutionVariable} to add. + */ + public void addCallStateVariable(IExecutionVariable variable) { + callStateVariables.add(variable); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionMethodCall getMethodCall() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignature() throws ProofInputException { + return signature; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getMethodReturnCondition() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedMethodReturnCondition() throws ProofInputException { + return formatedMethodReturn; + } + } + + /** + * An implementation of {@link IExecutionExceptionalMethodReturn} which is independent from KeY + * and provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessExceptionalMethodReturn extends + AbstractKeYlessBaseExecutionNode implements IExecutionExceptionalMethodReturn { + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param signature The signature. + * @param formatedMethodReturn The formated method return condition. + */ + public KeYlessExceptionalMethodReturn(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, String signature, + String formatedMethodReturn) { + super(parent, name, formatedPathCondition, pathConditionChanged, signature, + formatedMethodReturn); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Exceptional Method Return"; + } + } + + /** + * An implementation of {@link IExecutionMethodReturn} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessMethodReturn extends AbstractKeYlessBaseExecutionNode + implements IExecutionMethodReturn { + /** + * The name including the return value. + */ + private final String nameIncludingReturnValue; + + /** + * The signature including the return value. + */ + private final String signatureIncludingReturnValue; + + /** + * Defines if the return value is computed or not. + */ + private final boolean returnValueComputed; + + /** + * The possible return values. + */ + private final List returnValues = + new LinkedList(); + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param formatedPathCondition The formated path condition. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param nameIncludingReturnValue The name including the return value. + * @param signature The signature. + * @param signatureIncludingReturnValue The signature including return value. + * @param returnValueComputed Is the return value computed? + * @param formatedMethodReturn The formated method return condition. + */ + public KeYlessMethodReturn(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + String nameIncludingReturnValue, String signature, + String signatureIncludingReturnValue, boolean returnValueComputed, + String formatedMethodReturn) { + super(parent, name, formatedPathCondition, pathConditionChanged, signature, + formatedMethodReturn); + this.nameIncludingReturnValue = nameIncludingReturnValue; + this.signatureIncludingReturnValue = signatureIncludingReturnValue; + this.returnValueComputed = returnValueComputed; + } + + /** + * {@inheritDoc} + */ + @Override + public String getNameIncludingReturnValue() throws ProofInputException { + return nameIncludingReturnValue; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignatureIncludingReturnValue() throws ProofInputException { + return signatureIncludingReturnValue; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Method Return"; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isReturnValuesComputed() { + return returnValueComputed; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException { + return returnValues.toArray(new IExecutionMethodReturnValue[returnValues.size()]); + } + + /** + * Adds the given {@link IExecutionMethodReturnValue}. + * + * @param returnValue The {@link IExecutionMethodReturnValue} to add. + */ + public void addReturnValue(IExecutionMethodReturnValue returnValue) { + returnValues.add(returnValue); + } + } + + /** + * An implementation of {@link IExecutionMethodReturn} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessMethodReturnValue extends AbstractKeYlessExecutionElement + implements IExecutionMethodReturnValue { + /** + * The human readable return value. + */ + private final String returnValueString; + + /** + * Is a condition available? + */ + private final boolean hasCondition; + + /** + * The optional human readable condition. + */ + private final String conditionString; + + /** + * Constructor. + * + * @param name The name of this node. + * @param returnValueString The human readable return value. + * @param hasCondition Is a condition available? + * @param conditionString The optional human readable condition. + */ + public KeYlessMethodReturnValue(String name, String returnValueString, boolean hasCondition, + String conditionString) { + super(name); + this.returnValueString = returnValueString; + this.hasCondition = hasCondition; + this.conditionString = conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Return Value"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getReturnValue() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getReturnValueString() throws ProofInputException { + return returnValueString; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasCondition() throws ProofInputException { + return hasCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() throws ProofInputException { + return conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return null; + } + } + + /** + * An implementation of {@link IExecutionStatement} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessStatement extends AbstractKeYlessExecutionNode + implements IExecutionStatement { + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedPathCondition The formated path condition. + */ + public KeYlessStatement(IExecutionNode parent, String name, String formatedPathCondition, + boolean pathConditionChanged) { + super(parent, name, formatedPathCondition, pathConditionChanged); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Statement"; + } + } + + /** + * An implementation of {@link IExecutionJoin} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessJoin extends AbstractKeYlessExecutionNode + implements IExecutionJoin { + /** + * Is the weakening verified? + */ + private final boolean weakeningVerified; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedPathCondition The formated path condition. + * @param weakeningVerified Is the weakening verified? + */ + public KeYlessJoin(IExecutionNode parent, String name, String formatedPathCondition, + boolean pathConditionChanged, boolean weakeningVerified) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.weakeningVerified = weakeningVerified; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Join"; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWeakeningVerified() { + return weakeningVerified; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWeakeningVerificationSupported() { + return true; + } + } + + /** + * An implementation of {@link IExecutionOperationContract} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessOperationContract extends AbstractKeYlessExecutionNode + implements IExecutionOperationContract { + /** + * Is precondition complied? + */ + private final boolean preconditionComplied; + + /** + * Has not null check? + */ + private final boolean hasNotNullCheck; + + /** + * Is not null check complied? + */ + private final boolean notNullCheckComplied; + + /** + * The formated result term. + */ + private final String formatedResultTerm; + + /** + * The formated exception term. + */ + private final String formatedExceptionTerm; + + /** + * The formated self term. + */ + private final String formatedSelfTerm; + + /** + * The formated contract parameters. + */ + private final String formatedContractParams; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedPathCondition The formated path condition. + * @param preconditionComplied Is precondition complied? + * @param hasNotNullCheck Has not null check? + * @param notNullCheckComplied Is not null check complied? + * @param formatedResultTerm The formated result term. + * @param formatedExceptionTerm The formated exception term. + * @param formatedSelfTerm The formated self term. + * @param formatedContractParams The formated contract parameters. + */ + public KeYlessOperationContract(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + boolean preconditionComplied, boolean hasNotNullCheck, boolean notNullCheckComplied, + String formatedResultTerm, String formatedExceptionTerm, String formatedSelfTerm, + String formatedContractParams) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.preconditionComplied = preconditionComplied; + this.hasNotNullCheck = hasNotNullCheck; + this.notNullCheckComplied = notNullCheckComplied; + this.formatedResultTerm = formatedResultTerm; + this.formatedExceptionTerm = formatedExceptionTerm; + this.formatedSelfTerm = formatedSelfTerm; + this.formatedContractParams = formatedContractParams; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Operation Contract"; + } + + /** + * {@inheritDoc} + */ + @Override + public Contract getContract() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getContractProgramMethod() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPreconditionComplied() { + return preconditionComplied; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasNotNullCheck() { + return hasNotNullCheck; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isNotNullCheckComplied() { + return notNullCheckComplied; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getResultTerm() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getExceptionTerm() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedResultTerm() throws ProofInputException { + return formatedResultTerm; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedExceptionTerm() throws ProofInputException { + return formatedExceptionTerm; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getSelfTerm() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getContractParams() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedSelfTerm() throws ProofInputException { + return formatedSelfTerm; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedContractParams() throws ProofInputException { + return formatedContractParams; + } + } + + /** + * An implementation of {@link IExecutionLoopInvariant} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessLoopInvariant extends AbstractKeYlessExecutionNode + implements IExecutionLoopInvariant { + /** + * Initially valid? + */ + private final boolean initiallyValid; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedPathCondition The formated path condition. + * @param initiallyValid Initially valid? + */ + public KeYlessLoopInvariant(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + boolean initiallyValid) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.initiallyValid = initiallyValid; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Invariant"; + } + + /** + * {@inheritDoc} + */ + @Override + public LoopSpecification getLoopInvariant() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public While getLoopStatement() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isInitiallyValid() { + return initiallyValid; + } + } + + /** + * An implementation of {@link IExecutionAuxiliaryContract} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessBlockContract extends AbstractKeYlessExecutionNode + implements IExecutionAuxiliaryContract { + /** + * Precondition complied? + */ + private final boolean preconditionComplied; + + /** + * Constructor. + * + * @param parent The parent {@link IExecutionNode}. + * @param name The name of this node. + * @param pathConditionChanged Is the path condition changed compared to parent? + * @param formatedPathCondition The formated path condition. + * @param preconditionComplied Precondition complied? + */ + public KeYlessBlockContract(IExecutionNode parent, String name, + String formatedPathCondition, boolean pathConditionChanged, + boolean preconditionComplied) { + super(parent, name, formatedPathCondition, pathConditionChanged); + this.preconditionComplied = preconditionComplied; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Block Contract"; + } + + /** + * {@inheritDoc} + */ + @Override + public BlockContract getContract() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public StatementBlock getBlock() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPreconditionComplied() { + return preconditionComplied; + } + } + + /** + * An implementation of {@link IExecutionConstraint} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessConstraint extends AbstractKeYlessExecutionElement + implements IExecutionConstraint { + /** + * Constructor. + * + * @param name The name. + */ + public KeYlessConstraint(String name) { + super(name); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Constraint"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getTerm() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return null; + } + } + + /** + * An implementation of {@link IExecutionVariable} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessVariable extends AbstractKeYlessExecutionElement + implements IExecutionVariable { + /** + * The parent {@link IExecutionValue} if available. + */ + private final IExecutionValue parentValue; + + /** + * The is array flag. + */ + private final boolean isArrayIndex; + + /** + * The array index. + */ + private final String arrayIndexString; + + /** + * The contained values. + */ + private final List values = new LinkedList(); + + /** + * Constructor. + * + * @param parentVariable The parent {@link IExecutionValue} if available. + * @param isArrayIndex The is array flag. + * @param arrayIndexString The array index. + * @param name The name. + */ + public KeYlessVariable(IExecutionValue parentValue, boolean isArrayIndex, + String arrayIndexString, String name) { + super(name); + this.parentValue = parentValue; + this.isArrayIndex = isArrayIndex; + this.arrayIndexString = arrayIndexString; + } + + /** + * Adds the given child {@link IExecutionValue}. + * + * @param variable The child {@link IExecutionValue} to add. + */ + public void addValue(IExecutionValue variable) { + values.add(variable); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionValue getParentValue() { + return parentValue; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionValue[] getValues() { + return values.toArray(new IExecutionValue[values.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndexString; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isArrayIndex() { + return isArrayIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Variable"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getAdditionalCondition() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term createSelectTerm() { + return null; + } + } + + /** + * An implementation of {@link IExecutionLink} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYLessLink implements IExecutionLink { + /** + * The source. + */ + private IExecutionNode source; + + /** + * The target. + */ + private IExecutionNode target; + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode getSource() { + return source; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode getTarget() { + return target; + } + + /** + * Sets the source. + * + * @param target The source to set. + */ + public void setSource(IExecutionNode source) { + this.source = source; + } + + /** + * Sets the target. + * + * @param target The target to set. + */ + public void setTarget(IExecutionNode target) { + this.target = target; + } + } + + /** + * An implementation of {@link IExecutionValue} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessValue extends AbstractKeYlessExecutionElement + implements IExecutionValue { + /** + * The parent {@link IExecutionVariable} if available. + */ + private final IExecutionVariable variable; + + /** + * The type string. + */ + private final String typeString; + + /** + * The value string. + */ + private final String valueString; + + /** + * Is the value unknown? + */ + private final boolean valueUnknown; + + /** + * Is the value an object? + */ + private final boolean valueAnObject; + + /** + * The child variables. + */ + private final List childVariables = + new LinkedList(); + + /** + * The condition as {@link String}. + */ + private final String conditionString; + + /** + * The related {@link IExecutionConstraint}s. + */ + private final List constraints = + new LinkedList(); + + /** + * Constructor. + * + * @param variable The parent {@link IExecutionVariable}. + * @param typeString The type string. + * @param valueString The value string. + * @param name The name. + * @param valueUnknown Is the value unknown? + * @param valueAnObject Is the value an object? + * @param conditionString The condition as human readable {@link String}. + */ + public KeYlessValue(IExecutionVariable variable, String typeString, String valueString, + String name, boolean valueUnknown, boolean valueAnObject, String conditionString) { + super(name); + this.variable = variable; + this.typeString = typeString; + this.valueString = valueString; + this.valueUnknown = valueUnknown; + this.valueAnObject = valueAnObject; + this.conditionString = conditionString; + } + + /** + * Adds the given child {@link IExecutionVariable}. + * + * @param variable The child {@link IExecutionVariable} to add. + */ + public void addChildVariable(IExecutionVariable variable) { + childVariables.add(variable); + } + + /** + * {@inheritDoc} + */ + @Override + public String getValueString() throws ProofInputException { + return valueString; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() { + return typeString; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() throws ProofInputException { + return conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable getVariable() { + return variable; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getChildVariables() throws ProofInputException { + return childVariables.toArray(new IExecutionVariable[childVariables.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValueUnknown() throws ProofInputException { + return valueUnknown; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValueAnObject() throws ProofInputException { + return valueAnObject; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getValue() throws ProofInputException { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Value"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() throws ProofInputException { + return null; + } + + /** + * Adds the given {@link IExecutionConstraint}. + * + * @param constraint The {@link IExecutionConstraint} to add. + */ + public void addConstraint(IExecutionConstraint constraint) { + constraints.add(constraint); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionConstraint[] getConstraints() throws ProofInputException { + return constraints.toArray(new IExecutionConstraint[constraints.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return null; + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeSymbolicLayoutExtractor.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeSymbolicLayoutExtractor.java index bb32e1f9305..2ebfb1a2acf 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeSymbolicLayoutExtractor.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeSymbolicLayoutExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import de.uka.ilkd.key.proof.init.ProofInputException; @@ -6,50 +9,50 @@ /** * Special {@link SymbolicLayoutExtractor} for {@link IExecutionNode}s. + * * @author Martin Hentschel */ public class ExecutionNodeSymbolicLayoutExtractor extends SymbolicLayoutExtractor { - /** - * The {@link IExecutionNode} to extract memory layouts from. - */ - private final IExecutionNode executionNode; + /** + * The {@link IExecutionNode} to extract memory layouts from. + */ + private final IExecutionNode executionNode; - /** - * Constructor. - * @param executionNode The {@link IExecutionNode} to extract memory layouts from. - */ - public ExecutionNodeSymbolicLayoutExtractor(IExecutionNode executionNode) { - super(executionNode.getProofNode(), - executionNode.getModalityPIO(), - executionNode.getSettings().isUseUnicode(), - executionNode.getSettings().isUsePrettyPrinting(), - executionNode.getSettings().isSimplifyConditions()); - this.executionNode = executionNode; - } + /** + * Constructor. + * + * @param executionNode The {@link IExecutionNode} to extract memory layouts from. + */ + public ExecutionNodeSymbolicLayoutExtractor(IExecutionNode executionNode) { + super(executionNode.getProofNode(), executionNode.getModalityPIO(), + executionNode.getSettings().isUseUnicode(), + executionNode.getSettings().isUsePrettyPrinting(), + executionNode.getSettings().isSimplifyConditions()); + this.executionNode = executionNode; + } - /** - * {@inheritDoc} - */ - @Override - protected String computeInitialStateName() { - try { - return SymbolicExecutionUtil.getRoot(executionNode).getName() + " resulting in " + computeCurrentStateName(); - } - catch (ProofInputException e) { - return e.getMessage(); - } - } + /** + * {@inheritDoc} + */ + @Override + protected String computeInitialStateName() { + try { + return SymbolicExecutionUtil.getRoot(executionNode).getName() + " resulting in " + + computeCurrentStateName(); + } catch (ProofInputException e) { + return e.getMessage(); + } + } - /** - * {@inheritDoc} - */ - @Override - protected String computeCurrentStateName() { - try { - return executionNode.getName(); - } - catch (ProofInputException e) { - return e.getMessage(); - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + protected String computeCurrentStateName() { + try { + return executionNode.getName(); + } catch (ProofInputException e) { + return e.getMessage(); + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeWriter.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeWriter.java index d5b491b59cd..d59561516f2 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeWriter.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionNodeWriter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.io.File; @@ -38,1267 +41,1285 @@ import de.uka.ilkd.key.util.LinkedHashMap; /** - * Allows to persistent selected properties of {@link IExecutionNode}s - * as XML file. Such files can be read via an {@link ExecutionNodeReader} instance. + * Allows to persistent selected properties of {@link IExecutionNode}s as XML file. Such files can + * be read via an {@link ExecutionNodeReader} instance. + * * @author Martin Hentschel * @see ExecutionNodeReader */ -public class ExecutionNodeWriter extends AbstractWriter { - /** - * Attribute name to store {@link IExecutionElement#getName()}. - */ - public static final String ATTRIBUTE_NAME = "name"; - - /** - * Attribute name to store {@link IExecutionMethodReturn#getNameIncludingReturnValue()}. - */ - public static final String ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE = "nameIncludingReturnValue"; - - /** - * Attribute name to store {@link IExecutionMethodReturn#getSignatureIncludingReturnValue()}. - */ - public static final String ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE = "signatureIncludingReturnValue"; - - /** - * Attribute name to store {@link IExecutionMethodReturn#getSignature()}. - */ - public static final String ATTRIBUTE_SIGNATURE = "signature"; - - /** - * Attribute exceptional termination to store {@link IExecutionTermination#getTerminationKind()}. - */ - public static final String ATTRIBUTE_TERMINATION_KIND = "terminationKind"; - - /** - * Attribute name to store {@link IExecutionVariable#getTypeString()}. - */ - public static final String ATTRIBUTE_TYPE_STRING = "typeString"; - - /** - * Attribute name to store {@link IExecutionVariable#getValueString()}. - */ - public static final String ATTRIBUTE_VALUE_STRING = "valueString"; - - /** - * Attribute name to store {@link IExecutionValue#getConditionString()}. - */ - public static final String ATTRIBUTE_CONDITION_STRING = "conditionString"; - - /** - * Attribute name to store {@link IExecutionMethodReturnValue#getReturnValueString()}. - */ - public static final String ATTRIBUTE_RETURN_VALUE_STRING = "returnValueString"; - - /** - * Attribute name to store {@link IExecutionMethodReturnValue#hasCondition()}. - */ - public static final String ATTRIBUTE_HAS_CONDITION = "hasCondition"; - - /** - * Attribute name to store {@link IExecutionTermination#isBranchVerified()}. - */ - public static final String ATTRIBUTE_BRANCH_VERIFIED = "branchVerified"; - - /** - * Attribute name to store {@link IExecutionVariable#getArrayIndexString()}. - */ - public static final String ATTRIBUTE_ARRAY_INDEX = "arrayIndex"; - - /** - * Attribute name to store {@link IExecutionVariable#isArrayIndex()}. - */ - public static final String ATTRIBUTE_IS_ARRAY_INDEX = "isArrayIndex"; - - /** - * Attribute name to store {@link IExecutionBranchCondition#getFormatedBranchCondition()}. - */ - public static final String ATTRIBUTE_BRANCH_CONDITION = "branchCondition"; - - /** - * Attribute name to store {@link IExecutionNode#getPathCondition()}. - */ - public static final String ATTRIBUTE_PATH_CONDITION = "pathCondition"; - - /** - * Attribute name to store {@link IExecutionNode#isPathConditionChanged()}. - */ - public static final String ATTRIBUTE_PATH_CONDITION_CHANGED = "pathConditionChanged"; - - /** - * A path which refers to an {@link IExecutionNode} starting from the root. - */ - public static final String ATTRIBUTE_PATH_IN_TREE = "path"; - - /** - * Attribute name to store {@link IExecutionBranchCondition#isMergedBranchCondition()}. - */ - public static final String ATTRIBUTE_MERGED_BRANCH_CONDITION = "mergedBranchCondition"; - - /** - * Attribute name to store {@link IExecutionVariable#isValueAnObject()}. - */ - public static final String ATTRIBUTE_IS_VALUE_AN_OBJECT = "isValueAnObject"; - - /** - * Attribute name to store {@link IExecutionVariable#isValueUnknown()}. - */ - public static final String ATTRIBUTE_IS_VALUE_UNKNOWN = "isValueUnknown"; - - /** - * Attribute name to store {@link IExecutionOperationContract#isPreconditionComplied()}. - */ - public static final String ATTRIBUTE_PRECONDITION_COMPLIED = "preconditionComplied"; - - /** - * Attribute name to store {@link IExecutionOperationContract#hasNotNullCheck()}. - */ - public static final String ATTRIBUTE_HAS_NOT_NULL_CHECK = "hasNotNullCheck"; - - /** - * Attribute name to store {@link IExecutionMethodReturn#isReturnValuesComputed()}. - */ - public static final String ATTRIBUTE_RETURN_VALUE_COMPUTED = "isReturnValueComputed"; - - /** - * Attribute name to store {@link IExecutionBranchCondition#isBranchConditionComputed()}. - */ - public static final String ATTRIBUTE_BRANCH_CONDITION_COMPUTED = "isBranchConditionComputed"; - - /** - * Attribute name to store {@link IExecutionOperationContract#isNotNullCheckComplied()}. - */ - public static final String ATTRIBUTE_NOT_NULL_CHECK_COMPLIED = "notNullCheckComplied"; - - /** - * Attribute name to store {@link IExecutionLoopInvariant#isInitiallyValid()}. - */ - public static final String ATTRIBUTE_INITIALLY_VALID = "initiallyValid"; - - /** - * Attribute name to store {@link IExecutionBranchCondition#getAdditionalBranchLabel()}. - */ - public static final String ATTRIBUTE_ADDITIONAL_BRANCH_LABEL = "additionalBranchLabel"; - - /** - * Attribute name to store {@link IExecutionMethodReturn#getMethodReturnCondition()}. - */ - public static final String ATTRIBUTE_METHOD_RETURN_CONDITION = "methodReturnCondition"; - - /** - * Attribute name to store {@link IExecutionOperationContract#getFormatedResultTerm()}. - */ - public static final String ATTRIBUTE_RESULT_TERM = "resultTerm"; - - /** - * Attribute name to store {@link IExecutionOperationContract#getFormatedExceptionTerm()}. - */ - public static final String ATTRIBUTE_EXCEPTION_TERM = "exceptionTerm"; - - /** - * Attribute name to store {@link IExecutionOperationContract#getFormatedSelfTerm()}. - */ - public static final String ATTRIBUTE_SELF_TERM = "selfTerm"; - - /** - * Attribute name to store {@link IExecutionOperationContract#getFormatedContractParams()}. - */ - public static final String ATTRIBUTE_CONTRACT_PARAMETERS = "contractParameters"; - - /** - * Attribute name to store {@link IExecutionBlockStartNode#isBlockOpened()}. - */ - public static final String ATTRIBUTE_BLOCK_OPENED = "blockOpened"; - - /** - * Attribute name to store {@link IExecutionJoin#isWeakeningVerified()}. - */ - public static final String ATTRIBUTE_WEAKENING_VERIFIED = "weakeningVerified"; - - /** - * Tag name to store {@link IExecutionBranchCondition}s. - */ - public static final String TAG_BRANCH_CONDITION = "branchCondition"; - - /** - * Tag name to store {@link IExecutionStart}s. - */ - public static final String TAG_START = "start"; - - /** - * Tag name to store {@link IExecutionBranchStatement}s. - */ - public static final String TAG_BRANCH_STATEMENT = "branchStatement"; - - /** - * Tag name to store {@link IExecutionLoopCondition}s. - */ - public static final String TAG_LOOP_CONDITION = "loopCondition"; - - /** - * Tag name to store {@link IExecutionLoopStatement}s. - */ - public static final String TAG_LOOP_STATEMENT = "loopStatement"; - - /** - * Tag name to store {@link IExecutionMethodCall}s. - */ - public static final String TAG_METHOD_CALL = "methodCall"; - - /** - * Tag name to store {@link IExecutionMethodReturn}s. - */ - public static final String TAG_METHOD_RETURN = "methodReturn"; - - /** - * Tag name to store {@link IExecutionExceptionalMethodReturn}s. - */ - public static final String TAG_EXCEPTIONAL_METHOD_RETURN = "exceptionalMethodReturn"; - - /** - * Tag name to store {@link IExecutionMethodReturnValue}s. - */ - public static final String TAG_METHOD_RETURN_VALUE = "methodReturnValue"; - - /** - * Tag name to store {@link IExecutionStatement}s. - */ - public static final String TAG_STATEMENT = "statement"; - - /** - * Tag name to store {@link IExecutionTermination}s. - */ - public static final String TAG_TERMINATION = "termination"; - - /** - * Tag name to store {@link IExecutionJoin}s. - */ - public static final String TAG_JOIN = "join"; - - /** - * Tag name to store {@link IExecutionOperationContract}s. - */ - public static final String TAG_OPERATION_CONTRACT = "operationContract"; - - /** - * Tag name to store {@link IExecutionAuxiliaryContract}s. - */ - public static final String TAG_BLOCK_CONTRACT = "blockContract"; - - /** - * Tag name to store {@link IExecutionLoopInvariant}s. - */ - public static final String TAG_LOOP_INVARIANT = "loopInvariant"; - - /** - * Tag name to store {@link IExecutionConstraint}s. - */ - public static final String TAG_CONSTRAINT = "constraint"; - - /** - * Tag name to store {@link IExecutionVariable}s. - */ - public static final String TAG_VARIABLE = "variable"; - - /** - * Tag name to store call state {@link IExecutionVariable}s. - */ - public static final String TAG_CALL_STATE_VARIABLE = "callStateVariable"; - - /** - * Tag name to store {@link IExecutionValue}s. - */ - public static final String TAG_VALUE = "value"; - - /** - * Tag name to store one entry of {@link IExecutionNode#getCallStack()}. - */ - public static final String TAG_CALL_STACK_ENTRY = "callStackEntry"; - - /** - * Tag name to store one entry of {@link IExecutionMethodCall#getMethodReturns()}. - */ - public static final String TAG_METHOD_RETURN_ENTRY = "methodReturnEntry"; - - /** - * Tag name to store on entry of {@link IExecutionNode#getCompletedBlocks()} - * together with its condition {@link IExecutionNode#getFormatedBlockCompletionCondition(IExecutionNode)}. - */ - public static final String TAG_COMPLETED_BLOCK_ENTRY = "completedBlockEntry"; - - /** - * Tag name to store one entry of {@link IExecutionBranchStatement#getBlockCompletions()}. - */ - public static final String TAG_BLOCK_COMPLETION_ENTRY = "blockCompletionEntry"; - - /** - * Tag name to store one entry of {@link IExecutionStart#getTerminations()}. - */ - public static final String TAG_TERMINATION_ENTRY = "terminationEntry"; - - /** - * Tag name to store one entry of {@link IExecutionNode#getOutgoingLinks()}. - */ - public static final String TAG_OUTGOING_LINK = "outgoingLink"; - - /** - * Character to separate path entries in attributes {@value #ATTRIBUTE_PATH_IN_TREE}. - */ - public static final char PATH_SEPARATOR = '/'; - - /** - * Writes the given {@link IExecutionNode} as XML file. - * @param node The {@link IExecutionNode} to save. - * @param encoding The encoding to use. - * @param file The {@link File} to save to. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @throws IOException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - public void write(IExecutionNode node, - String encoding, - File file, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints) throws IOException, ProofInputException { - write(node, encoding, new FileOutputStream(file), saveVariables, saveCallStack, saveReturnValues, saveConstraints); - } - - /** - * Writes the given {@link IExecutionNode} into the {@link OutputStream}. - * @param node The {@link IExecutionNode} to save. - * @param encoding The encoding to use. - * @param out The {@link OutputStream} to save to. The {@link OutputStream} will be closed by this method. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @throws IOException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - public void write(IExecutionNode node, - String encoding, - OutputStream out, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints) throws IOException, ProofInputException { - if (out != null) { - try { - Charset charset = encoding != null ? Charset.forName(encoding) : Charset.defaultCharset(); - String xml = toXML(node, charset.displayName(), saveVariables, saveCallStack, saveReturnValues, saveConstraints); - out.write(xml.getBytes(charset)); - } - finally { - out.close(); - } - } - } - - /** - * Converts the given {@link IExecutionNode} into XML. - * @param node The {@link IExecutionNode} to convert. - * @param encoding The encoding to use. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @return The created XML content. - * @throws ProofInputException Occurred Exception. - */ - public String toXML(IExecutionNode node, - String encoding, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints) throws ProofInputException { - StringBuffer sb = new StringBuffer(); - appendXmlHeader(encoding, sb); - appendExecutionNode(0, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - return sb.toString(); - } - - /** - * Converts the given {@link IExecutionNode} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionNode} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionNode(int level, - IExecutionNode node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - if (node instanceof IExecutionBranchCondition) { - appendExecutionBranchCondition(level, (IExecutionBranchCondition)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionStart) { - appendExecutionStart(level, (IExecutionStart)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionBranchStatement) { - appendExecutionBranchStatement(level, (IExecutionBranchStatement)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionLoopCondition) { - appendExecutionLoopCondition(level, (IExecutionLoopCondition)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionLoopStatement) { - appendExecutionLoopStatement(level, (IExecutionLoopStatement)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionMethodCall) { - appendExecutionMethodCall(level, (IExecutionMethodCall)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionMethodReturn) { - appendExecutionMethodReturn(level, (IExecutionMethodReturn)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionExceptionalMethodReturn) { - appendExecutionExceptionalMethodReturn(level, (IExecutionExceptionalMethodReturn)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionStatement) { - appendExecutionStatement(level, (IExecutionStatement)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionTermination) { - appendExecutionTermination(level, (IExecutionTermination)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionOperationContract) { - appendExecutionOperationContract(level, (IExecutionOperationContract)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionLoopInvariant) { - appendExecutionLoopInvariant(level, (IExecutionLoopInvariant)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionAuxiliaryContract) { - appendExecutionBlockContract(level, (IExecutionAuxiliaryContract)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else if (node instanceof IExecutionJoin) { - appendExecutionJoin(level, (IExecutionJoin)node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - else { - throw new IllegalArgumentException("Not supported node \"" + node + "\"."); - } - } - - /** - * Converts the given {@link IExecutionBranchCondition} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionBranchCondition} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionBranchCondition(int level, - IExecutionBranchCondition node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_BRANCH_CONDITION, node.getFormatedBranchCondition()); - attributeValues.put(ATTRIBUTE_MERGED_BRANCH_CONDITION, node.isMergedBranchCondition() + ""); - attributeValues.put(ATTRIBUTE_BRANCH_CONDITION_COMPUTED, node.isBranchConditionComputed() + ""); - attributeValues.put(ATTRIBUTE_ADDITIONAL_BRANCH_LABEL, node.getAdditionalBranchLabel()); - appendStartTag(level, TAG_BRANCH_CONDITION, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_BRANCH_CONDITION, sb); - } - - /** - * Converts the given {@link IExecutionStart} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionStart} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionStart(int level, - IExecutionStart node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - appendStartTag(level, TAG_START, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendTerminations(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_START, sb); - } - - /** - * Appends the termination entries to the given {@link StringBuffer}. - * @param level The level of the children. - * @param node The {@link IExecutionStart} which provides the termination entries. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendTerminations(int level, IExecutionStart node, StringBuffer sb) { - ImmutableList terminations = node.getTerminations(); - if (terminations != null) { - for (IExecutionTermination termination : terminations) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(termination)); - appendEmptyTag(level, TAG_TERMINATION_ENTRY, attributeValues, sb); - } - } - } - - /** - * Converts the given {@link IExecutionLoopCondition} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionLoopCondition} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionBranchStatement(int level, - IExecutionBranchStatement node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); - appendStartTag(level, TAG_BRANCH_STATEMENT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendBlockCompletions(level + 1, node, sb); - appendEndTag(level, TAG_BRANCH_STATEMENT, sb); - } - - /** - * Converts the given {@link IExecutionLoopCondition} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionLoopCondition} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionLoopCondition(int level, - IExecutionLoopCondition node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); - appendStartTag(level, TAG_LOOP_CONDITION, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendBlockCompletions(level + 1, node, sb); - appendEndTag(level, TAG_LOOP_CONDITION, sb); - } - - /** - * Converts the given {@link IExecutionLoopStatement} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionLoopStatement} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionLoopStatement(int level, - IExecutionLoopStatement node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); - appendStartTag(level, TAG_LOOP_STATEMENT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendBlockCompletions(level + 1, node, sb); - appendEndTag(level, TAG_LOOP_STATEMENT, sb); - } - - /** - * Converts the given {@link IExecutionMethodCall} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionMethodCall} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionMethodCall(int level, - IExecutionMethodCall node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - appendStartTag(level, TAG_METHOD_CALL, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendMethodReturns(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_METHOD_CALL, sb); - } - - /** - * Converts the given {@link IExecutionMethodReturn} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionMethodReturn} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionMethodReturn(int level, - IExecutionMethodReturn node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_SIGNATURE, node.getSignature()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - if (saveReturnValues) { - attributeValues.put(ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE, node.getNameIncludingReturnValue()); - attributeValues.put(ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE, node.getSignatureIncludingReturnValue()); - } - attributeValues.put(ATTRIBUTE_RETURN_VALUE_COMPUTED, node.isReturnValuesComputed() + ""); - attributeValues.put(ATTRIBUTE_METHOD_RETURN_CONDITION, node.getFormatedMethodReturnCondition()); - appendStartTag(level, TAG_METHOD_RETURN, attributeValues, sb); - if (saveReturnValues) { - IExecutionMethodReturnValue[] returnValues = node.getReturnValues(); - for (IExecutionMethodReturnValue returnValue : returnValues) { - appendExecutionMethodReturnValue(level + 1, returnValue, sb); - } - } - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendCallStateVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendEndTag(level, TAG_METHOD_RETURN, sb); - } - - /** - * Converts the given {@link IExecutionExceptionalMethodReturn} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionExceptionalMethodReturn} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionExceptionalMethodReturn(int level, - IExecutionExceptionalMethodReturn node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_SIGNATURE, node.getSignature()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_METHOD_RETURN_CONDITION, node.getFormatedMethodReturnCondition()); - appendStartTag(level, TAG_EXCEPTIONAL_METHOD_RETURN, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendCallStateVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendEndTag(level, TAG_EXCEPTIONAL_METHOD_RETURN, sb); - } - - /** - * Converts the given {@link IExecutionMethodReturnValue} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param returnValue The {@link IExecutionMethodReturnValue} to convert. - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionMethodReturnValue(int level, - IExecutionMethodReturnValue returnValue, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, returnValue.getName()); - attributeValues.put(ATTRIBUTE_RETURN_VALUE_STRING, returnValue.getReturnValueString()); - attributeValues.put(ATTRIBUTE_HAS_CONDITION, returnValue.hasCondition() + ""); - attributeValues.put(ATTRIBUTE_CONDITION_STRING, returnValue.getConditionString()); - appendStartTag(level, TAG_METHOD_RETURN_VALUE, attributeValues, sb); - appendEndTag(level, TAG_METHOD_RETURN_VALUE, sb); - } - - /** - * Converts the given {@link IExecutionStatement} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionStatement} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionStatement(int level, - IExecutionStatement node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - appendStartTag(level, TAG_STATEMENT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_STATEMENT, sb); - } - - /** - * Converts the given {@link IExecutionJoin} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionJoin} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionJoin(int level, - IExecutionJoin node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_WEAKENING_VERIFIED, node.isWeakeningVerified() + ""); - appendStartTag(level, TAG_JOIN, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_JOIN, sb); - } - - /** - * Converts the given {@link IExecutionOperationContract} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionOperationContract} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionOperationContract(int level, - IExecutionOperationContract node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_RESULT_TERM, node.getFormatedResultTerm()); - attributeValues.put(ATTRIBUTE_EXCEPTION_TERM, node.getFormatedExceptionTerm()); - attributeValues.put(ATTRIBUTE_SELF_TERM, node.getFormatedSelfTerm()); - attributeValues.put(ATTRIBUTE_CONTRACT_PARAMETERS, node.getFormatedContractParams()); - - attributeValues.put(ATTRIBUTE_PRECONDITION_COMPLIED, node.isPreconditionComplied() + ""); - attributeValues.put(ATTRIBUTE_HAS_NOT_NULL_CHECK, node.hasNotNullCheck() + ""); - attributeValues.put(ATTRIBUTE_NOT_NULL_CHECK_COMPLIED, node.isNotNullCheckComplied() + ""); - - appendStartTag(level, TAG_OPERATION_CONTRACT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_OPERATION_CONTRACT, sb); - } - - /** - * Converts the given {@link IExecutionLoopInvariant} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionLoopInvariant} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionLoopInvariant(int level, - IExecutionLoopInvariant node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - - attributeValues.put(ATTRIBUTE_INITIALLY_VALID, node.isInitiallyValid() + ""); - - appendStartTag(level, TAG_LOOP_INVARIANT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_LOOP_INVARIANT, sb); - } - - /** - * Converts the given {@link IExecutionAuxiliaryContract} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionLoopInvariant} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionBlockContract(int level, - IExecutionAuxiliaryContract node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - - attributeValues.put(ATTRIBUTE_PRECONDITION_COMPLIED, node.isPreconditionComplied() + ""); - - appendStartTag(level, TAG_BLOCK_CONTRACT, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_BLOCK_CONTRACT, sb); - } - - /** - * Converts the given {@link IExecutionTermination} into XML and appends it to the {@link StringBuffer}. - * @param level The current child level. - * @param node The {@link IExecutionTermination} to convert. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendExecutionTermination(int level, - IExecutionTermination node, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, node.getName()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); - attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); - attributeValues.put(ATTRIBUTE_TERMINATION_KIND, node.getTerminationKind().toString()); - attributeValues.put(ATTRIBUTE_BRANCH_VERIFIED, node.isBranchVerified() + ""); - appendStartTag(level, TAG_TERMINATION, attributeValues, sb); - appendConstraints(level + 1, node, saveConstraints, sb); - appendVariables(level + 1, node, saveVariables, saveConstraints, sb); - appendCallStack(level + 1, node, saveCallStack, sb); - appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - appendOutgoingLinks(level + 1, node, sb); - appendCompletedBlocks(level + 1, node, sb); - appendEndTag(level, TAG_TERMINATION, sb); - } - - /** - * Appends the contained {@link IExecutionConstraint}s to the given {@link StringBuffer}. - * @param level The level to use. - * @param value The {@link IExecutionValue} which provides the {@link IExecutionConstraint}s. - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendConstraints(int level, IExecutionValue value, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - if (saveConstraints) { - IExecutionConstraint[] constraints = value.getConstraints(); - for (IExecutionConstraint constraint : constraints) { - appendConstraint(level, constraint, sb); - } - } - } - - /** - * Appends the contained {@link IExecutionConstraint}s to the given {@link StringBuffer}. - * @param level The level to use. - * @param node The {@link IExecutionNode} which provides the {@link IExecutionConstraint}s. - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendConstraints(int level, IExecutionNode node, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - if (saveConstraints) { - IExecutionConstraint[] constraints = node.getConstraints(); - for (IExecutionConstraint constraint : constraints) { - appendConstraint(level, constraint, sb); - } - } - } - - /** - * Appends the given {@link IExecutionConstraint} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param constraint The {@link IExecutionConstraint} to append. - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendConstraint(int level, IExecutionConstraint constraint, StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, constraint.getName()); - appendEmptyTag(level, TAG_CONSTRAINT, attributeValues, sb); - } - - /** - * Appends the contained {@link IExecutionVariable}s to the given {@link StringBuffer}. - * @param level The level to use. - * @param node The {@link IExecutionNode} which provides the {@link IExecutionVariable}s. - * @param saveVariables Save variables? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendVariables(int level, IExecutionNode node, boolean saveVariables, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - if (saveVariables) { - IExecutionVariable[] variables = node.getVariables(); - for (IExecutionVariable variable : variables) { - appendVariable(level, variable, saveConstraints, TAG_VARIABLE, sb); - } - } - } - - /** - * Appends the contained {@link IExecutionVariable}s to the given {@link StringBuffer}. - * @param level The level to use. - * @param node The {@link IExecutionNode} which provides the {@link IExecutionVariable}s. - * @param saveVariables Save variables? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendCallStateVariables(int level, IExecutionBaseMethodReturn node, boolean saveVariables, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - if (saveVariables) { - IExecutionVariable[] variables = node.getCallStateVariables(); - for (IExecutionVariable variable : variables) { - appendVariable(level, variable, saveConstraints, TAG_CALL_STATE_VARIABLE, sb); - } - } - } - - /** - * Appends the given {@link IExecutionVariable} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param variable The {@link IExecutionVariable} to append. - * @param saveConstraints Save constraints? - * @param tagName The tag name to store an {@link IExecutionVariable}. - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendVariable(int level, IExecutionVariable variable, boolean saveConstraints, String tagName, StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, variable.getName()); - attributeValues.put(ATTRIBUTE_ARRAY_INDEX, variable.getArrayIndexString()); - attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, variable.isArrayIndex() + ""); - appendStartTag(level, tagName, attributeValues, sb); - appendValues(level + 1, variable, saveConstraints, sb); - appendEndTag(level, tagName, sb); - } - - /** - * Appends the contained {@link IExecutionValue}s to the given {@link StringBuffer}. - * @param level The level to use. - * @param variable The {@link IExecutionVariable} which provides the {@link IExecutionValue}s. - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendValues(int level, IExecutionVariable variable, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - IExecutionValue[] values = variable.getValues(); - for (IExecutionValue value : values) { - appendValue(level, value, saveConstraints, sb); - } - } - - /** - * Appends the given {@link IExecutionValue} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param value The {@link IExecutionValue} to append. - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendValue(int level, IExecutionValue value, boolean saveConstraints, StringBuffer sb) throws ProofInputException { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, value.getName()); - attributeValues.put(ATTRIBUTE_TYPE_STRING, value.getTypeString()); - attributeValues.put(ATTRIBUTE_VALUE_STRING, value.getValueString()); - attributeValues.put(ATTRIBUTE_IS_VALUE_AN_OBJECT, value.isValueAnObject() + ""); - attributeValues.put(ATTRIBUTE_IS_VALUE_UNKNOWN, value.isValueUnknown() + ""); - attributeValues.put(ATTRIBUTE_CONDITION_STRING, value.getConditionString()); - appendStartTag(level, TAG_VALUE, attributeValues, sb); - // Constraints - appendConstraints(level + 1, value, saveConstraints, sb); - // Children - IExecutionVariable[] childVariables = value.getChildVariables(); - for (IExecutionVariable childVariable : childVariables) { - appendVariable(level + 1, childVariable, saveConstraints, TAG_VARIABLE, sb); - } - appendEndTag(level, TAG_VALUE, sb); - } - - /** - * Appends the child nodes to the given {@link StringBuffer}. - * @param childLevel The level of the children. - * @param parent The parent {@link IExecutionNode} which provides the children. - * @param saveVariables Save variables? - * @param saveCallStack Save method call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception. - */ - protected void appendChildren(int childLevel, - IExecutionNode parent, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints, - StringBuffer sb) throws ProofInputException { - IExecutionNode[] children = parent.getChildren(); - for (IExecutionNode child : children) { - appendExecutionNode(childLevel, child, saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); - } - } - - protected void appendOutgoingLinks(int level, IExecutionNode node, StringBuffer sb) { - if (!node.getOutgoingLinks().isEmpty()) { - for (IExecutionLink link : node.getOutgoingLinks()) { - appendOutgoingLink(level, link, sb); - } - } - } - - protected void appendOutgoingLink(int level, IExecutionLink link, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(link.getTarget())); - appendEmptyTag(level, TAG_OUTGOING_LINK, attributeValues, sb); - } - - /** - * Appends the call stack entries if required to the given {@link StringBuffer}. - * @param level The level of the children. - * @param node The {@link IExecutionNode} which provides the call stack. - * @param saveCallStack Defines if the call stack should be saved or not. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendCallStack(int level, IExecutionNode node, boolean saveCallStack, StringBuffer sb) { - if (saveCallStack) { - IExecutionNode[] callStack = node.getCallStack(); - if (callStack != null) { - for (IExecutionNode stackNode : callStack) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(stackNode)); - appendEmptyTag(level, TAG_CALL_STACK_ENTRY, attributeValues, sb); +public class ExecutionNodeWriter extends AbstractWriter { + /** + * Attribute name to store {@link IExecutionElement#getName()}. + */ + public static final String ATTRIBUTE_NAME = "name"; + + /** + * Attribute name to store {@link IExecutionMethodReturn#getNameIncludingReturnValue()}. + */ + public static final String ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE = "nameIncludingReturnValue"; + + /** + * Attribute name to store {@link IExecutionMethodReturn#getSignatureIncludingReturnValue()}. + */ + public static final String ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE = + "signatureIncludingReturnValue"; + + /** + * Attribute name to store {@link IExecutionMethodReturn#getSignature()}. + */ + public static final String ATTRIBUTE_SIGNATURE = "signature"; + + /** + * Attribute exceptional termination to store + * {@link IExecutionTermination#getTerminationKind()}. + */ + public static final String ATTRIBUTE_TERMINATION_KIND = "terminationKind"; + + /** + * Attribute name to store {@link IExecutionVariable#getTypeString()}. + */ + public static final String ATTRIBUTE_TYPE_STRING = "typeString"; + + /** + * Attribute name to store {@link IExecutionVariable#getValueString()}. + */ + public static final String ATTRIBUTE_VALUE_STRING = "valueString"; + + /** + * Attribute name to store {@link IExecutionValue#getConditionString()}. + */ + public static final String ATTRIBUTE_CONDITION_STRING = "conditionString"; + + /** + * Attribute name to store {@link IExecutionMethodReturnValue#getReturnValueString()}. + */ + public static final String ATTRIBUTE_RETURN_VALUE_STRING = "returnValueString"; + + /** + * Attribute name to store {@link IExecutionMethodReturnValue#hasCondition()}. + */ + public static final String ATTRIBUTE_HAS_CONDITION = "hasCondition"; + + /** + * Attribute name to store {@link IExecutionTermination#isBranchVerified()}. + */ + public static final String ATTRIBUTE_BRANCH_VERIFIED = "branchVerified"; + + /** + * Attribute name to store {@link IExecutionVariable#getArrayIndexString()}. + */ + public static final String ATTRIBUTE_ARRAY_INDEX = "arrayIndex"; + + /** + * Attribute name to store {@link IExecutionVariable#isArrayIndex()}. + */ + public static final String ATTRIBUTE_IS_ARRAY_INDEX = "isArrayIndex"; + + /** + * Attribute name to store {@link IExecutionBranchCondition#getFormatedBranchCondition()}. + */ + public static final String ATTRIBUTE_BRANCH_CONDITION = "branchCondition"; + + /** + * Attribute name to store {@link IExecutionNode#getPathCondition()}. + */ + public static final String ATTRIBUTE_PATH_CONDITION = "pathCondition"; + + /** + * Attribute name to store {@link IExecutionNode#isPathConditionChanged()}. + */ + public static final String ATTRIBUTE_PATH_CONDITION_CHANGED = "pathConditionChanged"; + + /** + * A path which refers to an {@link IExecutionNode} starting from the root. + */ + public static final String ATTRIBUTE_PATH_IN_TREE = "path"; + + /** + * Attribute name to store {@link IExecutionBranchCondition#isMergedBranchCondition()}. + */ + public static final String ATTRIBUTE_MERGED_BRANCH_CONDITION = "mergedBranchCondition"; + + /** + * Attribute name to store {@link IExecutionVariable#isValueAnObject()}. + */ + public static final String ATTRIBUTE_IS_VALUE_AN_OBJECT = "isValueAnObject"; + + /** + * Attribute name to store {@link IExecutionVariable#isValueUnknown()}. + */ + public static final String ATTRIBUTE_IS_VALUE_UNKNOWN = "isValueUnknown"; + + /** + * Attribute name to store {@link IExecutionOperationContract#isPreconditionComplied()}. + */ + public static final String ATTRIBUTE_PRECONDITION_COMPLIED = "preconditionComplied"; + + /** + * Attribute name to store {@link IExecutionOperationContract#hasNotNullCheck()}. + */ + public static final String ATTRIBUTE_HAS_NOT_NULL_CHECK = "hasNotNullCheck"; + + /** + * Attribute name to store {@link IExecutionMethodReturn#isReturnValuesComputed()}. + */ + public static final String ATTRIBUTE_RETURN_VALUE_COMPUTED = "isReturnValueComputed"; + + /** + * Attribute name to store {@link IExecutionBranchCondition#isBranchConditionComputed()}. + */ + public static final String ATTRIBUTE_BRANCH_CONDITION_COMPUTED = "isBranchConditionComputed"; + + /** + * Attribute name to store {@link IExecutionOperationContract#isNotNullCheckComplied()}. + */ + public static final String ATTRIBUTE_NOT_NULL_CHECK_COMPLIED = "notNullCheckComplied"; + + /** + * Attribute name to store {@link IExecutionLoopInvariant#isInitiallyValid()}. + */ + public static final String ATTRIBUTE_INITIALLY_VALID = "initiallyValid"; + + /** + * Attribute name to store {@link IExecutionBranchCondition#getAdditionalBranchLabel()}. + */ + public static final String ATTRIBUTE_ADDITIONAL_BRANCH_LABEL = "additionalBranchLabel"; + + /** + * Attribute name to store {@link IExecutionMethodReturn#getMethodReturnCondition()}. + */ + public static final String ATTRIBUTE_METHOD_RETURN_CONDITION = "methodReturnCondition"; + + /** + * Attribute name to store {@link IExecutionOperationContract#getFormatedResultTerm()}. + */ + public static final String ATTRIBUTE_RESULT_TERM = "resultTerm"; + + /** + * Attribute name to store {@link IExecutionOperationContract#getFormatedExceptionTerm()}. + */ + public static final String ATTRIBUTE_EXCEPTION_TERM = "exceptionTerm"; + + /** + * Attribute name to store {@link IExecutionOperationContract#getFormatedSelfTerm()}. + */ + public static final String ATTRIBUTE_SELF_TERM = "selfTerm"; + + /** + * Attribute name to store {@link IExecutionOperationContract#getFormatedContractParams()}. + */ + public static final String ATTRIBUTE_CONTRACT_PARAMETERS = "contractParameters"; + + /** + * Attribute name to store {@link IExecutionBlockStartNode#isBlockOpened()}. + */ + public static final String ATTRIBUTE_BLOCK_OPENED = "blockOpened"; + + /** + * Attribute name to store {@link IExecutionJoin#isWeakeningVerified()}. + */ + public static final String ATTRIBUTE_WEAKENING_VERIFIED = "weakeningVerified"; + + /** + * Tag name to store {@link IExecutionBranchCondition}s. + */ + public static final String TAG_BRANCH_CONDITION = "branchCondition"; + + /** + * Tag name to store {@link IExecutionStart}s. + */ + public static final String TAG_START = "start"; + + /** + * Tag name to store {@link IExecutionBranchStatement}s. + */ + public static final String TAG_BRANCH_STATEMENT = "branchStatement"; + + /** + * Tag name to store {@link IExecutionLoopCondition}s. + */ + public static final String TAG_LOOP_CONDITION = "loopCondition"; + + /** + * Tag name to store {@link IExecutionLoopStatement}s. + */ + public static final String TAG_LOOP_STATEMENT = "loopStatement"; + + /** + * Tag name to store {@link IExecutionMethodCall}s. + */ + public static final String TAG_METHOD_CALL = "methodCall"; + + /** + * Tag name to store {@link IExecutionMethodReturn}s. + */ + public static final String TAG_METHOD_RETURN = "methodReturn"; + + /** + * Tag name to store {@link IExecutionExceptionalMethodReturn}s. + */ + public static final String TAG_EXCEPTIONAL_METHOD_RETURN = "exceptionalMethodReturn"; + + /** + * Tag name to store {@link IExecutionMethodReturnValue}s. + */ + public static final String TAG_METHOD_RETURN_VALUE = "methodReturnValue"; + + /** + * Tag name to store {@link IExecutionStatement}s. + */ + public static final String TAG_STATEMENT = "statement"; + + /** + * Tag name to store {@link IExecutionTermination}s. + */ + public static final String TAG_TERMINATION = "termination"; + + /** + * Tag name to store {@link IExecutionJoin}s. + */ + public static final String TAG_JOIN = "join"; + + /** + * Tag name to store {@link IExecutionOperationContract}s. + */ + public static final String TAG_OPERATION_CONTRACT = "operationContract"; + + /** + * Tag name to store {@link IExecutionAuxiliaryContract}s. + */ + public static final String TAG_BLOCK_CONTRACT = "blockContract"; + + /** + * Tag name to store {@link IExecutionLoopInvariant}s. + */ + public static final String TAG_LOOP_INVARIANT = "loopInvariant"; + + /** + * Tag name to store {@link IExecutionConstraint}s. + */ + public static final String TAG_CONSTRAINT = "constraint"; + + /** + * Tag name to store {@link IExecutionVariable}s. + */ + public static final String TAG_VARIABLE = "variable"; + + /** + * Tag name to store call state {@link IExecutionVariable}s. + */ + public static final String TAG_CALL_STATE_VARIABLE = "callStateVariable"; + + /** + * Tag name to store {@link IExecutionValue}s. + */ + public static final String TAG_VALUE = "value"; + + /** + * Tag name to store one entry of {@link IExecutionNode#getCallStack()}. + */ + public static final String TAG_CALL_STACK_ENTRY = "callStackEntry"; + + /** + * Tag name to store one entry of {@link IExecutionMethodCall#getMethodReturns()}. + */ + public static final String TAG_METHOD_RETURN_ENTRY = "methodReturnEntry"; + + /** + * Tag name to store on entry of {@link IExecutionNode#getCompletedBlocks()} together with its + * condition {@link IExecutionNode#getFormatedBlockCompletionCondition(IExecutionNode)}. + */ + public static final String TAG_COMPLETED_BLOCK_ENTRY = "completedBlockEntry"; + + /** + * Tag name to store one entry of {@link IExecutionBranchStatement#getBlockCompletions()}. + */ + public static final String TAG_BLOCK_COMPLETION_ENTRY = "blockCompletionEntry"; + + /** + * Tag name to store one entry of {@link IExecutionStart#getTerminations()}. + */ + public static final String TAG_TERMINATION_ENTRY = "terminationEntry"; + + /** + * Tag name to store one entry of {@link IExecutionNode#getOutgoingLinks()}. + */ + public static final String TAG_OUTGOING_LINK = "outgoingLink"; + + /** + * Character to separate path entries in attributes {@value #ATTRIBUTE_PATH_IN_TREE}. + */ + public static final char PATH_SEPARATOR = '/'; + + /** + * Writes the given {@link IExecutionNode} as XML file. + * + * @param node The {@link IExecutionNode} to save. + * @param encoding The encoding to use. + * @param file The {@link File} to save to. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @throws IOException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + public void write(IExecutionNode node, String encoding, File file, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints) + throws IOException, ProofInputException { + write(node, encoding, new FileOutputStream(file), saveVariables, saveCallStack, + saveReturnValues, saveConstraints); + } + + /** + * Writes the given {@link IExecutionNode} into the {@link OutputStream}. + * + * @param node The {@link IExecutionNode} to save. + * @param encoding The encoding to use. + * @param out The {@link OutputStream} to save to. The {@link OutputStream} will be closed by + * this method. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @throws IOException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + public void write(IExecutionNode node, String encoding, OutputStream out, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints) throws IOException, ProofInputException { + if (out != null) { + try { + Charset charset = + encoding != null ? Charset.forName(encoding) : Charset.defaultCharset(); + String xml = toXML(node, charset.displayName(), saveVariables, saveCallStack, + saveReturnValues, saveConstraints); + out.write(xml.getBytes(charset)); + } finally { + out.close(); } - } - } - } - - /** - * Appends the method return entries to the given {@link StringBuffer}. - * @param level The level of the children. - * @param node The {@link IExecutionMethodCall} which provides the call stack. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendMethodReturns(int level, IExecutionMethodCall node, StringBuffer sb) { - ImmutableList> methodReturns = node.getMethodReturns(); - if (methodReturns != null) { - for (IExecutionBaseMethodReturn methodReturn : methodReturns) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(methodReturn)); - appendEmptyTag(level, TAG_METHOD_RETURN_ENTRY, attributeValues, sb); - } - } - } - - /** - * Appends the completed block entries to the given {@link StringBuffer}. - * @param level The level of the children. - * @param node The {@link IExecutionNode} which provides the block entries. - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception - */ - protected void appendCompletedBlocks(int level, IExecutionNode node, StringBuffer sb) throws ProofInputException { - ImmutableList> completedBlocks = node.getCompletedBlocks(); - if (completedBlocks != null) { - for (IExecutionBlockStartNode completedBlock : completedBlocks) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(completedBlock)); - attributeValues.put(ATTRIBUTE_CONDITION_STRING, node.getFormatedBlockCompletionCondition(completedBlock)); - appendEmptyTag(level, TAG_COMPLETED_BLOCK_ENTRY, attributeValues, sb); - } - } - } - - /** - * Appends the block completion entries to the given {@link StringBuffer}. - * @param level The level of the children. - * @param node The {@link IExecutionBlockStartNode} which provides the completed blocks. - * @param sb The {@link StringBuffer} to append to. - * @throws ProofInputException Occurred Exception - */ - protected void appendBlockCompletions(int level, IExecutionBlockStartNode node, StringBuffer sb) throws ProofInputException { - ImmutableList> blockCompletions = node.getBlockCompletions(); - if (blockCompletions != null) { - for (IExecutionNode blockCompletion : blockCompletions) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(blockCompletion)); - appendEmptyTag(level, TAG_BLOCK_COMPLETION_ENTRY, attributeValues, sb); - } - } - } - - /** - * Computes the path from the root of the symbolic execution tree to the given {@link IExecutionNode}. - * @param node The {@link IExecutionNode} to compute path to. - * @return The computed path. - */ - protected String computePath(IExecutionNode node) { - StringBuffer sb = new StringBuffer(); - boolean afterFirst = false; - while (node != null) { - IExecutionNode parent = node.getParent(); - if (parent != null) { - if (afterFirst) { - sb.insert(0, PATH_SEPARATOR); + } + } + + /** + * Converts the given {@link IExecutionNode} into XML. + * + * @param node The {@link IExecutionNode} to convert. + * @param encoding The encoding to use. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @return The created XML content. + * @throws ProofInputException Occurred Exception. + */ + public String toXML(IExecutionNode node, String encoding, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints) + throws ProofInputException { + StringBuffer sb = new StringBuffer(); + appendXmlHeader(encoding, sb); + appendExecutionNode(0, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + return sb.toString(); + } + + /** + * Converts the given {@link IExecutionNode} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionNode} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionNode(int level, IExecutionNode node, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + if (node instanceof IExecutionBranchCondition) { + appendExecutionBranchCondition(level, (IExecutionBranchCondition) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionStart) { + appendExecutionStart(level, (IExecutionStart) node, saveVariables, saveCallStack, + saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionBranchStatement) { + appendExecutionBranchStatement(level, (IExecutionBranchStatement) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionLoopCondition) { + appendExecutionLoopCondition(level, (IExecutionLoopCondition) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionLoopStatement) { + appendExecutionLoopStatement(level, (IExecutionLoopStatement) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionMethodCall) { + appendExecutionMethodCall(level, (IExecutionMethodCall) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionMethodReturn) { + appendExecutionMethodReturn(level, (IExecutionMethodReturn) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionExceptionalMethodReturn) { + appendExecutionExceptionalMethodReturn(level, (IExecutionExceptionalMethodReturn) node, + saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionStatement) { + appendExecutionStatement(level, (IExecutionStatement) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionTermination) { + appendExecutionTermination(level, (IExecutionTermination) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionOperationContract) { + appendExecutionOperationContract(level, (IExecutionOperationContract) node, + saveVariables, saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionLoopInvariant) { + appendExecutionLoopInvariant(level, (IExecutionLoopInvariant) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionAuxiliaryContract) { + appendExecutionBlockContract(level, (IExecutionAuxiliaryContract) node, saveVariables, + saveCallStack, saveReturnValues, saveConstraints, sb); + } else if (node instanceof IExecutionJoin) { + appendExecutionJoin(level, (IExecutionJoin) node, saveVariables, saveCallStack, + saveReturnValues, saveConstraints, sb); + } else { + throw new IllegalArgumentException("Not supported node \"" + node + "\"."); + } + } + + /** + * Converts the given {@link IExecutionBranchCondition} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionBranchCondition} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionBranchCondition(int level, IExecutionBranchCondition node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_BRANCH_CONDITION, node.getFormatedBranchCondition()); + attributeValues.put(ATTRIBUTE_MERGED_BRANCH_CONDITION, node.isMergedBranchCondition() + ""); + attributeValues.put(ATTRIBUTE_BRANCH_CONDITION_COMPUTED, + node.isBranchConditionComputed() + ""); + attributeValues.put(ATTRIBUTE_ADDITIONAL_BRANCH_LABEL, node.getAdditionalBranchLabel()); + appendStartTag(level, TAG_BRANCH_CONDITION, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_BRANCH_CONDITION, sb); + } + + /** + * Converts the given {@link IExecutionStart} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionStart} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionStart(int level, IExecutionStart node, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + appendStartTag(level, TAG_START, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendTerminations(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_START, sb); + } + + /** + * Appends the termination entries to the given {@link StringBuffer}. + * + * @param level The level of the children. + * @param node The {@link IExecutionStart} which provides the termination entries. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendTerminations(int level, IExecutionStart node, StringBuffer sb) { + ImmutableList terminations = node.getTerminations(); + if (terminations != null) { + for (IExecutionTermination termination : terminations) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(termination)); + appendEmptyTag(level, TAG_TERMINATION_ENTRY, attributeValues, sb); } - else { - afterFirst = true; + } + } + + /** + * Converts the given {@link IExecutionLoopCondition} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionLoopCondition} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionBranchStatement(int level, IExecutionBranchStatement node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); + appendStartTag(level, TAG_BRANCH_STATEMENT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendBlockCompletions(level + 1, node, sb); + appendEndTag(level, TAG_BRANCH_STATEMENT, sb); + } + + /** + * Converts the given {@link IExecutionLoopCondition} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionLoopCondition} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionLoopCondition(int level, IExecutionLoopCondition node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); + appendStartTag(level, TAG_LOOP_CONDITION, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendBlockCompletions(level + 1, node, sb); + appendEndTag(level, TAG_LOOP_CONDITION, sb); + } + + /** + * Converts the given {@link IExecutionLoopStatement} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionLoopStatement} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionLoopStatement(int level, IExecutionLoopStatement node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_BLOCK_OPENED, node.isBlockOpened() + ""); + appendStartTag(level, TAG_LOOP_STATEMENT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendBlockCompletions(level + 1, node, sb); + appendEndTag(level, TAG_LOOP_STATEMENT, sb); + } + + /** + * Converts the given {@link IExecutionMethodCall} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionMethodCall} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionMethodCall(int level, IExecutionMethodCall node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + appendStartTag(level, TAG_METHOD_CALL, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendMethodReturns(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_METHOD_CALL, sb); + } + + /** + * Converts the given {@link IExecutionMethodReturn} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionMethodReturn} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionMethodReturn(int level, IExecutionMethodReturn node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_SIGNATURE, node.getSignature()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + if (saveReturnValues) { + attributeValues.put(ATTRIBUTE_NAME_INCLUDING_RETURN_VALUE, + node.getNameIncludingReturnValue()); + attributeValues.put(ATTRIBUTE_SIGNATURE_INCLUDING_RETURN_VALUE, + node.getSignatureIncludingReturnValue()); + } + attributeValues.put(ATTRIBUTE_RETURN_VALUE_COMPUTED, node.isReturnValuesComputed() + ""); + attributeValues.put(ATTRIBUTE_METHOD_RETURN_CONDITION, + node.getFormatedMethodReturnCondition()); + appendStartTag(level, TAG_METHOD_RETURN, attributeValues, sb); + if (saveReturnValues) { + IExecutionMethodReturnValue[] returnValues = node.getReturnValues(); + for (IExecutionMethodReturnValue returnValue : returnValues) { + appendExecutionMethodReturnValue(level + 1, returnValue, sb); } - int index = ArrayUtil.indexOf(parent.getChildren(), node); - assert index >= 0 : "Node \"" + node + "\" is not contained in parents children \"" + Arrays.toString(parent.getChildren()) + "\"."; - sb.insert(0, index); - } - else { - sb.insert(0, PATH_SEPARATOR); - } - node = parent; - } - return sb.toString(); - } -} \ No newline at end of file + } + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendCallStateVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendEndTag(level, TAG_METHOD_RETURN, sb); + } + + /** + * Converts the given {@link IExecutionExceptionalMethodReturn} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionExceptionalMethodReturn} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionExceptionalMethodReturn(int level, + IExecutionExceptionalMethodReturn node, boolean saveVariables, boolean saveCallStack, + boolean saveReturnValues, boolean saveConstraints, StringBuffer sb) + throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_SIGNATURE, node.getSignature()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_METHOD_RETURN_CONDITION, + node.getFormatedMethodReturnCondition()); + appendStartTag(level, TAG_EXCEPTIONAL_METHOD_RETURN, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendCallStateVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendEndTag(level, TAG_EXCEPTIONAL_METHOD_RETURN, sb); + } + + /** + * Converts the given {@link IExecutionMethodReturnValue} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param returnValue The {@link IExecutionMethodReturnValue} to convert. + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionMethodReturnValue(int level, + IExecutionMethodReturnValue returnValue, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, returnValue.getName()); + attributeValues.put(ATTRIBUTE_RETURN_VALUE_STRING, returnValue.getReturnValueString()); + attributeValues.put(ATTRIBUTE_HAS_CONDITION, returnValue.hasCondition() + ""); + attributeValues.put(ATTRIBUTE_CONDITION_STRING, returnValue.getConditionString()); + appendStartTag(level, TAG_METHOD_RETURN_VALUE, attributeValues, sb); + appendEndTag(level, TAG_METHOD_RETURN_VALUE, sb); + } + + /** + * Converts the given {@link IExecutionStatement} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionStatement} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionStatement(int level, IExecutionStatement node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + appendStartTag(level, TAG_STATEMENT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_STATEMENT, sb); + } + + /** + * Converts the given {@link IExecutionJoin} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionJoin} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionJoin(int level, IExecutionJoin node, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_WEAKENING_VERIFIED, node.isWeakeningVerified() + ""); + appendStartTag(level, TAG_JOIN, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_JOIN, sb); + } + + /** + * Converts the given {@link IExecutionOperationContract} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionOperationContract} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionOperationContract(int level, IExecutionOperationContract node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_RESULT_TERM, node.getFormatedResultTerm()); + attributeValues.put(ATTRIBUTE_EXCEPTION_TERM, node.getFormatedExceptionTerm()); + attributeValues.put(ATTRIBUTE_SELF_TERM, node.getFormatedSelfTerm()); + attributeValues.put(ATTRIBUTE_CONTRACT_PARAMETERS, node.getFormatedContractParams()); + + attributeValues.put(ATTRIBUTE_PRECONDITION_COMPLIED, node.isPreconditionComplied() + ""); + attributeValues.put(ATTRIBUTE_HAS_NOT_NULL_CHECK, node.hasNotNullCheck() + ""); + attributeValues.put(ATTRIBUTE_NOT_NULL_CHECK_COMPLIED, node.isNotNullCheckComplied() + ""); + + appendStartTag(level, TAG_OPERATION_CONTRACT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_OPERATION_CONTRACT, sb); + } + + /** + * Converts the given {@link IExecutionLoopInvariant} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionLoopInvariant} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionLoopInvariant(int level, IExecutionLoopInvariant node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + + attributeValues.put(ATTRIBUTE_INITIALLY_VALID, node.isInitiallyValid() + ""); + + appendStartTag(level, TAG_LOOP_INVARIANT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_LOOP_INVARIANT, sb); + } + + /** + * Converts the given {@link IExecutionAuxiliaryContract} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionLoopInvariant} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionBlockContract(int level, IExecutionAuxiliaryContract node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + + attributeValues.put(ATTRIBUTE_PRECONDITION_COMPLIED, node.isPreconditionComplied() + ""); + + appendStartTag(level, TAG_BLOCK_CONTRACT, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_BLOCK_CONTRACT, sb); + } + + /** + * Converts the given {@link IExecutionTermination} into XML and appends it to the + * {@link StringBuffer}. + * + * @param level The current child level. + * @param node The {@link IExecutionTermination} to convert. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendExecutionTermination(int level, IExecutionTermination node, + boolean saveVariables, boolean saveCallStack, boolean saveReturnValues, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, node.getName()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION, node.getFormatedPathCondition()); + attributeValues.put(ATTRIBUTE_PATH_CONDITION_CHANGED, node.isPathConditionChanged() + ""); + attributeValues.put(ATTRIBUTE_TERMINATION_KIND, node.getTerminationKind().toString()); + attributeValues.put(ATTRIBUTE_BRANCH_VERIFIED, node.isBranchVerified() + ""); + appendStartTag(level, TAG_TERMINATION, attributeValues, sb); + appendConstraints(level + 1, node, saveConstraints, sb); + appendVariables(level + 1, node, saveVariables, saveConstraints, sb); + appendCallStack(level + 1, node, saveCallStack, sb); + appendChildren(level + 1, node, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + appendOutgoingLinks(level + 1, node, sb); + appendCompletedBlocks(level + 1, node, sb); + appendEndTag(level, TAG_TERMINATION, sb); + } + + /** + * Appends the contained {@link IExecutionConstraint}s to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param value The {@link IExecutionValue} which provides the {@link IExecutionConstraint}s. + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendConstraints(int level, IExecutionValue value, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + if (saveConstraints) { + IExecutionConstraint[] constraints = value.getConstraints(); + for (IExecutionConstraint constraint : constraints) { + appendConstraint(level, constraint, sb); + } + } + } + + /** + * Appends the contained {@link IExecutionConstraint}s to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param node The {@link IExecutionNode} which provides the {@link IExecutionConstraint}s. + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendConstraints(int level, IExecutionNode node, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + if (saveConstraints) { + IExecutionConstraint[] constraints = node.getConstraints(); + for (IExecutionConstraint constraint : constraints) { + appendConstraint(level, constraint, sb); + } + } + } + + /** + * Appends the given {@link IExecutionConstraint} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param constraint The {@link IExecutionConstraint} to append. + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendConstraint(int level, IExecutionConstraint constraint, StringBuffer sb) + throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, constraint.getName()); + appendEmptyTag(level, TAG_CONSTRAINT, attributeValues, sb); + } + + /** + * Appends the contained {@link IExecutionVariable}s to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param node The {@link IExecutionNode} which provides the {@link IExecutionVariable}s. + * @param saveVariables Save variables? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendVariables(int level, IExecutionNode node, boolean saveVariables, + boolean saveConstraints, StringBuffer sb) throws ProofInputException { + if (saveVariables) { + IExecutionVariable[] variables = node.getVariables(); + for (IExecutionVariable variable : variables) { + appendVariable(level, variable, saveConstraints, TAG_VARIABLE, sb); + } + } + } + + /** + * Appends the contained {@link IExecutionVariable}s to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param node The {@link IExecutionNode} which provides the {@link IExecutionVariable}s. + * @param saveVariables Save variables? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendCallStateVariables(int level, IExecutionBaseMethodReturn node, + boolean saveVariables, boolean saveConstraints, StringBuffer sb) + throws ProofInputException { + if (saveVariables) { + IExecutionVariable[] variables = node.getCallStateVariables(); + for (IExecutionVariable variable : variables) { + appendVariable(level, variable, saveConstraints, TAG_CALL_STATE_VARIABLE, sb); + } + } + } + + /** + * Appends the given {@link IExecutionVariable} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param variable The {@link IExecutionVariable} to append. + * @param saveConstraints Save constraints? + * @param tagName The tag name to store an {@link IExecutionVariable}. + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendVariable(int level, IExecutionVariable variable, boolean saveConstraints, + String tagName, StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, variable.getName()); + attributeValues.put(ATTRIBUTE_ARRAY_INDEX, variable.getArrayIndexString()); + attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, variable.isArrayIndex() + ""); + appendStartTag(level, tagName, attributeValues, sb); + appendValues(level + 1, variable, saveConstraints, sb); + appendEndTag(level, tagName, sb); + } + + /** + * Appends the contained {@link IExecutionValue}s to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param variable The {@link IExecutionVariable} which provides the {@link IExecutionValue}s. + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendValues(int level, IExecutionVariable variable, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + IExecutionValue[] values = variable.getValues(); + for (IExecutionValue value : values) { + appendValue(level, value, saveConstraints, sb); + } + } + + /** + * Appends the given {@link IExecutionValue} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param value The {@link IExecutionValue} to append. + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendValue(int level, IExecutionValue value, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, value.getName()); + attributeValues.put(ATTRIBUTE_TYPE_STRING, value.getTypeString()); + attributeValues.put(ATTRIBUTE_VALUE_STRING, value.getValueString()); + attributeValues.put(ATTRIBUTE_IS_VALUE_AN_OBJECT, value.isValueAnObject() + ""); + attributeValues.put(ATTRIBUTE_IS_VALUE_UNKNOWN, value.isValueUnknown() + ""); + attributeValues.put(ATTRIBUTE_CONDITION_STRING, value.getConditionString()); + appendStartTag(level, TAG_VALUE, attributeValues, sb); + // Constraints + appendConstraints(level + 1, value, saveConstraints, sb); + // Children + IExecutionVariable[] childVariables = value.getChildVariables(); + for (IExecutionVariable childVariable : childVariables) { + appendVariable(level + 1, childVariable, saveConstraints, TAG_VARIABLE, sb); + } + appendEndTag(level, TAG_VALUE, sb); + } + + /** + * Appends the child nodes to the given {@link StringBuffer}. + * + * @param childLevel The level of the children. + * @param parent The parent {@link IExecutionNode} which provides the children. + * @param saveVariables Save variables? + * @param saveCallStack Save method call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception. + */ + protected void appendChildren(int childLevel, IExecutionNode parent, boolean saveVariables, + boolean saveCallStack, boolean saveReturnValues, boolean saveConstraints, + StringBuffer sb) throws ProofInputException { + IExecutionNode[] children = parent.getChildren(); + for (IExecutionNode child : children) { + appendExecutionNode(childLevel, child, saveVariables, saveCallStack, saveReturnValues, + saveConstraints, sb); + } + } + + protected void appendOutgoingLinks(int level, IExecutionNode node, StringBuffer sb) { + if (!node.getOutgoingLinks().isEmpty()) { + for (IExecutionLink link : node.getOutgoingLinks()) { + appendOutgoingLink(level, link, sb); + } + } + } + + protected void appendOutgoingLink(int level, IExecutionLink link, StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(link.getTarget())); + appendEmptyTag(level, TAG_OUTGOING_LINK, attributeValues, sb); + } + + /** + * Appends the call stack entries if required to the given {@link StringBuffer}. + * + * @param level The level of the children. + * @param node The {@link IExecutionNode} which provides the call stack. + * @param saveCallStack Defines if the call stack should be saved or not. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendCallStack(int level, IExecutionNode node, boolean saveCallStack, + StringBuffer sb) { + if (saveCallStack) { + IExecutionNode[] callStack = node.getCallStack(); + if (callStack != null) { + for (IExecutionNode stackNode : callStack) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(stackNode)); + appendEmptyTag(level, TAG_CALL_STACK_ENTRY, attributeValues, sb); + } + } + } + } + + /** + * Appends the method return entries to the given {@link StringBuffer}. + * + * @param level The level of the children. + * @param node The {@link IExecutionMethodCall} which provides the call stack. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendMethodReturns(int level, IExecutionMethodCall node, StringBuffer sb) { + ImmutableList> methodReturns = node.getMethodReturns(); + if (methodReturns != null) { + for (IExecutionBaseMethodReturn methodReturn : methodReturns) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(methodReturn)); + appendEmptyTag(level, TAG_METHOD_RETURN_ENTRY, attributeValues, sb); + } + } + } + + /** + * Appends the completed block entries to the given {@link StringBuffer}. + * + * @param level The level of the children. + * @param node The {@link IExecutionNode} which provides the block entries. + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception + */ + protected void appendCompletedBlocks(int level, IExecutionNode node, StringBuffer sb) + throws ProofInputException { + ImmutableList> completedBlocks = node.getCompletedBlocks(); + if (completedBlocks != null) { + for (IExecutionBlockStartNode completedBlock : completedBlocks) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(completedBlock)); + attributeValues.put(ATTRIBUTE_CONDITION_STRING, + node.getFormatedBlockCompletionCondition(completedBlock)); + appendEmptyTag(level, TAG_COMPLETED_BLOCK_ENTRY, attributeValues, sb); + } + } + } + + /** + * Appends the block completion entries to the given {@link StringBuffer}. + * + * @param level The level of the children. + * @param node The {@link IExecutionBlockStartNode} which provides the completed blocks. + * @param sb The {@link StringBuffer} to append to. + * @throws ProofInputException Occurred Exception + */ + protected void appendBlockCompletions(int level, IExecutionBlockStartNode node, + StringBuffer sb) throws ProofInputException { + ImmutableList> blockCompletions = node.getBlockCompletions(); + if (blockCompletions != null) { + for (IExecutionNode blockCompletion : blockCompletions) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_PATH_IN_TREE, computePath(blockCompletion)); + appendEmptyTag(level, TAG_BLOCK_COMPLETION_ENTRY, attributeValues, sb); + } + } + } + + /** + * Computes the path from the root of the symbolic execution tree to the given + * {@link IExecutionNode}. + * + * @param node The {@link IExecutionNode} to compute path to. + * @return The computed path. + */ + protected String computePath(IExecutionNode node) { + StringBuffer sb = new StringBuffer(); + boolean afterFirst = false; + while (node != null) { + IExecutionNode parent = node.getParent(); + if (parent != null) { + if (afterFirst) { + sb.insert(0, PATH_SEPARATOR); + } else { + afterFirst = true; + } + int index = ArrayUtil.indexOf(parent.getChildren(), node); + assert index >= 0 : "Node \"" + node + "\" is not contained in parents children \"" + + Arrays.toString(parent.getChildren()) + "\"."; + sb.insert(0, index); + } else { + sb.insert(0, PATH_SEPARATOR); + } + node = parent; + } + return sb.toString(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionVariableExtractor.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionVariableExtractor.java index feba754fa54..3cce3a18690 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionVariableExtractor.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/ExecutionVariableExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.Collection; @@ -31,697 +34,743 @@ /** * Extracts the current state and represents it as {@link IExecutionVariable}s. + * * @author Martin Hentschel */ public class ExecutionVariableExtractor extends AbstractUpdateExtractor { - /** - * The current {@link IExecutionNode}. - */ - private final IExecutionNode executionNode; - - /** - * An optional additional condition. - */ - private final Term additionalCondition; - - /** - * The layout term. - */ - private final Term layoutTerm; - - /** - * The current locations. - */ - private final Set currentLocations; - - /** - * The objects to ignore. - */ - private final Set objectsToIgnore; - - /** - * The found {@link IExecutionVariable}s available via {@link #analyse()}. - */ - private final Map allStateVariables; - - /** - * {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - private final boolean simplifyConditions; - - /** - * Constructor. - * @param node The {@link Node} which provides the state. - * @param modalityPio The {@link PosInOccurrence} in the {@link Node}. - * @param executionNode The current {@link IExecutionNode}. - * @param condition An optional additional condition. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @throws ProofInputException Occurred Exception - */ - public ExecutionVariableExtractor(Node node, - PosInOccurrence modalityPio, - IExecutionNode executionNode, - Term condition, - boolean simplifyConditions) throws ProofInputException { - super(node, modalityPio); - this.executionNode = executionNode; - this.additionalCondition = condition; - this.simplifyConditions = simplifyConditions; - // Get path condition - Term pathCondition = SymbolicExecutionUtil.computePathCondition(executionNode.getProofNode(), - true, // Path condition needs always to be simplified, because otherwise additinal symbolic values might be introduced. - false); - pathCondition = removeImplicitSubTermsFromPathCondition(pathCondition); - // Extract locations from updates - Set temporaryCurrentLocations = new LinkedHashSet(); - objectsToIgnore = computeInitialObjectsToIgnore(false, false); // Contains all objects which should be ignored, like exc of the proof obligation. - Set updateCreatedObjects = new LinkedHashSet(); // Contains all objects which are created during symbolic execution - Set updateValueObjects = new LinkedHashSet(); // Contains all objects which are the value of an update - collectLocationsFromUpdates(node.sequent(), temporaryCurrentLocations, updateCreatedObjects, updateValueObjects, objectsToIgnore); - objectsToIgnore.addAll(updateCreatedObjects); - Set initialLocations = extractLocationsFromTerm(pathCondition, objectsToIgnore); - initialLocations.addAll(extractLocationsFromSequent(node.sequent(), objectsToIgnore)); - currentLocations = new LinkedHashSet(initialLocations); - currentLocations.addAll(temporaryCurrentLocations); - // Create location predicate - layoutTerm = createLocationPredicateAndTerm(currentLocations); - // Create state variables - this.allStateVariables = new LinkedHashMap(); - for (ExtractLocationParameter location : currentLocations) { - if (location.isStateMember()) { - LocationDefinition locDef = new LocationDefinition(location.getProgramVariable(), location.getArrayIndex()); - if (!allStateVariables.containsKey(locDef)) { - StateExecutionVariable variable = new StateExecutionVariable(executionNode, - node, - modalityPio, - location.getProgramVariable(), - location.getArrayIndex(), - additionalCondition); - allStateVariables.put(locDef, variable); - } - } - } - } - - /** - * Extracts the current state and represents it as {@link IExecutionVariable}s. - * @return The {@link IExecutionVariable}s representing the current state. - * @throws ProofInputException Occurred Exception. - */ - public IExecutionVariable[] analyse() throws ProofInputException { - Collection variables = allStateVariables.values(); - return variables.toArray(new StateExecutionVariable[variables.size()]); - } - - /** - * Analyzes the tree structure of the given {@link ExecutionVariableValuePair}s. - * @param pairs The {@link ExecutionVariableValuePair}s to analyze. - * @param topVariables The state locations, - * @param contentMap The child locations. - */ - protected void analyzeTreeStructure(Set pairs, - Map> topVariables, - Map>> contentMap) { - for (ExecutionVariableValuePair pair : pairs) { - if (pair.isStateMember()) { - LocationDefinition locDef = new LocationDefinition(pair.getProgramVariable(), pair.getArrayIndex()); - List currentTopPairs = topVariables.get(locDef); - if (currentTopPairs == null) { - currentTopPairs = new LinkedList(); - topVariables.put(locDef, currentTopPairs); - } - currentTopPairs.add(pair); - } - else { - ParentDefinition parentDef = new ParentDefinition(pair.getParent(), pair.getGoalNode()); - Map> content = contentMap.get(parentDef); - if (content == null) { - content = new LinkedHashMap>(); - contentMap.put(parentDef, content); + /** + * The current {@link IExecutionNode}. + */ + private final IExecutionNode executionNode; + + /** + * An optional additional condition. + */ + private final Term additionalCondition; + + /** + * The layout term. + */ + private final Term layoutTerm; + + /** + * The current locations. + */ + private final Set currentLocations; + + /** + * The objects to ignore. + */ + private final Set objectsToIgnore; + + /** + * The found {@link IExecutionVariable}s available via {@link #analyse()}. + */ + private final Map allStateVariables; + + /** + * {@code true} simplify conditions, {@code false} do not simplify conditions. + */ + private final boolean simplifyConditions; + + /** + * Constructor. + * + * @param node The {@link Node} which provides the state. + * @param modalityPio The {@link PosInOccurrence} in the {@link Node}. + * @param executionNode The current {@link IExecutionNode}. + * @param condition An optional additional condition. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @throws ProofInputException Occurred Exception + */ + public ExecutionVariableExtractor(Node node, PosInOccurrence modalityPio, + IExecutionNode executionNode, Term condition, boolean simplifyConditions) + throws ProofInputException { + super(node, modalityPio); + this.executionNode = executionNode; + this.additionalCondition = condition; + this.simplifyConditions = simplifyConditions; + // Get path condition + Term pathCondition = + SymbolicExecutionUtil.computePathCondition(executionNode.getProofNode(), true, // Path + // condition + // needs + // always + // to + // be + // simplified, + // because + // otherwise + // additinal + // symbolic + // values + // might + // be + // introduced. + false); + pathCondition = removeImplicitSubTermsFromPathCondition(pathCondition); + // Extract locations from updates + Set temporaryCurrentLocations = + new LinkedHashSet(); + objectsToIgnore = computeInitialObjectsToIgnore(false, false); // Contains all objects which + // should be ignored, like + // exc of the proof + // obligation. + Set updateCreatedObjects = new LinkedHashSet(); // Contains all objects which + // are created during symbolic + // execution + Set updateValueObjects = new LinkedHashSet(); // Contains all objects which are + // the value of an update + collectLocationsFromUpdates(node.sequent(), temporaryCurrentLocations, updateCreatedObjects, + updateValueObjects, objectsToIgnore); + objectsToIgnore.addAll(updateCreatedObjects); + Set initialLocations = + extractLocationsFromTerm(pathCondition, objectsToIgnore); + initialLocations.addAll(extractLocationsFromSequent(node.sequent(), objectsToIgnore)); + currentLocations = new LinkedHashSet(initialLocations); + currentLocations.addAll(temporaryCurrentLocations); + // Create location predicate + layoutTerm = createLocationPredicateAndTerm(currentLocations); + // Create state variables + this.allStateVariables = new LinkedHashMap(); + for (ExtractLocationParameter location : currentLocations) { + if (location.isStateMember()) { + LocationDefinition locDef = new LocationDefinition(location.getProgramVariable(), + location.getArrayIndex()); + if (!allStateVariables.containsKey(locDef)) { + StateExecutionVariable variable = new StateExecutionVariable(executionNode, + node, modalityPio, location.getProgramVariable(), + location.getArrayIndex(), additionalCondition); + allStateVariables.put(locDef, variable); + } } - LocationDefinition locDef = new LocationDefinition(pair.getProgramVariable(), pair.getArrayIndex()); - List locationContent = content.get(locDef); - if (locationContent == null) { - locationContent = new LinkedList(); - content.put(locDef, locationContent); + } + } + + /** + * Extracts the current state and represents it as {@link IExecutionVariable}s. + * + * @return The {@link IExecutionVariable}s representing the current state. + * @throws ProofInputException Occurred Exception. + */ + public IExecutionVariable[] analyse() throws ProofInputException { + Collection variables = allStateVariables.values(); + return variables.toArray(new StateExecutionVariable[variables.size()]); + } + + /** + * Analyzes the tree structure of the given {@link ExecutionVariableValuePair}s. + * + * @param pairs The {@link ExecutionVariableValuePair}s to analyze. + * @param topVariables The state locations, + * @param contentMap The child locations. + */ + protected void analyzeTreeStructure(Set pairs, + Map> topVariables, + Map>> contentMap) { + for (ExecutionVariableValuePair pair : pairs) { + if (pair.isStateMember()) { + LocationDefinition locDef = + new LocationDefinition(pair.getProgramVariable(), pair.getArrayIndex()); + List currentTopPairs = topVariables.get(locDef); + if (currentTopPairs == null) { + currentTopPairs = new LinkedList(); + topVariables.put(locDef, currentTopPairs); + } + currentTopPairs.add(pair); + } else { + ParentDefinition parentDef = + new ParentDefinition(pair.getParent(), pair.getGoalNode()); + Map> content = + contentMap.get(parentDef); + if (content == null) { + content = + new LinkedHashMap>(); + contentMap.put(parentDef, content); + } + LocationDefinition locDef = + new LocationDefinition(pair.getProgramVariable(), pair.getArrayIndex()); + List locationContent = content.get(locDef); + if (locationContent == null) { + locationContent = new LinkedList(); + content.put(locDef, locationContent); + } + locationContent.add(pair); } - locationContent.add(pair); - } - } - } - - /** - * Creates an {@link IExecutionVariable} for the given {@link ExecutionVariableValuePair}s. - * @param pairs The {@link ExecutionVariableValuePair}s to represent. - * @param contentMap The {@link Map} providing child content information. - * @param parentValue The optional parent {@link IExecutionValue}. - * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the current path in the variable-value-hierarchy. - * @return The created {@link IExecutionVariable}. - * @throws ProofInputException Occurred Exception. - */ - protected IExecutionVariable createVariablesValueStructure(final List pairs, - final Map>> contentMap, - final ExtractedExecutionValue parentValue, - final ImmutableList alreadyVisitedObjects) throws ProofInputException { - assert !pairs.isEmpty(); - // Create variable - ExecutionVariableValuePair firstPair = pairs.get(0); - ExtractedExecutionVariable variable = new ExtractedExecutionVariable(executionNode, - node, - modalityPio, - firstPair.getProgramVariable(), - firstPair.getArrayIndex(), - firstPair.getArrayStartIndex(), - firstPair.getArrayEndIndex(), - additionalCondition, - parentValue); - if (parentValue != null) { - parentValue.addChildVariable(variable); - } - // Fill variable with values - List values = new LinkedList(); - createValues(variable, pairs, firstPair, contentMap, values, alreadyVisitedObjects); - variable.setValues(values); - return variable; - } - - /** - * Creates the {@link IExecutionValue}s of the given {@link IExecutionVariable}. - * @param variable The {@link IExecutionVariable}. - * @param pairs The {@link ExecutionVariableValuePair}s which provides the content. - * @param firstPair The first entry in the {@link ExecutionVariableValuePair}s. - * @param contentMap The content {@link Map}. - * @param valueListToFill The result {@link List} to fill. - * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the current path in the variable-value-hierarchy. - * @throws ProofInputException Occurred Exception. - */ - protected void createValues(final IExecutionVariable variable, - final List pairs, - final ExecutionVariableValuePair firstPair, - final Map>> contentMap, - final List valueListToFill, - final ImmutableList alreadyVisitedObjects) throws ProofInputException { - // Group pairs with same value but with different conditions - Map> groupedPairs = new LinkedHashMap>(); - for (ExecutionVariableValuePair pair : pairs) { - assert firstPair.getProgramVariable() == pair.getProgramVariable(); - assert firstPair.getArrayIndex() == pair.getArrayIndex(); - assert firstPair.isArrayIndex() == pair.isArrayIndex(); - assert firstPair.getArrayStartIndex() == pair.getArrayStartIndex(); - assert firstPair.getArrayEndIndex() == pair.getArrayEndIndex(); - assert firstPair.isArrayRange() == pair.isArrayRange(); - List values = groupedPairs.get(pair.getValue()); - if (values == null) { - values = new LinkedList(); - groupedPairs.put(pair.getValue(), values); - } - values.add(pair); - } - // Create variable - for (List group : groupedPairs.values()) { - if (group.size() == 1) { - ExecutionVariableValuePair pair = group.get(0); - ExtractedExecutionValue value = new ExtractedExecutionValue(executionNode, - node, - variable, - pair.getCondition(), - pair.getValue()); - valueListToFill.add(value); - Pair> cycleCheckResult = updateAlreadyVisitedObjects(alreadyVisitedObjects, pair.getValue()); - if (!cycleCheckResult.first) { // No cycle detected - ParentDefinition parentDef = new ParentDefinition(pair.getValue(), pair.getGoalNode()); - Map> content = contentMap.get(parentDef); - if (content != null) { - for (List child : content.values()) { - createVariablesValueStructure(child, contentMap, value, cycleCheckResult.second); - } - } + } + } + + /** + * Creates an {@link IExecutionVariable} for the given {@link ExecutionVariableValuePair}s. + * + * @param pairs The {@link ExecutionVariableValuePair}s to represent. + * @param contentMap The {@link Map} providing child content information. + * @param parentValue The optional parent {@link IExecutionValue}. + * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the + * current path in the variable-value-hierarchy. + * @return The created {@link IExecutionVariable}. + * @throws ProofInputException Occurred Exception. + */ + protected IExecutionVariable createVariablesValueStructure( + final List pairs, + final Map>> contentMap, + final ExtractedExecutionValue parentValue, + final ImmutableList alreadyVisitedObjects) throws ProofInputException { + assert !pairs.isEmpty(); + // Create variable + ExecutionVariableValuePair firstPair = pairs.get(0); + ExtractedExecutionVariable variable = new ExtractedExecutionVariable(executionNode, node, + modalityPio, firstPair.getProgramVariable(), firstPair.getArrayIndex(), + firstPair.getArrayStartIndex(), firstPair.getArrayEndIndex(), additionalCondition, + parentValue); + if (parentValue != null) { + parentValue.addChildVariable(variable); + } + // Fill variable with values + List values = new LinkedList(); + createValues(variable, pairs, firstPair, contentMap, values, alreadyVisitedObjects); + variable.setValues(values); + return variable; + } + + /** + * Creates the {@link IExecutionValue}s of the given {@link IExecutionVariable}. + * + * @param variable The {@link IExecutionVariable}. + * @param pairs The {@link ExecutionVariableValuePair}s which provides the content. + * @param firstPair The first entry in the {@link ExecutionVariableValuePair}s. + * @param contentMap The content {@link Map}. + * @param valueListToFill The result {@link List} to fill. + * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the + * current path in the variable-value-hierarchy. + * @throws ProofInputException Occurred Exception. + */ + protected void createValues(final IExecutionVariable variable, + final List pairs, + final ExecutionVariableValuePair firstPair, + final Map>> contentMap, + final List valueListToFill, + final ImmutableList alreadyVisitedObjects) throws ProofInputException { + // Group pairs with same value but with different conditions + Map> groupedPairs = + new LinkedHashMap>(); + for (ExecutionVariableValuePair pair : pairs) { + assert firstPair.getProgramVariable() == pair.getProgramVariable(); + assert firstPair.getArrayIndex() == pair.getArrayIndex(); + assert firstPair.isArrayIndex() == pair.isArrayIndex(); + assert firstPair.getArrayStartIndex() == pair.getArrayStartIndex(); + assert firstPair.getArrayEndIndex() == pair.getArrayEndIndex(); + assert firstPair.isArrayRange() == pair.isArrayRange(); + List values = groupedPairs.get(pair.getValue()); + if (values == null) { + values = new LinkedList(); + groupedPairs.put(pair.getValue(), values); } - } - else { - List conditions = new LinkedList(); - Map> childContentMap = new LinkedHashMap>(); - for (ExecutionVariableValuePair pair : group) { - conditions.add(pair.getCondition()); - ParentDefinition parentDef = new ParentDefinition(pair.getValue(), pair.getGoalNode()); - Map> content = contentMap.get(parentDef); - if (content != null) { - for (Entry> entry : content.entrySet()) { - List childList = childContentMap.get(entry.getKey()); - if (childList == null) { - childList = new LinkedList(); - childContentMap.put(entry.getKey(), childList); - } - childList.addAll(entry.getValue()); - } - } + values.add(pair); + } + // Create variable + for (List group : groupedPairs.values()) { + if (group.size() == 1) { + ExecutionVariableValuePair pair = group.get(0); + ExtractedExecutionValue value = new ExtractedExecutionValue(executionNode, node, + variable, pair.getCondition(), pair.getValue()); + valueListToFill.add(value); + Pair> cycleCheckResult = + updateAlreadyVisitedObjects(alreadyVisitedObjects, pair.getValue()); + if (!cycleCheckResult.first) { // No cycle detected + ParentDefinition parentDef = + new ParentDefinition(pair.getValue(), pair.getGoalNode()); + Map> content = + contentMap.get(parentDef); + if (content != null) { + for (List child : content.values()) { + createVariablesValueStructure(child, contentMap, value, + cycleCheckResult.second); + } + } + } + } else { + List conditions = new LinkedList(); + Map> childContentMap = + new LinkedHashMap>(); + for (ExecutionVariableValuePair pair : group) { + conditions.add(pair.getCondition()); + ParentDefinition parentDef = + new ParentDefinition(pair.getValue(), pair.getGoalNode()); + Map> content = + contentMap.get(parentDef); + if (content != null) { + for (Entry> entry : content + .entrySet()) { + List childList = + childContentMap.get(entry.getKey()); + if (childList == null) { + childList = new LinkedList(); + childContentMap.put(entry.getKey(), childList); + } + childList.addAll(entry.getValue()); + } + } + } + final Services services = getServices(); + Term comboundPathCondition = services.getTermBuilder().or(conditions); + if (simplifyConditions) { + comboundPathCondition = SymbolicExecutionUtil.simplify( + getProof().getInitConfig(), getProof(), comboundPathCondition); + } + comboundPathCondition = + SymbolicExecutionUtil.improveReadability(comboundPathCondition, services); + ExtractedExecutionValue value = new ExtractedExecutionValue(executionNode, node, + variable, comboundPathCondition, group.get(0).getValue()); + valueListToFill.add(value); + Pair> cycleCheckResult = + updateAlreadyVisitedObjects(alreadyVisitedObjects, group.get(0).getValue()); + if (!cycleCheckResult.first) { // No cycle detected + if (!childContentMap.isEmpty()) { + for (List child : childContentMap.values()) { + createVariablesValueStructure(child, contentMap, value, + cycleCheckResult.second); + } + } + } } - final Services services = getServices(); - Term comboundPathCondition = services.getTermBuilder().or(conditions); - if (simplifyConditions) { - comboundPathCondition = SymbolicExecutionUtil.simplify(getProof().getInitConfig(), getProof(), comboundPathCondition); + } + } + + /** + * Updates the already visited objects list if required. + * + * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the + * current path in the variable-value-hierarchy. + * @param value The current value. + * @return The new already visited objects list or the original one if the current value is not + * an object. + */ + protected Pair> updateAlreadyVisitedObjects( + final ImmutableList alreadyVisitedObjects, Term value) { + ImmutableList alreadyVisitedObjectsForChildren = alreadyVisitedObjects; + boolean cycleDetected = false; + if (value != null && SymbolicExecutionUtil.hasReferenceSort(getServices(), value) + && !SymbolicExecutionUtil.isNullSort(value.sort(), getServices())) { + if (!alreadyVisitedObjects.contains(value)) { + alreadyVisitedObjectsForChildren = alreadyVisitedObjectsForChildren.prepend(value); + } else { + cycleDetected = true; } - comboundPathCondition = SymbolicExecutionUtil.improveReadability(comboundPathCondition, services); - ExtractedExecutionValue value = new ExtractedExecutionValue(executionNode, - node, - variable, - comboundPathCondition, - group.get(0).getValue()); - valueListToFill.add(value); - Pair> cycleCheckResult = updateAlreadyVisitedObjects(alreadyVisitedObjects, group.get(0).getValue()); - if (!cycleCheckResult.first) { // No cycle detected - if (!childContentMap.isEmpty()) { - for (List child : childContentMap.values()) { - createVariablesValueStructure(child, contentMap, value, cycleCheckResult.second); - } - } + } + return new Pair>(cycleDetected, + alreadyVisitedObjectsForChildren); + } + + /** + * Utility class representing a parent definition. + * + * @author Martin Hentschel + */ + private static final class ParentDefinition { + /** + * The parent. + */ + private final Term parent; + + /** + * The {@link Node} on which this result is based on. + */ + private final Node goalNode; + + /** + * Constructor. + * + * @param parent The parent. + * @param goalNode The {@link Node} on which this result is based on. + */ + public ParentDefinition(Term parent, Node goalNode) { + this.parent = parent; + this.goalNode = goalNode; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ParentDefinition) { + ParentDefinition other = (ParentDefinition) obj; + return ObjectUtil.equals(parent, other.parent) + && ObjectUtil.equals(goalNode, other.goalNode); + } else { + return false; } - } - } - } - - /** - * Updates the already visited objects list if required. - * @param alreadyVisitedObjects The value {@link Term}s of already visited objects on the current path in the variable-value-hierarchy. - * @param value The current value. - * @return The new already visited objects list or the original one if the current value is not an object. - */ - protected Pair> updateAlreadyVisitedObjects(final ImmutableList alreadyVisitedObjects, Term value) { - ImmutableList alreadyVisitedObjectsForChildren = alreadyVisitedObjects; - boolean cycleDetected = false; - if (value != null && - SymbolicExecutionUtil.hasReferenceSort(getServices(), value) && - !SymbolicExecutionUtil.isNullSort(value.sort(), getServices())) { - if (!alreadyVisitedObjects.contains(value)) { - alreadyVisitedObjectsForChildren = alreadyVisitedObjectsForChildren.prepend(value); - } - else { - cycleDetected = true; - } - } - return new Pair>(cycleDetected, alreadyVisitedObjectsForChildren); - } - - /** - * Utility class representing a parent definition. - * @author Martin Hentschel - */ - private static final class ParentDefinition { - /** - * The parent. - */ - private final Term parent; - - /** - * The {@link Node} on which this result is based on. - */ - private final Node goalNode; - - /** - * Constructor. - * @param parent The parent. - * @param goalNode The {@link Node} on which this result is based on. - */ - public ParentDefinition(Term parent, Node goalNode) { - this.parent = parent; - this.goalNode = goalNode; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof ParentDefinition) { - ParentDefinition other = (ParentDefinition)obj; - return ObjectUtil.equals(parent, other.parent) && - ObjectUtil.equals(goalNode, other.goalNode); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (parent != null ? parent.hashCode() : 0); - result = 31 * result + (goalNode != null ? goalNode.hashCode() : 0); - return result; - } - } - - /** - * Utility class representing a location. - * @author Martin Hentschel - */ - private static final class LocationDefinition { - /** - * The {@link ProgramVariable} or {@code null} if an array index is used instead. - */ - private final ProgramVariable programVariable; - - /** - * The array index or {@code null} if a {@link ProgramVariable} is used instead. - */ - private final Term arrayIndex; - - /** - * Constructor. - * @param programVariable The {@link ProgramVariable} or {@code null} if an array index is used instead. - * @param arrayIndex The array index or {@code null} if a {@link ProgramVariable} is used instead. - */ - public LocationDefinition(ProgramVariable programVariable, Term arrayIndex) { - this.programVariable = programVariable; - this.arrayIndex = arrayIndex; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof LocationDefinition) { - LocationDefinition other = (LocationDefinition)obj; - return programVariable == other.programVariable && - ObjectUtil.equals(arrayIndex, other.arrayIndex); - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - result = 31 * result + (programVariable != null ? programVariable.hashCode() : 0); - result = 31 * result + (arrayIndex != null ? arrayIndex.hashCode() : 0); - return result; - } - } - - /** - * The {@link IExecutionVariable} instantiated by the {@link ExecutionVariableExtractor}. - * @author Martin Hentschel - */ - private class StateExecutionVariable extends AbstractExecutionVariable { - /** - * The contained {@link IExecutionValue}s. - */ - private IExecutionValue[] values; - - /** - * Constructor. - * @param parentNode The {@link IExecutionNode} providing relevant information. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - * @param programVariable The represented {@link IProgramVariable} which value is shown. - * @param arrayIndex The index in the parent array. - * @param additionalCondition An optional additional condition to consider. - */ - public StateExecutionVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - IProgramVariable programVariable, - Term arrayIndex, - Term additionalCondition) { - super(parentNode.getSettings(), - proofNode, - programVariable, - null, - arrayIndex, - additionalCondition, - modalityPIO); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionValue[] getValues() throws ProofInputException { - if (values == null) { - synchronized (allStateVariables) { - if (values == null) { - // Compute values - Set pairs = computeVariableValuePairs(getAdditionalCondition(), layoutTerm, currentLocations, true, simplifyConditions); - if (pairs != null) { - // Analyze tree structure of pairs - Map> topVariables = new LinkedHashMap>(); - Map>> contentMap = new LinkedHashMap>>(); - analyzeTreeStructure(pairs, topVariables, contentMap); - // Create variables and values from tree structure - for (List pairsList : topVariables.values()) { - ExecutionVariableValuePair firstPair = pairsList.get(0); - List values = new LinkedList(); - StateExecutionVariable variable = allStateVariables.get(new LocationDefinition(firstPair.getProgramVariable(), firstPair.getArrayIndex())); - assert variable != null; - createValues(variable, pairsList, firstPair, contentMap, values, ImmutableSLList.nil()); - variable.values = values.toArray(new IExecutionValue[values.size()]); - } - } - else { - values = new IExecutionValue[0]; // Something went wrong, values are not available. - } - } + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (parent != null ? parent.hashCode() : 0); + result = 31 * result + (goalNode != null ? goalNode.hashCode() : 0); + return result; + } + } + + /** + * Utility class representing a location. + * + * @author Martin Hentschel + */ + private static final class LocationDefinition { + /** + * The {@link ProgramVariable} or {@code null} if an array index is used instead. + */ + private final ProgramVariable programVariable; + + /** + * The array index or {@code null} if a {@link ProgramVariable} is used instead. + */ + private final Term arrayIndex; + + /** + * Constructor. + * + * @param programVariable The {@link ProgramVariable} or {@code null} if an array index is + * used instead. + * @param arrayIndex The array index or {@code null} if a {@link ProgramVariable} is used + * instead. + */ + public LocationDefinition(ProgramVariable programVariable, Term arrayIndex) { + this.programVariable = programVariable; + this.arrayIndex = arrayIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof LocationDefinition) { + LocationDefinition other = (LocationDefinition) obj; + return programVariable == other.programVariable + && ObjectUtil.equals(arrayIndex, other.arrayIndex); + } else { + return false; } - } - return values; - } - - /** - * {@inheritDoc} - */ - @Override - public Term createSelectTerm() { - return SymbolicExecutionUtil.createSelectTerm(this); - } - } - - /** - * The {@link IExecutionVariable} instantiated by the {@link ExecutionVariableExtractor}. - * @author Martin Hentschel - */ - public static class ExtractedExecutionVariable extends AbstractExecutionVariable { - /** - * The contained {@link IExecutionValue}s. - */ - private List values; - - /** - * The array start index or {@code null} if not used. - */ - private final Term arrayStartIndex; - - /** - * The array end index or {@code null} if not used. - */ - private final Term arrayEndIndex; - - /** - * Constructor. - * @param parentNode The {@link IExecutionNode} providing relevant information. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - * @param programVariable The represented {@link IProgramVariable} which value is shown. - * @param arrayIndex The index in the parent array. - * @param additionalCondition An optional additional condition to consider. - * @param parentValue The parent {@link IExecutionValue} or {@code null} if not available. - */ - public ExtractedExecutionVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - IProgramVariable programVariable, - Term arrayIndex, - Term arrayStartIndex, - Term arrayEndIndex, - Term additionalCondition, - ExtractedExecutionValue parentValue) { - super(parentNode.getSettings(), - proofNode, - programVariable, - parentValue, - arrayIndex, - additionalCondition, - modalityPIO); - this.arrayStartIndex = arrayStartIndex; - this.arrayEndIndex = arrayEndIndex; - } - - /** - * Sets the {@link IExecutionValue}s. - * @param values The {@link IExecutionValue}s to set. - */ - private void setValues(List values) { - this.values = values; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionValue[] getValues() throws ProofInputException { - return values.toArray(new IExecutionValue[values.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public Term createSelectTerm() { - return SymbolicExecutionUtil.createSelectTerm(this); - } - - /** - * Returns the array start index. - * @return The array start index. - */ - public Term getArrayStartIndex() { - return arrayStartIndex; - } - - /** - * Returns the human readable array start index. - * @return The human readable array start index. - */ - public String getArrayStartIndexString() { - return arrayStartIndex != null ? formatTerm(arrayStartIndex, getServices()) : null; - } - - /** - * Returns the array end index. - * @return The array end index. - */ - public Term getArrayEndIndex() { - return arrayEndIndex; - } - - /** - * Returns the human readable array end index. - * @return The human readable array end index. - */ - public String getArrayEndIndexString() { - return arrayEndIndex != null ? formatTerm(arrayEndIndex, getServices()) : null; - } - - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - if (getArrayStartIndex() != null || getArrayEndIndex() != null) { - String name = "["; - if (getArrayStartIndex() != null) { - name += getArrayIndexString() + " >= " + getArrayStartIndexString(); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = 17; + result = 31 * result + (programVariable != null ? programVariable.hashCode() : 0); + result = 31 * result + (arrayIndex != null ? arrayIndex.hashCode() : 0); + return result; + } + } + + /** + * The {@link IExecutionVariable} instantiated by the {@link ExecutionVariableExtractor}. + * + * @author Martin Hentschel + */ + private class StateExecutionVariable extends AbstractExecutionVariable { + /** + * The contained {@link IExecutionValue}s. + */ + private IExecutionValue[] values; + + /** + * Constructor. + * + * @param parentNode The {@link IExecutionNode} providing relevant information. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + * @param programVariable The represented {@link IProgramVariable} which value is shown. + * @param arrayIndex The index in the parent array. + * @param additionalCondition An optional additional condition to consider. + */ + public StateExecutionVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, IProgramVariable programVariable, Term arrayIndex, + Term additionalCondition) { + super(parentNode.getSettings(), proofNode, programVariable, null, arrayIndex, + additionalCondition, modalityPIO); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionValue[] getValues() throws ProofInputException { + if (values == null) { + synchronized (allStateVariables) { + if (values == null) { + // Compute values + Set pairs = + computeVariableValuePairs(getAdditionalCondition(), layoutTerm, + currentLocations, true, simplifyConditions); + if (pairs != null) { + // Analyze tree structure of pairs + Map> topVariables = + new LinkedHashMap>(); + Map>> contentMap = + new LinkedHashMap>>(); + analyzeTreeStructure(pairs, topVariables, contentMap); + // Create variables and values from tree structure + for (List pairsList : topVariables + .values()) { + ExecutionVariableValuePair firstPair = pairsList.get(0); + List values = new LinkedList(); + StateExecutionVariable variable = allStateVariables + .get(new LocationDefinition(firstPair.getProgramVariable(), + firstPair.getArrayIndex())); + assert variable != null; + createValues(variable, pairsList, firstPair, contentMap, values, + ImmutableSLList.nil()); + variable.values = + values.toArray(new IExecutionValue[values.size()]); + } + } else { + values = new IExecutionValue[0]; // Something went wrong, values are not + // available. + } + } + } } - if (getArrayStartIndex() != null && getArrayEndIndex() != null) { - name += " and "; + return values; + } + + /** + * {@inheritDoc} + */ + @Override + public Term createSelectTerm() { + return SymbolicExecutionUtil.createSelectTerm(this); + } + } + + /** + * The {@link IExecutionVariable} instantiated by the {@link ExecutionVariableExtractor}. + * + * @author Martin Hentschel + */ + public static class ExtractedExecutionVariable extends AbstractExecutionVariable { + /** + * The contained {@link IExecutionValue}s. + */ + private List values; + + /** + * The array start index or {@code null} if not used. + */ + private final Term arrayStartIndex; + + /** + * The array end index or {@code null} if not used. + */ + private final Term arrayEndIndex; + + /** + * Constructor. + * + * @param parentNode The {@link IExecutionNode} providing relevant information. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + * @param programVariable The represented {@link IProgramVariable} which value is shown. + * @param arrayIndex The index in the parent array. + * @param additionalCondition An optional additional condition to consider. + * @param parentValue The parent {@link IExecutionValue} or {@code null} if not available. + */ + public ExtractedExecutionVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, IProgramVariable programVariable, Term arrayIndex, + Term arrayStartIndex, Term arrayEndIndex, Term additionalCondition, + ExtractedExecutionValue parentValue) { + super(parentNode.getSettings(), proofNode, programVariable, parentValue, arrayIndex, + additionalCondition, modalityPIO); + this.arrayStartIndex = arrayStartIndex; + this.arrayEndIndex = arrayEndIndex; + } + + /** + * Sets the {@link IExecutionValue}s. + * + * @param values The {@link IExecutionValue}s to set. + */ + private void setValues(List values) { + this.values = values; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionValue[] getValues() throws ProofInputException { + return values.toArray(new IExecutionValue[values.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public Term createSelectTerm() { + return SymbolicExecutionUtil.createSelectTerm(this); + } + + /** + * Returns the array start index. + * + * @return The array start index. + */ + public Term getArrayStartIndex() { + return arrayStartIndex; + } + + /** + * Returns the human readable array start index. + * + * @return The human readable array start index. + */ + public String getArrayStartIndexString() { + return arrayStartIndex != null ? formatTerm(arrayStartIndex, getServices()) : null; + } + + /** + * Returns the array end index. + * + * @return The array end index. + */ + public Term getArrayEndIndex() { + return arrayEndIndex; + } + + /** + * Returns the human readable array end index. + * + * @return The human readable array end index. + */ + public String getArrayEndIndexString() { + return arrayEndIndex != null ? formatTerm(arrayEndIndex, getServices()) : null; + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + if (getArrayStartIndex() != null || getArrayEndIndex() != null) { + String name = "["; + if (getArrayStartIndex() != null) { + name += getArrayIndexString() + " >= " + getArrayStartIndexString(); + } + if (getArrayStartIndex() != null && getArrayEndIndex() != null) { + name += " and "; + } + if (getArrayEndIndex() != null) { + name += getArrayIndexString() + " <= " + getArrayEndIndexString(); + } + name += "]"; + return name; + } else { + return super.lazyComputeName(); } - if (getArrayEndIndex() != null) { - name += getArrayIndexString() + " <= " + getArrayEndIndexString(); + } + } + + /** + * The {@link IExecutionValue} instantiated by the {@link ExecutionVariableExtractor}. + * + * @author Martin Hentschel + */ + public static class ExtractedExecutionValue extends AbstractExecutionValue { + /** + * The available child {@link ExtractedExecutionVariable}. + */ + private final List childVariables = + new LinkedList(); + + /** + * The {@link IExecutionNode} providing the {@link IExecutionConstraint}s. + */ + private final IExecutionNode parentNode; + + /** + * Constructor. + * + * @param parentNode The {@link IExecutionNode} providing relevant information. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param variable The parent {@link IExecutionVariable} which contains this value. + * @param condition The condition. + * @param value The value. + */ + public ExtractedExecutionValue(IExecutionNode parentNode, Node proofNode, + IExecutionVariable variable, Term condition, Term value) { + super(parentNode.getSettings(), proofNode, variable, condition, value); + this.parentNode = parentNode; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() throws ProofInputException { + return getCondition() != null ? formatTerm(getCondition(), getServices()) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValueUnknown() throws ProofInputException { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public String getValueString() throws ProofInputException { + return getValue() != null ? formatTerm(getValue(), getServices()) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() throws ProofInputException { + return getValue() != null && getValue().sort() != null ? getValue().sort().toString() + : null; + } + + /** + * Adds a child {@link ExtractedExecutionVariable}. + * + * @param variable The {@link ExtractedExecutionVariable} to add. + */ + protected void addChildVariable(ExtractedExecutionVariable variable) { + if (variable != null) { + childVariables.add(variable); } - name += "]"; - return name; - } - else { - return super.lazyComputeName(); - } - } - } - - /** - * The {@link IExecutionValue} instantiated by the {@link ExecutionVariableExtractor}. - * @author Martin Hentschel - */ - public static class ExtractedExecutionValue extends AbstractExecutionValue { - /** - * The available child {@link ExtractedExecutionVariable}. - */ - private final List childVariables = new LinkedList(); - - /** - * The {@link IExecutionNode} providing the {@link IExecutionConstraint}s. - */ - private final IExecutionNode parentNode; - - /** - * Constructor. - * @param parentNode The {@link IExecutionNode} providing relevant information. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param variable The parent {@link IExecutionVariable} which contains this value. - * @param condition The condition. - * @param value The value. - */ - public ExtractedExecutionValue(IExecutionNode parentNode, - Node proofNode, - IExecutionVariable variable, - Term condition, - Term value) { - super(parentNode.getSettings(), proofNode, variable, condition, value); - this.parentNode = parentNode; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() throws ProofInputException { - return getCondition() != null ? formatTerm(getCondition(), getServices()) : null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isValueUnknown() throws ProofInputException { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public String getValueString() throws ProofInputException { - return getValue() != null ? formatTerm(getValue(), getServices()) : null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() throws ProofInputException { - return getValue() != null && getValue().sort() != null ? getValue().sort().toString() : null; - } - - /** - * Adds a child {@link ExtractedExecutionVariable}. - * @param variable The {@link ExtractedExecutionVariable} to add. - */ - protected void addChildVariable(ExtractedExecutionVariable variable) { - if (variable != null) { - childVariables.add(variable); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ExtractedExecutionVariable[] getChildVariables() throws ProofInputException { - return childVariables.toArray(new ExtractedExecutionVariable[childVariables.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] getNodeConstraints() { - return parentNode.getConstraints(); - } - } + } + + /** + * {@inheritDoc} + */ + @Override + public ExtractedExecutionVariable[] getChildVariables() throws ProofInputException { + return childVariables.toArray(new ExtractedExecutionVariable[childVariables.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] getNodeConstraints() { + return parentNode.getConstraints(); + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicExecutionTreeBuilder.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicExecutionTreeBuilder.java index 71fb881fd8b..e048a95aa1c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicExecutionTreeBuilder.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicExecutionTreeBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.Deque; @@ -91,42 +94,37 @@ /** *

- * Instances of this class are used to extract the symbolic execution tree - * from a normal KeY's proof tree. The requirement is that the proof contains - * a predicate which is not evaluable to filter invalid execution tree paths. - * The easiest way to achieve this is to use a - * {@link FunctionalOperationContractPO} (addUninterpretedPredicate = {@code true}) instance as proof - * obligation to instantiate a {@link Proof} from. + * Instances of this class are used to extract the symbolic execution tree from a normal KeY's proof + * tree. The requirement is that the proof contains a predicate which is not evaluable to filter + * invalid execution tree paths. The easiest way to achieve this is to use a + * {@link FunctionalOperationContractPO} (addUninterpretedPredicate = {@code true}) instance as + * proof obligation to instantiate a {@link Proof} from. *

*

- * A symbolic execution tree consists of {@link IExecutionNode}s which - * represents the executed statements and other Java constructs. The root - * of a symbolic execution tree is an {@link IExecutionStart} which is - * available via {@link #getProof()}. + * A symbolic execution tree consists of {@link IExecutionNode}s which represents the executed + * statements and other Java constructs. The root of a symbolic execution tree is an + * {@link IExecutionStart} which is available via {@link #getProof()}. *

*

- * Some assumptions about how {@link Sequent}s in the proof tree looks like - * are required to extract the symbolic execution tree. To make sure that - * they hold (otherwise exceptions are thrown) it is required to execute - * the {@link SymbolicExecutionStrategy} in KeY's auto mode and not to apply rules - * manually or to use other strategies. + * Some assumptions about how {@link Sequent}s in the proof tree looks like are required to extract + * the symbolic execution tree. To make sure that they hold (otherwise exceptions are thrown) it is + * required to execute the {@link SymbolicExecutionStrategy} in KeY's auto mode and not to apply + * rules manually or to use other strategies. *

*

- * The symbolic execution tree is not updated automatically when KeY's - * proof tree has changed. The update must be started manually via - * {@link #analyse()}. In this case the proof tree will be analyzed and the - * execution tree model created or updated if it already exist. + * The symbolic execution tree is not updated automatically when KeY's proof tree has changed. The + * update must be started manually via {@link #analyse()}. In this case the proof tree will be + * analyzed and the execution tree model created or updated if it already exist. *

*

- * Proof trees and also symbolic execution trees are very large even in - * small programs. For this reason it is not possible to iterate over the - * tree via recursive method calls. Instead, an instance of - * {@link ExecutionNodePreorderIterator} should be used to iterate over - * a symbolic execution tree. + * Proof trees and also symbolic execution trees are very large even in small programs. For this + * reason it is not possible to iterate over the tree via recursive method calls. Instead, an + * instance of {@link ExecutionNodePreorderIterator} should be used to iterate over a symbolic + * execution tree. *

*

- * The following snippet shows the basic usage of this class to extract - * an symbolic execution tree: + * The following snippet shows the basic usage of this class to extract an symbolic execution tree: + * *

  * {@code
  * Proof proof; // Create proof with proof obligation FunctionalOperationContractPO and set addUninterpretedPredicate to true
@@ -147,6 +145,7 @@
  * 
*

* @author Martin Hentschel + * * @see FunctionalOperationContractPO#isAddUninterpretedPredicate() * @see IExecutionNode * @see IExecutionStart @@ -154,1627 +153,1832 @@ * @see ExecutionNodePreorderIterator */ public class SymbolicExecutionTreeBuilder { - /** - * The {@link Proof} from which the symbolic execution tree is extracted. - */ - private Proof proof; - - /** - * The start node of the symbolic execution tree. - */ - private ExecutionStart startNode; - - /** - *

- * Maps a {@link Node} of KeY's proof tree to his execution tree model representation - * if it is available. - *

- *

- * In case that the {@link Node} is represented by multiple {@link AbstractExecutionNode}s, - * e.g. a return statement and a method return, the last node is returned. - *

- */ - private Map> keyNodeMapping = new LinkedHashMap>(); - - /** - * In case a {@link Node} is represented by multiple {@link AbstractExecutionNode}s, - * this map maps the {@link Node} to all its representations. - */ - private Map>> multipleExecutionNodes = new LinkedHashMap>>(); - - /** - * Maps a loop condition of a {@link Node} of KeY's proof tree to his - * execution tree model representation ({@link IExecutionLoopCondition}) if it is available. - */ - private Map keyNodeLoopConditionMapping = new LinkedHashMap(); - - /** - * Maps a branch condition of a {@link Node} of KeY's proof tree to his - * execution tree model representation ({@link IExecutionBranchCondition}) if it is available. - */ - private Map keyNodeBranchConditionMapping = new LinkedHashMap(); - - /** - * Contains the method call stacks for each tracked symbolic execution modality. - * As key is {@link SymbolicExecutionTermLabel#getId()} used. - */ - private Map>> methodCallStackMap = new LinkedHashMap>>(); - - /** - * Contains the possible statements after a code block of interest for each tracked symbolic execution modality. - * As key is {@link SymbolicExecutionTermLabel#getId()} used. - */ - private Map>>>> afterBlockMap = new LinkedHashMap>>>>(); - - /** - * Contains {@link Node}s of method calls which return statements should be ignored. - * As key is {@link SymbolicExecutionTermLabel#getId()} used. - */ - private Map> methodReturnsToIgnoreMap = new LinkedHashMap>(); - - /** - * Contains the exception variable which is used to check if the executed program in proof terminates normally. - */ - private IProgramVariable exceptionVariable; - - /** - * The {@link TreeSettings} to use. - */ - private final TreeSettings settings; - - /** - * {@code true} infeasible paths are closed, {@code false} infeasible may be open may be closed. - */ - private final boolean isUninterpretedPredicateUsed; - - /** - * Branch conditions ({@link ExecutionBranchCondition}) are only applied to the - * execution tree model if they have at least one child. For this reason they are - * added to the model in {@link #completeTree()} after the whole proof - * tree of KeY was analyzed via {@link #visit(Proof, Node)}. The adding - * of {@link ExecutionBranchCondition} to the model must be done from leaf nodes - * to the root, but in correct child order. This {@link Deque} forms - * the order in that the {@link ExecutionBranchCondition} must be applied. - * The contained {@link List} makes sure that the children are applied - * in the same order as they occur in KeY's proof tree. - */ - private final Deque, List>> branchConditionsStack = new LinkedList, List>>(); - - /** - * Constructor. - * @param proof The {@link Proof} to extract the symbolic execution tree from. - * @param mergeBranchConditions {@code true} merge branch conditions which means that a branch condition never contains another branch condition or {@code false} allow that branch conditions contains branch conditions. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public SymbolicExecutionTreeBuilder(Proof proof, - boolean mergeBranchConditions, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) { - assert proof != null; - this.proof = proof; - this.isUninterpretedPredicateUsed = AbstractOperationPO.getUninterpretedPredicate(getProof()) != null; - this.settings = new TreeSettings(mergeBranchConditions, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - this.exceptionVariable = SymbolicExecutionUtil.extractExceptionVariable(proof); - this.startNode = new ExecutionStart(settings, proof.root()); - this.keyNodeMapping.put(proof.root(), this.startNode); - initMethodCallStack(proof.root(), proof.getServices()); - } - - /** - *

- * This method initializes {@link #methodCallStack} in case that the - * initial {@link Sequent} contains {@link MethodFrame}s in its modality. - *

- *

- * This is required because if a block of statements is executed instead - * of a method the initial {@link Sequent} contains also a {@link MethodFrame}. - * This initial {@link MethodFrame} is required to simulate an execution - * context which is required to access class members. - *

- * @param root The root {@link Node} with the initial {@link Sequent}. - * @param services The {@link Services} to use. - */ - protected void initMethodCallStack(final Node root, Services services) { - // Find all modalities in the succedent - final List modalityTerms = new LinkedList(); - for (SequentFormula sequentFormula : root.sequent().succedent()) { - sequentFormula.formula().execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - if (visited.op() instanceof Modality && SymbolicExecutionUtil.hasSymbolicExecutionLabel(visited)) { - modalityTerms.add(visited); - } + /** + * The {@link Proof} from which the symbolic execution tree is extracted. + */ + private Proof proof; + + /** + * The start node of the symbolic execution tree. + */ + private ExecutionStart startNode; + + /** + *

+ * Maps a {@link Node} of KeY's proof tree to his execution tree model representation if it is + * available. + *

+ *

+ * In case that the {@link Node} is represented by multiple {@link AbstractExecutionNode}s, e.g. + * a return statement and a method return, the last node is returned. + *

+ */ + private Map> keyNodeMapping = + new LinkedHashMap>(); + + /** + * In case a {@link Node} is represented by multiple {@link AbstractExecutionNode}s, this map + * maps the {@link Node} to all its representations. + */ + private Map>> multipleExecutionNodes = + new LinkedHashMap>>(); + + /** + * Maps a loop condition of a {@link Node} of KeY's proof tree to his execution tree model + * representation ({@link IExecutionLoopCondition}) if it is available. + */ + private Map keyNodeLoopConditionMapping = + new LinkedHashMap(); + + /** + * Maps a branch condition of a {@link Node} of KeY's proof tree to his execution tree model + * representation ({@link IExecutionBranchCondition}) if it is available. + */ + private Map keyNodeBranchConditionMapping = + new LinkedHashMap(); + + /** + * Contains the method call stacks for each tracked symbolic execution modality. As key is + * {@link SymbolicExecutionTermLabel#getId()} used. + */ + private Map>> methodCallStackMap = + new LinkedHashMap>>(); + + /** + * Contains the possible statements after a code block of interest for each tracked symbolic + * execution modality. As key is {@link SymbolicExecutionTermLabel#getId()} used. + */ + private Map>>>> afterBlockMap = + new LinkedHashMap>>>>(); + + /** + * Contains {@link Node}s of method calls which return statements should be ignored. As key is + * {@link SymbolicExecutionTermLabel#getId()} used. + */ + private Map> methodReturnsToIgnoreMap = + new LinkedHashMap>(); + + /** + * Contains the exception variable which is used to check if the executed program in proof + * terminates normally. + */ + private IProgramVariable exceptionVariable; + + /** + * The {@link TreeSettings} to use. + */ + private final TreeSettings settings; + + /** + * {@code true} infeasible paths are closed, {@code false} infeasible may be open may be closed. + */ + private final boolean isUninterpretedPredicateUsed; + + /** + * Branch conditions ({@link ExecutionBranchCondition}) are only applied to the execution tree + * model if they have at least one child. For this reason they are added to the model in + * {@link #completeTree()} after the whole proof tree of KeY was analyzed via + * {@link #visit(Proof, Node)}. The adding of {@link ExecutionBranchCondition} to the model must + * be done from leaf nodes to the root, but in correct child order. This {@link Deque} forms the + * order in that the {@link ExecutionBranchCondition} must be applied. The contained + * {@link List} makes sure that the children are applied in the same order as they occur in + * KeY's proof tree. + */ + private final Deque, List>> branchConditionsStack = + new LinkedList, List>>(); + + /** + * Constructor. + * + * @param proof The {@link Proof} to extract the symbolic execution tree from. + * @param mergeBranchConditions {@code true} merge branch conditions which means that a branch + * condition never contains another branch condition or {@code false} allow that branch + * conditions contains branch conditions. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + */ + public SymbolicExecutionTreeBuilder(Proof proof, boolean mergeBranchConditions, + boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean simplifyConditions) { + assert proof != null; + this.proof = proof; + this.isUninterpretedPredicateUsed = + AbstractOperationPO.getUninterpretedPredicate(getProof()) != null; + this.settings = new TreeSettings(mergeBranchConditions, useUnicode, usePrettyPrinting, + variablesAreOnlyComputedFromUpdates, simplifyConditions); + this.exceptionVariable = SymbolicExecutionUtil.extractExceptionVariable(proof); + this.startNode = new ExecutionStart(settings, proof.root()); + this.keyNodeMapping.put(proof.root(), this.startNode); + initMethodCallStack(proof.root(), proof.getServices()); + } + + /** + *

+ * This method initializes {@link #methodCallStack} in case that the initial {@link Sequent} + * contains {@link MethodFrame}s in its modality. + *

+ *

+ * This is required because if a block of statements is executed instead of a method the initial + * {@link Sequent} contains also a {@link MethodFrame}. This initial {@link MethodFrame} is + * required to simulate an execution context which is required to access class members. + *

+ * + * @param root The root {@link Node} with the initial {@link Sequent}. + * @param services The {@link Services} to use. + */ + protected void initMethodCallStack(final Node root, Services services) { + // Find all modalities in the succedent + final List modalityTerms = new LinkedList(); + for (SequentFormula sequentFormula : root.sequent().succedent()) { + sequentFormula.formula().execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + if (visited.op() instanceof Modality + && SymbolicExecutionUtil.hasSymbolicExecutionLabel(visited)) { + modalityTerms.add(visited); + } + } + }); + } + // Make sure that at least one modality was found + if (modalityTerms.isEmpty()) { + throw new IllegalStateException( + "Sequent contains no modalities with symbolic execution label."); + } + // Make sure that at most one modality was found + if (modalityTerms.size() >= 2) { + throw new IllegalStateException( + "Sequent contains multiple modalities with symbolic execution label."); + } + // Make sure that modality has symbolic execution label + Term modalityTerm = modalityTerms.get(0); + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); + if (label == null) { + throw new IllegalStateException( + "Modality \"" + modalityTerm + "\" has no symbolic execution term label."); + } + // Check if modality contains method frames + if (!modalityTerms.isEmpty()) { + JavaBlock javaBlock = modalityTerm.javaBlock(); + final ProgramElement program = javaBlock.program(); + final List initialStack = new LinkedList(); + new JavaASTVisitor(program, services) { + @Override + protected void doDefaultAction(SourceElement node) {} + + @Override + public void performActionOnMethodFrame(MethodFrame x) { + initialStack.add(root); + } + + public void run() { + walk(program); + } + }.run(); + Map> methodCallStack = getMethodCallStack(label); + methodCallStack.put(root, ImmutableSLList.nil().append(initialStack)); + } + } + + /** + * Returns the method {@link Node}s of method calls for which its return should be ignored. If + * not already available an empty method {@link Set} is created. + * + * @param ruleApp The {@link RuleApp} which modifies a modality {@link Term} with a + * {@link SymbolicExecutionTermLabel}. + * @return The {@link Set} of {@link Node}s to ignore its return. + */ + protected Set getMethodReturnsToIgnore(RuleApp ruleApp) { + SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); + return getMethodReturnsToIgnore(label); + } + + /** + * Returns the method {@link Node}s of method calls for which its return should be ignored. If + * not already available an empty method {@link Set} is created. + * + * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. + * @return The {@link Set} of {@link Node}s to ignore its return. + */ + protected Set getMethodReturnsToIgnore(SymbolicExecutionTermLabel label) { + assert label != null : "No symbolic execuion term label provided"; + return getMethodReturnsToIgnore(label.getId()); + } + + /** + * Returns the method {@link Node}s of method calls for which its return should be ignored. If + * not already available an empty method {@link Set} is created. + * + * @param id The ID. + * @return The {@link Set} of {@link Node}s to ignore its return. + */ + protected Set getMethodReturnsToIgnore(int id) { + synchronized (methodReturnsToIgnoreMap) { + Integer key = Integer.valueOf(id); + Set result = methodReturnsToIgnoreMap.get(key); + if (result == null) { + result = new LinkedHashSet(); + methodReturnsToIgnoreMap.put(key, result); } - }); - } - // Make sure that at least one modality was found - if (modalityTerms.isEmpty()) { - throw new IllegalStateException("Sequent contains no modalities with symbolic execution label."); - } - // Make sure that at most one modality was found - if (modalityTerms.size() >= 2) { - throw new IllegalStateException("Sequent contains multiple modalities with symbolic execution label."); - } - // Make sure that modality has symbolic execution label - Term modalityTerm = modalityTerms.get(0); - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); - if (label == null) { - throw new IllegalStateException("Modality \"" + modalityTerm + "\" has no symbolic execution term label."); - } - // Check if modality contains method frames - if (!modalityTerms.isEmpty()) { - JavaBlock javaBlock = modalityTerm.javaBlock(); - final ProgramElement program = javaBlock.program(); - final List initialStack = new LinkedList(); - new JavaASTVisitor(program, services) { - @Override - protected void doDefaultAction(SourceElement node) { + return result; + } + } + + /** + * Returns the method call stack. If not already available an empty method call stack is + * created. + * + * @param ruleApp The {@link RuleApp} which modifies a modality {@link Term} with a + * {@link SymbolicExecutionTermLabel}. + * @return The method call stack of the ID of the modified modality {@link Term} with a + * {@link SymbolicExecutionTermLabel}. + */ + protected Map> getMethodCallStack(RuleApp ruleApp) { + SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); + return getMethodCallStack(label); + } + + /** + * Returns the method call stack. If not already available an empty method call stack is + * created. + * + * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. + * @return The method call stack of the ID of the given {@link SymbolicExecutionTermLabel}. + */ + protected Map> getMethodCallStack(SymbolicExecutionTermLabel label) { + assert label != null : "No symbolic execuion term label provided"; + return getMethodCallStack(label.getId()); + } + + /** + * Returns the method call stack used for the given ID. If not already available an empty method + * call stack is created. + * + * @param id The ID. + * @return The method call stack of the given ID. + */ + protected Map> getMethodCallStack(int id) { + synchronized (methodCallStackMap) { + Integer key = Integer.valueOf(id); + Map> result = methodCallStackMap.get(key); + if (result == null) { + result = new HashMap>(); + methodCallStackMap.put(key, result); } - - @Override - public void performActionOnMethodFrame(MethodFrame x) { - initialStack.add(root); + return result; + } + } + + /** + * Frees all resources. If this method is called it is no longer possible to use the + * {@link SymbolicExecutionTreeBuilder} instance! Later usage is not checked and punished with + * exceptions. + */ + public void dispose() { + if (keyNodeMapping != null) { + keyNodeMapping.clear(); + keyNodeMapping = null; + } + if (keyNodeLoopConditionMapping != null) { + keyNodeLoopConditionMapping.clear(); + keyNodeLoopConditionMapping = null; + } + if (keyNodeBranchConditionMapping != null) { + keyNodeBranchConditionMapping.clear(); + keyNodeBranchConditionMapping = null; + } + if (methodCallStackMap != null) { + methodCallStackMap.clear(); + methodCallStackMap = null; + } + if (afterBlockMap != null) { + afterBlockMap.clear(); + afterBlockMap = null; + } + if (methodReturnsToIgnoreMap != null) { + methodReturnsToIgnoreMap.clear(); + methodReturnsToIgnoreMap = null; + } + exceptionVariable = null; + proof = null; + startNode = null; + } + + /** + * Returns the {@link Proof} from which the symbolic execution tree is extracted. + * + * @return The {@link Proof} from which the symbolic execution tree is extracted. + */ + public Proof getProof() { + return proof; + } + + /** + * Returns the start node of the symbolic execution tree. + * + * @return The start node of the symbolic execution tree. + */ + public IExecutionStart getStartNode() { + return startNode; + } + + /** + * This method must be called programmatically to update the symbolic execution tree. The first + * call will create the initial tree and further call will update the existing tree. + * + * @return The detected {@link SymbolicExecutionCompletions} during symbolic execution. + */ + public SymbolicExecutionCompletions analyse() { + SymbolicExecutionCompletions completions = new SymbolicExecutionCompletions(); + AnalyzerProofVisitor visitor = new AnalyzerProofVisitor(completions); + NodePreorderIterator iter = new NodePreorderIterator(proof.root()); + while (iter.hasNext()) { + Node node = iter.next(); + visitor.visit(proof, node); // This visitor pattern must be used because a recursive + // iteration causes StackOverflowErrors if the proof tree in + // KeY is to deep (e.g. simple list with 2000 elements + // during computation of fibonacci(7) + } + visitor.completeTree(); + visitor.injectLinks(); // Needs to be execute after the completeTree() is called. + return completions; + } + + /** + * Prunes the symbolic execution tree at the first {@link IExecutionNode} in the parent + * hierarchy of the given {@link Node} (including the Node itself). + * + * @param node {@link Node} to be pruned. + * @author Anna Filighera + * @return The {@link AbstractExecutionNode}'s which where deleted. + */ + public Set> prune(Node node) { + // search for the first node in the parent hierarchy (including the node itself) who is an + // AbstractExecutionNode + boolean pruneOnExNode = false; + IExecutionNode firstFather = getExecutionNode(node); + if (firstFather != null && firstFather != startNode) { + pruneOnExNode = true; + } else { + while (firstFather == null) { + node = node.parent(); + firstFather = getExecutionNode(node); } - - public void run() { - walk(program); + } + // determine which nodes should be pruned + ExecutionNodePreorderIterator subtreeToBePruned = + new ExecutionNodePreorderIterator(firstFather); + // include the first execution node in the hierarchy only if it was pruned on + if (!pruneOnExNode) { + subtreeToBePruned.next(); + } + Set> exNodesToDelete = new HashSet>(); + while (subtreeToBePruned.hasNext()) { + AbstractExecutionNode exNode = (AbstractExecutionNode) subtreeToBePruned.next(); + exNodesToDelete.add(exNode); + Node correspondingNode = exNode.getProofNode(); + keyNodeMapping.remove(correspondingNode); + keyNodeLoopConditionMapping.remove(correspondingNode); + keyNodeBranchConditionMapping.remove(correspondingNode); + SymbolicExecutionTermLabel label = SymbolicExecutionUtil + .getSymbolicExecutionLabel(correspondingNode.getAppliedRuleApp()); + if (label != null) { + methodCallStackMap.remove(label); + afterBlockMap.remove(label); + methodReturnsToIgnoreMap.remove(label); } - }.run(); - Map> methodCallStack = getMethodCallStack(label); - methodCallStack.put(root, ImmutableSLList.nil().append(initialStack)); - } - } - - /** - * Returns the method {@link Node}s of method calls for - * which its return should be ignored. If not already - * available an empty method {@link Set} is created. - * @param ruleApp The {@link RuleApp} which modifies a modality {@link Term} with a {@link SymbolicExecutionTermLabel}. - * @return The {@link Set} of {@link Node}s to ignore its return. - */ - protected Set getMethodReturnsToIgnore(RuleApp ruleApp) { - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); - return getMethodReturnsToIgnore(label); - } - - /** - * Returns the method {@link Node}s of method calls for - * which its return should be ignored. If not already - * available an empty method {@link Set} is created. - * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. - * @return The {@link Set} of {@link Node}s to ignore its return. - */ - protected Set getMethodReturnsToIgnore(SymbolicExecutionTermLabel label) { - assert label != null : "No symbolic execuion term label provided"; - return getMethodReturnsToIgnore(label.getId()); - } - - /** - * Returns the method {@link Node}s of method calls for - * which its return should be ignored. If not already - * available an empty method {@link Set} is created. - * @param id The ID. - * @return The {@link Set} of {@link Node}s to ignore its return. - */ - protected Set getMethodReturnsToIgnore(int id) { - synchronized (methodReturnsToIgnoreMap) { - Integer key = Integer.valueOf(id); - Set result = methodReturnsToIgnoreMap.get(key); - if (result == null) { - result = new LinkedHashSet(); - methodReturnsToIgnoreMap.put(key, result); - } - return result; - } - } - - /** - * Returns the method call stack. If not already - * available an empty method call stack is created. - * @param ruleApp The {@link RuleApp} which modifies a modality {@link Term} with a {@link SymbolicExecutionTermLabel}. - * @return The method call stack of the ID of the modified modality {@link Term} with a {@link SymbolicExecutionTermLabel}. - */ - protected Map> getMethodCallStack(RuleApp ruleApp) { - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); - return getMethodCallStack(label); - } - - /** - * Returns the method call stack. If not already - * available an empty method call stack is created. - * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. - * @return The method call stack of the ID of the given {@link SymbolicExecutionTermLabel}. - */ - protected Map> getMethodCallStack(SymbolicExecutionTermLabel label) { - assert label != null : "No symbolic execuion term label provided"; - return getMethodCallStack(label.getId()); - } - - /** - * Returns the method call stack used for the given ID. If not already - * available an empty method call stack is created. - * @param id The ID. - * @return The method call stack of the given ID. - */ - protected Map> getMethodCallStack(int id) { - synchronized (methodCallStackMap) { - Integer key = Integer.valueOf(id); - Map> result = methodCallStackMap.get(key); - if (result == null) { - result = new HashMap>(); - methodCallStackMap.put(key, result); - } - return result; - } - } - - /** - * Frees all resources. If this method is called it is no longer possible - * to use the {@link SymbolicExecutionTreeBuilder} instance! Later usage - * is not checked and punished with exceptions. - */ - public void dispose() { - if (keyNodeMapping != null) { - keyNodeMapping.clear(); - keyNodeMapping = null; - } - if (keyNodeLoopConditionMapping != null) { - keyNodeLoopConditionMapping.clear(); - keyNodeLoopConditionMapping = null; - } - if (keyNodeBranchConditionMapping != null) { - keyNodeBranchConditionMapping.clear(); - keyNodeBranchConditionMapping = null; - } - if (methodCallStackMap != null) { - methodCallStackMap.clear(); - methodCallStackMap = null; - } - if (afterBlockMap != null) { - afterBlockMap.clear(); - afterBlockMap = null; - } - if (methodReturnsToIgnoreMap != null) { - methodReturnsToIgnoreMap.clear(); - methodReturnsToIgnoreMap = null; - } - exceptionVariable = null; - proof = null; - startNode = null; - } - - /** - * Returns the {@link Proof} from which the symbolic execution tree is extracted. - * @return The {@link Proof} from which the symbolic execution tree is extracted. - */ - public Proof getProof() { - return proof; - } - - /** - * Returns the start node of the symbolic execution tree. - * @return The start node of the symbolic execution tree. - */ - public IExecutionStart getStartNode() { - return startNode; - } - - /** - * This method must be called programmatically to update the - * symbolic execution tree. The first call will create the initial tree - * and further call will update the existing tree. - * @return The detected {@link SymbolicExecutionCompletions} during symbolic execution. - */ - public SymbolicExecutionCompletions analyse() { - SymbolicExecutionCompletions completions = new SymbolicExecutionCompletions(); - AnalyzerProofVisitor visitor = new AnalyzerProofVisitor(completions); - NodePreorderIterator iter = new NodePreorderIterator(proof.root()); - while (iter.hasNext()) { - Node node = iter.next(); - visitor.visit(proof, node); // This visitor pattern must be used because a recursive iteration causes StackOverflowErrors if the proof tree in KeY is to deep (e.g. simple list with 2000 elements during computation of fibonacci(7) - } - visitor.completeTree(); - visitor.injectLinks(); // Needs to be execute after the completeTree() is called. - return completions; - } - - /** - * Prunes the symbolic execution tree at the first {@link IExecutionNode} in the parent hierarchy of the given - * {@link Node} (including the Node itself). - * @param node {@link Node} to be pruned. - * @author Anna Filighera - * @return The {@link AbstractExecutionNode}'s which where deleted. - */ - public Set> prune(Node node) { - // search for the first node in the parent hierarchy (including the node itself) who is an AbstractExecutionNode - boolean pruneOnExNode = false; - IExecutionNode firstFather = getExecutionNode(node); - if (firstFather != null && firstFather != startNode) { - pruneOnExNode = true; - } - else { - while (firstFather == null) { - node = node.parent(); - firstFather = getExecutionNode(node); - } - } - // determine which nodes should be pruned - ExecutionNodePreorderIterator subtreeToBePruned = new ExecutionNodePreorderIterator(firstFather); - // include the first execution node in the hierarchy only if it was pruned on - if (!pruneOnExNode) { - subtreeToBePruned.next(); - } - Set> exNodesToDelete = new HashSet>(); - while (subtreeToBePruned.hasNext()) { - AbstractExecutionNode exNode = (AbstractExecutionNode) subtreeToBePruned.next(); - exNodesToDelete.add(exNode); - Node correspondingNode = exNode.getProofNode(); - keyNodeMapping.remove(correspondingNode); - keyNodeLoopConditionMapping.remove(correspondingNode); - keyNodeBranchConditionMapping.remove(correspondingNode); - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(correspondingNode.getAppliedRuleApp()); - if (label != null) { - methodCallStackMap.remove(label); - afterBlockMap.remove(label); - methodReturnsToIgnoreMap.remove(label); - } - } - // remove all parent-child-references of pruned nodes and links - Iterator> prunedExNodes = exNodesToDelete.iterator(); - while (prunedExNodes.hasNext()) { - // remove all parent-child-references of pruned nodes - AbstractExecutionNode exNode = prunedExNodes.next(); - AbstractExecutionNode exParent = exNode.getParent(); - if (exParent != null) { - exParent.removeChild(exNode); - exNode.setParent(null); - } - // Remove outgoing links - if (!exNode.getOutgoingLinks().isEmpty()) { - for (IExecutionLink link : exNode.getOutgoingLinks()) { - ((AbstractExecutionNode) link.getSource()).removeOutgoingLink(link); - ((AbstractExecutionNode) link.getTarget()).removeIncomingLink(link); + } + // remove all parent-child-references of pruned nodes and links + Iterator> prunedExNodes = exNodesToDelete.iterator(); + while (prunedExNodes.hasNext()) { + // remove all parent-child-references of pruned nodes + AbstractExecutionNode exNode = prunedExNodes.next(); + AbstractExecutionNode exParent = exNode.getParent(); + if (exParent != null) { + exParent.removeChild(exNode); + exNode.setParent(null); } - } - // Remove incoming links - if (!exNode.getIncomingLinks().isEmpty()) { - for (IExecutionLink link : exNode.getIncomingLinks()) { - ((AbstractExecutionNode) link.getSource()).removeOutgoingLink(link); - ((AbstractExecutionNode) link.getTarget()).removeIncomingLink(link); + // Remove outgoing links + if (!exNode.getOutgoingLinks().isEmpty()) { + for (IExecutionLink link : exNode.getOutgoingLinks()) { + ((AbstractExecutionNode) link.getSource()).removeOutgoingLink(link); + ((AbstractExecutionNode) link.getTarget()).removeIncomingLink(link); + } } - } - } - // remove all other references to deleted nodes - ExecutionNodePreorderIterator remainingExNodes = new ExecutionNodePreorderIterator(startNode); - while (remainingExNodes.hasNext()) { - AbstractExecutionNode exNode = (AbstractExecutionNode) remainingExNodes.next(); - LinkedList> deletedBlocks = new LinkedList>(); - Iterator> blockIter = exNode.getCompletedBlocks().iterator(); - // remove pruned completed blocks - while (blockIter.hasNext()) { - IExecutionBlockStartNode block = blockIter.next(); - if (exNodesToDelete.contains(block)) { - deletedBlocks.add(block); + // Remove incoming links + if (!exNode.getIncomingLinks().isEmpty()) { + for (IExecutionLink link : exNode.getIncomingLinks()) { + ((AbstractExecutionNode) link.getSource()).removeOutgoingLink(link); + ((AbstractExecutionNode) link.getTarget()).removeIncomingLink(link); + } } - } - for (IExecutionBlockStartNode block : deletedBlocks) { - exNode.removeCompletedBlock(block); - } - // remove all pruned method returns - if (exNode instanceof ExecutionMethodCall) { - Iterator> iter = ((ExecutionMethodCall) exNode).getMethodReturns().iterator(); - LinkedList> removed = new LinkedList>(); - while (iter.hasNext()) { - IExecutionBaseMethodReturn methodReturn = iter.next(); - if (exNodesToDelete.contains(methodReturn)) { - removed.add(methodReturn); - } + } + // remove all other references to deleted nodes + ExecutionNodePreorderIterator remainingExNodes = + new ExecutionNodePreorderIterator(startNode); + while (remainingExNodes.hasNext()) { + AbstractExecutionNode exNode = (AbstractExecutionNode) remainingExNodes.next(); + LinkedList> deletedBlocks = + new LinkedList>(); + Iterator> blockIter = + exNode.getCompletedBlocks().iterator(); + // remove pruned completed blocks + while (blockIter.hasNext()) { + IExecutionBlockStartNode block = blockIter.next(); + if (exNodesToDelete.contains(block)) { + deletedBlocks.add(block); + } } - for (IExecutionBaseMethodReturn deleted : removed) { - ((ExecutionMethodCall) exNode).removeMethodReturn(deleted); + for (IExecutionBlockStartNode block : deletedBlocks) { + exNode.removeCompletedBlock(block); } - } - // remove all pruned execution nodes that complete a still existing block - if (exNode instanceof AbstractExecutionBlockStartNode) { - Iterator> iter = ((AbstractExecutionBlockStartNode) exNode).getBlockCompletions().iterator(); - LinkedList> removed = new LinkedList>(); - while (iter.hasNext()) { - IExecutionNode completion = iter.next(); - if (exNodesToDelete.contains(completion)) { - removed.add(completion); - } + // remove all pruned method returns + if (exNode instanceof ExecutionMethodCall) { + Iterator> iter = + ((ExecutionMethodCall) exNode).getMethodReturns().iterator(); + LinkedList> removed = + new LinkedList>(); + while (iter.hasNext()) { + IExecutionBaseMethodReturn methodReturn = iter.next(); + if (exNodesToDelete.contains(methodReturn)) { + removed.add(methodReturn); + } + } + for (IExecutionBaseMethodReturn deleted : removed) { + ((ExecutionMethodCall) exNode).removeMethodReturn(deleted); + } } - for (IExecutionNode deleted : removed) { - ((AbstractExecutionBlockStartNode) exNode).removeBlockCompletion(deleted); + // remove all pruned execution nodes that complete a still existing block + if (exNode instanceof AbstractExecutionBlockStartNode) { + Iterator> iter = ((AbstractExecutionBlockStartNode) exNode) + .getBlockCompletions().iterator(); + LinkedList> removed = new LinkedList>(); + while (iter.hasNext()) { + IExecutionNode completion = iter.next(); + if (exNodesToDelete.contains(completion)) { + removed.add(completion); + } + } + for (IExecutionNode deleted : removed) { + ((AbstractExecutionBlockStartNode) exNode).removeBlockCompletion(deleted); + } } - } - // remove all pruned terminations - if (exNode instanceof ExecutionStart) { - Iterator iter = ((ExecutionStart) exNode).getTerminations().iterator(); - LinkedList removed = new LinkedList(); - while (iter.hasNext()) { - IExecutionTermination termination = iter.next(); - if (exNodesToDelete.contains(termination)) { - removed.add(termination); + // remove all pruned terminations + if (exNode instanceof ExecutionStart) { + Iterator iter = + ((ExecutionStart) exNode).getTerminations().iterator(); + LinkedList removed = new LinkedList(); + while (iter.hasNext()) { + IExecutionTermination termination = iter.next(); + if (exNodesToDelete.contains(termination)) { + removed.add(termination); + } + } + for (IExecutionTermination deleted : removed) { + ((ExecutionStart) exNode).removeTermination(deleted); } - } - for (IExecutionTermination deleted : removed) { - ((ExecutionStart) exNode).removeTermination(deleted); - } - } - } - return exNodesToDelete; - } - - /** - * Instances of this class are returned by {@link SymbolicExecutionTreeBuilder#analyse()} - * to inform about newly completed blocks and returned methods. - * @author Martin Hentschel - */ - public static class SymbolicExecutionCompletions { - /** - * The newly block completion. - */ - private final List> blockCompletions = new LinkedList>(); - - /** - * The newly methods return. - */ - private final List> methodReturns = new LinkedList>(); - - /** - * Returns the newly block completion. - * @return The newly block completion. - */ - public IExecutionNode[] getBlockCompletions() { - return blockCompletions.toArray(new IExecutionNode[blockCompletions.size()]); - } - - /** - * Registers the newly completed block. - * @param blockCompletion The new block completion. - */ - private void addBlockCompletion(IExecutionNode blockCompletion) { - if (blockCompletion != null) { - blockCompletions.add(blockCompletion); - } - } - - /** - * Returns the newly methods return. - * @return The newly methods return. - */ - public IExecutionBaseMethodReturn[] getMethodReturns() { - return methodReturns.toArray(new IExecutionBaseMethodReturn[methodReturns.size()]); - } - - /** - * Registers the newly methods return. - * @param methodReturn The method return. - */ - private void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { - if (methodReturn != null) { - methodReturns.add(methodReturn); - } - } - } - - /** - * This {@link ProofVisitor} is used to transfer the proof tree in KeY - * into {@link IExecutionNode}s which forms the symbolic execution tree. - * @author Martin Hentschel - */ - private class AnalyzerProofVisitor implements ProofVisitor { - /** - * The {@link SymbolicExecutionCompletions} to update. - */ - private final SymbolicExecutionCompletions completions; - - /** - * Maps the {@link Node} in KeY's proof tree to the {@link IExecutionNode} of the symbolic execution tree where the {@link Node}s children should be added to. - */ - private Map> addToMapping = new LinkedHashMap>(); - - /** - * This utility {@link Map} helps to find a {@link List} in {@link #branchConditionsStack} - * for the given parent node to that elements in the {@link List} should be added. - */ - private Map, List> parentToBranchConditionMapping = new LinkedHashMap, List>(); - - /** - * Contains all {@link Node}s which are closed after a join. - */ - private ImmutableList joinNodes = ImmutableSLList.nil(); - - /** - * Constructor. - * @param completions The {@link SymbolicExecutionCompletions} to update. - */ - public AnalyzerProofVisitor(SymbolicExecutionCompletions completions) { - this.completions = completions; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Proof proof, Node visitedNode) { - // Find the parent node (IExecutionNode) to that the execution tree model representation of the given KeY's proof tree node should be added. - AbstractExecutionNode parentToAddTo = keyNodeBranchConditionMapping.get(visitedNode); - if (parentToAddTo == null) { - Node parent = visitedNode.parent(); - if (parent != null) { - parentToAddTo = addToMapping.get(parent); } - else { - parentToAddTo = startNode; + } + return exNodesToDelete; + } + + /** + * Instances of this class are returned by {@link SymbolicExecutionTreeBuilder#analyse()} to + * inform about newly completed blocks and returned methods. + * + * @author Martin Hentschel + */ + public static class SymbolicExecutionCompletions { + /** + * The newly block completion. + */ + private final List> blockCompletions = + new LinkedList>(); + + /** + * The newly methods return. + */ + private final List> methodReturns = + new LinkedList>(); + + /** + * Returns the newly block completion. + * + * @return The newly block completion. + */ + public IExecutionNode[] getBlockCompletions() { + return blockCompletions.toArray(new IExecutionNode[blockCompletions.size()]); + } + + /** + * Registers the newly completed block. + * + * @param blockCompletion The new block completion. + */ + private void addBlockCompletion(IExecutionNode blockCompletion) { + if (blockCompletion != null) { + blockCompletions.add(blockCompletion); } - } - // Transform the current proof node into a symbolic execution tree node if possible - parentToAddTo = analyzeNode(visitedNode, parentToAddTo, completions); - addToMapping.put(visitedNode, parentToAddTo); - // Check if the current node has branch conditions which should be added to the execution tree model - if (!(parentToAddTo instanceof IExecutionStart) && // Ignore branch conditions before starting with code execution - hasBranchCondition(visitedNode)) { - Iterator iter = visitedNode.childrenIterator(); - while (iter.hasNext()) { - Node childNode = iter.next(); - if (!keyNodeBranchConditionMapping.containsKey(childNode)) { - if (!shouldPrune(visitedNode)) { // Filter out branches that are closed - // Create branch condition - String additionalBranchLabel = null; - if (visitedNode.getAppliedRuleApp().rule() instanceof BuiltInRule) { - additionalBranchLabel = childNode.getNodeInfo().getBranchLabel(); - } - ExecutionBranchCondition condition = new ExecutionBranchCondition(settings, childNode, additionalBranchLabel); - // Add branch condition to the branch condition attributes for later adding to the proof tree. This is required for instance to filter out branches after the symbolic execution has finished. - List list = parentToBranchConditionMapping.get(parentToAddTo); - if (list == null) { - list = new LinkedList(); - branchConditionsStack.addFirst(new DefaultEntry, List>(parentToAddTo, list)); - parentToBranchConditionMapping.put(parentToAddTo, list); - } - list.add(condition); - keyNodeBranchConditionMapping.put(childNode, condition); - // Set call stack on new created node if possible - if (SymbolicExecutionUtil.hasSymbolicExecutionLabel(visitedNode.getAppliedRuleApp())) { - condition.setCallStack(createCallStack(visitedNode)); - } - } - } + } + + /** + * Returns the newly methods return. + * + * @return The newly methods return. + */ + public IExecutionBaseMethodReturn[] getMethodReturns() { + return methodReturns.toArray(new IExecutionBaseMethodReturn[methodReturns.size()]); + } + + /** + * Registers the newly methods return. + * + * @param methodReturn The method return. + */ + private void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { + if (methodReturn != null) { + methodReturns.add(methodReturn); } - } - if (SymbolicExecutionUtil.isJoin(visitedNode.getAppliedRuleApp())) { - joinNodes = joinNodes.prepend(visitedNode); - } - } - - /** - * Instantiates all missing {@link IExecutionLink}s and injects them into the symbolic execution tree. - */ - public void injectLinks() { - for (Node node : joinNodes) { - MergeRuleBuiltInRuleApp ruleApp = (MergeRuleBuiltInRuleApp) node.getAppliedRuleApp(); - IExecutionNode source = getBestExecutionNode(node); - if (source != null) { - for (MergePartner partner : ruleApp.getMergePartners()) { - IExecutionNode target = getBestExecutionNode(partner.getGoal().node()); - // Ignore branch conditions below join node - while (target instanceof IExecutionBranchCondition) { - target = getBestExecutionNode(target.getProofNode().parent()); - } - if (target != null) { - IExecutionLink link = source.getOutgoingLink(target); - if (link == null) { - link = new ExecutionLink(target, source); // Source and target needs to be swapped in the symbolic execution tree - ((AbstractExecutionNode) link.getTarget()).addIncomingLink(link); - ((AbstractExecutionNode) link.getSource()).addOutgoingLink(link); - } - } - } + } + } + + /** + * This {@link ProofVisitor} is used to transfer the proof tree in KeY into + * {@link IExecutionNode}s which forms the symbolic execution tree. + * + * @author Martin Hentschel + */ + private class AnalyzerProofVisitor implements ProofVisitor { + /** + * The {@link SymbolicExecutionCompletions} to update. + */ + private final SymbolicExecutionCompletions completions; + + /** + * Maps the {@link Node} in KeY's proof tree to the {@link IExecutionNode} of the symbolic + * execution tree where the {@link Node}s children should be added to. + */ + private Map> addToMapping = + new LinkedHashMap>(); + + /** + * This utility {@link Map} helps to find a {@link List} in {@link #branchConditionsStack} + * for the given parent node to that elements in the {@link List} should be added. + */ + private Map, List> parentToBranchConditionMapping = + new LinkedHashMap, List>(); + + /** + * Contains all {@link Node}s which are closed after a join. + */ + private ImmutableList joinNodes = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param completions The {@link SymbolicExecutionCompletions} to update. + */ + public AnalyzerProofVisitor(SymbolicExecutionCompletions completions) { + this.completions = completions; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Proof proof, Node visitedNode) { + // Find the parent node (IExecutionNode) to that the execution tree model representation + // of the given KeY's proof tree node should be added. + AbstractExecutionNode parentToAddTo = keyNodeBranchConditionMapping.get(visitedNode); + if (parentToAddTo == null) { + Node parent = visitedNode.parent(); + if (parent != null) { + parentToAddTo = addToMapping.get(parent); + } else { + parentToAddTo = startNode; + } } - } - } - - /** - *

- * Completes the execution tree model after all {@link Node}s were visited - * in {@link #visit(Proof, Node)}. The task of this method is to add - * {@link ExecutionBranchCondition} to the model if they have at least one child. - *

- *

- * Fore more details have a look at the documentation of {@link #branchConditionsStack}. - *

- */ - public void completeTree() { - Iterator, List>> stackIter = branchConditionsStack.iterator(); - while (stackIter.hasNext()) { - Entry, List> entry = stackIter.next(); - Iterator bcIter = entry.getValue().iterator(); - while (bcIter.hasNext()) { - ExecutionBranchCondition condition = bcIter.next(); - AbstractExecutionNode[] conditionsChildren = condition.getChildren(); - if (!ArrayUtil.isEmpty(conditionsChildren)) { - if (settings.isMergeBranchConditions()) { - // Merge branch conditions if possible - boolean addingToParentRequired = false; - for (AbstractExecutionNode child : conditionsChildren) { - if (child instanceof ExecutionBranchCondition) { - ExecutionBranchCondition bcChild = (ExecutionBranchCondition)child; - bcChild.addMergedProofNode(condition.getProofNode()); - addChild(entry.getKey(), child); // Move child one up in hierarchy - finishBlockCompletion(condition); + // Transform the current proof node into a symbolic execution tree node if possible + parentToAddTo = analyzeNode(visitedNode, parentToAddTo, completions); + addToMapping.put(visitedNode, parentToAddTo); + // Check if the current node has branch conditions which should be added to the + // execution tree model + if (!(parentToAddTo instanceof IExecutionStart) && // Ignore branch conditions before + // starting with code execution + hasBranchCondition(visitedNode)) { + Iterator iter = visitedNode.childrenIterator(); + while (iter.hasNext()) { + Node childNode = iter.next(); + if (!keyNodeBranchConditionMapping.containsKey(childNode)) { + if (!shouldPrune(visitedNode)) { // Filter out branches that are closed + // Create branch condition + String additionalBranchLabel = null; + if (visitedNode.getAppliedRuleApp().rule() instanceof BuiltInRule) { + additionalBranchLabel = childNode.getNodeInfo().getBranchLabel(); + } + ExecutionBranchCondition condition = new ExecutionBranchCondition( + settings, childNode, additionalBranchLabel); + // Add branch condition to the branch condition attributes for later + // adding to the proof tree. This is required for instance to filter out + // branches after the symbolic execution has finished. + List list = + parentToBranchConditionMapping.get(parentToAddTo); + if (list == null) { + list = new LinkedList(); + branchConditionsStack.addFirst( + new DefaultEntry, List>( + parentToAddTo, list)); + parentToBranchConditionMapping.put(parentToAddTo, list); + } + list.add(condition); + keyNodeBranchConditionMapping.put(childNode, condition); + // Set call stack on new created node if possible + if (SymbolicExecutionUtil + .hasSymbolicExecutionLabel(visitedNode.getAppliedRuleApp())) { + condition.setCallStack(createCallStack(visitedNode)); + } } - else { - addingToParentRequired = true; // Adding of current branch condition is required because non branch condition children are available - } - } - if (addingToParentRequired) { - addChild(entry.getKey(), condition); - finishBlockCompletion(condition); - } - } - else { - // Add all branch conditions without merging - addChild(entry.getKey(), condition); - finishBlockCompletion(condition); - } - bcIter.remove(); - } - } - if (entry.getValue().isEmpty()) { - stackIter.remove(); + } + } } - } - } - - protected void finishBlockCompletion(IExecutionBranchCondition node) { - for (IExecutionBlockStartNode start : node.getCompletedBlocks()) { - ((AbstractExecutionBlockStartNode) start).addBlockCompletion(node); // BranchConditions are updated when they are added to the SET. - completions.addBlockCompletion(node); - } - } - } - - /** - *

- * Analyzes the given {@link Proof} and his contained proof tree by - * filling the start node {@link SymbolicExecutionTreeBuilder#getStartNode()} - * with {@link IExecutionNode}s which are instantiated if a {@link Node} - * in KeY's proof tree applies a rule of symbolic execution. - *

- *

- * Attention : A correct pruning requires at the moment that - * the Taclet Option "runtimeExceptions" is set to "runtimeExceptions:allow". - * Alternatively it is required to modify rule {@code assignment_to_reference_array_component} - * in file {@code javaRules.key} by uncommenting {@code \add (!(#v=null) & lt(#se, length(#v)) & geq(#se,0) & arrayStoreValid(#v, #se0)==>)}. - *

- * @param node The {@link Node} to analyze. - * @param parentToAddTo The parent {@link IExecutionNode} to add the created execution tree model representation ({@link IExecutionNode}) of the given {@link Node} to. - * @param completions The {@link SymbolicExecutionCompletions} to update. - * @return The {@link IExecutionNode} to which children of the current {@link Node} should be added. If no execution tree model representation was created the return value is identical to the given one (parentToAddTo). - */ - protected AbstractExecutionNode analyzeNode(Node node, - AbstractExecutionNode parentToAddTo, - SymbolicExecutionCompletions completions) { - // Analyze node - if (!shouldPrune(node)) { // Prune closed branches because they are invalid - // Get required information - NodeInfo info = node.getNodeInfo(); - SourceElement statement = info.getActiveStatement(); - // Update call stack - updateCallStack(node, statement); - // Update block map - RuleApp currentOrFutureRuleApplication = node.getAppliedRuleApp(); - if (currentOrFutureRuleApplication == null && - node != proof.root()) { // Executing peekNext() on the root crashes the tests for unknown reasons. - Goal goal = proof.getGoal(node); - if (goal != null) { - currentOrFutureRuleApplication = goal.getRuleAppManager().peekNext(); + if (SymbolicExecutionUtil.isJoin(visitedNode.getAppliedRuleApp())) { + joinNodes = joinNodes.prepend(visitedNode); } - } - if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, currentOrFutureRuleApplication)) { - Map>> completedBlocks = updateAfterBlockMap(node, currentOrFutureRuleApplication); - if (completedBlocks != null) { - for (Entry>> entry : completedBlocks.entrySet()) { - for (IExecutionNode entryNode : entry.getValue()) { - if (entryNode != parentToAddTo) { // Ignore empty blocks - if (entryNode instanceof AbstractExecutionBlockStartNode) { - parentToAddTo.addCompletedBlock((AbstractExecutionBlockStartNode) entryNode); - if (!(parentToAddTo instanceof IExecutionBranchCondition)) { - ((AbstractExecutionBlockStartNode) entryNode).addBlockCompletion(parentToAddTo); // BranchConditions are updated when they are added to the SET. - completions.addBlockCompletion(parentToAddTo); - } + } + + /** + * Instantiates all missing {@link IExecutionLink}s and injects them into the symbolic + * execution tree. + */ + public void injectLinks() { + for (Node node : joinNodes) { + MergeRuleBuiltInRuleApp ruleApp = + (MergeRuleBuiltInRuleApp) node.getAppliedRuleApp(); + IExecutionNode source = getBestExecutionNode(node); + if (source != null) { + for (MergePartner partner : ruleApp.getMergePartners()) { + IExecutionNode target = getBestExecutionNode(partner.getGoal().node()); + // Ignore branch conditions below join node + while (target instanceof IExecutionBranchCondition) { + target = getBestExecutionNode(target.getProofNode().parent()); + } + if (target != null) { + IExecutionLink link = source.getOutgoingLink(target); + if (link == null) { + link = new ExecutionLink(target, source); // Source and target needs + // to be swapped in the + // symbolic execution tree + ((AbstractExecutionNode) link.getTarget()).addIncomingLink(link); + ((AbstractExecutionNode) link.getSource()).addOutgoingLink(link); + } } - } - } - } + } + } } - } - // Check if the node is already contained in the symbolic execution tree - AbstractExecutionNode executionNode = keyNodeMapping.get(node); - if (executionNode == null) { - // Try to create a new node - executionNode = createExecutionTreeModelRepresentation(parentToAddTo, node, statement); - parentToAddTo = addNodeToTreeAndUpdateParent(node, parentToAddTo, executionNode); - // Check if execution node is a method return - executionNode = createMehtodReturn(parentToAddTo, node, statement, completions); - parentToAddTo = addNodeToTreeAndUpdateParent(node, parentToAddTo, executionNode); - } - else { - parentToAddTo = executionNode; - } - // Check if loop condition is available - boolean isLoopCondition = false; - if (SymbolicExecutionUtil.hasLoopCondition(node, node.getAppliedRuleApp(), statement)) { - if (((LoopStatement) statement).getGuardExpression().getPositionInfo() != PositionInfo.UNDEFINED && - !SymbolicExecutionUtil.isDoWhileLoopCondition(node, statement) && - !SymbolicExecutionUtil.isForLoopCondition(node, statement)) { // do while and for loops exists only in the first iteration where the loop condition is not evaluated. They are transfered into while loops in later proof nodes. - isLoopCondition = true; + } + + /** + *

+ * Completes the execution tree model after all {@link Node}s were visited in + * {@link #visit(Proof, Node)}. The task of this method is to add + * {@link ExecutionBranchCondition} to the model if they have at least one child. + *

+ *

+ * Fore more details have a look at the documentation of {@link #branchConditionsStack}. + *

+ */ + public void completeTree() { + Iterator, List>> stackIter = + branchConditionsStack.iterator(); + while (stackIter.hasNext()) { + Entry, List> entry = + stackIter.next(); + Iterator bcIter = entry.getValue().iterator(); + while (bcIter.hasNext()) { + ExecutionBranchCondition condition = bcIter.next(); + AbstractExecutionNode[] conditionsChildren = condition.getChildren(); + if (!ArrayUtil.isEmpty(conditionsChildren)) { + if (settings.isMergeBranchConditions()) { + // Merge branch conditions if possible + boolean addingToParentRequired = false; + for (AbstractExecutionNode child : conditionsChildren) { + if (child instanceof ExecutionBranchCondition) { + ExecutionBranchCondition bcChild = + (ExecutionBranchCondition) child; + bcChild.addMergedProofNode(condition.getProofNode()); + addChild(entry.getKey(), child); // Move child one up in + // hierarchy + finishBlockCompletion(condition); + } else { + addingToParentRequired = true; // Adding of current branch + // condition is required because + // non branch condition children + // are available + } + } + if (addingToParentRequired) { + addChild(entry.getKey(), condition); + finishBlockCompletion(condition); + } + } else { + // Add all branch conditions without merging + addChild(entry.getKey(), condition); + finishBlockCompletion(condition); + } + bcIter.remove(); + } + } + if (entry.getValue().isEmpty()) { + stackIter.remove(); + } } - } - // Check if loop condition is available after loop invariant (rewritten into if statement) - if (statement instanceof If && - ((If) statement).getExpression().getPositionInfo() != PositionInfo.UNDEFINED && - SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()) != null && - searchDirectParentBodyPreservesInvariantBranchCondition(parentToAddTo) != null) { - isLoopCondition = true; - } - // Create loop condition if required - if (isLoopCondition) { - ExecutionLoopCondition condition = keyNodeLoopConditionMapping.get(node); - if (condition == null) { - condition = new ExecutionLoopCondition(settings, node); - addChild(parentToAddTo, condition); - keyNodeLoopConditionMapping.put(node, condition); - // Set call stack on new created node - condition.setCallStack(createCallStack(node)); - Pair secondPair = SymbolicExecutionUtil.computeSecondStatement(node.getAppliedRuleApp()); - addToBlockMap(node, condition, secondPair.first, secondPair.second, statement); + } + + protected void finishBlockCompletion(IExecutionBranchCondition node) { + for (IExecutionBlockStartNode start : node.getCompletedBlocks()) { + ((AbstractExecutionBlockStartNode) start).addBlockCompletion(node); // BranchConditions + // are + // updated + // when they + // are added + // to the + // SET. + completions.addBlockCompletion(node); } - parentToAddTo = condition; - } - } - return parentToAddTo; - } - - /** - * Searches the direct parent {@link IExecutionBranchCondition} representing - * the 'Body Preserves Invariant' branch. - * @param current The {@link IExecutionNode} to check its parent {@link IExecutionBranchCondition}s. - * @return The found {@link IExecutionBranchCondition} or {@code null} if not available. - */ - protected IExecutionBranchCondition searchDirectParentBodyPreservesInvariantBranchCondition(IExecutionNode current) { - Iterator, List>> iter = branchConditionsStack.iterator(); - while (current instanceof IExecutionBranchCondition) { - if (WhileInvariantRule.BODY_PRESERVES_INVARIANT_LABEL.equals(current.getProofNode().getNodeInfo().getBranchLabel())) { - return (IExecutionBranchCondition) current; - } - else { - // Search parent (current.getParent() is not yet defined) - boolean parentFound = false; - while (!parentFound && iter.hasNext()) { - Entry, List> entry = iter.next(); - if (entry.getValue().contains(current)) { - current = entry.getKey(); - parentFound = true; - } + } + } + + /** + *

+ * Analyzes the given {@link Proof} and his contained proof tree by filling the start node + * {@link SymbolicExecutionTreeBuilder#getStartNode()} with {@link IExecutionNode}s which are + * instantiated if a {@link Node} in KeY's proof tree applies a rule of symbolic execution. + *

+ *

+ * Attention : A correct pruning requires at the moment that the Taclet Option + * "runtimeExceptions" is set to "runtimeExceptions:allow". Alternatively it is required to + * modify rule {@code assignment_to_reference_array_component} in file {@code javaRules.key} by + * uncommenting + * {@code \add (!(#v=null) & lt(#se, length(#v)) & geq(#se,0) & arrayStoreValid(#v, #se0)==>)}. + *

+ * + * @param node The {@link Node} to analyze. + * @param parentToAddTo The parent {@link IExecutionNode} to add the created execution tree + * model representation ({@link IExecutionNode}) of the given {@link Node} to. + * @param completions The {@link SymbolicExecutionCompletions} to update. + * @return The {@link IExecutionNode} to which children of the current {@link Node} should be + * added. If no execution tree model representation was created the return value is + * identical to the given one (parentToAddTo). + */ + protected AbstractExecutionNode analyzeNode(Node node, + AbstractExecutionNode parentToAddTo, SymbolicExecutionCompletions completions) { + // Analyze node + if (!shouldPrune(node)) { // Prune closed branches because they are invalid + // Get required information + NodeInfo info = node.getNodeInfo(); + SourceElement statement = info.getActiveStatement(); + // Update call stack + updateCallStack(node, statement); + // Update block map + RuleApp currentOrFutureRuleApplication = node.getAppliedRuleApp(); + if (currentOrFutureRuleApplication == null && node != proof.root()) { // Executing + // peekNext() on + // the root + // crashes the + // tests for + // unknown + // reasons. + Goal goal = proof.getGoal(node); + if (goal != null) { + currentOrFutureRuleApplication = goal.getRuleAppManager().peekNext(); + } } - if (!parentFound) { - current = null; + if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, + currentOrFutureRuleApplication)) { + Map>> completedBlocks = + updateAfterBlockMap(node, currentOrFutureRuleApplication); + if (completedBlocks != null) { + for (Entry>> entry : completedBlocks + .entrySet()) { + for (IExecutionNode entryNode : entry.getValue()) { + if (entryNode != parentToAddTo) { // Ignore empty blocks + if (entryNode instanceof AbstractExecutionBlockStartNode) { + parentToAddTo.addCompletedBlock( + (AbstractExecutionBlockStartNode) entryNode); + if (!(parentToAddTo instanceof IExecutionBranchCondition)) { + ((AbstractExecutionBlockStartNode) entryNode) + .addBlockCompletion(parentToAddTo); // BranchConditions + // are updated + // when they are + // added to the + // SET. + completions.addBlockCompletion(parentToAddTo); + } + } + } + } + } + } } - } - } - return null; - } - - protected boolean shouldPrune(Node node) { - if (isUninterpretedPredicateUsed) { - return node.isClosed(); - } - else { - return false; - } - } - - /** - * Adds the new created {@link AbstractExecutionNode} to the symbolic execution tree - * if available and returns the new parent for future detected nodes. - * @param node The {@link Node}. - * @param parentToAddTo The parent {@link AbstractExecutionNode}. - * @param executionNode The new child {@link AbstractExecutionNode}. - * @return The new parent {@link AbstractExecutionNode}. - */ - protected AbstractExecutionNode addNodeToTreeAndUpdateParent(Node node, - AbstractExecutionNode parentToAddTo, - AbstractExecutionNode executionNode) { - // Check if a new node was created - if (executionNode != null) { - // Add new node to symbolic execution tree - addChild(parentToAddTo, executionNode); - if (keyNodeMapping.get(node) != null) { - if (multipleExecutionNodes.containsKey(node)) { - multipleExecutionNodes.get(node).add(executionNode); + // Check if the node is already contained in the symbolic execution tree + AbstractExecutionNode executionNode = keyNodeMapping.get(node); + if (executionNode == null) { + // Try to create a new node + executionNode = + createExecutionTreeModelRepresentation(parentToAddTo, node, statement); + parentToAddTo = addNodeToTreeAndUpdateParent(node, parentToAddTo, executionNode); + // Check if execution node is a method return + executionNode = createMehtodReturn(parentToAddTo, node, statement, completions); + parentToAddTo = addNodeToTreeAndUpdateParent(node, parentToAddTo, executionNode); } else { - LinkedList> list = new LinkedList>(); - list.add(keyNodeMapping.get(node)); - list.add(executionNode); - multipleExecutionNodes.put(node, list); - } - } - keyNodeMapping.put(node, executionNode); - parentToAddTo = executionNode; - // Set call stack on new created node - executionNode.setCallStack(createCallStack(node)); - } - return parentToAddTo; - } - - /** - * Updates the call stack ({@link #methodCallStack}) if the given {@link Node} - * in KeY's proof tree is a method call. - * @param node The current {@link Node}. - * @param statement The statement ({@link SourceElement}). - */ - protected void updateCallStack(Node node, - SourceElement statement) { - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); - if (label != null && - SymbolicExecutionUtil.isMethodCallNode(node, node.getAppliedRuleApp(), statement, true)) { - // Remove outdated methods from call stack - int currentLevel = SymbolicExecutionUtil.computeStackSize(node.getAppliedRuleApp()); - Map> methodCallStack = getMethodCallStack(label); - ImmutableList stack = findMethodCallStack(methodCallStack, node); - if (stack != null) { - while (stack.size() > currentLevel) { - stack = stack.take(1); - } - } - else { - stack = ImmutableSLList.nil(); - } - // Add new node to call stack. - stack = stack.prepend(node); - methodCallStack.put(node, stack); - } - } - - protected ImmutableList findMethodCallStack(Map> methodCallStack, Node node) { - ImmutableList result = null; - while (result == null && node != null) { - result = methodCallStack.get(node); - node = node.parent(); - } - return result; - } - - /** - * Creates a new execution tree model representation ({@link IExecutionNode}) - * if possible for the given {@link Node} in KeY's proof tree. - * @param parent The parent {@link IExecutionNode}. - * @param node The {@link Node} in the proof tree of KeY. - * @param statement The actual statement ({@link SourceElement}). - * @return The created {@link IExecutionNode} or {@code null} if the {@link Node} should be ignored in the symbolic execution tree. - */ - protected AbstractExecutionNode createExecutionTreeModelRepresentation(AbstractExecutionNode parent, - Node node, - SourceElement statement) { - AbstractExecutionNode result = null; - // Make sure that a statement (SourceElement) is available. - if (SymbolicExecutionUtil.hasSymbolicExecutionLabel(node.getAppliedRuleApp())) { - if (statement != null && !SymbolicExecutionUtil.isRuleAppToIgnore(node.getAppliedRuleApp())) { - // Get position information - PositionInfo posInfo = statement.getPositionInfo(); - // Determine the node representation and create it if one is available - if (SymbolicExecutionUtil.isMethodCallNode(node, node.getAppliedRuleApp(), statement)) { - result = new ExecutionMethodCall(settings, node); - } - else if (SymbolicExecutionUtil.isTerminationNode(node, node.getAppliedRuleApp())) { - if (!SymbolicExecutionUtil.hasLoopBodyLabel(node.getAppliedRuleApp())) { - Term modalityTerm = TermBuilder.goBelowUpdates(node.getAppliedRuleApp().posInOccurrence().subTerm()); - BlockContractValidityTermLabel bcLabel = (BlockContractValidityTermLabel) modalityTerm.getLabel(BlockContractValidityTermLabel.NAME); - result = new ExecutionTermination(settings, - node, - bcLabel != null ? MiscTools.findActualVariable(bcLabel.getExceptionVariable(), node) : exceptionVariable, - null); - startNode.addTermination((ExecutionTermination)result); - } + parentToAddTo = executionNode; } - else if (SymbolicExecutionUtil.isBranchStatement(node, node.getAppliedRuleApp(), statement, posInfo)) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionBranchStatement(settings, node); - addToBlockMap(node, (ExecutionBranchStatement)result); - } - } - else if (SymbolicExecutionUtil.isLoopStatement(node, node.getAppliedRuleApp(), statement, posInfo)) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionLoopStatement(settings, node); - addToBlockMap(node, (ExecutionLoopStatement)result); - } + // Check if loop condition is available + boolean isLoopCondition = false; + if (SymbolicExecutionUtil.hasLoopCondition(node, node.getAppliedRuleApp(), statement)) { + if (((LoopStatement) statement).getGuardExpression() + .getPositionInfo() != PositionInfo.UNDEFINED + && !SymbolicExecutionUtil.isDoWhileLoopCondition(node, statement) + && !SymbolicExecutionUtil.isForLoopCondition(node, statement)) { // do while + // and for + // loops + // exists + // only in + // the + // first + // iteration + // where + // the loop + // condition + // is not + // evaluated. + // They are + // transfered + // into + // while + // loops in + // later + // proof + // nodes. + isLoopCondition = true; + } } - else if (SymbolicExecutionUtil.isStatementNode(node, node.getAppliedRuleApp(), statement, posInfo)) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionStatement(settings, node); - } + // Check if loop condition is available after loop invariant (rewritten into if + // statement) + if (statement instanceof If + && ((If) statement).getExpression().getPositionInfo() != PositionInfo.UNDEFINED + && SymbolicExecutionUtil + .getSymbolicExecutionLabel(node.getAppliedRuleApp()) != null + && searchDirectParentBodyPreservesInvariantBranchCondition( + parentToAddTo) != null) { + isLoopCondition = true; } - } - else if (SymbolicExecutionUtil.isOperationContract(node, node.getAppliedRuleApp())) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionOperationContract(settings, node); + // Create loop condition if required + if (isLoopCondition) { + ExecutionLoopCondition condition = keyNodeLoopConditionMapping.get(node); + if (condition == null) { + condition = new ExecutionLoopCondition(settings, node); + addChild(parentToAddTo, condition); + keyNodeLoopConditionMapping.put(node, condition); + // Set call stack on new created node + condition.setCallStack(createCallStack(node)); + Pair secondPair = + SymbolicExecutionUtil.computeSecondStatement(node.getAppliedRuleApp()); + addToBlockMap(node, condition, secondPair.first, secondPair.second, statement); + } + parentToAddTo = condition; } - } - else if (SymbolicExecutionUtil.isLoopInvariant(node, node.getAppliedRuleApp())) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionLoopInvariant(settings, node); - // Initialize new call stack of the preserves loop invariant branch - initNewLoopBodyMethodCallStack(node); + } + return parentToAddTo; + } + + /** + * Searches the direct parent {@link IExecutionBranchCondition} representing the 'Body Preserves + * Invariant' branch. + * + * @param current The {@link IExecutionNode} to check its parent + * {@link IExecutionBranchCondition}s. + * @return The found {@link IExecutionBranchCondition} or {@code null} if not available. + */ + protected IExecutionBranchCondition searchDirectParentBodyPreservesInvariantBranchCondition( + IExecutionNode current) { + Iterator, List>> iter = + branchConditionsStack.iterator(); + while (current instanceof IExecutionBranchCondition) { + if (WhileInvariantRule.BODY_PRESERVES_INVARIANT_LABEL + .equals(current.getProofNode().getNodeInfo().getBranchLabel())) { + return (IExecutionBranchCondition) current; + } else { + // Search parent (current.getParent() is not yet defined) + boolean parentFound = false; + while (!parentFound && iter.hasNext()) { + Entry, List> entry = + iter.next(); + if (entry.getValue().contains(current)) { + current = entry.getKey(); + parentFound = true; + } + } + if (!parentFound) { + current = null; + } } - } - else if (SymbolicExecutionUtil.isBlockSpecificationElement(node, node.getAppliedRuleApp())) { - if (isNotInImplicitMethod(node)) { - result = new ExecutionAuxiliaryContract(settings, node); - // Initialize new call stack of the validity branch - initNewValidiityMethodCallStack(node); + } + return null; + } + + protected boolean shouldPrune(Node node) { + if (isUninterpretedPredicateUsed) { + return node.isClosed(); + } else { + return false; + } + } + + /** + * Adds the new created {@link AbstractExecutionNode} to the symbolic execution tree if + * available and returns the new parent for future detected nodes. + * + * @param node The {@link Node}. + * @param parentToAddTo The parent {@link AbstractExecutionNode}. + * @param executionNode The new child {@link AbstractExecutionNode}. + * @return The new parent {@link AbstractExecutionNode}. + */ + protected AbstractExecutionNode addNodeToTreeAndUpdateParent(Node node, + AbstractExecutionNode parentToAddTo, AbstractExecutionNode executionNode) { + // Check if a new node was created + if (executionNode != null) { + // Add new node to symbolic execution tree + addChild(parentToAddTo, executionNode); + if (keyNodeMapping.get(node) != null) { + if (multipleExecutionNodes.containsKey(node)) { + multipleExecutionNodes.get(node).add(executionNode); + } else { + LinkedList> list = + new LinkedList>(); + list.add(keyNodeMapping.get(node)); + list.add(executionNode); + multipleExecutionNodes.put(node, list); + } } - } - else if (SymbolicExecutionUtil.isCloseAfterJoin(node.getAppliedRuleApp())) { - result = new ExecutionJoin(settings, node); - } - } - else if (SymbolicExecutionUtil.isLoopBodyTermination(node, node.getAppliedRuleApp())) { - result = new ExecutionTermination(settings, node, exceptionVariable, TerminationKind.LOOP_BODY); - startNode.addTermination((ExecutionTermination)result); - } - return result; - } - - /** - * Adds the given {@link AbstractExecutionNode} add reason for a new block to the block maps. - * @param node The current {@link Node}. - * @param blockStartNode The {@link AbstractExecutionNode} to add. - */ - protected void addToBlockMap(Node node, AbstractExecutionBlockStartNode blockStartNode) { - Pair secondPair = SymbolicExecutionUtil.computeSecondStatement(node.getAppliedRuleApp()); - addToBlockMap(node, blockStartNode, secondPair.first, secondPair.second); - } - - /** - * Adds the given {@link AbstractExecutionNode} add reason for a new block to the block maps. - * @param node The current {@link Node}. - * @param blockStartNode The {@link AbstractExecutionNode} to add. - * @param secondPair The next element to end at. - * @return {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - protected void addToBlockMap(Node node, AbstractExecutionBlockStartNode blockStartNode, int stackSize, SourceElement... sourceElements) { - boolean blockPossible = checkBlockPossibility(node, stackSize, sourceElements); - if (blockPossible) { - if (sourceElements != null && sourceElements.length >= 1) { - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); - // Find most recent map - Map>>> afterBlockMaps = getAfterBlockMaps(label); - Map>> afterBlockMap = findAfterBlockMap(afterBlockMaps, node); - if (afterBlockMap == null) { - afterBlockMap = new LinkedHashMap>>(); + keyNodeMapping.put(node, executionNode); + parentToAddTo = executionNode; + // Set call stack on new created node + executionNode.setCallStack(createCallStack(node)); + } + return parentToAddTo; + } + + /** + * Updates the call stack ({@link #methodCallStack}) if the given {@link Node} in KeY's proof + * tree is a method call. + * + * @param node The current {@link Node}. + * @param statement The statement ({@link SourceElement}). + */ + protected void updateCallStack(Node node, SourceElement statement) { + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); + if (label != null && SymbolicExecutionUtil.isMethodCallNode(node, node.getAppliedRuleApp(), + statement, true)) { + // Remove outdated methods from call stack + int currentLevel = SymbolicExecutionUtil.computeStackSize(node.getAppliedRuleApp()); + Map> methodCallStack = getMethodCallStack(label); + ImmutableList stack = findMethodCallStack(methodCallStack, node); + if (stack != null) { + while (stack.size() > currentLevel) { + stack = stack.take(1); + } + } else { + stack = ImmutableSLList.nil(); } - else { - afterBlockMap = new LinkedHashMap>>(afterBlockMap); + // Add new node to call stack. + stack = stack.prepend(node); + methodCallStack.put(node, stack); + } + } + + protected ImmutableList findMethodCallStack( + Map> methodCallStack, Node node) { + ImmutableList result = null; + while (result == null && node != null) { + result = methodCallStack.get(node); + node = node.parent(); + } + return result; + } + + /** + * Creates a new execution tree model representation ({@link IExecutionNode}) if possible for + * the given {@link Node} in KeY's proof tree. + * + * @param parent The parent {@link IExecutionNode}. + * @param node The {@link Node} in the proof tree of KeY. + * @param statement The actual statement ({@link SourceElement}). + * @return The created {@link IExecutionNode} or {@code null} if the {@link Node} should be + * ignored in the symbolic execution tree. + */ + protected AbstractExecutionNode createExecutionTreeModelRepresentation( + AbstractExecutionNode parent, Node node, SourceElement statement) { + AbstractExecutionNode result = null; + // Make sure that a statement (SourceElement) is available. + if (SymbolicExecutionUtil.hasSymbolicExecutionLabel(node.getAppliedRuleApp())) { + if (statement != null + && !SymbolicExecutionUtil.isRuleAppToIgnore(node.getAppliedRuleApp())) { + // Get position information + PositionInfo posInfo = statement.getPositionInfo(); + // Determine the node representation and create it if one is available + if (SymbolicExecutionUtil.isMethodCallNode(node, node.getAppliedRuleApp(), + statement)) { + result = new ExecutionMethodCall(settings, node); + } else if (SymbolicExecutionUtil.isTerminationNode(node, + node.getAppliedRuleApp())) { + if (!SymbolicExecutionUtil.hasLoopBodyLabel(node.getAppliedRuleApp())) { + Term modalityTerm = TermBuilder.goBelowUpdates( + node.getAppliedRuleApp().posInOccurrence().subTerm()); + BlockContractValidityTermLabel bcLabel = + (BlockContractValidityTermLabel) modalityTerm + .getLabel(BlockContractValidityTermLabel.NAME); + result = new ExecutionTermination(settings, node, + bcLabel != null + ? MiscTools.findActualVariable( + bcLabel.getExceptionVariable(), node) + : exceptionVariable, + null); + startNode.addTermination((ExecutionTermination) result); + } + } else if (SymbolicExecutionUtil.isBranchStatement(node, node.getAppliedRuleApp(), + statement, posInfo)) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionBranchStatement(settings, node); + addToBlockMap(node, (ExecutionBranchStatement) result); + } + } else if (SymbolicExecutionUtil.isLoopStatement(node, node.getAppliedRuleApp(), + statement, posInfo)) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionLoopStatement(settings, node); + addToBlockMap(node, (ExecutionLoopStatement) result); + } + } else if (SymbolicExecutionUtil.isStatementNode(node, node.getAppliedRuleApp(), + statement, posInfo)) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionStatement(settings, node); + } + } + } else if (SymbolicExecutionUtil.isOperationContract(node, node.getAppliedRuleApp())) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionOperationContract(settings, node); + } + } else if (SymbolicExecutionUtil.isLoopInvariant(node, node.getAppliedRuleApp())) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionLoopInvariant(settings, node); + // Initialize new call stack of the preserves loop invariant branch + initNewLoopBodyMethodCallStack(node); + } + } else if (SymbolicExecutionUtil.isBlockSpecificationElement(node, + node.getAppliedRuleApp())) { + if (isNotInImplicitMethod(node)) { + result = new ExecutionAuxiliaryContract(settings, node); + // Initialize new call stack of the validity branch + initNewValidiityMethodCallStack(node); + } + } else if (SymbolicExecutionUtil.isCloseAfterJoin(node.getAppliedRuleApp())) { + result = new ExecutionJoin(settings, node); } - afterBlockMaps.put(node, afterBlockMap); - JavaPair secondPair = new JavaPair(stackSize, ImmutableSLList.nil().append(sourceElements)); - ImmutableList> blockStartList = afterBlockMap.get(secondPair); - if (blockStartList == null) { - blockStartList = ImmutableSLList.nil(); + } else if (SymbolicExecutionUtil.isLoopBodyTermination(node, node.getAppliedRuleApp())) { + result = new ExecutionTermination(settings, node, exceptionVariable, + TerminationKind.LOOP_BODY); + startNode.addTermination((ExecutionTermination) result); + } + return result; + } + + /** + * Adds the given {@link AbstractExecutionNode} add reason for a new block to the block maps. + * + * @param node The current {@link Node}. + * @param blockStartNode The {@link AbstractExecutionNode} to add. + */ + protected void addToBlockMap(Node node, AbstractExecutionBlockStartNode blockStartNode) { + Pair secondPair = + SymbolicExecutionUtil.computeSecondStatement(node.getAppliedRuleApp()); + addToBlockMap(node, blockStartNode, secondPair.first, secondPair.second); + } + + /** + * Adds the given {@link AbstractExecutionNode} add reason for a new block to the block maps. + * + * @param node The current {@link Node}. + * @param blockStartNode The {@link AbstractExecutionNode} to add. + * @param secondPair The next element to end at. + * @return {@code false} block is definitively not opened, {@code true} block is or might be + * opened. + */ + protected void addToBlockMap(Node node, AbstractExecutionBlockStartNode blockStartNode, + int stackSize, SourceElement... sourceElements) { + boolean blockPossible = checkBlockPossibility(node, stackSize, sourceElements); + if (blockPossible) { + if (sourceElements != null && sourceElements.length >= 1) { + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); + // Find most recent map + Map>>> afterBlockMaps = + getAfterBlockMaps(label); + Map>> afterBlockMap = + findAfterBlockMap(afterBlockMaps, node); + if (afterBlockMap == null) { + afterBlockMap = new LinkedHashMap>>(); + } else { + afterBlockMap = new LinkedHashMap>>( + afterBlockMap); + } + afterBlockMaps.put(node, afterBlockMap); + JavaPair secondPair = new JavaPair(stackSize, + ImmutableSLList.nil().append(sourceElements)); + ImmutableList> blockStartList = afterBlockMap.get(secondPair); + if (blockStartList == null) { + blockStartList = ImmutableSLList.nil(); + } + blockStartList = blockStartList.append(blockStartNode); + afterBlockMap.put(secondPair, blockStartList); } - blockStartList = blockStartList.append(blockStartNode); - afterBlockMap.put(secondPair, blockStartList); - } - } - blockStartNode.setBlockOpened(blockPossible); - } - - /** - * Checks if it possible that the current {@link Node} opens a block. - * @param node The current {@link Node}. - * @param expectedStackSize The expected stack size. - * @param expectedSourceElements The expected after block {@link SourceElement}s. - * @return {@code false} A block is definitively not possible, {@code true} a block is or might be possible. - */ - private boolean checkBlockPossibility(Node node, - int expectedStackSize, - SourceElement... expectedSourceElements) { - if (node != null && expectedSourceElements != null && expectedSourceElements.length >= 1) { - RuleApp ruleApp = null; - boolean seNodeFound = false; - // Find single symbolic execution child node - while (!seNodeFound && node != null) { - // Select new child node - if (node.childrenCount() > 1) { - int i = 0; - int openChildCount = 0; - Node nextNode = null; - while (i < node.childrenCount()) { - Node child = node.child(i); - if (!child.isClosed()) { - openChildCount++; - nextNode = child; - } - i++; - } - if (openChildCount == 1) { - node = nextNode; - } - else { - node = null; // Stop search because multiple open branches indicate that a block is required. - } + } + blockStartNode.setBlockOpened(blockPossible); + } + + /** + * Checks if it possible that the current {@link Node} opens a block. + * + * @param node The current {@link Node}. + * @param expectedStackSize The expected stack size. + * @param expectedSourceElements The expected after block {@link SourceElement}s. + * @return {@code false} A block is definitively not possible, {@code true} a block is or might + * be possible. + */ + private boolean checkBlockPossibility(Node node, int expectedStackSize, + SourceElement... expectedSourceElements) { + if (node != null && expectedSourceElements != null && expectedSourceElements.length >= 1) { + RuleApp ruleApp = null; + boolean seNodeFound = false; + // Find single symbolic execution child node + while (!seNodeFound && node != null) { + // Select new child node + if (node.childrenCount() > 1) { + int i = 0; + int openChildCount = 0; + Node nextNode = null; + while (i < node.childrenCount()) { + Node child = node.child(i); + if (!child.isClosed()) { + openChildCount++; + nextNode = child; + } + i++; + } + if (openChildCount == 1) { + node = nextNode; + } else { + node = null; // Stop search because multiple open branches indicate that a + // block is required. + } + } else if (node.childrenCount() == 1) { + node = node.child(0); + } else { + node = null; + } + // Check selected child + if (node != null) { + if (node.childrenCount() == 0) { + Goal goal = proof.getGoal(node); + ruleApp = goal.getRuleAppManager().peekNext(); + } else { + ruleApp = node.getAppliedRuleApp(); + } + seNodeFound = SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp); + } } - else if (node.childrenCount() == 1) { - node = node.child(0); + // If SE node is found check if the after block state is reached. + if (seNodeFound) { + int currentStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); + SourceElement currentActiveStatement = NodeInfo.computeActiveStatement(ruleApp); + JavaBlock currentJavaBlock = ruleApp.posInOccurrence().subTerm().javaBlock(); + MethodFrame currentInnerMostMethodFrame = + JavaTools.getInnermostMethodFrame(currentJavaBlock, proof.getServices()); + return !isAfterBlockReached(currentStackSize, currentInnerMostMethodFrame, + currentActiveStatement, expectedStackSize, ImmutableSLList + .nil().append(expectedSourceElements).iterator()); + } else { + return true; // No single SE node reached, so allow blocks } - else { - node = null; + } else { + return true; // Don't know, so allow blocks + } + } + + /** + * Searches the relevant after block {@link Map} in the given once for the given {@link Node}. + * + * @param afterBlockMaps The available after sblock {@link Map}s. + * @param node The {@link Node} for which the block {@link Map} is requested. + * @return The found after block {@link Map} or {@code null} if not available. + */ + protected Map>> findAfterBlockMap( + Map>>> afterBlockMaps, Node node) { + if (afterBlockMaps != null) { + Map>> result = null; + while (result == null && node != null) { + result = afterBlockMaps.get(node); + node = node.parent(); } - // Check selected child - if (node != null) { - if (node.childrenCount() == 0) { - Goal goal = proof.getGoal(node); - ruleApp = goal.getRuleAppManager().peekNext(); - } - else { - ruleApp = node.getAppliedRuleApp(); - } - seNodeFound = SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp); + return result; + } else { + return null; + } + } + + /** + * Returns the after block map. If not already available an empty block map is created. + * + * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. + * @return The after block map of the ID of the given {@link SymbolicExecutionTermLabel}. + */ + protected Map>>> getAfterBlockMaps( + SymbolicExecutionTermLabel label) { + assert label != null : "No symbolic execuion term label provided"; + return getAfterBlockMaps(label.getId()); + } + + /** + * Returns the after block map used for the given ID. If not already available an empty block + * map is created. + * + * @param id The ID. + * @return The after block map of the given ID. + */ + protected Map>>> getAfterBlockMaps(int id) { + synchronized (afterBlockMap) { + Integer key = Integer.valueOf(id); + Map>>> result = + afterBlockMap.get(key); + if (result == null) { + result = new LinkedHashMap>>>(); + afterBlockMap.put(key, result); } - } - // If SE node is found check if the after block state is reached. - if (seNodeFound) { - int currentStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); - SourceElement currentActiveStatement = NodeInfo.computeActiveStatement(ruleApp); - JavaBlock currentJavaBlock = ruleApp.posInOccurrence().subTerm().javaBlock(); - MethodFrame currentInnerMostMethodFrame = JavaTools.getInnermostMethodFrame(currentJavaBlock, proof.getServices()); - return !isAfterBlockReached(currentStackSize, currentInnerMostMethodFrame, currentActiveStatement, expectedStackSize, ImmutableSLList.nil().append(expectedSourceElements).iterator()); - } - else { - return true; // No single SE node reached, so allow blocks - } - } - else { - return true; // Don't know, so allow blocks - } - } - - /** - * Searches the relevant after block {@link Map} in the given once for the given {@link Node}. - * @param afterBlockMaps The available after sblock {@link Map}s. - * @param node The {@link Node} for which the block {@link Map} is requested. - * @return The found after block {@link Map} or {@code null} if not available. - */ - protected Map>> findAfterBlockMap(Map>>> afterBlockMaps, Node node) { - if (afterBlockMaps != null) { - Map>> result = null; - while (result == null && node != null) { - result = afterBlockMaps.get(node); - node = node.parent(); - } - return result; - } - else { - return null; - } - } - - /** - * Returns the after block map. If not already - * available an empty block map is created. - * @param label The {@link SymbolicExecutionTermLabel} which provides the ID. - * @return The after block map of the ID of the given {@link SymbolicExecutionTermLabel}. - */ - protected Map>>> getAfterBlockMaps(SymbolicExecutionTermLabel label) { - assert label != null : "No symbolic execuion term label provided"; - return getAfterBlockMaps(label.getId()); - } - - /** - * Returns the after block map used for the given ID. If not already - * available an empty block map is created. - * @param id The ID. - * @return The after block map of the given ID. - */ - protected Map>>> getAfterBlockMaps(int id) { - synchronized (afterBlockMap) { - Integer key = Integer.valueOf(id); - Map>>> result = afterBlockMap.get(key); - if (result == null) { - result = new LinkedHashMap>>>(); - afterBlockMap.put(key, result); - } - return result; - } - } - - /** - * Updates the after block maps when a symbolic execution tree node is detected. - * @param node The {@link Node} which is a symbolic execution tree node. - * @param ruleApp The {@link RuleApp} to consider. - * @return The now completed blocks. - */ - protected Map>> updateAfterBlockMap(Node node, RuleApp ruleApp) { - Map>> completedBlocks = new LinkedHashMap>>(); - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); - if (label != null) { - // Find most recent map - Map>>> afterBlockMaps = getAfterBlockMaps(label); - Map>> oldBlockMap = findAfterBlockMap(afterBlockMaps, node); - if (oldBlockMap != null) { - // Compute stack and active statement - int stackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); - SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); - JavaBlock javaBlock = ruleApp.posInOccurrence().subTerm().javaBlock(); - MethodFrame innerMostMethodFrame = JavaTools.getInnermostMethodFrame(javaBlock, proof.getServices()); - // Create copy with values below level - Map>> newBlockMap = new LinkedHashMap>>(); + return result; + } + } + + /** + * Updates the after block maps when a symbolic execution tree node is detected. + * + * @param node The {@link Node} which is a symbolic execution tree node. + * @param ruleApp The {@link RuleApp} to consider. + * @return The now completed blocks. + */ + protected Map>> updateAfterBlockMap(Node node, + RuleApp ruleApp) { + Map>> completedBlocks = + new LinkedHashMap>>(); + SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(ruleApp); + if (label != null) { + // Find most recent map + Map>>> afterBlockMaps = + getAfterBlockMaps(label); + Map>> oldBlockMap = + findAfterBlockMap(afterBlockMaps, node); if (oldBlockMap != null) { - for (Entry>> entry : oldBlockMap.entrySet()) { - if (!isContained(entry.getValue(), node)) { // Ensure that with stepwise execution loops are not completed by their own. - boolean done = isAfterBlockReached(stackSize, innerMostMethodFrame, activeStatement, entry.getKey()); - if (done) { - completedBlocks.put(entry.getKey(), entry.getValue()); - } - else { - newBlockMap.put(entry.getKey(), entry.getValue()); - } - } - } + // Compute stack and active statement + int stackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); + SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); + JavaBlock javaBlock = ruleApp.posInOccurrence().subTerm().javaBlock(); + MethodFrame innerMostMethodFrame = + JavaTools.getInnermostMethodFrame(javaBlock, proof.getServices()); + // Create copy with values below level + Map>> newBlockMap = + new LinkedHashMap>>(); + if (oldBlockMap != null) { + for (Entry>> entry : oldBlockMap + .entrySet()) { + if (!isContained(entry.getValue(), node)) { // Ensure that with stepwise + // execution loops are not + // completed by their own. + boolean done = isAfterBlockReached(stackSize, innerMostMethodFrame, + activeStatement, entry.getKey()); + if (done) { + completedBlocks.put(entry.getKey(), entry.getValue()); + } else { + newBlockMap.put(entry.getKey(), entry.getValue()); + } + } + } + } + // Add new block + afterBlockMaps.put(node, newBlockMap); } - // Add new block - afterBlockMaps.put(node, newBlockMap); - } - } - return completedBlocks; - } - - /** - * Checks if one of the give {@link IExecutionNode}s represents the given {@link Node}. - * @param list The {@link IExecutionNode}s to check. - * @param node The {@link Node} to check for. - * @return {@code true} is contained, {@code false} is not contained. - */ - protected boolean isContained(ImmutableList> list, Node node) { - boolean contained = false; - Iterator> iter = list.iterator(); - while (!contained && iter.hasNext()) { - IExecutionNode next = iter.next(); - if (next.getProofNode() == node) { - contained = true; - } - } - return contained; - } - - /** - * Checks if the after block condition is fulfilled. - * @param currentStackSize The current stack size. - * @param currentInnerMostMethodFrame The current inner most {@link MethodFrame}. - * @param currentActiveStatement The current active statement. - * @param expectedPair The {@link JavaPair} specifying the after block statements. - * @return {@code true} after block is reached, {@code false} after block is not reached. - */ - protected boolean isAfterBlockReached(int currentStackSize, - MethodFrame currentInnerMostMethodFrame, - SourceElement currentActiveStatement, - JavaPair expectedPair) { - return isAfterBlockReached(currentStackSize, currentInnerMostMethodFrame, currentActiveStatement, expectedPair.first, expectedPair.second.iterator()); - } - - /** - * Checks if the after block condition is fulfilled. - * @param currentStackSize The current stack size. - * @param currentInnerMostMethodFrame The current inner most {@link MethodFrame}. - * @param currentActiveStatement The current active statement. - * @param expectedStackSize The expected stack size. - * @param expectedStatementsIterator An {@link Iterator} with the expected after block statements. - * @return {@code true} after block is reached, {@code false} after block is not reached. - */ - protected boolean isAfterBlockReached(int currentStackSize, - MethodFrame currentInnerMostMethodFrame, - SourceElement currentActiveStatement, - int expectedStackSize, - Iterator expectedStatementsIterator) { - boolean done = false; - if (expectedStackSize > currentStackSize) { - done = true; - } - else { - while (!done && expectedStatementsIterator.hasNext()) { - SourceElement next = expectedStatementsIterator.next(); - if (SymbolicExecutionUtil.equalsWithPosition(next, currentActiveStatement)) { // Comparison by == is not possible since loops are recreated - done = true; + } + return completedBlocks; + } + + /** + * Checks if one of the give {@link IExecutionNode}s represents the given {@link Node}. + * + * @param list The {@link IExecutionNode}s to check. + * @param node The {@link Node} to check for. + * @return {@code true} is contained, {@code false} is not contained. + */ + protected boolean isContained(ImmutableList> list, Node node) { + boolean contained = false; + Iterator> iter = list.iterator(); + while (!contained && iter.hasNext()) { + IExecutionNode next = iter.next(); + if (next.getProofNode() == node) { + contained = true; } - else if (expectedStackSize == currentStackSize && - (currentInnerMostMethodFrame != null && currentInnerMostMethodFrame.getBody().isEmpty() || - (next != null && !SymbolicExecutionUtil.containsStatement(currentInnerMostMethodFrame, next, proof.getServices())))) { - done = true; + } + return contained; + } + + /** + * Checks if the after block condition is fulfilled. + * + * @param currentStackSize The current stack size. + * @param currentInnerMostMethodFrame The current inner most {@link MethodFrame}. + * @param currentActiveStatement The current active statement. + * @param expectedPair The {@link JavaPair} specifying the after block statements. + * @return {@code true} after block is reached, {@code false} after block is not reached. + */ + protected boolean isAfterBlockReached(int currentStackSize, + MethodFrame currentInnerMostMethodFrame, SourceElement currentActiveStatement, + JavaPair expectedPair) { + return isAfterBlockReached(currentStackSize, currentInnerMostMethodFrame, + currentActiveStatement, expectedPair.first, expectedPair.second.iterator()); + } + + /** + * Checks if the after block condition is fulfilled. + * + * @param currentStackSize The current stack size. + * @param currentInnerMostMethodFrame The current inner most {@link MethodFrame}. + * @param currentActiveStatement The current active statement. + * @param expectedStackSize The expected stack size. + * @param expectedStatementsIterator An {@link Iterator} with the expected after block + * statements. + * @return {@code true} after block is reached, {@code false} after block is not reached. + */ + protected boolean isAfterBlockReached(int currentStackSize, + MethodFrame currentInnerMostMethodFrame, SourceElement currentActiveStatement, + int expectedStackSize, Iterator expectedStatementsIterator) { + boolean done = false; + if (expectedStackSize > currentStackSize) { + done = true; + } else { + while (!done && expectedStatementsIterator.hasNext()) { + SourceElement next = expectedStatementsIterator.next(); + if (SymbolicExecutionUtil.equalsWithPosition(next, currentActiveStatement)) { // Comparison + // by + // == + // is + // not + // possible + // since + // loops + // are + // recreated + done = true; + } else if (expectedStackSize == currentStackSize + && (currentInnerMostMethodFrame != null + && currentInnerMostMethodFrame.getBody().isEmpty() + || (next != null && !SymbolicExecutionUtil.containsStatement( + currentInnerMostMethodFrame, next, proof.getServices())))) { + done = true; + } } - } - } - return done; - } - - /** - * Creates an method return node. - * @param parent The parent {@link AbstractExecutionNode}. - * @param node The {@link Node} which represents a method return. - * @param statement The currently active {@link SourceElement}. - * @param completions The {@link SymbolicExecutionCompletions} to update. - * @return The created {@link AbstractExecutionMethodReturn}. - */ - protected AbstractExecutionMethodReturn createMehtodReturn(AbstractExecutionNode parent, - Node node, - SourceElement statement, - SymbolicExecutionCompletions completions) { - AbstractExecutionMethodReturn result = null; - if (SymbolicExecutionUtil.hasSymbolicExecutionLabel(node.getAppliedRuleApp())) { - if (statement != null && !SymbolicExecutionUtil.isRuleAppToIgnore(node.getAppliedRuleApp())) { - boolean methodReturn = SymbolicExecutionUtil.isMethodReturnNode(node, node.getAppliedRuleApp()); - boolean exceptionalMethodReturn = !methodReturn && SymbolicExecutionUtil.isExceptionalMethodReturnNode(node, node.getAppliedRuleApp()); - if (methodReturn || exceptionalMethodReturn) { - // Find the Node in the proof tree of KeY for that this Node is the return - Node callNode = findMethodCallNode(node, node.getAppliedRuleApp()); - if (callNode != null) { - // Make sure that the return should not be ignored - Set methodReturnsToIgnore = getMethodReturnsToIgnore(node.getAppliedRuleApp()); - if (!methodReturnsToIgnore.contains(callNode)) { - // Find the call Node representation in SED, if not available ignore it. - IExecutionNode callSEDNode = keyNodeMapping.get(callNode); - if (callSEDNode instanceof ExecutionMethodCall) { // Could be the start node if the initial sequent already contains some method frames. - if (methodReturn) { - result = new ExecutionMethodReturn(settings, node, (ExecutionMethodCall)callSEDNode); - completions.addMethodReturn(result); - } - else { - result = new ExecutionExceptionalMethodReturn(settings, node, (ExecutionMethodCall)callSEDNode); - completions.addMethodReturn(result); + } + return done; + } + + /** + * Creates an method return node. + * + * @param parent The parent {@link AbstractExecutionNode}. + * @param node The {@link Node} which represents a method return. + * @param statement The currently active {@link SourceElement}. + * @param completions The {@link SymbolicExecutionCompletions} to update. + * @return The created {@link AbstractExecutionMethodReturn}. + */ + protected AbstractExecutionMethodReturn createMehtodReturn(AbstractExecutionNode parent, + Node node, SourceElement statement, SymbolicExecutionCompletions completions) { + AbstractExecutionMethodReturn result = null; + if (SymbolicExecutionUtil.hasSymbolicExecutionLabel(node.getAppliedRuleApp())) { + if (statement != null + && !SymbolicExecutionUtil.isRuleAppToIgnore(node.getAppliedRuleApp())) { + boolean methodReturn = + SymbolicExecutionUtil.isMethodReturnNode(node, node.getAppliedRuleApp()); + boolean exceptionalMethodReturn = !methodReturn && SymbolicExecutionUtil + .isExceptionalMethodReturnNode(node, node.getAppliedRuleApp()); + if (methodReturn || exceptionalMethodReturn) { + // Find the Node in the proof tree of KeY for that this Node is the return + Node callNode = findMethodCallNode(node, node.getAppliedRuleApp()); + if (callNode != null) { + // Make sure that the return should not be ignored + Set methodReturnsToIgnore = + getMethodReturnsToIgnore(node.getAppliedRuleApp()); + if (!methodReturnsToIgnore.contains(callNode)) { + // Find the call Node representation in SED, if not available ignore it. + IExecutionNode callSEDNode = keyNodeMapping.get(callNode); + if (callSEDNode instanceof ExecutionMethodCall) { // Could be the start + // node if the initial + // sequent already + // contains some + // method frames. + if (methodReturn) { + result = new ExecutionMethodReturn(settings, node, + (ExecutionMethodCall) callSEDNode); + completions.addMethodReturn(result); + } else { + result = new ExecutionExceptionalMethodReturn(settings, node, + (ExecutionMethodCall) callSEDNode); + completions.addMethodReturn(result); + } + } } - } - } - } - } - } - } - return result; - } - - /** - * Checks if the given {@link Node} is not in an implicit method. - * @param node The {@link Node} to check. - * @return {@code true} is not implicit, {@code false} is implicit - */ - protected boolean isNotInImplicitMethod(Node node) { - Term term = node.getAppliedRuleApp().posInOccurrence().subTerm(); - term = TermBuilder.goBelowUpdates(term); - Services services = proof.getServices(); - IExecutionContext ec = JavaTools.getInnermostExecutionContext(term.javaBlock(), services); - IProgramMethod pm = ec.getMethodContext(); - return SymbolicExecutionUtil.isNotImplicit(services, pm); - } - - /** - * This method initializes the method call stack of loop body modalities - * with the values from the original call stack. For each {@link MethodFrame} - * in the new modality is its method call {@link Node} added to the new - * method call stack. - * @param node The {@link Node} on which the loop invariant rule is applied. - */ - protected void initNewLoopBodyMethodCallStack(Node node) { - PosInOccurrence childPIO = SymbolicExecutionUtil.findModalityWithMaxSymbolicExecutionLabelId(node.child(1).sequent()); - initNewMethodCallStack(node, childPIO); - } - - /** - * This method initializes the method call stack of validity modalities - * with the values from the original call stack. For each {@link MethodFrame} - * in the new modality is its method call {@link Node} added to the new - * method call stack. - * @param node The {@link Node} on which the block contract rule is applied. - */ - protected void initNewValidiityMethodCallStack(Node node) { - PosInOccurrence childPIO = SymbolicExecutionUtil.findModalityWithMaxSymbolicExecutionLabelId(node.child(0).sequent()); - initNewMethodCallStack(node, childPIO); - } - - /** - * Initializes a new method call stack. - * @param currentNode The current {@link Node}. - * @param childPIO The {@link PosInOccurrence} where the modality has a new symbolic execution label counter. - */ - protected void initNewMethodCallStack(Node currentNode, PosInOccurrence childPIO) { - Term newModality = childPIO != null ? TermBuilder.goBelowUpdates(childPIO.subTerm()) : null; - assert newModality != null; - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(newModality); - assert label != null; - JavaBlock jb = newModality.javaBlock(); - MethodFrameCounterJavaASTVisitor newCounter = new MethodFrameCounterJavaASTVisitor(jb.program(), proof.getServices()); - int newCount = newCounter.run(); - Term oldModality = currentNode.getAppliedRuleApp().posInOccurrence().subTerm(); - oldModality = TermBuilder.goBelowUpdates(oldModality); - Map> currentMethodCallStackMap = getMethodCallStack(currentNode.getAppliedRuleApp()); - Map> newMethodCallStackMap = getMethodCallStack(label.getId()); - ImmutableList currentMethodCallStack = findMethodCallStack(currentMethodCallStackMap, currentNode); - ImmutableList newMethodCallStack = ImmutableSLList.nil(); - Set currentIgnoreSet = getMethodReturnsToIgnore(label.getId()); - assert newMethodCallStack.isEmpty() : "Method call stack is not empty."; - Iterator currentIter = currentMethodCallStack.iterator(); - int i = 0; - while (currentIter.hasNext() && i < newCount) { - Node next = currentIter.next(); - newMethodCallStack = newMethodCallStack.prepend(next); - currentIgnoreSet.add(next); - i++; - } - newMethodCallStackMap.put(currentNode, newMethodCallStack); - } - - /** - * Checks if the uninterpreted predicate is available or not. - * @return {@code true} uninterpreted predicate is available, {@code false} otherwise. - */ - public boolean isUninterpretedPredicateUsed() { - return isUninterpretedPredicateUsed; - } - - /** - * Utility class used in {@link SymbolicExecutionTreeBuilder#initNewLoopBodyMethodCallStack(Node)} - * to compute the number of available {@link MethodFrame}s. - * @author Martin Hentschel - */ - private static final class MethodFrameCounterJavaASTVisitor extends JavaASTVisitor { - /** - * The number of {@link MethodFrame}s. - */ - private int count = 0; - - /** - * Constructor. - * @param root The {@link ProgramElement} to count the contained {@link MethodFrame}s. - * @param services The {@link Services} to use. - */ - public MethodFrameCounterJavaASTVisitor(ProgramElement root, Services services) { - super(root, services); - } - - /** - * {@inheritDoc} - */ - @Override - protected void doDefaultAction(SourceElement node) { - } - - /** - * {@inheritDoc} - */ - @Override - public void performActionOnMethodFrame(MethodFrame x) { - count++; - } - - /** - * Performs the counting of {@link MethodFrame}s. - * @return The number of found {@link MethodFrame}s. - */ - public int run() { - walk(root()); - return count; - } - } - - /** - * Computes the method call stack of the given {@link Node}. - * @param node The {@link Node}. - * @return The computed method call stack. - */ - protected IExecutionNode[] createCallStack(Node node) { - // Compute number of call stack size - int size = SymbolicExecutionUtil.computeStackSize(node.getAppliedRuleApp()); - if (size >= 1) { - // Add call stack entries - List> callStack = new LinkedList>(); - Map> methodCallStack = getMethodCallStack(node.getAppliedRuleApp()); - ImmutableList stack = findMethodCallStack(methodCallStack, node); - stack = stack.take(stack.size() - size); - Iterator stackIter = stack.iterator(); - for (int i = 0; i < size; i++) { - Node stackEntry = stackIter.next(); - if (stackEntry != proof.root()) { // Ignore call stack entries provided by the initial sequent - IExecutionNode executionNode = getExecutionNode(stackEntry); - if (executionNode != null) { // It might be null in case of API methods. - callStack.add(executionNode); - } - } - } - return callStack.toArray(new IExecutionNode[callStack.size()]); - } - else { - return new IExecutionNode[0]; - } - } - - /** - * Finds the {@link Node} in the proof tree of KeY which has called the - * method that is now executed or returned in the {@link Node}. - * @param currentNode The {@link Node} for that the method call {@link Node} is needed. - * @return The found call {@link Node} or {@code null} if no one was found. - */ - protected Node findMethodCallNode(Node currentNode, RuleApp ruleApp) { - // Compute the stack frame size before the method is called - int returnStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); - // Return the method from the call stack - if (returnStackSize >= 0) { - Map> methodCallStack = getMethodCallStack(ruleApp); - ImmutableList stack = findMethodCallStack(methodCallStack, currentNode); - return stack.take(stack.size() - returnStackSize).head(); - } - else { - return null; - } - } - - /** - * Checks if the given {@link Node} handles something in an implicit method. - * @param node The {@link Node} to check. - * @return {@code true} is in implicit method, {@code false} is not in implicit method. - */ - protected boolean isInImplicitMethod(Node node) { - return SymbolicExecutionUtil.isInImplicitMethod(node, node.getAppliedRuleApp()); - } - - /** - * Checks if the given {@link Node} has a branch condition. - * @param node The {@link Node} to check. - * @return {@code true} has branch condition, {@code false} has no branch condition. - */ - protected boolean hasBranchCondition(Node node) { - if (node.childrenCount() >= 2) { // Check if it is a possible branch statement, otherwise there is no need for complex computation to filter out not relevant branches - int openChildrenCount = 0; - Iterator childIter = node.childrenIterator(); - while (childIter.hasNext()) { - Node child = childIter.next(); - // Make sure that the branch is not closed - if (!shouldPrune(child)) { - // Check if the current method on stack is not an implicit method - Node previousSymbolicExecutionNode = searchPreviousSymbolicExecutionNode(child); - if (!isInImplicitMethod(previousSymbolicExecutionNode)) { - openChildrenCount ++; - } + } + } } - } - return openChildrenCount >= 2; - } - else { - return false; - } - } - - /** - * Searches the first node in the parent hierarchy (including the given node) - * which executes a statement. - * @param node The {@link Node} to start search in. - * @return The found {@link Node} with the symbolic statement or {@code null} if no one was found. - */ - protected Node searchPreviousSymbolicExecutionNode(Node node) { - while (node != null && node.getNodeInfo().getActiveStatement() == null) { - node = node.parent(); - } - return node; - } - - /** - * Adds the child to the parent. - * @param parent The parent to add to. - * @param child The child to add. - */ - protected void addChild(AbstractExecutionNode parent, AbstractExecutionNode child) { - child.setParent(parent); - parent.addChild(child); - } - - /** - * Returns the best matching {@link IExecutionNode} for the given proof {@link Node} - * in the parent hierarchy. - * @param proofNode The proof {@link Node}. - * @return The best matching {@link IExecutionNode} or {@code null} if not available. - */ - public IExecutionNode getBestExecutionNode(Node proofNode) { - IExecutionNode node = getExecutionNode(proofNode); - while (node == null && proofNode != null) { - proofNode = proofNode.parent(); - node = getExecutionNode(proofNode); - } - return node; - } - - /** - *

- * Searches the {@link IExecutionNode} which represents the given {@link Node} of KeY's proof tree. - *

- * In case that the {@link Node} is represented by multiple {@link AbstractExecutionNode}s, - * e.g. a return statement and a method return, the last node is returned. - *

- * @param proofNode The {@link Node} in KeY's proof tree. - * @return The {@link IExecutionNode} representation or {@code null} if no one is available. - */ - public IExecutionNode getExecutionNode(Node proofNode) { - IExecutionNode result = keyNodeMapping.get(proofNode); - if (result == null) { - result = keyNodeBranchConditionMapping.get(proofNode); - } - if (result == null) { - result = keyNodeLoopConditionMapping.get(proofNode); - } - return result; - } - - /** - * Returns the minimal required PO {@link Properties} to support - * symbolic execution tree extraction in a {@link SymbolicExecutionJavaProfile}. - * @return The minimal required PO {@link Properties}. - */ - public static Properties createPoPropertiesToForce() { - Properties poPropertiesToForce = new Properties(); - poPropertiesToForce.setProperty(IPersistablePO.PROPERTY_ADD_SYMBOLIC_EXECUTION_LABEL, true + ""); - return poPropertiesToForce; - } - - /** - * Utility class to group a call stack size with an {@link ImmutableList} of {@link SourceElement} with the elements of interest. - * @author Martin Hentschel - */ - protected static class JavaPair extends Pair> { - /** - * Constructor. - * @param stackSize The call stack size. - * @param elementsOfInterest The {@link SourceElement}s of interest. - */ - public JavaPair(Integer stackSize, ImmutableList elementsOfInterest) { - super(stackSize, elementsOfInterest); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object o) { - if (super.equals(o)) { - if (o instanceof JavaPair) { - JavaPair other = (JavaPair) o; - if (second.size() == other.second.size()) { - Iterator iter = second.iterator(); - Iterator otherIter = other.second.iterator(); - boolean equals = true; - while (equals && iter.hasNext()) { - SourceElement next = iter.next(); - SourceElement otherNext = otherIter.next(); - if (!SymbolicExecutionUtil.equalsWithPosition(next, otherNext)) { // Comparison by == is not possible since loops are recreated - equals = false; - } - } - assert !otherIter.hasNext(); - return equals; - } - else { - return false; - } + } + return result; + } + + /** + * Checks if the given {@link Node} is not in an implicit method. + * + * @param node The {@link Node} to check. + * @return {@code true} is not implicit, {@code false} is implicit + */ + protected boolean isNotInImplicitMethod(Node node) { + Term term = node.getAppliedRuleApp().posInOccurrence().subTerm(); + term = TermBuilder.goBelowUpdates(term); + Services services = proof.getServices(); + IExecutionContext ec = JavaTools.getInnermostExecutionContext(term.javaBlock(), services); + IProgramMethod pm = ec.getMethodContext(); + return SymbolicExecutionUtil.isNotImplicit(services, pm); + } + + /** + * This method initializes the method call stack of loop body modalities with the values from + * the original call stack. For each {@link MethodFrame} in the new modality is its method call + * {@link Node} added to the new method call stack. + * + * @param node The {@link Node} on which the loop invariant rule is applied. + */ + protected void initNewLoopBodyMethodCallStack(Node node) { + PosInOccurrence childPIO = SymbolicExecutionUtil + .findModalityWithMaxSymbolicExecutionLabelId(node.child(1).sequent()); + initNewMethodCallStack(node, childPIO); + } + + /** + * This method initializes the method call stack of validity modalities with the values from the + * original call stack. For each {@link MethodFrame} in the new modality is its method call + * {@link Node} added to the new method call stack. + * + * @param node The {@link Node} on which the block contract rule is applied. + */ + protected void initNewValidiityMethodCallStack(Node node) { + PosInOccurrence childPIO = SymbolicExecutionUtil + .findModalityWithMaxSymbolicExecutionLabelId(node.child(0).sequent()); + initNewMethodCallStack(node, childPIO); + } + + /** + * Initializes a new method call stack. + * + * @param currentNode The current {@link Node}. + * @param childPIO The {@link PosInOccurrence} where the modality has a new symbolic execution + * label counter. + */ + protected void initNewMethodCallStack(Node currentNode, PosInOccurrence childPIO) { + Term newModality = childPIO != null ? TermBuilder.goBelowUpdates(childPIO.subTerm()) : null; + assert newModality != null; + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(newModality); + assert label != null; + JavaBlock jb = newModality.javaBlock(); + MethodFrameCounterJavaASTVisitor newCounter = + new MethodFrameCounterJavaASTVisitor(jb.program(), proof.getServices()); + int newCount = newCounter.run(); + Term oldModality = currentNode.getAppliedRuleApp().posInOccurrence().subTerm(); + oldModality = TermBuilder.goBelowUpdates(oldModality); + Map> currentMethodCallStackMap = + getMethodCallStack(currentNode.getAppliedRuleApp()); + Map> newMethodCallStackMap = getMethodCallStack(label.getId()); + ImmutableList currentMethodCallStack = + findMethodCallStack(currentMethodCallStackMap, currentNode); + ImmutableList newMethodCallStack = ImmutableSLList.nil(); + Set currentIgnoreSet = getMethodReturnsToIgnore(label.getId()); + assert newMethodCallStack.isEmpty() : "Method call stack is not empty."; + Iterator currentIter = currentMethodCallStack.iterator(); + int i = 0; + while (currentIter.hasNext() && i < newCount) { + Node next = currentIter.next(); + newMethodCallStack = newMethodCallStack.prepend(next); + currentIgnoreSet.add(next); + i++; + } + newMethodCallStackMap.put(currentNode, newMethodCallStack); + } + + /** + * Checks if the uninterpreted predicate is available or not. + * + * @return {@code true} uninterpreted predicate is available, {@code false} otherwise. + */ + public boolean isUninterpretedPredicateUsed() { + return isUninterpretedPredicateUsed; + } + + /** + * Utility class used in + * {@link SymbolicExecutionTreeBuilder#initNewLoopBodyMethodCallStack(Node)} to compute the + * number of available {@link MethodFrame}s. + * + * @author Martin Hentschel + */ + private static final class MethodFrameCounterJavaASTVisitor extends JavaASTVisitor { + /** + * The number of {@link MethodFrame}s. + */ + private int count = 0; + + /** + * Constructor. + * + * @param root The {@link ProgramElement} to count the contained {@link MethodFrame}s. + * @param services The {@link Services} to use. + */ + public MethodFrameCounterJavaASTVisitor(ProgramElement root, Services services) { + super(root, services); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doDefaultAction(SourceElement node) {} + + /** + * {@inheritDoc} + */ + @Override + public void performActionOnMethodFrame(MethodFrame x) { + count++; + } + + /** + * Performs the counting of {@link MethodFrame}s. + * + * @return The number of found {@link MethodFrame}s. + */ + public int run() { + walk(root()); + return count; + } + } + + /** + * Computes the method call stack of the given {@link Node}. + * + * @param node The {@link Node}. + * @return The computed method call stack. + */ + protected IExecutionNode[] createCallStack(Node node) { + // Compute number of call stack size + int size = SymbolicExecutionUtil.computeStackSize(node.getAppliedRuleApp()); + if (size >= 1) { + // Add call stack entries + List> callStack = new LinkedList>(); + Map> methodCallStack = + getMethodCallStack(node.getAppliedRuleApp()); + ImmutableList stack = findMethodCallStack(methodCallStack, node); + stack = stack.take(stack.size() - size); + Iterator stackIter = stack.iterator(); + for (int i = 0; i < size; i++) { + Node stackEntry = stackIter.next(); + if (stackEntry != proof.root()) { // Ignore call stack entries provided by the + // initial sequent + IExecutionNode executionNode = getExecutionNode(stackEntry); + if (executionNode != null) { // It might be null in case of API methods. + callStack.add(executionNode); + } + } } - else { - return false; + return callStack.toArray(new IExecutionNode[callStack.size()]); + } else { + return new IExecutionNode[0]; + } + } + + /** + * Finds the {@link Node} in the proof tree of KeY which has called the method that is now + * executed or returned in the {@link Node}. + * + * @param currentNode The {@link Node} for that the method call {@link Node} is needed. + * @return The found call {@link Node} or {@code null} if no one was found. + */ + protected Node findMethodCallNode(Node currentNode, RuleApp ruleApp) { + // Compute the stack frame size before the method is called + int returnStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); + // Return the method from the call stack + if (returnStackSize >= 0) { + Map> methodCallStack = getMethodCallStack(ruleApp); + ImmutableList stack = findMethodCallStack(methodCallStack, currentNode); + return stack.take(stack.size() - returnStackSize).head(); + } else { + return null; + } + } + + /** + * Checks if the given {@link Node} handles something in an implicit method. + * + * @param node The {@link Node} to check. + * @return {@code true} is in implicit method, {@code false} is not in implicit method. + */ + protected boolean isInImplicitMethod(Node node) { + return SymbolicExecutionUtil.isInImplicitMethod(node, node.getAppliedRuleApp()); + } + + /** + * Checks if the given {@link Node} has a branch condition. + * + * @param node The {@link Node} to check. + * @return {@code true} has branch condition, {@code false} has no branch condition. + */ + protected boolean hasBranchCondition(Node node) { + if (node.childrenCount() >= 2) { // Check if it is a possible branch statement, otherwise + // there is no need for complex computation to filter out + // not relevant branches + int openChildrenCount = 0; + Iterator childIter = node.childrenIterator(); + while (childIter.hasNext()) { + Node child = childIter.next(); + // Make sure that the branch is not closed + if (!shouldPrune(child)) { + // Check if the current method on stack is not an implicit method + Node previousSymbolicExecutionNode = searchPreviousSymbolicExecutionNode(child); + if (!isInImplicitMethod(previousSymbolicExecutionNode)) { + openChildrenCount++; + } + } } - } - else { + return openChildrenCount >= 2; + } else { return false; - } - } - } -} \ No newline at end of file + } + } + + /** + * Searches the first node in the parent hierarchy (including the given node) which executes a + * statement. + * + * @param node The {@link Node} to start search in. + * @return The found {@link Node} with the symbolic statement or {@code null} if no one was + * found. + */ + protected Node searchPreviousSymbolicExecutionNode(Node node) { + while (node != null && node.getNodeInfo().getActiveStatement() == null) { + node = node.parent(); + } + return node; + } + + /** + * Adds the child to the parent. + * + * @param parent The parent to add to. + * @param child The child to add. + */ + protected void addChild(AbstractExecutionNode parent, AbstractExecutionNode child) { + child.setParent(parent); + parent.addChild(child); + } + + /** + * Returns the best matching {@link IExecutionNode} for the given proof {@link Node} in the + * parent hierarchy. + * + * @param proofNode The proof {@link Node}. + * @return The best matching {@link IExecutionNode} or {@code null} if not available. + */ + public IExecutionNode getBestExecutionNode(Node proofNode) { + IExecutionNode node = getExecutionNode(proofNode); + while (node == null && proofNode != null) { + proofNode = proofNode.parent(); + node = getExecutionNode(proofNode); + } + return node; + } + + /** + *

+ * Searches the {@link IExecutionNode} which represents the given {@link Node} of KeY's proof + * tree. + *

+ * In case that the {@link Node} is represented by multiple {@link AbstractExecutionNode}s, e.g. + * a return statement and a method return, the last node is returned. + *

+ * + * @param proofNode The {@link Node} in KeY's proof tree. + * @return The {@link IExecutionNode} representation or {@code null} if no one is available. + */ + public IExecutionNode getExecutionNode(Node proofNode) { + IExecutionNode result = keyNodeMapping.get(proofNode); + if (result == null) { + result = keyNodeBranchConditionMapping.get(proofNode); + } + if (result == null) { + result = keyNodeLoopConditionMapping.get(proofNode); + } + return result; + } + + /** + * Returns the minimal required PO {@link Properties} to support symbolic execution tree + * extraction in a {@link SymbolicExecutionJavaProfile}. + * + * @return The minimal required PO {@link Properties}. + */ + public static Properties createPoPropertiesToForce() { + Properties poPropertiesToForce = new Properties(); + poPropertiesToForce.setProperty(IPersistablePO.PROPERTY_ADD_SYMBOLIC_EXECUTION_LABEL, + true + ""); + return poPropertiesToForce; + } + + /** + * Utility class to group a call stack size with an {@link ImmutableList} of + * {@link SourceElement} with the elements of interest. + * + * @author Martin Hentschel + */ + protected static class JavaPair extends Pair> { + /** + * Constructor. + * + * @param stackSize The call stack size. + * @param elementsOfInterest The {@link SourceElement}s of interest. + */ + public JavaPair(Integer stackSize, ImmutableList elementsOfInterest) { + super(stackSize, elementsOfInterest); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object o) { + if (super.equals(o)) { + if (o instanceof JavaPair) { + JavaPair other = (JavaPair) o; + if (second.size() == other.second.size()) { + Iterator iter = second.iterator(); + Iterator otherIter = other.second.iterator(); + boolean equals = true; + while (equals && iter.hasNext()) { + SourceElement next = iter.next(); + SourceElement otherNext = otherIter.next(); + if (!SymbolicExecutionUtil.equalsWithPosition(next, otherNext)) { // Comparison + // by + // == + // is + // not + // possible + // since + // loops + // are + // recreated + equals = false; + } + } + assert !otherIter.hasNext(); + return equals; + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutExtractor.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutExtractor.java index 0de02089d64..3dece949242 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutExtractor.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.ArrayList; @@ -58,18 +61,18 @@ /** *

- * Instances of this class can be used to compute memory layouts - * (objects with values and associations to other objects on the heap together - * with objects and associations to objects on the current state of the stack) - * which a given {@link Node} of KeY's proof tree can have based on - * equivalence classes (aliasing) of objects. - * Such memory layouts are named current memory layouts. It is also possible - * to compute how the heap and stack was when the proof was started. Such - * memory layouts are named initial memory layouts. + * Instances of this class can be used to compute memory layouts (objects with values and + * associations to other objects on the heap together with objects and associations to objects on + * the current state of the stack) which a given {@link Node} of KeY's proof tree can have based on + * equivalence classes (aliasing) of objects. Such memory layouts are named current memory + * layouts. It is also possible to compute how the heap and stack was when the proof was + * started. Such memory layouts are named initial memory layouts. *

*

* Example program: - *


+ *
+ * 
+ * 
  * public class Example {
  *    private int value;
  *
@@ -81,16 +84,19 @@
  *       return e.value + e.next.value; // Current node in KeY's proof tree
  *    }
  * }
- * 
- * If the symbolic execution stops at the return statement, - * two memory layouts are possible. In the first case refers - * {@code e} and {@code e.next} to different objects (result is {@code 3}). - * In the second case refers both to the same object (result is {@code 4}). - * That both objects can't be {@code null} is ensured by the path condition from root to the current node in KeY's proof tree. + *
+ *
+ * + * If the symbolic execution stops at the return statement, two memory layouts are possible. In the + * first case refers {@code e} and {@code e.next} to different objects (result is {@code 3}). In the + * second case refers both to the same object (result is {@code 4}). That both objects can't be + * {@code null} is ensured by the path condition from root to the current node in KeY's proof tree. *

*

* The following code snippet shows how to use this class: - *


+ *
+ * 
+ * 
  * SymbolicLayoutExtractor e = new SymbolicLayoutExtractor(node);
  * e.analyse();
  * for (int i = 0; i < e.getLayoutsCount(); i++) {
@@ -98,794 +104,914 @@
  *    ISymbolicLayout initial = e.getInitialLayout(i);
  *    ISymbolicLayout current = e.getCurrentLayout(i);
  * }
- * 
+ *
+ *
*

*

* Rough description of the implemented algorithm: *

    - *
  1. - * Compute possible equivalence classes which leads to different memory layouts via {@link #analyse()}. - *
      - *
    1. - * Compute path condition from root to the node for which memory layouts should be build. - *
    2. - *
    3. - * Compute locations (values/associations of objects and state) to show later in initial and current memory layouts. - * Initial locations are extracted from path condition and conditions of node's sequent. - * Current locations are all initial locations plus locations defined in updates of node's sequent. - * The location of the exc variable and backup of initial method arguments and the heap of the initial proof obligation are ignored. - * Objects of updates created during symbolic execution and objects of the right site of updates are also collected. - *
    4. - *
    5. - * Compute objects which should be checked for equality (aliasing). The Set consists of objects from path condition, - * objects on the right side of updates, objects in conditions of node's antecedent and null. - *
    6. - *
    7. - * Create a site proof which starts in a modified version of the root node. - * It contains the given path condition as additional antecedent and the modality with he java code is removed. - * Cut rules are applied to this sequent for each possible combination of two different objects. - * Each goal represents a memory layout and the applied cuts in each goal represents the equality classes. - *
    8. - *
    9. - * Create a predicate which is used to compute the objects, values and associations of an initial/a current memory layout. - * Objects are represented as expressions like {@code e} or {@code e.next}. The problem is that in a current memory layout the - * object structure might have changed and {@code e.next} is a different object compared to the initial memory layout. - * To solve this issue is an additional update is used which stores each object in a temporary program variable, e.g. - * {@code pre0 = e}, {@code pre1 = e.next}. This makes sure that the objects are the same in initial and current memory layouts. - *
    10. - *
    - *
  2. - *
  3. - * Compute a concrete initial or current memory layout when they are requested the first time via {@link #lazyComputeLayout(Node, ImmutableSet, Term, Set, ImmutableList, Term, String)}. - *
      - *
    1. - * Start side proof based on node's sequent for a current memory layout or root's sequent for an initial memory layout. - * The sequent is modified by adding the pre updates and on initial memory layouts also the path condition. - * The equivalence classes are added and the modality is replaced with the predicate to compute objects, values and associations. - *
    2. - *
    3. - * Extract values from the predicate. - *
    4. - *
    5. - * Create new {@link ISymbolicLayout} and fill it with objects, values and associations from the extracted values of the side proof. - *
    6. - *
    - *
  4. + *
  5. Compute possible equivalence classes which leads to different memory layouts via + * {@link #analyse()}. + *
      + *
    1. Compute path condition from root to the node for which memory layouts should be build.
    2. + *
    3. Compute locations (values/associations of objects and state) to show later in initial and + * current memory layouts. Initial locations are extracted from path condition and conditions of + * node's sequent. Current locations are all initial locations plus locations defined in updates of + * node's sequent. The location of the exc variable and backup of initial method arguments and the + * heap of the initial proof obligation are ignored. Objects of updates created during symbolic + * execution and objects of the right site of updates are also collected.
    4. + *
    5. Compute objects which should be checked for equality (aliasing). The Set consists of objects + * from path condition, objects on the right side of updates, objects in conditions of node's + * antecedent and null.
    6. + *
    7. Create a site proof which starts in a modified version of the root node. It contains the + * given path condition as additional antecedent and the modality with he java code is removed. Cut + * rules are applied to this sequent for each possible combination of two different objects. Each + * goal represents a memory layout and the applied cuts in each goal represents the equality + * classes.
    8. + *
    9. Create a predicate which is used to compute the objects, values and associations of an + * initial/a current memory layout. Objects are represented as expressions like {@code e} or + * {@code e.next}. The problem is that in a current memory layout the object structure might have + * changed and {@code e.next} is a different object compared to the initial memory layout. To solve + * this issue is an additional update is used which stores each object in a temporary program + * variable, e.g. {@code pre0 = e}, {@code pre1 = e.next}. This makes sure that the objects are the + * same in initial and current memory layouts.
    10. + *
    + *
  6. + *
  7. Compute a concrete initial or current memory layout when they are requested the first time + * via {@link #lazyComputeLayout(Node, ImmutableSet, Term, Set, ImmutableList, Term, String)}. + *
      + *
    1. Start side proof based on node's sequent for a current memory layout or root's sequent for an + * initial memory layout. The sequent is modified by adding the pre updates and on initial memory + * layouts also the path condition. The equivalence classes are added and the modality is replaced + * with the predicate to compute objects, values and associations.
    2. + *
    3. Extract values from the predicate.
    4. + *
    5. Create new {@link ISymbolicLayout} and fill it with objects, values and associations from the + * extracted values of the side proof.
    6. + *
    + *
  8. *
*

+ * * @author Martin Hentschel * @see ISymbolicLayout * @see ExecutionNodeSymbolicLayoutExtractor */ public class SymbolicLayoutExtractor extends AbstractUpdateExtractor { - /** - * The used {@link IModelSettings}. - */ - private final IModelSettings settings; - - /** - * Contains the applied cuts of each possible memory layout. - * An applied cut is represented as {@link Term} of the from - * {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. - */ - private List> appliedCutsPerLayout; - - /** - * Contains the current memory layouts accessible via {@link #getCurrentLayout(int)}. - */ - private Map currentLayouts; - - /** - * The {@link ExtractLocationParameter} instances used to compute a current memory layout. - */ - private Set currentLocations; - - /** - * Contains the initial memory layouts accessible via {@link #getInitialLayout(int)}. - */ - private Map initialLayouts; - - /** - * The {@link ExtractLocationParameter} instances used to compute an initial memory layout. - */ - private Set initialLocations; - - /** - * Contains the equivalent classes accessible via {@link #getEquivalenceClasses(int)}. - */ - private Map> layoutsEquivalentClasses; - - /** - * Contains objects which should be ignored in the state because they - * are created during symbolic execution or part of the proof obligation. - */ - private Set objectsToIgnore; - - /** - * The updates to consider. - */ - private ImmutableList updates; - - /** - * Constructor. - * @param node The {@link Node} of KeY's proof tree to compute memory layouts for. - * @param modalityPio The {@link PosInOccurrence} of the modality or its updates. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public SymbolicLayoutExtractor(Node node, - PosInOccurrence modalityPio, - boolean useUnicode, - boolean usePrettyPrinting, - boolean simplifyConditions) { - super(node, modalityPio); - this.settings = new ModelSettings(useUnicode, usePrettyPrinting, simplifyConditions); - } - - /** - *

- * Computes the possible memory layouts. - *

- *

- * This is the prerequisite to access equivalence classes, initial - * and current states. - *

- * @throws ProofInputException Occurred Exception. - */ - public void analyse() throws ProofInputException { - synchronized (this) { - if (!isAnalysed()) { - // Get path condition - Term pathCondition = SymbolicExecutionUtil.computePathCondition(node, - true, // Path condition needs always to be simplified, because otherwise additinal symbolic values might be introduced. - false); - pathCondition = removeImplicitSubTermsFromPathCondition(pathCondition); - // Compute all locations used in path conditions and updates. The values of the locations will be later computed in the state computation (and finally shown in a memory layout). - Set temporaryCurrentLocations = new LinkedHashSet(); - objectsToIgnore = computeInitialObjectsToIgnore(false, false); // Contains all objects which should be ignored, like exc of the proof obligation. - Set updateCreatedObjects = new LinkedHashSet(); // Contains all objects which are created during symbolic execution - Set updateValueObjects = new LinkedHashSet(); // Contains all objects which are the value of an update - collectLocationsFromUpdates(node.sequent(), temporaryCurrentLocations, updateCreatedObjects, updateValueObjects, objectsToIgnore); - objectsToIgnore.addAll(updateCreatedObjects); - initialLocations = extractLocationsFromTerm(pathCondition, objectsToIgnore); - initialLocations.addAll(extractLocationsFromSequent(node.sequent(), objectsToIgnore)); - currentLocations = new LinkedHashSet(initialLocations); - currentLocations.addAll(temporaryCurrentLocations); - // Compute objects for equivalence check. - Set symbolicObjectsResultingInCurrentState = new LinkedHashSet(); - symbolicObjectsResultingInCurrentState.addAll(filterOutObjectsToIgnore(updateValueObjects, objectsToIgnore)); - symbolicObjectsResultingInCurrentState.addAll(collectObjectsFromSequent(node.sequent(), objectsToIgnore)); - symbolicObjectsResultingInCurrentState = sortTerms(symbolicObjectsResultingInCurrentState); // Sort terms alphabetically. This guarantees that in equivalence classes the representative term is for instance self.next and not self.next.next. - symbolicObjectsResultingInCurrentState.add(getServices().getTermBuilder().NULL()); // Add null because it can happen that a object is null and this option must be included in equivalence class computation - // Find updates - updates = extractInitialUpdates(); - // Compute a Sequent with the initial conditions of the proof without modality - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent initialConditionsSequent = createSequentForEquivalenceClassComputation(); - ApplyStrategyInfo info = null; - try { - // Instantiate proof in which equivalent classes of symbolic objects are computed. - ProofStarter equivalentClassesProofStarter = SymbolicExecutionSideProofUtil.createSideProof(sideProofEnv, initialConditionsSequent, null); - // Apply cut rules to compute equivalent classes - applyCutRules(equivalentClassesProofStarter, symbolicObjectsResultingInCurrentState, updates); - // Finish proof automatically - info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), - equivalentClassesProofStarter, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_NORMAL); - // Compute the available instance memory layout via the opened goals of the equivalent proof. - appliedCutsPerLayout = extractAppliedCutsFromGoals(equivalentClassesProofStarter.getProof()); - // Create memory layout maps which are filled lazily - initialLayouts = new LinkedHashMap(appliedCutsPerLayout.size()); - currentLayouts = new LinkedHashMap(appliedCutsPerLayout.size()); - layoutsEquivalentClasses = new LinkedHashMap>(); + /** + * The used {@link IModelSettings}. + */ + private final IModelSettings settings; + + /** + * Contains the applied cuts of each possible memory layout. An applied cut is represented as + * {@link Term} of the from {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. + */ + private List> appliedCutsPerLayout; + + /** + * Contains the current memory layouts accessible via {@link #getCurrentLayout(int)}. + */ + private Map currentLayouts; + + /** + * The {@link ExtractLocationParameter} instances used to compute a current memory layout. + */ + private Set currentLocations; + + /** + * Contains the initial memory layouts accessible via {@link #getInitialLayout(int)}. + */ + private Map initialLayouts; + + /** + * The {@link ExtractLocationParameter} instances used to compute an initial memory layout. + */ + private Set initialLocations; + + /** + * Contains the equivalent classes accessible via {@link #getEquivalenceClasses(int)}. + */ + private Map> layoutsEquivalentClasses; + + /** + * Contains objects which should be ignored in the state because they are created during + * symbolic execution or part of the proof obligation. + */ + private Set objectsToIgnore; + + /** + * The updates to consider. + */ + private ImmutableList updates; + + /** + * Constructor. + * + * @param node The {@link Node} of KeY's proof tree to compute memory layouts for. + * @param modalityPio The {@link PosInOccurrence} of the modality or its updates. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + */ + public SymbolicLayoutExtractor(Node node, PosInOccurrence modalityPio, boolean useUnicode, + boolean usePrettyPrinting, boolean simplifyConditions) { + super(node, modalityPio); + this.settings = new ModelSettings(useUnicode, usePrettyPrinting, simplifyConditions); + } + + /** + *

+ * Computes the possible memory layouts. + *

+ *

+ * This is the prerequisite to access equivalence classes, initial and current states. + *

+ * + * @throws ProofInputException Occurred Exception. + */ + public void analyse() throws ProofInputException { + synchronized (this) { + if (!isAnalysed()) { + // Get path condition + Term pathCondition = SymbolicExecutionUtil.computePathCondition(node, true, // Path + // condition + // needs + // always + // to be + // simplified, + // because + // otherwise + // additinal + // symbolic + // values + // might + // be + // introduced. + false); + pathCondition = removeImplicitSubTermsFromPathCondition(pathCondition); + // Compute all locations used in path conditions and updates. The values of the + // locations will be later computed in the state computation (and finally shown in a + // memory layout). + Set temporaryCurrentLocations = + new LinkedHashSet(); + objectsToIgnore = computeInitialObjectsToIgnore(false, false); // Contains all + // objects which + // should be ignored, + // like exc of the + // proof obligation. + Set updateCreatedObjects = new LinkedHashSet(); // Contains all objects + // which are created + // during symbolic + // execution + Set updateValueObjects = new LinkedHashSet(); // Contains all objects + // which are the value of + // an update + collectLocationsFromUpdates(node.sequent(), temporaryCurrentLocations, + updateCreatedObjects, updateValueObjects, objectsToIgnore); + objectsToIgnore.addAll(updateCreatedObjects); + initialLocations = extractLocationsFromTerm(pathCondition, objectsToIgnore); + initialLocations + .addAll(extractLocationsFromSequent(node.sequent(), objectsToIgnore)); + currentLocations = new LinkedHashSet(initialLocations); + currentLocations.addAll(temporaryCurrentLocations); + // Compute objects for equivalence check. + Set symbolicObjectsResultingInCurrentState = new LinkedHashSet(); + symbolicObjectsResultingInCurrentState + .addAll(filterOutObjectsToIgnore(updateValueObjects, objectsToIgnore)); + symbolicObjectsResultingInCurrentState + .addAll(collectObjectsFromSequent(node.sequent(), objectsToIgnore)); + symbolicObjectsResultingInCurrentState = + sortTerms(symbolicObjectsResultingInCurrentState); // Sort terms + // alphabetically. This + // guarantees that in + // equivalence classes + // the representative + // term is for instance + // self.next and not + // self.next.next. + symbolicObjectsResultingInCurrentState.add(getServices().getTermBuilder().NULL()); // Add + // null + // because + // it + // can + // happen + // that + // a + // object + // is + // null + // and + // this + // option + // must + // be + // included + // in + // equivalence + // class + // computation + // Find updates + updates = extractInitialUpdates(); + // Compute a Sequent with the initial conditions of the proof without modality + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it has + // an + // internal + // state + // and the + // default + // instance + // can't + // be used + // parallel. + Sequent initialConditionsSequent = createSequentForEquivalenceClassComputation(); + ApplyStrategyInfo info = null; + try { + // Instantiate proof in which equivalent classes of symbolic objects are + // computed. + ProofStarter equivalentClassesProofStarter = SymbolicExecutionSideProofUtil + .createSideProof(sideProofEnv, initialConditionsSequent, null); + // Apply cut rules to compute equivalent classes + applyCutRules(equivalentClassesProofStarter, + symbolicObjectsResultingInCurrentState, updates); + // Finish proof automatically + info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), + equivalentClassesProofStarter, StrategyProperties.METHOD_CONTRACT, + StrategyProperties.LOOP_INVARIANT, StrategyProperties.QUERY_ON, + StrategyProperties.SPLITTING_NORMAL); + // Compute the available instance memory layout via the opened goals of the + // equivalent proof. + appliedCutsPerLayout = + extractAppliedCutsFromGoals(equivalentClassesProofStarter.getProof()); + // Create memory layout maps which are filled lazily + initialLayouts = new LinkedHashMap( + appliedCutsPerLayout.size()); + currentLayouts = new LinkedHashMap( + appliedCutsPerLayout.size()); + layoutsEquivalentClasses = + new LinkedHashMap>(); + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "Equivalence class computation on node " + node.serialNr() + ".", info); + } } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Equivalence class computation on node " + node.serialNr() + ".", info); - } - } - } - } - - /** - * Computes the initial updates to consider. - * @return The initial updates to consider. - */ - protected ImmutableList extractInitialUpdates() { - Sequent sequent = getRoot().sequent(); - assert sequent.antecedent().isEmpty(); - assert sequent.succedent().size() == 1; - Term sf = sequent.succedent().get(0).formula(); - assert sf.op() == Junctor.IMP; - Term modality = sf.sub(1); - return TermBuilder.goBelowUpdates2(modality).first; - } - - /** - * Sorts the given {@link Term}s alphabetically. - * @param terms The {@link Term}s to sort. - * @return The sorted {@link Term}s. - */ - protected Set sortTerms(Set terms) { - List list = new LinkedList(terms); - Collections.sort(list, new Comparator() { - @Override - public int compare(Term o1, Term o2) { - String o1s = o1.toString(); - String o2s = o2.toString(); - return o1s.length() - o2s.length(); - } - }); - return new LinkedHashSet(list); - } - - /** - * Filters out the objects from the second {@link Set} in the first {@link Set}. - * @param objectsToFilter The {@link Set} to filter. - * @param objectsToIgnore The {@link Set} with the objects to filter out. - * @return A new {@link Set} which contains all objects of the first {@link Set} which are not contained in the second {@link Set}. - * @throws ProofInputException - */ - protected Set filterOutObjectsToIgnore(Set objectsToFilter, - Set objectsToIgnore) throws ProofInputException { - Set result = new LinkedHashSet(); - for (Term symbolicObject : objectsToFilter) { - if (!objectsToIgnore.contains(symbolicObject)) { - result.add(symbolicObject); - } - } - return result; - } - - /** - *

- * Creates a {@link Sequent} which is used to compute equivalence classes. - *

- *

- * The created {@link Sequent} is the {@link Sequent} of {@link #node} - * without the modality. - *

- * @return The created {@link Sequent} to use for equivalence class computation. - */ - protected Sequent createSequentForEquivalenceClassComputation() { - return SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, - modalityPio, - null, - null, - updates, - false); - } - - /** - *

- * Applies cut rules to the given side proofs to compute equivalence classes. - *

- *

- * For each possible combination (without identity and ignoring the order) of the given objects is one cut performed. - *

- * @param starter The {@link ProofStarter} which provides the side proof. - * @param symbolicObjects The symbolic objects to compute equivalence classes for. - * @param updates The updates to consider. - */ - protected void applyCutRules(ProofStarter starter, Set symbolicObjects, ImmutableList updates) { - final TermBuilder tb = getServices().getTermBuilder(); - List objectsCopy = new ArrayList(symbolicObjects); - int maxProofSteps = 8000; - for (int i = 0; i < objectsCopy.size(); i++) { - for (int j = i + 1; j < objectsCopy.size(); j++) { - Term equalTerm = tb.equals(objectsCopy.get(i), objectsCopy.get(j)); - Term updateTerm = tb.applyParallel(updates, equalTerm); - applyCut(starter, updateTerm, maxProofSteps); - } - } - starter.setMaxRuleApplications(maxProofSteps); - starter.start(); - } - - /** - * Applies one single cut rule for the given {@link Term}. - * @param starter The {@link ProofStarter} to apply cut rule in. - * @param term The {@link Term} to cut out. - * @param maxProofSteps The maximal number of proof steps applied after cut via auto mode. - */ - protected void applyCut(ProofStarter starter, Term term, int maxProofSteps) { - ImmutableList goals = starter.getProof().openEnabledGoals(); - if (!goals.isEmpty()) { - int proofSteps = maxProofSteps / goals.size(); - if (proofSteps < 300) { - proofSteps = 300; - } - starter.setMaxRuleApplications(maxProofSteps); - for (final Goal g : goals) { - final NoPosTacletApp c = g.indexOfTaclets().lookup("cut"); - assert c != null; - - ImmutableSet set2 = c.uninstantiatedVars(); - SchemaVariable cutF = set2.iterator().next(); - - TacletApp t2 = c.addInstantiation(cutF, term, false, getServices()); - - final ImmutableList branches = g.apply(t2); - starter.start(branches); } - } - } - - /** - *

- * Extracts the possible memory layouts from the given side proof. - * Each open {@link Goal} of the proof results in its own memory layout. - *

- *

- * The applied cuts per memory layout are represented as {@link Term} - * stored in the {@link ImmutableSet}s. Each {@link Term} has the form - * {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))} - *

- * @param proof The {@link Proof} which provides the {@link Goal}s to extract memory layouts from. - * @return Each entry in the list represents a equivalence class memory layout. For each object pair checked via cut rules application exists one entry in the {@link Set} of the form {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. - * @throws ProofInputException Occurred Exception. - */ - protected List> extractAppliedCutsFromGoals(Proof proof) throws ProofInputException { - Set> resultSet = new LinkedHashSet>(); - Node root = proof.root(); - for (Goal goal : proof.openGoals()) { - resultSet.add(extractAppliedCutsSet(goal.node(), root)); - } - return new ArrayList>(resultSet); - } - - /** - * Extracts the applied cut rules in the given {@link Node}. Each cut - * rule is represented as {@link Term} of the form {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. - * @param goalnode The current {@link Node}. - * @param root The root {@link Node}. - * @return The applied cut rules. - * @throws ProofInputException Occurred Exception. - */ - protected ImmutableSet extractAppliedCutsSet(Node goalnode, Node root) throws ProofInputException { - ImmutableSet result = DefaultImmutableSet. nil(); - if (!root.find(goalnode)) { - throw new ProofInputException("Node \"" + goalnode + "\" ist not a childs of root node \"" + root + "\"."); - } - while (!(goalnode.serialNr() == root.serialNr())) { - final Node oldNode = goalnode; - goalnode = goalnode.parent(); - if (goalnode.getAppliedRuleApp() instanceof NoPosTacletApp) { - NoPosTacletApp npta = (NoPosTacletApp) goalnode.getAppliedRuleApp(); - if ("CUT".equals(npta.taclet().name().toString().toUpperCase())) { - Term inst = (Term) npta.instantiations().lookupEntryForSV(new Name("cutFormula")).value().getInstantiation(); - inst = TermBuilder.goBelowUpdates(inst); - if (goalnode.child(1) == oldNode) { - inst = getServices().getTermBuilder().not(inst); - } - result = result.add(inst); + } + + /** + * Computes the initial updates to consider. + * + * @return The initial updates to consider. + */ + protected ImmutableList extractInitialUpdates() { + Sequent sequent = getRoot().sequent(); + assert sequent.antecedent().isEmpty(); + assert sequent.succedent().size() == 1; + Term sf = sequent.succedent().get(0).formula(); + assert sf.op() == Junctor.IMP; + Term modality = sf.sub(1); + return TermBuilder.goBelowUpdates2(modality).first; + } + + /** + * Sorts the given {@link Term}s alphabetically. + * + * @param terms The {@link Term}s to sort. + * @return The sorted {@link Term}s. + */ + protected Set sortTerms(Set terms) { + List list = new LinkedList(terms); + Collections.sort(list, new Comparator() { + @Override + public int compare(Term o1, Term o2) { + String o1s = o1.toString(); + String o2s = o2.toString(); + return o1s.length() - o2s.length(); } - } - } - return result; - } - - /** - * Checks if {@link #analyse()} was already executed. - * @return {@code true} {@link #analyse()} was executed, {@code false} {@link #analyse()} was not executed. - */ - public boolean isAnalysed() { - synchronized (this) { - return initialLayouts != null && currentLayouts != null; - } - } - - /** - *

- * Returns the number of available memory layouts. - *

- *

- * Attention: Requires that {@link #analyse()} was executed. - *

- * @return The number of available memory layouts. - */ - public int getLayoutsCount() { - synchronized (this) { - assert isAnalysed(); - return appliedCutsPerLayout.size(); - } - } - - /** - *

- * Returns the initial memory layout at the given index. - *

- *

- * Attention: Requires that {@link #analyse()} was executed. - *

- * @param layoutIndex The index of the initial memory layout. - * @return The initial memory layout at the given index. - * @throws ProofInputException Occurred Exception - */ - public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException { - return getLayout(initialLayouts, layoutIndex, initialLocations, computeInitialStateName(), false); - } - - /** - * Computes the state name of an initial memory layout. - * @return The state name of an initial memory layout. - */ - protected String computeInitialStateName() { - return getRoot().name() + " resulting in " + computeCurrentStateName(); - } - - /** - *

- * Returns the current memory layout at the given index. - *

- *

- * Attention: Requires that {@link #analyse()} was executed. - *

- * @param layoutIndex The index of the current memory layout. - * @return The current memory layout at the given index. - * @throws ProofInputException Occurred Exception - */ - public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException { - return getLayout(currentLayouts, layoutIndex, currentLocations, computeCurrentStateName(), true); - } - - /** - * Computes the state name of a current memory layout. - * @return The state name of a current memory layout. - */ - protected String computeCurrentStateName() { - return node.name(); - } - - /** - * Helper method of {@link #getInitialLayout(int)} and - * {@link #getCurrentLayout(int)} to lazily compute and get a memory layout. - * @param confiurationsMap The map which contains already computed memory layouts. - * @param layoutIndex The index of the memory layout to lazily compute and return. - * @param locations The locations to compute in side proof. - * @param stateName The name of the state. - * @param currentLayout {@code true} current layout, {@code false} initial layout. - * @return The lazily computed memory layout. - * @throws ProofInputException Occurred Exception. - */ - protected ISymbolicLayout getLayout(Map confiurationsMap, - int layoutIndex, - Set locations, - String stateName, - boolean currentLayout) throws ProofInputException { - synchronized (this) { - assert layoutIndex >= 0; - assert layoutIndex < appliedCutsPerLayout.size(); - assert isAnalysed(); - ISymbolicLayout result = confiurationsMap.get(Integer.valueOf(layoutIndex)); - if (result == null) { - // Get memory layout - ImmutableSet layout = appliedCutsPerLayout.get(layoutIndex); - ImmutableList equivalentClasses = getEquivalenceClasses(layoutIndex); - result = lazyComputeLayout(layout, locations, equivalentClasses, stateName, currentLayout); - confiurationsMap.put(Integer.valueOf(layoutIndex), result); - } - return result; - } - } - - /** - *

- * Computes a memory layout lazily when it is first time requested via - * {@link #getLayout(Map, int, Term, Set, String, boolean)}. - *

- *

- * Finally, the last step is to create the {@link ISymbolicLayout} instance - * and to fill it with the values/associations defined by {@link ExecutionVariableValuePair} instances. - *

- * @param layout The memory layout terms. - * @param locations The locations to compute in side proof. - * @param equivalentClasses The equivalence classes defined by the memory layout terms. - * @param stateName The name of the state. - * @param currentLayout {@code true} current layout, {@code false} initial layout. - * @return The created memory layout. - * @throws ProofInputException Occurred Exception. - */ - protected ISymbolicLayout lazyComputeLayout(ImmutableSet layout, - Set locations, - ImmutableList equivalentClasses, - String stateName, - boolean currentLayout) throws ProofInputException { - if (!locations.isEmpty()) { - final TermBuilder tb = getServices().getTermBuilder(); - List updateConditions = new ArrayList(layout.size()); - for (Term term : layout) { - updateConditions.add(tb.applyParallel(updates, term)); - } - Term layoutCondition = tb.and(updateConditions); - Set locationsAccordingToEquivalentClass = updateLocationsAccordingtoEquivalentClass(locations, equivalentClasses); - Term layoutTerm = createLocationPredicateAndTerm(locationsAccordingToEquivalentClass); - Set pairs = computeVariableValuePairs(layoutCondition, layoutTerm, locationsAccordingToEquivalentClass, currentLayout, settings.isSimplifyConditions()); - return createLayoutFromExecutionVariableValuePairs(equivalentClasses, pairs, stateName); - } - else { - return createLayoutFromExecutionVariableValuePairs(equivalentClasses, new LinkedHashSet(), stateName); - } - } - - /** - * Replaces the parent of each {@link ExtractLocationParameter} according - * to the {@link ISymbolicEquivalenceClass}es, because there is no guarantee - * that the strategy evaluates each aliased location to the same symbolic value. - * @param locations The available {@link ExtractLocationParameter}s. - * @param equivalentClasses The available {@link ISymbolicEquivalenceClass}es. - * @return The updated {@link ExtractLocationParameter}s. - */ - protected Set updateLocationsAccordingtoEquivalentClass(Set locations, ImmutableList equivalentClasses) { - Set newLocations = new LinkedHashSet(locations.size()); - for (ExtractLocationParameter location : locations) { - Term parent = location.getParentTerm(); - ISymbolicEquivalenceClass eq = findEquivalentClass(equivalentClasses, parent); - if (eq != null) { - newLocations.add(new ExtractLocationParameter(location, eq.getRepresentative())); - } - else { - newLocations.add(location); - } - } - return newLocations; - } - - /** - * Collects all objects which are used in the conditions of the {@link Sequent}. - * @param sequent The {@link Sequent} which provides the conditions to collect objects from. - * @param objectsToIgnore Objects which should be excluded in the result. - * @return The found objects. - * @throws ProofInputException Occurred Exception. - */ - protected Set collectObjectsFromSequent(Sequent sequent, - Set objectsToIgnore) throws ProofInputException { - Set result = new LinkedHashSet(); - for (SequentFormula sf : sequent) { - if (SymbolicExecutionUtil.checkSkolemEquality(sf) == 0) { - result.addAll(collectSymbolicObjectsFromTerm(sf.formula(), objectsToIgnore)); - } - } - return result; - } - - /** - * Collects all objects which are used in the given {@link Term}. - * @param term The {@link Term} to collect objects in. - * @param objectsToIgnore Objects which should be excluded in the result. - * @return The found objects. - * @throws ProofInputException Occurred Exception. - */ - protected Set collectSymbolicObjectsFromTerm(Term term, - final Set objectsToIgnore) throws ProofInputException { - final Set result = new LinkedHashSet(); - term.execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - visited = OriginTermLabel.removeOriginLabels(visited, getServices()); - if (SymbolicExecutionUtil.hasReferenceSort(getServices(), visited) && - visited.freeVars().isEmpty() && - !objectsToIgnore.contains(visited) && - !SymbolicExecutionUtil.isSkolemConstant(visited)) { - result.add(visited); + }); + return new LinkedHashSet(list); + } + + /** + * Filters out the objects from the second {@link Set} in the first {@link Set}. + * + * @param objectsToFilter The {@link Set} to filter. + * @param objectsToIgnore The {@link Set} with the objects to filter out. + * @return A new {@link Set} which contains all objects of the first {@link Set} which are not + * contained in the second {@link Set}. + * @throws ProofInputException + */ + protected Set filterOutObjectsToIgnore(Set objectsToFilter, + Set objectsToIgnore) throws ProofInputException { + Set result = new LinkedHashSet(); + for (Term symbolicObject : objectsToFilter) { + if (!objectsToIgnore.contains(symbolicObject)) { + result.add(symbolicObject); } - } - }); - return result; - } - - /** - *

- * Returns the equivalence class of the memory layout defined by the index. - *

- *

- * Attention: Requires that {@link #analyse()} was executed. - *

- * @param layoutIndex The index of the memory layout to get its equivalence classes. - * @return The equivalence classes of the memory layout at the given index. - */ - public ImmutableList getEquivalenceClasses(int layoutIndex) { - synchronized (this) { - ImmutableList equivalentClasses = layoutsEquivalentClasses.get(Integer.valueOf(layoutIndex)); - if (equivalentClasses == null) { - ImmutableSet appliedCuts = appliedCutsPerLayout.get(layoutIndex); - equivalentClasses = lazyComputeEquivalenceClasses(appliedCuts); - layoutsEquivalentClasses.put(Integer.valueOf(layoutIndex), equivalentClasses); - } - return equivalentClasses; - } - } - - /** - *

- * Computes the equivalence classes from the given applied cut rules - * lazily when {@link #getEquivalenceClasses(int)} is called the first time. - *

- *

- * Each entry in the given {@link ImmutableSet} is of the form - * {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. - *

- *

- * An {@link ISymbolicEquivalenceClass} is only created for objects which - * are equal. Objects which are equal to no other one are not represented - * in an {@link ISymbolicEquivalenceClass}. This makes sure that each - * {@link ISymbolicEquivalenceClass} contains at least two objects and - * that the result is empty if all objects are not equal to each other. - *

- * @param appliedCuts The applied cut rules. - * @return The created {@link ISymbolicEquivalenceClass} instances. - */ - protected ImmutableList lazyComputeEquivalenceClasses(ImmutableSet appliedCuts) { - ImmutableList result = ImmutableSLList.nil(); - for (Term term : appliedCuts) { - if (Junctor.NOT != term.op()) { - assert term.op() == Equality.EQUALS; - - final Iterator iter = term.subs().iterator(); - ISymbolicEquivalenceClass ec = null; - while (ec == null && iter.hasNext()) { - ec = findEquivalentClass(result, iter.next()); + } + return result; + } + + /** + *

+ * Creates a {@link Sequent} which is used to compute equivalence classes. + *

+ *

+ * The created {@link Sequent} is the {@link Sequent} of {@link #node} without the modality. + *

+ * + * @return The created {@link Sequent} to use for equivalence class computation. + */ + protected Sequent createSequentForEquivalenceClassComputation() { + return SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, modalityPio, null, + null, updates, false); + } + + /** + *

+ * Applies cut rules to the given side proofs to compute equivalence classes. + *

+ *

+ * For each possible combination (without identity and ignoring the order) of the given objects + * is one cut performed. + *

+ * + * @param starter The {@link ProofStarter} which provides the side proof. + * @param symbolicObjects The symbolic objects to compute equivalence classes for. + * @param updates The updates to consider. + */ + protected void applyCutRules(ProofStarter starter, Set symbolicObjects, + ImmutableList updates) { + final TermBuilder tb = getServices().getTermBuilder(); + List objectsCopy = new ArrayList(symbolicObjects); + int maxProofSteps = 8000; + for (int i = 0; i < objectsCopy.size(); i++) { + for (int j = i + 1; j < objectsCopy.size(); j++) { + Term equalTerm = tb.equals(objectsCopy.get(i), objectsCopy.get(j)); + Term updateTerm = tb.applyParallel(updates, equalTerm); + applyCut(starter, updateTerm, maxProofSteps); } - if (ec == null) { - ec = new SymbolicEquivalenceClass(getServices(), settings); - result = result.append(ec); + } + starter.setMaxRuleApplications(maxProofSteps); + starter.start(); + } + + /** + * Applies one single cut rule for the given {@link Term}. + * + * @param starter The {@link ProofStarter} to apply cut rule in. + * @param term The {@link Term} to cut out. + * @param maxProofSteps The maximal number of proof steps applied after cut via auto mode. + */ + protected void applyCut(ProofStarter starter, Term term, int maxProofSteps) { + ImmutableList goals = starter.getProof().openEnabledGoals(); + if (!goals.isEmpty()) { + int proofSteps = maxProofSteps / goals.size(); + if (proofSteps < 300) { + proofSteps = 300; } - for (Term sub : term.subs()) { - if (!ec.containsTerm(sub)) { - ((SymbolicEquivalenceClass)ec).addTerm(sub); - } + starter.setMaxRuleApplications(maxProofSteps); + for (final Goal g : goals) { + final NoPosTacletApp c = g.indexOfTaclets().lookup("cut"); + assert c != null; + + ImmutableSet set2 = c.uninstantiatedVars(); + SchemaVariable cutF = set2.iterator().next(); + + TacletApp t2 = c.addInstantiation(cutF, term, false, getServices()); + + final ImmutableList branches = g.apply(t2); + starter.start(branches); } - } - } - return result; - } - - /** - * Searches the {@link ISymbolicEquivalenceClass} from the given one - * which contains the given {@link Term}. - * @param equivalentClasses The available {@link ISymbolicEquivalenceClass} to search in. - * @param term The {@link Term} to search. - * @return The found {@link ISymbolicEquivalenceClass} which contains the given {@link Term} or {@code null} if no one was found. - */ - protected ISymbolicEquivalenceClass findEquivalentClass(ImmutableList equivalentClasses, - final Term term) { - return CollectionUtil.search(equivalentClasses, new IFilter() { - @Override - public boolean select(ISymbolicEquivalenceClass element) { - return element.containsTerm(term); - } - }); - } - - /** - * Creates an {@link ISymbolicLayout} which shows the objects, - * values and associations defined by the given {@link ExecutionVariableValuePair}s. - * @param equivalentClasses The used {@link ISymbolicEquivalenceClass} instances of the memory layout. - * @param pairs Provides the available objects, their values and associations together with the variables and association of the state. - * @param stateName The name of the state. - * @return The created {@link ISymbolicLayout} with the given content. - * @throws ProofInputException Occurred Exception. - */ - protected ISymbolicLayout createLayoutFromExecutionVariableValuePairs(ImmutableList equivalentClasses, - Set pairs, - String stateName) throws ProofInputException { - SymbolicLayout result = new SymbolicLayout(settings, equivalentClasses); - // Create state - SymbolicState state = new SymbolicState(stateName, settings); - result.setState(state); - // Create objects - Map objects = new LinkedHashMap(); - for (ExecutionVariableValuePair pair : pairs) { - // Create object for parent of current value - createObjectForTerm(objects, equivalentClasses, result, pair.getParent()); - // Create object for current value - createObjectForTerm(objects, equivalentClasses, result, pair.getValue()); - } - // Fill objects and state with association and values - for (ExecutionVariableValuePair pair : pairs) { - // Find parent object/state - Term parent = pair.getParent(); - Term valueTerm = pair.getValue(); - AbstractSymbolicAssociationValueContainer container; - if (parent != null) { - ISymbolicEquivalenceClass equivalentClass = findEquivalentClass(equivalentClasses, parent); - container = objects.get(equivalentClass != null ? equivalentClass.getRepresentative() : parent); - } - else { - if (pair.isStateMember() || !objectsToIgnore.contains(valueTerm)) { - container = state; // Add only updates of local variables to the + } + } + + /** + *

+ * Extracts the possible memory layouts from the given side proof. Each open {@link Goal} of the + * proof results in its own memory layout. + *

+ *

+ * The applied cuts per memory layout are represented as {@link Term} stored in the + * {@link ImmutableSet}s. Each {@link Term} has the form {@code equals(obj1, obj2)} or + * {@code not(equals(obj1, obj2))} + *

+ * + * @param proof The {@link Proof} which provides the {@link Goal}s to extract memory layouts + * from. + * @return Each entry in the list represents a equivalence class memory layout. For each object + * pair checked via cut rules application exists one entry in the {@link Set} of the + * form {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. + * @throws ProofInputException Occurred Exception. + */ + protected List> extractAppliedCutsFromGoals(Proof proof) + throws ProofInputException { + Set> resultSet = new LinkedHashSet>(); + Node root = proof.root(); + for (Goal goal : proof.openGoals()) { + resultSet.add(extractAppliedCutsSet(goal.node(), root)); + } + return new ArrayList>(resultSet); + } + + /** + * Extracts the applied cut rules in the given {@link Node}. Each cut rule is represented as + * {@link Term} of the form {@code equals(obj1, obj2)} or {@code not(equals(obj1, obj2))}. + * + * @param goalnode The current {@link Node}. + * @param root The root {@link Node}. + * @return The applied cut rules. + * @throws ProofInputException Occurred Exception. + */ + protected ImmutableSet extractAppliedCutsSet(Node goalnode, Node root) + throws ProofInputException { + ImmutableSet result = DefaultImmutableSet.nil(); + if (!root.find(goalnode)) { + throw new ProofInputException( + "Node \"" + goalnode + "\" ist not a childs of root node \"" + root + "\"."); + } + while (!(goalnode.serialNr() == root.serialNr())) { + final Node oldNode = goalnode; + goalnode = goalnode.parent(); + if (goalnode.getAppliedRuleApp() instanceof NoPosTacletApp) { + NoPosTacletApp npta = (NoPosTacletApp) goalnode.getAppliedRuleApp(); + if ("CUT".equals(npta.taclet().name().toString().toUpperCase())) { + Term inst = (Term) npta.instantiations() + .lookupEntryForSV(new Name("cutFormula")).value().getInstantiation(); + inst = TermBuilder.goBelowUpdates(inst); + if (goalnode.child(1) == oldNode) { + inst = getServices().getTermBuilder().not(inst); + } + result = result.add(inst); + } } - else { - container = null; + } + return result; + } + + /** + * Checks if {@link #analyse()} was already executed. + * + * @return {@code true} {@link #analyse()} was executed, {@code false} {@link #analyse()} was + * not executed. + */ + public boolean isAnalysed() { + synchronized (this) { + return initialLayouts != null && currentLayouts != null; + } + } + + /** + *

+ * Returns the number of available memory layouts. + *

+ *

+ * Attention: Requires that {@link #analyse()} was executed. + *

+ * + * @return The number of available memory layouts. + */ + public int getLayoutsCount() { + synchronized (this) { + assert isAnalysed(); + return appliedCutsPerLayout.size(); + } + } + + /** + *

+ * Returns the initial memory layout at the given index. + *

+ *

+ * Attention: Requires that {@link #analyse()} was executed. + *

+ * + * @param layoutIndex The index of the initial memory layout. + * @return The initial memory layout at the given index. + * @throws ProofInputException Occurred Exception + */ + public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException { + return getLayout(initialLayouts, layoutIndex, initialLocations, computeInitialStateName(), + false); + } + + /** + * Computes the state name of an initial memory layout. + * + * @return The state name of an initial memory layout. + */ + protected String computeInitialStateName() { + return getRoot().name() + " resulting in " + computeCurrentStateName(); + } + + /** + *

+ * Returns the current memory layout at the given index. + *

+ *

+ * Attention: Requires that {@link #analyse()} was executed. + *

+ * + * @param layoutIndex The index of the current memory layout. + * @return The current memory layout at the given index. + * @throws ProofInputException Occurred Exception + */ + public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException { + return getLayout(currentLayouts, layoutIndex, currentLocations, computeCurrentStateName(), + true); + } + + /** + * Computes the state name of a current memory layout. + * + * @return The state name of a current memory layout. + */ + protected String computeCurrentStateName() { + return node.name(); + } + + /** + * Helper method of {@link #getInitialLayout(int)} and {@link #getCurrentLayout(int)} to lazily + * compute and get a memory layout. + * + * @param confiurationsMap The map which contains already computed memory layouts. + * @param layoutIndex The index of the memory layout to lazily compute and return. + * @param locations The locations to compute in side proof. + * @param stateName The name of the state. + * @param currentLayout {@code true} current layout, {@code false} initial layout. + * @return The lazily computed memory layout. + * @throws ProofInputException Occurred Exception. + */ + protected ISymbolicLayout getLayout(Map confiurationsMap, + int layoutIndex, Set locations, String stateName, + boolean currentLayout) throws ProofInputException { + synchronized (this) { + assert layoutIndex >= 0; + assert layoutIndex < appliedCutsPerLayout.size(); + assert isAnalysed(); + ISymbolicLayout result = confiurationsMap.get(Integer.valueOf(layoutIndex)); + if (result == null) { + // Get memory layout + ImmutableSet layout = appliedCutsPerLayout.get(layoutIndex); + ImmutableList equivalentClasses = + getEquivalenceClasses(layoutIndex); + result = lazyComputeLayout(layout, locations, equivalentClasses, stateName, + currentLayout); + confiurationsMap.put(Integer.valueOf(layoutIndex), result); + } + return result; + } + } + + /** + *

+ * Computes a memory layout lazily when it is first time requested via + * {@link #getLayout(Map, int, Term, Set, String, boolean)}. + *

+ *

+ * Finally, the last step is to create the {@link ISymbolicLayout} instance and to fill it with + * the values/associations defined by {@link ExecutionVariableValuePair} instances. + *

+ * + * @param layout The memory layout terms. + * @param locations The locations to compute in side proof. + * @param equivalentClasses The equivalence classes defined by the memory layout terms. + * @param stateName The name of the state. + * @param currentLayout {@code true} current layout, {@code false} initial layout. + * @return The created memory layout. + * @throws ProofInputException Occurred Exception. + */ + protected ISymbolicLayout lazyComputeLayout(ImmutableSet layout, + Set locations, + ImmutableList equivalentClasses, String stateName, + boolean currentLayout) throws ProofInputException { + if (!locations.isEmpty()) { + final TermBuilder tb = getServices().getTermBuilder(); + List updateConditions = new ArrayList(layout.size()); + for (Term term : layout) { + updateConditions.add(tb.applyParallel(updates, term)); } - } - // Check if a container was found, if not it is an less important equivalent object - if (container != null) { - // Check if the term is in an equivalent class, in this case use the representative term instead of the term itself. - ISymbolicEquivalenceClass eq = findEquivalentClass(equivalentClasses, valueTerm); + Term layoutCondition = tb.and(updateConditions); + Set locationsAccordingToEquivalentClass = + updateLocationsAccordingtoEquivalentClass(locations, equivalentClasses); + Term layoutTerm = createLocationPredicateAndTerm(locationsAccordingToEquivalentClass); + Set pairs = computeVariableValuePairs(layoutCondition, + layoutTerm, locationsAccordingToEquivalentClass, currentLayout, + settings.isSimplifyConditions()); + return createLayoutFromExecutionVariableValuePairs(equivalentClasses, pairs, stateName); + } else { + return createLayoutFromExecutionVariableValuePairs(equivalentClasses, + new LinkedHashSet(), stateName); + } + } + + /** + * Replaces the parent of each {@link ExtractLocationParameter} according to the + * {@link ISymbolicEquivalenceClass}es, because there is no guarantee that the strategy + * evaluates each aliased location to the same symbolic value. + * + * @param locations The available {@link ExtractLocationParameter}s. + * @param equivalentClasses The available {@link ISymbolicEquivalenceClass}es. + * @return The updated {@link ExtractLocationParameter}s. + */ + protected Set updateLocationsAccordingtoEquivalentClass( + Set locations, + ImmutableList equivalentClasses) { + Set newLocations = + new LinkedHashSet(locations.size()); + for (ExtractLocationParameter location : locations) { + Term parent = location.getParentTerm(); + ISymbolicEquivalenceClass eq = findEquivalentClass(equivalentClasses, parent); if (eq != null) { - valueTerm = eq.getRepresentative(); + newLocations.add(new ExtractLocationParameter(location, eq.getRepresentative())); + } else { + newLocations.add(location); + } + } + return newLocations; + } + + /** + * Collects all objects which are used in the conditions of the {@link Sequent}. + * + * @param sequent The {@link Sequent} which provides the conditions to collect objects from. + * @param objectsToIgnore Objects which should be excluded in the result. + * @return The found objects. + * @throws ProofInputException Occurred Exception. + */ + protected Set collectObjectsFromSequent(Sequent sequent, Set objectsToIgnore) + throws ProofInputException { + Set result = new LinkedHashSet(); + for (SequentFormula sf : sequent) { + if (SymbolicExecutionUtil.checkSkolemEquality(sf) == 0) { + result.addAll(collectSymbolicObjectsFromTerm(sf.formula(), objectsToIgnore)); + } + } + return result; + } + + /** + * Collects all objects which are used in the given {@link Term}. + * + * @param term The {@link Term} to collect objects in. + * @param objectsToIgnore Objects which should be excluded in the result. + * @return The found objects. + * @throws ProofInputException Occurred Exception. + */ + protected Set collectSymbolicObjectsFromTerm(Term term, final Set objectsToIgnore) + throws ProofInputException { + final Set result = new LinkedHashSet(); + term.execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + visited = OriginTermLabel.removeOriginLabels(visited, getServices()); + if (SymbolicExecutionUtil.hasReferenceSort(getServices(), visited) + && visited.freeVars().isEmpty() && !objectsToIgnore.contains(visited) + && !SymbolicExecutionUtil.isSkolemConstant(visited)) { + result.add(visited); + } + } + }); + return result; + } + + /** + *

+ * Returns the equivalence class of the memory layout defined by the index. + *

+ *

+ * Attention: Requires that {@link #analyse()} was executed. + *

+ * + * @param layoutIndex The index of the memory layout to get its equivalence classes. + * @return The equivalence classes of the memory layout at the given index. + */ + public ImmutableList getEquivalenceClasses(int layoutIndex) { + synchronized (this) { + ImmutableList equivalentClasses = + layoutsEquivalentClasses.get(Integer.valueOf(layoutIndex)); + if (equivalentClasses == null) { + ImmutableSet appliedCuts = appliedCutsPerLayout.get(layoutIndex); + equivalentClasses = lazyComputeEquivalenceClasses(appliedCuts); + layoutsEquivalentClasses.put(Integer.valueOf(layoutIndex), equivalentClasses); } - // Check if it is an association - SymbolicObject target = objects.get(valueTerm); - if (target != null) { - SymbolicAssociation association; - if (pair.isArrayRange()) { - association = new SymbolicAssociation(getServices(), pair.getArrayIndex(), pair.getArrayStartIndex(), pair.getArrayEndIndex(), target, pair.getCondition(), settings); - } - else if (pair.isArrayIndex()) { - association = new SymbolicAssociation(getServices(), pair.getArrayIndex(), target, pair.getCondition(), settings); - } - else { - association = new SymbolicAssociation(getServices(), pair.getProgramVariable(), target, pair.getCondition(), settings); - } - // Add association only if not already present - ISymbolicAssociation existingAssociation = container.getAssociation(association.getProgramVariable(), association.isArrayIndex(), association.getArrayIndex(), association.getCondition()); - if (existingAssociation == null) { - // Add association to the container - container.addAssociation(association); - } - else { - // Make sure that target is the same - if (!ObjectUtil.equals(association.getTarget(), existingAssociation.getTarget())) { - throw new ProofInputException("Multiple association targets found: " + association + " and " + existingAssociation + "."); - } - } + return equivalentClasses; + } + } + + /** + *

+ * Computes the equivalence classes from the given applied cut rules lazily when + * {@link #getEquivalenceClasses(int)} is called the first time. + *

+ *

+ * Each entry in the given {@link ImmutableSet} is of the form {@code equals(obj1, obj2)} or + * {@code not(equals(obj1, obj2))}. + *

+ *

+ * An {@link ISymbolicEquivalenceClass} is only created for objects which are equal. Objects + * which are equal to no other one are not represented in an {@link ISymbolicEquivalenceClass}. + * This makes sure that each {@link ISymbolicEquivalenceClass} contains at least two objects and + * that the result is empty if all objects are not equal to each other. + *

+ * + * @param appliedCuts The applied cut rules. + * @return The created {@link ISymbolicEquivalenceClass} instances. + */ + protected ImmutableList lazyComputeEquivalenceClasses( + ImmutableSet appliedCuts) { + ImmutableList result = ImmutableSLList.nil(); + for (Term term : appliedCuts) { + if (Junctor.NOT != term.op()) { + assert term.op() == Equality.EQUALS; + + final Iterator iter = term.subs().iterator(); + ISymbolicEquivalenceClass ec = null; + while (ec == null && iter.hasNext()) { + ec = findEquivalentClass(result, iter.next()); + } + if (ec == null) { + ec = new SymbolicEquivalenceClass(getServices(), settings); + result = result.append(ec); + } + for (Term sub : term.subs()) { + if (!ec.containsTerm(sub)) { + ((SymbolicEquivalenceClass) ec).addTerm(sub); + } + } + } + } + return result; + } + + /** + * Searches the {@link ISymbolicEquivalenceClass} from the given one which contains the given + * {@link Term}. + * + * @param equivalentClasses The available {@link ISymbolicEquivalenceClass} to search in. + * @param term The {@link Term} to search. + * @return The found {@link ISymbolicEquivalenceClass} which contains the given {@link Term} or + * {@code null} if no one was found. + */ + protected ISymbolicEquivalenceClass findEquivalentClass( + ImmutableList equivalentClasses, final Term term) { + return CollectionUtil.search(equivalentClasses, new IFilter() { + @Override + public boolean select(ISymbolicEquivalenceClass element) { + return element.containsTerm(term); + } + }); + } + + /** + * Creates an {@link ISymbolicLayout} which shows the objects, values and associations defined + * by the given {@link ExecutionVariableValuePair}s. + * + * @param equivalentClasses The used {@link ISymbolicEquivalenceClass} instances of the memory + * layout. + * @param pairs Provides the available objects, their values and associations together with the + * variables and association of the state. + * @param stateName The name of the state. + * @return The created {@link ISymbolicLayout} with the given content. + * @throws ProofInputException Occurred Exception. + */ + protected ISymbolicLayout createLayoutFromExecutionVariableValuePairs( + ImmutableList equivalentClasses, + Set pairs, String stateName) throws ProofInputException { + SymbolicLayout result = new SymbolicLayout(settings, equivalentClasses); + // Create state + SymbolicState state = new SymbolicState(stateName, settings); + result.setState(state); + // Create objects + Map objects = new LinkedHashMap(); + for (ExecutionVariableValuePair pair : pairs) { + // Create object for parent of current value + createObjectForTerm(objects, equivalentClasses, result, pair.getParent()); + // Create object for current value + createObjectForTerm(objects, equivalentClasses, result, pair.getValue()); + } + // Fill objects and state with association and values + for (ExecutionVariableValuePair pair : pairs) { + // Find parent object/state + Term parent = pair.getParent(); + Term valueTerm = pair.getValue(); + AbstractSymbolicAssociationValueContainer container; + if (parent != null) { + ISymbolicEquivalenceClass equivalentClass = + findEquivalentClass(equivalentClasses, parent); + container = objects.get( + equivalentClass != null ? equivalentClass.getRepresentative() : parent); + } else { + if (pair.isStateMember() || !objectsToIgnore.contains(valueTerm)) { + container = state; // Add only updates of local variables to the + } else { + container = null; + } } - else { - SymbolicValue value; - if (pair.isArrayRange()) { - value = new SymbolicValue(getServices(), pair.getArrayIndex(), pair.getArrayStartIndex(), pair.getArrayEndIndex(), valueTerm, pair.getCondition(), settings); - } - else if (pair.isArrayIndex()) { - value = new SymbolicValue(getServices(), pair.getArrayIndex(), valueTerm, pair.getCondition(), settings); - } - else { - value = new SymbolicValue(getServices(), pair.getProgramVariable(), valueTerm, pair.getCondition(), settings); - } - // Add value only if not already present - ISymbolicValue existingValue = container.getValue(value.getProgramVariable(), value.isArrayIndex(), value.getArrayIndex(), value.getCondition()); - if (existingValue == null) { - // Add value to the container - container.addValue(value); - } - else { - // Make sure that the value is the same - if (!ObjectUtil.equals(value.getValue(), existingValue.getValue())) { - throw new ProofInputException("Multiple values found: " + value + " and " + existingValue + "."); - } - } + // Check if a container was found, if not it is an less important equivalent object + if (container != null) { + // Check if the term is in an equivalent class, in this case use the representative + // term instead of the term itself. + ISymbolicEquivalenceClass eq = findEquivalentClass(equivalentClasses, valueTerm); + if (eq != null) { + valueTerm = eq.getRepresentative(); + } + // Check if it is an association + SymbolicObject target = objects.get(valueTerm); + if (target != null) { + SymbolicAssociation association; + if (pair.isArrayRange()) { + association = new SymbolicAssociation(getServices(), pair.getArrayIndex(), + pair.getArrayStartIndex(), pair.getArrayEndIndex(), target, + pair.getCondition(), settings); + } else if (pair.isArrayIndex()) { + association = new SymbolicAssociation(getServices(), pair.getArrayIndex(), + target, pair.getCondition(), settings); + } else { + association = new SymbolicAssociation(getServices(), + pair.getProgramVariable(), target, pair.getCondition(), settings); + } + // Add association only if not already present + ISymbolicAssociation existingAssociation = container.getAssociation( + association.getProgramVariable(), association.isArrayIndex(), + association.getArrayIndex(), association.getCondition()); + if (existingAssociation == null) { + // Add association to the container + container.addAssociation(association); + } else { + // Make sure that target is the same + if (!ObjectUtil.equals(association.getTarget(), + existingAssociation.getTarget())) { + throw new ProofInputException("Multiple association targets found: " + + association + " and " + existingAssociation + "."); + } + } + } else { + SymbolicValue value; + if (pair.isArrayRange()) { + value = new SymbolicValue(getServices(), pair.getArrayIndex(), + pair.getArrayStartIndex(), pair.getArrayEndIndex(), valueTerm, + pair.getCondition(), settings); + } else if (pair.isArrayIndex()) { + value = new SymbolicValue(getServices(), pair.getArrayIndex(), valueTerm, + pair.getCondition(), settings); + } else { + value = new SymbolicValue(getServices(), pair.getProgramVariable(), + valueTerm, pair.getCondition(), settings); + } + // Add value only if not already present + ISymbolicValue existingValue = container.getValue(value.getProgramVariable(), + value.isArrayIndex(), value.getArrayIndex(), value.getCondition()); + if (existingValue == null) { + // Add value to the container + container.addValue(value); + } else { + // Make sure that the value is the same + if (!ObjectUtil.equals(value.getValue(), existingValue.getValue())) { + throw new ProofInputException("Multiple values found: " + value + + " and " + existingValue + "."); + } + } + } } - } - } - return result; - } - - /** - * Creates for the object defined by the given {@link Term} an {@link SymbolicObject} instance if not already available. - * @param objects The already available {@link SymbolicObject}s. - * @param equivalentClasses The available {@link ISymbolicEquivalenceClass}. - * @param result The {@link SymbolicLayout} to add the {@link SymbolicObject} to. - * @param objectTerm The {@link Term} which represents the {@link Object} a {@link SymbolicObject} should be created for. - */ - protected void createObjectForTerm(Map objects, - ImmutableList equivalentClasses, - SymbolicLayout result, - Term objectTerm) { - if (objectTerm != null && SymbolicExecutionUtil.hasReferenceSort(getServices(), objectTerm)) { - ISymbolicEquivalenceClass equivalentClass = findEquivalentClass(equivalentClasses, objectTerm); - if (equivalentClass != null) { - objectTerm = equivalentClass.getRepresentative(); - } - SymbolicObject object = objects.get(objectTerm); - if (object == null) { - object = new SymbolicObject(getServices(), objectTerm, settings); - objects.put(objectTerm, object); - result.addObject(object); - } - } - } -} \ No newline at end of file + } + return result; + } + + /** + * Creates for the object defined by the given {@link Term} an {@link SymbolicObject} instance + * if not already available. + * + * @param objects The already available {@link SymbolicObject}s. + * @param equivalentClasses The available {@link ISymbolicEquivalenceClass}. + * @param result The {@link SymbolicLayout} to add the {@link SymbolicObject} to. + * @param objectTerm The {@link Term} which represents the {@link Object} a + * {@link SymbolicObject} should be created for. + */ + protected void createObjectForTerm(Map objects, + ImmutableList equivalentClasses, SymbolicLayout result, + Term objectTerm) { + if (objectTerm != null + && SymbolicExecutionUtil.hasReferenceSort(getServices(), objectTerm)) { + ISymbolicEquivalenceClass equivalentClass = + findEquivalentClass(equivalentClasses, objectTerm); + if (equivalentClass != null) { + objectTerm = equivalentClass.getRepresentative(); + } + SymbolicObject object = objects.get(objectTerm); + if (object == null) { + object = new SymbolicObject(getServices(), objectTerm, settings); + objects.put(objectTerm, object); + result.addObject(object); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutReader.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutReader.java index 2d39a202faa..b4e3fb2ade7 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutReader.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutReader.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.io.File; @@ -34,1041 +37,1095 @@ import de.uka.ilkd.key.symbolic_execution.object_model.ISymbolicValue; /** - * Allows to read XML files which contains an object model - * written via an {@link SymbolicLayoutWriter}. + * Allows to read XML files which contains an object model written via an + * {@link SymbolicLayoutWriter}. + * * @author Martin Hentschel * @see SymbolicLayoutWriter */ public class SymbolicLayoutReader { - /** - * Reads the given {@link File}. - * @param file The {@link File} to read. - * @return The root of the model. - * @throws ParserConfigurationException Occurred Exception. - * @throws SAXException Occurred Exception. - * @throws IOException Occurred Exception. - */ - public ISymbolicLayout read(File file) throws ParserConfigurationException, SAXException, IOException { - return read(new FileInputStream(file)); - } - - /** - * Reads from the given {@link InputStream} and closes it. - * @param in The {@link InputStream} to read from. - * @return The root of the model. - * @throws ParserConfigurationException Occurred Exception. - * @throws SAXException Occurred Exception. - * @throws IOException Occurred Exception. - */ - public ISymbolicLayout read(InputStream in) throws ParserConfigurationException, SAXException, IOException { - if (in != null) { - try { - // Parse XML file - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setNamespaceAware(true); - SAXParser saxParser = factory.newSAXParser(); - SEDSAXHandler handler = new SEDSAXHandler(); - saxParser.parse(in, handler); - // Get root - ISymbolicLayout root = handler.getRoot(); - // Return result - return root; - } - finally { - in.close(); - } - } - else { - return null; - } - } - - /** - * {@link DefaultHandler} implementation used in {@link ExecutionNodeReader#read(InputStream)}. - * @author Martin Hentschel - */ - private class SEDSAXHandler extends DefaultHandler { - /** - * The root of the model. - */ - private ISymbolicLayout root; - - /** - * The hierarchy in building phase. - */ - private Deque parentStack = new LinkedList(); - - /** - * Maps each unique object ID to the instantiated {@link ISymbolicObject}. - */ - private Map objectIdMapping = new LinkedHashMap(); - - /** - * Maps a {@link KeYlessAssociation} to its target object ID. - */ - private Map associationTargetMapping = new LinkedHashMap(); - - /** - * {@inheritDoc} - */ - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - Object parent = parentStack.peekFirst(); - if (isModel(uri, localName, qName)) { - if (root == null) { - root = new KeYlessLayout(); - parentStack.addFirst(root); - } - else { - throw new SAXException("Model found a second time."); - } - } - else if (isState(uri, localName, qName)) { - if (!(parent instanceof KeYlessLayout)) { - throw new SAXException("Found state in wrong hierarchy."); - } - KeYlessState state = new KeYlessState(getName(attributes)); - if (((KeYlessLayout)parent).getState() != null) { - throw new SAXException("State found a second time."); + /** + * Reads the given {@link File}. + * + * @param file The {@link File} to read. + * @return The root of the model. + * @throws ParserConfigurationException Occurred Exception. + * @throws SAXException Occurred Exception. + * @throws IOException Occurred Exception. + */ + public ISymbolicLayout read(File file) + throws ParserConfigurationException, SAXException, IOException { + return read(new FileInputStream(file)); + } + + /** + * Reads from the given {@link InputStream} and closes it. + * + * @param in The {@link InputStream} to read from. + * @return The root of the model. + * @throws ParserConfigurationException Occurred Exception. + * @throws SAXException Occurred Exception. + * @throws IOException Occurred Exception. + */ + public ISymbolicLayout read(InputStream in) + throws ParserConfigurationException, SAXException, IOException { + if (in != null) { + try { + // Parse XML file + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setNamespaceAware(true); + SAXParser saxParser = factory.newSAXParser(); + SEDSAXHandler handler = new SEDSAXHandler(); + saxParser.parse(in, handler); + // Get root + ISymbolicLayout root = handler.getRoot(); + // Return result + return root; + } finally { + in.close(); } - ((KeYlessLayout)parent).setState(state); - parentStack.addFirst(state); - } - else if (isObject(uri, localName, qName)) { - if (!(parent instanceof KeYlessLayout)) { - throw new SAXException("Found object in wrong hierarchy."); + } else { + return null; + } + } + + /** + * {@link DefaultHandler} implementation used in {@link ExecutionNodeReader#read(InputStream)}. + * + * @author Martin Hentschel + */ + private class SEDSAXHandler extends DefaultHandler { + /** + * The root of the model. + */ + private ISymbolicLayout root; + + /** + * The hierarchy in building phase. + */ + private Deque parentStack = new LinkedList(); + + /** + * Maps each unique object ID to the instantiated {@link ISymbolicObject}. + */ + private Map objectIdMapping = + new LinkedHashMap(); + + /** + * Maps a {@link KeYlessAssociation} to its target object ID. + */ + private Map associationTargetMapping = + new LinkedHashMap(); + + /** + * {@inheritDoc} + */ + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { + Object parent = parentStack.peekFirst(); + if (isModel(uri, localName, qName)) { + if (root == null) { + root = new KeYlessLayout(); + parentStack.addFirst(root); + } else { + throw new SAXException("Model found a second time."); + } + } else if (isState(uri, localName, qName)) { + if (!(parent instanceof KeYlessLayout)) { + throw new SAXException("Found state in wrong hierarchy."); + } + KeYlessState state = new KeYlessState(getName(attributes)); + if (((KeYlessLayout) parent).getState() != null) { + throw new SAXException("State found a second time."); + } + ((KeYlessLayout) parent).setState(state); + parentStack.addFirst(state); + } else if (isObject(uri, localName, qName)) { + if (!(parent instanceof KeYlessLayout)) { + throw new SAXException("Found object in wrong hierarchy."); + } + KeYlessObject object = + new KeYlessObject(getName(attributes), getTypeString(attributes)); + ((KeYlessLayout) parent).addObject(object); + parentStack.addFirst(object); + objectIdMapping.put(getId(attributes), object); + } else if (isValue(uri, localName, qName)) { + if (!(parent instanceof AbstractKeYlessAssociationValueContainer)) { + throw new SAXException("Found value in wrong hierarchy."); + } + KeYlessValue value = new KeYlessValue(getName(attributes), + getProgramVariableString(attributes), isArrayIndex(attributes), + getArrayIndexString(attributes), getValueString(attributes), + getTypeString(attributes), getConditionString(attributes)); + ((AbstractKeYlessAssociationValueContainer) parent).addValue(value); + parentStack.addFirst(value); + } else if (isAssociation(uri, localName, qName)) { + if (!(parent instanceof AbstractKeYlessAssociationValueContainer)) { + throw new SAXException("Found association in wrong hierarchy."); + } + KeYlessAssociation association = new KeYlessAssociation(getName(attributes), + getProgramVariableString(attributes), isArrayIndex(attributes), + getArrayIndexString(attributes), getConditionString(attributes)); + ((AbstractKeYlessAssociationValueContainer) parent).addAssociation(association); + parentStack.addFirst(association); + associationTargetMapping.put(association, getTarget(attributes)); + } else if (isEquivalenceClass(uri, localName, qName)) { + if (!(parent instanceof KeYlessLayout)) { + throw new SAXException("Found equivalence class in wrong hierarchy."); + } + KeYlessEquivalenceClass ec = + new KeYlessEquivalenceClass(getRepresentativeTerm(attributes)); + ((KeYlessLayout) parent).addEquivalenceClass(ec); + parentStack.addFirst(ec); + } else if (isTerm(uri, localName, qName)) { + if (!(parent instanceof ISymbolicEquivalenceClass)) { + throw new SAXException("Found term in wrong hierarchy."); + } + ((KeYlessEquivalenceClass) parent).addTermString(getTerm(attributes)); + } else { + throw new SAXException("Unsupported tag \"" + localName + "\"."); } - KeYlessObject object = new KeYlessObject(getName(attributes), getTypeString(attributes)); - ((KeYlessLayout)parent).addObject(object); - parentStack.addFirst(object); - objectIdMapping.put(getId(attributes), object); - } - else if (isValue(uri, localName, qName)) { - if (!(parent instanceof AbstractKeYlessAssociationValueContainer)) { - throw new SAXException("Found value in wrong hierarchy."); + } + + /** + * {@inheritDoc} + */ + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + if (!isTerm(uri, localName, qName)) { + parentStack.removeFirst(); } - KeYlessValue value = new KeYlessValue(getName(attributes), getProgramVariableString(attributes), isArrayIndex(attributes), getArrayIndexString(attributes), getValueString(attributes), getTypeString(attributes), getConditionString(attributes)); - ((AbstractKeYlessAssociationValueContainer)parent).addValue(value); - parentStack.addFirst(value); - } - else if (isAssociation(uri, localName, qName)) { - if (!(parent instanceof AbstractKeYlessAssociationValueContainer)) { - throw new SAXException("Found association in wrong hierarchy."); + } + + /** + * {@inheritDoc} + */ + @Override + public void endDocument() throws SAXException { + // Fill associations with target references + for (Entry entry : associationTargetMapping.entrySet()) { + ISymbolicObject target = objectIdMapping.get(entry.getValue()); + if (target == null) { + throw new SAXException("Association target object with id \"" + entry.getValue() + + "\" is not available."); + } + entry.getKey().setTarget(target); } - KeYlessAssociation association = new KeYlessAssociation(getName(attributes), getProgramVariableString(attributes), isArrayIndex(attributes), getArrayIndexString(attributes), getConditionString(attributes)); - ((AbstractKeYlessAssociationValueContainer)parent).addAssociation(association); - parentStack.addFirst(association); - associationTargetMapping.put(association, getTarget(attributes)); - } - else if (isEquivalenceClass(uri, localName, qName)) { - if (!(parent instanceof KeYlessLayout)) { - throw new SAXException("Found equivalence class in wrong hierarchy."); - } - KeYlessEquivalenceClass ec = new KeYlessEquivalenceClass(getRepresentativeTerm(attributes)); - ((KeYlessLayout)parent).addEquivalenceClass(ec); - parentStack.addFirst(ec); - } - else if (isTerm(uri, localName, qName)) { - if (!(parent instanceof ISymbolicEquivalenceClass)) { - throw new SAXException("Found term in wrong hierarchy."); - } - ((KeYlessEquivalenceClass)parent).addTermString(getTerm(attributes)); - } - else { - throw new SAXException("Unsupported tag \"" + localName + "\"."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void endElement(String uri, String localName, String qName) throws SAXException { - if (!isTerm(uri, localName, qName)) { - parentStack.removeFirst(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void endDocument() throws SAXException { - // Fill associations with target references - for (Entry entry : associationTargetMapping.entrySet()) { - ISymbolicObject target = objectIdMapping.get(entry.getValue()); - if (target == null) { - throw new SAXException("Association target object with id \"" + entry.getValue() + "\" is not available."); - } - entry.getKey().setTarget(target); - } - } - - /** - * Returns the root of the model. - * @return The root of the model. - */ - public ISymbolicLayout getRoot() { - return root; - } - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicLayout}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicLayout}, {@code false} is something else. - */ - protected boolean isModel(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_MODEL.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicAssociation}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicAssociation}, {@code false} is something else. - */ - protected boolean isAssociation(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_ASSOCIATION.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicValue}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicValue}, {@code false} is something else. - */ - protected boolean isValue(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_VALUE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicObject}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicObject}, {@code false} is something else. - */ - protected boolean isObject(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_OBJECT.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicState}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicState}, {@code false} is something else. - */ - protected boolean isState(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_STATE.equals(qName); - } - - /** - * Checks if the currently parsed tag represents an {@link ISymbolicEquivalenceClass}. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents an {@link ISymbolicEquivalenceClass}, {@code false} is something else. - */ - protected boolean isEquivalenceClass(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_EQUIVALENCE_CLASS.equals(qName); - } - - /** - * Checks if the currently parsed tag represents a term. - * @param uri The URI. - * @param localName THe local name. - * @param qName The qName. - * @return {@code true} represents a term, {@code false} is something else. - */ - protected boolean isTerm(String uri, String localName, String qName) { - return SymbolicLayoutWriter.TAG_TERM.equals(qName); - } - - /** - * Returns the value value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getValueString(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_VALUE); - } - - /** - * Returns the condition value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getConditionString(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_CONDITION); - } - - /** - * Returns the type value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getTypeString(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TYPE); - } - - /** - * Returns the program variable value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getProgramVariableString(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_PROGRAM_VARIABLE); - } - - /** - * Returns the name value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getName(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_NAME); - } - - /** - * Returns the array index value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getArrayIndexString(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_ARRAY_INDEX); - } - - /** - * Returns the is array index flag. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected boolean isArrayIndex(Attributes attributes) { - return Boolean.parseBoolean(attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_IS_ARRAY_INDEX)); - } - - /** - * Returns the ID value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getId(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_XML_ID); - } - - /** - * Returns the target value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getTarget(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TARGET); - } - - /** - * Returns the representative term value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getRepresentativeTerm(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_REPRESENTATIVE); - } - - /** - * Returns the term value. - * @param attributes The {@link Attributes} which provides the content. - * @return The value. - */ - protected String getTerm(Attributes attributes) { - return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TERM); - } - - - /** - * An implementation of {@link ISymbolicElement} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessElement implements ISymbolicElement { - /** - * {@inheritDoc} - */ - @Override - public IModelSettings getSettings() { - return null; - } - } - - /** - * An implementation of {@link ISymbolicLayout} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessLayout extends AbstractKeYlessElement implements ISymbolicLayout { - /** - * The state. - */ - private ISymbolicState state; - - /** - * The objects. - */ - private ImmutableList objects = ImmutableSLList.nil(); - - /** - * The symbolic equivalence classes. - */ - private ImmutableList equivalenceClasses = ImmutableSLList.nil(); - - /** - * {@inheritDoc} - */ - - @Override - public ISymbolicState getState() { - return state; - } - - /** - * Sets the state. - * @param state The state to set. - */ - public void setState(ISymbolicState state) { - this.state = state; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getObjects() { - return objects; - } - - /** - * Add a new child {@link ISymbolicObject}. - * @param object The {@link ISymbolicObject} to add. - */ - public void addObject(ISymbolicObject object) { - objects = objects.append(object); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getEquivalenceClasses() { - return equivalenceClasses; - } - - /** - * Add a new child {@link ISymbolicEquivalenceClass}. - * @param object The {@link ISymbolicEquivalenceClass} to add. - */ - public void addEquivalenceClass(ISymbolicEquivalenceClass ec) { - equivalenceClasses = equivalenceClasses.append(ec); - } - } - - /** - * An implementation of {@link ISymbolicAssociationValueContainer} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static abstract class AbstractKeYlessAssociationValueContainer extends AbstractKeYlessElement implements ISymbolicAssociationValueContainer { - /** - * The associations. - */ - private ImmutableList associations = ImmutableSLList.nil(); - - /** - * The values. - */ - private ImmutableList values = ImmutableSLList.nil(); - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getAssociations() { - return associations; - } - - /** - * Adds a new child {@link ISymbolicAssociation} - * @param association The {@link ISymbolicAssociation} to add. - */ - public void addAssociation(ISymbolicAssociation association) { - associations = associations.append(association); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getValues() { - return values; - } - - /** - * Adds a new child {@link ISymbolicValue}. - * @param value The value to add. - */ - public void addValue(ISymbolicValue value) { - values = values.append(value); - } - } - - /** - * An implementation of {@link ISymbolicState} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessState extends AbstractKeYlessAssociationValueContainer implements ISymbolicState { - /** - * The name. - */ - private String name; - - /** - * Constructor. - * @param name The name. - */ - public KeYlessState(String name) { - super(); - this.name = name; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return name; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicAssociation getAssociation(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicValue getValue(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition) { - return null; - } - } - - /** - * An implementation of {@link ISymbolicObject} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessObject extends AbstractKeYlessAssociationValueContainer implements ISymbolicObject { - /** - * The name. - */ - private String nameString; - - /** - * The type. - */ - private String typeString; - - /** - * Constructor. - * @param nameString The name. - * @param typeString The type. - */ - public KeYlessObject(String nameString, String typeString) { - super(); - this.nameString = nameString; - this.typeString = typeString; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Object " + getNameString(); - } - - /** - * {@inheritDoc} - */ - @Override - public Term getName() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getNameString() { - return nameString; - } - - /** - * {@inheritDoc} - */ - @Override - public Sort getType() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() { - return typeString; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicAssociation getAssociation(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicValue getValue(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition) { - return null; - } - } - - /** - * An implementation of {@link ISymbolicValue} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessValue extends AbstractKeYlessElement implements ISymbolicValue { - /** - * The program variable. - */ - private String programVariableString; - - /** - * The value. - */ - private String valueString; - - /** - * The type. - */ - private String typeString; - - /** - * The name. - */ - private String name; - - /** - * The is array index flag. - */ - private boolean isArrayIndex; - - /** - * The array index. - */ - private String arrayIndexString; - - /** - * The optional condition under which this value is valid. - */ - private String conditionString; - - /** - * Constructor. - * @param name The name. - * @param programVariableString The program variable. - * @param isArrayIndex The is array index flag. - * @param arrayIndexString The array index. - * @param valueString The value. - * @param typeString The type. - * @param conditionString The optional condition under which this value is valid. - */ - public KeYlessValue(String name, String programVariableString, boolean isArrayIndex, String arrayIndexString, String valueString, String typeString, String conditionString) { - super(); - this.name = name; - this.programVariableString = programVariableString; - this.isArrayIndex = isArrayIndex; - this.arrayIndexString = arrayIndexString; - this.valueString = valueString; - this.typeString = typeString; - this.conditionString = conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Value of " + getName() + " is " + getValueString(); - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getProgramVariableString() { - return programVariableString; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getValue() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getValueString() { - return valueString; - } - - /** - * {@inheritDoc} - */ - @Override - public Sort getType() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() { - return typeString; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return name; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isArrayIndex() { - return isArrayIndex; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndexString; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() { - return conditionString; - } - } - - /** - * An implementation of {@link ISymbolicAssociation} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessAssociation extends AbstractKeYlessElement implements ISymbolicAssociation { - /** - * The program variable. - */ - private String programVariableString; - - /** - * The target. - */ - private ISymbolicObject target; - - /** - * The name. - */ - private String name; - - /** - * The is array index flag. - */ - private boolean isArrayIndex; - - /** - * The array index. - */ - private String arrayIndexString; - - /** - * The optional condition under which this association is valid. - */ - private String conditionString; - - /** - * Constructor. - * @param name The name. - * @param programVariableString The program variable. - * @param isArrayIndex The is array index flag. - * @param arrayIndexString The array index. - * @param conditionString The optional condition under which this association is valid. - */ - public KeYlessAssociation(String name, String programVariableString, boolean isArrayIndex, String arrayIndexString, String conditionString) { - this(name, programVariableString, isArrayIndex, arrayIndexString, null, conditionString); - } - - /** - * Constructor. - * @param name The name. - * @param programVariableString The program variable. - * @param isArrayIndex The is array index flag. - * @param arrayIndexString The array index. - * @param target The target. - * @param conditionString The optional condition under which this association is valid. - */ - public KeYlessAssociation(String name, String programVariableString, boolean isArrayIndex, String arrayIndexString, ISymbolicObject target, String conditionString) { - super(); - this.name = name; - this.programVariableString = programVariableString; - this.isArrayIndex = isArrayIndex; - this.arrayIndexString = arrayIndexString; - this.target = target; - this.conditionString = conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Association " + getName() + " to " + getTarget(); - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getProgramVariableString() { - return programVariableString; - } - - /** - * Sets the target. - * @param target The target to set. - */ - public void setTarget(ISymbolicObject target) { - this.target = target; - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicObject getTarget() { - return target; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return name; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isArrayIndex() { - return isArrayIndex; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndexString; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() { - return conditionString; - } - } - - /** - * An implementation of {@link ISymbolicEquivalenceClass} which is independent - * from KeY and provides such only children and default attributes. - * @author Martin Hentschel - */ - public static class KeYlessEquivalenceClass extends AbstractKeYlessElement implements ISymbolicEquivalenceClass { - /** - * The terms. - */ - private ImmutableList termStrings; - - /** - * The representative term. - */ - private String representativeString; - - /** - * Constructor. - * @param representativeString The representative term. - */ - public KeYlessEquivalenceClass(String representativeString) { - this(ImmutableSLList.nil(), representativeString); - } - - /** - * Constructor. - * @param termStrings The terms. - * @param representativeString The representative term. - */ - public KeYlessEquivalenceClass(ImmutableList termStrings, String representativeString) { - this.termStrings = termStrings; - this.representativeString = representativeString; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTerms() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTermStrings() { - return termStrings; - } - - /** - * Add a new child term string. - * @param object The term string to add. - */ - public void addTermString(String termString) { - this.termStrings = termStrings.append(termString); - } - - /** - * {@inheritDoc} - */ - @Override - public Term getRepresentative() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getRepresentativeString() { - return representativeString; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsTerm(Term term) { - return false; - } - } -} \ No newline at end of file + } + + /** + * Returns the root of the model. + * + * @return The root of the model. + */ + public ISymbolicLayout getRoot() { + return root; + } + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicLayout}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicLayout}, {@code false} is something else. + */ + protected boolean isModel(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_MODEL.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicAssociation}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicAssociation}, {@code false} is something + * else. + */ + protected boolean isAssociation(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_ASSOCIATION.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicValue}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicValue}, {@code false} is something else. + */ + protected boolean isValue(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_VALUE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicObject}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicObject}, {@code false} is something else. + */ + protected boolean isObject(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_OBJECT.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicState}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicState}, {@code false} is something else. + */ + protected boolean isState(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_STATE.equals(qName); + } + + /** + * Checks if the currently parsed tag represents an {@link ISymbolicEquivalenceClass}. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents an {@link ISymbolicEquivalenceClass}, {@code false} is + * something else. + */ + protected boolean isEquivalenceClass(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_EQUIVALENCE_CLASS.equals(qName); + } + + /** + * Checks if the currently parsed tag represents a term. + * + * @param uri The URI. + * @param localName THe local name. + * @param qName The qName. + * @return {@code true} represents a term, {@code false} is something else. + */ + protected boolean isTerm(String uri, String localName, String qName) { + return SymbolicLayoutWriter.TAG_TERM.equals(qName); + } + + /** + * Returns the value value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getValueString(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_VALUE); + } + + /** + * Returns the condition value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getConditionString(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_CONDITION); + } + + /** + * Returns the type value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getTypeString(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TYPE); + } + + /** + * Returns the program variable value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getProgramVariableString(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_PROGRAM_VARIABLE); + } + + /** + * Returns the name value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getName(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_NAME); + } + + /** + * Returns the array index value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getArrayIndexString(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_ARRAY_INDEX); + } + + /** + * Returns the is array index flag. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected boolean isArrayIndex(Attributes attributes) { + return Boolean + .parseBoolean(attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_IS_ARRAY_INDEX)); + } + + /** + * Returns the ID value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getId(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_XML_ID); + } + + /** + * Returns the target value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getTarget(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TARGET); + } + + /** + * Returns the representative term value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getRepresentativeTerm(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_REPRESENTATIVE); + } + + /** + * Returns the term value. + * + * @param attributes The {@link Attributes} which provides the content. + * @return The value. + */ + protected String getTerm(Attributes attributes) { + return attributes.getValue(SymbolicLayoutWriter.ATTRIBUTE_TERM); + } + + + /** + * An implementation of {@link ISymbolicElement} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessElement implements ISymbolicElement { + /** + * {@inheritDoc} + */ + @Override + public IModelSettings getSettings() { + return null; + } + } + + /** + * An implementation of {@link ISymbolicLayout} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessLayout extends AbstractKeYlessElement implements ISymbolicLayout { + /** + * The state. + */ + private ISymbolicState state; + + /** + * The objects. + */ + private ImmutableList objects = ImmutableSLList.nil(); + + /** + * The symbolic equivalence classes. + */ + private ImmutableList equivalenceClasses = ImmutableSLList.nil(); + + /** + * {@inheritDoc} + */ + + @Override + public ISymbolicState getState() { + return state; + } + + /** + * Sets the state. + * + * @param state The state to set. + */ + public void setState(ISymbolicState state) { + this.state = state; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getObjects() { + return objects; + } + + /** + * Add a new child {@link ISymbolicObject}. + * + * @param object The {@link ISymbolicObject} to add. + */ + public void addObject(ISymbolicObject object) { + objects = objects.append(object); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getEquivalenceClasses() { + return equivalenceClasses; + } + + /** + * Add a new child {@link ISymbolicEquivalenceClass}. + * + * @param object The {@link ISymbolicEquivalenceClass} to add. + */ + public void addEquivalenceClass(ISymbolicEquivalenceClass ec) { + equivalenceClasses = equivalenceClasses.append(ec); + } + } + + /** + * An implementation of {@link ISymbolicAssociationValueContainer} which is independent from KeY + * and provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static abstract class AbstractKeYlessAssociationValueContainer + extends AbstractKeYlessElement implements ISymbolicAssociationValueContainer { + /** + * The associations. + */ + private ImmutableList associations = ImmutableSLList.nil(); + + /** + * The values. + */ + private ImmutableList values = ImmutableSLList.nil(); + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getAssociations() { + return associations; + } + + /** + * Adds a new child {@link ISymbolicAssociation} + * + * @param association The {@link ISymbolicAssociation} to add. + */ + public void addAssociation(ISymbolicAssociation association) { + associations = associations.append(association); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getValues() { + return values; + } + + /** + * Adds a new child {@link ISymbolicValue}. + * + * @param value The value to add. + */ + public void addValue(ISymbolicValue value) { + values = values.append(value); + } + } + + /** + * An implementation of {@link ISymbolicState} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessState extends AbstractKeYlessAssociationValueContainer + implements ISymbolicState { + /** + * The name. + */ + private String name; + + /** + * Constructor. + * + * @param name The name. + */ + public KeYlessState(String name) { + super(); + this.name = name; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicAssociation getAssociation(IProgramVariable programVariable, + boolean isArrayIndex, Term arrayIndex, Term condition) { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicValue getValue(IProgramVariable programVariable, boolean isArrayIndex, + Term arrayIndex, Term condition) { + return null; + } + } + + /** + * An implementation of {@link ISymbolicObject} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessObject extends AbstractKeYlessAssociationValueContainer + implements ISymbolicObject { + /** + * The name. + */ + private String nameString; + + /** + * The type. + */ + private String typeString; + + /** + * Constructor. + * + * @param nameString The name. + * @param typeString The type. + */ + public KeYlessObject(String nameString, String typeString) { + super(); + this.nameString = nameString; + this.typeString = typeString; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Object " + getNameString(); + } + + /** + * {@inheritDoc} + */ + @Override + public Term getName() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getNameString() { + return nameString; + } + + /** + * {@inheritDoc} + */ + @Override + public Sort getType() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() { + return typeString; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicAssociation getAssociation(IProgramVariable programVariable, + boolean isArrayIndex, Term arrayIndex, Term condition) { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicValue getValue(IProgramVariable programVariable, boolean isArrayIndex, + Term arrayIndex, Term condition) { + return null; + } + } + + /** + * An implementation of {@link ISymbolicValue} which is independent from KeY and provides such + * only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessValue extends AbstractKeYlessElement implements ISymbolicValue { + /** + * The program variable. + */ + private String programVariableString; + + /** + * The value. + */ + private String valueString; + + /** + * The type. + */ + private String typeString; + + /** + * The name. + */ + private String name; + + /** + * The is array index flag. + */ + private boolean isArrayIndex; + + /** + * The array index. + */ + private String arrayIndexString; + + /** + * The optional condition under which this value is valid. + */ + private String conditionString; + + /** + * Constructor. + * + * @param name The name. + * @param programVariableString The program variable. + * @param isArrayIndex The is array index flag. + * @param arrayIndexString The array index. + * @param valueString The value. + * @param typeString The type. + * @param conditionString The optional condition under which this value is valid. + */ + public KeYlessValue(String name, String programVariableString, boolean isArrayIndex, + String arrayIndexString, String valueString, String typeString, + String conditionString) { + super(); + this.name = name; + this.programVariableString = programVariableString; + this.isArrayIndex = isArrayIndex; + this.arrayIndexString = arrayIndexString; + this.valueString = valueString; + this.typeString = typeString; + this.conditionString = conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Value of " + getName() + " is " + getValueString(); + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getProgramVariableString() { + return programVariableString; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getValue() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getValueString() { + return valueString; + } + + /** + * {@inheritDoc} + */ + @Override + public Sort getType() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() { + return typeString; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isArrayIndex() { + return isArrayIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndexString; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() { + return conditionString; + } + } + + /** + * An implementation of {@link ISymbolicAssociation} which is independent from KeY and provides + * such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessAssociation extends AbstractKeYlessElement + implements ISymbolicAssociation { + /** + * The program variable. + */ + private String programVariableString; + + /** + * The target. + */ + private ISymbolicObject target; + + /** + * The name. + */ + private String name; + + /** + * The is array index flag. + */ + private boolean isArrayIndex; + + /** + * The array index. + */ + private String arrayIndexString; + + /** + * The optional condition under which this association is valid. + */ + private String conditionString; + + /** + * Constructor. + * + * @param name The name. + * @param programVariableString The program variable. + * @param isArrayIndex The is array index flag. + * @param arrayIndexString The array index. + * @param conditionString The optional condition under which this association is valid. + */ + public KeYlessAssociation(String name, String programVariableString, boolean isArrayIndex, + String arrayIndexString, String conditionString) { + this(name, programVariableString, isArrayIndex, arrayIndexString, null, + conditionString); + } + + /** + * Constructor. + * + * @param name The name. + * @param programVariableString The program variable. + * @param isArrayIndex The is array index flag. + * @param arrayIndexString The array index. + * @param target The target. + * @param conditionString The optional condition under which this association is valid. + */ + public KeYlessAssociation(String name, String programVariableString, boolean isArrayIndex, + String arrayIndexString, ISymbolicObject target, String conditionString) { + super(); + this.name = name; + this.programVariableString = programVariableString; + this.isArrayIndex = isArrayIndex; + this.arrayIndexString = arrayIndexString; + this.target = target; + this.conditionString = conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Association " + getName() + " to " + getTarget(); + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getProgramVariableString() { + return programVariableString; + } + + /** + * Sets the target. + * + * @param target The target to set. + */ + public void setTarget(ISymbolicObject target) { + this.target = target; + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicObject getTarget() { + return target; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isArrayIndex() { + return isArrayIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndexString; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() { + return conditionString; + } + } + + /** + * An implementation of {@link ISymbolicEquivalenceClass} which is independent from KeY and + * provides such only children and default attributes. + * + * @author Martin Hentschel + */ + public static class KeYlessEquivalenceClass extends AbstractKeYlessElement + implements ISymbolicEquivalenceClass { + /** + * The terms. + */ + private ImmutableList termStrings; + + /** + * The representative term. + */ + private String representativeString; + + /** + * Constructor. + * + * @param representativeString The representative term. + */ + public KeYlessEquivalenceClass(String representativeString) { + this(ImmutableSLList.nil(), representativeString); + } + + /** + * Constructor. + * + * @param termStrings The terms. + * @param representativeString The representative term. + */ + public KeYlessEquivalenceClass(ImmutableList termStrings, + String representativeString) { + this.termStrings = termStrings; + this.representativeString = representativeString; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTerms() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTermStrings() { + return termStrings; + } + + /** + * Add a new child term string. + * + * @param object The term string to add. + */ + public void addTermString(String termString) { + this.termStrings = termStrings.append(termString); + } + + /** + * {@inheritDoc} + */ + @Override + public Term getRepresentative() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getRepresentativeString() { + return representativeString; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsTerm(Term term) { + return false; + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutWriter.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutWriter.java index 7f0af33776e..5a2108154f9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutWriter.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/SymbolicLayoutWriter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.io.File; @@ -17,287 +20,302 @@ import de.uka.ilkd.key.util.LinkedHashMap; /** - * Allows to persistent selected properties of {@link ISymbolicLayout}s - * as XML file. Such files can be read via a {@link SymbolicLayoutReader} instance. + * Allows to persistent selected properties of {@link ISymbolicLayout}s as XML file. Such files can + * be read via a {@link SymbolicLayoutReader} instance. + * * @author Martin Hentschel * @see SymbolicLayoutReader */ public class SymbolicLayoutWriter extends AbstractWriter { - /** - * Tag name to store {@link ISymbolicLayout}s. - */ - public static final String TAG_MODEL = "model"; - - /** - * Tag name to store {@link ISymbolicState}s. - */ - public static final String TAG_STATE = "state"; + /** + * Tag name to store {@link ISymbolicLayout}s. + */ + public static final String TAG_MODEL = "model"; - /** - * Tag name to store {@link ISymbolicObject}s. - */ - public static final String TAG_OBJECT = "object"; + /** + * Tag name to store {@link ISymbolicState}s. + */ + public static final String TAG_STATE = "state"; - /** - * Tag name to store {@link ISymbolicValue}s. - */ - public static final String TAG_VALUE = "value"; + /** + * Tag name to store {@link ISymbolicObject}s. + */ + public static final String TAG_OBJECT = "object"; - /** - * Tag name to store {@link ISymbolicAssociation}s. - */ - public static final String TAG_ASSOCIATION = "association"; + /** + * Tag name to store {@link ISymbolicValue}s. + */ + public static final String TAG_VALUE = "value"; - /** - * Tag name to store {@link ISymbolicEquivalenceClass}s. - */ - public static final String TAG_EQUIVALENCE_CLASS = "equivalenceClass"; + /** + * Tag name to store {@link ISymbolicAssociation}s. + */ + public static final String TAG_ASSOCIATION = "association"; - /** - * Tag name to store entries of {@link ISymbolicEquivalenceClass#getTerms()}s. - */ - public static final String TAG_TERM = "term"; + /** + * Tag name to store {@link ISymbolicEquivalenceClass}s. + */ + public static final String TAG_EQUIVALENCE_CLASS = "equivalenceClass"; - /** - * Attribute name to store {@link ISymbolicObject#getNameString()}. - */ - public static final String ATTRIBUTE_NAME = "name"; + /** + * Tag name to store entries of {@link ISymbolicEquivalenceClass#getTerms()}s. + */ + public static final String TAG_TERM = "term"; - /** - * Attribute name to store {@link ISymbolicValue#getProgramVariableString()} - * and {@link ISymbolicAssociation#getProgramVariableString()}. - */ - public static final String ATTRIBUTE_PROGRAM_VARIABLE = "programVariable"; + /** + * Attribute name to store {@link ISymbolicObject#getNameString()}. + */ + public static final String ATTRIBUTE_NAME = "name"; - /** - * Attribute name to store {@link ISymbolicValue#getValueString()}. - */ - public static final String ATTRIBUTE_VALUE = "value"; + /** + * Attribute name to store {@link ISymbolicValue#getProgramVariableString()} and + * {@link ISymbolicAssociation#getProgramVariableString()}. + */ + public static final String ATTRIBUTE_PROGRAM_VARIABLE = "programVariable"; - /** - * Attribute name to store {@link ISymbolicValue#getConditionString()} and - * {@link ISymbolicAssociation#getConditionString()}. - */ - public static final String ATTRIBUTE_CONDITION = "condition"; + /** + * Attribute name to store {@link ISymbolicValue#getValueString()}. + */ + public static final String ATTRIBUTE_VALUE = "value"; - /** - * Attribute name to store {@link ISymbolicAssociation#getTarget()}. - */ - public static final String ATTRIBUTE_TARGET = "target"; + /** + * Attribute name to store {@link ISymbolicValue#getConditionString()} and + * {@link ISymbolicAssociation#getConditionString()}. + */ + public static final String ATTRIBUTE_CONDITION = "condition"; - /** - * Attribute name to store an entry of {@link ISymbolicEquivalenceClass#getTermStrings()} - */ - public static final String ATTRIBUTE_TERM = "term"; + /** + * Attribute name to store {@link ISymbolicAssociation#getTarget()}. + */ + public static final String ATTRIBUTE_TARGET = "target"; - /** - * Attribute name to store {@link ISymbolicEquivalenceClass#getRepresentativeString()}. - */ - public static final String ATTRIBUTE_REPRESENTATIVE = "representativeTerm"; + /** + * Attribute name to store an entry of {@link ISymbolicEquivalenceClass#getTermStrings()} + */ + public static final String ATTRIBUTE_TERM = "term"; - /** - * Attribute name to store {@link ISymbolicValue#getTypeString()} and - * {@link ISymbolicObject#getTypeString()}. - */ - public static final String ATTRIBUTE_TYPE = "type"; + /** + * Attribute name to store {@link ISymbolicEquivalenceClass#getRepresentativeString()}. + */ + public static final String ATTRIBUTE_REPRESENTATIVE = "representativeTerm"; - /** - * Attribute name to store {@link ISymbolicValue#isArrayIndex()} and - * {@link ISymbolicAssociation#getArrayIndexString()}. - */ - public static final String ATTRIBUTE_IS_ARRAY_INDEX = "isArrayIndex"; + /** + * Attribute name to store {@link ISymbolicValue#getTypeString()} and + * {@link ISymbolicObject#getTypeString()}. + */ + public static final String ATTRIBUTE_TYPE = "type"; - /** - * Attribute name to store {@link ISymbolicValue#getArrayIndexString()} and - * {@link ISymbolicAssociation#getArrayIndexString()}. - */ - public static final String ATTRIBUTE_ARRAY_INDEX = "arrayIndex"; + /** + * Attribute name to store {@link ISymbolicValue#isArrayIndex()} and + * {@link ISymbolicAssociation#getArrayIndexString()}. + */ + public static final String ATTRIBUTE_IS_ARRAY_INDEX = "isArrayIndex"; - /** - * Writes the given {@link ISymbolicLayout} as XML file. - * @param model The {@link ISymbolicLayout} to save. - * @param encoding The encoding to use. - * @param file The {@link File} to save to. - * @throws IOException Occurred Exception. - */ - public void write(ISymbolicLayout model, - String encoding, - File file) throws IOException { - write(model, encoding, new FileOutputStream(file)); - } - - /** - * Writes the given {@link ISymbolicLayout} into the {@link OutputStream}. - * @param node The {@link ISymbolicLayout} to save. - * @param encoding The encoding to use. - * @param out The {@link OutputStream} to save to. The {@link OutputStream} will be closed by this method. - * @throws IOException Occurred Exception. - */ - public void write(ISymbolicLayout model, - String encoding, - OutputStream out) throws IOException { - if (out != null) { - try { - Charset charset = encoding != null ? Charset.forName(encoding) : Charset.defaultCharset(); - String xml = toXML(model, charset.displayName()); - out.write(xml.getBytes(charset)); - } - finally { - out.close(); - } - } - } - - /** - * Converts the given {@link ISymbolicLayout} into XML. - * @param node The {@link ISymbolicLayout} to convert. - * @param encoding The encoding to use. - * @return The created XML content. - */ - public String toXML(ISymbolicLayout model, - String encoding){ - StringBuffer sb = new StringBuffer(); - appendXmlHeader(encoding, sb); - appendModel(0, model, sb); - return sb.toString(); - } + /** + * Attribute name to store {@link ISymbolicValue#getArrayIndexString()} and + * {@link ISymbolicAssociation#getArrayIndexString()}. + */ + public static final String ATTRIBUTE_ARRAY_INDEX = "arrayIndex"; - /** - * Appends the given {@link ISymbolicLayout} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param model The {@link ISymbolicLayout} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendModel(int level, ISymbolicLayout model, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - appendStartTag(level, TAG_MODEL, attributeValues, sb); - for (ISymbolicEquivalenceClass ec : model.getEquivalenceClasses()) { - appendEquivalenceClass(level + 1, ec, sb); - } - appendState(level + 1, model, model.getState(), sb); - for (ISymbolicObject object : model.getObjects()) { - appendObject(level + 1, model, object, sb); - } - appendEndTag(level, TAG_MODEL, sb); - } + /** + * Writes the given {@link ISymbolicLayout} as XML file. + * + * @param model The {@link ISymbolicLayout} to save. + * @param encoding The encoding to use. + * @param file The {@link File} to save to. + * @throws IOException Occurred Exception. + */ + public void write(ISymbolicLayout model, String encoding, File file) throws IOException { + write(model, encoding, new FileOutputStream(file)); + } - /** - * Appends the given {@link ISymbolicEquivalenceClass} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param ec The {@link ISymbolicEquivalenceClass} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendEquivalenceClass(int level, ISymbolicEquivalenceClass ec, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_REPRESENTATIVE, ec.getRepresentativeString()); - appendStartTag(level, TAG_EQUIVALENCE_CLASS, attributeValues, sb); - for (String term : ec.getTermStrings()) { - Map termAttributeValues = new LinkedHashMap(); - termAttributeValues.put(ATTRIBUTE_TERM, term); - appendEmptyTag(level + 1, TAG_TERM, termAttributeValues, sb); - } - appendEndTag(level, TAG_EQUIVALENCE_CLASS, sb); - } + /** + * Writes the given {@link ISymbolicLayout} into the {@link OutputStream}. + * + * @param node The {@link ISymbolicLayout} to save. + * @param encoding The encoding to use. + * @param out The {@link OutputStream} to save to. The {@link OutputStream} will be closed by + * this method. + * @throws IOException Occurred Exception. + */ + public void write(ISymbolicLayout model, String encoding, OutputStream out) throws IOException { + if (out != null) { + try { + Charset charset = + encoding != null ? Charset.forName(encoding) : Charset.defaultCharset(); + String xml = toXML(model, charset.displayName()); + out.write(xml.getBytes(charset)); + } finally { + out.close(); + } + } + } - /** - * Appends the given {@link ISymbolicState} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param model The {@link ISymbolicLayout} which provides all objects. - * @param state The {@link ISymbolicState} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendState(int level, ISymbolicLayout model, ISymbolicState state, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, state.getName()); - appendStartTag(level, TAG_STATE, attributeValues, sb); - for (ISymbolicValue value : state.getValues()) { - appendValue(level + 1, value, sb); - } - for (ISymbolicAssociation association : state.getAssociations()) { - appendAssociation(level + 1, model, association, sb); - } - appendEndTag(level, TAG_STATE, sb); - } + /** + * Converts the given {@link ISymbolicLayout} into XML. + * + * @param node The {@link ISymbolicLayout} to convert. + * @param encoding The encoding to use. + * @return The created XML content. + */ + public String toXML(ISymbolicLayout model, String encoding) { + StringBuffer sb = new StringBuffer(); + appendXmlHeader(encoding, sb); + appendModel(0, model, sb); + return sb.toString(); + } - /** - * Appends the given {@link ISymbolicObject} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param model The {@link ISymbolicLayout} which provides all objects. - * @param object The {@link ISymbolicObject} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendObject(int level, ISymbolicLayout model, ISymbolicObject object, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_XML_ID, computeObjectId(model, object)); - attributeValues.put(ATTRIBUTE_NAME, object.getNameString()); - attributeValues.put(ATTRIBUTE_TYPE, object.getTypeString()); - appendStartTag(level, TAG_OBJECT, attributeValues, sb); - for (ISymbolicValue value : object.getValues()) { - appendValue(level + 1, value, sb); - } - for (ISymbolicAssociation association : object.getAssociations()) { - appendAssociation(level + 1, model, association, sb); - } - appendEndTag(level, TAG_OBJECT, sb); - } + /** + * Appends the given {@link ISymbolicLayout} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param model The {@link ISymbolicLayout} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendModel(int level, ISymbolicLayout model, StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + appendStartTag(level, TAG_MODEL, attributeValues, sb); + for (ISymbolicEquivalenceClass ec : model.getEquivalenceClasses()) { + appendEquivalenceClass(level + 1, ec, sb); + } + appendState(level + 1, model, model.getState(), sb); + for (ISymbolicObject object : model.getObjects()) { + appendObject(level + 1, model, object, sb); + } + appendEndTag(level, TAG_MODEL, sb); + } - /** - * Appends the given {@link ISymbolicValue} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param value The {@link ISymbolicValue} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendValue(int level, ISymbolicValue value, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, value.getName()); - attributeValues.put(ATTRIBUTE_PROGRAM_VARIABLE, value.getProgramVariableString()); - attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, value.isArrayIndex() + ""); - attributeValues.put(ATTRIBUTE_ARRAY_INDEX, value.getArrayIndexString()); - attributeValues.put(ATTRIBUTE_VALUE, value.getValueString()); - attributeValues.put(ATTRIBUTE_TYPE, value.getTypeString()); - if (value.getConditionString() != null) { - attributeValues.put(ATTRIBUTE_CONDITION, value.getConditionString()); - } - appendEmptyTag(level, TAG_VALUE, attributeValues, sb); - } + /** + * Appends the given {@link ISymbolicEquivalenceClass} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param ec The {@link ISymbolicEquivalenceClass} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendEquivalenceClass(int level, ISymbolicEquivalenceClass ec, + StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_REPRESENTATIVE, ec.getRepresentativeString()); + appendStartTag(level, TAG_EQUIVALENCE_CLASS, attributeValues, sb); + for (String term : ec.getTermStrings()) { + Map termAttributeValues = new LinkedHashMap(); + termAttributeValues.put(ATTRIBUTE_TERM, term); + appendEmptyTag(level + 1, TAG_TERM, termAttributeValues, sb); + } + appendEndTag(level, TAG_EQUIVALENCE_CLASS, sb); + } - /** - * Appends the given {@link ISymbolicAssociation} with its children to the given {@link StringBuffer}. - * @param level The level to use. - * @param model The {@link ISymbolicLayout} which provides all objects. - * @param association The {@link ISymbolicAssociation} to append. - * @param sb The {@link StringBuffer} to append to. - */ - protected void appendAssociation(int level, ISymbolicLayout model, ISymbolicAssociation association, StringBuffer sb) { - Map attributeValues = new LinkedHashMap(); - attributeValues.put(ATTRIBUTE_NAME, association.getName()); - attributeValues.put(ATTRIBUTE_PROGRAM_VARIABLE, association.getProgramVariableString()); - attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, association.isArrayIndex() + ""); - attributeValues.put(ATTRIBUTE_ARRAY_INDEX, association.getArrayIndexString()); - attributeValues.put(ATTRIBUTE_TARGET, computeObjectId(model, association.getTarget())); - if (association.getConditionString() != null) { - attributeValues.put(ATTRIBUTE_CONDITION, association.getConditionString()); - } - appendEmptyTag(level, TAG_ASSOCIATION, attributeValues, sb); - } + /** + * Appends the given {@link ISymbolicState} with its children to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param model The {@link ISymbolicLayout} which provides all objects. + * @param state The {@link ISymbolicState} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendState(int level, ISymbolicLayout model, ISymbolicState state, + StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, state.getName()); + appendStartTag(level, TAG_STATE, attributeValues, sb); + for (ISymbolicValue value : state.getValues()) { + appendValue(level + 1, value, sb); + } + for (ISymbolicAssociation association : state.getAssociations()) { + appendAssociation(level + 1, model, association, sb); + } + appendEndTag(level, TAG_STATE, sb); + } - /** - * Computes a unique ID for the given object in the given model. - * @param model The {@link ISymbolicLayout} which provides all objects. - * @param object The {@link ISymbolicObject} to compute its unique ID. - * @return The unique ID. - */ - protected String computeObjectId(ISymbolicLayout model, ISymbolicObject object) { - int i = 0; - int index = -1; - Iterator iter = model.getObjects().iterator(); - while (index < 0 && iter.hasNext()) { - ISymbolicObject next = iter.next(); - if (next == object) { - index = i; - } - i++; - } - return "o" + (index + 1); - } -} \ No newline at end of file + /** + * Appends the given {@link ISymbolicObject} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param model The {@link ISymbolicLayout} which provides all objects. + * @param object The {@link ISymbolicObject} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendObject(int level, ISymbolicLayout model, ISymbolicObject object, + StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_XML_ID, computeObjectId(model, object)); + attributeValues.put(ATTRIBUTE_NAME, object.getNameString()); + attributeValues.put(ATTRIBUTE_TYPE, object.getTypeString()); + appendStartTag(level, TAG_OBJECT, attributeValues, sb); + for (ISymbolicValue value : object.getValues()) { + appendValue(level + 1, value, sb); + } + for (ISymbolicAssociation association : object.getAssociations()) { + appendAssociation(level + 1, model, association, sb); + } + appendEndTag(level, TAG_OBJECT, sb); + } + + /** + * Appends the given {@link ISymbolicValue} with its children to the given {@link StringBuffer}. + * + * @param level The level to use. + * @param value The {@link ISymbolicValue} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendValue(int level, ISymbolicValue value, StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, value.getName()); + attributeValues.put(ATTRIBUTE_PROGRAM_VARIABLE, value.getProgramVariableString()); + attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, value.isArrayIndex() + ""); + attributeValues.put(ATTRIBUTE_ARRAY_INDEX, value.getArrayIndexString()); + attributeValues.put(ATTRIBUTE_VALUE, value.getValueString()); + attributeValues.put(ATTRIBUTE_TYPE, value.getTypeString()); + if (value.getConditionString() != null) { + attributeValues.put(ATTRIBUTE_CONDITION, value.getConditionString()); + } + appendEmptyTag(level, TAG_VALUE, attributeValues, sb); + } + + /** + * Appends the given {@link ISymbolicAssociation} with its children to the given + * {@link StringBuffer}. + * + * @param level The level to use. + * @param model The {@link ISymbolicLayout} which provides all objects. + * @param association The {@link ISymbolicAssociation} to append. + * @param sb The {@link StringBuffer} to append to. + */ + protected void appendAssociation(int level, ISymbolicLayout model, + ISymbolicAssociation association, StringBuffer sb) { + Map attributeValues = new LinkedHashMap(); + attributeValues.put(ATTRIBUTE_NAME, association.getName()); + attributeValues.put(ATTRIBUTE_PROGRAM_VARIABLE, association.getProgramVariableString()); + attributeValues.put(ATTRIBUTE_IS_ARRAY_INDEX, association.isArrayIndex() + ""); + attributeValues.put(ATTRIBUTE_ARRAY_INDEX, association.getArrayIndexString()); + attributeValues.put(ATTRIBUTE_TARGET, computeObjectId(model, association.getTarget())); + if (association.getConditionString() != null) { + attributeValues.put(ATTRIBUTE_CONDITION, association.getConditionString()); + } + appendEmptyTag(level, TAG_ASSOCIATION, attributeValues, sb); + } + + /** + * Computes a unique ID for the given object in the given model. + * + * @param model The {@link ISymbolicLayout} which provides all objects. + * @param object The {@link ISymbolicObject} to compute its unique ID. + * @return The unique ID. + */ + protected String computeObjectId(ISymbolicLayout model, ISymbolicObject object) { + int i = 0; + int index = -1; + Iterator iter = model.getObjects().iterator(); + while (index < 0 && iter.hasNext()) { + ISymbolicObject next = iter.next(); + if (next == object) { + index = i; + } + i++; + } + return "o" + (index + 1); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/TruthValueTracingUtil.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/TruthValueTracingUtil.java index 7d9bcd594af..d5776d5ee66 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/TruthValueTracingUtil.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/TruthValueTracingUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution; import java.util.Collections; @@ -44,1325 +47,1379 @@ import de.uka.ilkd.key.util.NodePreorderIterator; /** - * Provides functionality to evaluate the truth value of labeled formulas - * (predicates and junctors). + * Provides functionality to evaluate the truth value of labeled formulas (predicates and junctors). + * * @author Martin Hentschel */ public final class TruthValueTracingUtil { - /** - * Forbid instances. - */ - private TruthValueTracingUtil() { - } - - /** - * Checks if the given {@link SequentFormula} is a predicate. - * @param sequentFormula The {@link SequentFormula} to check. - * @return {@code true} is predicate, {@code false} is something else. - */ - public static boolean isPredicate(SequentFormula sequentFormula) { - return sequentFormula != null ? - isPredicate(sequentFormula.formula()) : - false; - } - - /** - * Checks if the given {@link Term} is a predicate. - * @param term The {@link Term} to check. - * @return {@code true} is predicate, {@code false} is something else. - */ - public static boolean isPredicate(Term term) { - return term != null ? - isPredicate(term.op()) : - false; - } - - /** - * Checks if the given {@link Operator} is a predicate. - * @param operator The {@link Operator} to check. - * @return {@code true} is predicate, {@code false} is something else. - */ - public static boolean isPredicate(Operator operator) { - if (operator == Equality.EQV) { - return false; - } - else if (operator instanceof Junctor) { - return operator == Junctor.TRUE || operator == Junctor.FALSE; - } - else if (operator == AbstractTermTransformer.META_EQ || - operator == AbstractTermTransformer.META_GEQ || - operator == AbstractTermTransformer.META_GREATER || - operator == AbstractTermTransformer.META_LEQ || - operator == AbstractTermTransformer.META_LESS) { - return true; // These Meta constructs evaluate always to true or false - } - else if (operator instanceof SortedOperator) { - return ((SortedOperator) operator).sort() == Sort.FORMULA; - } - else { - return false; - } - } - - /** - * Checks if the given {@link Term} is a logical operator - * @param operator The {@link Term} to check. - * @return {@code true} is logical operator, {@code false} is something else. - */ - public static boolean isLogicOperator(Term term) { - if (term != null) { - return isLogicOperator(term.op(), term.subs()); - } - else { - return false; - } - } - - /** - * Checks if the given {@link Operator} and its sub {@link Term}s specify a logical operator. - * @param operator The {@link Operator}. - * @param subs The sub {@link Term}s. - * @return {@code true} is logical operator, {@code false} is something else. - */ - public static boolean isLogicOperator(Operator operator, ImmutableArray subs) { - if (operator instanceof Junctor) { - return operator != Junctor.TRUE && operator != Junctor.FALSE; - } - else if (operator == Equality.EQV) { - return true; - } - else if (isIfThenElseFormula(operator, subs)) { - return true; - } - else { - return false; - } - } - - /** - * Checks if the given {@link Term} is an if-then-else formula. - * @param term The {@link Term} to check. - * @return {@code true} is if-then-else formula, {@code false} is something else. - */ - public static boolean isIfThenElseFormula(Term term) { - if (term != null) { - return isIfThenElseFormula(term.op(), term.subs()); - } - else { - return false; - } - } - - /** - * Checks if the given {@link Operator} and its sub {@link Term}s specify an if-then-else formula. - * @param operator The {@link Operator}. - * @param subs The sub {@link Term}s. - * @return {@code true} is if-then-else formula, {@code false} is something else. - */ - public static boolean isIfThenElseFormula(Operator operator, ImmutableArray subs) { - if (operator == IfThenElse.IF_THEN_ELSE) { - Sort sort = operator.sort(subs); - return sort == Sort.FORMULA; - } - else { - return false; - } - } - - /** - * Evaluates the truth values in the subtree of the given {@link Node} - * for predicates labeled with the given {@link TermLabel} name. - * @param node The {@link Node} to start evaluation at. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @return The result. - * @throws ProofInputException Occurred Exception - */ - public static TruthValueTracingResult evaluate(Node node, - Name termLabelName, - boolean useUnicode, - boolean usePrettyPrinting) throws ProofInputException { - TruthValueTracingResult result = new TruthValueTracingResult(); - Deque> evaluationStack = new LinkedList>(); - evaluationStack.addFirst(new HashMap()); - Services services = node.proof().getServices(); - NodePreorderIterator iterator = new NodePreorderIterator(node); - while (iterator.hasNext()) { - // Get next node - int childIndexOnParnt = iterator.getChildIndexOnParent(); // Needs to be called before next is called. - Node next = iterator.next(); - // Create child result for current node - final Map topResults = evaluationStack.getFirst(); - Map nodeResults = new HashMap(topResults); - evaluationStack.addFirst(nodeResults); - // Analyze node - evaluateNode(node, - useUnicode, - usePrettyPrinting, - next, - childIndexOnParnt, - termLabelName, - nodeResults, - result, - services); - // Remove no longer needed child result of returned nodes - for (int i = 0; i < iterator.getReturnedParents(); i++) { - evaluationStack.removeFirst(); - } - } - return result; - } - - /** - * Evaluates the truth statuses changed from the parent {@link Node} to its child {@link Node}. - * @param evaluationNode The {@link Node} where the truth status tracing started. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param child The current child {@link Node} to analyze. - * @param childIndexOnParent The index of the child {@link Node} on its parent {@link Node}. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - * @param nodeResult The to child {@link Node} related result {@link Map} to update. - * @param result The overall {@link TruthValueTracingResult} to update. - * @param services The {@link Services} to use. - * @throws ProofInputException Occurred exception. - */ - protected static void evaluateNode(final Node evaluationNode, - final boolean useUnicode, - final boolean usePrettyPrinting, - final Node child, - final int childIndexOnParent, - final Name termLabelName, - Map nodeResult, - final TruthValueTracingResult result, - final Services services) throws ProofInputException { - // Analyze parent rule application - boolean checkPerformed = false; - if (childIndexOnParent >= 0) { - Node parent = child.parent(); - if (parent.getAppliedRuleApp() instanceof TacletApp) { - TacletApp tacletApp = (TacletApp) parent.getAppliedRuleApp(); - List labels = findInvolvedLabels(parent.sequent(), tacletApp, termLabelName); - if (!labels.isEmpty()) { - Taclet taclet = ((TacletApp) tacletApp).taclet(); - if (!isClosingRule(taclet)) { // Not a closing taclet - checkPerformed = true; - TacletGoalTemplate tacletGoal = taclet.goalTemplates().reverse().take(childIndexOnParent).head(); - // Check for new minor ids created by parent rule application - updatePredicateResultBasedOnNewMinorIds(child, termLabelName, services.getTermBuilder(), nodeResult); - analyzeTacletGoal(parent, tacletApp, tacletGoal, labels, services, nodeResult); - } - else if (tacletApp.posInOccurrence() != null) { - for (LabelOccurrence occurrence : labels) { - updatePredicateResult(occurrence.getLabel(), !occurrence.isInAntecedent(), nodeResult); - } - } - } - } - else if (parent.getAppliedRuleApp() instanceof OneStepSimplifierRuleApp) { - OneStepSimplifierRuleApp app = (OneStepSimplifierRuleApp) parent.getAppliedRuleApp(); - PosInOccurrence parentPio = null; - for (RuleApp protocolApp : app.getProtocol()) { - if (parentPio != null) { - updatePredicateResultBasedOnNewMinorIdsOSS(protocolApp.posInOccurrence(), parentPio, termLabelName, services.getTermBuilder(), nodeResult); - } - assert protocolApp instanceof TacletApp; - TacletApp tacletApp = (TacletApp) protocolApp; - Taclet taclet = tacletApp.taclet(); - assert taclet.goalTemplates().size() == 1; - List labels = findInvolvedLabels(parent.sequent(), tacletApp, termLabelName); - if (!labels.isEmpty()) { - analyzeTacletGoal(parent, tacletApp, taclet.goalTemplates().head(), labels, services, nodeResult); - } - parentPio = protocolApp.posInOccurrence(); - } - // Compare last PIO with PIO in child sequent (Attention: Child PIO is computed with help of the PIO of the OSS) - if (parentPio != null) { - assert 1 == parent.childrenCount() : "Implementaton of the OneStepSimplifierRule has changed."; - PosInOccurrence childPio = SymbolicExecutionUtil.posInOccurrenceToOtherSequent(parent, parent.getAppliedRuleApp().posInOccurrence(), parent.child(0)); - updatePredicateResultBasedOnNewMinorIdsOSS(childPio, parentPio, termLabelName, services.getTermBuilder(), nodeResult); - } - } - } - // If goal reached, update final result - int childCount = child.childrenCount(); - if (childCount == 0) { - Term condition = SymbolicExecutionUtil.computePathCondition(evaluationNode, child, false, true); - String conditionString = SymbolicExecutionUtil.formatTerm(condition, services, useUnicode, usePrettyPrinting); - result.addBranchResult(new BranchResult(child, nodeResult, condition, conditionString, termLabelName)); - } - else if (!checkPerformed) { - updatePredicateResultBasedOnNewMinorIds(child, termLabelName, services.getTermBuilder(), nodeResult); - } - } - - /** - * Checks if the {@link Taclet} is a closing rule. - * @param taclet The {@link Taclet} to check. - * @return {@code true} is closing, {@code false} is not closing. - */ - protected static boolean isClosingRule(Taclet taclet) { - return taclet.goalTemplates().isEmpty(); - } - - /** - * Computes the occurrences of all involved {@link FormulaTermLabel}s. - * @param sequent The {@link Sequent} on which the given {@link TacletApp} was applied. - * @param tacletApp The applied {@link TacletApp}. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - * @return The found {@link LabelOccurrence}s. - */ - protected static List findInvolvedLabels(Sequent sequent, - TacletApp tacletApp, - Name termLabelName) { - List result = new LinkedList(); - // Search for labels in find part - PosInOccurrence pio = tacletApp.posInOccurrence(); - if (pio != null) { - Term term = pio.subTerm(); - if (term != null) { - // Check for evaluated truth values - TermLabel label = term.getLabel(termLabelName); - if (label instanceof FormulaTermLabel) { - result.add(new LabelOccurrence((FormulaTermLabel) label, pio.isInAntec())); + /** + * Forbid instances. + */ + private TruthValueTracingUtil() {} + + /** + * Checks if the given {@link SequentFormula} is a predicate. + * + * @param sequentFormula The {@link SequentFormula} to check. + * @return {@code true} is predicate, {@code false} is something else. + */ + public static boolean isPredicate(SequentFormula sequentFormula) { + return sequentFormula != null ? isPredicate(sequentFormula.formula()) : false; + } + + /** + * Checks if the given {@link Term} is a predicate. + * + * @param term The {@link Term} to check. + * @return {@code true} is predicate, {@code false} is something else. + */ + public static boolean isPredicate(Term term) { + return term != null ? isPredicate(term.op()) : false; + } + + /** + * Checks if the given {@link Operator} is a predicate. + * + * @param operator The {@link Operator} to check. + * @return {@code true} is predicate, {@code false} is something else. + */ + public static boolean isPredicate(Operator operator) { + if (operator == Equality.EQV) { + return false; + } else if (operator instanceof Junctor) { + return operator == Junctor.TRUE || operator == Junctor.FALSE; + } else if (operator == AbstractTermTransformer.META_EQ + || operator == AbstractTermTransformer.META_GEQ + || operator == AbstractTermTransformer.META_GREATER + || operator == AbstractTermTransformer.META_LEQ + || operator == AbstractTermTransformer.META_LESS) { + return true; // These Meta constructs evaluate always to true or false + } else if (operator instanceof SortedOperator) { + return ((SortedOperator) operator).sort() == Sort.FORMULA; + } else { + return false; + } + } + + /** + * Checks if the given {@link Term} is a logical operator + * + * @param operator The {@link Term} to check. + * @return {@code true} is logical operator, {@code false} is something else. + */ + public static boolean isLogicOperator(Term term) { + if (term != null) { + return isLogicOperator(term.op(), term.subs()); + } else { + return false; + } + } + + /** + * Checks if the given {@link Operator} and its sub {@link Term}s specify a logical operator. + * + * @param operator The {@link Operator}. + * @param subs The sub {@link Term}s. + * @return {@code true} is logical operator, {@code false} is something else. + */ + public static boolean isLogicOperator(Operator operator, ImmutableArray subs) { + if (operator instanceof Junctor) { + return operator != Junctor.TRUE && operator != Junctor.FALSE; + } else if (operator == Equality.EQV) { + return true; + } else if (isIfThenElseFormula(operator, subs)) { + return true; + } else { + return false; + } + } + + /** + * Checks if the given {@link Term} is an if-then-else formula. + * + * @param term The {@link Term} to check. + * @return {@code true} is if-then-else formula, {@code false} is something else. + */ + public static boolean isIfThenElseFormula(Term term) { + if (term != null) { + return isIfThenElseFormula(term.op(), term.subs()); + } else { + return false; + } + } + + /** + * Checks if the given {@link Operator} and its sub {@link Term}s specify an if-then-else + * formula. + * + * @param operator The {@link Operator}. + * @param subs The sub {@link Term}s. + * @return {@code true} is if-then-else formula, {@code false} is something else. + */ + public static boolean isIfThenElseFormula(Operator operator, ImmutableArray subs) { + if (operator == IfThenElse.IF_THEN_ELSE) { + Sort sort = operator.sort(subs); + return sort == Sort.FORMULA; + } else { + return false; + } + } + + /** + * Evaluates the truth values in the subtree of the given {@link Node} for predicates labeled + * with the given {@link TermLabel} name. + * + * @param node The {@link Node} to start evaluation at. + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @return The result. + * @throws ProofInputException Occurred Exception + */ + public static TruthValueTracingResult evaluate(Node node, Name termLabelName, + boolean useUnicode, boolean usePrettyPrinting) throws ProofInputException { + TruthValueTracingResult result = new TruthValueTracingResult(); + Deque> evaluationStack = + new LinkedList>(); + evaluationStack.addFirst(new HashMap()); + Services services = node.proof().getServices(); + NodePreorderIterator iterator = new NodePreorderIterator(node); + while (iterator.hasNext()) { + // Get next node + int childIndexOnParnt = iterator.getChildIndexOnParent(); // Needs to be called before + // next is called. + Node next = iterator.next(); + // Create child result for current node + final Map topResults = evaluationStack.getFirst(); + Map nodeResults = + new HashMap(topResults); + evaluationStack.addFirst(nodeResults); + // Analyze node + evaluateNode(node, useUnicode, usePrettyPrinting, next, childIndexOnParnt, + termLabelName, nodeResults, result, services); + // Remove no longer needed child result of returned nodes + for (int i = 0; i < iterator.getReturnedParents(); i++) { + evaluationStack.removeFirst(); } - } - } - if (isClosingRule(tacletApp.taclet())) { - if (tacletApp.ifInstsComplete() && tacletApp.ifFormulaInstantiations() != null) { - for (IfFormulaInstantiation ifInst : tacletApp.ifFormulaInstantiations()) { - assert ifInst instanceof IfFormulaInstSeq; - Term term = ifInst.getConstrainedFormula().formula(); - TermLabel label = term.getLabel(termLabelName); - if (label instanceof FormulaTermLabel) { - result.add(new LabelOccurrence((FormulaTermLabel) label, ((IfFormulaInstSeq) ifInst).inAntec())); - } + } + return result; + } + + /** + * Evaluates the truth statuses changed from the parent {@link Node} to its child {@link Node}. + * + * @param evaluationNode The {@link Node} where the truth status tracing started. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param child The current child {@link Node} to analyze. + * @param childIndexOnParent The index of the child {@link Node} on its parent {@link Node}. + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + * @param nodeResult The to child {@link Node} related result {@link Map} to update. + * @param result The overall {@link TruthValueTracingResult} to update. + * @param services The {@link Services} to use. + * @throws ProofInputException Occurred exception. + */ + protected static void evaluateNode(final Node evaluationNode, final boolean useUnicode, + final boolean usePrettyPrinting, final Node child, final int childIndexOnParent, + final Name termLabelName, Map nodeResult, + final TruthValueTracingResult result, final Services services) + throws ProofInputException { + // Analyze parent rule application + boolean checkPerformed = false; + if (childIndexOnParent >= 0) { + Node parent = child.parent(); + if (parent.getAppliedRuleApp() instanceof TacletApp) { + TacletApp tacletApp = (TacletApp) parent.getAppliedRuleApp(); + List labels = + findInvolvedLabels(parent.sequent(), tacletApp, termLabelName); + if (!labels.isEmpty()) { + Taclet taclet = ((TacletApp) tacletApp).taclet(); + if (!isClosingRule(taclet)) { // Not a closing taclet + checkPerformed = true; + TacletGoalTemplate tacletGoal = + taclet.goalTemplates().reverse().take(childIndexOnParent).head(); + // Check for new minor ids created by parent rule application + updatePredicateResultBasedOnNewMinorIds(child, termLabelName, + services.getTermBuilder(), nodeResult); + analyzeTacletGoal(parent, tacletApp, tacletGoal, labels, services, + nodeResult); + } else if (tacletApp.posInOccurrence() != null) { + for (LabelOccurrence occurrence : labels) { + updatePredicateResult(occurrence.getLabel(), + !occurrence.isInAntecedent(), nodeResult); + } + } + } + } else if (parent.getAppliedRuleApp() instanceof OneStepSimplifierRuleApp) { + OneStepSimplifierRuleApp app = + (OneStepSimplifierRuleApp) parent.getAppliedRuleApp(); + PosInOccurrence parentPio = null; + for (RuleApp protocolApp : app.getProtocol()) { + if (parentPio != null) { + updatePredicateResultBasedOnNewMinorIdsOSS(protocolApp.posInOccurrence(), + parentPio, termLabelName, services.getTermBuilder(), nodeResult); + } + assert protocolApp instanceof TacletApp; + TacletApp tacletApp = (TacletApp) protocolApp; + Taclet taclet = tacletApp.taclet(); + assert taclet.goalTemplates().size() == 1; + List labels = + findInvolvedLabels(parent.sequent(), tacletApp, termLabelName); + if (!labels.isEmpty()) { + analyzeTacletGoal(parent, tacletApp, taclet.goalTemplates().head(), labels, + services, nodeResult); + } + parentPio = protocolApp.posInOccurrence(); + } + // Compare last PIO with PIO in child sequent (Attention: Child PIO is computed with + // help of the PIO of the OSS) + if (parentPio != null) { + assert 1 == parent.childrenCount() + : "Implementaton of the OneStepSimplifierRule has changed."; + PosInOccurrence childPio = SymbolicExecutionUtil.posInOccurrenceToOtherSequent( + parent, parent.getAppliedRuleApp().posInOccurrence(), parent.child(0)); + updatePredicateResultBasedOnNewMinorIdsOSS(childPio, parentPio, termLabelName, + services.getTermBuilder(), nodeResult); + } } - } - } - return result; - } - - /** - * Utility class which specifies the occurrence of a {@link FormulaTermLabel}. - * @author Martin Hentschel - */ - private static class LabelOccurrence { - /** - * The {@link FormulaTermLabel}. - */ - private final FormulaTermLabel label; - - /** - * {@code true} occurred in antecedent, {@code false} occurred in succedent. - */ - private final boolean inAntecedent; - - /** - * Constructor. - * @param label The {@link FormulaTermLabel}. - * @param inAntecedent {@code true} occurred in antecedent, {@code false} occurred in succedent. - */ - public LabelOccurrence(FormulaTermLabel label, boolean inAntecedent) { - this.label = label; - this.inAntecedent = inAntecedent; - } - - /** - * Returns the {@link FormulaTermLabel}. - * @return The {@link FormulaTermLabel}. - */ - public FormulaTermLabel getLabel() { - return label; - } - - /** - * Checks if the label occurred in antecedent or succedent. - * @return {@code true} occurred in antecedent, {@code false} occurred in succedent. - */ - public boolean isInAntecedent() { - return inAntecedent; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return label + - (inAntecedent ? " in antecedent" : " in succedent"); - } - } - - /** - * Analyzes the given {@link TacletGoalTemplate}. - * @param parent The current {@link Node} on which the rule was applied. - * @param tacletApp The {@link TacletApp}. - * @param tacletGoal The {@link TacletGoalTemplate}. - * @param labels The {@link FormulaTermLabel}s. - * @param servies The {@link Services} to use. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void analyzeTacletGoal(Node parent, - TacletApp tacletApp, - TacletGoalTemplate tacletGoal, - List labels, - Services services, - Map results) { - Object replaceObject = tacletGoal.replaceWithExpressionAsObject(); - if (replaceObject instanceof Term) { - Term replaceTerm = SymbolicExecutionUtil.instantiateTerm(parent, (Term) replaceObject, tacletApp, services); - if (replaceTerm.op() == Junctor.TRUE) { - // Find term is replaced by true - for (LabelOccurrence occurrence : labels) { - updatePredicateResult(occurrence.getLabel(), true, results); + } + // If goal reached, update final result + int childCount = child.childrenCount(); + if (childCount == 0) { + Term condition = + SymbolicExecutionUtil.computePathCondition(evaluationNode, child, false, true); + String conditionString = SymbolicExecutionUtil.formatTerm(condition, services, + useUnicode, usePrettyPrinting); + result.addBranchResult( + new BranchResult(child, nodeResult, condition, conditionString, termLabelName)); + } else if (!checkPerformed) { + updatePredicateResultBasedOnNewMinorIds(child, termLabelName, services.getTermBuilder(), + nodeResult); + } + } + + /** + * Checks if the {@link Taclet} is a closing rule. + * + * @param taclet The {@link Taclet} to check. + * @return {@code true} is closing, {@code false} is not closing. + */ + protected static boolean isClosingRule(Taclet taclet) { + return taclet.goalTemplates().isEmpty(); + } + + /** + * Computes the occurrences of all involved {@link FormulaTermLabel}s. + * + * @param sequent The {@link Sequent} on which the given {@link TacletApp} was applied. + * @param tacletApp The applied {@link TacletApp}. + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + * @return The found {@link LabelOccurrence}s. + */ + protected static List findInvolvedLabels(Sequent sequent, TacletApp tacletApp, + Name termLabelName) { + List result = new LinkedList(); + // Search for labels in find part + PosInOccurrence pio = tacletApp.posInOccurrence(); + if (pio != null) { + Term term = pio.subTerm(); + if (term != null) { + // Check for evaluated truth values + TermLabel label = term.getLabel(termLabelName); + if (label instanceof FormulaTermLabel) { + result.add(new LabelOccurrence((FormulaTermLabel) label, pio.isInAntec())); + } } - } - else if (replaceTerm.op() == Junctor.FALSE) { - // Find term is replaced by false - for (LabelOccurrence occurrence : labels) { - updatePredicateResult(occurrence.getLabel(), false, results); + } + if (isClosingRule(tacletApp.taclet())) { + if (tacletApp.ifInstsComplete() && tacletApp.ifFormulaInstantiations() != null) { + for (IfFormulaInstantiation ifInst : tacletApp.ifFormulaInstantiations()) { + assert ifInst instanceof IfFormulaInstSeq; + Term term = ifInst.getConstrainedFormula().formula(); + TermLabel label = term.getLabel(termLabelName); + if (label instanceof FormulaTermLabel) { + result.add(new LabelOccurrence((FormulaTermLabel) label, + ((IfFormulaInstSeq) ifInst).inAntec())); + } + } } - } - } - } - - /** - * Updates the {@link PredicateResult}s based on minor ID changes if - * available in case of {@link OneStepSimplifier} usage. - * @param childNode The child {@link Node}. - * @param termLabelName The name of the {@link TermLabel} which is added to predicates. - * @param tb The {@link TermBuilder} to use. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void updatePredicateResultBasedOnNewMinorIdsOSS(final PosInOccurrence childPio, - final PosInOccurrence parentPio, - final Name termLabelName, - final TermBuilder tb, - final Map results) { - if (parentPio != null) { - // Check application term and all of its children and grand children - parentPio.subTerm().execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - checkForNewMinorIdsOSS(childPio.sequentFormula(), visited, termLabelName, parentPio, tb, results); + } + return result; + } + + /** + * Utility class which specifies the occurrence of a {@link FormulaTermLabel}. + * + * @author Martin Hentschel + */ + private static class LabelOccurrence { + /** + * The {@link FormulaTermLabel}. + */ + private final FormulaTermLabel label; + + /** + * {@code true} occurred in antecedent, {@code false} occurred in succedent. + */ + private final boolean inAntecedent; + + /** + * Constructor. + * + * @param label The {@link FormulaTermLabel}. + * @param inAntecedent {@code true} occurred in antecedent, {@code false} occurred in + * succedent. + */ + public LabelOccurrence(FormulaTermLabel label, boolean inAntecedent) { + this.label = label; + this.inAntecedent = inAntecedent; + } + + /** + * Returns the {@link FormulaTermLabel}. + * + * @return The {@link FormulaTermLabel}. + */ + public FormulaTermLabel getLabel() { + return label; + } + + /** + * Checks if the label occurred in antecedent or succedent. + * + * @return {@code true} occurred in antecedent, {@code false} occurred in succedent. + */ + public boolean isInAntecedent() { + return inAntecedent; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return label + (inAntecedent ? " in antecedent" : " in succedent"); + } + } + + /** + * Analyzes the given {@link TacletGoalTemplate}. + * + * @param parent The current {@link Node} on which the rule was applied. + * @param tacletApp The {@link TacletApp}. + * @param tacletGoal The {@link TacletGoalTemplate}. + * @param labels The {@link FormulaTermLabel}s. + * @param servies The {@link Services} to use. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void analyzeTacletGoal(Node parent, TacletApp tacletApp, + TacletGoalTemplate tacletGoal, List labels, Services services, + Map results) { + Object replaceObject = tacletGoal.replaceWithExpressionAsObject(); + if (replaceObject instanceof Term) { + Term replaceTerm = SymbolicExecutionUtil.instantiateTerm(parent, (Term) replaceObject, + tacletApp, services); + if (replaceTerm.op() == Junctor.TRUE) { + // Find term is replaced by true + for (LabelOccurrence occurrence : labels) { + updatePredicateResult(occurrence.getLabel(), true, results); + } + } else if (replaceTerm.op() == Junctor.FALSE) { + // Find term is replaced by false + for (LabelOccurrence occurrence : labels) { + updatePredicateResult(occurrence.getLabel(), false, results); + } } - }); - // Check application term parents - PosInOccurrence currentPio = parentPio; - while (!currentPio.isTopLevel()) { - currentPio = currentPio.up(); - checkForNewMinorIdsOSS(childPio.sequentFormula(), currentPio.subTerm(), termLabelName, parentPio, tb, results); - } - } - } - - /** - * Checks if new minor IDs are available in case of {@link OneStepSimplifier} usage. - * @param onlyChangedChildSF The only changed {@link SequentFormula} in the child {@link Node}. - * @param term The {@link Term} contained in the child {@link Node} to check. - * @param termLabelName The name of the {@link TermLabel} which is added to predicates. - * @param parentPio The {@link PosInOccurrence} of the applied rule of the parent {@link Node}. - * @param tb The {@link TermBuilder} to use. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void checkForNewMinorIdsOSS(SequentFormula onlyChangedChildSF, - Term term, - Name termLabelName, - PosInOccurrence parentPio, - TermBuilder tb, - Map results) { - TermLabel label = term.getLabel(termLabelName); - if (label instanceof FormulaTermLabel) { - Term replacement = checkForNewMinorIdsOSS(onlyChangedChildSF, (FormulaTermLabel) label, parentPio.isInAntec(), tb); - if (replacement != null) { - updatePredicateResult((FormulaTermLabel) label, replacement, results); - } - } - } - - /** - * Checks if new minor IDs are available in case of {@link OneStepSimplifier} usage. - * @param onlyChangedChildSF The only changed {@link SequentFormula} in the child {@link Node}. - * @param label The {@link FormulaTermLabel} of interest. - * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule applied on succedent. - * @param tb The {@link TermBuilder} to use. - * @return The computed instruction {@link Term} or {@code null} if not available. - */ - protected static Term checkForNewMinorIdsOSS(SequentFormula onlyChangedChildSF, - FormulaTermLabel label, - boolean antecedentRuleApplication, - TermBuilder tb) { - // Search replacements - List antecedentReplacements = new LinkedList(); - List succedentReplacements = new LinkedList(); - if (antecedentRuleApplication) { - listLabelReplacements(onlyChangedChildSF, label.name(), label.getId(), antecedentReplacements); - } - else { - listLabelReplacements(onlyChangedChildSF, label.name(), label.getId(), succedentReplacements); - } - // Compute term - return computeInstructionTerm(antecedentReplacements, succedentReplacements, antecedentRuleApplication, tb); - } - - /** - * Updates the {@link PredicateResult}s based on minor ID changes if available. - * @param childNode The child {@link Node}. - * @param termLabelName The name of the {@link TermLabel} which is added to predicates. - * @param tb The {@link TermBuilder} to use. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void updatePredicateResultBasedOnNewMinorIds(final Node childNode, - final Name termLabelName, - final TermBuilder tb, - final Map results) { - final Node parentNode = childNode.parent(); - if (parentNode != null) { - final RuleApp parentRuleApp = parentNode.getAppliedRuleApp(); - final PosInOccurrence parentPio = parentRuleApp.posInOccurrence(); - if (parentPio != null) { + } + } + + /** + * Updates the {@link PredicateResult}s based on minor ID changes if available in case of + * {@link OneStepSimplifier} usage. + * + * @param childNode The child {@link Node}. + * @param termLabelName The name of the {@link TermLabel} which is added to predicates. + * @param tb The {@link TermBuilder} to use. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void updatePredicateResultBasedOnNewMinorIdsOSS(final PosInOccurrence childPio, + final PosInOccurrence parentPio, final Name termLabelName, final TermBuilder tb, + final Map results) { + if (parentPio != null) { // Check application term and all of its children and grand children parentPio.subTerm().execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - checkForNewMinorIds(childNode, visited, termLabelName, parentPio, tb, results); - } + @Override + public void visit(Term visited) { + checkForNewMinorIdsOSS(childPio.sequentFormula(), visited, termLabelName, + parentPio, tb, results); + } }); // Check application term parents PosInOccurrence currentPio = parentPio; while (!currentPio.isTopLevel()) { - currentPio = currentPio.up(); - checkForNewMinorIds(childNode, currentPio.subTerm(), termLabelName, parentPio, tb, results); - } - // Check if instantiations - if (parentRuleApp instanceof TacletApp) { - TacletApp ta = (TacletApp) parentRuleApp; - if (ta.ifInstsComplete() && ta.ifFormulaInstantiations() != null) { - for (IfFormulaInstantiation ifInst : ta.ifFormulaInstantiations()) { - checkForNewMinorIds(childNode, ifInst.getConstrainedFormula().formula(), termLabelName, parentPio, tb, results); - } - } - } - } - } - } - - /** - * Checks if new minor IDs are available. - * @param childNode The child {@link Node}. - * @param term The {@link Term} contained in the child {@link Node} to check. - * @param termLabelName The name of the {@link TermLabel} which is added to predicates. - * @param parentPio The {@link PosInOccurrence} of the applied rule of the parent {@link Node}. - * @param tb The {@link TermBuilder} to use. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void checkForNewMinorIds(Node childNode, - Term term, - Name termLabelName, - PosInOccurrence parentPio, - TermBuilder tb, - Map results) { - TermLabel label = term.getLabel(termLabelName); - if (label instanceof FormulaTermLabel) { - Term replacement = checkForNewMinorIds(childNode, (FormulaTermLabel) label, parentPio.isInAntec(), tb); - if (replacement != null) { - updatePredicateResult((FormulaTermLabel) label, replacement, results); - } - } - } - - /** - * Checks if new minor IDs are available. - * @param childNode The child {@link Node}. - * @param label The {@link FormulaTermLabel} of interest. - * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule applied on succedent. - * @param tb The {@link TermBuilder} to use. - * @return The computed instruction {@link Term} or {@code null} if not available. - */ - protected static Term checkForNewMinorIds(Node childNode, - FormulaTermLabel label, - boolean antecedentRuleApplication, - TermBuilder tb) { - // Search replacements - List antecedentReplacements = new LinkedList(); - List succedentReplacements = new LinkedList(); - for (SequentFormula sf : childNode.sequent().antecedent()) { - listLabelReplacements(sf, label.name(), label.getId(), antecedentReplacements); - } - for (SequentFormula sf : childNode.sequent().succedent()) { - listLabelReplacements(sf, label.name(), label.getId(), succedentReplacements); - } - // Compute term - return computeInstructionTerm(antecedentReplacements, succedentReplacements, antecedentRuleApplication, tb); - } - - /** - * Lists all label replacements in the given {@link SequentFormula}. - * @param sf The {@link SequentFormula} to analyze. - * @param labelName The name of the {@link TermLabel} which is added to predicates. - * @param labelId The label ID of interest. - * @param resultToFill The result {@link List} to fill. - */ - protected static void listLabelReplacements(final SequentFormula sf, - final Name labelName, - final String labelId, - final List resultToFill) { - sf.formula().execPreOrder(new DefaultVisitor() { - @Override - public boolean visitSubtree(Term visited) { - return !hasLabelOfInterest(visited); - } - - @Override - public void visit(Term visited) { - if (hasLabelOfInterest(visited)) { - resultToFill.add(visited); - } - } - - protected boolean hasLabelOfInterest(Term visited) { - TermLabel visitedLabel = visited.getLabel(labelName); - if (visitedLabel instanceof FormulaTermLabel) { - FormulaTermLabel pLabel = (FormulaTermLabel) visitedLabel; - String[] beforeIds = pLabel.getBeforeIds(); - return ArrayUtil.contains(beforeIds, labelId); + currentPio = currentPio.up(); + checkForNewMinorIdsOSS(childPio.sequentFormula(), currentPio.subTerm(), + termLabelName, parentPio, tb, results); } - else { - return false; + } + } + + /** + * Checks if new minor IDs are available in case of {@link OneStepSimplifier} usage. + * + * @param onlyChangedChildSF The only changed {@link SequentFormula} in the child {@link Node}. + * @param term The {@link Term} contained in the child {@link Node} to check. + * @param termLabelName The name of the {@link TermLabel} which is added to predicates. + * @param parentPio The {@link PosInOccurrence} of the applied rule of the parent {@link Node}. + * @param tb The {@link TermBuilder} to use. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void checkForNewMinorIdsOSS(SequentFormula onlyChangedChildSF, Term term, + Name termLabelName, PosInOccurrence parentPio, TermBuilder tb, + Map results) { + TermLabel label = term.getLabel(termLabelName); + if (label instanceof FormulaTermLabel) { + Term replacement = checkForNewMinorIdsOSS(onlyChangedChildSF, (FormulaTermLabel) label, + parentPio.isInAntec(), tb); + if (replacement != null) { + updatePredicateResult((FormulaTermLabel) label, replacement, results); } - } - }); - } - - /** - * Computes the {@link Term} with the instruction how to compute the truth - * value based on the found replacements. - * @param antecedentReplacements The replacements found in the antecedent. - * @param succedentReplacements The replacements found in the succedent. - * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule applied on succedent. - * @param tb The {@link TermBuilder} to use. - * @return The computed instruction {@link Term} or {@code null} if not available. - */ - protected static Term computeInstructionTerm(List antecedentReplacements, - List succedentReplacements, - boolean antecedentRuleApplication, - TermBuilder tb) { - if (!antecedentReplacements.isEmpty() || !succedentReplacements.isEmpty()) { - Term left = tb.andPreserveLabels(antecedentReplacements); - Term right = tb.orPreserveLabels(succedentReplacements); - if (antecedentRuleApplication) { - return tb.andPreserveLabels(left, tb.notPreserveLabels(right)); - } - else { - return tb.impPreserveLabels(left, right); - } - } - else { - return null; - } - } - - /** - * Updates the instruction {@link Term} for the given {@link FormulaTermLabel} - * in the result {@link Map}. - * @param label The {@link FormulaTermLabel} to update its instruction {@link Term}. - * @param instructionTerm The new instruction {@link Term} to set. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void updatePredicateResult(FormulaTermLabel label, - Term instructionTerm, - Map results) { - MultiEvaluationResult result = results.get(label.getId()); - if (result == null) { - result = new MultiEvaluationResult(instructionTerm); - } - else { - result = result.newInstructionTerm(instructionTerm); - } - results.put(label.getId(), result); - } - - /** - * Updates the evaluation result for the given {@link FormulaTermLabel} - * in the result {@link Map}. - * @param label The {@link FormulaTermLabel} to update its instruction {@link Term}. - * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} label evaluates at least once to false. - * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. - */ - protected static void updatePredicateResult(FormulaTermLabel label, - boolean evaluationResult, - Map results) { - MultiEvaluationResult result = results.get(label.getId()); - if (result == null) { - result = new MultiEvaluationResult(evaluationResult); - } - else { - result = result.newEvaluationResult(evaluationResult); - } - results.put(label.getId(), result); - } - - /** - * Instances of this unmodifyable class are used to store the found - * evaluation results. - * @author Martin Hentschel - */ - public static class MultiEvaluationResult { - /** - * {@code true} label evaluates at least once to true, {@code false} label never evaluates to true. - */ - private final boolean evaluatesToTrue; - - /** - * {@code true} label evaluates at least once to false, {@code false} label never evaluates to false. - */ - private final boolean evaluatesToFalse; - - /** - * The instruction {@link Term}. - */ - private final Term instructionTerm; - - /** - * Constructor. - * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} label evaluates at least once to false. - */ - public MultiEvaluationResult(boolean evaluationResult) { - this(evaluationResult, !evaluationResult, null); - } - - /** - * Constructor. - * @param instructionTerm The instruction {@link Term}. - */ - public MultiEvaluationResult(Term instructionTerm) { - this(false, false, instructionTerm); - } - - /** - * Constructor. - * @param evaluatesToTrue {@code true} label evaluates at least once to true, {@code false} label never evaluates to true. - * @param evaluatesToFalse {@code true} label evaluates at least once to false, {@code false} label never evaluates to false. - * @param instructionTerm The instruction {@link Term}. - */ - public MultiEvaluationResult(boolean evaluatesToTrue, boolean evaluatesToFalse, Term instructionTerm) { - this.evaluatesToTrue = evaluatesToTrue; - this.evaluatesToFalse = evaluatesToFalse; - this.instructionTerm = instructionTerm; - } - - /** - * Checks if it is at least once evaluated to {@code true}. - * @return {@code true} label evaluates at least once to true, {@code false} label never evaluates to true. - */ - public boolean isEvaluatesToTrue() { - return evaluatesToTrue; - } - - /** - * Checks if it is at least once evaluated to {@code false}. - * @return {@code true} label evaluates at least once to false, {@code false} label never evaluates to false. - */ - public boolean isEvaluatesToFalse() { - return evaluatesToFalse; - } - - /** - * Returns the instruction {@link Term}. - * @return The instruction {@link Term} or {@code null} if undefined. - */ - public Term getInstructionTerm() { - return instructionTerm; - } - - /** - * Creates a new {@link MultiEvaluationResult} based on the current once - * but with an updated evaluation result. - * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} label evaluates at least once to false. - * @return The new created {@link MultiEvaluationResult}. - */ - public MultiEvaluationResult newEvaluationResult(boolean evaluationResult) { - if (evaluationResult) { - return newEvaluatesToTrue(true); - } - else { - return newEvaluatesToFalse(true); - } - } - - /** - * Creates a new {@link MultiEvaluationResult} based on the current once - * but with an update evaluates to true state. - * @param newEvaluatesToTrue {@code true} label evaluates at least once to true, {@code false} label never evaluates to true. - * @return The new created {@link MultiEvaluationResult}. - */ - public MultiEvaluationResult newEvaluatesToTrue(boolean newEvaluatesToTrue) { - return new MultiEvaluationResult(newEvaluatesToTrue, evaluatesToFalse, instructionTerm); - } - - /** - * Creates a new {@link MultiEvaluationResult} based on the current once - * but with an update evaluates to false state. - * @param newEvaluatesToFalse {@code true} label evaluates at least once to false, {@code false} label never evaluates to false. - * @return The new created {@link MultiEvaluationResult}. - */ - public MultiEvaluationResult newEvaluatesToFalse(boolean newEvaluatesToFalse) { - return new MultiEvaluationResult(evaluatesToTrue, newEvaluatesToFalse, instructionTerm); - } - - /** - * Creates a new {@link MultiEvaluationResult} based on the current once - * but with an update instruction term. - * @param newInstructionTerm The new instruction {@link Term}. - * @return The new created {@link MultiEvaluationResult}. - */ - public MultiEvaluationResult newInstructionTerm(Term newInstructionTerm) { - return new MultiEvaluationResult(evaluatesToTrue, evaluatesToFalse, newInstructionTerm); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "true=" + evaluatesToTrue + - ", false=" + evaluatesToFalse + - ", instruction=" + instructionTerm; - } - - /** - * Creates a pretty printed {@link String}. - * @param services The {@link Services} to use. - * @return The pretty printed {@link String}. - */ - public String toPrettyString(Services services) { - return "true=" + evaluatesToTrue + - ", false=" + evaluatesToFalse + - (instructionTerm != null ? ", instruction:\n" + ProofSaver.printTerm(instructionTerm, services) : ""); - } - - /** - * Computes the final truth value. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - * @param results All available {@link MultiEvaluationResult}s. - * @return The computed {@link TruthValue}. - */ - public TruthValue evaluate(Name termLabelName, Map results) { - if (evaluatesToTrue && evaluatesToFalse) { - return TruthValue.UNKNOWN; - } - else if (evaluatesToTrue) { - return TruthValue.TRUE; - } - else if (evaluatesToFalse) { - return TruthValue.FALSE; - } - else if (instructionTerm != null) { - return evaluateTerm(instructionTerm, termLabelName, results); - } - else { - return TruthValue.UNKNOWN; - } - } - - /*** - * Computes the {@link TruthValue} of the given instruction {@link Term}. - * @param term The instruction {@link Term} to evaluate. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - * @param results All available {@link MultiEvaluationResult}s. - * @return The computed {@link TruthValue}. - */ - private static TruthValue evaluateTerm(Term term, Name termLabelName, Map results) { - TermLabel label = term.getLabel(termLabelName); - // Return direct label result if available - if (label instanceof FormulaTermLabel) { - MultiEvaluationResult instruction = results.get(((FormulaTermLabel) label).getId()); - if (instruction != null) { - return instruction.evaluate(termLabelName, results); + } + } + + /** + * Checks if new minor IDs are available in case of {@link OneStepSimplifier} usage. + * + * @param onlyChangedChildSF The only changed {@link SequentFormula} in the child {@link Node}. + * @param label The {@link FormulaTermLabel} of interest. + * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule + * applied on succedent. + * @param tb The {@link TermBuilder} to use. + * @return The computed instruction {@link Term} or {@code null} if not available. + */ + protected static Term checkForNewMinorIdsOSS(SequentFormula onlyChangedChildSF, + FormulaTermLabel label, boolean antecedentRuleApplication, TermBuilder tb) { + // Search replacements + List antecedentReplacements = new LinkedList(); + List succedentReplacements = new LinkedList(); + if (antecedentRuleApplication) { + listLabelReplacements(onlyChangedChildSF, label.name(), label.getId(), + antecedentReplacements); + } else { + listLabelReplacements(onlyChangedChildSF, label.name(), label.getId(), + succedentReplacements); + } + // Compute term + return computeInstructionTerm(antecedentReplacements, succedentReplacements, + antecedentRuleApplication, tb); + } + + /** + * Updates the {@link PredicateResult}s based on minor ID changes if available. + * + * @param childNode The child {@link Node}. + * @param termLabelName The name of the {@link TermLabel} which is added to predicates. + * @param tb The {@link TermBuilder} to use. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void updatePredicateResultBasedOnNewMinorIds(final Node childNode, + final Name termLabelName, final TermBuilder tb, + final Map results) { + final Node parentNode = childNode.parent(); + if (parentNode != null) { + final RuleApp parentRuleApp = parentNode.getAppliedRuleApp(); + final PosInOccurrence parentPio = parentRuleApp.posInOccurrence(); + if (parentPio != null) { + // Check application term and all of its children and grand children + parentPio.subTerm().execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + checkForNewMinorIds(childNode, visited, termLabelName, parentPio, tb, + results); + } + }); + // Check application term parents + PosInOccurrence currentPio = parentPio; + while (!currentPio.isTopLevel()) { + currentPio = currentPio.up(); + checkForNewMinorIds(childNode, currentPio.subTerm(), termLabelName, parentPio, + tb, results); + } + // Check if instantiations + if (parentRuleApp instanceof TacletApp) { + TacletApp ta = (TacletApp) parentRuleApp; + if (ta.ifInstsComplete() && ta.ifFormulaInstantiations() != null) { + for (IfFormulaInstantiation ifInst : ta.ifFormulaInstantiations()) { + checkForNewMinorIds(childNode, ifInst.getConstrainedFormula().formula(), + termLabelName, parentPio, tb, results); + } + } + } } - } - // If direct label result is not available try to compute it. (e.g. because of or/and label was replaced by sequent top level formuals) - if (term.op() == Junctor.AND || - term.op() == Junctor.IMP || - term.op() == Junctor.OR || - term.op() == Equality.EQV) { - Term leftTerm = TermBuilder.goBelowUpdates(term.sub(0)); - Term rightTerm = TermBuilder.goBelowUpdates(term.sub(1)); - TermLabel leftLabel = leftTerm.getLabel(termLabelName); - TermLabel rightLabel = rightTerm.getLabel(termLabelName); - MultiEvaluationResult leftInstruction = leftLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) leftLabel).getId()) : null; - MultiEvaluationResult rightInstruction = rightLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) rightLabel).getId()) : null; - TruthValue leftValue = leftInstruction != null ? leftInstruction.evaluate(termLabelName, results) : evaluateTerm(leftTerm, termLabelName, results); - TruthValue rightValue = rightInstruction != null ? rightInstruction.evaluate(termLabelName, results) : evaluateTerm(rightTerm, termLabelName, results); - TruthValue resultValue; - if (term.op() == Junctor.AND) { - resultValue = TruthValue.and(leftValue, rightValue); + } + } + + /** + * Checks if new minor IDs are available. + * + * @param childNode The child {@link Node}. + * @param term The {@link Term} contained in the child {@link Node} to check. + * @param termLabelName The name of the {@link TermLabel} which is added to predicates. + * @param parentPio The {@link PosInOccurrence} of the applied rule of the parent {@link Node}. + * @param tb The {@link TermBuilder} to use. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void checkForNewMinorIds(Node childNode, Term term, Name termLabelName, + PosInOccurrence parentPio, TermBuilder tb, Map results) { + TermLabel label = term.getLabel(termLabelName); + if (label instanceof FormulaTermLabel) { + Term replacement = checkForNewMinorIds(childNode, (FormulaTermLabel) label, + parentPio.isInAntec(), tb); + if (replacement != null) { + updatePredicateResult((FormulaTermLabel) label, replacement, results); } - else if (term.op() == Junctor.IMP) { - resultValue = TruthValue.imp(leftValue, rightValue); + } + } + + /** + * Checks if new minor IDs are available. + * + * @param childNode The child {@link Node}. + * @param label The {@link FormulaTermLabel} of interest. + * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule + * applied on succedent. + * @param tb The {@link TermBuilder} to use. + * @return The computed instruction {@link Term} or {@code null} if not available. + */ + protected static Term checkForNewMinorIds(Node childNode, FormulaTermLabel label, + boolean antecedentRuleApplication, TermBuilder tb) { + // Search replacements + List antecedentReplacements = new LinkedList(); + List succedentReplacements = new LinkedList(); + for (SequentFormula sf : childNode.sequent().antecedent()) { + listLabelReplacements(sf, label.name(), label.getId(), antecedentReplacements); + } + for (SequentFormula sf : childNode.sequent().succedent()) { + listLabelReplacements(sf, label.name(), label.getId(), succedentReplacements); + } + // Compute term + return computeInstructionTerm(antecedentReplacements, succedentReplacements, + antecedentRuleApplication, tb); + } + + /** + * Lists all label replacements in the given {@link SequentFormula}. + * + * @param sf The {@link SequentFormula} to analyze. + * @param labelName The name of the {@link TermLabel} which is added to predicates. + * @param labelId The label ID of interest. + * @param resultToFill The result {@link List} to fill. + */ + protected static void listLabelReplacements(final SequentFormula sf, final Name labelName, + final String labelId, final List resultToFill) { + sf.formula().execPreOrder(new DefaultVisitor() { + @Override + public boolean visitSubtree(Term visited) { + return !hasLabelOfInterest(visited); } - else if (term.op() == Junctor.OR) { - resultValue = TruthValue.or(leftValue, rightValue); + + @Override + public void visit(Term visited) { + if (hasLabelOfInterest(visited)) { + resultToFill.add(visited); + } } - else if (term.op() == Equality.EQV) { - resultValue = TruthValue.eqv(leftValue, rightValue); + + protected boolean hasLabelOfInterest(Term visited) { + TermLabel visitedLabel = visited.getLabel(labelName); + if (visitedLabel instanceof FormulaTermLabel) { + FormulaTermLabel pLabel = (FormulaTermLabel) visitedLabel; + String[] beforeIds = pLabel.getBeforeIds(); + return ArrayUtil.contains(beforeIds, labelId); + } else { + return false; + } } - else { - throw new IllegalStateException("Operator '" + term.op() + "' is not supported."); + }); + } + + /** + * Computes the {@link Term} with the instruction how to compute the truth value based on the + * found replacements. + * + * @param antecedentReplacements The replacements found in the antecedent. + * @param succedentReplacements The replacements found in the succedent. + * @param antecedentRuleApplication {@code true} rule applied on antecedent, {@code false} rule + * applied on succedent. + * @param tb The {@link TermBuilder} to use. + * @return The computed instruction {@link Term} or {@code null} if not available. + */ + protected static Term computeInstructionTerm(List antecedentReplacements, + List succedentReplacements, boolean antecedentRuleApplication, TermBuilder tb) { + if (!antecedentReplacements.isEmpty() || !succedentReplacements.isEmpty()) { + Term left = tb.andPreserveLabels(antecedentReplacements); + Term right = tb.orPreserveLabels(succedentReplacements); + if (antecedentRuleApplication) { + return tb.andPreserveLabels(left, tb.notPreserveLabels(right)); + } else { + return tb.impPreserveLabels(left, right); } - return resultValue; - } - else if (term.op() == Junctor.NOT) { - Term argumentTerm = TermBuilder.goBelowUpdates(term.sub(0)); - TermLabel argumentLabel = argumentTerm.getLabel(termLabelName); - MultiEvaluationResult argumentInstruction = argumentLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) argumentLabel).getId()) : null; - TruthValue argumentValue = argumentInstruction != null ? argumentInstruction.evaluate(termLabelName, results) : evaluateTerm(argumentTerm, termLabelName, results); - TruthValue resultValue = TruthValue.not(argumentValue); - return resultValue; - } - else if (term.op() == Junctor.TRUE) { - return TruthValue.TRUE; - } - else if (term.op() == Junctor.FALSE) { - return TruthValue.FALSE; - } - else if (isIfThenElseFormula(term)) { - Term conditionTerm = TermBuilder.goBelowUpdates(term.sub(0)); - Term thenTerm = TermBuilder.goBelowUpdates(term.sub(1)); - Term elseTerm = TermBuilder.goBelowUpdates(term.sub(2)); - TermLabel conditionLabel = conditionTerm.getLabel(termLabelName); - TermLabel thenLabel = thenTerm.getLabel(termLabelName); - TermLabel elseLabel = elseTerm.getLabel(termLabelName); - MultiEvaluationResult conditionInstruction = conditionLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) conditionLabel).getId()) : null; - MultiEvaluationResult thenInstruction = thenLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) thenLabel).getId()) : null; - MultiEvaluationResult elseInstruction = elseLabel instanceof FormulaTermLabel ? results.get(((FormulaTermLabel) elseLabel).getId()) : null; - TruthValue conditionValue = conditionInstruction != null ? conditionInstruction.evaluate(termLabelName, results) : evaluateTerm(conditionTerm, termLabelName, results); - TruthValue thenValue = thenInstruction != null ? thenInstruction.evaluate(termLabelName, results) : evaluateTerm(thenTerm, termLabelName, results); - TruthValue elseValue = elseInstruction != null ? elseInstruction.evaluate(termLabelName, results) : evaluateTerm(elseTerm, termLabelName, results); - TruthValue resultValue = TruthValue.ifThenElse(conditionValue, thenValue, elseValue); - return resultValue; - } - else { + } else { return null; - } - } - } - - /** - * Represents the final predicate evaluation result returned by - * {@link TruthValueEvaluationUtil#evaluate(Node, Name, boolean, boolean). - * @author Martin Hentschel - */ - public static class TruthValueTracingResult { - /** - * The {@link BranchResult}s. - */ - private final List branchResults = new LinkedList(); - - /** - * Adds a {@link BranchResult}. - * @param result The {@link BranchResult} to add. - */ - public void addBranchResult(BranchResult result) { - if (result != null) { - branchResults.add(result); - } - } - - /** - * Returns all {@link BranchResult}s. - * @return The {@link BranchResult}s. - */ - public BranchResult[] getBranchResults() { - return branchResults.toArray(new BranchResult[branchResults.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - boolean afterFirst = false; - for (BranchResult result : branchResults) { - if (afterFirst) { - sb.append("\n\n"); - } - else { - afterFirst = true; - } - sb.append(result); - } - return sb.toString(); - } - } - - /** - * Represents the unmodifiable predicate results of a leaf {@link Node} ({@link Goal}). - * @author Martin Hentschel - */ - public static class BranchResult { - /** - * All found results. - */ - private final Map results; - - /** - * The leaf {@link Node}. - */ - private final Node leafNode; - - /** - * The condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - */ - private final Term condition; - - /** - * The human readable condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - */ - private final String conditionString; - - /** - * The {@link Name} of the {@link TermLabel} to consider. - */ - private final Name termLabelName; - - /** - * Constructor. - * @param leafNode The leaf {@link Node}. - * @param results All found results. - * @param condition The condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - * @param conditionString The human readable condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. - */ - public BranchResult(Node leafNode, - Map results, - Term condition, - String conditionString, - Name termLabelName) { - assert leafNode != null; - assert results != null; - assert termLabelName != null; - this.leafNode = leafNode; - this.results = results; - this.condition = condition; - this.conditionString = conditionString; - this.termLabelName = termLabelName; - } - - /** - * Returns all found results. - * @return All found results. - */ - public Map getResults() { - return Collections.unmodifiableMap(results); - } - - /** - * Returns the {@link MultiEvaluationResult} for the given {@link FormulaTermLabel}. - * @param termLabel The {@link FormulaTermLabel}. - * @return The found {@link MultiEvaluationResult} or {@code null} if not available. - */ - public MultiEvaluationResult getResult(FormulaTermLabel termLabel) { - return termLabel != null ? results.get(termLabel.getId()) : null; - } - - /** - * Updates a result. - *

- * Warning: {@link BranchResult}s are considered to be unmodifiable. This means that an update of the result needs to be done before results are shown to the user by the UI. - * @param termLabel The {@link FormulaTermLabel} to update. - * @param result The new result of the given {@link FormulaTermLabel}. - */ - public void updateResult(FormulaTermLabel termLabel, MultiEvaluationResult result) { - if (termLabel != null) { - results.put(termLabel.getId(), result); - } - } - - /** - * Returns the condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - * @return The condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - */ - public Term getCondition() { - return condition; - } - - /** - * Returns the human readable condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - * @return The human readable condition under which the leaf {@link Node} is reached from the analyzed {@link Node}. - */ - public String getConditionString() { - return conditionString; - } - - /** - * Returns the {@link Name} of the {@link TermLabel} to consider. - * @return The {@link Name} of the {@link TermLabel} to consider. - */ - public Name getTermLabelName() { - return termLabelName; - } - - /** - * Checks if the {@link Term} has a {@link TermLabel} with {@link Name} {@link #getTermLabelName()}. - * @param term The {@link Term} to check. - * @return {@code true} has {@link TermLabel}, {@code false} do not has {@link TermLabel}. - */ - public boolean hasPredicateLabel(Term term) { - return getPredicateLabel(term) != null; - } - - /** - * Returns the first {@link FormulaTermLabel} with {@link Name} {@link #getTermLabelName()}. - * @param term The {@link Term}. - * @return The found {@link FormulaTermLabel} or {@code null} otherwise. - */ - public FormulaTermLabel getPredicateLabel(Term term) { - TermLabel label = term.getLabel(termLabelName); - return label instanceof FormulaTermLabel ? (FormulaTermLabel) label : null; - } - - /** - * Returns the leaf {@link Node}. - * @return The leaf {@link Node}. - */ - public Node getLeafNode() { - return leafNode; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("Goal "); - sb.append(leafNode.serialNr()); - sb.append("\n"); - boolean afterFirst = false; - for (Entry entry : results.entrySet()) { - if (afterFirst) { - sb.append("\n"); - } - else { - afterFirst = true; + } + } + + /** + * Updates the instruction {@link Term} for the given {@link FormulaTermLabel} in the result + * {@link Map}. + * + * @param label The {@link FormulaTermLabel} to update its instruction {@link Term}. + * @param instructionTerm The new instruction {@link Term} to set. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void updatePredicateResult(FormulaTermLabel label, Term instructionTerm, + Map results) { + MultiEvaluationResult result = results.get(label.getId()); + if (result == null) { + result = new MultiEvaluationResult(instructionTerm); + } else { + result = result.newInstructionTerm(instructionTerm); + } + results.put(label.getId(), result); + } + + /** + * Updates the evaluation result for the given {@link FormulaTermLabel} in the result + * {@link Map}. + * + * @param label The {@link FormulaTermLabel} to update its instruction {@link Term}. + * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} + * label evaluates at least once to false. + * @param results The {@link Map} with all available {@link MultiEvaluationResult}s. + */ + protected static void updatePredicateResult(FormulaTermLabel label, boolean evaluationResult, + Map results) { + MultiEvaluationResult result = results.get(label.getId()); + if (result == null) { + result = new MultiEvaluationResult(evaluationResult); + } else { + result = result.newEvaluationResult(evaluationResult); + } + results.put(label.getId(), result); + } + + /** + * Instances of this unmodifyable class are used to store the found evaluation results. + * + * @author Martin Hentschel + */ + public static class MultiEvaluationResult { + /** + * {@code true} label evaluates at least once to true, {@code false} label never evaluates + * to true. + */ + private final boolean evaluatesToTrue; + + /** + * {@code true} label evaluates at least once to false, {@code false} label never evaluates + * to false. + */ + private final boolean evaluatesToFalse; + + /** + * The instruction {@link Term}. + */ + private final Term instructionTerm; + + /** + * Constructor. + * + * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} + * label evaluates at least once to false. + */ + public MultiEvaluationResult(boolean evaluationResult) { + this(evaluationResult, !evaluationResult, null); + } + + /** + * Constructor. + * + * @param instructionTerm The instruction {@link Term}. + */ + public MultiEvaluationResult(Term instructionTerm) { + this(false, false, instructionTerm); + } + + /** + * Constructor. + * + * @param evaluatesToTrue {@code true} label evaluates at least once to true, {@code false} + * label never evaluates to true. + * @param evaluatesToFalse {@code true} label evaluates at least once to false, + * {@code false} label never evaluates to false. + * @param instructionTerm The instruction {@link Term}. + */ + public MultiEvaluationResult(boolean evaluatesToTrue, boolean evaluatesToFalse, + Term instructionTerm) { + this.evaluatesToTrue = evaluatesToTrue; + this.evaluatesToFalse = evaluatesToFalse; + this.instructionTerm = instructionTerm; + } + + /** + * Checks if it is at least once evaluated to {@code true}. + * + * @return {@code true} label evaluates at least once to true, {@code false} label never + * evaluates to true. + */ + public boolean isEvaluatesToTrue() { + return evaluatesToTrue; + } + + /** + * Checks if it is at least once evaluated to {@code false}. + * + * @return {@code true} label evaluates at least once to false, {@code false} label never + * evaluates to false. + */ + public boolean isEvaluatesToFalse() { + return evaluatesToFalse; + } + + /** + * Returns the instruction {@link Term}. + * + * @return The instruction {@link Term} or {@code null} if undefined. + */ + public Term getInstructionTerm() { + return instructionTerm; + } + + /** + * Creates a new {@link MultiEvaluationResult} based on the current once but with an updated + * evaluation result. + * + * @param evaluationResult {@code true} label evaluates at least once to true, {@code false} + * label evaluates at least once to false. + * @return The new created {@link MultiEvaluationResult}. + */ + public MultiEvaluationResult newEvaluationResult(boolean evaluationResult) { + if (evaluationResult) { + return newEvaluatesToTrue(true); + } else { + return newEvaluatesToFalse(true); } - sb.append(entry.getKey()); - sb.append(" = "); - sb.append(entry.getValue().evaluate(termLabelName, results)); - sb.append(" :: "); - sb.append(entry.getValue()); - } - return sb.toString(); - } - - /** - * Creates a pretty printed {@link String}. - * @return The pretty printed {@link String}. - */ - public String toPrettyString() { - StringBuffer sb = new StringBuffer(); - sb.append("Goal "); - sb.append(leafNode.serialNr()); - sb.append("\n"); - boolean afterFirst = false; - for (Entry entry : results.entrySet()) { - if (afterFirst) { - sb.append("\n"); + } + + /** + * Creates a new {@link MultiEvaluationResult} based on the current once but with an update + * evaluates to true state. + * + * @param newEvaluatesToTrue {@code true} label evaluates at least once to true, + * {@code false} label never evaluates to true. + * @return The new created {@link MultiEvaluationResult}. + */ + public MultiEvaluationResult newEvaluatesToTrue(boolean newEvaluatesToTrue) { + return new MultiEvaluationResult(newEvaluatesToTrue, evaluatesToFalse, instructionTerm); + } + + /** + * Creates a new {@link MultiEvaluationResult} based on the current once but with an update + * evaluates to false state. + * + * @param newEvaluatesToFalse {@code true} label evaluates at least once to false, + * {@code false} label never evaluates to false. + * @return The new created {@link MultiEvaluationResult}. + */ + public MultiEvaluationResult newEvaluatesToFalse(boolean newEvaluatesToFalse) { + return new MultiEvaluationResult(evaluatesToTrue, newEvaluatesToFalse, instructionTerm); + } + + /** + * Creates a new {@link MultiEvaluationResult} based on the current once but with an update + * instruction term. + * + * @param newInstructionTerm The new instruction {@link Term}. + * @return The new created {@link MultiEvaluationResult}. + */ + public MultiEvaluationResult newInstructionTerm(Term newInstructionTerm) { + return new MultiEvaluationResult(evaluatesToTrue, evaluatesToFalse, newInstructionTerm); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "true=" + evaluatesToTrue + ", false=" + evaluatesToFalse + ", instruction=" + + instructionTerm; + } + + /** + * Creates a pretty printed {@link String}. + * + * @param services The {@link Services} to use. + * @return The pretty printed {@link String}. + */ + public String toPrettyString(Services services) { + return "true=" + evaluatesToTrue + ", false=" + evaluatesToFalse + + (instructionTerm != null + ? ", instruction:\n" + ProofSaver.printTerm(instructionTerm, services) + : ""); + } + + /** + * Computes the final truth value. + * + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + * @param results All available {@link MultiEvaluationResult}s. + * @return The computed {@link TruthValue}. + */ + public TruthValue evaluate(Name termLabelName, Map results) { + if (evaluatesToTrue && evaluatesToFalse) { + return TruthValue.UNKNOWN; + } else if (evaluatesToTrue) { + return TruthValue.TRUE; + } else if (evaluatesToFalse) { + return TruthValue.FALSE; + } else if (instructionTerm != null) { + return evaluateTerm(instructionTerm, termLabelName, results); + } else { + return TruthValue.UNKNOWN; } - else { - afterFirst = true; + } + + /*** + * Computes the {@link TruthValue} of the given instruction {@link Term}. + * + * @param term The instruction {@link Term} to evaluate. + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + * @param results All available {@link MultiEvaluationResult}s. + * @return The computed {@link TruthValue}. + */ + private static TruthValue evaluateTerm(Term term, Name termLabelName, + Map results) { + TermLabel label = term.getLabel(termLabelName); + // Return direct label result if available + if (label instanceof FormulaTermLabel) { + MultiEvaluationResult instruction = results.get(((FormulaTermLabel) label).getId()); + if (instruction != null) { + return instruction.evaluate(termLabelName, results); + } } - sb.append(entry.getKey()); - sb.append(" = "); - sb.append(entry.getValue().evaluate(termLabelName, results)); - sb.append(" :: "); - sb.append(entry.getValue().toPrettyString(leafNode.proof().getServices())); - } - return sb.toString(); - } - - /** - * Evaluates the given {@link FormulaTermLabel}. - * @param termLabel The {@link FormulaTermLabel} to evaluate. - * @return The evaluation result. - */ - public TruthValue evaluate(FormulaTermLabel termLabel) { - if (termLabel != null) { - MultiEvaluationResult instruction = getResult(termLabel); - return instruction != null ? instruction.evaluate(termLabelName, results) : null; - } - else { - return null; - } - } - } - - /** - * Represents the possible truth values. - * @author Martin Hentschel - */ - public static enum TruthValue { - /** - * True. - */ - TRUE, - - /** - * False. - */ - FALSE, - - /** - * Unknown in cases: - *

    - *
  • Predicate evaluates to true and false.
  • - *
  • Predicate is dropped without evaluation.
  • - *
  • Predicate is never evaluated.
  • - *
- */ - UNKNOWN; - - /** - * {@inheritDoc} - * @return - */ - @Override - public String toString() { - if (this == TRUE) { - return "true"; - } - else if (this == FALSE) { - return "false"; - } - else { - return "unknown"; - } - } - - /** - * Computes the {@code and} value. - * @param left The left {@link TruthValue}. - * @param right The right {@link TruthValue}. - * @return The computed {@code and} value. - */ - public static TruthValue and(TruthValue left, TruthValue right) { - if (left == null || UNKNOWN.equals(left)) { - if (FALSE.equals(right)) { - return FALSE; + // If direct label result is not available try to compute it. (e.g. because of or/and + // label was replaced by sequent top level formuals) + if (term.op() == Junctor.AND || term.op() == Junctor.IMP || term.op() == Junctor.OR + || term.op() == Equality.EQV) { + Term leftTerm = TermBuilder.goBelowUpdates(term.sub(0)); + Term rightTerm = TermBuilder.goBelowUpdates(term.sub(1)); + TermLabel leftLabel = leftTerm.getLabel(termLabelName); + TermLabel rightLabel = rightTerm.getLabel(termLabelName); + MultiEvaluationResult leftInstruction = leftLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) leftLabel).getId()) + : null; + MultiEvaluationResult rightInstruction = rightLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) rightLabel).getId()) + : null; + TruthValue leftValue = + leftInstruction != null ? leftInstruction.evaluate(termLabelName, results) + : evaluateTerm(leftTerm, termLabelName, results); + TruthValue rightValue = + rightInstruction != null ? rightInstruction.evaluate(termLabelName, results) + : evaluateTerm(rightTerm, termLabelName, results); + TruthValue resultValue; + if (term.op() == Junctor.AND) { + resultValue = TruthValue.and(leftValue, rightValue); + } else if (term.op() == Junctor.IMP) { + resultValue = TruthValue.imp(leftValue, rightValue); + } else if (term.op() == Junctor.OR) { + resultValue = TruthValue.or(leftValue, rightValue); + } else if (term.op() == Equality.EQV) { + resultValue = TruthValue.eqv(leftValue, rightValue); + } else { + throw new IllegalStateException( + "Operator '" + term.op() + "' is not supported."); + } + return resultValue; + } else if (term.op() == Junctor.NOT) { + Term argumentTerm = TermBuilder.goBelowUpdates(term.sub(0)); + TermLabel argumentLabel = argumentTerm.getLabel(termLabelName); + MultiEvaluationResult argumentInstruction = + argumentLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) argumentLabel).getId()) + : null; + TruthValue argumentValue = argumentInstruction != null + ? argumentInstruction.evaluate(termLabelName, results) + : evaluateTerm(argumentTerm, termLabelName, results); + TruthValue resultValue = TruthValue.not(argumentValue); + return resultValue; + } else if (term.op() == Junctor.TRUE) { + return TruthValue.TRUE; + } else if (term.op() == Junctor.FALSE) { + return TruthValue.FALSE; + } else if (isIfThenElseFormula(term)) { + Term conditionTerm = TermBuilder.goBelowUpdates(term.sub(0)); + Term thenTerm = TermBuilder.goBelowUpdates(term.sub(1)); + Term elseTerm = TermBuilder.goBelowUpdates(term.sub(2)); + TermLabel conditionLabel = conditionTerm.getLabel(termLabelName); + TermLabel thenLabel = thenTerm.getLabel(termLabelName); + TermLabel elseLabel = elseTerm.getLabel(termLabelName); + MultiEvaluationResult conditionInstruction = + conditionLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) conditionLabel).getId()) + : null; + MultiEvaluationResult thenInstruction = thenLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) thenLabel).getId()) + : null; + MultiEvaluationResult elseInstruction = elseLabel instanceof FormulaTermLabel + ? results.get(((FormulaTermLabel) elseLabel).getId()) + : null; + TruthValue conditionValue = conditionInstruction != null + ? conditionInstruction.evaluate(termLabelName, results) + : evaluateTerm(conditionTerm, termLabelName, results); + TruthValue thenValue = + thenInstruction != null ? thenInstruction.evaluate(termLabelName, results) + : evaluateTerm(thenTerm, termLabelName, results); + TruthValue elseValue = + elseInstruction != null ? elseInstruction.evaluate(termLabelName, results) + : evaluateTerm(elseTerm, termLabelName, results); + TruthValue resultValue = + TruthValue.ifThenElse(conditionValue, thenValue, elseValue); + return resultValue; + } else { + return null; } - else { - return UNKNOWN; + } + } + + /** + * Represents the final predicate evaluation result returned by + * {@link TruthValueEvaluationUtil#evaluate(Node, Name, boolean, boolean). + * + * @author Martin Hentschel + */ + public static class TruthValueTracingResult { + /** + * The {@link BranchResult}s. + */ + private final List branchResults = new LinkedList(); + + /** + * Adds a {@link BranchResult}. + * + * @param result The {@link BranchResult} to add. + */ + public void addBranchResult(BranchResult result) { + if (result != null) { + branchResults.add(result); } - } - else if (right == null || UNKNOWN.equals(right)) { - if (FALSE.equals(left)) { - return FALSE; + } + + /** + * Returns all {@link BranchResult}s. + * + * @return The {@link BranchResult}s. + */ + public BranchResult[] getBranchResults() { + return branchResults.toArray(new BranchResult[branchResults.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + boolean afterFirst = false; + for (BranchResult result : branchResults) { + if (afterFirst) { + sb.append("\n\n"); + } else { + afterFirst = true; + } + sb.append(result); } - else { - return UNKNOWN; + return sb.toString(); + } + } + + /** + * Represents the unmodifiable predicate results of a leaf {@link Node} ({@link Goal}). + * + * @author Martin Hentschel + */ + public static class BranchResult { + /** + * All found results. + */ + private final Map results; + + /** + * The leaf {@link Node}. + */ + private final Node leafNode; + + /** + * The condition under which the leaf {@link Node} is reached from the analyzed + * {@link Node}. + */ + private final Term condition; + + /** + * The human readable condition under which the leaf {@link Node} is reached from the + * analyzed {@link Node}. + */ + private final String conditionString; + + /** + * The {@link Name} of the {@link TermLabel} to consider. + */ + private final Name termLabelName; + + /** + * Constructor. + * + * @param leafNode The leaf {@link Node}. + * @param results All found results. + * @param condition The condition under which the leaf {@link Node} is reached from the + * analyzed {@link Node}. + * @param conditionString The human readable condition under which the leaf {@link Node} is + * reached from the analyzed {@link Node}. + * @param termLabelName The {@link Name} of the {@link TermLabel} to consider. + */ + public BranchResult(Node leafNode, Map results, + Term condition, String conditionString, Name termLabelName) { + assert leafNode != null; + assert results != null; + assert termLabelName != null; + this.leafNode = leafNode; + this.results = results; + this.condition = condition; + this.conditionString = conditionString; + this.termLabelName = termLabelName; + } + + /** + * Returns all found results. + * + * @return All found results. + */ + public Map getResults() { + return Collections.unmodifiableMap(results); + } + + /** + * Returns the {@link MultiEvaluationResult} for the given {@link FormulaTermLabel}. + * + * @param termLabel The {@link FormulaTermLabel}. + * @return The found {@link MultiEvaluationResult} or {@code null} if not available. + */ + public MultiEvaluationResult getResult(FormulaTermLabel termLabel) { + return termLabel != null ? results.get(termLabel.getId()) : null; + } + + /** + * Updates a result. + *

+ * Warning: {@link BranchResult}s are considered to be unmodifiable. This means that + * an update of the result needs to be done before results are shown to the user by the UI. + * + * @param termLabel The {@link FormulaTermLabel} to update. + * @param result The new result of the given {@link FormulaTermLabel}. + */ + public void updateResult(FormulaTermLabel termLabel, MultiEvaluationResult result) { + if (termLabel != null) { + results.put(termLabel.getId(), result); } - } - else { - if (TRUE.equals(left) && TRUE.equals(right)) { - return TRUE; + } + + /** + * Returns the condition under which the leaf {@link Node} is reached from the analyzed + * {@link Node}. + * + * @return The condition under which the leaf {@link Node} is reached from the analyzed + * {@link Node}. + */ + public Term getCondition() { + return condition; + } + + /** + * Returns the human readable condition under which the leaf {@link Node} is reached from + * the analyzed {@link Node}. + * + * @return The human readable condition under which the leaf {@link Node} is reached from + * the analyzed {@link Node}. + */ + public String getConditionString() { + return conditionString; + } + + /** + * Returns the {@link Name} of the {@link TermLabel} to consider. + * + * @return The {@link Name} of the {@link TermLabel} to consider. + */ + public Name getTermLabelName() { + return termLabelName; + } + + /** + * Checks if the {@link Term} has a {@link TermLabel} with {@link Name} + * {@link #getTermLabelName()}. + * + * @param term The {@link Term} to check. + * @return {@code true} has {@link TermLabel}, {@code false} do not has {@link TermLabel}. + */ + public boolean hasPredicateLabel(Term term) { + return getPredicateLabel(term) != null; + } + + /** + * Returns the first {@link FormulaTermLabel} with {@link Name} {@link #getTermLabelName()}. + * + * @param term The {@link Term}. + * @return The found {@link FormulaTermLabel} or {@code null} otherwise. + */ + public FormulaTermLabel getPredicateLabel(Term term) { + TermLabel label = term.getLabel(termLabelName); + return label instanceof FormulaTermLabel ? (FormulaTermLabel) label : null; + } + + /** + * Returns the leaf {@link Node}. + * + * @return The leaf {@link Node}. + */ + public Node getLeafNode() { + return leafNode; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("Goal "); + sb.append(leafNode.serialNr()); + sb.append("\n"); + boolean afterFirst = false; + for (Entry entry : results.entrySet()) { + if (afterFirst) { + sb.append("\n"); + } else { + afterFirst = true; + } + sb.append(entry.getKey()); + sb.append(" = "); + sb.append(entry.getValue().evaluate(termLabelName, results)); + sb.append(" :: "); + sb.append(entry.getValue()); } - else { - return FALSE; + return sb.toString(); + } + + /** + * Creates a pretty printed {@link String}. + * + * @return The pretty printed {@link String}. + */ + public String toPrettyString() { + StringBuffer sb = new StringBuffer(); + sb.append("Goal "); + sb.append(leafNode.serialNr()); + sb.append("\n"); + boolean afterFirst = false; + for (Entry entry : results.entrySet()) { + if (afterFirst) { + sb.append("\n"); + } else { + afterFirst = true; + } + sb.append(entry.getKey()); + sb.append(" = "); + sb.append(entry.getValue().evaluate(termLabelName, results)); + sb.append(" :: "); + sb.append(entry.getValue().toPrettyString(leafNode.proof().getServices())); } - } - } - - /** - * Computes the {@code imp} value. - * @param left The left {@link TruthValue}. - * @param right The right {@link TruthValue}. - * @return The computed {@code imp} value. - */ - public static TruthValue imp(TruthValue left, TruthValue right) { - return or(not(left), right); - } - - /** - * Computes the {@code or} value. - * @param left The left {@link TruthValue}. - * @param right The right {@link TruthValue}. - * @return The computed {@code or} value. - */ - public static TruthValue or(TruthValue left, TruthValue right) { - if (left == null || UNKNOWN.equals(left)) { - if (TRUE.equals(right)) { - return TRUE; + return sb.toString(); + } + + /** + * Evaluates the given {@link FormulaTermLabel}. + * + * @param termLabel The {@link FormulaTermLabel} to evaluate. + * @return The evaluation result. + */ + public TruthValue evaluate(FormulaTermLabel termLabel) { + if (termLabel != null) { + MultiEvaluationResult instruction = getResult(termLabel); + return instruction != null ? instruction.evaluate(termLabelName, results) : null; + } else { + return null; } - else { - return UNKNOWN; + } + } + + /** + * Represents the possible truth values. + * + * @author Martin Hentschel + */ + public static enum TruthValue { + /** + * True. + */ + TRUE, + + /** + * False. + */ + FALSE, + + /** + * Unknown in cases: + *

    + *
  • Predicate evaluates to true and false.
  • + *
  • Predicate is dropped without evaluation.
  • + *
  • Predicate is never evaluated.
  • + *
+ */ + UNKNOWN; + + /** + * {@inheritDoc} + * + * @return + */ + @Override + public String toString() { + if (this == TRUE) { + return "true"; + } else if (this == FALSE) { + return "false"; + } else { + return "unknown"; } - } - else if (right == null || UNKNOWN.equals(right)) { - if (TRUE.equals(left)) { - return TRUE; + } + + /** + * Computes the {@code and} value. + * + * @param left The left {@link TruthValue}. + * @param right The right {@link TruthValue}. + * @return The computed {@code and} value. + */ + public static TruthValue and(TruthValue left, TruthValue right) { + if (left == null || UNKNOWN.equals(left)) { + if (FALSE.equals(right)) { + return FALSE; + } else { + return UNKNOWN; + } + } else if (right == null || UNKNOWN.equals(right)) { + if (FALSE.equals(left)) { + return FALSE; + } else { + return UNKNOWN; + } + } else { + if (TRUE.equals(left) && TRUE.equals(right)) { + return TRUE; + } else { + return FALSE; + } } - else { - return UNKNOWN; + } + + /** + * Computes the {@code imp} value. + * + * @param left The left {@link TruthValue}. + * @param right The right {@link TruthValue}. + * @return The computed {@code imp} value. + */ + public static TruthValue imp(TruthValue left, TruthValue right) { + return or(not(left), right); + } + + /** + * Computes the {@code or} value. + * + * @param left The left {@link TruthValue}. + * @param right The right {@link TruthValue}. + * @return The computed {@code or} value. + */ + public static TruthValue or(TruthValue left, TruthValue right) { + if (left == null || UNKNOWN.equals(left)) { + if (TRUE.equals(right)) { + return TRUE; + } else { + return UNKNOWN; + } + } else if (right == null || UNKNOWN.equals(right)) { + if (TRUE.equals(left)) { + return TRUE; + } else { + return UNKNOWN; + } + } else { + if (TRUE.equals(left) || TRUE.equals(right)) { + return TRUE; + } else { + return FALSE; + } } - } - else { - if (TRUE.equals(left) || TRUE.equals(right)) { - return TRUE; + } + + /** + * Computes the {@code not} value. + * + * @param value The {@link TruthValue}. + * @return The computed {@code not} value. + */ + public static TruthValue not(TruthValue value) { + if (TRUE.equals(value)) { + return FALSE; + } else if (FALSE.equals(value)) { + return TRUE; + } else { + return UNKNOWN; } - else { - return FALSE; + } + + /** + * Computes the {@code eqv} value. + * + * @param value The {@link TruthValue}. + * @return The computed {@code not} value. + */ + public static TruthValue eqv(TruthValue left, TruthValue right) { + return or(and(left, right), and(not(left), not(right))); + } + + /** + * Computes the {@code if-then-else} value. + * + * @param conditionValue The condition value. + * @param thenValue The then value. + * @param elseValue The else value. + * @return The computed {@code if-then-else} value. + */ + public static TruthValue ifThenElse(TruthValue conditionValue, TruthValue thenValue, + TruthValue elseValue) { + if (TRUE.equals(conditionValue)) { + return thenValue; + } else if (FALSE.equals(conditionValue)) { + return elseValue; + } else { + return UNKNOWN; } - } - } - - /** - * Computes the {@code not} value. - * @param value The {@link TruthValue}. - * @return The computed {@code not} value. - */ - public static TruthValue not(TruthValue value) { - if (TRUE.equals(value)) { - return FALSE; - } - else if (FALSE.equals(value)) { - return TRUE; - } - else { - return UNKNOWN; - } - } - - /** - * Computes the {@code eqv} value. - * @param value The {@link TruthValue}. - * @return The computed {@code not} value. - */ - public static TruthValue eqv(TruthValue left, TruthValue right) { - return or(and(left, right), and(not(left), not(right))); - } - - /** - * Computes the {@code if-then-else} value. - * @param conditionValue The condition value. - * @param thenValue The then value. - * @param elseValue The else value. - * @return The computed {@code if-then-else} value. - */ - public static TruthValue ifThenElse(TruthValue conditionValue, - TruthValue thenValue, - TruthValue elseValue) { - if (TRUE.equals(conditionValue)) { - return thenValue; - } - else if (FALSE.equals(conditionValue)) { - return elseValue; - } - else { - return UNKNOWN; - } - } - } + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionAuxiliaryContract.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionAuxiliaryContract.java index 90d20c70c72..1c78f41a9c2 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionAuxiliaryContract.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionAuxiliaryContract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -12,29 +15,33 @@ * A node in the symbolic execution tree which represents a use block/loop contract application. *

*

- * The default implementation is {@link ExecutionAuxiliaryContract} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionAuxiliaryContract} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionAuxiliaryContract */ public interface IExecutionAuxiliaryContract extends IExecutionNode { - /** - * Returns the applied {@link AuxiliaryContract}. - * @return The applied {@link AuxiliaryContract}. - */ - public AuxiliaryContract getContract(); - - /** - * Returns the {@link StatementBlock} at which the {@link BlockContract} is applied. - * @return The {@link StatementBlock} at which the {@link BlockContract} is applied. - */ - public StatementBlock getBlock(); - - /** - * Checks if the precondition is complied. - * @return {@code true} precondition complied, {@code false} precondition not complied. - */ - public boolean isPreconditionComplied(); -} \ No newline at end of file + /** + * Returns the applied {@link AuxiliaryContract}. + * + * @return The applied {@link AuxiliaryContract}. + */ + public AuxiliaryContract getContract(); + + /** + * Returns the {@link StatementBlock} at which the {@link BlockContract} is applied. + * + * @return The {@link StatementBlock} at which the {@link BlockContract} is applied. + */ + public StatementBlock getBlock(); + + /** + * Checks if the precondition is complied. + * + * @return {@code true} precondition complied, {@code false} precondition not complied. + */ + public boolean isPreconditionComplied(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBaseMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBaseMethodReturn.java index 53f91167cdb..eb21fde8253 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBaseMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBaseMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -5,41 +8,49 @@ import de.uka.ilkd.key.proof.init.ProofInputException; /** - * Defines the common interface of {@link IExecutionMethodReturn} - * and {@link IExecutionExceptionalMethodReturn}. + * Defines the common interface of {@link IExecutionMethodReturn} and + * {@link IExecutionExceptionalMethodReturn}. + * * @author Martin Hentschel */ public interface IExecutionBaseMethodReturn extends IExecutionNode { - /** - * A reference to the {@link IExecutionMethodCall} which is now returned. - * @return The call of the now returned method. - */ - public IExecutionMethodCall getMethodCall(); - - /** - * Returns a human readable signature which describes this element. - * @return The human readable signature which describes this element. - * @throws ProofInputException Occurred Exception. - */ - public String getSignature() throws ProofInputException; - - /** - * Returns the condition under which this method return is reached from - * the calling {@link IExecutionMethodCall}. - * @return The method return condition to reach this node from its {@link IExecutionMethodCall} as {@link Term}. - */ - public Term getMethodReturnCondition() throws ProofInputException; - - /** - * Returns the human readable condition under which this method return is reached from - * the calling {@link IExecutionMethodCall}. - * @return The human readable method return condition to reach this node from its {@link IExecutionMethodCall}. - */ - public String getFormatedMethodReturnCondition() throws ProofInputException; - - /** - * Returns the variable value pairs of the state when the method has been called. - * @return The variable value pairs. - */ - public IExecutionVariable[] getCallStateVariables() throws ProofInputException; + /** + * A reference to the {@link IExecutionMethodCall} which is now returned. + * + * @return The call of the now returned method. + */ + public IExecutionMethodCall getMethodCall(); + + /** + * Returns a human readable signature which describes this element. + * + * @return The human readable signature which describes this element. + * @throws ProofInputException Occurred Exception. + */ + public String getSignature() throws ProofInputException; + + /** + * Returns the condition under which this method return is reached from the calling + * {@link IExecutionMethodCall}. + * + * @return The method return condition to reach this node from its {@link IExecutionMethodCall} + * as {@link Term}. + */ + public Term getMethodReturnCondition() throws ProofInputException; + + /** + * Returns the human readable condition under which this method return is reached from the + * calling {@link IExecutionMethodCall}. + * + * @return The human readable method return condition to reach this node from its + * {@link IExecutionMethodCall}. + */ + public String getFormatedMethodReturnCondition() throws ProofInputException; + + /** + * Returns the variable value pairs of the state when the method has been called. + * + * @return The variable value pairs. + */ + public IExecutionVariable[] getCallStateVariables() throws ProofInputException; } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBlockStartNode.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBlockStartNode.java index 9efd3c486b6..cac36b47182 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBlockStartNode.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBlockStartNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import org.key_project.util.collection.ImmutableList; @@ -6,18 +9,22 @@ /** * An extended {@link IExecutionNode} which groups several child nodes. + * * @author Martin Hentschel */ public interface IExecutionBlockStartNode extends IExecutionNode { - /** - * Checks if a block might be opened. - * @return {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public boolean isBlockOpened(); - - /** - * Returns the up to now discovered {@link IExecutionNode}s. - * @return The up to now discovered {@link IExecutionNode}s. - */ - public ImmutableList> getBlockCompletions(); + /** + * Checks if a block might be opened. + * + * @return {@code false} block is definitively not opened, {@code true} block is or might be + * opened. + */ + public boolean isBlockOpened(); + + /** + * Returns the up to now discovered {@link IExecutionNode}s. + * + * @return The up to now discovered {@link IExecutionNode}s. + */ + public ImmutableList> getBlockCompletions(); } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchCondition.java index ecb3a07c668..52c662cd68b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -9,69 +12,77 @@ /** *

- * A node in the symbolic execution tree which represents a branch condition, - * e.g. {@code x < 0}. + * A node in the symbolic execution tree which represents a branch condition, e.g. {@code x < 0}. *

*

- * The default implementation is {@link ExecutionBranchCondition} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionBranchCondition} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionBranchCondition */ public interface IExecutionBranchCondition extends IExecutionNode { - /** - * Returns the optional additional branch label. - * @return The additional branch label if available or {@code null} if not available. - */ - public String getAdditionalBranchLabel(); - - /** - * Checks if the value of {@link #getBranchCondition()} is already computed. - * @return {@code true} value of {@link #getBranchCondition()} is already computed, {@code false} value of {@link #getBranchCondition()} needs to be computed. - */ - public boolean isBranchConditionComputed(); - - /** - *

- * Returns the branch condition as {@link Term}. - *

- *

- * If this branch conditions merged proof nodes this {@link Term} - * is the overall branch condition. - *

- * @return The branch condition as {@link Term}. - */ - public Term getBranchCondition() throws ProofInputException; - - /** - * Returns the human readable branch condition as string. - * @return The human readable branch condition. - */ - public String getFormatedBranchCondition() throws ProofInputException; - - /** - * Checks if this branch condition is a merged one. - * @return {@code true} is merged branch condition, {@code false} is normal branch condition. - */ - public boolean isMergedBranchCondition(); - - /** - *

- * Returns the branch condition nodes in KeY's proof tree - * which are merged into this {@link IExecutionBranchCondition}. - *

- *

- * It includes also {@link #getProofNode()}. - *

- * @return The merged proof nodes. - */ - public Node[] getMergedProofNodes(); - - /** - * Returns the branch condition {@link Term}s. - * @return The branch condition {@link Term}s. - */ - public Term[] getMergedBranchCondtions() throws ProofInputException; -} \ No newline at end of file + /** + * Returns the optional additional branch label. + * + * @return The additional branch label if available or {@code null} if not available. + */ + public String getAdditionalBranchLabel(); + + /** + * Checks if the value of {@link #getBranchCondition()} is already computed. + * + * @return {@code true} value of {@link #getBranchCondition()} is already computed, + * {@code false} value of {@link #getBranchCondition()} needs to be computed. + */ + public boolean isBranchConditionComputed(); + + /** + *

+ * Returns the branch condition as {@link Term}. + *

+ *

+ * If this branch conditions merged proof nodes this {@link Term} is the overall branch + * condition. + *

+ * + * @return The branch condition as {@link Term}. + */ + public Term getBranchCondition() throws ProofInputException; + + /** + * Returns the human readable branch condition as string. + * + * @return The human readable branch condition. + */ + public String getFormatedBranchCondition() throws ProofInputException; + + /** + * Checks if this branch condition is a merged one. + * + * @return {@code true} is merged branch condition, {@code false} is normal branch condition. + */ + public boolean isMergedBranchCondition(); + + /** + *

+ * Returns the branch condition nodes in KeY's proof tree which are merged into this + * {@link IExecutionBranchCondition}. + *

+ *

+ * It includes also {@link #getProofNode()}. + *

+ * + * @return The merged proof nodes. + */ + public Node[] getMergedProofNodes(); + + /** + * Returns the branch condition {@link Term}s. + * + * @return The branch condition {@link Term}s. + */ + public Term[] getMergedBranchCondtions() throws ProofInputException; +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchStatement.java index 58822864015..690f0f84821 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionBranchStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.statement.BranchStatement; @@ -6,17 +9,17 @@ /** *

- * A node in the symbolic execution tree which represents a node which - * creates multiple child branches defined by branch conditions ({@link ISEDBranchCondition}), - * e.g. {@code if(x >= 0)}. + * A node in the symbolic execution tree which represents a node which creates multiple child + * branches defined by branch conditions ({@link ISEDBranchCondition}), e.g. {@code if(x >= 0)}. *

*

- * The default implementation is {@link ExecutionBranchStatement} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionBranchStatement} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionBranchStatement */ public interface IExecutionBranchStatement extends IExecutionBlockStartNode { -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionConstraint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionConstraint.java index ed9853b32c9..cc687cc03c4 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionConstraint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionConstraint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.logic.Term; @@ -8,19 +11,20 @@ * A constrained considered during symbolic execution. *

*

- * The default implementation is {@link ExecutionConstraint} which - * is instantiated lazily by the {@link IExecutionNode} and - * {@link IExecutionValue} implementations. + * The default implementation is {@link ExecutionConstraint} which is instantiated lazily by the + * {@link IExecutionNode} and {@link IExecutionValue} implementations. *

+ * * @author Martin Hentschel * @see IExecutionNode * @see IExecutionValue * @see ExecutionConstraint */ public interface IExecutionConstraint extends IExecutionElement { - /** - * Returns the {@link Term} representing the constraint. - * @return The {@link Term} representing the constraint. - */ - public Term getTerm(); + /** + * Returns the {@link Term} representing the constraint. + * + * @return The {@link Term} representing the constraint. + */ + public Term getTerm(); } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionElement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionElement.java index e5d942da904..c8cffcc3304 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionElement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.Services; @@ -10,75 +13,88 @@ import de.uka.ilkd.key.rule.RuleApp; /** - * Defines the basic methods and properties each element in the - * symbolic execution tree model has. + * Defines the basic methods and properties each element in the symbolic execution tree model has. + * * @author Martin Hentschel */ public interface IExecutionElement { - /** - * Returns the {@link ITreeSettings} to use. - * @return The {@link ITreeSettings} to use. - */ - public ITreeSettings getSettings(); - - /** - * Returns the {@link Services} used by {@link #getProof()}. - * @return The {@link Services} used by {@link #getProof()}. - */ - public Services getServices(); - - /** - * Returns the {@link InitConfig} used by {@link #getProof()}. - * @return The {@link InitConfig} used by {@link #getProof()}. - */ - public InitConfig getInitConfig(); - - /** - * Returns the {@link Proof} from which the symbolic execution tree was extracted. - * @return The {@link Proof} from which the symbolic execution tree was extracted. - */ - public Proof getProof(); - - /** - * Returns the {@link Node} in KeY's proof tree which is represented by this execution tree node. - * @return The {@link Node} in KeY's proof tree which is represented by this execution tree node. - */ - public Node getProofNode(); - - /** - * Returns the applied {@link RuleApp}. - * @return The applied {@link RuleApp}. - */ - public RuleApp getAppliedRuleApp(); - - /** - * Returns the {@link PosInOccurrence} of the modality of interest including updates. - * @return The {@link PosInOccurrence} of the modality of interest including updates. - */ - public PosInOccurrence getModalityPIO(); - - /** - * Returns the {@link NodeInfo} of {@link #getProofNode()}. - * @return The {@link NodeInfo} of {@link #getProofNode()}. - */ - public NodeInfo getProofNodeInfo(); - - /** - * Returns a human readable name which describes this element. - * @return The human readable name which describes this element. - * @throws ProofInputException Occurred Exception. - */ - public String getName() throws ProofInputException; - - /** - * Returns a human readable element type name. - * @return The human readable element type. - */ - public String getElementType(); - - /** - * Checks if the proof is disposed. - * @return {@code true} proof is disposed, {@code false} proof is not disposed and still valid. - */ - public boolean isDisposed(); -} \ No newline at end of file + /** + * Returns the {@link ITreeSettings} to use. + * + * @return The {@link ITreeSettings} to use. + */ + public ITreeSettings getSettings(); + + /** + * Returns the {@link Services} used by {@link #getProof()}. + * + * @return The {@link Services} used by {@link #getProof()}. + */ + public Services getServices(); + + /** + * Returns the {@link InitConfig} used by {@link #getProof()}. + * + * @return The {@link InitConfig} used by {@link #getProof()}. + */ + public InitConfig getInitConfig(); + + /** + * Returns the {@link Proof} from which the symbolic execution tree was extracted. + * + * @return The {@link Proof} from which the symbolic execution tree was extracted. + */ + public Proof getProof(); + + /** + * Returns the {@link Node} in KeY's proof tree which is represented by this execution tree + * node. + * + * @return The {@link Node} in KeY's proof tree which is represented by this execution tree + * node. + */ + public Node getProofNode(); + + /** + * Returns the applied {@link RuleApp}. + * + * @return The applied {@link RuleApp}. + */ + public RuleApp getAppliedRuleApp(); + + /** + * Returns the {@link PosInOccurrence} of the modality of interest including updates. + * + * @return The {@link PosInOccurrence} of the modality of interest including updates. + */ + public PosInOccurrence getModalityPIO(); + + /** + * Returns the {@link NodeInfo} of {@link #getProofNode()}. + * + * @return The {@link NodeInfo} of {@link #getProofNode()}. + */ + public NodeInfo getProofNodeInfo(); + + /** + * Returns a human readable name which describes this element. + * + * @return The human readable name which describes this element. + * @throws ProofInputException Occurred Exception. + */ + public String getName() throws ProofInputException; + + /** + * Returns a human readable element type name. + * + * @return The human readable element type. + */ + public String getElementType(); + + /** + * Checks if the proof is disposed. + * + * @return {@code true} proof is disposed, {@code false} proof is not disposed and still valid. + */ + public boolean isDisposed(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionExceptionalMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionExceptionalMethodReturn.java index 72403cf9760..00a7caccee6 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionExceptionalMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionExceptionalMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.statement.Throw; @@ -9,12 +12,13 @@ * A node in the symbolic execution tree which represents a exceptional method return. *

*

- * The default implementation is {@link ExecutionExceptionalMethodReturn} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionExceptionalMethodReturn} which is instantiated via + * a {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionExceptionalMethodReturn */ public interface IExecutionExceptionalMethodReturn extends IExecutionBaseMethodReturn { -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionJoin.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionJoin.java index 28128435315..dd1212a38f1 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionJoin.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionJoin.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -9,23 +12,26 @@ * A node in the symbolic execution tree which represents a join. *

*

- * The default implementation is {@link ExecutionJoin} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionJoin} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionJoin */ public interface IExecutionJoin extends IExecutionNode { - /** - * Checks if the weakening is verified. - * @return {@code true} is verified, {@code false} is not verified. - */ - public boolean isWeakeningVerified(); + /** + * Checks if the weakening is verified. + * + * @return {@code true} is verified, {@code false} is not verified. + */ + public boolean isWeakeningVerified(); - /** - * Checks if the weakening verification is supported. - * @return {@code true} supported, {@code false} not supported. - */ - public boolean isWeakeningVerificationSupported(); + /** + * Checks if the weakening verification is supported. + * + * @return {@code true} supported, {@code false} not supported. + */ + public boolean isWeakeningVerificationSupported(); } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLink.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLink.java index d6cadd83267..e22f25ff155 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLink.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLink.java @@ -1,19 +1,25 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; /** * A link between two {@link IExecutionNode}s. + * * @author Martin Hentschel */ public interface IExecutionLink { - /** - * Returns the source. - * @return The source. - */ - public IExecutionNode getSource(); + /** + * Returns the source. + * + * @return The source. + */ + public IExecutionNode getSource(); - /** - * Returns the target. - * @return The target. - */ - public IExecutionNode getTarget(); + /** + * Returns the target. + * + * @return The target. + */ + public IExecutionNode getTarget(); } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopCondition.java index bfed282bc4e..85c2fc52400 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.Expression; @@ -8,27 +11,29 @@ /** *

- * A node in the symbolic execution tree which represents a loop condition, - * e.g. {@code x >= 0}. + * A node in the symbolic execution tree which represents a loop condition, e.g. {@code x >= 0}. *

*

- * The default implementation is {@link ExecutionLoopCondition} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionLoopCondition} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionLoopCondition */ public interface IExecutionLoopCondition extends IExecutionBlockStartNode { - /** - * Returns the loop expression which is executed. - * @return The executed loop expression. - */ - public Expression getGuardExpression(); + /** + * Returns the loop expression which is executed. + * + * @return The executed loop expression. + */ + public Expression getGuardExpression(); - /** - * Returns the code position of the executed loop expression ({@link #getGuardExpression()}). - * @return The code of the executed loop expression. - */ - public PositionInfo getGuardExpressionPositionInfo(); -} \ No newline at end of file + /** + * Returns the code position of the executed loop expression ({@link #getGuardExpression()}). + * + * @return The code of the executed loop expression. + */ + public PositionInfo getGuardExpressionPositionInfo(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopInvariant.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopInvariant.java index 39857fa3e47..7ccd0d2d306 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopInvariant.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopInvariant.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -11,29 +14,33 @@ * A node in the symbolic execution tree which represents a loop invariant application. *

*

- * The default implementation is {@link ExecutionLoopInvariant} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionLoopInvariant} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionLoopInvariant */ public interface IExecutionLoopInvariant extends IExecutionNode { - /** - * Returns the used {@link LoopSpecification}. - * @return The used {@link LoopSpecification}. - */ - public LoopSpecification getLoopInvariant(); - - /** - * Returns the loop statement which is simulated by its loop invariant. - * @return The loop statement which is simulated by its loop invariant. - */ - public While getLoopStatement(); - - /** - * Checks if the loop invariant is initially valid. - * @return {@code true} initially valid, {@code false} initially invalid. - */ - public boolean isInitiallyValid(); -} \ No newline at end of file + /** + * Returns the used {@link LoopSpecification}. + * + * @return The used {@link LoopSpecification}. + */ + public LoopSpecification getLoopInvariant(); + + /** + * Returns the loop statement which is simulated by its loop invariant. + * + * @return The loop statement which is simulated by its loop invariant. + */ + public While getLoopStatement(); + + /** + * Checks if the loop invariant is initially valid. + * + * @return {@code true} initially valid, {@code false} initially invalid. + */ + public boolean isInitiallyValid(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopStatement.java index a6f1cb7977a..14d705a702b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionLoopStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.statement.LoopStatement; @@ -6,17 +9,18 @@ /** *

- * A node in the symbolic execution tree which represents a loop. - * e.g. {@code while(x >= 0)}. The loop condition ({@code x >= 0}) itself - * is represented as {@link IExecutionLoopCondition} instance. + * A node in the symbolic execution tree which represents a loop. e.g. {@code while(x >= 0)}. The + * loop condition ({@code x >= 0}) itself is represented as {@link IExecutionLoopCondition} + * instance. *

*

- * The default implementation is {@link ExecutionLoopStatement} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionLoopStatement} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionLoopStatement */ public interface IExecutionLoopStatement extends IExecutionBlockStartNode { -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodCall.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodCall.java index 2ffeef07310..d45083d9902 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodCall.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodCall.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import org.key_project.util.collection.ImmutableList; @@ -10,52 +13,60 @@ /** *

- * A node in the symbolic execution tree which represents a method call, - * e.g. {@code foo()}. + * A node in the symbolic execution tree which represents a method call, e.g. {@code foo()}. *

*

- * The default implementation is {@link ExecutionMethodCall} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionMethodCall} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionMethodCall */ public interface IExecutionMethodCall extends IExecutionNode { - /** - * Returns the {@link MethodReference} instance of the called method. - * @return The {@link MethodReference} of the called method. - */ - public MethodReference getMethodReference(); - - /** - * Returns the called {@link IProgramMethod}. - * @return The called {@link IProgramMethod}. - */ - public IProgramMethod getProgramMethod(); - - /** - * Checks if an implicit constructor is called. - * @return {@code true} implicit constructor is called, {@code false} method or explicit constructor is called. - */ - public boolean isImplicitConstructor(); - - /** - * Returns a copy of the {@link MethodReference} which calls the - * explicit constructor instead of the implicit constructor. - * @return The {@link MethodReference} to the explicit constructor or {@code null} if no constructor is called. - */ - public MethodReference getExplicitConstructorMethodReference(); - - /** - * Returns the explicit constructor. - * @return The explicit constructor or {@code null} if no constructor is called. - */ - public IProgramMethod getExplicitConstructorProgramMethod(); - - /** - * Returns the up to now discovered {@link IExecutionBaseMethodReturn}s. - * @return The up to now discovered {@link IExecutionBaseMethodReturn}s. - */ - public ImmutableList> getMethodReturns(); -} \ No newline at end of file + /** + * Returns the {@link MethodReference} instance of the called method. + * + * @return The {@link MethodReference} of the called method. + */ + public MethodReference getMethodReference(); + + /** + * Returns the called {@link IProgramMethod}. + * + * @return The called {@link IProgramMethod}. + */ + public IProgramMethod getProgramMethod(); + + /** + * Checks if an implicit constructor is called. + * + * @return {@code true} implicit constructor is called, {@code false} method or explicit + * constructor is called. + */ + public boolean isImplicitConstructor(); + + /** + * Returns a copy of the {@link MethodReference} which calls the explicit constructor instead of + * the implicit constructor. + * + * @return The {@link MethodReference} to the explicit constructor or {@code null} if no + * constructor is called. + */ + public MethodReference getExplicitConstructorMethodReference(); + + /** + * Returns the explicit constructor. + * + * @return The explicit constructor or {@code null} if no constructor is called. + */ + public IProgramMethod getExplicitConstructorProgramMethod(); + + /** + * Returns the up to now discovered {@link IExecutionBaseMethodReturn}s. + * + * @return The up to now discovered {@link IExecutionBaseMethodReturn}s. + */ + public ImmutableList> getMethodReturns(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturn.java index 7fabd01a129..63a3f502bfc 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -7,42 +10,47 @@ /** *

- * A node in the symbolic execution tree which represents a method return, - * e.g. {@code return 42}. + * A node in the symbolic execution tree which represents a method return, e.g. {@code return 42}. *

*

- * The default implementation is {@link ExecutionMethodReturn} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionMethodReturn} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

+ * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionMethodReturn */ -public interface IExecutionMethodReturn extends IExecutionBaseMethodReturn { - /** - * Returns the human readable node name including the return value ({@link #getReturnValues()}). - * @return The human readable node name including the return value. - * @throws ProofInputException Occurred Exception. - */ - public String getNameIncludingReturnValue() throws ProofInputException; - - /** - * Returns the human readable signature including the return value ({@link #getReturnValues()}). - * @return The human readable signature including the return value. - * @throws ProofInputException Occurred Exception. - */ - public String getSignatureIncludingReturnValue() throws ProofInputException; +public interface IExecutionMethodReturn extends IExecutionBaseMethodReturn { + /** + * Returns the human readable node name including the return value ({@link #getReturnValues()}). + * + * @return The human readable node name including the return value. + * @throws ProofInputException Occurred Exception. + */ + public String getNameIncludingReturnValue() throws ProofInputException; - /** - * Checks if the values of {@link #getReturnValues()} are already computed. - * @return {@code true} value of {@link #getReturnValues()} are already computed, {@code false} values of {@link #getReturnValues()} needs to be computed. - */ - public boolean isReturnValuesComputed(); - - /** - * Returns the possible return values. - * @return The possible return values. - * @throws ProofInputException Occurred Exception. - */ - public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException; -} \ No newline at end of file + /** + * Returns the human readable signature including the return value ({@link #getReturnValues()}). + * + * @return The human readable signature including the return value. + * @throws ProofInputException Occurred Exception. + */ + public String getSignatureIncludingReturnValue() throws ProofInputException; + + /** + * Checks if the values of {@link #getReturnValues()} are already computed. + * + * @return {@code true} value of {@link #getReturnValues()} are already computed, {@code false} + * values of {@link #getReturnValues()} needs to be computed. + */ + public boolean isReturnValuesComputed(); + + /** + * Returns the possible return values. + * + * @return The possible return values. + * @throws ProofInputException Occurred Exception. + */ + public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException; +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturnValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturnValue.java index 45306d5f1ba..db0b2eb93ec 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturnValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionMethodReturnValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.logic.Term; @@ -9,48 +12,54 @@ *

* A return value of an {@link IExecutionMethodReturn}. *

- * The default implementation is {@link ExecutionMethodReturnValue} which - * is instantiated via a {@link ExecutionMethodReturn} instances. - *

+ * The default implementation is {@link ExecutionMethodReturnValue} which is instantiated via a + * {@link ExecutionMethodReturn} instances. + *

+ * * @author Martin Hentschel * @see ExecutionMethodReturn * @see ExecutionMethodReturnValue */ public interface IExecutionMethodReturnValue extends IExecutionElement { - /** - * Returns the return value. - * @return The return value. - * @throws ProofInputException Occurred Exception. - */ - public Term getReturnValue() throws ProofInputException; - - /** - * Returns the return value as human readable {@link String}. - * @return The return value as human readable {@link String}. - * @throws ProofInputException Occurred Exception. - */ - public String getReturnValueString() throws ProofInputException; - - /** - * Checks if a condition is available via {@link #getCondition()} - * under which this return value is returned. - * @return {@code true} condition is available, {@code false} condition is not available. - * @throws ProofInputException - */ - public boolean hasCondition() throws ProofInputException; - - /** - * Returns the optional condition under which the return value is valid. - * @return The optional condition under which the return value is valid. - * @throws ProofInputException Occurred Exception. - */ - public Term getCondition() throws ProofInputException; - - /** - * Returns the optional condition under which the return value is valid - * as human readable {@link String}. - * @return The optional condition as human readable {@link String}. - * @throws ProofInputException Occurred Exception. - */ - public String getConditionString() throws ProofInputException; -} \ No newline at end of file + /** + * Returns the return value. + * + * @return The return value. + * @throws ProofInputException Occurred Exception. + */ + public Term getReturnValue() throws ProofInputException; + + /** + * Returns the return value as human readable {@link String}. + * + * @return The return value as human readable {@link String}. + * @throws ProofInputException Occurred Exception. + */ + public String getReturnValueString() throws ProofInputException; + + /** + * Checks if a condition is available via {@link #getCondition()} under which this return value + * is returned. + * + * @return {@code true} condition is available, {@code false} condition is not available. + * @throws ProofInputException + */ + public boolean hasCondition() throws ProofInputException; + + /** + * Returns the optional condition under which the return value is valid. + * + * @return The optional condition under which the return value is valid. + * @throws ProofInputException Occurred Exception. + */ + public Term getCondition() throws ProofInputException; + + /** + * Returns the optional condition under which the return value is valid as human readable + * {@link String}. + * + * @return The optional condition as human readable {@link String}. + * @throws ProofInputException Occurred Exception. + */ + public String getConditionString() throws ProofInputException; +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionNode.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionNode.java index 082ef9fa6b3..d7b5b82c746 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionNode.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import org.key_project.util.collection.ImmutableList; @@ -12,10 +15,9 @@ /** *

- * Provides the basic methods each node in a symbolic execution tree - * should have and allows to access the children. A symbolic execution tree - * always starts with an {@link IExecutionStart} and is created via - * a {@link SymbolicExecutionTreeBuilder} instance. + * Provides the basic methods each node in a symbolic execution tree should have and allows to + * access the children. A symbolic execution tree always starts with an {@link IExecutionStart} and + * is created via a {@link SymbolicExecutionTreeBuilder} instance. *

*

* The following concrete nodes are available @@ -26,166 +28,201 @@ *

  • {@link IExecutionBranchCondition} (branch condition, e.g. {@code x < 0})
  • *
  • {@link IExecutionMethodCall} (method call, e.g. {@code foo()})
  • *
  • {@link IExecutionMethodReturn} (method return, e.g. {@code return 42})
  • - *
  • {@link IExecutionTermination} (termination, e.g. {@code } or {@code })
  • + *
  • {@link IExecutionTermination} (termination, e.g. {@code } or + * {@code })
  • * *

    + * * @author Martin Hentschel */ public interface IExecutionNode extends IExecutionElement { - /** - * Prefix that is used in {@link IExecutionNode}s which represents an internal state in KeY which is not part of the source code. - */ - public static final String INTERNAL_NODE_NAME_START = "<"; - - /** - * Suffix that is used in {@link IExecutionNode}s which represents an internal state in KeY which is not part of the source code. - */ - public static final String INTERNAL_NODE_NAME_END = ">"; - - /** - * Returns the parent {@link IExecutionNode} or {@code null} if the - * current node is the root. - * @return The parent {@link IExecutionNode} or {@code null} on root. - */ - public IExecutionNode getParent(); - - /** - * Returns the available children. - * @return The available children. - */ - public IExecutionNode[] getChildren(); - - /** - * Checks if this node has changed the path condition of the parent. - * @return {@code true} has different path condition compared to its parent, {@code false} has same path condition as parent. - */ - public boolean isPathConditionChanged(); - - /** - * Returns the path condition to reach this node as {@link Term}. - * @return The path condition to reach this node as {@link Term}. - */ - public Term getPathCondition() throws ProofInputException; - - /** - * Returns the human readable path condition to reach this node as string. - * @return The human readable path condition as string. - */ - public String getFormatedPathCondition() throws ProofInputException; - - /** - * Returns the method call stack. - * @return The method call stack. - */ - public IExecutionNode[] getCallStack(); - - /** - * Returns all available {@link IExecutionConstraint}s. - * @return The available {@link IExecutionConstraint}s. - */ - public IExecutionConstraint[] getConstraints(); - - /** - * Returns the active statement which is executed in the code. - * @return The active statement which is executed in the code. - */ - public S getActiveStatement(); - - /** - * Returns the {@link PositionInfo} of {@link #getActiveStatement()}. - * @return The {@link PositionInfo} of {@link #getActiveStatement()}. - */ - public PositionInfo getActivePositionInfo(); - - /** - * Returns the variable value pairs of the current state. - * @return The variable value pairs. - * @throws ProofInputException Occurred Exception. - */ - public IExecutionVariable[] getVariables() throws ProofInputException; - - /** - * Returns the variable value pairs of the current state under the given condition. - * @param condition A {@link Term} specifying some additional constraints to consider. - * @return The variable value pairs. - */ - public IExecutionVariable[] getVariables(Term condition) throws ProofInputException; - - /** - * Returns the number of memory layouts. - * @return The number of memory layouts. - * @throws ProofInputException Occurred Exception. - */ - public int getLayoutsCount() throws ProofInputException; - - /** - * Returns the equivalence classes of the memory layout with the given index. - * @param layoutIndex The index of the memory layout. - * @return The equivalence classes of the memory layout at the given index. - * @throws ProofInputException Occurred Exception. - */ - public ImmutableList getLayoutsEquivalenceClasses(int layoutIndex) throws ProofInputException; - - /** - * Returns the initial memory layout before the method was executed. - * @param layoutIndex The index of the memory layout. - * @return The initial memory layout at the given index. - * @throws ProofInputException Occurred Exception. - */ - public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException; - - /** - * Returns the current memory layout which shows the memory - * structure before the current node in the symbolic execution tree is executed. - * @param layoutIndex The index of the memory layout. - * @return The current memory layout at the given index. - * @throws ProofInputException Occurred Exception. - */ - public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException; - - /** - * Returns all code blocks completed by this {@link IExecutionBlockStartNode}. - * @return All code blocks completed by this {@link IExecutionBlockStartNode}. - */ - public ImmutableList> getCompletedBlocks(); - - /** - * Returns the condition under which this node completes the code block of the given {@link IExecutionBlockStartNode}. - * @param completedNode The completed {@link IExecutionBlockStartNode} for which the condition is requested. - * @return The condition under which this node completes the code block of the given {@link IExecutionBlockStartNode}. - */ - public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException; - - /** - * Returns the human readable condition under which this node completes the code block of the given {@link IExecutionBlockStartNode}. - * @param completedNode The completed {@link IExecutionBlockStartNode} for which the condition is requested. - * @return The human readable condition under which this node completes the code block of the given {@link IExecutionBlockStartNode}. - */ - public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException; - - /** - * Returns the outgoing {@link IExecutionLink}. - * @param target The target {@link IExecutionNode}. - * @return The found {@link IExecutionLink} or {@code null} if such a link is not available. - */ - public IExecutionLink getOutgoingLink(IExecutionNode target); - - /** - * Returns all available outgoing links. - * @return The available outgoing links. - */ - public ImmutableList getOutgoingLinks(); - - /** - * Returns the incoming {@link IExecutionLink}. - * @param source The source {@link IExecutionNode}. - * @return The found {@link IExecutionLink} or {@code null} if such a link is not available. - */ - public IExecutionLink getIncomingLink(IExecutionNode source); - - /** - * Returns all available incoming links. - * @return The available incoming links. - */ - public ImmutableList getIncomingLinks(); -} \ No newline at end of file + /** + * Prefix that is used in {@link IExecutionNode}s which represents an internal state in KeY + * which is not part of the source code. + */ + public static final String INTERNAL_NODE_NAME_START = "<"; + + /** + * Suffix that is used in {@link IExecutionNode}s which represents an internal state in KeY + * which is not part of the source code. + */ + public static final String INTERNAL_NODE_NAME_END = ">"; + + /** + * Returns the parent {@link IExecutionNode} or {@code null} if the current node is the root. + * + * @return The parent {@link IExecutionNode} or {@code null} on root. + */ + public IExecutionNode getParent(); + + /** + * Returns the available children. + * + * @return The available children. + */ + public IExecutionNode[] getChildren(); + + /** + * Checks if this node has changed the path condition of the parent. + * + * @return {@code true} has different path condition compared to its parent, {@code false} has + * same path condition as parent. + */ + public boolean isPathConditionChanged(); + + /** + * Returns the path condition to reach this node as {@link Term}. + * + * @return The path condition to reach this node as {@link Term}. + */ + public Term getPathCondition() throws ProofInputException; + + /** + * Returns the human readable path condition to reach this node as string. + * + * @return The human readable path condition as string. + */ + public String getFormatedPathCondition() throws ProofInputException; + + /** + * Returns the method call stack. + * + * @return The method call stack. + */ + public IExecutionNode[] getCallStack(); + + /** + * Returns all available {@link IExecutionConstraint}s. + * + * @return The available {@link IExecutionConstraint}s. + */ + public IExecutionConstraint[] getConstraints(); + + /** + * Returns the active statement which is executed in the code. + * + * @return The active statement which is executed in the code. + */ + public S getActiveStatement(); + + /** + * Returns the {@link PositionInfo} of {@link #getActiveStatement()}. + * + * @return The {@link PositionInfo} of {@link #getActiveStatement()}. + */ + public PositionInfo getActivePositionInfo(); + + /** + * Returns the variable value pairs of the current state. + * + * @return The variable value pairs. + * @throws ProofInputException Occurred Exception. + */ + public IExecutionVariable[] getVariables() throws ProofInputException; + + /** + * Returns the variable value pairs of the current state under the given condition. + * + * @param condition A {@link Term} specifying some additional constraints to consider. + * @return The variable value pairs. + */ + public IExecutionVariable[] getVariables(Term condition) throws ProofInputException; + + /** + * Returns the number of memory layouts. + * + * @return The number of memory layouts. + * @throws ProofInputException Occurred Exception. + */ + public int getLayoutsCount() throws ProofInputException; + + /** + * Returns the equivalence classes of the memory layout with the given index. + * + * @param layoutIndex The index of the memory layout. + * @return The equivalence classes of the memory layout at the given index. + * @throws ProofInputException Occurred Exception. + */ + public ImmutableList getLayoutsEquivalenceClasses(int layoutIndex) + throws ProofInputException; + + /** + * Returns the initial memory layout before the method was executed. + * + * @param layoutIndex The index of the memory layout. + * @return The initial memory layout at the given index. + * @throws ProofInputException Occurred Exception. + */ + public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException; + + /** + * Returns the current memory layout which shows the memory structure before the current node in + * the symbolic execution tree is executed. + * + * @param layoutIndex The index of the memory layout. + * @return The current memory layout at the given index. + * @throws ProofInputException Occurred Exception. + */ + public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException; + + /** + * Returns all code blocks completed by this {@link IExecutionBlockStartNode}. + * + * @return All code blocks completed by this {@link IExecutionBlockStartNode}. + */ + public ImmutableList> getCompletedBlocks(); + + /** + * Returns the condition under which this node completes the code block of the given + * {@link IExecutionBlockStartNode}. + * + * @param completedNode The completed {@link IExecutionBlockStartNode} for which the condition + * is requested. + * @return The condition under which this node completes the code block of the given + * {@link IExecutionBlockStartNode}. + */ + public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException; + + /** + * Returns the human readable condition under which this node completes the code block of the + * given {@link IExecutionBlockStartNode}. + * + * @param completedNode The completed {@link IExecutionBlockStartNode} for which the condition + * is requested. + * @return The human readable condition under which this node completes the code block of the + * given {@link IExecutionBlockStartNode}. + */ + public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException; + + /** + * Returns the outgoing {@link IExecutionLink}. + * + * @param target The target {@link IExecutionNode}. + * @return The found {@link IExecutionLink} or {@code null} if such a link is not available. + */ + public IExecutionLink getOutgoingLink(IExecutionNode target); + + /** + * Returns all available outgoing links. + * + * @return The available outgoing links. + */ + public ImmutableList getOutgoingLinks(); + + /** + * Returns the incoming {@link IExecutionLink}. + * + * @param source The source {@link IExecutionNode}. + * @return The found {@link IExecutionLink} or {@code null} if such a link is not available. + */ + public IExecutionLink getIncomingLink(IExecutionNode source); + + /** + * Returns all available incoming links. + * + * @return The available incoming links. + */ + public ImmutableList getIncomingLinks(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionOperationContract.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionOperationContract.java index c1a19a1ba04..ecaa6b602d9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionOperationContract.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionOperationContract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import org.key_project.util.collection.ImmutableList; @@ -15,97 +18,123 @@ * A node in the symbolic execution tree which represents a use operation contract application. *

    *

    - * The default implementation is {@link ExecutionOperationContract} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionOperationContract} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

    + * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionOperationContract */ public interface IExecutionOperationContract extends IExecutionNode { - /** - * Returns the applied {@link Contract}. - * @return The applied {@link Contract}. - */ - public Contract getContract(); - - /** - * Returns the {@link IProgramMethod} of the applied {@link Contract}. - * @return The {@link IProgramMethod} of the applied {@link Contract}. - */ - public IProgramMethod getContractProgramMethod(); - - /** - * Checks if the precondition is complied. - * @return {@code true} precondition complied, {@code false} precondition not complied. - */ - public boolean isPreconditionComplied(); + /** + * Returns the applied {@link Contract}. + * + * @return The applied {@link Contract}. + */ + public Contract getContract(); - /** - * Checks if a not null check is available (instance method) or not (static method or constructor). - * @return {@code true} not null check available, {@code false} not null check is not available. - */ - public boolean hasNotNullCheck(); - - /** - * Checks if the not null check is complied. - * @return {@code true} not null check complied, {@code false} not null check not complied. - */ - public boolean isNotNullCheckComplied(); - - /** - * Returns the result {@link Term} in which the result of the applied {@link Contract} is stored. - * @return The result {@link Term} in which the result of the applied {@link Contract} is stored. - * @throws ProofInputException Occurred Exception. - */ - public Term getResultTerm() throws ProofInputException; - - /** - * Returns the exception {@link Term} in which a by the {@link Contract} thrown {@link Exception} is stored. - * @return The exception {@link Term} in which a by the {@link Contract} thrown {@link Exception} is stored. - * @throws ProofInputException Occurred Exception. - */ - public Term getExceptionTerm() throws ProofInputException; - - /** - * Returns the self {@link Term} of the called method for which a {@link Contract} is applied. - * @return The self {@link Term} or {@code null} if not available. - * @throws ProofInputException Occurred Exception. - */ - public Term getSelfTerm() throws ProofInputException; - - /** - * Returns the parameters of the called method for which a {@link Contract} is applied. - * @return The parameters of the called method for which a {@link Contract} is applied. - * @throws ProofInputException Occurred Exception. - */ - public ImmutableList getContractParams() throws ProofInputException; - - /** - * Returns the human readable result {@link Term} in which the result of the applied {@link Contract} is stored. - * @return The human readable result {@link Term} in which the result of the applied {@link Contract} is stored. - * @throws ProofInputException Occurred Exception. - */ - public String getFormatedResultTerm() throws ProofInputException; - - /** - * Returns the human readable exception {@link Term} in which a by the {@link Contract} thrown {@link Exception} is stored. - * @return The human readable exception {@link Term} in which a by the {@link Contract} thrown {@link Exception} is stored. - * @throws ProofInputException Occurred Exception. - */ - public String getFormatedExceptionTerm() throws ProofInputException; - - /** - * Returns the human readable self {@link Term} of the called method for which a {@link Contract} is applied. - * @return The human readable self {@link Term} or {@code null} if not available. - * @throws ProofInputException Occurred Exception. - */ - public String getFormatedSelfTerm() throws ProofInputException; - - /** - * Returns the human readable parameters of the called method for which a {@link Contract} is applied. - * @return The human readable parameters of the called method for which a {@link Contract} is applied. - * @throws ProofInputException Occurred Exception. - */ - public String getFormatedContractParams() throws ProofInputException; -} \ No newline at end of file + /** + * Returns the {@link IProgramMethod} of the applied {@link Contract}. + * + * @return The {@link IProgramMethod} of the applied {@link Contract}. + */ + public IProgramMethod getContractProgramMethod(); + + /** + * Checks if the precondition is complied. + * + * @return {@code true} precondition complied, {@code false} precondition not complied. + */ + public boolean isPreconditionComplied(); + + /** + * Checks if a not null check is available (instance method) or not (static method or + * constructor). + * + * @return {@code true} not null check available, {@code false} not null check is not available. + */ + public boolean hasNotNullCheck(); + + /** + * Checks if the not null check is complied. + * + * @return {@code true} not null check complied, {@code false} not null check not complied. + */ + public boolean isNotNullCheckComplied(); + + /** + * Returns the result {@link Term} in which the result of the applied {@link Contract} is + * stored. + * + * @return The result {@link Term} in which the result of the applied {@link Contract} is + * stored. + * @throws ProofInputException Occurred Exception. + */ + public Term getResultTerm() throws ProofInputException; + + /** + * Returns the exception {@link Term} in which a by the {@link Contract} thrown + * {@link Exception} is stored. + * + * @return The exception {@link Term} in which a by the {@link Contract} thrown + * {@link Exception} is stored. + * @throws ProofInputException Occurred Exception. + */ + public Term getExceptionTerm() throws ProofInputException; + + /** + * Returns the self {@link Term} of the called method for which a {@link Contract} is applied. + * + * @return The self {@link Term} or {@code null} if not available. + * @throws ProofInputException Occurred Exception. + */ + public Term getSelfTerm() throws ProofInputException; + + /** + * Returns the parameters of the called method for which a {@link Contract} is applied. + * + * @return The parameters of the called method for which a {@link Contract} is applied. + * @throws ProofInputException Occurred Exception. + */ + public ImmutableList getContractParams() throws ProofInputException; + + /** + * Returns the human readable result {@link Term} in which the result of the applied + * {@link Contract} is stored. + * + * @return The human readable result {@link Term} in which the result of the applied + * {@link Contract} is stored. + * @throws ProofInputException Occurred Exception. + */ + public String getFormatedResultTerm() throws ProofInputException; + + /** + * Returns the human readable exception {@link Term} in which a by the {@link Contract} thrown + * {@link Exception} is stored. + * + * @return The human readable exception {@link Term} in which a by the {@link Contract} thrown + * {@link Exception} is stored. + * @throws ProofInputException Occurred Exception. + */ + public String getFormatedExceptionTerm() throws ProofInputException; + + /** + * Returns the human readable self {@link Term} of the called method for which a + * {@link Contract} is applied. + * + * @return The human readable self {@link Term} or {@code null} if not available. + * @throws ProofInputException Occurred Exception. + */ + public String getFormatedSelfTerm() throws ProofInputException; + + /** + * Returns the human readable parameters of the called method for which a {@link Contract} is + * applied. + * + * @return The human readable parameters of the called method for which a {@link Contract} is + * applied. + * @throws ProofInputException Occurred Exception. + */ + public String getFormatedContractParams() throws ProofInputException; +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStart.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStart.java index c16fc27e1a8..88e3a410901 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStart.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStart.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import org.key_project.util.collection.ImmutableList; @@ -11,22 +14,25 @@ * The start node of a symbolic execution tree. *

    *

    - * The default implementation is {@link ExecutionStart} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionStart} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

    + * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionStart */ public interface IExecutionStart extends IExecutionNode { - /** - * The default name of an {@link IExecutionStart}. - */ - public static final String DEFAULT_START_NODE_NAME = INTERNAL_NODE_NAME_START + "start" + INTERNAL_NODE_NAME_END; - - /** - * Returns the up to now discovered {@link IExecutionTermination}s. - * @return The up to now discovered {@link IExecutionTermination}s. - */ - public ImmutableList getTerminations(); -} \ No newline at end of file + /** + * The default name of an {@link IExecutionStart}. + */ + public static final String DEFAULT_START_NODE_NAME = + INTERNAL_NODE_NAME_START + "start" + INTERNAL_NODE_NAME_END; + + /** + * Returns the up to now discovered {@link IExecutionTermination}s. + * + * @return The up to now discovered {@link IExecutionTermination}s. + */ + public ImmutableList getTerminations(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStatement.java index da9c79beba2..9428306f9e3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -6,16 +9,17 @@ /** *

    - * A node in the symbolic execution tree which represents a single statement, - * e.g. {@code int x = 1 + 2;}. + * A node in the symbolic execution tree which represents a single statement, e.g. + * {@code int x = 1 + 2;}. *

    *

    - * The default implementation is {@link ExecutionStatement} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionStatement} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

    + * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionStatement */ public interface IExecutionStatement extends IExecutionNode { -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionTermination.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionTermination.java index c760e83f396..883fe526e11 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionTermination.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionTermination.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.java.SourceElement; @@ -10,84 +13,91 @@ /** *

    - * A node in the symbolic execution tree which represents the normal termination of a branch, - * e.g. {@code } in case of normal termination or {@code } + * A node in the symbolic execution tree which represents the normal termination of a branch, e.g. + * {@code } in case of normal termination or {@code } * in case of exceptional termination. *

    *

    - * The default implementation is {@link ExecutionTermination} which - * is instantiated via a {@link SymbolicExecutionTreeBuilder} instance. + * The default implementation is {@link ExecutionTermination} which is instantiated via a + * {@link SymbolicExecutionTreeBuilder} instance. *

    + * * @author Martin Hentschel * @see SymbolicExecutionTreeBuilder * @see ExecutionTermination */ public interface IExecutionTermination extends IExecutionNode { - /** - * The default name of a termination node with {@link TerminationKind#NORMAL}. - */ - public static final String NORMAL_TERMINATION_NODE_NAME = INTERNAL_NODE_NAME_START + "end" + INTERNAL_NODE_NAME_END; - - /** - * The default name of a termination node with {@link TerminationKind#LOOP_BODY}. - */ - public static final String LOOP_BODY_TERMINATION_NODE_NAME = INTERNAL_NODE_NAME_START + "loop body end" + INTERNAL_NODE_NAME_END; + /** + * The default name of a termination node with {@link TerminationKind#NORMAL}. + */ + public static final String NORMAL_TERMINATION_NODE_NAME = + INTERNAL_NODE_NAME_START + "end" + INTERNAL_NODE_NAME_END; - /** - * Returns the {@link IProgramVariable} which is used in the {@link Sequent} - * of {@link Proof#root()} to check if a normal or exceptional termination - * occurred. - * @return The {@link IProgramVariable} which is used to caught global exceptions. - */ - public IProgramVariable getExceptionVariable(); - - /** - * Returns the {@link Sort} of the caught exception. - * @return The {@link Sort} of the caught exception. - */ - public Sort getExceptionSort(); - - /** - * Returns the {@link TerminationKind}. - * @return The {@link TerminationKind}. - */ - public TerminationKind getTerminationKind(); - - /** - * Checks if this branch would be closed without the uninterpreted predicate - * and thus be treated as valid/closed in a regular proof. - * @return {@code true} verified/closed, {@code false} not verified/still open - */ - public boolean isBranchVerified(); - - /** - * Defines the possible termination kinds. - * @author Martin Hentschel - */ - public static enum TerminationKind { - /** - * Normal termination without any exceptions. - */ - NORMAL, - - /** - * Termination with uncaught exception. - */ - EXCEPTIONAL, - - /** - * Partial termination of a loop body. - */ - LOOP_BODY, - - /** - * Normal termination without any exceptions of the block contract validity branch. - */ - BLOCK_CONTRACT_NORMAL, - - /** - * Termination with uncaught exception of the block contract validity branch. - */ - BLOCK_CONTRACT_EXCEPTIONAL - } -} \ No newline at end of file + /** + * The default name of a termination node with {@link TerminationKind#LOOP_BODY}. + */ + public static final String LOOP_BODY_TERMINATION_NODE_NAME = + INTERNAL_NODE_NAME_START + "loop body end" + INTERNAL_NODE_NAME_END; + + /** + * Returns the {@link IProgramVariable} which is used in the {@link Sequent} of + * {@link Proof#root()} to check if a normal or exceptional termination occurred. + * + * @return The {@link IProgramVariable} which is used to caught global exceptions. + */ + public IProgramVariable getExceptionVariable(); + + /** + * Returns the {@link Sort} of the caught exception. + * + * @return The {@link Sort} of the caught exception. + */ + public Sort getExceptionSort(); + + /** + * Returns the {@link TerminationKind}. + * + * @return The {@link TerminationKind}. + */ + public TerminationKind getTerminationKind(); + + /** + * Checks if this branch would be closed without the uninterpreted predicate and thus be treated + * as valid/closed in a regular proof. + * + * @return {@code true} verified/closed, {@code false} not verified/still open + */ + public boolean isBranchVerified(); + + /** + * Defines the possible termination kinds. + * + * @author Martin Hentschel + */ + public static enum TerminationKind { + /** + * Normal termination without any exceptions. + */ + NORMAL, + + /** + * Termination with uncaught exception. + */ + EXCEPTIONAL, + + /** + * Partial termination of a loop body. + */ + LOOP_BODY, + + /** + * Normal termination without any exceptions of the block contract validity branch. + */ + BLOCK_CONTRACT_NORMAL, + + /** + * Termination with uncaught exception of the block contract validity branch. + */ + BLOCK_CONTRACT_EXCEPTIONAL + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionValue.java index cc084e368ac..36d7caef15e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.logic.Term; @@ -6,112 +9,125 @@ /** *

    - * A value of an {@link IExecutionVariable}, e.g. - * the method parameter {@code int x = 42;} will have the variable value pair - * {@code x = 42}. This class represents the value ({@code 42}). + * A value of an {@link IExecutionVariable}, e.g. the method parameter {@code int x = 42;} will have + * the variable value pair {@code x = 42}. This class represents the value ({@code 42}). *

    *

    - * The default implementation is {@link ExecutionValue} which - * is instantiated lazily by the {@link IExecutionVariable} implementation. + * The default implementation is {@link ExecutionValue} which is instantiated lazily by the + * {@link IExecutionVariable} implementation. *

    + * * @author Martin Hentschel * @see IExecutionVariable * @see ExecutionValue */ public interface IExecutionValue extends IExecutionElement { - /** - * Returns the condition under which the variable ({@link #getVariable()}) - * has this value. - * @return The condition. - * @throws ProofInputException Occurred Exception. - */ - public Term getCondition() throws ProofInputException; - - /** - * Returns the condition under which the variable ({@link #getVariable()}) - * has this value as human readable {@link String}. - * @return The condition as human readable {@link String}. - * @throws ProofInputException Occurred Exception. - */ - public String getConditionString() throws ProofInputException; - - /** - *

    - * Checks if the value is unknown. - *

    - *

    - * Imagine the following class: - *

    
    -    * public class A {
    -    *    private A next;
    -    *    
    -    *    public int main() {
    -    *       return 42; // breakpoint
    -    *    }
    -    * }
    -    * 
    - * If the main method is debugged symbolically and stopped at the statement - * marked with the comment {@code // breakpoint} the field {@code self.next} - * has the symbolic value {@code SVself.next}. And its field - * {@code self.next.next} has again a symbolic value {@code SVself.next.next}. - * This chain is infinite deep. But on the other side the Sequent contains - * no information about {@code self.next} so the symbolic value can be - * {@code null} or a concrete object. Such symbolic values which are not - * founded in the Sequent are treated in the symbolic execution API as - * "unknown" to avoid infinite deep value hierarchies if they are not cyclic. - *

    - * @return {@code true} value is unknown, {@code false} value is known. - */ - public boolean isValueUnknown() throws ProofInputException; - - /** - * Returns the value of the variable. - * @return The value of the variable. - */ - public Term getValue() throws ProofInputException; - - /** - * Returns the value of the variable as human readable string representation. - * @return The value of the variable as human readable string representation. - */ - public String getValueString() throws ProofInputException; - - /** - *

    - * Checks if the value represents an object or an attribute of the object - * defined by the parent {@link IExecutionValue}. - *

    - *

    - * All values which are not a basic datatype (integer, boolean, ...) and - * not an instance of a library class will be treated as object. - *

    - * @return {@code true} is an object, {@code false} is an attribute of the object defined by the parent {@link IExecutionValue}. - * @throws ProofInputException Occurred Exception. - */ - public boolean isValueAnObject() throws ProofInputException; - - /** - * Returns the type of the variable as human readable string. - * @return The type of the variable as human readable string. - */ - public String getTypeString() throws ProofInputException; - - /** - * Returns the parent {@link IExecutionVariable}. - * @return The parent {@link IExecutionVariable}. - */ - public IExecutionVariable getVariable(); - - /** - * Returns contained child variables which forms complex data types. - * @return The contained child variables. - */ - public IExecutionVariable[] getChildVariables() throws ProofInputException; - - /** - * Returns all available {@link IExecutionConstraint}s. - * @return The available {@link IExecutionConstraint}s. - * @throws ProofInputException Occurred Exception. - */ - public IExecutionConstraint[] getConstraints() throws ProofInputException; -} \ No newline at end of file + /** + * Returns the condition under which the variable ({@link #getVariable()}) has this value. + * + * @return The condition. + * @throws ProofInputException Occurred Exception. + */ + public Term getCondition() throws ProofInputException; + + /** + * Returns the condition under which the variable ({@link #getVariable()}) has this value as + * human readable {@link String}. + * + * @return The condition as human readable {@link String}. + * @throws ProofInputException Occurred Exception. + */ + public String getConditionString() throws ProofInputException; + + /** + *

    + * Checks if the value is unknown. + *

    + *

    + * Imagine the following class: + * + *

    +     * 
    +     * public class A {
    +     *    private A next;
    +     *
    +     *    public int main() {
    +     *       return 42; // breakpoint
    +     *    }
    +     * }
    +     * 
    +     * 
    + * + * If the main method is debugged symbolically and stopped at the statement marked with the + * comment {@code // breakpoint} the field {@code self.next} has the symbolic value + * {@code SVself.next}. And its field {@code self.next.next} has again a symbolic value + * {@code SVself.next.next}. This chain is infinite deep. But on the other side the Sequent + * contains no information about {@code self.next} so the symbolic value can be {@code null} or + * a concrete object. Such symbolic values which are not founded in the Sequent are treated in + * the symbolic execution API as "unknown" to avoid infinite deep value hierarchies if they are + * not cyclic. + *

    + * + * @return {@code true} value is unknown, {@code false} value is known. + */ + public boolean isValueUnknown() throws ProofInputException; + + /** + * Returns the value of the variable. + * + * @return The value of the variable. + */ + public Term getValue() throws ProofInputException; + + /** + * Returns the value of the variable as human readable string representation. + * + * @return The value of the variable as human readable string representation. + */ + public String getValueString() throws ProofInputException; + + /** + *

    + * Checks if the value represents an object or an attribute of the object defined by the parent + * {@link IExecutionValue}. + *

    + *

    + * All values which are not a basic datatype (integer, boolean, ...) and not an instance of a + * library class will be treated as object. + *

    + * + * @return {@code true} is an object, {@code false} is an attribute of the object defined by the + * parent {@link IExecutionValue}. + * @throws ProofInputException Occurred Exception. + */ + public boolean isValueAnObject() throws ProofInputException; + + /** + * Returns the type of the variable as human readable string. + * + * @return The type of the variable as human readable string. + */ + public String getTypeString() throws ProofInputException; + + /** + * Returns the parent {@link IExecutionVariable}. + * + * @return The parent {@link IExecutionVariable}. + */ + public IExecutionVariable getVariable(); + + /** + * Returns contained child variables which forms complex data types. + * + * @return The contained child variables. + */ + public IExecutionVariable[] getChildVariables() throws ProofInputException; + + /** + * Returns all available {@link IExecutionConstraint}s. + * + * @return The available {@link IExecutionConstraint}s. + * @throws ProofInputException Occurred Exception. + */ + public IExecutionConstraint[] getConstraints() throws ProofInputException; +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionVariable.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionVariable.java index 31f6e1bb6a7..9cd84a5c60a 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionVariable.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/IExecutionVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; import de.uka.ilkd.key.logic.Term; @@ -7,67 +10,77 @@ /** *

    - * A variable value pair contained in an {@link IExecutionNode}, e.g. - * the method parameter {@code int x = 42;} will have the variable value pair - * {@code x = 42}. This class represents the variable ({@code x}) which is represented - * while its values are represented as child {@link IExecutionValue} instances. + * A variable value pair contained in an {@link IExecutionNode}, e.g. the method parameter + * {@code int x = 42;} will have the variable value pair {@code x = 42}. This class represents the + * variable ({@code x}) which is represented while its values are represented as child + * {@link IExecutionValue} instances. *

    *

    - * The default implementation is {@link ExecutionVariable} which - * is instantiated lazily by the {@link IExecutionNode} implementations. + * The default implementation is {@link ExecutionVariable} which is instantiated lazily by the + * {@link IExecutionNode} implementations. *

    + * * @author Martin Hentschel * @see IExecutionNode * @see IExecutionValue * @see ExecutionVariable */ public interface IExecutionVariable extends IExecutionElement { - /** - * Returns the {@link IProgramVariable} which contains the represented value. - * @return The {@link IProgramVariable} which contains the represented value. - */ - public IProgramVariable getProgramVariable(); - - /** - * Returns the index in the parent array if an array cell value is represented. - * @return The index in the parent array or {@code null} if no array cell value is represented. - */ - public Term getArrayIndex(); - - /** - * Returns the human readable index in the parent array if an array cell value is represented. - * @return The human readable index in the parent array or {@code null} if no array cell value is represented. - */ - public String getArrayIndexString(); - - /** - * Checks if the current value is part of a parent array. - * @return {@code true} is array cell value, {@code false} is a "normal" value. - */ - public boolean isArrayIndex(); - - /** - * Returns the optional additional condition considered during value computation. - * @return The optional additional condition considered during value computation. - */ - public Term getAdditionalCondition(); - - /** - * Returns the parent {@link IExecutionValue} if available. - * @return The parent {@link IExecutionValue} if available and {@code null} otherwise. - */ - public IExecutionValue getParentValue(); - - /** - * Returns the possible values of this {@link IExecutionVariable}. - * @return The possible values of this {@link IExecutionVariable}. - */ - public IExecutionValue[] getValues() throws ProofInputException; - - /** - * Creates recursive a term which can be used to determine the value - * of {@link #getProgramVariable()}. - * @return The created term. - */ - public Term createSelectTerm(); -} \ No newline at end of file + /** + * Returns the {@link IProgramVariable} which contains the represented value. + * + * @return The {@link IProgramVariable} which contains the represented value. + */ + public IProgramVariable getProgramVariable(); + + /** + * Returns the index in the parent array if an array cell value is represented. + * + * @return The index in the parent array or {@code null} if no array cell value is represented. + */ + public Term getArrayIndex(); + + /** + * Returns the human readable index in the parent array if an array cell value is represented. + * + * @return The human readable index in the parent array or {@code null} if no array cell value + * is represented. + */ + public String getArrayIndexString(); + + /** + * Checks if the current value is part of a parent array. + * + * @return {@code true} is array cell value, {@code false} is a "normal" value. + */ + public boolean isArrayIndex(); + + /** + * Returns the optional additional condition considered during value computation. + * + * @return The optional additional condition considered during value computation. + */ + public Term getAdditionalCondition(); + + /** + * Returns the parent {@link IExecutionValue} if available. + * + * @return The parent {@link IExecutionValue} if available and {@code null} otherwise. + */ + public IExecutionValue getParentValue(); + + /** + * Returns the possible values of this {@link IExecutionVariable}. + * + * @return The possible values of this {@link IExecutionVariable}. + */ + public IExecutionValue[] getValues() throws ProofInputException; + + /** + * Creates recursive a term which can be used to determine the value of + * {@link #getProgramVariable()}. + * + * @return The created term. + */ + public Term createSelectTerm(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/ITreeSettings.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/ITreeSettings.java index 371b98be6d7..9e5accf94a9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/ITreeSettings.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/ITreeSettings.java @@ -1,38 +1,50 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model; /** * Provides the settings used to construct the symbolic execution tree. + * * @author Martin Hentschel */ public interface ITreeSettings { - /** - * Checks if multiple branch conditions are merged or not. - * @return {@code true} merge branch conditions which means that a branch condition never contains another branch condition - * or {@code false} allow that branch conditions contains branch conditions. - */ - public boolean isMergeBranchConditions(); - - /** - * Checks if unicode characters are used. - * @return {@code true} use unicode characters, {@code false} do not use unicode characters. - */ - public boolean isUseUnicode(); + /** + * Checks if multiple branch conditions are merged or not. + * + * @return {@code true} merge branch conditions which means that a branch condition never + * contains another branch condition or {@code false} allow that branch conditions + * contains branch conditions. + */ + public boolean isMergeBranchConditions(); - /** - * Checks if pretty printing is used or not. - * @return {@code true} use pretty printing, {@code false} do not use pretty printing. - */ - public boolean isUsePrettyPrinting(); - - /** - * Checks how variables are computed. - * @return {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - */ - public boolean isVariablesAreOnlyComputedFromUpdates(); - - /** - * Checks if conditions should be simplified or not. - * @return {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public boolean isSimplifyConditions(); -} \ No newline at end of file + /** + * Checks if unicode characters are used. + * + * @return {@code true} use unicode characters, {@code false} do not use unicode characters. + */ + public boolean isUseUnicode(); + + /** + * Checks if pretty printing is used or not. + * + * @return {@code true} use pretty printing, {@code false} do not use pretty printing. + */ + public boolean isUsePrettyPrinting(); + + /** + * Checks how variables are computed. + * + * @return {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} + * {@link IExecutionVariable}s are computed according to the type structure of the + * visible memory. + */ + public boolean isVariablesAreOnlyComputedFromUpdates(); + + /** + * Checks if conditions should be simplified or not. + * + * @return {@code true} simplify conditions, {@code false} do not simplify conditions. + */ + public boolean isSimplifyConditions(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionBlockStartNode.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionBlockStartNode.java index 683161f9141..0d29020911e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionBlockStartNode.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionBlockStartNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import org.key_project.util.collection.ImmutableList; @@ -11,73 +14,81 @@ /** * Provides a basic implementation of {@link IExecutionBlockStartNode}. + * * @author Martin Hentschel */ -public abstract class AbstractExecutionBlockStartNode extends AbstractExecutionNode implements IExecutionBlockStartNode { - /** - * The up to know discovered completing {@link IExecutionNode}s. - */ - private ImmutableList> blockCompletions = ImmutableSLList.nil(); +public abstract class AbstractExecutionBlockStartNode + extends AbstractExecutionNode implements IExecutionBlockStartNode { + /** + * The up to know discovered completing {@link IExecutionNode}s. + */ + private ImmutableList> blockCompletions = ImmutableSLList.nil(); - /** - * Defines if a block is or might be opened. - */ - private boolean blockOpened = true; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public AbstractExecutionBlockStartNode(ITreeSettings settings, Node proofNode) { - super(settings, proofNode); - } + /** + * Defines if a block is or might be opened. + */ + private boolean blockOpened = true; - /** - * {@inheritDoc} - */ - @Override - public boolean isBlockOpened() { - return blockOpened; - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public AbstractExecutionBlockStartNode(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * Defines if a block might be opened or not. - * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or might be opened. - */ - public void setBlockOpened(boolean blockOpened) { - this.blockOpened = blockOpened; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isBlockOpened() { + return blockOpened; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getBlockCompletions() { - return blockCompletions; - } - - /** - * Removes the given block completion. - * @param completion The block completion to be removed. - * @author Anna Filighera - */ - public void removeBlockCompletion(IExecutionNode completion) { - blockCompletions = blockCompletions.removeAll(completion); - } - - /** - * Registers the given {@link IExecutionNode}. - * @param blockCompletion The {@link IExecutionNode} to register. - */ - public void addBlockCompletion(IExecutionNode blockCompletion) { - if (blockCompletion != null && !blockCompletions.contains(blockCompletion)) { - if (blockCompletion instanceof AbstractExecutionNode) { - blockCompletions = blockCompletions.append(blockCompletion); - } - else { - throw new IllegalArgumentException("Unsupported block completion: " + blockCompletion); - } - } - } + /** + * Defines if a block might be opened or not. + * + * @param blockOpened {@code false} block is definitively not opened, {@code true} block is or + * might be opened. + */ + public void setBlockOpened(boolean blockOpened) { + this.blockOpened = blockOpened; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getBlockCompletions() { + return blockCompletions; + } + + /** + * Removes the given block completion. + * + * @param completion The block completion to be removed. + * @author Anna Filighera + */ + public void removeBlockCompletion(IExecutionNode completion) { + blockCompletions = blockCompletions.removeAll(completion); + } + + /** + * Registers the given {@link IExecutionNode}. + * + * @param blockCompletion The {@link IExecutionNode} to register. + */ + public void addBlockCompletion(IExecutionNode blockCompletion) { + if (blockCompletion != null && !blockCompletions.contains(blockCompletion)) { + if (blockCompletion instanceof AbstractExecutionNode) { + blockCompletions = blockCompletions.append(blockCompletion); + } else { + throw new IllegalArgumentException( + "Unsupported block completion: " + blockCompletion); + } + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionElement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionElement.java index b81078e252f..6c7c59c2970 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionElement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.Services; @@ -15,162 +18,164 @@ /** * Provides a basic implementation of {@link IExecutionElement}. + * * @author Martin Hentschel */ public abstract class AbstractExecutionElement implements IExecutionElement { - /** - * The used {@link TreeSettings}. - */ - private final ITreeSettings settings; - - /** - * The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - private final Node proofNode; - - /** - * The human readable name of this node. - */ - private String name; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public AbstractExecutionElement(ITreeSettings settings, - Node proofNode) { - assert settings != null; - assert proofNode != null; - this.settings = settings; - this.proofNode = proofNode; - } - - /** - * {@inheritDoc} - */ - @Override - public Services getServices() { - Proof proof = getProof(); - return proof != null && !proof.isDisposed() ? proof.getServices() : null; - } - - /** - * {@inheritDoc} - */ - @Override - public RuleApp getAppliedRuleApp() { - return proofNode.getAppliedRuleApp(); - } - - /** - * {@inheritDoc} - */ - @Override - public InitConfig getInitConfig() { - Proof proof = getProof(); - return proof != null && !proof.isDisposed() ? proof.getInitConfig() : null; - } - - /** - * {@inheritDoc} - */ - @Override - public Proof getProof() { - return getProofNode().proof(); - } - - /** - * {@inheritDoc} - */ - @Override - public Node getProofNode() { - return proofNode; - } - - /** - * {@inheritDoc} - */ - @Override - public NodeInfo getProofNodeInfo() { - return getProofNode().getNodeInfo(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() throws ProofInputException { - synchronized (this) { - if (name == null) { - name = lazyComputeName(); - } - return name; - } - } - - /** - * Sets the name. - * @param name The new name to set. - */ - protected void setName(String name) { - this.name = name; - } - - /** - * Checks if the value of {@link #getName()} is already computed. - * @return {@code ture} name is computed, {@code false} name is not computed yet. - */ - protected boolean isNameComputed() { - return name != null; - } - - /** - * Computes the name of this node lazily when {@link #getName()} - * is called the first time. - * @return The human readable name of this {@link IExecutionNode}. - */ - protected abstract String lazyComputeName() throws ProofInputException; - - /** - * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. - * @param term The {@link Term} to convert. - * @param services The {@link Services} to use. - * @return The {@link String} representation of the given {@link Term}. - */ - protected String formatTerm(Term term, Services services) { - return SymbolicExecutionUtil.formatTerm(term, - services, - settings.isUseUnicode(), - settings.isUsePrettyPrinting()); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - try { - return getElementType() + " " + getName(); - } - catch (ProofInputException e) { - return getElementType() + " " + e.getMessage(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isDisposed() { - return getProof().isDisposed(); - } - - /** - * {@inheritDoc} - */ - @Override - public ITreeSettings getSettings() { - return settings; - } -} \ No newline at end of file + /** + * The used {@link TreeSettings}. + */ + private final ITreeSettings settings; + + /** + * The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. + */ + private final Node proofNode; + + /** + * The human readable name of this node. + */ + private String name; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public AbstractExecutionElement(ITreeSettings settings, Node proofNode) { + assert settings != null; + assert proofNode != null; + this.settings = settings; + this.proofNode = proofNode; + } + + /** + * {@inheritDoc} + */ + @Override + public Services getServices() { + Proof proof = getProof(); + return proof != null && !proof.isDisposed() ? proof.getServices() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public RuleApp getAppliedRuleApp() { + return proofNode.getAppliedRuleApp(); + } + + /** + * {@inheritDoc} + */ + @Override + public InitConfig getInitConfig() { + Proof proof = getProof(); + return proof != null && !proof.isDisposed() ? proof.getInitConfig() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public Proof getProof() { + return getProofNode().proof(); + } + + /** + * {@inheritDoc} + */ + @Override + public Node getProofNode() { + return proofNode; + } + + /** + * {@inheritDoc} + */ + @Override + public NodeInfo getProofNodeInfo() { + return getProofNode().getNodeInfo(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() throws ProofInputException { + synchronized (this) { + if (name == null) { + name = lazyComputeName(); + } + return name; + } + } + + /** + * Sets the name. + * + * @param name The new name to set. + */ + protected void setName(String name) { + this.name = name; + } + + /** + * Checks if the value of {@link #getName()} is already computed. + * + * @return {@code ture} name is computed, {@code false} name is not computed yet. + */ + protected boolean isNameComputed() { + return name != null; + } + + /** + * Computes the name of this node lazily when {@link #getName()} is called the first time. + * + * @return The human readable name of this {@link IExecutionNode}. + */ + protected abstract String lazyComputeName() throws ProofInputException; + + /** + * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. + * + * @param term The {@link Term} to convert. + * @param services The {@link Services} to use. + * @return The {@link String} representation of the given {@link Term}. + */ + protected String formatTerm(Term term, Services services) { + return SymbolicExecutionUtil.formatTerm(term, services, settings.isUseUnicode(), + settings.isUsePrettyPrinting()); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + try { + return getElementType() + " " + getName(); + } catch (ProofInputException e) { + return getElementType() + " " + e.getMessage(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDisposed() { + return getProof().isDisposed(); + } + + /** + * {@inheritDoc} + */ + @Override + public ITreeSettings getSettings() { + return settings; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionMethodReturn.java index 6dfada83f22..9ab61efe06c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.LinkedList; @@ -22,168 +25,177 @@ /** * The default implementation of {@link IExecutionBaseMethodReturn}. + * * @author Martin Hentschel */ -public abstract class AbstractExecutionMethodReturn extends AbstractExecutionNode implements IExecutionBaseMethodReturn { - /** - * The {@link IExecutionMethodCall} which is now returned. - */ - private final ExecutionMethodCall methodCall; - - /** - * The signature. - */ - private String signature; - - /** - * The method return condition to reach this node from its calling {@link IExecutionMethodCall}. - */ - private Term methodReturnCondition; - - /** - * The human readable method return condition to reach this node from its calling {@link IExecutionMethodCall}. - */ - private String formatedMethodReturnCondition; - - /** - * The variable value pairs of the state when the method has been called. - */ - private IExecutionVariable[] callStateVariables; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param methodCall The {@link IExecutionMethodCall} which is now returned. - */ - public AbstractExecutionMethodReturn(ITreeSettings settings, - Node proofNode, - ExecutionMethodCall methodCall) { - super(settings, proofNode); - assert methodCall != null; - this.methodCall = methodCall; - this.methodCall.addMethodReturn(this); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionMethodCall getMethodCall() { - return methodCall; - } - - /** - * {@inheritDoc} - */ - @Override - public String getSignature() throws ProofInputException { - if (signature == null) { - signature = lazyComputeSignature(); - } - return signature; - } - - /** - * Computes the signature lazily when - * {@link #getSignature()} is called the first time. - * @return The name including the return value. - * @throws Occurred Exception. - */ - protected abstract String lazyComputeSignature() throws ProofInputException; - - - /** - * {@inheritDoc} - */ - @Override - public Term getMethodReturnCondition() throws ProofInputException { - if (methodReturnCondition == null) { - lazyComputeMethodReturnCondition(); - } - return methodReturnCondition; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedMethodReturnCondition() throws ProofInputException { - if (methodReturnCondition == null) { - lazyComputeMethodReturnCondition(); - } - return formatedMethodReturnCondition; - } - - /** - * Computes the method return condition lazily when {@link #getMethodReturnCondition()} - * or {@link #getFormatedMethodReturnCondition()} is called the first time. - * @throws ProofInputException Occurred Exception - */ - protected void lazyComputeMethodReturnCondition() throws ProofInputException { - final InitConfig initConfig = getProof().getInitConfig(); - if (initConfig != null) { // Otherwise Proof is disposed. - final Services services = initConfig.getServices(); - // Collect branch conditions - List bcs = new LinkedList(); - AbstractExecutionNode parent = getParent(); - while (parent != null && parent != methodCall) { - if (parent instanceof IExecutionBranchCondition) { - bcs.add(((IExecutionBranchCondition)parent).getBranchCondition()); +public abstract class AbstractExecutionMethodReturn + extends AbstractExecutionNode implements IExecutionBaseMethodReturn { + /** + * The {@link IExecutionMethodCall} which is now returned. + */ + private final ExecutionMethodCall methodCall; + + /** + * The signature. + */ + private String signature; + + /** + * The method return condition to reach this node from its calling {@link IExecutionMethodCall}. + */ + private Term methodReturnCondition; + + /** + * The human readable method return condition to reach this node from its calling + * {@link IExecutionMethodCall}. + */ + private String formatedMethodReturnCondition; + + /** + * The variable value pairs of the state when the method has been called. + */ + private IExecutionVariable[] callStateVariables; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param methodCall The {@link IExecutionMethodCall} which is now returned. + */ + public AbstractExecutionMethodReturn(ITreeSettings settings, Node proofNode, + ExecutionMethodCall methodCall) { + super(settings, proofNode); + assert methodCall != null; + this.methodCall = methodCall; + this.methodCall.addMethodReturn(this); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionMethodCall getMethodCall() { + return methodCall; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignature() throws ProofInputException { + if (signature == null) { + signature = lazyComputeSignature(); + } + return signature; + } + + /** + * Computes the signature lazily when {@link #getSignature()} is called the first time. + * + * @return The name including the return value. + * @throws Occurred Exception. + */ + protected abstract String lazyComputeSignature() throws ProofInputException; + + + /** + * {@inheritDoc} + */ + @Override + public Term getMethodReturnCondition() throws ProofInputException { + if (methodReturnCondition == null) { + lazyComputeMethodReturnCondition(); + } + return methodReturnCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedMethodReturnCondition() throws ProofInputException { + if (methodReturnCondition == null) { + lazyComputeMethodReturnCondition(); + } + return formatedMethodReturnCondition; + } + + /** + * Computes the method return condition lazily when {@link #getMethodReturnCondition()} or + * {@link #getFormatedMethodReturnCondition()} is called the first time. + * + * @throws ProofInputException Occurred Exception + */ + protected void lazyComputeMethodReturnCondition() throws ProofInputException { + final InitConfig initConfig = getProof().getInitConfig(); + if (initConfig != null) { // Otherwise Proof is disposed. + final Services services = initConfig.getServices(); + // Collect branch conditions + List bcs = new LinkedList(); + AbstractExecutionNode parent = getParent(); + while (parent != null && parent != methodCall) { + if (parent instanceof IExecutionBranchCondition) { + bcs.add(((IExecutionBranchCondition) parent).getBranchCondition()); + } + parent = parent.getParent(); } - parent = parent.getParent(); - } - // Add current branch condition to path - methodReturnCondition = services.getTermBuilder().and(bcs); - // Simplify path condition - if (getSettings().isSimplifyConditions()) { - methodReturnCondition = SymbolicExecutionUtil.simplify(initConfig, getProof(), methodReturnCondition); - } - methodReturnCondition = SymbolicExecutionUtil.improveReadability(methodReturnCondition, services); - // Format path condition - formatedMethodReturnCondition = formatTerm(methodReturnCondition, services); - } - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getCallStateVariables() throws ProofInputException { - synchronized (this) { - if (callStateVariables == null) { - callStateVariables = lazyComputeCallStateVariables(); - } - return callStateVariables; - } - } - - /** - * Computes the variables lazily when {@link #getCallStateVariables()} is - * called the first time. - * @return The {@link IExecutionVariable}s of the state when the method has been called. - * @throws ProofInputException - */ - protected IExecutionVariable[] lazyComputeCallStateVariables() throws ProofInputException { - // Get relevant information in current node - Node proofNode = methodCall.getProofNode(); - assert proofNode.childrenCount() == 1; - PosInOccurrence originalPIO = methodCall.getModalityPIO(); - int index = originalPIO.isInAntec() ? - proofNode.sequent().antecedent().indexOf(originalPIO.sequentFormula()) : - proofNode.sequent().succedent().indexOf(originalPIO.sequentFormula()); - // Search relevant position in child node - Node childNode = proofNode.child(0); - SequentFormula nodeSF = originalPIO.isInAntec() ? - childNode.sequent().antecedent().get(index) : - childNode.sequent().succedent().get(index); - PosInOccurrence modalityPIO = new PosInOccurrence(nodeSF, originalPIO.posInTerm(), originalPIO.isInAntec()); - Term modalityTerm = modalityPIO.subTerm(); - while (modalityTerm.op() instanceof UpdateApplication) { - modalityPIO = modalityPIO.down(1); - modalityTerm = modalityPIO.subTerm(); - } - // Compute variables - return SymbolicExecutionUtil.createExecutionVariables(this, childNode, modalityPIO, getMethodReturnCondition()); - } + // Add current branch condition to path + methodReturnCondition = services.getTermBuilder().and(bcs); + // Simplify path condition + if (getSettings().isSimplifyConditions()) { + methodReturnCondition = SymbolicExecutionUtil.simplify(initConfig, getProof(), + methodReturnCondition); + } + methodReturnCondition = + SymbolicExecutionUtil.improveReadability(methodReturnCondition, services); + // Format path condition + formatedMethodReturnCondition = formatTerm(methodReturnCondition, services); + } + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getCallStateVariables() throws ProofInputException { + synchronized (this) { + if (callStateVariables == null) { + callStateVariables = lazyComputeCallStateVariables(); + } + return callStateVariables; + } + } + + /** + * Computes the variables lazily when {@link #getCallStateVariables()} is called the first time. + * + * @return The {@link IExecutionVariable}s of the state when the method has been called. + * @throws ProofInputException + */ + protected IExecutionVariable[] lazyComputeCallStateVariables() throws ProofInputException { + // Get relevant information in current node + Node proofNode = methodCall.getProofNode(); + assert proofNode.childrenCount() == 1; + PosInOccurrence originalPIO = methodCall.getModalityPIO(); + int index = originalPIO.isInAntec() + ? proofNode.sequent().antecedent().indexOf(originalPIO.sequentFormula()) + : proofNode.sequent().succedent().indexOf(originalPIO.sequentFormula()); + // Search relevant position in child node + Node childNode = proofNode.child(0); + SequentFormula nodeSF = + originalPIO.isInAntec() ? childNode.sequent().antecedent().get(index) + : childNode.sequent().succedent().get(index); + PosInOccurrence modalityPIO = + new PosInOccurrence(nodeSF, originalPIO.posInTerm(), originalPIO.isInAntec()); + Term modalityTerm = modalityPIO.subTerm(); + while (modalityTerm.op() instanceof UpdateApplication) { + modalityPIO = modalityPIO.down(1); + modalityTerm = modalityPIO.subTerm(); + } + // Compute variables + return SymbolicExecutionUtil.createExecutionVariables(this, childNode, modalityPIO, + getMethodReturnCondition()); + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionNode.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionNode.java index 25d33114b5d..ab1b9fb7132 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionNode.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.HashMap; @@ -33,541 +36,563 @@ /** * Provides a basic implementation of {@link IExecutionNode}. + * * @author Martin Hentschel */ -public abstract class AbstractExecutionNode extends AbstractExecutionElement implements IExecutionNode { - /** - * Reference to the parent {@link IExecutionNode}. - */ - private AbstractExecutionNode parent; - - /** - * Contains all child {@link IExecutionNode}s. - */ - private final List> children = new LinkedList>(); - - /** - * The contained call stack. - */ - private IExecutionNode[] callStack; - - /** - * The available {@link IExecutionConstraint}s. - */ - private IExecutionConstraint[] constraints; - - /** - * The variable value pairs of the current state. - */ - private IExecutionVariable[] variables; - - /** - * The variable value pairs of the current state under given conditions. - */ - private final Map conditionalVariables = new HashMap(); - - /** - * The used {@link ExecutionNodeSymbolicLayoutExtractor}. - */ - private ExecutionNodeSymbolicLayoutExtractor layoutExtractor; - - /** - * The {@link PosInOccurrence} of the modality or its updates. - */ - private PosInOccurrence modalityPIO; - - /** - * The up to know discovered completed {@link IExecutionBlockStartNode}s. - */ - private ImmutableList> completedBlocks = ImmutableSLList.nil(); - - /** - * The already computed block completion conditions. - */ - private final Map, Term> blockCompletionConditions = new HashMap, Term>(); - - /** - * The already computed human readable block completion conditions. - */ - private final Map, String> formatedBlockCompletionConditions = new HashMap, String>(); - - /** - * The up to know discovered outgoing links. - */ - private ImmutableList outgoingLinks = ImmutableSLList.nil(); - - /** - * The up to know discovered incoming links. - */ - private ImmutableList incomingLinks = ImmutableSLList.nil(); - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public AbstractExecutionNode(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractExecutionNode getParent() { - return parent; - } - - /** - * Sets the parent {@link AbstractExecutionNode}. - * @param parent The parent {@link AbstractExecutionNode} to set. - */ - public void setParent(AbstractExecutionNode parent) { - this.parent = parent; - } - - /** - * {@inheritDoc} - */ - @Override - public AbstractExecutionNode[] getChildren() { - return children.toArray(new AbstractExecutionNode[children.size()]); - } - - /** - * Adds a new child {@link AbstractExecutionNode}. - * @param child A new child {@link AbstractExecutionNode}. - */ - public void addChild(AbstractExecutionNode child) { - if (child != null) { - children.add(child); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isPathConditionChanged() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getPathCondition() throws ProofInputException { - // Search path condition of the parent which is used by default. - Term result = null; - AbstractExecutionNode parent = getParent(); - while (result == null && parent != null) { - if (parent.isPathConditionChanged()) { - result = parent.getPathCondition(); - } - else { - parent = parent.getParent(); - } - } - // Check if a path condition was found. - return result != null ? result : getServices().getTermBuilder().tt(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedPathCondition() throws ProofInputException { - // Search path condition of the parent which is used by default. - String result = null; - AbstractExecutionNode parent = getParent(); - while (result == null && parent != null) { - if (parent.isPathConditionChanged()) { - result = parent.getFormatedPathCondition(); - } - else { - parent = parent.getParent(); - } - } - // Check if a path condition was found. - if (!isDisposed()) { - return result != null ? result : getServices().getTermBuilder().tt().toString(); - } - else { - return result; - } - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode[] getCallStack() { - return callStack; - } - - /** - * Sets the call stack. - * @param callStack The call stack. - */ - public void setCallStack(IExecutionNode[] callStack) { - this.callStack = callStack; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionConstraint[] getConstraints() { - synchronized (this) { - if (constraints == null) { - constraints = lazyComputeConstraints(); - } - return constraints; - } - } - - /** - * Computes the constraints lazily when {@link #getConstraints()} is - * called the first time. - * @return The {@link IExecutionConstraint}s of the current state. - */ - protected abstract IExecutionConstraint[] lazyComputeConstraints(); - - /** - * {@inheritDoc} - */ - @SuppressWarnings("unchecked") - @Override - public S getActiveStatement() { - return (S)getProofNodeInfo().getActiveStatement(); - } - - /** - * {@inheritDoc} - */ - @Override - public PositionInfo getActivePositionInfo() { - return getActiveStatement().getPositionInfo(); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getVariables() throws ProofInputException { - synchronized (this) { - if (variables == null) { - variables = lazyComputeVariables(); - } - return variables; - } - } - - /** - * Computes the variables lazily when {@link #getVariables()} is - * called the first time. - * @return The {@link IExecutionVariable}s of the current state. - * @throws ProofInputException - */ - protected IExecutionVariable[] lazyComputeVariables() throws ProofInputException { - return SymbolicExecutionUtil.createExecutionVariables(this); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getVariables(Term condition) throws ProofInputException { - synchronized (this) { - IExecutionVariable[] result = conditionalVariables.get(condition); - if (result == null) { - result = lazyComputeVariables(condition); - conditionalVariables.put(condition, result); - } - return result; - } - } - - /** - * Computes the variables lazily when {@link #getVariables(Term)} is - * called the first time. - * @param condition A {@link Term} specifying some additional constraints to consider. - * @return The {@link IExecutionVariable}s of the current state under the given condition. - * @throws ProofInputException - */ - protected IExecutionVariable[] lazyComputeVariables(Term condition) throws ProofInputException { - return SymbolicExecutionUtil.createExecutionVariables(this, condition); - } - - /** - * Returns the used {@link ExecutionNodeSymbolicLayoutExtractor}. - * @return The used {@link ExecutionNodeSymbolicLayoutExtractor}. - * @throws ProofInputException Occurred Exception. - */ - public ExecutionNodeSymbolicLayoutExtractor getLayoutExtractor() throws ProofInputException { - synchronized (this) { - if (layoutExtractor == null) { - layoutExtractor = lazyComputeLayoutExtractor(); - } - return layoutExtractor; - } - } - - /** - * Instantiates the used {@link ExecutionNodeSymbolicLayoutExtractor} lazily - * when {@link #getLayoutExtractor()} is called the first time. - * @return The created {@link ExecutionNodeSymbolicLayoutExtractor}. - * @throws ProofInputException Occurred Exception. - */ - protected ExecutionNodeSymbolicLayoutExtractor lazyComputeLayoutExtractor() throws ProofInputException { - ExecutionNodeSymbolicLayoutExtractor result = new ExecutionNodeSymbolicLayoutExtractor(this); - result.analyse(); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public int getLayoutsCount() throws ProofInputException { - return getLayoutExtractor().getLayoutsCount(); - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException { - return getLayoutExtractor().getInitialLayout(layoutIndex); - } - - /** - * {@inheritDoc} - */ - @Override - public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException { - return getLayoutExtractor().getCurrentLayout(layoutIndex); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getLayoutsEquivalenceClasses(int layoutIndex) throws ProofInputException { - return getLayoutExtractor().getEquivalenceClasses(layoutIndex); - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - if (modalityPIO == null) { - modalityPIO = lazyComputeModalityPIO(); - } - return modalityPIO; - } - - /** - * Computes the {@link PosInOccurrence} lazily when {@link #getModalityPIO()} is - * called the first time. - * @return The {@link PosInOccurrence}s of the modality or its updates. - */ - protected PosInOccurrence lazyComputeModalityPIO() { - PosInOccurrence originalPio = getProofNode().getAppliedRuleApp().posInOccurrence(); - // Try to go back to the parent which provides the updates - PosInOccurrence pio = originalPio; - Term term = pio.subTerm(); - if (!pio.isTopLevel() && term.op() != UpdateApplication.UPDATE_APPLICATION) { - pio = pio.up(); - term = pio.subTerm(); - } - // Return found updates or the original pio otherwise - return term.op() == UpdateApplication.UPDATE_APPLICATION ? - pio : - originalPio; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getCompletedBlocks() { - return completedBlocks; - } - - /** - * Registers the given {@link IExecutionBlockStartNode}. - * @param completedBlock The {@link IExecutionBlockStartNode} to register. - */ - public void addCompletedBlock(IExecutionBlockStartNode completedBlock) { - if (completedBlock != null && !completedBlocks.contains(completedBlock)) { - completedBlocks = completedBlocks.append(completedBlock); - } - } - - /** - * Removes the given {@link IExecutionBlockStartNode} from registration. - * @param completedBlock The {@link IExecutionBlockStartNode} to be remove. - * @author Anna Filighera - */ - public void removeCompletedBlock(IExecutionBlockStartNode completedBlock) { - if (completedBlock != null && completedBlocks.contains(completedBlock)) { - completedBlocks = completedBlocks.removeAll(completedBlock); - blockCompletionConditions.remove(completedBlock); - formatedBlockCompletionConditions.remove(completedBlock); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException { - Term result = blockCompletionConditions.get(completedNode); - if (result == null) { - result = (Term) lazyComputeBlockCompletionCondition(completedNode, false); - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) throws ProofInputException { - String result = formatedBlockCompletionConditions.get(completedNode); - if (result == null) { - result = (String) lazyComputeBlockCompletionCondition(completedNode, true); - } - return result; - } - - /** - * Computes the condition lazily when {@link #getBlockCompletionCondition(IExecutionNode)} - * or {@link #getFormatedBlockCompletionCondition(IExecutionNode)} is called the first time. - * @param completedNode The completed {@link IExecutionNode} for which the condition is requested. - * @param returnFormatedCondition {@code true} formated condition is returned, {@code false} {@link Term} is returned. - * @throws ProofInputException Occurred Exception - */ - protected Object lazyComputeBlockCompletionCondition(IExecutionBlockStartNode completedNode, boolean returnFormatedCondition) throws ProofInputException { - final InitConfig initConfig = getInitConfig(); - if (initConfig != null && // Otherwise Proof is disposed. - completedBlocks.contains(completedNode)) { - final Services services = initConfig.getServices(); - // Collect branch conditions - List bcs = new LinkedList(); - AbstractExecutionNode parent = getParent(); - while (parent != null && parent != completedNode) { - if (parent instanceof IExecutionBranchCondition) { - Term bc = ((IExecutionBranchCondition)parent).getBranchCondition(); - if (bc == null) { - return null; // Proof disposed in between, computation not possible - } - bcs.add(bc); +public abstract class AbstractExecutionNode + extends AbstractExecutionElement implements IExecutionNode { + /** + * Reference to the parent {@link IExecutionNode}. + */ + private AbstractExecutionNode parent; + + /** + * Contains all child {@link IExecutionNode}s. + */ + private final List> children = new LinkedList>(); + + /** + * The contained call stack. + */ + private IExecutionNode[] callStack; + + /** + * The available {@link IExecutionConstraint}s. + */ + private IExecutionConstraint[] constraints; + + /** + * The variable value pairs of the current state. + */ + private IExecutionVariable[] variables; + + /** + * The variable value pairs of the current state under given conditions. + */ + private final Map conditionalVariables = + new HashMap(); + + /** + * The used {@link ExecutionNodeSymbolicLayoutExtractor}. + */ + private ExecutionNodeSymbolicLayoutExtractor layoutExtractor; + + /** + * The {@link PosInOccurrence} of the modality or its updates. + */ + private PosInOccurrence modalityPIO; + + /** + * The up to know discovered completed {@link IExecutionBlockStartNode}s. + */ + private ImmutableList> completedBlocks = ImmutableSLList.nil(); + + /** + * The already computed block completion conditions. + */ + private final Map, Term> blockCompletionConditions = + new HashMap, Term>(); + + /** + * The already computed human readable block completion conditions. + */ + private final Map, String> formatedBlockCompletionConditions = + new HashMap, String>(); + + /** + * The up to know discovered outgoing links. + */ + private ImmutableList outgoingLinks = ImmutableSLList.nil(); + + /** + * The up to know discovered incoming links. + */ + private ImmutableList incomingLinks = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public AbstractExecutionNode(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } + + /** + * {@inheritDoc} + */ + @Override + public AbstractExecutionNode getParent() { + return parent; + } + + /** + * Sets the parent {@link AbstractExecutionNode}. + * + * @param parent The parent {@link AbstractExecutionNode} to set. + */ + public void setParent(AbstractExecutionNode parent) { + this.parent = parent; + } + + /** + * {@inheritDoc} + */ + @Override + public AbstractExecutionNode[] getChildren() { + return children.toArray(new AbstractExecutionNode[children.size()]); + } + + /** + * Adds a new child {@link AbstractExecutionNode}. + * + * @param child A new child {@link AbstractExecutionNode}. + */ + public void addChild(AbstractExecutionNode child) { + if (child != null) { + children.add(child); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPathConditionChanged() { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getPathCondition() throws ProofInputException { + // Search path condition of the parent which is used by default. + Term result = null; + AbstractExecutionNode parent = getParent(); + while (result == null && parent != null) { + if (parent.isPathConditionChanged()) { + result = parent.getPathCondition(); + } else { + parent = parent.getParent(); } - parent = parent.getParent(); - } - // Add current branch condition to path - Term condition = services.getTermBuilder().and(bcs); - // Simplify path condition - if (getSettings().isSimplifyConditions()) { - condition = SymbolicExecutionUtil.simplify(initConfig, getProof(), condition); - } - condition = SymbolicExecutionUtil.improveReadability(condition, services); - // Format path condition - String formatedCondition = formatTerm(condition, services); - // Update maps - blockCompletionConditions.put(completedNode, condition); - formatedBlockCompletionConditions.put(completedNode, formatedCondition); - return returnFormatedCondition ? formatedCondition : condition; - } - else { - return null; - } - } - - /** - * Removes the given child. - * @param child The child to be removed. - * @author Anna Filighera - */ - public void removeChild(IExecutionNode child) { - children.remove(child); - } - - /** - * Adds the given {@link IExecutionLink} as outgoing link. - * @param link The {@link IExecutionLink} to add. - */ - public void addOutgoingLink(IExecutionLink link) { - outgoingLinks = outgoingLinks.prepend(link); - } - - /** - * Removes the given {@link IExecutionLink} from the outgoing links. - * @param link The {@link IExecutionLink} to remove. - */ - public void removeOutgoingLink(IExecutionLink link) { - outgoingLinks = outgoingLinks.removeAll(link); - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionLink getOutgoingLink(final IExecutionNode target) { - return CollectionUtil.search(outgoingLinks, new IFilter() { - @Override - public boolean select(IExecutionLink element) { - return element.getTarget() == target; - } - }); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getOutgoingLinks() { - return outgoingLinks; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionLink getIncomingLink(final IExecutionNode source) { - return CollectionUtil.search(incomingLinks, new IFilter() { - @Override - public boolean select(IExecutionLink element) { - return element.getSource() == source; - } - }); - } - - /** - * Adds the given {@link IExecutionLink} as incoming link. - * @param link The {@link IExecutionLink} to add. - */ - public void addIncomingLink(IExecutionLink link) { - incomingLinks = incomingLinks.prepend(link); - } - - /** - * Removes the given {@link IExecutionLink} from the incoming links. - * @param link The {@link IExecutionLink} to remove. - */ - public void removeIncomingLink(IExecutionLink link) { - incomingLinks = incomingLinks.removeAll(link); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getIncomingLinks() { - return incomingLinks; - } -} \ No newline at end of file + } + // Check if a path condition was found. + return result != null ? result : getServices().getTermBuilder().tt(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedPathCondition() throws ProofInputException { + // Search path condition of the parent which is used by default. + String result = null; + AbstractExecutionNode parent = getParent(); + while (result == null && parent != null) { + if (parent.isPathConditionChanged()) { + result = parent.getFormatedPathCondition(); + } else { + parent = parent.getParent(); + } + } + // Check if a path condition was found. + if (!isDisposed()) { + return result != null ? result : getServices().getTermBuilder().tt().toString(); + } else { + return result; + } + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode[] getCallStack() { + return callStack; + } + + /** + * Sets the call stack. + * + * @param callStack The call stack. + */ + public void setCallStack(IExecutionNode[] callStack) { + this.callStack = callStack; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionConstraint[] getConstraints() { + synchronized (this) { + if (constraints == null) { + constraints = lazyComputeConstraints(); + } + return constraints; + } + } + + /** + * Computes the constraints lazily when {@link #getConstraints()} is called the first time. + * + * @return The {@link IExecutionConstraint}s of the current state. + */ + protected abstract IExecutionConstraint[] lazyComputeConstraints(); + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public S getActiveStatement() { + return (S) getProofNodeInfo().getActiveStatement(); + } + + /** + * {@inheritDoc} + */ + @Override + public PositionInfo getActivePositionInfo() { + return getActiveStatement().getPositionInfo(); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getVariables() throws ProofInputException { + synchronized (this) { + if (variables == null) { + variables = lazyComputeVariables(); + } + return variables; + } + } + + /** + * Computes the variables lazily when {@link #getVariables()} is called the first time. + * + * @return The {@link IExecutionVariable}s of the current state. + * @throws ProofInputException + */ + protected IExecutionVariable[] lazyComputeVariables() throws ProofInputException { + return SymbolicExecutionUtil.createExecutionVariables(this); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getVariables(Term condition) throws ProofInputException { + synchronized (this) { + IExecutionVariable[] result = conditionalVariables.get(condition); + if (result == null) { + result = lazyComputeVariables(condition); + conditionalVariables.put(condition, result); + } + return result; + } + } + + /** + * Computes the variables lazily when {@link #getVariables(Term)} is called the first time. + * + * @param condition A {@link Term} specifying some additional constraints to consider. + * @return The {@link IExecutionVariable}s of the current state under the given condition. + * @throws ProofInputException + */ + protected IExecutionVariable[] lazyComputeVariables(Term condition) throws ProofInputException { + return SymbolicExecutionUtil.createExecutionVariables(this, condition); + } + + /** + * Returns the used {@link ExecutionNodeSymbolicLayoutExtractor}. + * + * @return The used {@link ExecutionNodeSymbolicLayoutExtractor}. + * @throws ProofInputException Occurred Exception. + */ + public ExecutionNodeSymbolicLayoutExtractor getLayoutExtractor() throws ProofInputException { + synchronized (this) { + if (layoutExtractor == null) { + layoutExtractor = lazyComputeLayoutExtractor(); + } + return layoutExtractor; + } + } + + /** + * Instantiates the used {@link ExecutionNodeSymbolicLayoutExtractor} lazily when + * {@link #getLayoutExtractor()} is called the first time. + * + * @return The created {@link ExecutionNodeSymbolicLayoutExtractor}. + * @throws ProofInputException Occurred Exception. + */ + protected ExecutionNodeSymbolicLayoutExtractor lazyComputeLayoutExtractor() + throws ProofInputException { + ExecutionNodeSymbolicLayoutExtractor result = + new ExecutionNodeSymbolicLayoutExtractor(this); + result.analyse(); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public int getLayoutsCount() throws ProofInputException { + return getLayoutExtractor().getLayoutsCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicLayout getInitialLayout(int layoutIndex) throws ProofInputException { + return getLayoutExtractor().getInitialLayout(layoutIndex); + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicLayout getCurrentLayout(int layoutIndex) throws ProofInputException { + return getLayoutExtractor().getCurrentLayout(layoutIndex); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getLayoutsEquivalenceClasses(int layoutIndex) + throws ProofInputException { + return getLayoutExtractor().getEquivalenceClasses(layoutIndex); + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + if (modalityPIO == null) { + modalityPIO = lazyComputeModalityPIO(); + } + return modalityPIO; + } + + /** + * Computes the {@link PosInOccurrence} lazily when {@link #getModalityPIO()} is called the + * first time. + * + * @return The {@link PosInOccurrence}s of the modality or its updates. + */ + protected PosInOccurrence lazyComputeModalityPIO() { + PosInOccurrence originalPio = getProofNode().getAppliedRuleApp().posInOccurrence(); + // Try to go back to the parent which provides the updates + PosInOccurrence pio = originalPio; + Term term = pio.subTerm(); + if (!pio.isTopLevel() && term.op() != UpdateApplication.UPDATE_APPLICATION) { + pio = pio.up(); + term = pio.subTerm(); + } + // Return found updates or the original pio otherwise + return term.op() == UpdateApplication.UPDATE_APPLICATION ? pio : originalPio; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getCompletedBlocks() { + return completedBlocks; + } + + /** + * Registers the given {@link IExecutionBlockStartNode}. + * + * @param completedBlock The {@link IExecutionBlockStartNode} to register. + */ + public void addCompletedBlock(IExecutionBlockStartNode completedBlock) { + if (completedBlock != null && !completedBlocks.contains(completedBlock)) { + completedBlocks = completedBlocks.append(completedBlock); + } + } + + /** + * Removes the given {@link IExecutionBlockStartNode} from registration. + * + * @param completedBlock The {@link IExecutionBlockStartNode} to be remove. + * @author Anna Filighera + */ + public void removeCompletedBlock(IExecutionBlockStartNode completedBlock) { + if (completedBlock != null && completedBlocks.contains(completedBlock)) { + completedBlocks = completedBlocks.removeAll(completedBlock); + blockCompletionConditions.remove(completedBlock); + formatedBlockCompletionConditions.remove(completedBlock); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term getBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException { + Term result = blockCompletionConditions.get(completedNode); + if (result == null) { + result = (Term) lazyComputeBlockCompletionCondition(completedNode, false); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedBlockCompletionCondition(IExecutionBlockStartNode completedNode) + throws ProofInputException { + String result = formatedBlockCompletionConditions.get(completedNode); + if (result == null) { + result = (String) lazyComputeBlockCompletionCondition(completedNode, true); + } + return result; + } + + /** + * Computes the condition lazily when {@link #getBlockCompletionCondition(IExecutionNode)} or + * {@link #getFormatedBlockCompletionCondition(IExecutionNode)} is called the first time. + * + * @param completedNode The completed {@link IExecutionNode} for which the condition is + * requested. + * @param returnFormatedCondition {@code true} formated condition is returned, {@code false} + * {@link Term} is returned. + * @throws ProofInputException Occurred Exception + */ + protected Object lazyComputeBlockCompletionCondition(IExecutionBlockStartNode completedNode, + boolean returnFormatedCondition) throws ProofInputException { + final InitConfig initConfig = getInitConfig(); + if (initConfig != null && // Otherwise Proof is disposed. + completedBlocks.contains(completedNode)) { + final Services services = initConfig.getServices(); + // Collect branch conditions + List bcs = new LinkedList(); + AbstractExecutionNode parent = getParent(); + while (parent != null && parent != completedNode) { + if (parent instanceof IExecutionBranchCondition) { + Term bc = ((IExecutionBranchCondition) parent).getBranchCondition(); + if (bc == null) { + return null; // Proof disposed in between, computation not possible + } + bcs.add(bc); + } + parent = parent.getParent(); + } + // Add current branch condition to path + Term condition = services.getTermBuilder().and(bcs); + // Simplify path condition + if (getSettings().isSimplifyConditions()) { + condition = SymbolicExecutionUtil.simplify(initConfig, getProof(), condition); + } + condition = SymbolicExecutionUtil.improveReadability(condition, services); + // Format path condition + String formatedCondition = formatTerm(condition, services); + // Update maps + blockCompletionConditions.put(completedNode, condition); + formatedBlockCompletionConditions.put(completedNode, formatedCondition); + return returnFormatedCondition ? formatedCondition : condition; + } else { + return null; + } + } + + /** + * Removes the given child. + * + * @param child The child to be removed. + * @author Anna Filighera + */ + public void removeChild(IExecutionNode child) { + children.remove(child); + } + + /** + * Adds the given {@link IExecutionLink} as outgoing link. + * + * @param link The {@link IExecutionLink} to add. + */ + public void addOutgoingLink(IExecutionLink link) { + outgoingLinks = outgoingLinks.prepend(link); + } + + /** + * Removes the given {@link IExecutionLink} from the outgoing links. + * + * @param link The {@link IExecutionLink} to remove. + */ + public void removeOutgoingLink(IExecutionLink link) { + outgoingLinks = outgoingLinks.removeAll(link); + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionLink getOutgoingLink(final IExecutionNode target) { + return CollectionUtil.search(outgoingLinks, new IFilter() { + @Override + public boolean select(IExecutionLink element) { + return element.getTarget() == target; + } + }); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getOutgoingLinks() { + return outgoingLinks; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionLink getIncomingLink(final IExecutionNode source) { + return CollectionUtil.search(incomingLinks, new IFilter() { + @Override + public boolean select(IExecutionLink element) { + return element.getSource() == source; + } + }); + } + + /** + * Adds the given {@link IExecutionLink} as incoming link. + * + * @param link The {@link IExecutionLink} to add. + */ + public void addIncomingLink(IExecutionLink link) { + incomingLinks = incomingLinks.prepend(link); + } + + /** + * Removes the given {@link IExecutionLink} from the incoming links. + * + * @param link The {@link IExecutionLink} to remove. + */ + public void removeIncomingLink(IExecutionLink link) { + incomingLinks = incomingLinks.removeAll(link); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getIncomingLinks() { + return incomingLinks; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionValue.java index 3118e3572c7..afcf90e1d72 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.HashSet; @@ -21,207 +24,211 @@ /** * Provides a basic implementation of {@link IExecutionValue}. + * * @author Martin Hentschel */ -public abstract class AbstractExecutionValue extends AbstractExecutionElement implements IExecutionValue { - /** - * The parent {@link IExecutionVariable} which provides this {@link IExecutionValue}. - */ - private final IExecutionVariable variable; - - /** - * The condition under which the variable has this value. - */ - private final Term condition; - - /** - * The {@link IExecutionConstraint}s. - */ - private IExecutionConstraint[] constraints; - - /** - * The value. - */ - private final Term value; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param variable The parent {@link IExecutionVariable} which contains this value. - * @param condition The condition. - * @param value The value. - */ - public AbstractExecutionValue(ITreeSettings settings, - Node proofNode, - IExecutionVariable variable, - Term condition, - Term value) { - super(settings, proofNode); - this.variable = variable; - this.condition = condition; - this.value = value; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionConstraint[] getConstraints() throws ProofInputException { - synchronized (this) { - if (constraints == null) { - constraints = lazyComputeConstraints(); - } - return constraints; - } - } - - /** - * Computes the related constraints lazily when {@link #getConstraints()} is called the first time. - * @return The related {@link IExecutionConstraint}s. - * @throws ProofInputException Occurred Exception - */ - protected IExecutionConstraint[] lazyComputeConstraints() throws ProofInputException { - if (!isDisposed() && !isValueUnknown()) { - List constraints = new LinkedList(); - IExecutionConstraint[] allConstraints = getNodeConstraints(); - Set relevantTerms = collectRelevantTerms(getServices(), getValue()); - for (IExecutionConstraint constraint : allConstraints) { - if (containsTerm(constraint.getTerm(), relevantTerms)) { - constraints.add(constraint); +public abstract class AbstractExecutionValue extends AbstractExecutionElement + implements IExecutionValue { + /** + * The parent {@link IExecutionVariable} which provides this {@link IExecutionValue}. + */ + private final IExecutionVariable variable; + + /** + * The condition under which the variable has this value. + */ + private final Term condition; + + /** + * The {@link IExecutionConstraint}s. + */ + private IExecutionConstraint[] constraints; + + /** + * The value. + */ + private final Term value; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param variable The parent {@link IExecutionVariable} which contains this value. + * @param condition The condition. + * @param value The value. + */ + public AbstractExecutionValue(ITreeSettings settings, Node proofNode, + IExecutionVariable variable, Term condition, Term value) { + super(settings, proofNode); + this.variable = variable; + this.condition = condition; + this.value = value; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionConstraint[] getConstraints() throws ProofInputException { + synchronized (this) { + if (constraints == null) { + constraints = lazyComputeConstraints(); } - } - return constraints.toArray(new IExecutionConstraint[constraints.size()]); - } - else { - return new IExecutionConstraint[0]; - } - } - - /** - * Returns all available {@link IExecutionConstraint}s of the {@link IExecutionNode} on which this {@link IExecutionValue} is part of. - * @return All available {@link IExecutionConstraint}s. - */ - protected abstract IExecutionConstraint[] getNodeConstraints(); - - /** - * Collects all {@link Term}s contained in relevant constraints. - * @param services The {@link Services} to use. - * @param term The initial {@link Term}. - * @return The relevant {@link Term}s. - */ - protected Set collectRelevantTerms(Services services, Term term) { - final Set terms = new HashSet(); - fillRelevantTerms(services, term, terms); - return terms; - } - - /** - * Utility method used by {@link #collectRelevantTerms(Services, Term)}. - * @param services The {@link Services} to use. - * @param term The initial {@link Term}. - * @param toFill The {@link Set} of relevant {@link Term}s to fill. - */ - protected void fillRelevantTerms(Services services, Term term, Set toFill) { - if (term != null) { - if (term.op() instanceof ProgramVariable || - SymbolicExecutionUtil.isSelect(services, term)) { - toFill.add(OriginTermLabel.removeOriginLabels(term, services)); - } - else { - for (int i = 0; i < term.arity(); i++) { - fillRelevantTerms(services, term.sub(i), toFill); + return constraints; + } + } + + /** + * Computes the related constraints lazily when {@link #getConstraints()} is called the first + * time. + * + * @return The related {@link IExecutionConstraint}s. + * @throws ProofInputException Occurred Exception + */ + protected IExecutionConstraint[] lazyComputeConstraints() throws ProofInputException { + if (!isDisposed() && !isValueUnknown()) { + List constraints = new LinkedList(); + IExecutionConstraint[] allConstraints = getNodeConstraints(); + Set relevantTerms = collectRelevantTerms(getServices(), getValue()); + for (IExecutionConstraint constraint : allConstraints) { + if (containsTerm(constraint.getTerm(), relevantTerms)) { + constraints.add(constraint); + } + } + return constraints.toArray(new IExecutionConstraint[constraints.size()]); + } else { + return new IExecutionConstraint[0]; + } + } + + /** + * Returns all available {@link IExecutionConstraint}s of the {@link IExecutionNode} on which + * this {@link IExecutionValue} is part of. + * + * @return All available {@link IExecutionConstraint}s. + */ + protected abstract IExecutionConstraint[] getNodeConstraints(); + + /** + * Collects all {@link Term}s contained in relevant constraints. + * + * @param services The {@link Services} to use. + * @param term The initial {@link Term}. + * @return The relevant {@link Term}s. + */ + protected Set collectRelevantTerms(Services services, Term term) { + final Set terms = new HashSet(); + fillRelevantTerms(services, term, terms); + return terms; + } + + /** + * Utility method used by {@link #collectRelevantTerms(Services, Term)}. + * + * @param services The {@link Services} to use. + * @param term The initial {@link Term}. + * @param toFill The {@link Set} of relevant {@link Term}s to fill. + */ + protected void fillRelevantTerms(Services services, Term term, Set toFill) { + if (term != null) { + if (term.op() instanceof ProgramVariable + || SymbolicExecutionUtil.isSelect(services, term)) { + toFill.add(OriginTermLabel.removeOriginLabels(term, services)); + } else { + for (int i = 0; i < term.arity(); i++) { + fillRelevantTerms(services, term.sub(i), toFill); + } } - } - } - } - - /** - * Checks if the given {@link Term} contains at least one of the given once. - * @param term The {@link Term} to search in. - * @param toSearch The {@link Term}s to search. - * @return {@code true} at least one {@link Term} is contained, {@code false} none of the {@link Term}s is contained. - */ - protected boolean containsTerm(Term term, Set toSearch) { - if (toSearch.contains(OriginTermLabel.removeOriginLabels(term, getServices()))) { - return true; - } - else { - boolean contained = false; - int i = 0; - while (!contained && i < term.arity()) { - contained = containsTerm(term.sub(i), toSearch); - i++; - } - return contained; - } - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable getVariable() { - return variable; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return getVariable().getModalityPIO(); - } - - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - String conditionString = getConditionString(); - if (conditionString != null) { - return getVariable().getName() + " {" + getConditionString() + "}"; - } - else { - return getVariable().getName(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Value"; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() throws ProofInputException { - return condition; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getValue() throws ProofInputException { - return value; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isValueAnObject() throws ProofInputException { - if (isValueUnknown()) { - return false; - } - else { - Term value = getValue(); - return SymbolicExecutionUtil.hasReferenceSort(getServices(), value); - } - } + } + } + + /** + * Checks if the given {@link Term} contains at least one of the given once. + * + * @param term The {@link Term} to search in. + * @param toSearch The {@link Term}s to search. + * @return {@code true} at least one {@link Term} is contained, {@code false} none of the + * {@link Term}s is contained. + */ + protected boolean containsTerm(Term term, Set toSearch) { + if (toSearch.contains(OriginTermLabel.removeOriginLabels(term, getServices()))) { + return true; + } else { + boolean contained = false; + int i = 0; + while (!contained && i < term.arity()) { + contained = containsTerm(term.sub(i), toSearch); + i++; + } + return contained; + } + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable getVariable() { + return variable; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return getVariable().getModalityPIO(); + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + String conditionString = getConditionString(); + if (conditionString != null) { + return getVariable().getName() + " {" + getConditionString() + "}"; + } else { + return getVariable().getName(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Value"; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() throws ProofInputException { + return condition; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getValue() throws ProofInputException { + return value; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValueAnObject() throws ProofInputException { + if (isValueUnknown()) { + return false; + } else { + Term value = getValue(); + return SymbolicExecutionUtil.hasReferenceSort(getServices(), value); + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionVariable.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionVariable.java index e73bafb0c76..08d031b704f 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionVariable.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/AbstractExecutionVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.logic.PosInOccurrence; @@ -13,134 +16,133 @@ /** * Provides a basic implementation of {@link IExecutionVariable}s. + * * @author Martin Hentschel */ -public abstract class AbstractExecutionVariable extends AbstractExecutionElement implements IExecutionVariable { - /** - * The represented {@link IProgramVariable} which value is shown. - */ - private final IProgramVariable programVariable; - - /** - * The parent {@link ExecutionValue} or {@code null} if not available. - */ - private final IExecutionValue parentValue; - - /** - * The index in the parent array. - */ - private final Term arrayIndex; - - /** - * An optional additional condition to consider. - */ - private final Term additionalCondition; - - /** - * The {@link PosInOccurrence} of the modality of interest. - */ - private final PosInOccurrence modalityPIO; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param programVariable The represented {@link IProgramVariable} which value is shown. - * @param parentValue The parent {@link IExecutionValue} or {@code null} if not available. - * @param arrayIndex The index in the parent array. - * @param additionalCondition An optional additional condition to consider. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - */ - public AbstractExecutionVariable(ITreeSettings settings, - Node proofNode, - IProgramVariable programVariable, - IExecutionValue parentValue, - Term arrayIndex, - Term additionalCondition, - PosInOccurrence modalityPIO) { - super(settings, proofNode); - this.programVariable = programVariable; - this.parentValue = parentValue; - this.arrayIndex = arrayIndex; - this.additionalCondition = additionalCondition; - this.modalityPIO = modalityPIO; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getAdditionalCondition() { - return additionalCondition; - } - - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - IProgramVariable pv = getProgramVariable(); - if (pv != null) { - return SymbolicExecutionUtil.getDisplayString(pv); - } - else { - return "[" + getArrayIndexString() + "]"; - } - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return programVariable; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return arrayIndex; - } - - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndex != null ? formatTerm(arrayIndex, getServices()) : null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isArrayIndex() { - return getArrayIndex() != null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Variable"; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionValue getParentValue() { - return parentValue; - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return modalityPIO; - } +public abstract class AbstractExecutionVariable extends AbstractExecutionElement + implements IExecutionVariable { + /** + * The represented {@link IProgramVariable} which value is shown. + */ + private final IProgramVariable programVariable; + + /** + * The parent {@link ExecutionValue} or {@code null} if not available. + */ + private final IExecutionValue parentValue; + + /** + * The index in the parent array. + */ + private final Term arrayIndex; + + /** + * An optional additional condition to consider. + */ + private final Term additionalCondition; + + /** + * The {@link PosInOccurrence} of the modality of interest. + */ + private final PosInOccurrence modalityPIO; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param programVariable The represented {@link IProgramVariable} which value is shown. + * @param parentValue The parent {@link IExecutionValue} or {@code null} if not available. + * @param arrayIndex The index in the parent array. + * @param additionalCondition An optional additional condition to consider. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + */ + public AbstractExecutionVariable(ITreeSettings settings, Node proofNode, + IProgramVariable programVariable, IExecutionValue parentValue, Term arrayIndex, + Term additionalCondition, PosInOccurrence modalityPIO) { + super(settings, proofNode); + this.programVariable = programVariable; + this.parentValue = parentValue; + this.arrayIndex = arrayIndex; + this.additionalCondition = additionalCondition; + this.modalityPIO = modalityPIO; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getAdditionalCondition() { + return additionalCondition; + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + IProgramVariable pv = getProgramVariable(); + if (pv != null) { + return SymbolicExecutionUtil.getDisplayString(pv); + } else { + return "[" + getArrayIndexString() + "]"; + } + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return programVariable; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return arrayIndex; + } + + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndex != null ? formatTerm(arrayIndex, getServices()) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isArrayIndex() { + return getArrayIndex() != null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Variable"; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionValue getParentValue() { + return parentValue; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return modalityPIO; + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAllArrayIndicesVariable.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAllArrayIndicesVariable.java index 038088b7467..13f1909de21 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAllArrayIndicesVariable.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAllArrayIndicesVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.Services; @@ -22,169 +25,178 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * An implementation of {@link IExecutionVariable} used to query - * all array indices at the same time. This supports also arrays where - * the length is symbolic and not a concrete number. + * An implementation of {@link IExecutionVariable} used to query all array indices at the same time. + * This supports also arrays where the length is symbolic and not a concrete number. + * * @author Martin Hentschel */ public class ExecutionAllArrayIndicesVariable extends ExecutionVariable { - /** - * The name of the constant used to query the value of all array indices. - */ - public static final String ARRAY_INDEX_CONSTANT_NAME = "*"; - - /** - * The name used to represent the fact that a value is not available. - */ - public static final String NOT_A_VALUE_NAME = ""; - - /** - * The constant representing an arbitrary array index. - */ - private Term constant; - - /** - * The constant representing the fact that no value is available. - */ - private final Term notAValue; + /** + * The name of the constant used to query the value of all array indices. + */ + public static final String ARRAY_INDEX_CONSTANT_NAME = "*"; - /** - * Constructor. - * @param parentNode The parent {@link IExecutionNode}. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - * @param parentValue The parent {@link IExecutionValue} representing the array. - * @param arrayProgramVariable The {@link IProgramVariable} of the array. - * @param additionalCondition An optional additional condition to consider. - */ - public ExecutionAllArrayIndicesVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - ExecutionValue parentValue, - IProgramVariable arrayProgramVariable, - Term additionalCondition) { - super(parentNode, - proofNode, - modalityPIO, - parentValue, - arrayProgramVariable, - additionalCondition); - assert parentValue != null; - TermBuilder tb = getServices().getTermBuilder(); - Function notAValueFunction = new Function(new Name(tb.newName(NOT_A_VALUE_NAME)), Sort.ANY); - notAValue = tb.func(notAValueFunction); - } + /** + * The name used to represent the fact that a value is not available. + */ + public static final String NOT_A_VALUE_NAME = ""; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - // Ensure that constant is defined - if (constant == null) { - getValues(); - } - // Compute name - String arrayName = super.lazyComputeName(); - return arrayName + "[" + constant + "]"; - } + /** + * The constant representing an arbitrary array index. + */ + private Term constant; - /** - * Computes the value for {@link #getValues()} - * lazily when the method is called the first time. - * @throws ProofInputException Occurred Exception. - */ - protected ExecutionValue[] lazyComputeValues() throws ProofInputException { - InitConfig initConfig = getInitConfig(); - if (initConfig != null) { // Otherwise proof is disposed. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - final Services sideServices = sideProofEnv.getServicesForEnvironment(); - final TermBuilder tb = sideServices.getTermBuilder(); - // Start site proof to extract the value of the result variable. - Term siteProofCondition = getAdditionalCondition() != null ? - tb.and(getAdditionalCondition(), getParentValue().getCondition()) : - getParentValue().getCondition(); - Term arrayTerm = createArrayTerm(); - // Create index constant - Function constantFunction = new Function(new Name(tb.newName(ARRAY_INDEX_CONSTANT_NAME)), sideServices.getTypeConverter().getIntegerLDT().targetSort()); - constant = tb.func(constantFunction); - setName(lazyComputeName()); // Update name because constant has changed - Term arrayIndex = tb.dotArr(arrayTerm, constant); - // Create if check - Function arrayLengthFunction = sideServices.getTypeConverter().getHeapLDT().getLength(); - Term arrayRange = tb.and(tb.geq(constant, tb.zero()), tb.lt(constant, tb.func(arrayLengthFunction, arrayTerm))); - Term resultIf = tb.ife(arrayRange, arrayIndex, notAValue); - - // Create predicate which will be used in formulas to store the value interested in. - Function resultPredicate = new Function(new Name(tb.newName("ResultPredicate")), Sort.FORMULA, resultIf.sort()); - // Create formula which contains the value interested in. - Term resultTerm = tb.func(resultPredicate, resultIf); - // Create Sequent to prove with new succedent. - Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(getProofNode(), getModalityPIO(), siteProofCondition, resultTerm, false); - // Perform side proof - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), - sideProofEnv, - sequent, - StrategyProperties.METHOD_NONE, - StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, - StrategyProperties.SPLITTING_DELAYED); - try { - return instantiateValuesFromSideProof(initConfig, - sideServices, - tb, - info, - resultPredicate, - arrayTerm, // Pass array to ensure that unknown values are correctly computed. - siteProofCondition); - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("All array indices value computation on node " + getProofNode().serialNr(), info); - } - } - else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean isValidValue(Term value) { - return notAValue != value; - } + /** + * The constant representing the fact that no value is available. + */ + private final Term notAValue; - /** - * Creates a {@link Term} to access the array. - * @return The {@link Term} to access the array. - */ - public Term createArrayTerm() { - return getParentValue().getVariable().createSelectTerm(); - } + /** + * Constructor. + * + * @param parentNode The parent {@link IExecutionNode}. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + * @param parentValue The parent {@link IExecutionValue} representing the array. + * @param arrayProgramVariable The {@link IProgramVariable} of the array. + * @param additionalCondition An optional additional condition to consider. + */ + public ExecutionAllArrayIndicesVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, ExecutionValue parentValue, + IProgramVariable arrayProgramVariable, Term additionalCondition) { + super(parentNode, proofNode, modalityPIO, parentValue, arrayProgramVariable, + additionalCondition); + assert parentValue != null; + TermBuilder tb = getServices().getTermBuilder(); + Function notAValueFunction = new Function(new Name(tb.newName(NOT_A_VALUE_NAME)), Sort.ANY); + notAValue = tb.func(notAValueFunction); + } - /** - * {@inheritDoc} - */ - @Override - public Term createSelectTerm() { - assert constant != null : "Call getValues() before calling createSelectTerm()."; - return getServices().getTermBuilder().dotArr(createArrayTerm(), constant); - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + // Ensure that constant is defined + if (constant == null) { + getValues(); + } + // Compute name + String arrayName = super.lazyComputeName(); + return arrayName + "[" + constant + "]"; + } - /** - * Returns the constant representing an arbitrary array index. - * @return The constant representing an arbitrary array index. - */ - public Term getConstant() { - return constant; - } + /** + * Computes the value for {@link #getValues()} lazily when the method is called the first time. + * + * @throws ProofInputException Occurred Exception. + */ + protected ExecutionValue[] lazyComputeValues() throws ProofInputException { + InitConfig initConfig = getInitConfig(); + if (initConfig != null) { // Otherwise proof is disposed. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New + // OneStepSimplifier + // is required + // because it + // has an + // internal + // state and + // the default + // instance + // can't be + // used + // parallel. + final Services sideServices = sideProofEnv.getServicesForEnvironment(); + final TermBuilder tb = sideServices.getTermBuilder(); + // Start site proof to extract the value of the result variable. + Term siteProofCondition = getAdditionalCondition() != null + ? tb.and(getAdditionalCondition(), getParentValue().getCondition()) + : getParentValue().getCondition(); + Term arrayTerm = createArrayTerm(); + // Create index constant + Function constantFunction = + new Function(new Name(tb.newName(ARRAY_INDEX_CONSTANT_NAME)), + sideServices.getTypeConverter().getIntegerLDT().targetSort()); + constant = tb.func(constantFunction); + setName(lazyComputeName()); // Update name because constant has changed + Term arrayIndex = tb.dotArr(arrayTerm, constant); + // Create if check + Function arrayLengthFunction = sideServices.getTypeConverter().getHeapLDT().getLength(); + Term arrayRange = tb.and(tb.geq(constant, tb.zero()), + tb.lt(constant, tb.func(arrayLengthFunction, arrayTerm))); + Term resultIf = tb.ife(arrayRange, arrayIndex, notAValue); - /** - * Returns the constant representing the fact that no value is available. - * @return The constant representing the fact that no value is available. - */ - public Term getNotAValue() { - return notAValue; - } + // Create predicate which will be used in formulas to store the value interested in. + Function resultPredicate = new Function(new Name(tb.newName("ResultPredicate")), + Sort.FORMULA, resultIf.sort()); + // Create formula which contains the value interested in. + Term resultTerm = tb.func(resultPredicate, resultIf); + // Create Sequent to prove with new succedent. + Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent( + getProofNode(), getModalityPIO(), siteProofCondition, resultTerm, false); + // Perform side proof + ApplyStrategyInfo info = + SymbolicExecutionSideProofUtil.startSideProof(getProof(), sideProofEnv, sequent, + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_DELAYED); + try { + return instantiateValuesFromSideProof(initConfig, sideServices, tb, info, + resultPredicate, arrayTerm, // Pass array to ensure that unknown values are + // correctly computed. + siteProofCondition); + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "All array indices value computation on node " + getProofNode().serialNr(), + info); + } + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean isValidValue(Term value) { + return notAValue != value; + } + + /** + * Creates a {@link Term} to access the array. + * + * @return The {@link Term} to access the array. + */ + public Term createArrayTerm() { + return getParentValue().getVariable().createSelectTerm(); + } + + /** + * {@inheritDoc} + */ + @Override + public Term createSelectTerm() { + assert constant != null : "Call getValues() before calling createSelectTerm()."; + return getServices().getTermBuilder().dotArr(createArrayTerm(), constant); + } + + /** + * Returns the constant representing an arbitrary array index. + * + * @return The constant representing an arbitrary array index. + */ + public Term getConstant() { + return constant; + } + + /** + * Returns the constant representing the fact that no value is available. + * + * @return The constant representing the fact that no value is available. + */ + public Term getNotAValue() { + return notAValue; + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAuxiliaryContract.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAuxiliaryContract.java index 40ecad90579..80d748d89d3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAuxiliaryContract.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionAuxiliaryContract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.LinkedHashMap; @@ -31,164 +34,188 @@ /** * The default implementation of {@link IExecutionAuxiliaryContract}. + * * @author Martin Hentschel */ -public class ExecutionAuxiliaryContract extends AbstractExecutionNode implements IExecutionAuxiliaryContract { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionAuxiliaryContract(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionAuxiliaryContract extends AbstractExecutionNode + implements IExecutionAuxiliaryContract { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionAuxiliaryContract(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Block Contract"; - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Block Contract"; + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - // Find self term - Term self = null; - Term applicationTerm = getModalityPIO().subTerm(); - Term modalityTerm = TermBuilder.goBelowUpdates(applicationTerm); - ExecutionContext ec = JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), getServices()); - if (ec != null) { - ReferencePrefix prefix = ec.getRuntimeInstance(); - if (prefix instanceof ProgramVariable) { - self = getServices().getTermBuilder().var((ProgramVariable) prefix); - } - } - Node usageNode = getProofNode().child(2); - assert "Usage".equals(usageNode.getNodeInfo().getBranchLabel()) : "Block Contract Rule has changed."; - Term usagePrecondition = usageNode.sequent().antecedent().get(usageNode.sequent().antecedent().size() - 1).formula(); - // Find remembrance heaps and local variables - while (applicationTerm.op() == UpdateApplication.UPDATE_APPLICATION) { - assert applicationTerm.sub(0) == usagePrecondition.sub(0) : "Block Contract Rule has changed."; - applicationTerm = applicationTerm.sub(1); - usagePrecondition = usagePrecondition.sub(1); - } - assert usagePrecondition.op() == UpdateApplication.UPDATE_APPLICATION : "Block Contract Rule has changed."; - Map remembranceHeaps = new LinkedHashMap(); - Map remembranceLocalVariables = new LinkedHashMap(); - collectRemembranceVariables(usagePrecondition.sub(0), remembranceHeaps, remembranceLocalVariables); - // Find remaining information - Node validitiyNode = getProofNode().child(0); - assert "Validity".equals(validitiyNode.getNodeInfo().getBranchLabel()) : "Block Contract Rule has changed."; - Term validitiyModalityTerm = TermBuilder.goBelowUpdates(SymbolicExecutionUtil.posInOccurrenceInOtherNode(getProofNode(), getModalityPIO(), validitiyNode)); - MethodFrame mf = JavaTools.getInnermostMethodFrame(validitiyModalityTerm.javaBlock(), getServices()); - StatementBlock sb = mf != null ? mf.getBody() : (StatementBlock) validitiyModalityTerm.javaBlock().program(); - AuxiliaryContract.Variables variables = getContract().getVariables(); - int statementIndex = variables.breakFlags.size() + variables.continueFlags.size(); // Skip break and continues - Term returnFlag = null; - Term result = null; - if (variables.returnFlag != null) { - returnFlag = declaredVariableAsTerm(sb, statementIndex); - statementIndex++; // Skip return flag - if (variables.result != null) { - result = declaredVariableAsTerm(sb, statementIndex); - statementIndex++; // Result variable - } - } - Term exception = null; - if (variables.exception != null) { - exception = declaredVariableAsTerm(sb, statementIndex); - } - AuxiliaryContract.Terms terms = new AuxiliaryContract.Terms(self, - null, // breakFlags are not used by getPlainText() - null, // continueFlags are not used by getPlainText() - returnFlag, // returnFlag are not used by getPlainText() - result, - exception, - remembranceHeaps, - remembranceLocalVariables, // remembranceLocalVariables are not used by getPlainText() - null, null); // outerRemembranceVariables are not used by getPlainText() + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + // Find self term + Term self = null; + Term applicationTerm = getModalityPIO().subTerm(); + Term modalityTerm = TermBuilder.goBelowUpdates(applicationTerm); + ExecutionContext ec = + JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), getServices()); + if (ec != null) { + ReferencePrefix prefix = ec.getRuntimeInstance(); + if (prefix instanceof ProgramVariable) { + self = getServices().getTermBuilder().var((ProgramVariable) prefix); + } + } + Node usageNode = getProofNode().child(2); + assert "Usage".equals(usageNode.getNodeInfo().getBranchLabel()) + : "Block Contract Rule has changed."; + Term usagePrecondition = usageNode.sequent().antecedent() + .get(usageNode.sequent().antecedent().size() - 1).formula(); + // Find remembrance heaps and local variables + while (applicationTerm.op() == UpdateApplication.UPDATE_APPLICATION) { + assert applicationTerm.sub(0) == usagePrecondition.sub(0) + : "Block Contract Rule has changed."; + applicationTerm = applicationTerm.sub(1); + usagePrecondition = usagePrecondition.sub(1); + } + assert usagePrecondition.op() == UpdateApplication.UPDATE_APPLICATION + : "Block Contract Rule has changed."; + Map remembranceHeaps = new LinkedHashMap(); + Map remembranceLocalVariables = + new LinkedHashMap(); + collectRemembranceVariables(usagePrecondition.sub(0), remembranceHeaps, + remembranceLocalVariables); + // Find remaining information + Node validitiyNode = getProofNode().child(0); + assert "Validity".equals(validitiyNode.getNodeInfo().getBranchLabel()) + : "Block Contract Rule has changed."; + Term validitiyModalityTerm = TermBuilder.goBelowUpdates(SymbolicExecutionUtil + .posInOccurrenceInOtherNode(getProofNode(), getModalityPIO(), validitiyNode)); + MethodFrame mf = + JavaTools.getInnermostMethodFrame(validitiyModalityTerm.javaBlock(), getServices()); + StatementBlock sb = mf != null ? mf.getBody() + : (StatementBlock) validitiyModalityTerm.javaBlock().program(); + AuxiliaryContract.Variables variables = getContract().getVariables(); + int statementIndex = variables.breakFlags.size() + variables.continueFlags.size(); // Skip + // break + // and + // continues + Term returnFlag = null; + Term result = null; + if (variables.returnFlag != null) { + returnFlag = declaredVariableAsTerm(sb, statementIndex); + statementIndex++; // Skip return flag + if (variables.result != null) { + result = declaredVariableAsTerm(sb, statementIndex); + statementIndex++; // Result variable + } + } + Term exception = null; + if (variables.exception != null) { + exception = declaredVariableAsTerm(sb, statementIndex); + } + AuxiliaryContract.Terms terms = new AuxiliaryContract.Terms(self, null, // breakFlags are + // not used by + // getPlainText() + null, // continueFlags are not used by getPlainText() + returnFlag, // returnFlag are not used by getPlainText() + result, exception, remembranceHeaps, remembranceLocalVariables, // remembranceLocalVariables + // are not used by + // getPlainText() + null, null); // outerRemembranceVariables are not used by getPlainText() - // Compute text - return getContract().getPlainText(getServices(), terms); - } + // Compute text + return getContract().getPlainText(getServices(), terms); + } - /** - * Returns the variable declared by the statement at the given index as {@link Term}. - * @param sb The {@link StatementBlock} which contains all variable declarations. - * @param statementIndex The index in the {@link StatementBlock} with the variable declaration of interest. - * @return The variable as {@link Term}. - */ - protected Term declaredVariableAsTerm(StatementBlock sb, int statementIndex) { - Statement resultInitStatement = sb.getStatementAt(statementIndex); - assert resultInitStatement instanceof LocalVariableDeclaration : "Block Contract Rule has changed."; - Named var = ((LocalVariableDeclaration) resultInitStatement).getVariables().get(0).getProgramVariable(); - assert var != null : "Block Contract Rule has changed."; - return getServices().getTermBuilder().var((ProgramVariable) var); - } + /** + * Returns the variable declared by the statement at the given index as {@link Term}. + * + * @param sb The {@link StatementBlock} which contains all variable declarations. + * @param statementIndex The index in the {@link StatementBlock} with the variable declaration + * of interest. + * @return The variable as {@link Term}. + */ + protected Term declaredVariableAsTerm(StatementBlock sb, int statementIndex) { + Statement resultInitStatement = sb.getStatementAt(statementIndex); + assert resultInitStatement instanceof LocalVariableDeclaration + : "Block Contract Rule has changed."; + Named var = ((LocalVariableDeclaration) resultInitStatement).getVariables().get(0) + .getProgramVariable(); + assert var != null : "Block Contract Rule has changed."; + return getServices().getTermBuilder().var((ProgramVariable) var); + } - /** - * Collects recursive all remembrance variables. - * @param term The {@link Term} to start collecting. - * @param remembranceHeaps The {@link Map} to fill. - * @param remembranceLocalVariables The {@link Map} to fill. - */ - protected void collectRemembranceVariables(Term term, Map remembranceHeaps, Map remembranceLocalVariables) { - if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { - for (Term sub : term.subs()) { - collectRemembranceVariables(sub, remembranceHeaps, remembranceLocalVariables); - } - } - else if (term.op() instanceof ElementaryUpdate) { - ElementaryUpdate eu = (ElementaryUpdate) term.op(); - if (SymbolicExecutionUtil.isHeap(eu.lhs(), getServices().getTypeConverter().getHeapLDT())) { - remembranceHeaps.put((LocationVariable) term.sub(0).op(), getServices().getTermBuilder().var(eu.lhs())); - } - else { - remembranceLocalVariables.put((LocationVariable) term.sub(0).op(), getServices().getTermBuilder().var(eu.lhs())); - } - } - else { - assert false : "Unsupported update term with operator '" + term.op() + "'."; - } - } + /** + * Collects recursive all remembrance variables. + * + * @param term The {@link Term} to start collecting. + * @param remembranceHeaps The {@link Map} to fill. + * @param remembranceLocalVariables The {@link Map} to fill. + */ + protected void collectRemembranceVariables(Term term, + Map remembranceHeaps, + Map remembranceLocalVariables) { + if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { + for (Term sub : term.subs()) { + collectRemembranceVariables(sub, remembranceHeaps, remembranceLocalVariables); + } + } else if (term.op() instanceof ElementaryUpdate) { + ElementaryUpdate eu = (ElementaryUpdate) term.op(); + if (SymbolicExecutionUtil.isHeap(eu.lhs(), + getServices().getTypeConverter().getHeapLDT())) { + remembranceHeaps.put((LocationVariable) term.sub(0).op(), + getServices().getTermBuilder().var(eu.lhs())); + } else { + remembranceLocalVariables.put((LocationVariable) term.sub(0).op(), + getServices().getTermBuilder().var(eu.lhs())); + } + } else { + assert false : "Unsupported update term with operator '" + term.op() + "'."; + } + } - /** - * {@inheritDoc} - */ - @Override - public boolean isPreconditionComplied() { - boolean complied = getProofNode().child(1).isClosed(); - return complied; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isPreconditionComplied() { + boolean complied = getProofNode().child(1).isClosed(); + return complied; + } - /** - * {@inheritDoc} - */ - @Override - public AuxiliaryContract getContract() { - return ((AbstractAuxiliaryContractBuiltInRuleApp)getProofNode().getAppliedRuleApp()).getContract(); - } + /** + * {@inheritDoc} + */ + @Override + public AuxiliaryContract getContract() { + return ((AbstractAuxiliaryContractBuiltInRuleApp) getProofNode().getAppliedRuleApp()) + .getContract(); + } - /** - * {@inheritDoc} - */ - @Override - public StatementBlock getBlock() { - return (StatementBlock) - ((AbstractAuxiliaryContractBuiltInRuleApp)getProofNode() - .getAppliedRuleApp()).getStatement(); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public StatementBlock getBlock() { + return (StatementBlock) ((AbstractAuxiliaryContractBuiltInRuleApp) getProofNode() + .getAppliedRuleApp()).getStatement(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchCondition.java index 1c6a82b650c..ad1112ee021 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.Iterator; @@ -20,285 +23,297 @@ /** * The default implementation of {@link IExecutionBranchCondition}. + * * @author Martin Hentschel */ -public class ExecutionBranchCondition extends AbstractExecutionNode implements IExecutionBranchCondition { - /** - * The optional additional branch label. - */ - private final String additionalBranchLabel; - - /** - * The {@link Term} which represents the branch condition. - */ - private Term branchCondition; - - /** - * The human readable branch condition. - */ - private String formatedBranchCondition; - - /** - * The path condition to reach this node. - */ - private Term pathCondition; - - /** - * The human readable path condition to reach this node. - */ - private String formatedPathCondition; - - /** - * Merged branch conditions. - */ - private List mergedProofNodes; - - /** - * Contains the merged branch conditions. - */ - private Term[] mergedBranchCondtions; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param additionalBranchLabel The optional additional branch label. - */ - public ExecutionBranchCondition(ITreeSettings settings, - Node proofNode, - String additionalBranchLabel) { - super(settings, proofNode); - this.additionalBranchLabel = additionalBranchLabel; - } +public class ExecutionBranchCondition extends AbstractExecutionNode + implements IExecutionBranchCondition { + /** + * The optional additional branch label. + */ + private final String additionalBranchLabel; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - return getFormatedBranchCondition(); - } + /** + * The {@link Term} which represents the branch condition. + */ + private Term branchCondition; - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Branch Condition"; - } - - /** - * {@inheritDoc} - */ - @Override - public String getFormatedBranchCondition() throws ProofInputException { - if (branchCondition == null) { - lazyComputeBranchCondition(); - } - return formatedBranchCondition; - } + /** + * The human readable branch condition. + */ + private String formatedBranchCondition; - /** - * {@inheritDoc} - */ - @Override - public boolean isBranchConditionComputed() { - return branchCondition != null; - } + /** + * The path condition to reach this node. + */ + private Term pathCondition; - /** - * {@inheritDoc} - */ - @Override - public Term getBranchCondition() throws ProofInputException { - if (branchCondition == null) { - lazyComputeBranchCondition(); - } - return branchCondition; - } + /** + * The human readable path condition to reach this node. + */ + private String formatedPathCondition; - /** - * Computes the branch condition lazily when {@link #getBranchCondition()} - * or {@link #getFormatedBranchCondition()} is called the first time. - * @throws ProofInputException Occurred Exception - */ - protected void lazyComputeBranchCondition() throws ProofInputException { - final InitConfig initConfig = getInitConfig(); - if (initConfig != null) { // Otherwise proof is disposed. - final Services services = initConfig.getServices(); - // Compute branch condition - if (isMergedBranchCondition()) { - // Add all merged branch conditions - Term[] mergedConditions = getMergedBranchCondtions(); - branchCondition = services.getTermBuilder().and(mergedBranchCondtions); - // Simplify merged branch conditions - if (mergedConditions.length >= 2) { - if (getSettings().isSimplifyConditions()) { - branchCondition = SymbolicExecutionUtil.simplify(initConfig, getProof(), branchCondition); - } - branchCondition = SymbolicExecutionUtil.improveReadability(branchCondition, services); + /** + * Merged branch conditions. + */ + private List mergedProofNodes; + + /** + * Contains the merged branch conditions. + */ + private Term[] mergedBranchCondtions; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param additionalBranchLabel The optional additional branch label. + */ + public ExecutionBranchCondition(ITreeSettings settings, Node proofNode, + String additionalBranchLabel) { + super(settings, proofNode); + this.additionalBranchLabel = additionalBranchLabel; + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + return getFormatedBranchCondition(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Branch Condition"; + } + + /** + * {@inheritDoc} + */ + @Override + public String getFormatedBranchCondition() throws ProofInputException { + if (branchCondition == null) { + lazyComputeBranchCondition(); + } + return formatedBranchCondition; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBranchConditionComputed() { + return branchCondition != null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getBranchCondition() throws ProofInputException { + if (branchCondition == null) { + lazyComputeBranchCondition(); + } + return branchCondition; + } + + /** + * Computes the branch condition lazily when {@link #getBranchCondition()} or + * {@link #getFormatedBranchCondition()} is called the first time. + * + * @throws ProofInputException Occurred Exception + */ + protected void lazyComputeBranchCondition() throws ProofInputException { + final InitConfig initConfig = getInitConfig(); + if (initConfig != null) { // Otherwise proof is disposed. + final Services services = initConfig.getServices(); + // Compute branch condition + if (isMergedBranchCondition()) { + // Add all merged branch conditions + Term[] mergedConditions = getMergedBranchCondtions(); + branchCondition = services.getTermBuilder().and(mergedBranchCondtions); + // Simplify merged branch conditions + if (mergedConditions.length >= 2) { + if (getSettings().isSimplifyConditions()) { + branchCondition = SymbolicExecutionUtil.simplify(initConfig, getProof(), + branchCondition); + } + branchCondition = + SymbolicExecutionUtil.improveReadability(branchCondition, services); + } + } else { + branchCondition = SymbolicExecutionUtil.computeBranchCondition(getProofNode(), + getSettings().isSimplifyConditions(), true); } - } - else { - branchCondition = SymbolicExecutionUtil.computeBranchCondition(getProofNode(), getSettings().isSimplifyConditions(), true); - } - // Format branch condition - formatedBranchCondition = formatTerm(branchCondition, services); - } - } + // Format branch condition + formatedBranchCondition = formatTerm(branchCondition, services); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPathConditionChanged() { + return true; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isPathConditionChanged() { - return true; - } + /** + * {@inheritDoc} + */ + @Override + public Term getPathCondition() throws ProofInputException { + if (pathCondition == null) { + lazyComputePathCondition(); + } + return pathCondition; + } - /** - * {@inheritDoc} - */ - @Override - public Term getPathCondition() throws ProofInputException { - if (pathCondition == null) { - lazyComputePathCondition(); - } - return pathCondition; - } + /** + * {@inheritDoc} + */ + @Override + public String getFormatedPathCondition() throws ProofInputException { + if (formatedPathCondition == null) { + lazyComputePathCondition(); + } + return formatedPathCondition; + } - /** - * {@inheritDoc} - */ - @Override - public String getFormatedPathCondition() throws ProofInputException { - if (formatedPathCondition == null) { - lazyComputePathCondition(); - } - return formatedPathCondition; - } + /** + * Computes the path condition lazily when {@link #getPathCondition()} or + * {@link #getFormatedPathCondition()} is called the first time. + * + * @throws ProofInputException Occurred Exception + */ + protected void lazyComputePathCondition() throws ProofInputException { + InitConfig initConfig = getInitConfig(); + if (initConfig != null) { // Otherwise proof is disposed. + final Services services = initConfig.getServices(); + // Get path to parent + Term parentPath; + if (getParent() != null) { + parentPath = getParent().getPathCondition(); + } else { + parentPath = services.getTermBuilder().tt(); + } + // Add current branch condition to path + Term branchCondition = getBranchCondition(); + if (branchCondition == null) { + return; // Proof disposed in between. + } + pathCondition = services.getTermBuilder().and(parentPath, branchCondition); + // Simplify path condition + if (getSettings().isSimplifyConditions()) { + pathCondition = + SymbolicExecutionUtil.simplify(initConfig, getProof(), pathCondition); + } + pathCondition = SymbolicExecutionUtil.improveReadability(pathCondition, services); + // Format path condition + formatedPathCondition = formatTerm(pathCondition, services); + } + } - /** - * Computes the path condition lazily when {@link #getPathCondition()} - * or {@link #getFormatedPathCondition()} is called the first time. - * @throws ProofInputException Occurred Exception - */ - protected void lazyComputePathCondition() throws ProofInputException { - InitConfig initConfig = getInitConfig(); - if (initConfig != null) { // Otherwise proof is disposed. - final Services services = initConfig.getServices(); - // Get path to parent - Term parentPath; - if (getParent() != null) { - parentPath = getParent().getPathCondition(); - } - else { - parentPath = services.getTermBuilder().tt(); - } - // Add current branch condition to path - Term branchCondition = getBranchCondition(); - if (branchCondition == null) { - return; // Proof disposed in between. - } - pathCondition = services.getTermBuilder().and(parentPath, branchCondition); - // Simplify path condition - if (getSettings().isSimplifyConditions()) { - pathCondition = SymbolicExecutionUtil.simplify(initConfig, getProof(), pathCondition); - } - pathCondition = SymbolicExecutionUtil.improveReadability(pathCondition, services); - // Format path condition - formatedPathCondition = formatTerm(pathCondition, services); - } - } + /** + * Adds a merged proof {@link Node}. + * + * @param node The proof {@link Node} to add. + */ + public void addMergedProofNode(Node node) { + if (mergedProofNodes == null) { + mergedProofNodes = new LinkedList(); + mergedProofNodes.add(getProofNode()); + } + mergedProofNodes.add(node); + } - /** - * Adds a merged proof {@link Node}. - * @param node The proof {@link Node} to add. - */ - public void addMergedProofNode(Node node) { - if (mergedProofNodes == null) { - mergedProofNodes = new LinkedList(); - mergedProofNodes.add(getProofNode()); - } - mergedProofNodes.add(node); - } - - /** - * {@inheritDoc} - */ - @Override - public Node[] getMergedProofNodes() { - return mergedProofNodes != null ? mergedProofNodes.toArray(new Node[mergedProofNodes.size()]) : new Node[0]; - } + /** + * {@inheritDoc} + */ + @Override + public Node[] getMergedProofNodes() { + return mergedProofNodes != null + ? mergedProofNodes.toArray(new Node[mergedProofNodes.size()]) + : new Node[0]; + } - /** - * {@inheritDoc} - */ - @Override - public Term[] getMergedBranchCondtions() throws ProofInputException { - if (mergedBranchCondtions == null) { - mergedBranchCondtions = lazyComputeMergedBranchCondtions(); - } - return mergedBranchCondtions; - } + /** + * {@inheritDoc} + */ + @Override + public Term[] getMergedBranchCondtions() throws ProofInputException { + if (mergedBranchCondtions == null) { + mergedBranchCondtions = lazyComputeMergedBranchCondtions(); + } + return mergedBranchCondtions; + } - /** - * Computes the branch condition lazily when {@link #getMergedBranchCondtions()} - * is called the first time. - * @throws ProofInputException Occurred Exception - */ - protected Term[] lazyComputeMergedBranchCondtions() throws ProofInputException { - if (isMergedBranchCondition()) { - Term[] result = new Term[mergedProofNodes.size()]; - Iterator iter = mergedProofNodes.iterator(); - for (int i = 0; i < result.length; i++) { - result[i] = SymbolicExecutionUtil.computeBranchCondition(iter.next(), getSettings().isSimplifyConditions(), true); - } - return result; - } - else { - return new Term[0]; - } - } + /** + * Computes the branch condition lazily when {@link #getMergedBranchCondtions()} is called the + * first time. + * + * @throws ProofInputException Occurred Exception + */ + protected Term[] lazyComputeMergedBranchCondtions() throws ProofInputException { + if (isMergedBranchCondition()) { + Term[] result = new Term[mergedProofNodes.size()]; + Iterator iter = mergedProofNodes.iterator(); + for (int i = 0; i < result.length; i++) { + result[i] = SymbolicExecutionUtil.computeBranchCondition(iter.next(), + getSettings().isSimplifyConditions(), true); + } + return result; + } else { + return new Term[0]; + } + } - /** - * {@inheritDoc} - */ - @Override - public boolean isMergedBranchCondition() { - return mergedProofNodes != null && !mergedProofNodes.isEmpty(); - } + /** + * {@inheritDoc} + */ + @Override + public boolean isMergedBranchCondition() { + return mergedProofNodes != null && !mergedProofNodes.isEmpty(); + } - /** - * {@inheritDoc} - */ - @Override - public String getAdditionalBranchLabel() { - return additionalBranchLabel; - } + /** + * {@inheritDoc} + */ + @Override + public String getAdditionalBranchLabel() { + return additionalBranchLabel; + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - protected PosInOccurrence lazyComputeModalityPIO() { - return SymbolicExecutionUtil.findModalityWithMaxSymbolicExecutionLabelId(getProofNode().sequent()); - } + /** + * {@inheritDoc} + */ + @Override + protected PosInOccurrence lazyComputeModalityPIO() { + return SymbolicExecutionUtil + .findModalityWithMaxSymbolicExecutionLabelId(getProofNode().sequent()); + } - /** - * {@inheritDoc} - */ - @Override - public SourceElement getActiveStatement() { - Term modalityTerm = getModalityPIO().subTerm(); - SourceElement firstStatement = modalityTerm.javaBlock().program().getFirstElement(); - return NodeInfo.computeActiveStatement(firstStatement); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public SourceElement getActiveStatement() { + Term modalityTerm = getModalityPIO().subTerm(); + SourceElement firstStatement = modalityTerm.javaBlock().program().getFirstElement(); + return NodeInfo.computeActiveStatement(firstStatement); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchStatement.java index 761bee8b27b..3b69baecce3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionBranchStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.io.IOException; @@ -16,60 +19,60 @@ /** * The default implementation of {@link IExecutionBranchStatement}. + * * @author Martin Hentschel */ -public class ExecutionBranchStatement extends AbstractExecutionBlockStartNode implements IExecutionBranchStatement { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionBranchStatement(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionBranchStatement extends AbstractExecutionBlockStartNode + implements IExecutionBranchStatement { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionBranchStatement(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - BranchStatement bs = getActiveStatement(); - try { - if (bs instanceof If) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printIf((If)bs, false); - return sw.toString(); - } - else if (bs instanceof Switch) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printSwitch((Switch)bs, false); - return sw.toString(); - } - else { + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + BranchStatement bs = getActiveStatement(); + try { + if (bs instanceof If) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printIf((If) bs, false); + return sw.toString(); + } else if (bs instanceof Switch) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printSwitch((Switch) bs, false); + return sw.toString(); + } else { + return bs.toString(); + } + } catch (IOException e) { return bs.toString(); - } - } - catch (IOException e) { - return bs.toString(); - } - } + } + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Branch Statement"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Branch Statement"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionConstraint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionConstraint.java index b1136bcf72b..afd4c7d985b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionConstraint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionConstraint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.logic.PosInOccurrence; @@ -10,62 +13,66 @@ /** * The default implementation of {@link IExecutionConstraint}. + * * @author Martin Hentschel */ public class ExecutionConstraint extends AbstractExecutionElement implements IExecutionConstraint { - /** - * The {@link Term} representing the constraint. - */ - private final Term term; - - /** - * The {@link PosInOccurrence} of the modality of interest. - */ - private final PosInOccurrence modalityPIO; + /** + * The {@link Term} representing the constraint. + */ + private final Term term; - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param term The {@link Term} representing the constraint. - */ - public ExecutionConstraint(ITreeSettings settings, Node proofNode, PosInOccurrence modalityPIO, Term term) { - super(settings, proofNode); - assert term != null; - assert modalityPIO != null; - this.term = term; - this.modalityPIO = modalityPIO; - } + /** + * The {@link PosInOccurrence} of the modality of interest. + */ + private final PosInOccurrence modalityPIO; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - return formatTerm(term, getServices()); - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param term The {@link Term} representing the constraint. + */ + public ExecutionConstraint(ITreeSettings settings, Node proofNode, PosInOccurrence modalityPIO, + Term term) { + super(settings, proofNode); + assert term != null; + assert modalityPIO != null; + this.term = term; + this.modalityPIO = modalityPIO; + } - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Constraint"; - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + return formatTerm(term, getServices()); + } - /** - * {@inheritDoc} - */ - @Override - public Term getTerm() { - return term; - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Constraint"; + } - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return modalityPIO; - } + /** + * {@inheritDoc} + */ + @Override + public Term getTerm() { + return term; + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return modalityPIO; + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionExceptionalMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionExceptionalMethodReturn.java index c48f4e9572b..914a36b8aaa 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionExceptionalMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionExceptionalMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import org.key_project.util.java.StringUtil; @@ -17,64 +20,64 @@ /** * The default implementation of {@link IExecutionExceptionalMethodReturn}. + * * @author Martin Hentschel */ -public class ExecutionExceptionalMethodReturn extends AbstractExecutionMethodReturn implements IExecutionExceptionalMethodReturn { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param methodCall The {@link IExecutionMethodCall} which is now returned. - */ - public ExecutionExceptionalMethodReturn(ITreeSettings settings, - Node proofNode, - ExecutionMethodCall methodCall) { - super(settings, proofNode, methodCall); - } +public class ExecutionExceptionalMethodReturn extends AbstractExecutionMethodReturn + implements IExecutionExceptionalMethodReturn { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param methodCall The {@link IExecutionMethodCall} which is now returned. + */ + public ExecutionExceptionalMethodReturn(ITreeSettings settings, Node proofNode, + ExecutionMethodCall methodCall) { + super(settings, proofNode, methodCall); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - String exceptionType; - Expression expression = getActiveStatement().getExpression(); - if (expression instanceof ProgramVariable) { - KeYJavaType type = ((ProgramVariable) expression).getKeYJavaType(); - exceptionType = type.getFullName(); - } - else { - exceptionType = expression.toString(); - } - return INTERNAL_NODE_NAME_START + "throw " + - exceptionType + - INTERNAL_NODE_NAME_END; - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + String exceptionType; + Expression expression = getActiveStatement().getExpression(); + if (expression instanceof ProgramVariable) { + KeYJavaType type = ((ProgramVariable) expression).getKeYJavaType(); + exceptionType = type.getFullName(); + } else { + exceptionType = expression.toString(); + } + return INTERNAL_NODE_NAME_START + "throw " + exceptionType + INTERNAL_NODE_NAME_END; + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeSignature() throws ProofInputException { - String methodName = getMethodCall().getName(); - return INTERNAL_NODE_NAME_START + "exceptional return" + - (!StringUtil.isTrimmedEmpty(methodName) ? " of " + methodName : "") + - INTERNAL_NODE_NAME_END; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Exceptional Method Return"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeSignature() throws ProofInputException { + String methodName = getMethodCall().getName(); + return INTERNAL_NODE_NAME_START + "exceptional return" + + (!StringUtil.isTrimmedEmpty(methodName) ? " of " + methodName : "") + + INTERNAL_NODE_NAME_END; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Exceptional Method Return"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionJoin.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionJoin.java index 41f3ecf8d90..c107be56499 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionJoin.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionJoin.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.SourceElement; @@ -10,61 +13,62 @@ /** * The default implementation of {@link IExecutionJoin}. + * * @author Martin Hentschel */ public class ExecutionJoin extends AbstractExecutionNode implements IExecutionJoin { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionJoin(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionJoin(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return "Join"; - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return "Join"; + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Join"; - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public boolean isWeakeningVerified() { - if (isWeakeningVerificationSupported()) { - return SymbolicExecutionUtil.lazyComputeIsMainBranchVerified(getProofNode().child(0)); - } - else { - return true; - } - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Join"; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isWeakeningVerificationSupported() { - return SymbolicExecutionUtil.isWeakeningGoalEnabled(getProof()); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean isWeakeningVerified() { + if (isWeakeningVerificationSupported()) { + return SymbolicExecutionUtil.lazyComputeIsMainBranchVerified(getProofNode().child(0)); + } else { + return true; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWeakeningVerificationSupported() { + return SymbolicExecutionUtil.isWeakeningGoalEnabled(getProof()); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLink.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLink.java index 4edc515e627..48fddc4804a 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLink.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLink.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.symbolic_execution.model.IExecutionLink; @@ -5,42 +8,44 @@ /** * The default implementation of {@link IExecutionLink}. + * * @author Martin Hentschel */ public class ExecutionLink implements IExecutionLink { - /** - * The source {@link IExecutionNode}. - */ - private final IExecutionNode source; - - /** - * The target {@link IExecutionNode}. - */ - private final IExecutionNode target; + /** + * The source {@link IExecutionNode}. + */ + private final IExecutionNode source; - /** - * Constructor. - * @param source The source {@link IExecutionNode}. - * @param target The target {@link IExecutionNode}. - */ - public ExecutionLink(IExecutionNode source, IExecutionNode target) { - this.source = source; - this.target = target; - } + /** + * The target {@link IExecutionNode}. + */ + private final IExecutionNode target; - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode getSource() { - return source; - } + /** + * Constructor. + * + * @param source The source {@link IExecutionNode}. + * @param target The target {@link IExecutionNode}. + */ + public ExecutionLink(IExecutionNode source, IExecutionNode target) { + this.source = source; + this.target = target; + } - /** - * {@inheritDoc} - */ - @Override - public IExecutionNode getTarget() { - return target; - } + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode getSource() { + return source; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionNode getTarget() { + return target; + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopCondition.java index 94cb764846f..a2132bb443e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.Expression; @@ -14,64 +17,65 @@ /** * The default implementation of {@link IExecutionLoopCondition}. + * * @author Martin Hentschel */ -public class ExecutionLoopCondition extends AbstractExecutionBlockStartNode implements IExecutionLoopCondition { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionLoopCondition(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionLoopCondition extends AbstractExecutionBlockStartNode + implements IExecutionLoopCondition { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionLoopCondition(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return getGuardExpression().toString(); - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return getGuardExpression().toString(); + } - /** - * {@inheritDoc} - */ - @Override - public Expression getGuardExpression() { - if (getActiveStatement() instanceof LoopStatement) { - return ((LoopStatement) getActiveStatement()).getGuardExpression(); - } - else if (getActiveStatement() instanceof If) { - return ((If) getActiveStatement()).getExpression(); - } - else { - return null; - } - } + /** + * {@inheritDoc} + */ + @Override + public Expression getGuardExpression() { + if (getActiveStatement() instanceof LoopStatement) { + return ((LoopStatement) getActiveStatement()).getGuardExpression(); + } else if (getActiveStatement() instanceof If) { + return ((If) getActiveStatement()).getExpression(); + } else { + return null; + } + } - /** - * {@inheritDoc} - */ - @Override - public PositionInfo getGuardExpressionPositionInfo() { - return getGuardExpression().getPositionInfo(); - } + /** + * {@inheritDoc} + */ + @Override + public PositionInfo getGuardExpressionPositionInfo() { + return getGuardExpression().getPositionInfo(); + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Condition"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Condition"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopInvariant.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopInvariant.java index 476064fb0c4..8e3bfaf21b8 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopInvariant.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopInvariant.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.SourceElement; @@ -13,76 +16,81 @@ /** * The default implementation of {@link IExecutionLoopInvariant}. + * * @author Martin Hentschel */ -public class ExecutionLoopInvariant extends AbstractExecutionNode implements IExecutionLoopInvariant { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionLoopInvariant(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionLoopInvariant extends AbstractExecutionNode + implements IExecutionLoopInvariant { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionLoopInvariant(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - public LoopInvariantBuiltInRuleApp getAppliedRuleApp() { - return (LoopInvariantBuiltInRuleApp) super.getAppliedRuleApp(); - } + /** + * {@inheritDoc} + */ + @Override + public LoopInvariantBuiltInRuleApp getAppliedRuleApp() { + return (LoopInvariantBuiltInRuleApp) super.getAppliedRuleApp(); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return getLoopInvariant().getPlainText(getServices(), getAppliedRuleApp().getHeapContext(), getSettings().isUsePrettyPrinting(), getSettings().isUseUnicode()).trim(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Invariant"; - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return getLoopInvariant().getPlainText(getServices(), getAppliedRuleApp().getHeapContext(), + getSettings().isUsePrettyPrinting(), getSettings().isUseUnicode()).trim(); + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Invariant"; + } - /** - * {@inheritDoc} - */ - @Override - public LoopSpecification getLoopInvariant() { - return ((LoopInvariantBuiltInRuleApp)getProofNode().getAppliedRuleApp()).getSpec(); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public While getLoopStatement() { - return ((LoopInvariantBuiltInRuleApp)getProofNode().getAppliedRuleApp()).getLoopStatement(); - } + /** + * {@inheritDoc} + */ + @Override + public LoopSpecification getLoopInvariant() { + return ((LoopInvariantBuiltInRuleApp) getProofNode().getAppliedRuleApp()).getSpec(); + } - /** - * {@inheritDoc} - */ - @Override - public boolean isInitiallyValid() { - boolean initiallyValid = false; - if (getProofNode().childrenCount() >= 1) { - initiallyValid = getProofNode().child(0).isClosed(); - } - return initiallyValid; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public While getLoopStatement() { + return ((LoopInvariantBuiltInRuleApp) getProofNode().getAppliedRuleApp()) + .getLoopStatement(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isInitiallyValid() { + boolean initiallyValid = false; + if (getProofNode().childrenCount() >= 1) { + initiallyValid = getProofNode().child(0).isClosed(); + } + return initiallyValid; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopStatement.java index 56b4ad5a14c..73cfb8652be 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionLoopStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.io.IOException; @@ -18,77 +21,74 @@ /** * The default implementation of {@link IExecutionLoopStatement}. + * * @author Martin Hentschel */ -public class ExecutionLoopStatement extends AbstractExecutionBlockStartNode implements IExecutionLoopStatement { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionLoopStatement(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionLoopStatement extends AbstractExecutionBlockStartNode + implements IExecutionLoopStatement { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionLoopStatement(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - LoopStatement ls = getActiveStatement(); - try { - if (ls.getGuardExpression() != null) { - if (ls instanceof While) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printWhile((While)ls, false); - return sw.toString(); + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + LoopStatement ls = getActiveStatement(); + try { + if (ls.getGuardExpression() != null) { + if (ls instanceof While) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printWhile((While) ls, false); + return sw.toString(); + } else if (ls instanceof For) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printFor((For) ls, false); + return sw.toString(); + } else if (ls instanceof EnhancedFor) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printEnhancedFor((EnhancedFor) ls, false); + return sw.toString(); + } else if (ls instanceof Do) { + StringWriter sw = new StringWriter(); + PrettyPrinter sb = new PrettyPrinter(sw, true); + sb.printDo((Do) ls, false); + return sw.toString(); + } else { + return ls.toString(); + } + } else { + return ls.toString(); } - else if (ls instanceof For) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printFor((For)ls, false); - return sw.toString(); - } - else if (ls instanceof EnhancedFor) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printEnhancedFor((EnhancedFor)ls, false); - return sw.toString(); - } - else if (ls instanceof Do) { - StringWriter sw = new StringWriter(); - PrettyPrinter sb = new PrettyPrinter(sw, true); - sb.printDo((Do)ls, false); - return sw.toString(); - } - else { - return ls.toString(); - } - } - else { + } catch (IOException e) { return ls.toString(); - } - } - catch (IOException e) { - return ls.toString(); - } - } + } + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Loop Statement"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Loop Statement"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodCall.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodCall.java index 70c7ea3cbd0..285d0640578 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodCall.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodCall.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import org.key_project.util.collection.ImmutableList; @@ -17,143 +20,149 @@ /** * The default implementation of {@link IExecutionMethodCall}. + * * @author Martin Hentschel */ -public class ExecutionMethodCall extends AbstractExecutionNode implements IExecutionMethodCall { - /** - * The up to know discovered {@link IExecutionBaseMethodReturn}s. - */ - private ImmutableList> methodReturns = ImmutableSLList.nil(); - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionMethodCall(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } - - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return INTERNAL_NODE_NAME_START + - "call " + getMethodCallText() + - INTERNAL_NODE_NAME_END; - } - - /** - * Computes the method call text. - * @return The method call text. - */ - protected String getMethodCallText() { - MethodReference explicitConstructorMR = getExplicitConstructorMethodReference(); - String call = explicitConstructorMR != null ? - explicitConstructorMR.toString() : - getMethodReference().toString(); - if (call.endsWith(";")) { - call = call.substring(0, call.length() - 1); - } - return call; - } - - /** - * Removes the given {@link IExecutionBaseMethodReturn}. - * @param methodReturn The {@link IExecutionBaseMethodReturn} to be deleted. - * @author Anna Filighera - */ - public void removeMethodReturn(IExecutionBaseMethodReturn methodReturn) { - methodReturns = methodReturns.removeAll(methodReturn); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isImplicitConstructor() { - return KeYTypeUtil.isImplicitConstructor(getProgramMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public MethodReference getExplicitConstructorMethodReference() { - IProgramMethod explicitConstructor = getExplicitConstructorProgramMethod(); - if (explicitConstructor != null) { - MethodReference mr = getMethodReference(); - return new MethodReference(mr.getArguments(), explicitConstructor.getProgramElementName(), null); // Ignore the prefix because it is ugly if a constructor is called on an object not part of the symbolic execution tree. - } - else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getExplicitConstructorProgramMethod() { - IProgramMethod pm = getProgramMethod(); - if (KeYTypeUtil.isImplicitConstructor(pm)) { - return KeYTypeUtil.findExplicitConstructor(getServices(), pm); - } - else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public MethodReference getMethodReference() { - return getActiveStatement().getMethodReference(); - } - - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getProgramMethod() { - return getActiveStatement().getProgramMethod(getServices()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Method Call"; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList> getMethodReturns() { - return methodReturns; - } - - /** - * Registers the given {@link IExecutionBaseMethodReturn}. - * @param methodReturn The {@link IExecutionBaseMethodReturn} to register. - */ - public void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { - if (methodReturn != null) { - assert methodReturn.getMethodCall() == this; - methodReturns = methodReturns.append(methodReturn); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } -} \ No newline at end of file +public class ExecutionMethodCall extends AbstractExecutionNode + implements IExecutionMethodCall { + /** + * The up to know discovered {@link IExecutionBaseMethodReturn}s. + */ + private ImmutableList> methodReturns = ImmutableSLList.nil(); + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionMethodCall(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return INTERNAL_NODE_NAME_START + "call " + getMethodCallText() + INTERNAL_NODE_NAME_END; + } + + /** + * Computes the method call text. + * + * @return The method call text. + */ + protected String getMethodCallText() { + MethodReference explicitConstructorMR = getExplicitConstructorMethodReference(); + String call = explicitConstructorMR != null ? explicitConstructorMR.toString() + : getMethodReference().toString(); + if (call.endsWith(";")) { + call = call.substring(0, call.length() - 1); + } + return call; + } + + /** + * Removes the given {@link IExecutionBaseMethodReturn}. + * + * @param methodReturn The {@link IExecutionBaseMethodReturn} to be deleted. + * @author Anna Filighera + */ + public void removeMethodReturn(IExecutionBaseMethodReturn methodReturn) { + methodReturns = methodReturns.removeAll(methodReturn); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isImplicitConstructor() { + return KeYTypeUtil.isImplicitConstructor(getProgramMethod()); + } + + /** + * {@inheritDoc} + */ + @Override + public MethodReference getExplicitConstructorMethodReference() { + IProgramMethod explicitConstructor = getExplicitConstructorProgramMethod(); + if (explicitConstructor != null) { + MethodReference mr = getMethodReference(); + return new MethodReference(mr.getArguments(), + explicitConstructor.getProgramElementName(), null); // Ignore the prefix because + // it is ugly if a + // constructor is called on + // an object not part of the + // symbolic execution tree. + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getExplicitConstructorProgramMethod() { + IProgramMethod pm = getProgramMethod(); + if (KeYTypeUtil.isImplicitConstructor(pm)) { + return KeYTypeUtil.findExplicitConstructor(getServices(), pm); + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public MethodReference getMethodReference() { + return getActiveStatement().getMethodReference(); + } + + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getProgramMethod() { + return getActiveStatement().getProgramMethod(getServices()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Method Call"; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList> getMethodReturns() { + return methodReturns; + } + + /** + * Registers the given {@link IExecutionBaseMethodReturn}. + * + * @param methodReturn The {@link IExecutionBaseMethodReturn} to register. + */ + public void addMethodReturn(IExecutionBaseMethodReturn methodReturn) { + if (methodReturn != null) { + assert methodReturn.getMethodCall() == this; + methodReturns = methodReturns.append(methodReturn); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturn.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturn.java index bbcaafc4046..e877f7a1171 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturn.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturn.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.LinkedHashMap; @@ -38,341 +41,379 @@ /** * The default implementation of {@link IExecutionMethodReturn}. + * * @author Martin Hentschel */ -public class ExecutionMethodReturn extends AbstractExecutionMethodReturn implements IExecutionMethodReturn { - /** - * The node name with signature including the return value. - */ - private String signatureIncludingReturnValue; - - /** - * The node name including the return value. - */ - private String nameIncludingReturnValue; - - /** - * The possible return values. - */ - private IExecutionMethodReturnValue[] returnValues; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param methodCall The {@link IExecutionMethodCall} which is now returned. - */ - public ExecutionMethodReturn(ITreeSettings settings, - Node proofNode, - ExecutionMethodCall methodCall) { - super(settings, proofNode, methodCall); - } +public class ExecutionMethodReturn extends AbstractExecutionMethodReturn + implements IExecutionMethodReturn { + /** + * The node name with signature including the return value. + */ + private String signatureIncludingReturnValue; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - return createMethodReturnName(null, computeCalledMethodName()); - } - - /** - * Computes the name of the called method. - * @return The name of the called method. - */ - protected String computeCalledMethodName() { - MethodReference explicitConstructorMR = getMethodCall().getExplicitConstructorMethodReference(); - return explicitConstructorMR != null ? - explicitConstructorMR.getMethodName().toString() : - getMethodCall().getProgramMethod().getName(); - } + /** + * The node name including the return value. + */ + private String nameIncludingReturnValue; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeSignature() throws ProofInputException { - return createMethodReturnName(null, computeCalledMethodSignature()); - } - - /** - * Computes the signature of the called method. - * @return The signature of the called method. - */ - protected String computeCalledMethodSignature() throws ProofInputException { - MethodReference explicitConstructorMR = getMethodCall().getExplicitConstructorMethodReference(); - String call = explicitConstructorMR != null ? - explicitConstructorMR.toString() : - getMethodCall().getMethodReference().toString(); - if (call.endsWith(";")) { - call = call.substring(0, call.length() - 1); - } - return call; - } + /** + * The possible return values. + */ + private IExecutionMethodReturnValue[] returnValues; - /** - * {@inheritDoc} - */ - @Override - public String getNameIncludingReturnValue() throws ProofInputException { - if (nameIncludingReturnValue == null) { - nameIncludingReturnValue = lazyComputeNameIncludingReturnValue(); - } - return nameIncludingReturnValue; - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param methodCall The {@link IExecutionMethodCall} which is now returned. + */ + public ExecutionMethodReturn(ITreeSettings settings, Node proofNode, + ExecutionMethodCall methodCall) { + super(settings, proofNode, methodCall); + } - /** - * Computes the name including the return value lazily when - * {@link #getNameIncludingReturnValue()} is called the first time. - * @return The name including the return value. - * @throws Occurred Exception. - */ - protected String lazyComputeNameIncludingReturnValue() throws ProofInputException { - IExecutionMethodReturnValue[] returnValues = getReturnValues(); - if (returnValues.length == 0) { - return createMethodReturnName(null, computeCalledMethodName()); - } - else if (returnValues.length == 1) { - return createMethodReturnName(returnValues[0].getName() + " ", computeCalledMethodName()); - } - else { - StringBuilder sb = new StringBuilder(); - sb.append('\n'); - boolean afterFirst = false; - for (IExecutionMethodReturnValue value : returnValues) { - if (afterFirst) { - sb.append(", \n"); - } - else { - afterFirst = true; - } - sb.append('\t'); - sb.append(value.getName()); - } - sb.append('\n'); - return createMethodReturnName(sb.toString(), computeCalledMethodName()); - } - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + return createMethodReturnName(null, computeCalledMethodName()); + } + + /** + * Computes the name of the called method. + * + * @return The name of the called method. + */ + protected String computeCalledMethodName() { + MethodReference explicitConstructorMR = + getMethodCall().getExplicitConstructorMethodReference(); + return explicitConstructorMR != null ? explicitConstructorMR.getMethodName().toString() + : getMethodCall().getProgramMethod().getName(); + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeSignature() throws ProofInputException { + return createMethodReturnName(null, computeCalledMethodSignature()); + } - /** - * {@inheritDoc} - */ - @Override - public String getSignatureIncludingReturnValue() throws ProofInputException { - if (signatureIncludingReturnValue == null) { - signatureIncludingReturnValue = lazyComputeSigntureIncludingReturnValue(); - } - return signatureIncludingReturnValue; - } + /** + * Computes the signature of the called method. + * + * @return The signature of the called method. + */ + protected String computeCalledMethodSignature() throws ProofInputException { + MethodReference explicitConstructorMR = + getMethodCall().getExplicitConstructorMethodReference(); + String call = explicitConstructorMR != null ? explicitConstructorMR.toString() + : getMethodCall().getMethodReference().toString(); + if (call.endsWith(";")) { + call = call.substring(0, call.length() - 1); + } + return call; + } - /** - * Computes the signature including the return value lazily when - * {@link #getNameIncludingReturnValue()} is called the first time. - * @return The name including the return value. - * @throws Occurred Exception. - */ - protected String lazyComputeSigntureIncludingReturnValue() throws ProofInputException { - IExecutionMethodReturnValue[] returnValues = getReturnValues(); - if (returnValues.length == 0) { - return createMethodReturnName(null, computeCalledMethodSignature()); - } - else if (returnValues.length == 1) { - return createMethodReturnName(returnValues[0].getName() + " ", computeCalledMethodSignature()); - } - else { - StringBuilder sb = new StringBuilder(); - sb.append('\n'); - boolean afterFirst = false; - for (IExecutionMethodReturnValue value : returnValues) { - if (afterFirst) { - sb.append(", \n"); + /** + * {@inheritDoc} + */ + @Override + public String getNameIncludingReturnValue() throws ProofInputException { + if (nameIncludingReturnValue == null) { + nameIncludingReturnValue = lazyComputeNameIncludingReturnValue(); + } + return nameIncludingReturnValue; + } + + /** + * Computes the name including the return value lazily when + * {@link #getNameIncludingReturnValue()} is called the first time. + * + * @return The name including the return value. + * @throws Occurred Exception. + */ + protected String lazyComputeNameIncludingReturnValue() throws ProofInputException { + IExecutionMethodReturnValue[] returnValues = getReturnValues(); + if (returnValues.length == 0) { + return createMethodReturnName(null, computeCalledMethodName()); + } else if (returnValues.length == 1) { + return createMethodReturnName(returnValues[0].getName() + " ", + computeCalledMethodName()); + } else { + StringBuilder sb = new StringBuilder(); + sb.append('\n'); + boolean afterFirst = false; + for (IExecutionMethodReturnValue value : returnValues) { + if (afterFirst) { + sb.append(", \n"); + } else { + afterFirst = true; + } + sb.append('\t'); + sb.append(value.getName()); } - else { - afterFirst = true; + sb.append('\n'); + return createMethodReturnName(sb.toString(), computeCalledMethodName()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getSignatureIncludingReturnValue() throws ProofInputException { + if (signatureIncludingReturnValue == null) { + signatureIncludingReturnValue = lazyComputeSigntureIncludingReturnValue(); + } + return signatureIncludingReturnValue; + } + + /** + * Computes the signature including the return value lazily when + * {@link #getNameIncludingReturnValue()} is called the first time. + * + * @return The name including the return value. + * @throws Occurred Exception. + */ + protected String lazyComputeSigntureIncludingReturnValue() throws ProofInputException { + IExecutionMethodReturnValue[] returnValues = getReturnValues(); + if (returnValues.length == 0) { + return createMethodReturnName(null, computeCalledMethodSignature()); + } else if (returnValues.length == 1) { + return createMethodReturnName(returnValues[0].getName() + " ", + computeCalledMethodSignature()); + } else { + StringBuilder sb = new StringBuilder(); + sb.append('\n'); + boolean afterFirst = false; + for (IExecutionMethodReturnValue value : returnValues) { + if (afterFirst) { + sb.append(", \n"); + } else { + afterFirst = true; + } + sb.append('\t'); + sb.append(value.getName()); } - sb.append('\t'); - sb.append(value.getName()); - } - sb.append('\n'); - return createMethodReturnName(sb.toString(), computeCalledMethodSignature()); - } - } + sb.append('\n'); + return createMethodReturnName(sb.toString(), computeCalledMethodSignature()); + } + } - /** - * {@inheritDoc} - */ - @Override - public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException { - if (returnValues == null) { - returnValues = lazyComputeReturnValues(); - } - return returnValues; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isReturnValuesComputed() { - return returnValues != null; - } - - /** - * Computes the return value lazily when - * {@link #getReturnValue()} is called the first time. - * @return The return value. - * @throws ProofInputException Occurred Exception. - */ - protected IExecutionMethodReturnValue[] lazyComputeReturnValues() throws ProofInputException { - InitConfig initConfig = getInitConfig(); - if (initConfig != null) { // Otherwise proof is disposed. - final Services services = initConfig.getServices(); - // Check if a result variable is available - MethodBodyStatement mbs = getMethodCall().getActiveStatement(); - IProgramVariable resultVar = mbs.getResultVariable(); - // Create a temporary result variable for non void methods in case that it is missing in method frame - if (resultVar == null) { - IProgramMethod pm = mbs.getProgramMethod(services); - if (!pm.isVoid()) { - resultVar = new LocationVariable(new ProgramElementName(services.getTermBuilder().newName("TmpResultVar")), pm.getReturnType()); + /** + * {@inheritDoc} + */ + @Override + public IExecutionMethodReturnValue[] getReturnValues() throws ProofInputException { + if (returnValues == null) { + returnValues = lazyComputeReturnValues(); + } + return returnValues; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isReturnValuesComputed() { + return returnValues != null; + } + + /** + * Computes the return value lazily when {@link #getReturnValue()} is called the first time. + * + * @return The return value. + * @throws ProofInputException Occurred Exception. + */ + protected IExecutionMethodReturnValue[] lazyComputeReturnValues() throws ProofInputException { + InitConfig initConfig = getInitConfig(); + if (initConfig != null) { // Otherwise proof is disposed. + final Services services = initConfig.getServices(); + // Check if a result variable is available + MethodBodyStatement mbs = getMethodCall().getActiveStatement(); + IProgramVariable resultVar = mbs.getResultVariable(); + // Create a temporary result variable for non void methods in case that it is missing in + // method frame + if (resultVar == null) { + IProgramMethod pm = mbs.getProgramMethod(services); + if (!pm.isVoid()) { + resultVar = new LocationVariable( + new ProgramElementName( + services.getTermBuilder().newName("TmpResultVar")), + pm.getReturnType()); + } } - } - if (resultVar != null) { - // Search the node with applied rule "methodCallReturn" which provides the required updates - Node methodReturnNode = findMethodReturnNode(getProofNode()); - if (methodReturnNode != null) { - // Start site proof to extract the value of the result variable. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - SiteProofVariableValueInput input = SymbolicExecutionUtil.createExtractReturnVariableValueSequent(services, - mbs.getBodySourceAsTypeReference(), - mbs.getProgramMethod(services), - mbs.getDesignatedContext(), - methodReturnNode, - getProofNode(), - resultVar); - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), - sideProofEnv, - input.getSequentToProve(), - StrategyProperties.METHOD_NONE, - StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, - StrategyProperties.SPLITTING_NORMAL); - try { - if (info.getProof().openGoals().size() == 1) { - Goal goal = info.getProof().openGoals().head(); - Term returnValue = SymbolicExecutionSideProofUtil.extractOperatorValue(goal, input.getOperator()); - assert returnValue != null; - returnValue = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), returnValue, services); - return new IExecutionMethodReturnValue[] {new ExecutionMethodReturnValue(getSettings(), getProofNode(), getModalityPIO(), returnValue, null)}; - } - else { - // Group equal values of different branches - Map> valueNodeMap = new LinkedHashMap>(); - for (Goal goal : info.getProof().openGoals()) { - Term returnValue = SymbolicExecutionSideProofUtil.extractOperatorValue(goal, input.getOperator()); - assert returnValue != null; - returnValue = SymbolicExecutionUtil.replaceSkolemConstants(goal.node().sequent(), returnValue, services); - List nodeList = valueNodeMap.get(returnValue); - if (nodeList == null) { - nodeList = new LinkedList(); - valueNodeMap.put(returnValue, nodeList); - } - nodeList.add(goal.node()); - } - // Create result - if (valueNodeMap.size() == 1) { - Term returnValue = valueNodeMap.keySet().iterator().next(); - return new IExecutionMethodReturnValue[] {new ExecutionMethodReturnValue(getSettings(), getProofNode(), getModalityPIO(), returnValue, null)}; - } - else { - IExecutionMethodReturnValue[] result = new IExecutionMethodReturnValue[valueNodeMap.size()]; - int i = 0; - for (Entry> entry : valueNodeMap.entrySet()) { - List conditions = new LinkedList(); - for (Node node : entry.getValue()) { - Term condition = SymbolicExecutionUtil.computePathCondition(node, getSettings().isSimplifyConditions(), false); - conditions.add(condition); - } - Term condition = services.getTermBuilder().or(conditions); - if (conditions.size() >= 2) { - if (getSettings().isSimplifyConditions()) { - condition = SymbolicExecutionUtil.simplify(initConfig, info.getProof(), condition); - } - } - condition = SymbolicExecutionUtil.improveReadability(condition, info.getProof().getServices()); - result[i] = new ExecutionMethodReturnValue(getSettings(), getProofNode(), getModalityPIO(), entry.getKey(), condition); - i++; + if (resultVar != null) { + // Search the node with applied rule "methodCallReturn" which provides the required + // updates + Node methodReturnNode = findMethodReturnNode(getProofNode()); + if (methodReturnNode != null) { + // Start site proof to extract the value of the result variable. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + SiteProofVariableValueInput input = + SymbolicExecutionUtil.createExtractReturnVariableValueSequent(services, + mbs.getBodySourceAsTypeReference(), + mbs.getProgramMethod(services), mbs.getDesignatedContext(), + methodReturnNode, getProofNode(), resultVar); + ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof( + getProof(), sideProofEnv, input.getSequentToProve(), + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_NORMAL); + try { + if (info.getProof().openGoals().size() == 1) { + Goal goal = info.getProof().openGoals().head(); + Term returnValue = SymbolicExecutionSideProofUtil + .extractOperatorValue(goal, input.getOperator()); + assert returnValue != null; + returnValue = SymbolicExecutionUtil + .replaceSkolemConstants(goal.sequent(), returnValue, services); + return new IExecutionMethodReturnValue[] { + new ExecutionMethodReturnValue(getSettings(), getProofNode(), + getModalityPIO(), returnValue, null) }; + } else { + // Group equal values of different branches + Map> valueNodeMap = + new LinkedHashMap>(); + for (Goal goal : info.getProof().openGoals()) { + Term returnValue = SymbolicExecutionSideProofUtil + .extractOperatorValue(goal, input.getOperator()); + assert returnValue != null; + returnValue = SymbolicExecutionUtil.replaceSkolemConstants( + goal.node().sequent(), returnValue, services); + List nodeList = valueNodeMap.get(returnValue); + if (nodeList == null) { + nodeList = new LinkedList(); + valueNodeMap.put(returnValue, nodeList); + } + nodeList.add(goal.node()); + } + // Create result + if (valueNodeMap.size() == 1) { + Term returnValue = valueNodeMap.keySet().iterator().next(); + return new IExecutionMethodReturnValue[] { + new ExecutionMethodReturnValue(getSettings(), + getProofNode(), getModalityPIO(), returnValue, + null) }; + } else { + IExecutionMethodReturnValue[] result = + new IExecutionMethodReturnValue[valueNodeMap.size()]; + int i = 0; + for (Entry> entry : valueNodeMap.entrySet()) { + List conditions = new LinkedList(); + for (Node node : entry.getValue()) { + Term condition = SymbolicExecutionUtil.computePathCondition( + node, getSettings().isSimplifyConditions(), false); + conditions.add(condition); + } + Term condition = services.getTermBuilder().or(conditions); + if (conditions.size() >= 2) { + if (getSettings().isSimplifyConditions()) { + condition = SymbolicExecutionUtil.simplify(initConfig, + info.getProof(), condition); + } + } + condition = SymbolicExecutionUtil.improveReadability(condition, + info.getProof().getServices()); + result[i] = new ExecutionMethodReturnValue(getSettings(), + getProofNode(), getModalityPIO(), entry.getKey(), + condition); + i++; + } + return result; + } } - return result; - } - } - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Return value computation on method return node " + methodReturnNode.serialNr() + ".", info); - } + } finally { + SymbolicExecutionSideProofUtil + .disposeOrStore("Return value computation on method return node " + + methodReturnNode.serialNr() + ".", info); + } + } else { + return new IExecutionMethodReturnValue[0]; + } + } else { + return new IExecutionMethodReturnValue[0]; } - else { - return new IExecutionMethodReturnValue[0]; - } - } - else { + } else { return new IExecutionMethodReturnValue[0]; - } - } - else { - return new IExecutionMethodReturnValue[0]; - } - } - - /** - * Searches from the given {@link Node} the parent which applies - * the rule "methodCallReturn" in the same modality. - * @param node The {@link Node} to start search from. - * @return The found {@link Node} with rule "methodCallReturn" or {@code null} if no node was found. - */ - protected Node findMethodReturnNode(Node node) { - Node resultNode = null; - SymbolicExecutionTermLabel origianlLabel = SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); - if (origianlLabel != null) { - while (node != null && resultNode == null) { - if ("methodCallReturn".equals(MiscTools.getRuleDisplayName(node))) { - SymbolicExecutionTermLabel currentLabel = SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); - if (currentLabel != null && origianlLabel.equals(currentLabel)) { - resultNode = node; - } + } + } + + /** + * Searches from the given {@link Node} the parent which applies the rule "methodCallReturn" in + * the same modality. + * + * @param node The {@link Node} to start search from. + * @return The found {@link Node} with rule "methodCallReturn" or {@code null} if no node was + * found. + */ + protected Node findMethodReturnNode(Node node) { + Node resultNode = null; + SymbolicExecutionTermLabel origianlLabel = + SymbolicExecutionUtil.getSymbolicExecutionLabel(node.getAppliedRuleApp()); + if (origianlLabel != null) { + while (node != null && resultNode == null) { + if ("methodCallReturn".equals(MiscTools.getRuleDisplayName(node))) { + SymbolicExecutionTermLabel currentLabel = SymbolicExecutionUtil + .getSymbolicExecutionLabel(node.getAppliedRuleApp()); + if (currentLabel != null && origianlLabel.equals(currentLabel)) { + resultNode = node; + } + } + node = node.parent(); } - node = node.parent(); - } - } - return resultNode; - } + } + return resultNode; + } + + /** + * Creates the human readable name which is shown in {@link IExecutionMethodReturn} instances. + * + * @param returnValue The return value. + * @param methodName The name of the method that is completely executed. + * @return The created human readable name. + */ + public static String createMethodReturnName(Object returnValue, String methodName) { + return INTERNAL_NODE_NAME_START + "return" + + (returnValue != null ? " " + returnValue + "as result" : "") + + (!StringUtil.isTrimmedEmpty(methodName) ? " of " + methodName : "") + + INTERNAL_NODE_NAME_END; + } - /** - * Creates the human readable name which is shown in {@link IExecutionMethodReturn} instances. - * @param returnValue The return value. - * @param methodName The name of the method that is completely executed. - * @return The created human readable name. - */ - public static String createMethodReturnName(Object returnValue, String methodName) { - return INTERNAL_NODE_NAME_START + "return" + - (returnValue != null ? " " + returnValue + "as result" : "") + - (!StringUtil.isTrimmedEmpty(methodName) ? " of " + methodName : "") + - INTERNAL_NODE_NAME_END; - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Method Return"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Method Return"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturnValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturnValue.java index 4a2df7451f6..fddde7b4317 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturnValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionMethodReturnValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.logic.PosInOccurrence; @@ -10,149 +13,150 @@ /** * The default implementation of {@link IExecutionMethodReturnValue}. + * * @author Martin Hentschel */ -public class ExecutionMethodReturnValue extends AbstractExecutionElement implements IExecutionMethodReturnValue { - /** - * The return value. - */ - private final Term returnValue; - - /** - * The {@link PosInOccurrence} of the modality of interest. - */ - private final PosInOccurrence modalityPIO; - - /** - * The return value as human readable {@link String}. - */ - private String returnValueString; - - /** - * The optional condition. - */ - private final Term condition; - - /** - * The optional condition as human readable {@link String}. - */ - private String conditionString; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param returnValue The return value. - * @param condition The optional condition or {@code null} if no condition is available. - */ - public ExecutionMethodReturnValue(ITreeSettings settings, - Node proofNode, - PosInOccurrence modalityPIO, - Term returnValue, - Term condition) { - super(settings, proofNode); - assert returnValue != null; - assert modalityPIO != null; - this.returnValue = returnValue; - this.condition = condition; - this.modalityPIO = modalityPIO; - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Return Value"; - } - - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - if (hasCondition()) { - return getReturnValueString() + " {" + getConditionString() + "}"; - } - else { - return getReturnValueString(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term getReturnValue() throws ProofInputException { - return returnValue; - } - - /** - * {@inheritDoc} - */ - @Override - public String getReturnValueString() throws ProofInputException { - if (returnValueString == null) { - returnValueString = lazyComputeReturnValueString(); - } - return returnValueString; - } - - /** - * Computes the human readable return value of this node lazily when {@link #getReturnValueString()} - * is called the first time. - * @return The human readable return value. - */ - protected String lazyComputeReturnValueString() throws ProofInputException { - return !isDisposed() ? formatTerm(returnValue, getServices()) : null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasCondition() throws ProofInputException { - return condition != null; - } - - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() throws ProofInputException { - return condition; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() throws ProofInputException { - if (conditionString == null) { - conditionString = lazyComputeConditionString(); - } - return conditionString; - } - - /** - * Computes the human readable return value of this node lazily when {@link #getConditionString()} - * is called the first time. - * @return The human readable return value. - */ - protected String lazyComputeConditionString() throws ProofInputException { - if (hasCondition()) { - return !isDisposed() ? formatTerm(condition, getServices()) : null; - } - else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public PosInOccurrence getModalityPIO() { - return modalityPIO; - } -} \ No newline at end of file +public class ExecutionMethodReturnValue extends AbstractExecutionElement + implements IExecutionMethodReturnValue { + /** + * The return value. + */ + private final Term returnValue; + + /** + * The {@link PosInOccurrence} of the modality of interest. + */ + private final PosInOccurrence modalityPIO; + + /** + * The return value as human readable {@link String}. + */ + private String returnValueString; + + /** + * The optional condition. + */ + private final Term condition; + + /** + * The optional condition as human readable {@link String}. + */ + private String conditionString; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param returnValue The return value. + * @param condition The optional condition or {@code null} if no condition is available. + */ + public ExecutionMethodReturnValue(ITreeSettings settings, Node proofNode, + PosInOccurrence modalityPIO, Term returnValue, Term condition) { + super(settings, proofNode); + assert returnValue != null; + assert modalityPIO != null; + this.returnValue = returnValue; + this.condition = condition; + this.modalityPIO = modalityPIO; + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Return Value"; + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + if (hasCondition()) { + return getReturnValueString() + " {" + getConditionString() + "}"; + } else { + return getReturnValueString(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term getReturnValue() throws ProofInputException { + return returnValue; + } + + /** + * {@inheritDoc} + */ + @Override + public String getReturnValueString() throws ProofInputException { + if (returnValueString == null) { + returnValueString = lazyComputeReturnValueString(); + } + return returnValueString; + } + + /** + * Computes the human readable return value of this node lazily when + * {@link #getReturnValueString()} is called the first time. + * + * @return The human readable return value. + */ + protected String lazyComputeReturnValueString() throws ProofInputException { + return !isDisposed() ? formatTerm(returnValue, getServices()) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasCondition() throws ProofInputException { + return condition != null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() throws ProofInputException { + return condition; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() throws ProofInputException { + if (conditionString == null) { + conditionString = lazyComputeConditionString(); + } + return conditionString; + } + + /** + * Computes the human readable return value of this node lazily when + * {@link #getConditionString()} is called the first time. + * + * @return The human readable return value. + */ + protected String lazyComputeConditionString() throws ProofInputException { + if (hasCondition()) { + return !isDisposed() ? formatTerm(condition, getServices()) : null; + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public PosInOccurrence getModalityPIO() { + return modalityPIO; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionOperationContract.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionOperationContract.java index 6e86275b69a..1a32762152a 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionOperationContract.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionOperationContract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.List; @@ -40,339 +43,347 @@ /** * The default implementation of {@link IExecutionOperationContract}. + * * @author Martin Hentschel */ -public class ExecutionOperationContract extends AbstractExecutionNode implements IExecutionOperationContract { - /** - * The exception {@link Term} used by the applied {@link Contract}. - */ - private Term exceptionTerm; +public class ExecutionOperationContract extends AbstractExecutionNode + implements IExecutionOperationContract { + /** + * The exception {@link Term} used by the applied {@link Contract}. + */ + private Term exceptionTerm; - /** - * The result {@link Term} used by the applied {@link Contract}. - */ - private Term resultTerm; + /** + * The result {@link Term} used by the applied {@link Contract}. + */ + private Term resultTerm; - /** - * The self {@link Term} or {@code null} if not available. - */ - private Term selfTerm; - - /** - * The current contract parameters. - */ - private ImmutableList contractParams; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionOperationContract(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } + /** + * The self {@link Term} or {@code null} if not available. + */ + private Term selfTerm; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() throws ProofInputException { - if (!isDisposed()) { - final Services services = getServices(); - // Make sure that the contract is compatible - if (!(getContract() instanceof FunctionalOperationContract)) { - throw new ProofInputException("Unsupported contract: " + getContract()); - } - FunctionalOperationContract contract = (FunctionalOperationContract)getContract(); - // Compute instantiation - Instantiation inst = UseOperationContractRule.computeInstantiation(getProofNode().getAppliedRuleApp().posInOccurrence().subTerm(), services); - // Extract used result and exception variable from proof nodes - resultTerm = searchResultTerm(contract, inst, services); - ContractPostOrExcPostExceptionVariableResult search = SymbolicExecutionUtil.searchContractPostOrExcPostExceptionVariable(getProofNode().child(0), services); // Post branch - exceptionTerm = search.getExceptionEquality().sub(0); - // Rename variables in contract to the current one - List heapContext = HeapContext.getModHeaps(services, inst.transaction); - Map atPreVars = UseOperationContractRule.computeAtPreVars(heapContext, services, inst); - Map atPres = HeapContext.getAtPres(atPreVars, services); - LocationVariable baseHeap = services.getTypeConverter().getHeapLDT().getHeap(); - Term baseHeapTerm = services.getTermBuilder().getBaseHeap(); - if (contract.hasSelfVar()) { - if (inst.pm.isConstructor()) { - selfTerm = searchConstructorSelfDefinition(search.getWorkingTerm(), inst.staticType, services); - if (selfTerm == null) { - throw new ProofInputException("Can't find self term, implementation of UseOperationContractRule might has changed!"); - } - KeYJavaType selfType = services.getJavaInfo().getKeYJavaType(selfTerm.sort()); - if (inst.staticType != selfType) { - throw new ProofInputException("Type \"" + inst.staticType + "\" expected but found \"" + selfType + "\", implementation of UseOperationContractRule might has changed!"); - } + /** + * The current contract parameters. + */ + private ImmutableList contractParams; + + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionOperationContract(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } + + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() throws ProofInputException { + if (!isDisposed()) { + final Services services = getServices(); + // Make sure that the contract is compatible + if (!(getContract() instanceof FunctionalOperationContract)) { + throw new ProofInputException("Unsupported contract: " + getContract()); + } + FunctionalOperationContract contract = (FunctionalOperationContract) getContract(); + // Compute instantiation + Instantiation inst = UseOperationContractRule.computeInstantiation( + getProofNode().getAppliedRuleApp().posInOccurrence().subTerm(), services); + // Extract used result and exception variable from proof nodes + resultTerm = searchResultTerm(contract, inst, services); + ContractPostOrExcPostExceptionVariableResult search = + SymbolicExecutionUtil.searchContractPostOrExcPostExceptionVariable( + getProofNode().child(0), services); // Post branch + exceptionTerm = search.getExceptionEquality().sub(0); + // Rename variables in contract to the current one + List heapContext = + HeapContext.getModHeaps(services, inst.transaction); + Map atPreVars = + UseOperationContractRule.computeAtPreVars(heapContext, services, inst); + Map atPres = HeapContext.getAtPres(atPreVars, services); + LocationVariable baseHeap = services.getTypeConverter().getHeapLDT().getHeap(); + Term baseHeapTerm = services.getTermBuilder().getBaseHeap(); + if (contract.hasSelfVar()) { + if (inst.pm.isConstructor()) { + selfTerm = searchConstructorSelfDefinition(search.getWorkingTerm(), + inst.staticType, services); + if (selfTerm == null) { + throw new ProofInputException( + "Can't find self term, implementation of UseOperationContractRule might has changed!"); + } + KeYJavaType selfType = services.getJavaInfo().getKeYJavaType(selfTerm.sort()); + if (inst.staticType != selfType) { + throw new ProofInputException("Type \"" + inst.staticType + + "\" expected but found \"" + selfType + + "\", implementation of UseOperationContractRule might has changed!"); + } + } else { + selfTerm = UseOperationContractRule.computeSelf(baseHeapTerm, atPres, baseHeap, + inst, resultTerm, services.getTermFactory()); + } + } + contractParams = UseOperationContractRule.computeParams(baseHeapTerm, atPres, baseHeap, + inst, services.getTermFactory()); + // Compute contract text + return FunctionalOperationContractImpl + .getText(contract, contractParams, resultTerm, selfTerm, exceptionTerm, + baseHeap, baseHeapTerm, heapContext, atPres, false, services, + getSettings().isUsePrettyPrinting(), getSettings().isUseUnicode()) + .trim(); + } else { + return null; + } + } + + /** + * Tries to find the self {@link Term} of the given {@link KeYJavaType}. + * + * @param term The {@link Term} to start search in. + * @param staticType The expected {@link KeYJavaType}. + * @param services The {@link Services} to use. + * @return The found self {@link Term} or {@code null} if not available. + */ + protected Term searchConstructorSelfDefinition(Term term, KeYJavaType staticType, + Services services) { + if (term.op() == Junctor.NOT && term.sub(0).op() == Equality.EQUALS + && term.sub(0).sub(0).op() instanceof LocationVariable + && SymbolicExecutionUtil.isNullSort(term.sub(0).sub(1).sort(), services) + && services.getJavaInfo().getKeYJavaType(term.sub(0).sub(0).sort()) == staticType) { + return term.sub(0).sub(0); + } else { + Term result = null; + int i = term.arity() - 1; + while (result == null && i >= 0) { + result = searchConstructorSelfDefinition(term.sub(i), staticType, services); + i--; + } + return result; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term getResultTerm() throws ProofInputException { + synchronized (this) { + if (!isNameComputed()) { + getName(); // Compute name and result term } - else { - selfTerm = UseOperationContractRule.computeSelf(baseHeapTerm, atPres, baseHeap, inst, resultTerm, services.getTermFactory()); + return resultTerm; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term getExceptionTerm() throws ProofInputException { + synchronized (this) { + if (!isNameComputed()) { + getName(); // Compute name and exception term + } + return exceptionTerm; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term getSelfTerm() throws ProofInputException { + synchronized (this) { + if (!isNameComputed()) { + getName(); // Compute name and self term } - } - contractParams = UseOperationContractRule.computeParams(baseHeapTerm, atPres, baseHeap, inst, services.getTermFactory()); - // Compute contract text - return FunctionalOperationContractImpl.getText(contract, - contractParams, - resultTerm, - selfTerm, - exceptionTerm, - baseHeap, - baseHeapTerm, - heapContext, - atPres, - false, - services, - getSettings().isUsePrettyPrinting(), - getSettings().isUseUnicode()).trim(); - } - else { - return null; - } - } - - /** - * Tries to find the self {@link Term} of the given {@link KeYJavaType}. - * @param term The {@link Term} to start search in. - * @param staticType The expected {@link KeYJavaType}. - * @param services The {@link Services} to use. - * @return The found self {@link Term} or {@code null} if not available. - */ - protected Term searchConstructorSelfDefinition(Term term, KeYJavaType staticType, Services services) { - if (term.op() == Junctor.NOT && - term.sub(0).op() == Equality.EQUALS && - term.sub(0).sub(0).op() instanceof LocationVariable && - SymbolicExecutionUtil.isNullSort(term.sub(0).sub(1).sort(), services) && - services.getJavaInfo().getKeYJavaType(term.sub(0).sub(0).sort()) == staticType) { - return term.sub(0).sub(0); - } - else { - Term result = null; - int i = term.arity() - 1; - while (result == null && i >= 0) { - result = searchConstructorSelfDefinition(term.sub(i), staticType, services); - i--; - } - return result; - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term getResultTerm() throws ProofInputException { - synchronized (this) { - if (!isNameComputed()) { - getName(); // Compute name and result term - } - return resultTerm; - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term getExceptionTerm() throws ProofInputException { - synchronized (this) { - if (!isNameComputed()) { - getName(); // Compute name and exception term - } - return exceptionTerm; - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term getSelfTerm() throws ProofInputException { - synchronized (this) { - if (!isNameComputed()) { - getName(); // Compute name and self term - } - return selfTerm; - } - } + return selfTerm; + } + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getContractParams() throws ProofInputException { - synchronized (this) { - if (!isNameComputed()) { - getName(); // Compute name and contract term - } - return contractParams; - } - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getContractParams() throws ProofInputException { + synchronized (this) { + if (!isNameComputed()) { + getName(); // Compute name and contract term + } + return contractParams; + } + } - /** - * {@inheritDoc} - */ - @Override - public String getFormatedResultTerm() throws ProofInputException { - Term resultTerm = getResultTerm(); - return resultTerm != null ? formatTerm(resultTerm, getServices()) : null; - } + /** + * {@inheritDoc} + */ + @Override + public String getFormatedResultTerm() throws ProofInputException { + Term resultTerm = getResultTerm(); + return resultTerm != null ? formatTerm(resultTerm, getServices()) : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getFormatedExceptionTerm() throws ProofInputException { - Term exceptionTerm = getExceptionTerm(); - return exceptionTerm != null ? formatTerm(exceptionTerm, getServices()) : null; - } + /** + * {@inheritDoc} + */ + @Override + public String getFormatedExceptionTerm() throws ProofInputException { + Term exceptionTerm = getExceptionTerm(); + return exceptionTerm != null ? formatTerm(exceptionTerm, getServices()) : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getFormatedSelfTerm() throws ProofInputException { - Term selfTerm = getSelfTerm(); - return selfTerm != null ? formatTerm(selfTerm, getServices()) : null; - } + /** + * {@inheritDoc} + */ + @Override + public String getFormatedSelfTerm() throws ProofInputException { + Term selfTerm = getSelfTerm(); + return selfTerm != null ? formatTerm(selfTerm, getServices()) : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getFormatedContractParams() throws ProofInputException { - ImmutableList contractParams = getContractParams(); - if (contractParams != null && !contractParams.isEmpty()) { - StringBuffer sb = new StringBuffer(); - boolean afterFirst = false; - for (Term term : contractParams) { - if (afterFirst) { - sb.append(", "); + /** + * {@inheritDoc} + */ + @Override + public String getFormatedContractParams() throws ProofInputException { + ImmutableList contractParams = getContractParams(); + if (contractParams != null && !contractParams.isEmpty()) { + StringBuffer sb = new StringBuffer(); + boolean afterFirst = false; + for (Term term : contractParams) { + if (afterFirst) { + sb.append(", "); + } else { + afterFirst = true; + } + sb.append(formatTerm(term, getServices())); } - else { - afterFirst = true; + return sb.toString(); + } else { + return null; + } + } + + /** + * Searches the result {@link Term}. + * + * @param contract The {@link FunctionalOperationContract}. + * @param inst The {@link Instantiation}. + * @param services The {@link Services}. + * @return The found result {@link Term} or {@code null} otherwise. + */ + protected Term searchResultTerm(FunctionalOperationContract contract, Instantiation inst, + Services services) { + Term resultTerm = null; + if (contract.hasResultVar()) { + ProgramVariable resultVar = + extractResultVariableFromPostBranch(getProofNode(), services); + if (resultVar == null) { + // Result variable not found in child, create a temporary variable to use in + // specification + resultVar = UseOperationContractRule.computeResultVar(inst, services); } - sb.append(formatTerm(term, getServices())); - } - return sb.toString(); - } - else { - return null; - } - } - - /** - * Searches the result {@link Term}. - * @param contract The {@link FunctionalOperationContract}. - * @param inst The {@link Instantiation}. - * @param services The {@link Services}. - * @return The found result {@link Term} or {@code null} otherwise. - */ - protected Term searchResultTerm(FunctionalOperationContract contract, Instantiation inst, Services services) { - Term resultTerm = null; - if (contract.hasResultVar()) { - ProgramVariable resultVar = extractResultVariableFromPostBranch(getProofNode(), services); - if (resultVar == null) { - // Result variable not found in child, create a temporary variable to use in specification - resultVar = UseOperationContractRule.computeResultVar(inst, services); - } - resultTerm = services.getTermBuilder().var(resultVar); - } - return resultTerm; - } - - /** - * Extracts the result variable from the given post branch. - * @param node The {@link Node} which is the post or exceptional post branch of an applied {@link ContractRuleApp}. - * @param services The {@link Services} to use. - * @return The found {@link LocationVariable} or {@code null} if not found. - */ - protected static LocationVariable extractResultVariableFromPostBranch(Node node, Services services) { - Term postModality = SymbolicExecutionUtil.posInOccurrenceInOtherNode(node, node.getAppliedRuleApp().posInOccurrence(), node.child(0)); - postModality = TermBuilder.goBelowUpdates(postModality); - MethodFrame mf = JavaTools.getInnermostMethodFrame(postModality.javaBlock(), services); - SourceElement firstElement = NodeInfo.computeActiveStatement(mf.getFirstElement()); - if (!(firstElement instanceof CopyAssignment)) { - return null; - } - CopyAssignment assignment = (CopyAssignment)firstElement; - ProgramElement rightChild = assignment.getChildAt(1); - if (!(rightChild instanceof LocationVariable)) { - return null; - } - return (LocationVariable)rightChild; - } + resultTerm = services.getTermBuilder().var(resultVar); + } + return resultTerm; + } + + /** + * Extracts the result variable from the given post branch. + * + * @param node The {@link Node} which is the post or exceptional post branch of an applied + * {@link ContractRuleApp}. + * @param services The {@link Services} to use. + * @return The found {@link LocationVariable} or {@code null} if not found. + */ + protected static LocationVariable extractResultVariableFromPostBranch(Node node, + Services services) { + Term postModality = SymbolicExecutionUtil.posInOccurrenceInOtherNode(node, + node.getAppliedRuleApp().posInOccurrence(), node.child(0)); + postModality = TermBuilder.goBelowUpdates(postModality); + MethodFrame mf = JavaTools.getInnermostMethodFrame(postModality.javaBlock(), services); + SourceElement firstElement = NodeInfo.computeActiveStatement(mf.getFirstElement()); + if (!(firstElement instanceof CopyAssignment)) { + return null; + } + CopyAssignment assignment = (CopyAssignment) firstElement; + ProgramElement rightChild = assignment.getChildAt(1); + if (!(rightChild instanceof LocationVariable)) { + return null; + } + return (LocationVariable) rightChild; + } + + /** + * {@inheritDoc} + */ + @Override + public Contract getContract() { + return ((AbstractContractRuleApp) getProofNode().getAppliedRuleApp()).getInstantiation(); + } - /** - * {@inheritDoc} - */ - @Override - public Contract getContract() { - return ((AbstractContractRuleApp)getProofNode().getAppliedRuleApp()).getInstantiation(); - } + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getContractProgramMethod() { + Contract contract = getContract(); + if (contract instanceof OperationContract) { + return ((OperationContract) contract).getTarget(); + } else { + return null; + } + } - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getContractProgramMethod() { - Contract contract = getContract(); - if (contract instanceof OperationContract) { - return ((OperationContract)contract).getTarget(); - } - else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Operation Contract"; - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Operation Contract"; + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - public boolean isPreconditionComplied() { - boolean complied = false; - if (getProofNode().childrenCount() >= 3) { - complied = getProofNode().child(2).isClosed(); - } - return complied; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isPreconditionComplied() { + boolean complied = false; + if (getProofNode().childrenCount() >= 3) { + complied = getProofNode().child(2).isClosed(); + } + return complied; + } - /** - * {@inheritDoc} - */ - @Override - public boolean hasNotNullCheck() { - return getProofNode().childrenCount() >= 4; - } + /** + * {@inheritDoc} + */ + @Override + public boolean hasNotNullCheck() { + return getProofNode().childrenCount() >= 4; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isNotNullCheckComplied() { - if (hasNotNullCheck()) { - return getProofNode().child(3).isClosed(); - } - else { - return false; - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean isNotNullCheckComplied() { + if (hasNotNullCheck()) { + return getProofNode().child(3).isClosed(); + } else { + return false; + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStart.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStart.java index 301afd76cce..79aa467168c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStart.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStart.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import org.key_project.util.collection.ImmutableList; @@ -17,90 +20,96 @@ /** * The default implementation of {@link IExecutionStart}. + * * @author Martin Hentschel */ -public class ExecutionStart extends AbstractExecutionNode implements IExecutionStart { - /** - * The up to know discovered {@link IExecutionTermination}s. - */ - private ImmutableList terminations = ImmutableSLList.nil(); - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionStart(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionStart extends AbstractExecutionNode + implements IExecutionStart { + /** + * The up to know discovered {@link IExecutionTermination}s. + */ + private ImmutableList terminations = ImmutableSLList.nil(); - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return DEFAULT_START_NODE_NAME; - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionStart(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Start"; - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return DEFAULT_START_NODE_NAME; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTerminations() { - return terminations; - } - - /** - * Registers the given {@link IExecutionTermination}. - * @param termination The {@link IExecutionTermination} to register. - */ - public void addTermination(IExecutionTermination termination) { - if (termination != null) { - terminations = terminations.append(termination); - } - } + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } - /** - * {@inheritDoc} - */ - @Override - protected PosInOccurrence lazyComputeModalityPIO() { - return SymbolicExecutionUtil.findModalityWithMaxSymbolicExecutionLabelId(getProofNode().sequent()); - } + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Start"; + } - /** - * {@inheritDoc} - */ - @Override - public SourceElement getActiveStatement() { - Term modalityTerm = getModalityPIO().subTerm(); - SourceElement firstStatement = modalityTerm.javaBlock().program().getFirstElement(); - return NodeInfo.computeActiveStatement(firstStatement); - } - - /** - * Removes the given termination. - * @param termination The termination to be deleted. - * @author Anna Filighera - */ - public void removeTermination(IExecutionTermination termination) { - terminations = terminations.removeAll(termination); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTerminations() { + return terminations; + } + + /** + * Registers the given {@link IExecutionTermination}. + * + * @param termination The {@link IExecutionTermination} to register. + */ + public void addTermination(IExecutionTermination termination) { + if (termination != null) { + terminations = terminations.append(termination); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected PosInOccurrence lazyComputeModalityPIO() { + return SymbolicExecutionUtil + .findModalityWithMaxSymbolicExecutionLabelId(getProofNode().sequent()); + } + + /** + * {@inheritDoc} + */ + @Override + public SourceElement getActiveStatement() { + Term modalityTerm = getModalityPIO().subTerm(); + SourceElement firstStatement = modalityTerm.javaBlock().program().getFirstElement(); + return NodeInfo.computeActiveStatement(firstStatement); + } + + /** + * Removes the given termination. + * + * @param termination The termination to be deleted. + * @author Anna Filighera + */ + public void removeTermination(IExecutionTermination termination) { + terminations = terminations.removeAll(termination); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStatement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStatement.java index 54891e46130..78fdf0942ae 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStatement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.SourceElement; @@ -10,40 +13,43 @@ /** * The default implementation of {@link IExecutionStatement}. + * * @author Martin Hentschel */ -public class ExecutionStatement extends AbstractExecutionNode implements IExecutionStatement { - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - */ - public ExecutionStatement(ITreeSettings settings, - Node proofNode) { - super(settings, proofNode); - } +public class ExecutionStatement extends AbstractExecutionNode + implements IExecutionStatement { + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + */ + public ExecutionStatement(ITreeSettings settings, Node proofNode) { + super(settings, proofNode); + } - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - return getActiveStatement().toString(); - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + return getActiveStatement().toString(); + } - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - return "Statement"; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + return "Statement"; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionTermination.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionTermination.java index 5e58b2071e1..6f7711b4dd4 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionTermination.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionTermination.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.java.SourceElement; @@ -13,139 +16,159 @@ /** * The default implementation of {@link IExecutionTermination}. + * * @author Martin Hentschel */ -public class ExecutionTermination extends AbstractExecutionNode implements IExecutionTermination { - /** - * Contains the exception variable which is used to check if the executed program in proof terminates normally. - */ - private final IProgramVariable exceptionVariable; - - /** - * The {@link Sort} of the uncaught exception. - */ - private Sort exceptionSort; +public class ExecutionTermination extends AbstractExecutionNode + implements IExecutionTermination { + /** + * Contains the exception variable which is used to check if the executed program in proof + * terminates normally. + */ + private final IProgramVariable exceptionVariable; - /** - * The {@link TerminationKind}. - */ - private TerminationKind terminationKind; - - /** - * Constructor. - * @param settings The {@link ITreeSettings} to use. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param exceptionVariable Contains the exception variable which is used to check if the executed program in proof terminates normally. - * @param terminationKind The {@link TerminationKind} or {@code null} to compute it when it is requested the first time (normal or exceptional termination only). - */ - public ExecutionTermination(ITreeSettings settings, - Node proofNode, - IProgramVariable exceptionVariable, - TerminationKind terminationKind) { - super(settings, proofNode); - this.exceptionVariable = exceptionVariable; - this.terminationKind = terminationKind; - } + /** + * The {@link Sort} of the uncaught exception. + */ + private Sort exceptionSort; - /** - * {@inheritDoc} - */ - @Override - protected String lazyComputeName() { - switch (getTerminationKind()) { - case EXCEPTIONAL : return INTERNAL_NODE_NAME_START + "uncaught " + exceptionSort + INTERNAL_NODE_NAME_END; - case LOOP_BODY : return LOOP_BODY_TERMINATION_NODE_NAME; - case BLOCK_CONTRACT_NORMAL : return INTERNAL_NODE_NAME_START + "block contract end" + INTERNAL_NODE_NAME_END; - case BLOCK_CONTRACT_EXCEPTIONAL : return INTERNAL_NODE_NAME_START + "block contract uncaught " + exceptionSort + INTERNAL_NODE_NAME_END; - default : return NORMAL_TERMINATION_NODE_NAME; - } - } + /** + * The {@link TerminationKind}. + */ + private TerminationKind terminationKind; - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getExceptionVariable() { - return exceptionVariable; - } + /** + * Constructor. + * + * @param settings The {@link ITreeSettings} to use. + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param exceptionVariable Contains the exception variable which is used to check if the + * executed program in proof terminates normally. + * @param terminationKind The {@link TerminationKind} or {@code null} to compute it when it is + * requested the first time (normal or exceptional termination only). + */ + public ExecutionTermination(ITreeSettings settings, Node proofNode, + IProgramVariable exceptionVariable, TerminationKind terminationKind) { + super(settings, proofNode); + this.exceptionVariable = exceptionVariable; + this.terminationKind = terminationKind; + } - /** - * {@inheritDoc} - */ - @Override - public TerminationKind getTerminationKind() { - if (terminationKind == null) { - if (isBlockContractTermination()) { - terminationKind = isExceptionalTermination() ? TerminationKind.BLOCK_CONTRACT_EXCEPTIONAL : TerminationKind.BLOCK_CONTRACT_NORMAL; - } - else { - terminationKind = isExceptionalTermination() ? TerminationKind.EXCEPTIONAL : TerminationKind.NORMAL; - } - } - return terminationKind; - } - - /** - * Checks if a block contract terminates. - * @return {@code true} A block contract terminates, {@code false} normal execution terminates. - */ - protected boolean isBlockContractTermination() { - return SymbolicExecutionUtil.isBlockContractValidityBranch(getModalityPIO()); - } + /** + * {@inheritDoc} + */ + @Override + protected String lazyComputeName() { + switch (getTerminationKind()) { + case EXCEPTIONAL: + return INTERNAL_NODE_NAME_START + "uncaught " + exceptionSort + INTERNAL_NODE_NAME_END; + case LOOP_BODY: + return LOOP_BODY_TERMINATION_NODE_NAME; + case BLOCK_CONTRACT_NORMAL: + return INTERNAL_NODE_NAME_START + "block contract end" + INTERNAL_NODE_NAME_END; + case BLOCK_CONTRACT_EXCEPTIONAL: + return INTERNAL_NODE_NAME_START + "block contract uncaught " + exceptionSort + + INTERNAL_NODE_NAME_END; + default: + return NORMAL_TERMINATION_NODE_NAME; + } + } - /** - * Checks if is an exceptional termination. - * @return {@code true} exceptional termination, {@code false} normal termination. - */ - protected boolean isExceptionalTermination() { - Sort sort = getExceptionSort(); - return sort != null && !(sort instanceof NullSort); - } + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getExceptionVariable() { + return exceptionVariable; + } - /** - * {@inheritDoc} - */ - @Override - public Sort getExceptionSort() { - if (exceptionSort == null) { - exceptionSort = SymbolicExecutionUtil.lazyComputeExceptionSort(getProofNode(), exceptionVariable); - } - return exceptionSort; - } - - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] lazyComputeConstraints() { - return SymbolicExecutionUtil.createExecutionConstraints(this); - } - - /** - * {@inheritDoc} - */ - @Override - public String getElementType() { - switch (getTerminationKind()) { - case EXCEPTIONAL : return "Exceptional Termination"; - case LOOP_BODY : return "Loop Body Termination"; - case BLOCK_CONTRACT_NORMAL : return "Block Contract Termination"; - case BLOCK_CONTRACT_EXCEPTIONAL : return "Block Contract Exceptional Termination"; - default : return "Termination"; - } - } + /** + * {@inheritDoc} + */ + @Override + public TerminationKind getTerminationKind() { + if (terminationKind == null) { + if (isBlockContractTermination()) { + terminationKind = + isExceptionalTermination() ? TerminationKind.BLOCK_CONTRACT_EXCEPTIONAL + : TerminationKind.BLOCK_CONTRACT_NORMAL; + } else { + terminationKind = isExceptionalTermination() ? TerminationKind.EXCEPTIONAL + : TerminationKind.NORMAL; + } + } + return terminationKind; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isBranchVerified() { - if (TerminationKind.BLOCK_CONTRACT_NORMAL.equals(terminationKind) || - TerminationKind.BLOCK_CONTRACT_EXCEPTIONAL.equals(terminationKind)) { - return SymbolicExecutionUtil.lazyComputeIsAdditionalBranchVerified(getProofNode()); - } - else { - return SymbolicExecutionUtil.lazyComputeIsMainBranchVerified(getProofNode()); - } - } -} \ No newline at end of file + /** + * Checks if a block contract terminates. + * + * @return {@code true} A block contract terminates, {@code false} normal execution terminates. + */ + protected boolean isBlockContractTermination() { + return SymbolicExecutionUtil.isBlockContractValidityBranch(getModalityPIO()); + } + + /** + * Checks if is an exceptional termination. + * + * @return {@code true} exceptional termination, {@code false} normal termination. + */ + protected boolean isExceptionalTermination() { + Sort sort = getExceptionSort(); + return sort != null && !(sort instanceof NullSort); + } + + /** + * {@inheritDoc} + */ + @Override + public Sort getExceptionSort() { + if (exceptionSort == null) { + exceptionSort = SymbolicExecutionUtil.lazyComputeExceptionSort(getProofNode(), + exceptionVariable); + } + return exceptionSort; + } + + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] lazyComputeConstraints() { + return SymbolicExecutionUtil.createExecutionConstraints(this); + } + + /** + * {@inheritDoc} + */ + @Override + public String getElementType() { + switch (getTerminationKind()) { + case EXCEPTIONAL: + return "Exceptional Termination"; + case LOOP_BODY: + return "Loop Body Termination"; + case BLOCK_CONTRACT_NORMAL: + return "Block Contract Termination"; + case BLOCK_CONTRACT_EXCEPTIONAL: + return "Block Contract Exceptional Termination"; + default: + return "Termination"; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBranchVerified() { + if (TerminationKind.BLOCK_CONTRACT_NORMAL.equals(terminationKind) + || TerminationKind.BLOCK_CONTRACT_EXCEPTIONAL.equals(terminationKind)) { + return SymbolicExecutionUtil.lazyComputeIsAdditionalBranchVerified(getProofNode()); + } else { + return SymbolicExecutionUtil.lazyComputeIsMainBranchVerified(getProofNode()); + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionValue.java index 4384c283bca..c876edf782b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.LinkedList; @@ -27,190 +30,223 @@ /** * The default implementation of {@link IExecutionValue}. + * * @author Martin Hentschel */ public class ExecutionValue extends AbstractExecutionValue { - /** - * Is the value unknown? - */ - private final boolean valueUnknown; - - /** - * The value as human readable {@link String}. - */ - private final String valueString; - - /** - * The type of the value. - */ - private final String typeString; - - /** - * The condition under which the variable has this value as human readable {@link String}. - */ - private final String conditionString; - - /** - * The child {@link IExecutionVariable}s. - */ - private IExecutionVariable[] childVariables; - - /** - * Constructor. - * @param proofNode The {@link Node} of KeY's proof tree which is represented by this {@link IExecutionNode}. - * @param variable The parent {@link ExecutionVariable} which contains this value. - * @param valueProofNode The {@link Node} in the value site proof from which this value was extracted. - * @param valueUnknown Is the value unknown? - * @param value The value. - * @param valueString The value as human readable string. - * @param typeString The type of the value. - */ - public ExecutionValue(Node proofNode, - ExecutionVariable variable, - boolean valueUnknown, - Term value, - String valueString, - String typeString, - Term condition, - String conditionString) { - super(variable.getSettings(), proofNode, variable, condition, value); - this.valueUnknown = valueUnknown; - this.valueString = valueString; - this.typeString = typeString; - this.conditionString = conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isValueUnknown() throws ProofInputException { - return valueUnknown; - } - - /** - * {@inheritDoc} - */ - @Override - public String getValueString() throws ProofInputException { - return valueString; - } - - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() throws ProofInputException { - return typeString; - } - - /** - * {@inheritDoc} - */ - @Override - public IExecutionVariable[] getChildVariables() throws ProofInputException { - synchronized (this) { - if (childVariables== null) { - childVariables = lazyComputeChildVariables(); - } - return childVariables; - } - } - - /** - * Computes the contained child variables lazily when {@link #getChildVariables()} is called the first time. - * @return The contained child {@link IExecutionVariable}s. - * @throws ProofInputException Occurred Exception. - */ - protected IExecutionVariable[] lazyComputeChildVariables() throws ProofInputException { - List children = new LinkedList(); - if (!isDisposed()) { - final Services services = getServices(); - Term value = getValue(); - if (value != null && !isValueUnknown()) { // Don't show children of unknown values - Sort valueSort = value.sort(); - if (valueSort != services.getJavaInfo().getNullType().getSort()) { - KeYJavaType keyType = services.getJavaInfo().getKeYJavaType(valueSort); - if (keyType != null) { // Can be null, e.g. if Sort is the Sort of Heap - Type javaType = keyType.getJavaType(); - if (javaType instanceof ArrayDeclaration) { - // Array value - ArrayDeclaration ad = (ArrayDeclaration)javaType; - Set pvs = SymbolicExecutionUtil.getProgramVariables(ad.length()); - if (pvs.size() == 1) { - ExecutionVariable lengthVariable = new ExecutionVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, pvs.iterator().next(), getVariable().getAdditionalCondition()); - children.add(lengthVariable); - ExecutionValue[] lengthValues = lengthVariable.getValues(); - if (!ArrayUtil.isEmpty(lengthValues)) { - for (ExecutionValue lengthValue : lengthValues) { - try { - int length = getSettings().isUsePrettyPrinting() ? - Integer.valueOf(lengthValue.getValueString()) : - Integer.valueOf(SymbolicExecutionUtil.formatTerm(lengthValue.getValue(), services, false, true)); - for (int i = 0; i < length; i++) { - Term indexTerm = services.getTermBuilder().zTerm(i); - ExecutionVariable childI = new ExecutionVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, indexTerm, lengthValue, getVariable().getAdditionalCondition()); - children.add(childI); - } - } - catch (NumberFormatException e) { - ExecutionAllArrayIndicesVariable arrayStarVariable = new ExecutionAllArrayIndicesVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, (IProgramVariable) value.op(), getVariable().getAdditionalCondition()); - children.add(arrayStarVariable); - } - } - } - else { - // Should never happen, just backup - ExecutionAllArrayIndicesVariable arrayStarVariable = new ExecutionAllArrayIndicesVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, (IProgramVariable) value.op(), getVariable().getAdditionalCondition()); - children.add(arrayStarVariable); - } - } - else { - // Should never happen, just backup - ExecutionAllArrayIndicesVariable arrayStarVariable = new ExecutionAllArrayIndicesVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, (IProgramVariable) value.op(), getVariable().getAdditionalCondition()); - children.add(arrayStarVariable); - } - } - else if (javaType instanceof ClassType) { - // Normal value - ImmutableList fields = ((ClassType)javaType).getAllFields(services); - for (Field field : fields) { - ImmutableList vars = services.getJavaInfo().getAllAttributes(field.getFullName(), keyType); - for (ProgramVariable var : vars) { - if (!var.isImplicit() && !var.isStatic()) { - children.add(new ExecutionVariable(getVariable().getParentNode(), getVariable().getProofNode(), getVariable().getModalityPIO(), this, field.getProgramVariable(), getVariable().getAdditionalCondition())); - } + /** + * Is the value unknown? + */ + private final boolean valueUnknown; + + /** + * The value as human readable {@link String}. + */ + private final String valueString; + + /** + * The type of the value. + */ + private final String typeString; + + /** + * The condition under which the variable has this value as human readable {@link String}. + */ + private final String conditionString; + + /** + * The child {@link IExecutionVariable}s. + */ + private IExecutionVariable[] childVariables; + + /** + * Constructor. + * + * @param proofNode The {@link Node} of KeY's proof tree which is represented by this + * {@link IExecutionNode}. + * @param variable The parent {@link ExecutionVariable} which contains this value. + * @param valueProofNode The {@link Node} in the value site proof from which this value was + * extracted. + * @param valueUnknown Is the value unknown? + * @param value The value. + * @param valueString The value as human readable string. + * @param typeString The type of the value. + */ + public ExecutionValue(Node proofNode, ExecutionVariable variable, boolean valueUnknown, + Term value, String valueString, String typeString, Term condition, + String conditionString) { + super(variable.getSettings(), proofNode, variable, condition, value); + this.valueUnknown = valueUnknown; + this.valueString = valueString; + this.typeString = typeString; + this.conditionString = conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValueUnknown() throws ProofInputException { + return valueUnknown; + } + + /** + * {@inheritDoc} + */ + @Override + public String getValueString() throws ProofInputException { + return valueString; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() throws ProofInputException { + return typeString; + } + + /** + * {@inheritDoc} + */ + @Override + public IExecutionVariable[] getChildVariables() throws ProofInputException { + synchronized (this) { + if (childVariables == null) { + childVariables = lazyComputeChildVariables(); + } + return childVariables; + } + } + + /** + * Computes the contained child variables lazily when {@link #getChildVariables()} is called the + * first time. + * + * @return The contained child {@link IExecutionVariable}s. + * @throws ProofInputException Occurred Exception. + */ + protected IExecutionVariable[] lazyComputeChildVariables() throws ProofInputException { + List children = new LinkedList(); + if (!isDisposed()) { + final Services services = getServices(); + Term value = getValue(); + if (value != null && !isValueUnknown()) { // Don't show children of unknown values + Sort valueSort = value.sort(); + if (valueSort != services.getJavaInfo().getNullType().getSort()) { + KeYJavaType keyType = services.getJavaInfo().getKeYJavaType(valueSort); + if (keyType != null) { // Can be null, e.g. if Sort is the Sort of Heap + Type javaType = keyType.getJavaType(); + if (javaType instanceof ArrayDeclaration) { + // Array value + ArrayDeclaration ad = (ArrayDeclaration) javaType; + Set pvs = + SymbolicExecutionUtil.getProgramVariables(ad.length()); + if (pvs.size() == 1) { + ExecutionVariable lengthVariable = new ExecutionVariable( + getVariable().getParentNode(), getVariable().getProofNode(), + getVariable().getModalityPIO(), this, pvs.iterator().next(), + getVariable().getAdditionalCondition()); + children.add(lengthVariable); + ExecutionValue[] lengthValues = lengthVariable.getValues(); + if (!ArrayUtil.isEmpty(lengthValues)) { + for (ExecutionValue lengthValue : lengthValues) { + try { + int length = getSettings().isUsePrettyPrinting() + ? Integer.valueOf(lengthValue.getValueString()) + : Integer.valueOf(SymbolicExecutionUtil + .formatTerm(lengthValue.getValue(), + services, false, true)); + for (int i = 0; i < length; i++) { + Term indexTerm = services.getTermBuilder().zTerm(i); + ExecutionVariable childI = new ExecutionVariable( + getVariable().getParentNode(), + getVariable().getProofNode(), + getVariable().getModalityPIO(), this, + indexTerm, lengthValue, + getVariable().getAdditionalCondition()); + children.add(childI); + } + } catch (NumberFormatException e) { + ExecutionAllArrayIndicesVariable arrayStarVariable = + new ExecutionAllArrayIndicesVariable( + getVariable().getParentNode(), + getVariable().getProofNode(), + getVariable().getModalityPIO(), this, + (IProgramVariable) value.op(), + getVariable().getAdditionalCondition()); + children.add(arrayStarVariable); + } + } + } else { + // Should never happen, just backup + ExecutionAllArrayIndicesVariable arrayStarVariable = + new ExecutionAllArrayIndicesVariable( + getVariable().getParentNode(), + getVariable().getProofNode(), + getVariable().getModalityPIO(), this, + (IProgramVariable) value.op(), + getVariable().getAdditionalCondition()); + children.add(arrayStarVariable); + } + } else { + // Should never happen, just backup + ExecutionAllArrayIndicesVariable arrayStarVariable = + new ExecutionAllArrayIndicesVariable( + getVariable().getParentNode(), + getVariable().getProofNode(), + getVariable().getModalityPIO(), this, + (IProgramVariable) value.op(), + getVariable().getAdditionalCondition()); + children.add(arrayStarVariable); + } + } else if (javaType instanceof ClassType) { + // Normal value + ImmutableList fields = + ((ClassType) javaType).getAllFields(services); + for (Field field : fields) { + ImmutableList vars = services.getJavaInfo() + .getAllAttributes(field.getFullName(), keyType); + for (ProgramVariable var : vars) { + if (!var.isImplicit() && !var.isStatic()) { + children.add( + new ExecutionVariable(getVariable().getParentNode(), + getVariable().getProofNode(), + getVariable().getModalityPIO(), this, + field.getProgramVariable(), + getVariable().getAdditionalCondition())); + } + } + } } - } - } - } + } + } } - } - } - return children.toArray(new IExecutionVariable[children.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() throws ProofInputException { - return conditionString; - } - - /** - * {@inheritDoc} - */ - @Override - public ExecutionVariable getVariable() { - return (ExecutionVariable)super.getVariable(); - } - - /** - * {@inheritDoc} - */ - @Override - protected IExecutionConstraint[] getNodeConstraints() { - return getVariable().getParentNode().getConstraints(); - } -} \ No newline at end of file + } + return children.toArray(new IExecutionVariable[children.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() throws ProofInputException { + return conditionString; + } + + /** + * {@inheritDoc} + */ + @Override + public ExecutionVariable getVariable() { + return (ExecutionVariable) super.getVariable(); + } + + /** + * {@inheritDoc} + */ + @Override + protected IExecutionConstraint[] getNodeConstraints() { + return getVariable().getParentNode().getConstraints(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionVariable.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionVariable.java index db112205170..17bb2b4574e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionVariable.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/ExecutionVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import java.util.ArrayList; @@ -33,346 +36,336 @@ /** * The default implementation of {@link IExecutionVariable}. + * * @author Martin Hentschel */ public class ExecutionVariable extends AbstractExecutionVariable { - /** - * The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - */ - private final IExecutionNode parentNode; - - /** - * The {@link ExecutionValue} from which the array length was computed. - */ - private final ExecutionValue lengthValue; + /** + * The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. + */ + private final IExecutionNode parentNode; - /** - * The possible values of this {@link IExecutionValue}. - */ - private ExecutionValue[] values; + /** + * The {@link ExecutionValue} from which the array length was computed. + */ + private final ExecutionValue lengthValue; - /** - * Constructor for a "normal" value. - * @param parentNode The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - * @param programVariable The represented {@link IProgramVariable} which value is shown. - * @param additionalCondition An optional additional condition to consider. - */ - public ExecutionVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - IProgramVariable programVariable, - Term additionalCondition) { - this(parentNode, proofNode, modalityPIO, null, programVariable, additionalCondition); - } - - /** - * Constructor for a "normal" child value. - * @param settings The {@link ITreeSettings} to use. - * @param parentNode The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - * @param parentValue The parent {@link ExecutionValue} or {@code null} if not available. - * @param programVariable The represented {@link IProgramVariable} which value is shown. - * @param additionalCondition An optional additional condition to consider. - */ - public ExecutionVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - ExecutionValue parentValue, - IProgramVariable programVariable, - Term additionalCondition) { - super(parentNode.getSettings(), - proofNode, - programVariable, - parentValue, - null, - additionalCondition, - modalityPIO); - assert programVariable != null; - assert modalityPIO != null; - this.parentNode = parentNode; - this.lengthValue = null; - } + /** + * The possible values of this {@link IExecutionValue}. + */ + private ExecutionValue[] values; - /** - * Constructor for an array cell value. - * @param parentNode The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - * @param parentValue The parent {@link ExecutionValue} or {@code null} if not available. - * @param arrayIndex The index in the parent array. - * @param lengthValue The {@link ExecutionValue} from which the array length was computed. - * @param additionalCondition An optional additional condition to consider. - */ - public ExecutionVariable(IExecutionNode parentNode, - Node proofNode, - PosInOccurrence modalityPIO, - ExecutionValue parentValue, - Term arrayIndex, - ExecutionValue lengthValue, - Term additionalCondition) { - super(parentNode.getSettings(), - proofNode, - null, - parentValue, - arrayIndex, - additionalCondition, - modalityPIO); - assert modalityPIO != null; - this.parentNode = parentNode; - this.lengthValue = lengthValue; - } + /** + * Constructor for a "normal" value. + * + * @param parentNode The parent {@link IExecutionNode} which provides this + * {@link ExecutionVariable}. + * @param programVariable The represented {@link IProgramVariable} which value is shown. + * @param additionalCondition An optional additional condition to consider. + */ + public ExecutionVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, IProgramVariable programVariable, + Term additionalCondition) { + this(parentNode, proofNode, modalityPIO, null, programVariable, additionalCondition); + } - /** - * {@inheritDoc} - */ - @Override - public ExecutionValue[] getValues() throws ProofInputException { - synchronized (this) { - if (values == null) { - values = lazyComputeValues(); - } - return values; - } - } - - /** - * Computes the value for {@link #getValues()} - * lazily when the method is called the first time. - * @throws ProofInputException Occurred Exception. - */ - protected ExecutionValue[] lazyComputeValues() throws ProofInputException { - InitConfig initConfig = getInitConfig(); - if (initConfig != null) { // Otherwise proof is disposed. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - final Services services = sideProofEnv.getServicesForEnvironment(); - final TermBuilder tb = services.getTermBuilder(); - // Start site proof to extract the value of the result variable. - SiteProofVariableValueInput sequentToProve; - Term siteProofSelectTerm = null; - Term siteProofCondition; - if (getAdditionalCondition() != null) { - siteProofCondition = getAdditionalCondition(); - } - else { - siteProofCondition = tb.tt(); - } - if (getParentValue() != null || SymbolicExecutionUtil.isStaticVariable(getProgramVariable())) { - siteProofSelectTerm = createSelectTerm(); - if (getParentValue() != null) { // Is null at static variables - siteProofCondition = tb.and(siteProofCondition, getParentValue().getCondition()); + /** + * Constructor for a "normal" child value. + * + * @param settings The {@link ITreeSettings} to use. + * @param parentNode The parent {@link IExecutionNode} which provides this + * {@link ExecutionVariable}. + * @param parentValue The parent {@link ExecutionValue} or {@code null} if not available. + * @param programVariable The represented {@link IProgramVariable} which value is shown. + * @param additionalCondition An optional additional condition to consider. + */ + public ExecutionVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, ExecutionValue parentValue, + IProgramVariable programVariable, Term additionalCondition) { + super(parentNode.getSettings(), proofNode, programVariable, parentValue, null, + additionalCondition, modalityPIO); + assert programVariable != null; + assert modalityPIO != null; + this.parentNode = parentNode; + this.lengthValue = null; + } + + /** + * Constructor for an array cell value. + * + * @param parentNode The parent {@link IExecutionNode} which provides this + * {@link ExecutionVariable}. + * @param parentValue The parent {@link ExecutionValue} or {@code null} if not available. + * @param arrayIndex The index in the parent array. + * @param lengthValue The {@link ExecutionValue} from which the array length was computed. + * @param additionalCondition An optional additional condition to consider. + */ + public ExecutionVariable(IExecutionNode parentNode, Node proofNode, + PosInOccurrence modalityPIO, ExecutionValue parentValue, Term arrayIndex, + ExecutionValue lengthValue, Term additionalCondition) { + super(parentNode.getSettings(), proofNode, null, parentValue, arrayIndex, + additionalCondition, modalityPIO); + assert modalityPIO != null; + this.parentNode = parentNode; + this.lengthValue = lengthValue; + } + + /** + * {@inheritDoc} + */ + @Override + public ExecutionValue[] getValues() throws ProofInputException { + synchronized (this) { + if (values == null) { + values = lazyComputeValues(); + } + return values; + } + } + + /** + * Computes the value for {@link #getValues()} lazily when the method is called the first time. + * + * @throws ProofInputException Occurred Exception. + */ + protected ExecutionValue[] lazyComputeValues() throws ProofInputException { + InitConfig initConfig = getInitConfig(); + if (initConfig != null) { // Otherwise proof is disposed. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New + // OneStepSimplifier + // is required + // because it + // has an + // internal + // state and + // the default + // instance + // can't be + // used + // parallel. + final Services services = sideProofEnv.getServicesForEnvironment(); + final TermBuilder tb = services.getTermBuilder(); + // Start site proof to extract the value of the result variable. + SiteProofVariableValueInput sequentToProve; + Term siteProofSelectTerm = null; + Term siteProofCondition; + if (getAdditionalCondition() != null) { + siteProofCondition = getAdditionalCondition(); + } else { + siteProofCondition = tb.tt(); + } + if (getParentValue() != null + || SymbolicExecutionUtil.isStaticVariable(getProgramVariable())) { + siteProofSelectTerm = createSelectTerm(); + if (getParentValue() != null) { // Is null at static variables + siteProofCondition = + tb.and(siteProofCondition, getParentValue().getCondition()); + } + if (lengthValue != null) { + siteProofCondition = tb.and(siteProofCondition, lengthValue.getCondition()); + } + sequentToProve = + SymbolicExecutionUtil.createExtractTermSequent(services, getProofNode(), + getModalityPIO(), siteProofCondition, siteProofSelectTerm, true); + } else { + sequentToProve = SymbolicExecutionUtil.createExtractVariableValueSequent(services, + getProofNode(), getModalityPIO(), siteProofCondition, getProgramVariable()); } - if (lengthValue != null) { - siteProofCondition = tb.and(siteProofCondition, lengthValue.getCondition()); + ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), + sideProofEnv, sequentToProve.getSequentToProve(), + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_DELAYED); + try { + return instantiateValuesFromSideProof(initConfig, services, tb, info, + sequentToProve.getOperator(), siteProofSelectTerm, siteProofCondition); + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "Value computation on node " + getProofNode().serialNr(), info); } - sequentToProve = SymbolicExecutionUtil.createExtractTermSequent(services, getProofNode(), getModalityPIO(), siteProofCondition, siteProofSelectTerm, true); - } - else { - sequentToProve = SymbolicExecutionUtil.createExtractVariableValueSequent(services, getProofNode(), getModalityPIO(), siteProofCondition, getProgramVariable()); - } - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(getProof(), - sideProofEnv, - sequentToProve.getSequentToProve(), - StrategyProperties.METHOD_NONE, - StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, - StrategyProperties.SPLITTING_DELAYED); - try { - return instantiateValuesFromSideProof(initConfig, - services, - tb, - info, - sequentToProve.getOperator(), - siteProofSelectTerm, - siteProofCondition); - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Value computation on node " + getProofNode().serialNr(), info); - } - } - else { - return null; - } - } - - /** - * Analyzes the side proof defined by the {@link ApplyStrategyInfo} - * and creates {@link ExecutionValue}s from it. - * @param initConfig The {@link InitConfig} of the side proof. - * @param services The {@link Services} of the side proof. - * @param tb The {@link TermBuilder} of the side proof. - * @param info The side proof. - * @param resultOperator The {@link Operator} of the result predicate. - * @param siteProofSelectTerm The queried value. - * @param siteProofCondition The condition under which the value is queried. - * @return The created {@link ExecutionValue} instances. - * @throws ProofInputException Occurred Exception. - */ - protected ExecutionValue[] instantiateValuesFromSideProof(InitConfig initConfig, - Services services, - TermBuilder tb, - ApplyStrategyInfo info, - Operator resultOperator, - Term siteProofSelectTerm, - Term siteProofCondition) throws ProofInputException { - List result = new ArrayList(info.getProof().openGoals().size()); - // Group values of the branches - Map> valueMap = new LinkedHashMap>(); - List unknownValues = new LinkedList(); - groupGoalsByValue(info.getProof().openGoals(), resultOperator, siteProofSelectTerm, siteProofCondition, valueMap, unknownValues, services); - // Instantiate child values - for (Entry> valueEntry : valueMap.entrySet()) { - Term value = valueEntry.getKey(); - if (isValidValue(value)) { - // Format return vale - String valueString = formatTerm(value, services); - // Determine type - String typeString = value.sort().toString(); + } else { + return null; + } + } + + /** + * Analyzes the side proof defined by the {@link ApplyStrategyInfo} and creates + * {@link ExecutionValue}s from it. + * + * @param initConfig The {@link InitConfig} of the side proof. + * @param services The {@link Services} of the side proof. + * @param tb The {@link TermBuilder} of the side proof. + * @param info The side proof. + * @param resultOperator The {@link Operator} of the result predicate. + * @param siteProofSelectTerm The queried value. + * @param siteProofCondition The condition under which the value is queried. + * @return The created {@link ExecutionValue} instances. + * @throws ProofInputException Occurred Exception. + */ + protected ExecutionValue[] instantiateValuesFromSideProof(InitConfig initConfig, + Services services, TermBuilder tb, ApplyStrategyInfo info, Operator resultOperator, + Term siteProofSelectTerm, Term siteProofCondition) throws ProofInputException { + List result = + new ArrayList(info.getProof().openGoals().size()); + // Group values of the branches + Map> valueMap = new LinkedHashMap>(); + List unknownValues = new LinkedList(); + groupGoalsByValue(info.getProof().openGoals(), resultOperator, siteProofSelectTerm, + siteProofCondition, valueMap, unknownValues, services); + // Instantiate child values + for (Entry> valueEntry : valueMap.entrySet()) { + Term value = valueEntry.getKey(); + if (isValidValue(value)) { + // Format return vale + String valueString = formatTerm(value, services); + // Determine type + String typeString = value.sort().toString(); + // Compute value condition + Term condition = computeValueCondition(tb, valueEntry.getValue(), initConfig); + String conditionString = null; + if (condition != null) { + conditionString = formatTerm(condition, services); + } + // Update result + result.add(new ExecutionValue(getProofNode(), this, false, value, valueString, + typeString, condition, conditionString)); + } + } + // Instantiate unknown child values + if (!unknownValues.isEmpty()) { // Compute value condition - Term condition = computeValueCondition(tb, valueEntry.getValue(), initConfig); + Term condition = computeValueCondition(tb, unknownValues, initConfig); String conditionString = null; if (condition != null) { - conditionString = formatTerm(condition, services); + conditionString = formatTerm(condition, services); } // Update result - result.add(new ExecutionValue(getProofNode(), - this, - false, - value, - valueString, - typeString, - condition, - conditionString)); - } - } - // Instantiate unknown child values - if (!unknownValues.isEmpty()) { - // Compute value condition - Term condition = computeValueCondition(tb, unknownValues, initConfig); - String conditionString = null; - if (condition != null) { - conditionString = formatTerm(condition, services); - } - // Update result - result.add(new ExecutionValue(getProofNode(), - this, - true, - null, - null, - null, - condition, - conditionString)); - } - // Return child values as result - return result.toArray(new ExecutionValue[result.size()]); - } + result.add(new ExecutionValue(getProofNode(), this, true, null, null, null, condition, + conditionString)); + } + // Return child values as result + return result.toArray(new ExecutionValue[result.size()]); + } - /** - * Checks if the given {@link Term} represents a valid value. - * @param value The value to check. - * @return {@code true} valid value, {@code false} invalid value to be ignored. - */ - protected boolean isValidValue(Term value) { - return true; - } + /** + * Checks if the given {@link Term} represents a valid value. + * + * @param value The value to check. + * @return {@code true} valid value, {@code false} invalid value to be ignored. + */ + protected boolean isValidValue(Term value) { + return true; + } - /** - * Groups all {@link Goal}s which provides the same value. - * @param goals All available {@link Goal}s to group. - * @param operator The {@link Operator} of the {@link Term} which provides the value. - * @param services The {@link Services} to use. - */ - protected void groupGoalsByValue(ImmutableList goals, - Operator operator, - Term siteProofSelectTerm, - Term siteProofCondition, - Map> valueMap, - List unknownValues, - Services services) throws ProofInputException { - for (Goal goal : goals) { - // Extract value - Term value = SymbolicExecutionSideProofUtil.extractOperatorValue(goal, operator); - assert value != null; - value = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), value, services); - // Compute unknown flag if required - boolean unknownValue = false; - if (siteProofSelectTerm != null) { - if (SymbolicExecutionUtil.isNullSort(value.sort(), services)) { - unknownValue = SymbolicExecutionUtil.isNull(getProofNode(), siteProofCondition, siteProofSelectTerm); // Check if the symbolic value is not null, if it fails the value is treated as unknown + /** + * Groups all {@link Goal}s which provides the same value. + * + * @param goals All available {@link Goal}s to group. + * @param operator The {@link Operator} of the {@link Term} which provides the value. + * @param services The {@link Services} to use. + */ + protected void groupGoalsByValue(ImmutableList goals, Operator operator, + Term siteProofSelectTerm, Term siteProofCondition, Map> valueMap, + List unknownValues, Services services) throws ProofInputException { + for (Goal goal : goals) { + // Extract value + Term value = SymbolicExecutionSideProofUtil.extractOperatorValue(goal, operator); + assert value != null; + value = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), value, services); + // Compute unknown flag if required + boolean unknownValue = false; + if (siteProofSelectTerm != null) { + if (SymbolicExecutionUtil.isNullSort(value.sort(), services)) { + unknownValue = SymbolicExecutionUtil.isNull(getProofNode(), siteProofCondition, + siteProofSelectTerm); // Check if the symbolic value is not null, if it + // fails the value is treated as unknown + } else { + unknownValue = SymbolicExecutionUtil.isNotNull(getProofNode(), + siteProofCondition, siteProofSelectTerm); // Check if the symbolic value + // is not null, if it fails + // the value is treated as + // unknown + } } - else { - unknownValue = SymbolicExecutionUtil.isNotNull(getProofNode(), siteProofCondition, siteProofSelectTerm); // Check if the symbolic value is not null, if it fails the value is treated as unknown + // Add to result list + if (unknownValue) { + unknownValues.add(goal); + } else { + List valueList = valueMap.get(value); + if (valueList == null) { + valueList = new LinkedList(); + valueMap.put(value, valueList); + } + valueList.add(goal); } - } - // Add to result list - if (unknownValue) { - unknownValues.add(goal); - } - else { - List valueList = valueMap.get(value); - if (valueList == null) { - valueList = new LinkedList(); - valueMap.put(value, valueList); + } + } + + /** + * Computes the combined path condition of all {@link Goal}s which is the or combination of each + * path condition per {@link Goal}. + * + * @param tb The {@link TermBuilder} to use passed to ensure that it is still available even if + * the {@link Proof} is disposed in between. + * @param valueGoals The {@link Goal}s to compute combined path condition for. + * @param initConfig The {@link InitConfig} to use. + * @return The combined path condition. + * @throws ProofInputException Occurred Exception. + */ + protected Term computeValueCondition(TermBuilder tb, List valueGoals, + InitConfig initConfig) throws ProofInputException { + if (!valueGoals.isEmpty()) { + List pathConditions = new LinkedList(); + Proof proof = null; + for (Goal valueGoal : valueGoals) { + pathConditions.add(SymbolicExecutionUtil.computePathCondition(valueGoal.node(), + getSettings().isSimplifyConditions(), false)); + proof = valueGoal.node().proof(); } - valueList.add(goal); - } - } - } - - /** - * Computes the combined path condition of all {@link Goal}s which is the - * or combination of each path condition per {@link Goal}. - * @param tb The {@link TermBuilder} to use passed to ensure that it is still available even if the {@link Proof} is disposed in between. - * @param valueGoals The {@link Goal}s to compute combined path condition for. - * @param initConfig The {@link InitConfig} to use. - * @return The combined path condition. - * @throws ProofInputException Occurred Exception. - */ - protected Term computeValueCondition(TermBuilder tb, List valueGoals, InitConfig initConfig) throws ProofInputException { - if (!valueGoals.isEmpty()) { - List pathConditions = new LinkedList(); - Proof proof = null; - for (Goal valueGoal : valueGoals) { - pathConditions.add(SymbolicExecutionUtil.computePathCondition(valueGoal.node(), getSettings().isSimplifyConditions(), false)); - proof = valueGoal.node().proof(); - } - Term comboundPathCondition = tb.or(pathConditions); - if (getSettings().isSimplifyConditions()) { - comboundPathCondition = SymbolicExecutionUtil.simplify(initConfig, proof, comboundPathCondition); - } - comboundPathCondition = SymbolicExecutionUtil.improveReadability(comboundPathCondition, initConfig.getServices()); - return comboundPathCondition; - } - else { - return tb.tt(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Term createSelectTerm() { - return SymbolicExecutionUtil.createSelectTerm(this); - } + Term comboundPathCondition = tb.or(pathConditions); + if (getSettings().isSimplifyConditions()) { + comboundPathCondition = + SymbolicExecutionUtil.simplify(initConfig, proof, comboundPathCondition); + } + comboundPathCondition = SymbolicExecutionUtil.improveReadability(comboundPathCondition, + initConfig.getServices()); + return comboundPathCondition; + } else { + return tb.tt(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Term createSelectTerm() { + return SymbolicExecutionUtil.createSelectTerm(this); + } - /** - * {@inheritDoc} - */ - @Override - public ExecutionValue getParentValue() { - return (ExecutionValue)super.getParentValue(); - } + /** + * {@inheritDoc} + */ + @Override + public ExecutionValue getParentValue() { + return (ExecutionValue) super.getParentValue(); + } - /** - * Returns the parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - * @return The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. - */ - public IExecutionNode getParentNode() { - return parentNode; - } + /** + * Returns the parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. + * + * @return The parent {@link IExecutionNode} which provides this {@link ExecutionVariable}. + */ + public IExecutionNode getParentNode() { + return parentNode; + } - /** - * Returns the {@link ExecutionValue} from which the array length was computed. - * @return The {@link ExecutionValue} from which the array length was computed. - */ - public ExecutionValue getLengthValue() { - return lengthValue; - } -} \ No newline at end of file + /** + * Returns the {@link ExecutionValue} from which the array length was computed. + * + * @return The {@link ExecutionValue} from which the array length was computed. + */ + public ExecutionValue getLengthValue() { + return lengthValue; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/TreeSettings.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/TreeSettings.java index fecba73199e..febf1ebc604 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/TreeSettings.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/model/impl/TreeSettings.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.model.impl; import de.uka.ilkd.key.symbolic_execution.model.IExecutionVariable; @@ -5,92 +8,102 @@ /** * The default implementation of {@link ITreeSettings}. + * * @author Martin Hentschel */ public class TreeSettings implements ITreeSettings { - /** - * {@code true} merge branch conditions which means that a branch condition never contains another branch condition - * or {@code false} allow that branch conditions contains branch conditions. - */ - private final boolean mergeBranchConditions; + /** + * {@code true} merge branch conditions which means that a branch condition never contains + * another branch condition or {@code false} allow that branch conditions contains branch + * conditions. + */ + private final boolean mergeBranchConditions; - /** - * {@code true} use unicode characters, {@code false} do not use unicode characters. - */ - private final boolean useUnicode; - - /** - * {@code true} use pretty printing, {@code false} do not use pretty printing. - */ - private final boolean usePrettyPrinting; - - /** - * {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - */ - private final boolean variablesAreOnlyComputedFromUpdates; - - /** - * {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - private final boolean simplifyConditions; + /** + * {@code true} use unicode characters, {@code false} do not use unicode characters. + */ + private final boolean useUnicode; - /** - * Constructor. - * @param mergeBranchConditions {@code true} merge branch conditions which means that a branch condition never contains another branch condition or {@code false} allow that branch conditions contains branch conditions. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public TreeSettings(boolean mergeBranchConditions, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) { - this.mergeBranchConditions = mergeBranchConditions; - this.useUnicode = useUnicode; - this.usePrettyPrinting = usePrettyPrinting; - this.variablesAreOnlyComputedFromUpdates = variablesAreOnlyComputedFromUpdates; - this.simplifyConditions = simplifyConditions; - } + /** + * {@code true} use pretty printing, {@code false} do not use pretty printing. + */ + private final boolean usePrettyPrinting; - /** - * {@inheritDoc} - */ - @Override - public boolean isMergeBranchConditions() { - return mergeBranchConditions; - } + /** + * {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} + * {@link IExecutionVariable}s are computed according to the type structure of the visible + * memory. + */ + private final boolean variablesAreOnlyComputedFromUpdates; - /** - * {@inheritDoc} - */ - @Override - public boolean isUseUnicode() { - return useUnicode; - } + /** + * {@code true} simplify conditions, {@code false} do not simplify conditions. + */ + private final boolean simplifyConditions; - /** - * {@inheritDoc} - */ - @Override - public boolean isUsePrettyPrinting() { - return usePrettyPrinting; - } + /** + * Constructor. + * + * @param mergeBranchConditions {@code true} merge branch conditions which means that a branch + * condition never contains another branch condition or {@code false} allow that branch + * conditions contains branch conditions. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + */ + public TreeSettings(boolean mergeBranchConditions, boolean useUnicode, + boolean usePrettyPrinting, boolean variablesAreOnlyComputedFromUpdates, + boolean simplifyConditions) { + this.mergeBranchConditions = mergeBranchConditions; + this.useUnicode = useUnicode; + this.usePrettyPrinting = usePrettyPrinting; + this.variablesAreOnlyComputedFromUpdates = variablesAreOnlyComputedFromUpdates; + this.simplifyConditions = simplifyConditions; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isVariablesAreOnlyComputedFromUpdates() { - return variablesAreOnlyComputedFromUpdates; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isMergeBranchConditions() { + return mergeBranchConditions; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isSimplifyConditions() { - return simplifyConditions; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean isUseUnicode() { + return useUnicode; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isUsePrettyPrinting() { + return usePrettyPrinting; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isVariablesAreOnlyComputedFromUpdates() { + return variablesAreOnlyComputedFromUpdates; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isSimplifyConditions() { + return simplifyConditions; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/IModelSettings.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/IModelSettings.java index e8a52ed584c..be3185dab0f 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/IModelSettings.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/IModelSettings.java @@ -1,25 +1,32 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; /** * Provides the settings used to construct a symbolic object model. + * * @author Martin Hentschel */ public interface IModelSettings { - /** - * Checks if unicode characters are used. - * @return {@code true} use unicode characters, {@code false} do not use unicode characters. - */ - public boolean isUseUnicode(); - - /** - * Checks if pretty printing is used or not. - * @return {@code true} use pretty printing, {@code false} do not use pretty printing. - */ - public boolean isUsePrettyPrinting(); - - /** - * Checks if conditions should be simplified or not. - * @return {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public boolean isSimplifyConditions(); -} \ No newline at end of file + /** + * Checks if unicode characters are used. + * + * @return {@code true} use unicode characters, {@code false} do not use unicode characters. + */ + public boolean isUseUnicode(); + + /** + * Checks if pretty printing is used or not. + * + * @return {@code true} use pretty printing, {@code false} do not use pretty printing. + */ + public boolean isUsePrettyPrinting(); + + /** + * Checks if conditions should be simplified or not. + * + * @return {@code true} simplify conditions, {@code false} do not simplify conditions. + */ + public boolean isSimplifyConditions(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociation.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociation.java index dcf85769789..7bac3877309 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociation.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import de.uka.ilkd.key.logic.Term; @@ -6,81 +9,91 @@ /** *

    - * Represents an association of an {@link ISymbolicState} or {@link ISymbolicObject} - * which is a reference to an {@link ISymbolicObject}. + * Represents an association of an {@link ISymbolicState} or {@link ISymbolicObject} which is a + * reference to an {@link ISymbolicObject}. *

    *

    * The default implementation is {@link SymbolicAssociation}. *

    + * * @author Martin Hentschel * @see SymbolicAssociation */ public interface ISymbolicAssociation extends ISymbolicElement { - /** - * Returns a human readable name. - * @return A human readable name. - */ - public String getName(); - - /** - * Checks if an array index or a program variable is represented. - * @return {@code true} array index, {@code false} program variable. - */ - public boolean isArrayIndex(); - - /** - * Returns the represented array index or {@code null} if a program variable is represented.. - * @return The represented array index or {@code null} if a program variable is represented.. - */ - public Term getArrayIndex(); - - /** - * Returns the human readable array index or {@code null} if a program variable is represented.. - * @return The human readable array index or {@code null} if a program variable is represented.. - */ - public String getArrayIndexString(); - - /** - * Returns the represented {@link IProgramVariable}. - * @return The represented {@link IProgramVariable}. - */ - public IProgramVariable getProgramVariable(); - - /** - * Returns the represented {@link IProgramVariable} as human readable {@link String}. - * @return The represented {@link IProgramVariable} as human readable {@link String}. - */ - public String getProgramVariableString(); + /** + * Returns a human readable name. + * + * @return A human readable name. + */ + public String getName(); - /** - * Returns the target {@link ISymbolicObject}. - * @return The target {@link ISymbolicObject}. - */ - public ISymbolicObject getTarget(); - - /** - *

    - * Returns the optional condition under which this association is valid. - *

    - *

    - * The condition should be {@code null} by default. Only in rare cases, - * e.g. path condition is not strong enough to describe the path completely, - * is a condition is provided. - *

    - * @return The optional condition under which this association is valid. - */ - public Term getCondition(); - - /** - *

    - * Returns the optional condition under which this association is valid as human readable {@link String}. - *

    - *

    - * The condition should be {@code null} by default. Only in rare cases, - * e.g. path condition is not strong enough to describe the path completely, - * is a condition is provided. - *

    - * @return The optional condition under which this association is valid as human readable {@link String}. - */ - public String getConditionString(); -} \ No newline at end of file + /** + * Checks if an array index or a program variable is represented. + * + * @return {@code true} array index, {@code false} program variable. + */ + public boolean isArrayIndex(); + + /** + * Returns the represented array index or {@code null} if a program variable is represented.. + * + * @return The represented array index or {@code null} if a program variable is represented.. + */ + public Term getArrayIndex(); + + /** + * Returns the human readable array index or {@code null} if a program variable is represented.. + * + * @return The human readable array index or {@code null} if a program variable is represented.. + */ + public String getArrayIndexString(); + + /** + * Returns the represented {@link IProgramVariable}. + * + * @return The represented {@link IProgramVariable}. + */ + public IProgramVariable getProgramVariable(); + + /** + * Returns the represented {@link IProgramVariable} as human readable {@link String}. + * + * @return The represented {@link IProgramVariable} as human readable {@link String}. + */ + public String getProgramVariableString(); + + /** + * Returns the target {@link ISymbolicObject}. + * + * @return The target {@link ISymbolicObject}. + */ + public ISymbolicObject getTarget(); + + /** + *

    + * Returns the optional condition under which this association is valid. + *

    + *

    + * The condition should be {@code null} by default. Only in rare cases, e.g. path condition is + * not strong enough to describe the path completely, is a condition is provided. + *

    + * + * @return The optional condition under which this association is valid. + */ + public Term getCondition(); + + /** + *

    + * Returns the optional condition under which this association is valid as human readable + * {@link String}. + *

    + *

    + * The condition should be {@code null} by default. Only in rare cases, e.g. path condition is + * not strong enough to describe the path completely, is a condition is provided. + *

    + * + * @return The optional condition under which this association is valid as human readable + * {@link String}. + */ + public String getConditionString(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociationValueContainer.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociationValueContainer.java index 2786d975e0b..04ec9814970 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociationValueContainer.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicAssociationValueContainer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import org.key_project.util.collection.ImmutableList; @@ -8,55 +11,59 @@ /** *

    - * This interface is not instantiated directly because it defines only the - * common behavior of {@link ISymbolicState} and {@link ISymbolicObject} which - * is to contain associations (references to other {@link ISymbolicObject}s) - * and values (local variables of simple types). + * This interface is not instantiated directly because it defines only the common behavior of + * {@link ISymbolicState} and {@link ISymbolicObject} which is to contain associations (references + * to other {@link ISymbolicObject}s) and values (local variables of simple types). *

    *

    * The default abstract implementation is {@link AbstractSymbolicAssociationValueContainer}. *

    + * * @author Martin Hentschel * @see AbstractSymbolicAssociationValueContainer * @see ISymbolicObject * @see ISymbolicState */ public interface ISymbolicAssociationValueContainer extends ISymbolicElement { - /** - * Returns the contained associations. - * @return The contained associations. - */ - public ImmutableList getAssociations(); - - /** - * Returns the {@link ISymbolicAssociation} with the given {@link IProgramVariable}. - * @param programVariable The {@link IProgramVariable} for which the {@link ISymbolicAssociation} is requested. - * @param isArrayIndex Is array index? - * @param arrayIndex The array index. - * @param condition The optional condition under which this association is valid. - * @return The found {@link ISymbolicAssociation} or {@code null} if no {@link ISymbolicAssociation} is available with the given {@link IProgramVariable}. - */ - public ISymbolicAssociation getAssociation(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition); - - /** - * Returns the contained values. - * @return The contained values. - */ - public ImmutableList getValues(); - - /** - * Returns the {@link ISymbolicValue} with the given {@link IProgramVariable}. - * @param programVariable The {@link IProgramVariable} for which the {@link ISymbolicValue} is requested. - * @param isArrayIndex Is array index? - * @param arrayIndex The array index. - * @param condition The optional condition under which this value is valid. - * @return The found {@link ISymbolicValue} or {@code null} if no {@link ISymbolicValue} is available with the given {@link IProgramVariable}. - */ - public ISymbolicValue getValue(IProgramVariable programVariable, - boolean isArrayIndex, - Term arrayIndex, - Term condition); -} \ No newline at end of file + /** + * Returns the contained associations. + * + * @return The contained associations. + */ + public ImmutableList getAssociations(); + + /** + * Returns the {@link ISymbolicAssociation} with the given {@link IProgramVariable}. + * + * @param programVariable The {@link IProgramVariable} for which the + * {@link ISymbolicAssociation} is requested. + * @param isArrayIndex Is array index? + * @param arrayIndex The array index. + * @param condition The optional condition under which this association is valid. + * @return The found {@link ISymbolicAssociation} or {@code null} if no + * {@link ISymbolicAssociation} is available with the given {@link IProgramVariable}. + */ + public ISymbolicAssociation getAssociation(IProgramVariable programVariable, + boolean isArrayIndex, Term arrayIndex, Term condition); + + /** + * Returns the contained values. + * + * @return The contained values. + */ + public ImmutableList getValues(); + + /** + * Returns the {@link ISymbolicValue} with the given {@link IProgramVariable}. + * + * @param programVariable The {@link IProgramVariable} for which the {@link ISymbolicValue} is + * requested. + * @param isArrayIndex Is array index? + * @param arrayIndex The array index. + * @param condition The optional condition under which this value is valid. + * @return The found {@link ISymbolicValue} or {@code null} if no {@link ISymbolicValue} is + * available with the given {@link IProgramVariable}. + */ + public ISymbolicValue getValue(IProgramVariable programVariable, boolean isArrayIndex, + Term arrayIndex, Term condition); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicElement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicElement.java index db8e9ff389a..c67de0322b9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicElement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicElement.java @@ -1,14 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; /** - * Defines the basic methods and properties each element in an - * symbolic object model has to have. + * Defines the basic methods and properties each element in an symbolic object model has to have. + * * @author Martin Hentschel */ public interface ISymbolicElement { - /** - * Returns the {@link IModelSettings} to use. - * @return The {@link IModelSettings} to use. - */ - public IModelSettings getSettings(); -} \ No newline at end of file + /** + * Returns the {@link IModelSettings} to use. + * + * @return The {@link IModelSettings} to use. + */ + public IModelSettings getSettings(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicEquivalenceClass.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicEquivalenceClass.java index 75417b56af7..cb639154354 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicEquivalenceClass.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicEquivalenceClass.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import org.key_project.util.collection.ImmutableList; @@ -5,39 +8,47 @@ import de.uka.ilkd.key.logic.Term; /** - * An equivalence class which defines which {@link Term}s represent - * the same {@link ISymbolicObject} in an {@link ISymbolicLayout}. + * An equivalence class which defines which {@link Term}s represent the same {@link ISymbolicObject} + * in an {@link ISymbolicLayout}. + * * @author Martin Hentschel */ public interface ISymbolicEquivalenceClass extends ISymbolicElement { - /** - * Returns the terms which represents the same {@link ISymbolicObject}. - * @return The terms which represents the same {@link ISymbolicObject}. - */ - public ImmutableList getTerms(); - - /** - * Checks if a {@link Term} is contained. - * @param term The {@link Term} to check. - * @return {@code true} {@link Term} is contained, {@code false} {@link Term} is not contained. - */ - public boolean containsTerm(Term term); - - /** - * Returns the terms which represents the same {@link ISymbolicObject} as human readable {@link String}. - * @return The terms which represents the same {@link ISymbolicObject} as human readable {@link String}. - */ - public ImmutableList getTermStrings(); - - /** - * Returns the most representative term. - * @return The most representative term. - */ - public Term getRepresentative(); + /** + * Returns the terms which represents the same {@link ISymbolicObject}. + * + * @return The terms which represents the same {@link ISymbolicObject}. + */ + public ImmutableList getTerms(); - /** - * Returns the most representative term as human readable {@link String}. - * @return The most representative term as human readable {@link String}. - */ - public String getRepresentativeString(); -} \ No newline at end of file + /** + * Checks if a {@link Term} is contained. + * + * @param term The {@link Term} to check. + * @return {@code true} {@link Term} is contained, {@code false} {@link Term} is not contained. + */ + public boolean containsTerm(Term term); + + /** + * Returns the terms which represents the same {@link ISymbolicObject} as human readable + * {@link String}. + * + * @return The terms which represents the same {@link ISymbolicObject} as human readable + * {@link String}. + */ + public ImmutableList getTermStrings(); + + /** + * Returns the most representative term. + * + * @return The most representative term. + */ + public Term getRepresentative(); + + /** + * Returns the most representative term as human readable {@link String}. + * + * @return The most representative term as human readable {@link String}. + */ + public String getRepresentativeString(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicLayout.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicLayout.java index d5b8d156ee8..34837d22cec 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicLayout.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicLayout.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import org.key_project.util.collection.ImmutableList; @@ -12,14 +15,15 @@ * This interface represents the root element of a symbolic memory layout. *

    *

    - * A symbolic memory layout defines how a heap and stack looks like and which objects - * are the same (equivalent classes). Such memory layouts can be created - * automatically via a {@link SymbolicLayoutExtractor} and saved/loaded - * via {@link SymbolicLayoutWriter}/{@link SymbolicLayoutReader}. + * A symbolic memory layout defines how a heap and stack looks like and which objects are the same + * (equivalent classes). Such memory layouts can be created automatically via a + * {@link SymbolicLayoutExtractor} and saved/loaded via + * {@link SymbolicLayoutWriter}/{@link SymbolicLayoutReader}. *

    *

    * The default implementation is {@link SymbolicLayout}. *

    + * * @author Martin Hentschel * @see SymbolicLayoutExtractor * @see SymbolicLayoutWriter @@ -27,21 +31,24 @@ * @see SymbolicLayout */ public interface ISymbolicLayout extends ISymbolicElement { - /** - * Returns the equivalence classes. - * @return The equivalence classes. - */ - public ImmutableList getEquivalenceClasses(); - - /** - * Returns the symbolic state. - * @return the symbolic state. - */ - public ISymbolicState getState(); - - /** - * Returns all available symbolic objects. - * @return The available symbolic objects. - */ - public ImmutableList getObjects(); -} \ No newline at end of file + /** + * Returns the equivalence classes. + * + * @return The equivalence classes. + */ + public ImmutableList getEquivalenceClasses(); + + /** + * Returns the symbolic state. + * + * @return the symbolic state. + */ + public ISymbolicState getState(); + + /** + * Returns all available symbolic objects. + * + * @return The available symbolic objects. + */ + public ImmutableList getObjects(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicObject.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicObject.java index 1dc1c8013da..db7e2b8c8ee 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicObject.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicObject.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import de.uka.ilkd.key.logic.Term; @@ -11,31 +14,36 @@ *

    * The default implementation is {@link SymbolicObject}. *

    + * * @author Martin Hentschel * @see SymbolicObject */ public interface ISymbolicObject extends ISymbolicAssociationValueContainer { - /** - * Returns the name of this object. - * @return The name of this object. - */ - public Term getName(); - - /** - * Returns the name of this object as human readable {@link String}. - * @return The name of this object as human readable {@link String}. - */ - public String getNameString(); - - /** - * Returns the type of this object. - * @return The type of this object. - */ - public Sort getType(); - - /** - * Returns the type of this object as human readable string. - * @return The type of this object as human readable string. - */ - public String getTypeString(); -} \ No newline at end of file + /** + * Returns the name of this object. + * + * @return The name of this object. + */ + public Term getName(); + + /** + * Returns the name of this object as human readable {@link String}. + * + * @return The name of this object as human readable {@link String}. + */ + public String getNameString(); + + /** + * Returns the type of this object. + * + * @return The type of this object. + */ + public Sort getType(); + + /** + * Returns the type of this object as human readable string. + * + * @return The type of this object as human readable string. + */ + public String getTypeString(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicState.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicState.java index f5ab673d27f..48bf4fcaefe 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicState.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import de.uka.ilkd.key.symbolic_execution.object_model.impl.SymbolicState; @@ -9,13 +12,15 @@ *

    * The default implementation is {@link SymbolicState}. *

    + * * @author Martin Hentschel * @see SymbolicState */ public interface ISymbolicState extends ISymbolicAssociationValueContainer { - /** - * Returns the name of this state. - * @return The name of this state. - */ - public String getName(); -} \ No newline at end of file + /** + * Returns the name of this state. + * + * @return The name of this state. + */ + public String getName(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicValue.java index f4966d77504..94ef6dc504a 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/ISymbolicValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model; import de.uka.ilkd.key.logic.Term; @@ -7,99 +10,116 @@ /** *

    - * Represents a variable of an {@link ISymbolicState} or {@link ISymbolicObject} - * which contains a value of a primitive type. + * Represents a variable of an {@link ISymbolicState} or {@link ISymbolicObject} which contains a + * value of a primitive type. *

    *

    * The default implementation is {@link SymbolicValue}. *

    + * * @author Martin Hentschel * @see SymbolicValue */ public interface ISymbolicValue extends ISymbolicElement { - /** - * Returns a human readable name. - * @return A human readable name. - */ - public String getName(); - - /** - * Checks if an array index or a program variable is represented. - * @return {@code true} array index, {@code false} program variable. - */ - public boolean isArrayIndex(); - - /** - * Returns the represented array index or {@code null} if a program variable is represented.. - * @return The represented array index or {@code null} if a program variable is represented.. - */ - public Term getArrayIndex(); - - /** - * Returns the human readable array index or {@code null} if a program variable is represented.. - * @return The human readable array index or {@code null} if a program variable is represented.. - */ - public String getArrayIndexString(); - - /** - * Returns the represented {@link IProgramVariable} or {@code null} if an array index is represented. - * @return The represented {@link IProgramVariable} or {@code null} if an array index is represented. - */ - public IProgramVariable getProgramVariable(); - - /** - * Returns the represented {@link IProgramVariable} as human readable {@link String} or {@code null} if an array index is represented. - * @return The represented {@link IProgramVariable} as human readable {@link String} or {@code null} if an array index is represented. - */ - public String getProgramVariableString(); - - /** - * Returns the value of the represented variable. - * @return The value of the represented variable. - */ - public Term getValue(); - - /** - * Returns the value of the represented variable as human readable {@link String}. - * @return The value of the represented variable as human readable {@link String}. - */ - public String getValueString(); - - /** - * Returns the type of the value. - * @return The type of the value. - */ - public Sort getType(); - - /** - * Returns the type of the value as human readable string. - * @return The type of the value as human readable string. - */ - public String getTypeString(); - - /** - *

    - * Returns the optional condition under which this value is valid. - *

    - *

    - * The condition should be {@code null} by default. Only in rare cases, - * e.g. path condition is not strong enough to describe the path completely, - * is a condition is provided. - *

    - * @return The optional condition under which this value is valid. - */ - public Term getCondition(); - - /** - *

    - * Returns the optional condition under which this value is valid as human readable {@link String}. - *

    - *

    - * The condition should be {@code null} by default. Only in rare cases, - * e.g. path condition is not strong enough to describe the path completely, - * is a condition is provided. - *

    - * @return The optional condition under which this value is valid as human readable {@link String}. - */ - public String getConditionString(); -} \ No newline at end of file + /** + * Returns a human readable name. + * + * @return A human readable name. + */ + public String getName(); + + /** + * Checks if an array index or a program variable is represented. + * + * @return {@code true} array index, {@code false} program variable. + */ + public boolean isArrayIndex(); + + /** + * Returns the represented array index or {@code null} if a program variable is represented.. + * + * @return The represented array index or {@code null} if a program variable is represented.. + */ + public Term getArrayIndex(); + + /** + * Returns the human readable array index or {@code null} if a program variable is represented.. + * + * @return The human readable array index or {@code null} if a program variable is represented.. + */ + public String getArrayIndexString(); + + /** + * Returns the represented {@link IProgramVariable} or {@code null} if an array index is + * represented. + * + * @return The represented {@link IProgramVariable} or {@code null} if an array index is + * represented. + */ + public IProgramVariable getProgramVariable(); + + /** + * Returns the represented {@link IProgramVariable} as human readable {@link String} or + * {@code null} if an array index is represented. + * + * @return The represented {@link IProgramVariable} as human readable {@link String} or + * {@code null} if an array index is represented. + */ + public String getProgramVariableString(); + + /** + * Returns the value of the represented variable. + * + * @return The value of the represented variable. + */ + public Term getValue(); + + /** + * Returns the value of the represented variable as human readable {@link String}. + * + * @return The value of the represented variable as human readable {@link String}. + */ + public String getValueString(); + + /** + * Returns the type of the value. + * + * @return The type of the value. + */ + public Sort getType(); + + /** + * Returns the type of the value as human readable string. + * + * @return The type of the value as human readable string. + */ + public String getTypeString(); + + /** + *

    + * Returns the optional condition under which this value is valid. + *

    + *

    + * The condition should be {@code null} by default. Only in rare cases, e.g. path condition is + * not strong enough to describe the path completely, is a condition is provided. + *

    + * + * @return The optional condition under which this value is valid. + */ + public Term getCondition(); + + /** + *

    + * Returns the optional condition under which this value is valid as human readable + * {@link String}. + *

    + *

    + * The condition should be {@code null} by default. Only in rare cases, e.g. path condition is + * not strong enough to describe the path completely, is a condition is provided. + *

    + * + * @return The optional condition under which this value is valid as human readable + * {@link String}. + */ + public String getConditionString(); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractElement.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractElement.java index b5e43eb87bc..298e13d89cb 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractElement.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.java.Services; @@ -8,40 +11,41 @@ /** * Default implementation of {@link ISymbolicElement}. + * * @author Martin Hentschel */ public abstract class AbstractElement implements ISymbolicElement { - /** - * The {@link IModelSettings} to use. - */ - private final IModelSettings settings; + /** + * The {@link IModelSettings} to use. + */ + private final IModelSettings settings; - /** - * Constructor. - * @param settings The {@link IModelSettings} to use. - */ - public AbstractElement(IModelSettings settings) { - this.settings = settings; - } + /** + * Constructor. + * + * @param settings The {@link IModelSettings} to use. + */ + public AbstractElement(IModelSettings settings) { + this.settings = settings; + } - /** - * {@inheritDoc} - */ - @Override - public IModelSettings getSettings() { - return settings; - } + /** + * {@inheritDoc} + */ + @Override + public IModelSettings getSettings() { + return settings; + } - /** - * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. - * @param term The {@link Term} to convert. - * @param services The {@link Services} to use. - * @return The {@link String} representation of the given {@link Term}. - */ - protected String formatTerm(Term term, Services services) { - return SymbolicExecutionUtil.formatTerm(term, - services, - settings.isUseUnicode(), - settings.isUsePrettyPrinting()); - } -} \ No newline at end of file + /** + * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. + * + * @param term The {@link Term} to convert. + * @param services The {@link Services} to use. + * @return The {@link String} representation of the given {@link Term}. + */ + protected String formatTerm(Term term, Services services) { + return SymbolicExecutionUtil.formatTerm(term, services, settings.isUseUnicode(), + settings.isUsePrettyPrinting()); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractSymbolicAssociationValueContainer.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractSymbolicAssociationValueContainer.java index 570cc5fec8f..076c232557f 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractSymbolicAssociationValueContainer.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/AbstractSymbolicAssociationValueContainer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import org.key_project.util.collection.ImmutableList; @@ -15,94 +18,95 @@ /** * Default implementation of {@link ISymbolicAssociationValueContainer}. + * * @author Martin Hentschel */ -public abstract class AbstractSymbolicAssociationValueContainer extends AbstractElement implements ISymbolicAssociationValueContainer { - /** - * The contained {@link ISymbolicAssociation}s. - */ - private ImmutableList associations = ImmutableSLList.nil(); - - /** - * The contained {@link ISymbolicValue}s. - */ - private ImmutableList values = ImmutableSLList.nil(); +public abstract class AbstractSymbolicAssociationValueContainer extends AbstractElement + implements ISymbolicAssociationValueContainer { + /** + * The contained {@link ISymbolicAssociation}s. + */ + private ImmutableList associations = ImmutableSLList.nil(); - /** - * Constructor. - * @param settings The {@link IModelSettings} to use. - */ - public AbstractSymbolicAssociationValueContainer(IModelSettings settings) { - super(settings); - } + /** + * The contained {@link ISymbolicValue}s. + */ + private ImmutableList values = ImmutableSLList.nil(); - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getAssociations() { - return associations; - } - - /** - * Adds a new {@link ISymbolicAssociation}. - * @param value The new {@link ISymbolicAssociation} to add. - */ - public void addAssociation(ISymbolicAssociation association) { - associations = associations.append(association); - } + /** + * Constructor. + * + * @param settings The {@link IModelSettings} to use. + */ + public AbstractSymbolicAssociationValueContainer(IModelSettings settings) { + super(settings); + } - /** - * {@inheritDoc} - */ - @Override - public ISymbolicAssociation getAssociation(final IProgramVariable programVariable, - final boolean isArrayIndex, - final Term arrayIndex, - final Term condition) { - return CollectionUtil.search(associations, new IFilter() { - @Override - public boolean select(ISymbolicAssociation element) { - return element.getProgramVariable() == programVariable && - element.isArrayIndex() == isArrayIndex && - ObjectUtil.equals(element.getArrayIndex(), arrayIndex) && - ObjectUtil.equals(element.getCondition(), condition); - } - }); - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getAssociations() { + return associations; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getValues() { - return values; - } - - /** - * Adds a new {@link ISymbolicValue}. - * @param value The new {@link ISymbolicValue} to add. - */ - public void addValue(ISymbolicValue value) { - values = values.append(value); - } + /** + * Adds a new {@link ISymbolicAssociation}. + * + * @param value The new {@link ISymbolicAssociation} to add. + */ + public void addAssociation(ISymbolicAssociation association) { + associations = associations.append(association); + } - /** - * {@inheritDoc} - */ - @Override - public ISymbolicValue getValue(final IProgramVariable programVariable, - final boolean isArrayIndex, - final Term arrayIndex, - final Term condition) { - return CollectionUtil.search(values, new IFilter() { - @Override - public boolean select(ISymbolicValue element) { - return element.getProgramVariable() == programVariable && - element.isArrayIndex() == isArrayIndex && - ObjectUtil.equals(element.getArrayIndex(), arrayIndex) && - ObjectUtil.equals(element.getCondition(), condition); - } - }); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public ISymbolicAssociation getAssociation(final IProgramVariable programVariable, + final boolean isArrayIndex, final Term arrayIndex, final Term condition) { + return CollectionUtil.search(associations, new IFilter() { + @Override + public boolean select(ISymbolicAssociation element) { + return element.getProgramVariable() == programVariable + && element.isArrayIndex() == isArrayIndex + && ObjectUtil.equals(element.getArrayIndex(), arrayIndex) + && ObjectUtil.equals(element.getCondition(), condition); + } + }); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getValues() { + return values; + } + + /** + * Adds a new {@link ISymbolicValue}. + * + * @param value The new {@link ISymbolicValue} to add. + */ + public void addValue(ISymbolicValue value) { + values = values.append(value); + } + + /** + * {@inheritDoc} + */ + @Override + public ISymbolicValue getValue(final IProgramVariable programVariable, + final boolean isArrayIndex, final Term arrayIndex, final Term condition) { + return CollectionUtil.search(values, new IFilter() { + @Override + public boolean select(ISymbolicValue element) { + return element.getProgramVariable() == programVariable + && element.isArrayIndex() == isArrayIndex + && ObjectUtil.equals(element.getArrayIndex(), arrayIndex) + && ObjectUtil.equals(element.getCondition(), condition); + } + }); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/ModelSettings.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/ModelSettings.java index ca1b61fb5f4..32cb3936d4e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/ModelSettings.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/ModelSettings.java @@ -1,60 +1,69 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.symbolic_execution.object_model.IModelSettings; /** * Default implementation of {@link IModelSettings}. + * * @author Martin Hentschel */ public class ModelSettings implements IModelSettings { - /** - * {@code true} use unicode characters, {@code false} do not use unicode characters. - */ - private final boolean useUnicode; - - /** - * {@code true} use pretty printing, {@code false} do not use pretty printing. - */ - private final boolean usePrettyPrinting; - - /** - * {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - private final boolean simplifyConditions; - - /** - * Constructor. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - */ - public ModelSettings(boolean useUnicode, boolean usePrettyPrinting, boolean simplifyConditions) { - this.useUnicode = useUnicode; - this.usePrettyPrinting = usePrettyPrinting; - this.simplifyConditions = simplifyConditions; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isUseUnicode() { - return useUnicode; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isUsePrettyPrinting() { - return usePrettyPrinting; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isSimplifyConditions() { - return simplifyConditions; - } -} \ No newline at end of file + /** + * {@code true} use unicode characters, {@code false} do not use unicode characters. + */ + private final boolean useUnicode; + + /** + * {@code true} use pretty printing, {@code false} do not use pretty printing. + */ + private final boolean usePrettyPrinting; + + /** + * {@code true} simplify conditions, {@code false} do not simplify conditions. + */ + private final boolean simplifyConditions; + + /** + * Constructor. + * + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + */ + public ModelSettings(boolean useUnicode, boolean usePrettyPrinting, + boolean simplifyConditions) { + this.useUnicode = useUnicode; + this.usePrettyPrinting = usePrettyPrinting; + this.simplifyConditions = simplifyConditions; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isUseUnicode() { + return useUnicode; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isUsePrettyPrinting() { + return usePrettyPrinting; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isSimplifyConditions() { + return simplifyConditions; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicAssociation.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicAssociation.java index f208bed157c..67e5bfae322 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicAssociation.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicAssociation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.java.Services; @@ -11,272 +14,269 @@ /** * Default implementation of {@link ISymbolicAssociation}. + * * @author Martin Hentschel */ public class SymbolicAssociation extends AbstractElement implements ISymbolicAssociation { - /** - * The {@link Services} to use. - */ - private final Services services; + /** + * The {@link Services} to use. + */ + private final Services services; - /** - * The array index. - */ - private final Term arrayIndex; - - /** - * The array start index or {@code null} if not used. - */ - private final Term arrayStartIndex; - - /** - * The array end index or {@code null} if not used. - */ - private final Term arrayEndIndex; - - /** - * The {@link IProgramVariable}. - */ - private final IProgramVariable programVariable; - - /** - * The target {@link ISymbolicObject}. - */ - private final ISymbolicObject target; - - /** - * The optional condition under which this association is valid. - */ - private final Term condition; - - /** - * Constructor. - * @param services The {@link Services} to use. - * @param arrayIndex The array index. - * @param target The target {@link ISymbolicObject}. - * @param condition The optional condition under which this association is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicAssociation(Services services, - Term arrayIndex, - ISymbolicObject target, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert target != null; - this.services = services; - this.programVariable = null; - this.arrayIndex = arrayIndex; - this.target = target; - this.condition = condition; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } - - /** - * Constructor. - * @param services The {@link Services} to use. - * @param arrayIndex The array index. - * @param arrayStartIndex The array start index or {@code null} if not used. - * @param arrayEndIndex The array end index or {@code null} if not used. - * @param target The target {@link ISymbolicObject}. - * @param condition The optional condition under which this association is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicAssociation(Services services, - Term arrayIndex, - Term arrayStartIndex, - Term arrayEndIndex, - ISymbolicObject target, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert target != null; - this.services = services; - this.programVariable = null; - this.arrayIndex = arrayIndex; - this.target = target; - this.condition = condition; - this.arrayStartIndex = arrayStartIndex; - this.arrayEndIndex = arrayEndIndex; - } - - /** - * Constructor. - * @param services The {@link Services} to use. - * @param programVariable The {@link IProgramVariable}. - * @param target The target {@link ISymbolicObject}. - * @param condition The optional condition under which this association is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicAssociation(Services services, - IProgramVariable programVariable, - ISymbolicObject target, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert programVariable != null; - assert target != null; - this.services = services; - this.programVariable = programVariable; - this.target = target; - this.arrayIndex = null; - this.condition = condition; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - StringBuffer sb = new StringBuffer(); - if (isArrayRange()) { - sb.append("["); - if (getArrayStartIndex() != null) { - sb.append(getArrayIndexString()); - sb.append(" >= "); - sb.append(getArrayStartIndexString()); - } - if (getArrayStartIndex() != null && getArrayEndIndex() != null) { - sb.append(" and "); - } - if (getArrayEndIndex() != null) { + /** + * The array index. + */ + private final Term arrayIndex; + + /** + * The array start index or {@code null} if not used. + */ + private final Term arrayStartIndex; + + /** + * The array end index or {@code null} if not used. + */ + private final Term arrayEndIndex; + + /** + * The {@link IProgramVariable}. + */ + private final IProgramVariable programVariable; + + /** + * The target {@link ISymbolicObject}. + */ + private final ISymbolicObject target; + + /** + * The optional condition under which this association is valid. + */ + private final Term condition; + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param arrayIndex The array index. + * @param target The target {@link ISymbolicObject}. + * @param condition The optional condition under which this association is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicAssociation(Services services, Term arrayIndex, ISymbolicObject target, + Term condition, IModelSettings settings) { + super(settings); + assert services != null; + assert target != null; + this.services = services; + this.programVariable = null; + this.arrayIndex = arrayIndex; + this.target = target; + this.condition = condition; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param arrayIndex The array index. + * @param arrayStartIndex The array start index or {@code null} if not used. + * @param arrayEndIndex The array end index or {@code null} if not used. + * @param target The target {@link ISymbolicObject}. + * @param condition The optional condition under which this association is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicAssociation(Services services, Term arrayIndex, Term arrayStartIndex, + Term arrayEndIndex, ISymbolicObject target, Term condition, IModelSettings settings) { + super(settings); + assert services != null; + assert target != null; + this.services = services; + this.programVariable = null; + this.arrayIndex = arrayIndex; + this.target = target; + this.condition = condition; + this.arrayStartIndex = arrayStartIndex; + this.arrayEndIndex = arrayEndIndex; + } + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param programVariable The {@link IProgramVariable}. + * @param target The target {@link ISymbolicObject}. + * @param condition The optional condition under which this association is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicAssociation(Services services, IProgramVariable programVariable, + ISymbolicObject target, Term condition, IModelSettings settings) { + super(settings); + assert services != null; + assert programVariable != null; + assert target != null; + this.services = services; + this.programVariable = programVariable; + this.target = target; + this.arrayIndex = null; + this.condition = condition; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + StringBuffer sb = new StringBuffer(); + if (isArrayRange()) { + sb.append("["); + if (getArrayStartIndex() != null) { + sb.append(getArrayIndexString()); + sb.append(" >= "); + sb.append(getArrayStartIndexString()); + } + if (getArrayStartIndex() != null && getArrayEndIndex() != null) { + sb.append(" and "); + } + if (getArrayEndIndex() != null) { + sb.append(getArrayIndexString()); + sb.append(" <= "); + sb.append(getArrayEndIndexString()); + } + sb.append("]"); + } else if (isArrayIndex()) { + sb.append("["); sb.append(getArrayIndexString()); - sb.append(" <= "); - sb.append(getArrayEndIndexString()); - } - sb.append("]"); - } - else if (isArrayIndex()) { - sb.append("["); - sb.append(getArrayIndexString()); - sb.append("]"); - } - else { - sb.append(getProgramVariableString()); - } - if (condition != null && condition.op() != Junctor.TRUE) { - sb.append(" {"); - sb.append(getConditionString()); - sb.append("}"); - } - return sb.toString(); - } - - /** - * Checks if an array index is represented. - * @return {@code true} is array index, {@code false} is something else. - */ - public boolean isArrayIndex() { - return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); - } + sb.append("]"); + } else { + sb.append(getProgramVariableString()); + } + if (condition != null && condition.op() != Junctor.TRUE) { + sb.append(" {"); + sb.append(getConditionString()); + sb.append("}"); + } + return sb.toString(); + } + + /** + * Checks if an array index is represented. + * + * @return {@code true} is array index, {@code false} is something else. + */ + public boolean isArrayIndex() { + return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); + } + + /** + * Checks if an array range is represented. + * + * @return {@code true} is array range, {@code false} is something else. + */ + public boolean isArrayRange() { + return arrayStartIndex != null && arrayEndIndex != null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return arrayIndex; + } - /** - * Checks if an array range is represented. - * @return {@code true} is array range, {@code false} is something else. - */ - public boolean isArrayRange() { - return arrayStartIndex != null && arrayEndIndex != null; - } + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return programVariable; + } - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return arrayIndex; - } + /** + * {@inheritDoc} + */ + @Override + public String getProgramVariableString() { + return SymbolicExecutionUtil.getDisplayString(programVariable); + } - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return programVariable; - } + /** + * {@inheritDoc} + */ + @Override + public ISymbolicObject getTarget() { + return target; + } - /** - * {@inheritDoc} - */ - @Override - public String getProgramVariableString() { - return SymbolicExecutionUtil.getDisplayString(programVariable); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Association " + getName() + " to " + getTarget(); + } - /** - * {@inheritDoc} - */ - @Override - public ISymbolicObject getTarget() { - return target; - } + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() { + return condition; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Association " + getName() + " to " + getTarget(); - } + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() { + return condition != null ? formatTerm(condition, services) : null; + } - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() { - return condition; - } + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndex != null ? formatTerm(arrayIndex, services) : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() { - return condition != null ? formatTerm(condition, services) : null; - } + /** + * Returns the array start index. + * + * @return The array start index. + */ + public Term getArrayStartIndex() { + return arrayStartIndex; + } - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndex != null ? formatTerm(arrayIndex, services) : null; - } + /** + * Returns the human readable array start index. + * + * @return The human readable array start index. + */ + public String getArrayStartIndexString() { + return arrayStartIndex != null ? formatTerm(arrayStartIndex, services) : null; + } - /** - * Returns the array start index. - * @return The array start index. - */ - public Term getArrayStartIndex() { - return arrayStartIndex; - } + /** + * Returns the array end index. + * + * @return The array end index. + */ + public Term getArrayEndIndex() { + return arrayEndIndex; + } - /** - * Returns the human readable array start index. - * @return The human readable array start index. - */ - public String getArrayStartIndexString() { - return arrayStartIndex != null ? formatTerm(arrayStartIndex, services) : null; - } - - /** - * Returns the array end index. - * @return The array end index. - */ - public Term getArrayEndIndex() { - return arrayEndIndex; - } - - /** - * Returns the human readable array end index. - * @return The human readable array end index. - */ - public String getArrayEndIndexString() { - return arrayEndIndex != null ? formatTerm(arrayEndIndex, services) : null; - } -} \ No newline at end of file + /** + * Returns the human readable array end index. + * + * @return The human readable array end index. + */ + public String getArrayEndIndexString() { + return arrayEndIndex != null ? formatTerm(arrayEndIndex, services) : null; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicEquivalenceClass.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicEquivalenceClass.java index 786f59a994a..ed236b7d310 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicEquivalenceClass.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicEquivalenceClass.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import org.key_project.util.collection.ImmutableList; @@ -16,125 +19,127 @@ /** * Default implementation of {@link ISymbolicEquivalenceClass}. + * * @author Martin Hentschel */ public class SymbolicEquivalenceClass extends AbstractElement implements ISymbolicEquivalenceClass { - /** - * The {@link Services} to use. - */ - private final Services services; + /** + * The {@link Services} to use. + */ + private final Services services; - /** - * The contained {@link Term}s which represents the same {@link ISymbolicObject}. - */ - private ImmutableList terms; + /** + * The contained {@link Term}s which represents the same {@link ISymbolicObject}. + */ + private ImmutableList terms; - /** - * Constructor. - * @param services The {@link Services} to use. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicEquivalenceClass(Services services, IModelSettings settings) { - this(services, ImmutableSLList.nil(), settings); - } + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicEquivalenceClass(Services services, IModelSettings settings) { + this(services, ImmutableSLList.nil(), settings); + } - /** - * Constructor. - * @param services The {@link Services} to use. - * @param terms The contained {@link Term}s which represents the same {@link ISymbolicObject}. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicEquivalenceClass(Services services, ImmutableList terms, IModelSettings settings) { - super(settings); - this.services = services; - this.terms = terms; - } + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param terms The contained {@link Term}s which represents the same {@link ISymbolicObject}. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicEquivalenceClass(Services services, ImmutableList terms, + IModelSettings settings) { + super(settings); + this.services = services; + this.terms = terms; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTerms() { - return terms; - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTerms() { + return terms; + } - /** - * Adds a new {@link Term}. - * @param value The new {@link Term} to add. - */ - public void addTerm(Term term) { - terms = terms.append(OriginTermLabel.removeOriginLabels(term, services)); - } + /** + * Adds a new {@link Term}. + * + * @param value The new {@link Term} to add. + */ + public void addTerm(Term term) { + terms = terms.append(OriginTermLabel.removeOriginLabels(term, services)); + } - /** - * {@inheritDoc} - */ - @Override - public boolean containsTerm(Term term) { - return terms.contains(OriginTermLabel.removeOriginLabels(term, services)); - } + /** + * {@inheritDoc} + */ + @Override + public boolean containsTerm(Term term) { + return terms.contains(OriginTermLabel.removeOriginLabels(term, services)); + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getTermStrings() { - ImmutableList strings = ImmutableSLList.nil(); - for (Term term : terms) { - strings = strings.append(formatTerm(term, services)); - } - return strings; - } + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getTermStrings() { + ImmutableList strings = ImmutableSLList.nil(); + for (Term term : terms) { + strings = strings.append(formatTerm(term, services)); + } + return strings; + } - /** - * {@inheritDoc} - */ - @Override - public Term getRepresentative() { - // Prefer null if contained in equivalence class - final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - Term nullTerm = CollectionUtil.search(terms, new IFilter() { - @Override - public boolean select(Term element) { - return element.op() == heapLDT.getNull(); - } - }); - if (nullTerm != null) { - return nullTerm; - } - else { - // Prefer terms which are a program variable - Term representative = CollectionUtil.search(terms, new IFilter() { + /** + * {@inheritDoc} + */ + @Override + public Term getRepresentative() { + // Prefer null if contained in equivalence class + final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + Term nullTerm = CollectionUtil.search(terms, new IFilter() { @Override public boolean select(Term element) { - return element.op() instanceof IProgramVariable; + return element.op() == heapLDT.getNull(); } - }); - return representative != null ? - representative : // Return term with program variable - terms.head(); // Return the first term - } - } + }); + if (nullTerm != null) { + return nullTerm; + } else { + // Prefer terms which are a program variable + Term representative = CollectionUtil.search(terms, new IFilter() { + @Override + public boolean select(Term element) { + return element.op() instanceof IProgramVariable; + } + }); + return representative != null ? representative : // Return term with program variable + terms.head(); // Return the first term + } + } - /** - * {@inheritDoc} - */ - @Override - public String getRepresentativeString() { - Term representative = getRepresentative(); - if (representative != null) { - return formatTerm(representative, services); - } - else { - return null; - } - } + /** + * {@inheritDoc} + */ + @Override + public String getRepresentativeString() { + Term representative = getRepresentative(); + if (representative != null) { + return formatTerm(representative, services); + } else { + return null; + } + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Equivalence Class " + getTermStrings(); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Equivalence Class " + getTermStrings(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicLayout.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicLayout.java index ccc5c8871b3..aee629baa51 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicLayout.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicLayout.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import org.key_project.util.collection.ImmutableList; @@ -11,73 +14,77 @@ /** * Default implementation of {@link ISymbolicLayout}. + * * @author Martin Hentschel */ public class SymbolicLayout extends AbstractElement implements ISymbolicLayout { - /** - * The contained {@link ISymbolicEquivalenceClass}. - */ - private final ImmutableList equivalenceClasses; - - /** - * The {@link ISymbolicState}. - */ - private ISymbolicState state; - - /** - * The contained {@link ISymbolicObject}s. - */ - private ImmutableList objects = ImmutableSLList.nil(); + /** + * The contained {@link ISymbolicEquivalenceClass}. + */ + private final ImmutableList equivalenceClasses; - /** - * Constructor. - * @param equivalenceClasses The provided equivalence classes. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicLayout(IModelSettings settings, - ImmutableList equivalenceClasses) { - super(settings); - assert equivalenceClasses != null; - this.equivalenceClasses = equivalenceClasses; - } + /** + * The {@link ISymbolicState}. + */ + private ISymbolicState state; - /** - * {@inheritDoc} - */ - @Override - public ISymbolicState getState() { - return state; - } + /** + * The contained {@link ISymbolicObject}s. + */ + private ImmutableList objects = ImmutableSLList.nil(); - /** - * Sets the {@link ISymbolicState}. - * @param state The {@link ISymbolicState} to set. - */ - public void setState(ISymbolicState state) { - this.state = state; - } + /** + * Constructor. + * + * @param equivalenceClasses The provided equivalence classes. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicLayout(IModelSettings settings, + ImmutableList equivalenceClasses) { + super(settings); + assert equivalenceClasses != null; + this.equivalenceClasses = equivalenceClasses; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getObjects() { - return objects; - } - - /** - * Adds a new {@link ISymbolicObject}. - * @param value The new {@link ISymbolicObject} to add. - */ - public void addObject(ISymbolicObject object) { - objects = objects.append(object); - } + /** + * {@inheritDoc} + */ + @Override + public ISymbolicState getState() { + return state; + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList getEquivalenceClasses() { - return equivalenceClasses; - } -} \ No newline at end of file + /** + * Sets the {@link ISymbolicState}. + * + * @param state The {@link ISymbolicState} to set. + */ + public void setState(ISymbolicState state) { + this.state = state; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getObjects() { + return objects; + } + + /** + * Adds a new {@link ISymbolicObject}. + * + * @param value The new {@link ISymbolicObject} to add. + */ + public void addObject(ISymbolicObject object) { + objects = objects.append(object); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList getEquivalenceClasses() { + return equivalenceClasses; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicObject.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicObject.java index 2ed2a75e909..98c2213352a 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicObject.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicObject.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.java.Services; @@ -8,69 +11,72 @@ /** * Default implementation of {@link ISymbolicObject}. + * * @author Martin Hentschel */ -public class SymbolicObject extends AbstractSymbolicAssociationValueContainer implements ISymbolicObject { - /** - * The {@link Services} to use. - */ - private final Services services; - - /** - * The name. - */ - private final Term name; +public class SymbolicObject extends AbstractSymbolicAssociationValueContainer + implements ISymbolicObject { + /** + * The {@link Services} to use. + */ + private final Services services; - /** - * Constructor. - * @param services The {@link Services} to use. - * @param name The name. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicObject(Services services, Term name, IModelSettings settings) { - super(settings); - this.services = services; - this.name = name; - } + /** + * The name. + */ + private final Term name; - /** - * {@inheritDoc} - */ - @Override - public Term getName() { - return name; - } + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param name The name. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicObject(Services services, Term name, IModelSettings settings) { + super(settings); + this.services = services; + this.name = name; + } - /** - * {@inheritDoc} - */ - @Override - public String getNameString() { - return formatTerm(name, services); - } + /** + * {@inheritDoc} + */ + @Override + public Term getName() { + return name; + } - /** - * {@inheritDoc} - */ - @Override - public Sort getType() { - return name != null ? name.sort() : null; - } + /** + * {@inheritDoc} + */ + @Override + public String getNameString() { + return formatTerm(name, services); + } - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() { - Sort sort = getType(); - return sort != null ? sort.toString() : null; - } + /** + * {@inheritDoc} + */ + @Override + public Sort getType() { + return name != null ? name.sort() : null; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Object " + getNameString(); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() { + Sort sort = getType(); + return sort != null ? sort.toString() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Object " + getNameString(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicState.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicState.java index df84c3ee748..798196d41b3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicState.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.symbolic_execution.object_model.IModelSettings; @@ -5,29 +8,32 @@ /** * Default implementation of {@link ISymbolicState}. + * * @author Martin Hentschel */ -public class SymbolicState extends AbstractSymbolicAssociationValueContainer implements ISymbolicState { - /** - * The name of this state. - */ - private final String name; +public class SymbolicState extends AbstractSymbolicAssociationValueContainer + implements ISymbolicState { + /** + * The name of this state. + */ + private final String name; - /** - * Constructor. - * @param name The name of this state. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicState(String name, IModelSettings settings) { - super(settings); - this.name = name; - } + /** + * Constructor. + * + * @param name The name of this state. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicState(String name, IModelSettings settings) { + super(settings); + this.name = name; + } - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return name; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicValue.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicValue.java index 53c623b777e..6eb258b24ff 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicValue.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/object_model/impl/SymbolicValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.object_model.impl; import de.uka.ilkd.key.java.Services; @@ -11,296 +14,293 @@ /** * Default implementation of {@link ISymbolicValue}. + * * @author Martin Hentschel */ public class SymbolicValue extends AbstractElement implements ISymbolicValue { - /** - * The {@link Services} to use. - */ - private final Services services; + /** + * The {@link Services} to use. + */ + private final Services services; - /** - * The array index. - */ - private final Term arrayIndex; - - /** - * The array start index or {@code null} if not used. - */ - private final Term arrayStartIndex; - - /** - * The array end index or {@code null} if not used. - */ - private final Term arrayEndIndex; - - /** - * The {@link IProgramVariable}. - */ - private final IProgramVariable programVariable; - - /** - * The value {@link Term}. - */ - private final Term value; - - /** - * The optional condition under which this value is valid. - */ - private final Term condition; + /** + * The array index. + */ + private final Term arrayIndex; - /** - * Constructor. - * @param services The {@link Services} to use. - * @param arrayIndex The array index. - * @param value The value {@link Term}. - * @param condition The optional condition under which this value is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicValue(Services services, - Term arrayIndex, - Term value, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert arrayIndex != null; - this.services = services; - this.programVariable = null; - this.arrayIndex = arrayIndex; - this.value = value; - this.condition = condition; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } + /** + * The array start index or {@code null} if not used. + */ + private final Term arrayStartIndex; - /** - * Constructor. - * @param services The {@link Services} to use. - * @param arrayIndex The array index. - * @param arrayStartIndex The array start index or {@code null} if not used. - * @param arrayEndIndex The array end index or {@code null} if not used. - * @param value The value {@link Term}. - * @param condition The optional condition under which this value is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicValue(Services services, - Term arrayIndex, - Term arrayStartIndex, - Term arrayEndIndex, - Term value, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert arrayIndex != null; - this.services = services; - this.programVariable = null; - this.arrayIndex = arrayIndex; - this.value = value; - this.condition = condition; - this.arrayStartIndex = arrayStartIndex; - this.arrayEndIndex = arrayEndIndex; - } + /** + * The array end index or {@code null} if not used. + */ + private final Term arrayEndIndex; - /** - * Constructor. - * @param services The {@link Services} to use. - * @param programVariable The {@link IProgramVariable}. - * @param value The value {@link Term}. - * @param condition The optional condition under which this value is valid. - * @param settings The {@link IModelSettings} to use. - */ - public SymbolicValue(Services services, - IProgramVariable programVariable, - Term value, - Term condition, - IModelSettings settings) { - super(settings); - assert services != null; - assert programVariable != null; - this.services = services; - this.programVariable = programVariable; - this.value = value; - this.arrayIndex = null; - this.condition = condition; - this.arrayStartIndex = null; - this.arrayEndIndex = null; - } + /** + * The {@link IProgramVariable}. + */ + private final IProgramVariable programVariable; - /** - * {@inheritDoc} - */ - @Override - public String getName() { - StringBuffer sb = new StringBuffer(); - if (isArrayRange()) { - sb.append("["); - if (getArrayStartIndex() != null) { - sb.append(getArrayIndexString()); - sb.append(" >= "); - sb.append(getArrayStartIndexString()); - } - if (getArrayStartIndex() != null && getArrayEndIndex() != null) { - sb.append(" and "); - } - if (getArrayEndIndex() != null) { + /** + * The value {@link Term}. + */ + private final Term value; + + /** + * The optional condition under which this value is valid. + */ + private final Term condition; + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param arrayIndex The array index. + * @param value The value {@link Term}. + * @param condition The optional condition under which this value is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicValue(Services services, Term arrayIndex, Term value, Term condition, + IModelSettings settings) { + super(settings); + assert services != null; + assert arrayIndex != null; + this.services = services; + this.programVariable = null; + this.arrayIndex = arrayIndex; + this.value = value; + this.condition = condition; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param arrayIndex The array index. + * @param arrayStartIndex The array start index or {@code null} if not used. + * @param arrayEndIndex The array end index or {@code null} if not used. + * @param value The value {@link Term}. + * @param condition The optional condition under which this value is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicValue(Services services, Term arrayIndex, Term arrayStartIndex, + Term arrayEndIndex, Term value, Term condition, IModelSettings settings) { + super(settings); + assert services != null; + assert arrayIndex != null; + this.services = services; + this.programVariable = null; + this.arrayIndex = arrayIndex; + this.value = value; + this.condition = condition; + this.arrayStartIndex = arrayStartIndex; + this.arrayEndIndex = arrayEndIndex; + } + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param programVariable The {@link IProgramVariable}. + * @param value The value {@link Term}. + * @param condition The optional condition under which this value is valid. + * @param settings The {@link IModelSettings} to use. + */ + public SymbolicValue(Services services, IProgramVariable programVariable, Term value, + Term condition, IModelSettings settings) { + super(settings); + assert services != null; + assert programVariable != null; + this.services = services; + this.programVariable = programVariable; + this.value = value; + this.arrayIndex = null; + this.condition = condition; + this.arrayStartIndex = null; + this.arrayEndIndex = null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + StringBuffer sb = new StringBuffer(); + if (isArrayRange()) { + sb.append("["); + if (getArrayStartIndex() != null) { + sb.append(getArrayIndexString()); + sb.append(" >= "); + sb.append(getArrayStartIndexString()); + } + if (getArrayStartIndex() != null && getArrayEndIndex() != null) { + sb.append(" and "); + } + if (getArrayEndIndex() != null) { + sb.append(getArrayIndexString()); + sb.append(" <= "); + sb.append(getArrayEndIndexString()); + } + sb.append("]"); + } else if (isArrayIndex()) { + sb.append("["); sb.append(getArrayIndexString()); - sb.append(" <= "); - sb.append(getArrayEndIndexString()); - } - sb.append("]"); - } - else if (isArrayIndex()) { - sb.append("["); - sb.append(getArrayIndexString()); - sb.append("]"); - } - else { - sb.append(getProgramVariableString()); - } - if (condition != null && condition.op() != Junctor.TRUE) { - sb.append(" {"); - sb.append(getConditionString()); - sb.append("}"); - } - return sb.toString(); - } - - /** - * Checks if an array index is represented. - * @return {@code true} is array index, {@code false} is something else. - */ - public boolean isArrayIndex() { - return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); - } + sb.append("]"); + } else { + sb.append(getProgramVariableString()); + } + if (condition != null && condition.op() != Junctor.TRUE) { + sb.append(" {"); + sb.append(getConditionString()); + sb.append("}"); + } + return sb.toString(); + } + + /** + * Checks if an array index is represented. + * + * @return {@code true} is array index, {@code false} is something else. + */ + public boolean isArrayIndex() { + return arrayIndex != null && (arrayStartIndex == null || arrayEndIndex == null); + } + + /** + * Checks if an array range is represented. + * + * @return {@code true} is array range, {@code false} is something else. + */ + public boolean isArrayRange() { + return arrayStartIndex != null && arrayEndIndex != null; + } + + /** + * {@inheritDoc} + */ + @Override + public Term getArrayIndex() { + return arrayIndex; + } - /** - * Checks if an array range is represented. - * @return {@code true} is array range, {@code false} is something else. - */ - public boolean isArrayRange() { - return arrayStartIndex != null && arrayEndIndex != null; - } + /** + * {@inheritDoc} + */ + @Override + public IProgramVariable getProgramVariable() { + return programVariable; + } - /** - * {@inheritDoc} - */ - @Override - public Term getArrayIndex() { - return arrayIndex; - } + /** + * {@inheritDoc} + */ + @Override + public String getProgramVariableString() { + return SymbolicExecutionUtil.getDisplayString(programVariable); + } - /** - * {@inheritDoc} - */ - @Override - public IProgramVariable getProgramVariable() { - return programVariable; - } + /** + * {@inheritDoc} + */ + @Override + public Term getValue() { + return value; + } - /** - * {@inheritDoc} - */ - @Override - public String getProgramVariableString() { - return SymbolicExecutionUtil.getDisplayString(programVariable); - } + /** + * {@inheritDoc} + */ + @Override + public String getValueString() { + return formatTerm(value, services); + } - /** - * {@inheritDoc} - */ - @Override - public Term getValue() { - return value; - } + /** + * {@inheritDoc} + */ + @Override + public Sort getType() { + return value != null ? value.sort() : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getValueString() { - return formatTerm(value, services); - } + /** + * {@inheritDoc} + */ + @Override + public String getTypeString() { + Sort sort = getType(); + return sort != null ? sort.toString() : null; + } - /** - * {@inheritDoc} - */ - @Override - public Sort getType() { - return value != null ? value.sort() : null; - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Value of " + getName() + " is " + getValueString(); + } - /** - * {@inheritDoc} - */ - @Override - public String getTypeString() { - Sort sort = getType(); - return sort != null ? sort.toString() : null; - } + /** + * {@inheritDoc} + */ + @Override + public Term getCondition() { + return condition; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Value of " + getName() + " is " + getValueString(); - } + /** + * {@inheritDoc} + */ + @Override + public String getConditionString() { + return condition != null ? formatTerm(condition, services) : null; + } - /** - * {@inheritDoc} - */ - @Override - public Term getCondition() { - return condition; - } + /** + * {@inheritDoc} + */ + @Override + public String getArrayIndexString() { + return arrayIndex != null ? formatTerm(arrayIndex, services) : null; + } - /** - * {@inheritDoc} - */ - @Override - public String getConditionString() { - return condition != null ? formatTerm(condition, services) : null; - } + /** + * Returns the array start index. + * + * @return The array start index. + */ + public Term getArrayStartIndex() { + return arrayStartIndex; + } - /** - * {@inheritDoc} - */ - @Override - public String getArrayIndexString() { - return arrayIndex != null ? formatTerm(arrayIndex, services) : null; - } + /** + * Returns the human readable array start index. + * + * @return The human readable array start index. + */ + public String getArrayStartIndexString() { + return arrayStartIndex != null ? formatTerm(arrayStartIndex, services) : null; + } - /** - * Returns the array start index. - * @return The array start index. - */ - public Term getArrayStartIndex() { - return arrayStartIndex; - } + /** + * Returns the array end index. + * + * @return The array end index. + */ + public Term getArrayEndIndex() { + return arrayEndIndex; + } - /** - * Returns the human readable array start index. - * @return The human readable array start index. - */ - public String getArrayStartIndexString() { - return arrayStartIndex != null ? formatTerm(arrayStartIndex, services) : null; - } - - /** - * Returns the array end index. - * @return The array end index. - */ - public Term getArrayEndIndex() { - return arrayEndIndex; - } - - /** - * Returns the human readable array end index. - * @return The human readable array end index. - */ - public String getArrayEndIndexString() { - return arrayEndIndex != null ? formatTerm(arrayEndIndex, services) : null; - } -} \ No newline at end of file + /** + * Returns the human readable array end index. + * + * @return The human readable array end index. + */ + public String getArrayEndIndexString() { + return arrayEndIndex != null ? formatTerm(arrayEndIndex, services) : null; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodPO.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodPO.java index ca310c817a3..7d38413b3fd 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodPO.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.po; import java.io.IOException; @@ -32,11 +35,11 @@ /** *

    - * This proof obligation executes an {@link IProgramMethod} with - * an optional precondition. + * This proof obligation executes an {@link IProgramMethod} with an optional precondition. *

    *

    * The generated {@link Sequent} has the following form: + * *

      * 
      * ==>
    @@ -51,341 +54,338 @@
      * 
      * 
    *

    + * * @author Martin Hentschel */ public class ProgramMethodPO extends AbstractOperationPO { - /** - * The {@link IProgramMethod} to execute code parts from. - */ - private IProgramMethod pm; + /** + * The {@link IProgramMethod} to execute code parts from. + */ + private IProgramMethod pm; - /** - * The precondition in JML syntax. - */ - private String precondition; + /** + * The precondition in JML syntax. + */ + private String precondition; - /** - * Constructor. - * @param initConfig The {@link InitConfig} to use. - * @param name The name to use. - * @param pm The {@link IProgramMethod} to execute code parts from. - * @param precondition An optional precondition to use. - */ - public ProgramMethodPO(InitConfig initConfig, - String name, - IProgramMethod pm, - String precondition) { - super(initConfig, name); - assert pm != null; - this.pm = pm; - this.precondition = precondition; - } + /** + * Constructor. + * + * @param initConfig The {@link InitConfig} to use. + * @param name The name to use. + * @param pm The {@link IProgramMethod} to execute code parts from. + * @param precondition An optional precondition to use. + */ + public ProgramMethodPO(InitConfig initConfig, String name, IProgramMethod pm, + String precondition) { + super(initConfig, name); + assert pm != null; + this.pm = pm; + this.precondition = precondition; + } - /** - * Constructor. - * @param initConfig The {@link InitConfig} to use. - * @param name The name to use. - * @param pm The {@link IProgramMethod} to execute code parts from. - * @param precondition An optional precondition to use. - * @param addUninterpretedPredicate {@code true} postcondition contains uninterpreted predicate, {@code false} uninterpreted predicate is not contained in postcondition. - * @param addSymbolicExecutionLabel {@code true} to add the {@link SymbolicExecutionTermLabel} to the modality, {@code false} to not label the modality. - */ - public ProgramMethodPO(InitConfig initConfig, - String name, - IProgramMethod pm, - String precondition, - boolean addUninterpretedPredicate, - boolean addSymbolicExecutionLabel) { - super(initConfig, name, addUninterpretedPredicate, addSymbolicExecutionLabel); - assert pm != null; - this.pm = pm; - this.precondition = precondition; - } + /** + * Constructor. + * + * @param initConfig The {@link InitConfig} to use. + * @param name The name to use. + * @param pm The {@link IProgramMethod} to execute code parts from. + * @param precondition An optional precondition to use. + * @param addUninterpretedPredicate {@code true} postcondition contains uninterpreted predicate, + * {@code false} uninterpreted predicate is not contained in postcondition. + * @param addSymbolicExecutionLabel {@code true} to add the {@link SymbolicExecutionTermLabel} + * to the modality, {@code false} to not label the modality. + */ + public ProgramMethodPO(InitConfig initConfig, String name, IProgramMethod pm, + String precondition, boolean addUninterpretedPredicate, + boolean addSymbolicExecutionLabel) { + super(initConfig, name, addUninterpretedPredicate, addSymbolicExecutionLabel); + assert pm != null; + this.pm = pm; + this.precondition = precondition; + } - /** - * {@inheritDoc} - */ - @Override - public IProgramMethod getProgramMethod() { - return pm; - } + /** + * {@inheritDoc} + */ + @Override + public IProgramMethod getProgramMethod() { + return pm; + } - /** - * {@inheritDoc} - */ - @Override - protected boolean isTransactionApplicable() { - return false; - } + /** + * {@inheritDoc} + */ + @Override + protected boolean isTransactionApplicable() { + return false; + } - /** - * {@inheritDoc} - */ - @Override - protected KeYJavaType getCalleeKeYJavaType() { - return pm.getContainerType(); - } + /** + * {@inheritDoc} + */ + @Override + protected KeYJavaType getCalleeKeYJavaType() { + return pm.getContainerType(); + } - /** - * {@inheritDoc} - */ - @Override - protected ImmutableList buildOperationBlocks(ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, Services services) { - // Get program method to execute - IProgramMethod pm = getProgramMethod(); - // Extracts code parts of the method - ImmutableArray args = new ImmutableArray(formalParVars.toArray(new ProgramVariable[formalParVars.size()])); - MethodBodyStatement mbs = new MethodBodyStatement(pm, selfVar, resultVar, args); - StatementBlock result = new StatementBlock(mbs); - return ImmutableSLList.nil().prepend(null, result, null, null); - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableList buildOperationBlocks( + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + // Get program method to execute + IProgramMethod pm = getProgramMethod(); + // Extracts code parts of the method + ImmutableArray args = new ImmutableArray( + formalParVars.toArray(new ProgramVariable[formalParVars.size()])); + MethodBodyStatement mbs = new MethodBodyStatement(pm, selfVar, resultVar, args); + StatementBlock result = new StatementBlock(mbs); + return ImmutableSLList.nil().prepend(null, result, null, null); + } - /** - * {@inheritDoc} - */ - @Override - protected Term generateMbyAtPreDef(ProgramVariable selfVar, - ImmutableList paramVars, Services services) { - return tb.tt(); - } + /** + * {@inheritDoc} + */ + @Override + protected Term generateMbyAtPreDef(ProgramVariable selfVar, + ImmutableList paramVars, Services services) { + return tb.tt(); + } - /** - * {@inheritDoc} - */ - @Override - protected Term getPre(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - Map atPreVars, - Services services) { - if (precondition != null && !precondition.isEmpty()) { - JmlIO io = new JmlIO() - .services(services) - .classType(getCalleeKeYJavaType()) - .selfVar(selfVar) - .parameters(paramVars); + /** + * {@inheritDoc} + */ + @Override + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, + Map atPreVars, Services services) { + if (precondition != null && !precondition.isEmpty()) { + JmlIO io = new JmlIO().services(services).classType(getCalleeKeYJavaType()) + .selfVar(selfVar).parameters(paramVars); - PositionedString ps = new PositionedString(precondition); - return io.parseExpression(ps); - } - else { - return tb.tt(); - } - } + PositionedString ps = new PositionedString(precondition); + return io.parseExpression(ps); + } else { + return tb.tt(); + } + } - /** - * {@inheritDoc} - */ - @Override - protected Term getPost(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - ProgramVariable resultVar, - ProgramVariable exceptionVar, - Map atPreVars, - Services services) { - return tb.tt(); - } + /** + * {@inheritDoc} + */ + @Override + protected Term getPost(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, ProgramVariable resultVar, + ProgramVariable exceptionVar, Map atPreVars, + Services services) { + return tb.tt(); + } - /** - * {@inheritDoc} - */ - @Override - protected Term buildFrameClause(List modHeaps, - Map heapToAtPre, - ProgramVariable selfVar, - ImmutableList paramVars, Services services) { - return tb.tt(); - } + /** + * {@inheritDoc} + */ + @Override + protected Term buildFrameClause(List modHeaps, Map heapToAtPre, + ProgramVariable selfVar, ImmutableList paramVars, Services services) { + return tb.tt(); + } - /** - * {@inheritDoc} - */ - @Override - protected Modality getTerminationMarker() { - return Modality.DIA; - } + /** + * {@inheritDoc} + */ + @Override + protected Modality getTerminationMarker() { + return Modality.DIA; + } - /** - * {@inheritDoc} - */ - @Override - protected boolean isMakeNamesUnique() { - return false; // Unique names crashes precondition parsing if names are renamed. - } + /** + * {@inheritDoc} + */ + @Override + protected boolean isMakeNamesUnique() { + return false; // Unique names crashes precondition parsing if names are renamed. + } - /** - * {@inheritDoc} - */ - @Override - protected boolean isCopyOfMethodArgumentsUsed() { - return false; - } + /** + * {@inheritDoc} + */ + @Override + protected boolean isCopyOfMethodArgumentsUsed() { + return false; + } - /** - * {@inheritDoc} - */ - @Override - protected String buildPOName(boolean transactionFlag) { - return name; - } + /** + * {@inheritDoc} + */ + @Override + protected String buildPOName(boolean transactionFlag) { + return name; + } - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return pm.hashCode() + - (precondition != null ? precondition.hashCode() : 0); - } + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return pm.hashCode() + (precondition != null ? precondition.hashCode() : 0); + } - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof ProgramMethodPO) { - ProgramMethodPO other = (ProgramMethodPO)obj; - return ObjectUtil.equals(pm, other.getProgramMethod()) && - ObjectUtil.equals(precondition, other.getPrecondition()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ProgramMethodPO) { + ProgramMethodPO other = (ProgramMethodPO) obj; + return ObjectUtil.equals(pm, other.getProgramMethod()) + && ObjectUtil.equals(precondition, other.getPrecondition()); + } else { + return false; + } + } - /** - * Returns the precondition in JML syntax. - * @return The precondition in JML syntax. - */ - public String getPrecondition() { - return precondition; - } + /** + * Returns the precondition in JML syntax. + * + * @return The precondition in JML syntax. + */ + public String getPrecondition() { + return precondition; + } - /** - * {@inheritDoc} - */ - @Override - public void fillSaveProperties(Properties properties) throws IOException { - super.fillSaveProperties(properties); - properties.setProperty("method", getProgramMethodSignature(getProgramMethod(), true)); - if (getPrecondition() != null && !getPrecondition().isEmpty()) { - properties.setProperty("precondition", getPrecondition()); - } - } + /** + * {@inheritDoc} + */ + @Override + public void fillSaveProperties(Properties properties) throws IOException { + super.fillSaveProperties(properties); + properties.setProperty("method", getProgramMethodSignature(getProgramMethod(), true)); + if (getPrecondition() != null && !getPrecondition().isEmpty()) { + properties.setProperty("precondition", getPrecondition()); + } + } - /** - * Returns a human readable full qualified method signature. - * @param pm The {@link IProgramMethod} which provides the signature. - * @param includeType Include the container type? - * @return The human readable method signature. - * @throws IOException Occurred Exception. - */ - public static String getProgramMethodSignature(IProgramMethod pm, boolean includeType) throws IOException { - StringWriter sw = new StringWriter(); - try { - PrettyPrinter x = new PrettyPrinter(sw); - if (includeType) { - KeYJavaType type = pm.getContainerType(); - sw.append(type.getFullName()); - sw.append("#"); - } - x.printFullMethodSignature(pm); - return sw.toString(); - } - finally { - sw.close(); - } - } + /** + * Returns a human readable full qualified method signature. + * + * @param pm The {@link IProgramMethod} which provides the signature. + * @param includeType Include the container type? + * @return The human readable method signature. + * @throws IOException Occurred Exception. + */ + public static String getProgramMethodSignature(IProgramMethod pm, boolean includeType) + throws IOException { + StringWriter sw = new StringWriter(); + try { + PrettyPrinter x = new PrettyPrinter(sw); + if (includeType) { + KeYJavaType type = pm.getContainerType(); + sw.append(type.getFullName()); + sw.append("#"); + } + x.printFullMethodSignature(pm); + return sw.toString(); + } finally { + sw.close(); + } + } - /** - * Instantiates a new proof obligation with the given settings. - * @param initConfig The already load {@link InitConfig}. - * @param properties The settings of the proof obligation to instantiate. - * @return The instantiated proof obligation. - * @throws IOException Occurred Exception. - */ - public static LoadedPOContainer loadFrom(InitConfig initConfig, Properties properties) throws IOException { - return new LoadedPOContainer(new ProgramMethodPO(initConfig, - getName(properties), - getProgramMethod(initConfig, properties), - getPrecondition(properties), - isAddUninterpretedPredicate(properties), - isAddSymbolicExecutionLabel(properties))); - } + /** + * Instantiates a new proof obligation with the given settings. + * + * @param initConfig The already load {@link InitConfig}. + * @param properties The settings of the proof obligation to instantiate. + * @return The instantiated proof obligation. + * @throws IOException Occurred Exception. + */ + public static LoadedPOContainer loadFrom(InitConfig initConfig, Properties properties) + throws IOException { + return new LoadedPOContainer(new ProgramMethodPO(initConfig, getName(properties), + getProgramMethod(initConfig, properties), getPrecondition(properties), + isAddUninterpretedPredicate(properties), isAddSymbolicExecutionLabel(properties))); + } - /** - * Searches the {@link IProgramMethod} defined by the given {@link Properties}. - * @param initConfig The already load {@link InitConfig}. - * @param properties The settings of the proof obligation to instantiate. - * @return The found {@link IProgramMethod}. - * @throws IOException Occurred Exception if it was not possible to find the {@link IProgramMethod}. - */ - public static IProgramMethod getProgramMethod(InitConfig initConfig, Properties properties) throws IOException { - // Get container class and method signature - String value = properties.getProperty("method"); - if (value == null) { - throw new IOException("Property \"method\" is not defined."); - } - int classMethodSeparator = value.indexOf("#"); - if (classMethodSeparator < 0) { - throw new IOException("Property \"method\" does not contain the class method separator \"#\"."); - } - String className = value.substring(0, classMethodSeparator); - String signature = value.substring(classMethodSeparator + 1); - JavaInfo javaInfo = initConfig.getServices().getJavaInfo(); - // Split signature in name and parameter type names - int breaketsStart = signature.indexOf("("); - if (breaketsStart < 0) { - throw new IOException("Method signature \"" + signature +"\" does not contain required character \"(\"."); - } - int breaketsEnd = signature.lastIndexOf(")"); - if (breaketsEnd < 0) { - throw new IOException("Method signature \"" + signature +"\" does not contain required character \")\"."); - } - if (breaketsEnd < breaketsStart) { - throw new IOException("Method signature has not valid order of chracters \"(\" and \")\"."); - } - String name = signature.substring(0, breaketsStart); - String parameters = signature.substring(breaketsStart + 1, breaketsEnd); - String[] types = parameters.isEmpty() ? new String[0] : parameters.split(","); - // Find container and parameter types - KeYJavaType type = javaInfo.getKeYJavaType(className.trim()); - if (type == null) { - throw new IOException("Can't find type \"" + className + "\"."); - } - ImmutableList parameterTypes = ImmutableSLList.nil(); - for (int i = 0; i < types.length; i++) { - KeYJavaType paramType = javaInfo.getKeYJavaType(types[i].trim()); - if (paramType == null) { - throw new IOException("Can't find type \"" + types[i] + "\"."); - } - parameterTypes = parameterTypes.append(paramType); - } - IProgramMethod pm = javaInfo.getProgramMethod(type, name.trim(), parameterTypes, type); - if (pm == null) { - pm = javaInfo.getConstructor(type, parameterTypes); - if (pm == null) { - throw new IOException("Can't find program method \"" + value + "\"."); - } - } - return pm; - } + /** + * Searches the {@link IProgramMethod} defined by the given {@link Properties}. + * + * @param initConfig The already load {@link InitConfig}. + * @param properties The settings of the proof obligation to instantiate. + * @return The found {@link IProgramMethod}. + * @throws IOException Occurred Exception if it was not possible to find the + * {@link IProgramMethod}. + */ + public static IProgramMethod getProgramMethod(InitConfig initConfig, Properties properties) + throws IOException { + // Get container class and method signature + String value = properties.getProperty("method"); + if (value == null) { + throw new IOException("Property \"method\" is not defined."); + } + int classMethodSeparator = value.indexOf("#"); + if (classMethodSeparator < 0) { + throw new IOException( + "Property \"method\" does not contain the class method separator \"#\"."); + } + String className = value.substring(0, classMethodSeparator); + String signature = value.substring(classMethodSeparator + 1); + JavaInfo javaInfo = initConfig.getServices().getJavaInfo(); + // Split signature in name and parameter type names + int breaketsStart = signature.indexOf("("); + if (breaketsStart < 0) { + throw new IOException("Method signature \"" + signature + + "\" does not contain required character \"(\"."); + } + int breaketsEnd = signature.lastIndexOf(")"); + if (breaketsEnd < 0) { + throw new IOException("Method signature \"" + signature + + "\" does not contain required character \")\"."); + } + if (breaketsEnd < breaketsStart) { + throw new IOException( + "Method signature has not valid order of chracters \"(\" and \")\"."); + } + String name = signature.substring(0, breaketsStart); + String parameters = signature.substring(breaketsStart + 1, breaketsEnd); + String[] types = parameters.isEmpty() ? new String[0] : parameters.split(","); + // Find container and parameter types + KeYJavaType type = javaInfo.getKeYJavaType(className.trim()); + if (type == null) { + throw new IOException("Can't find type \"" + className + "\"."); + } + ImmutableList parameterTypes = ImmutableSLList.nil(); + for (int i = 0; i < types.length; i++) { + KeYJavaType paramType = javaInfo.getKeYJavaType(types[i].trim()); + if (paramType == null) { + throw new IOException("Can't find type \"" + types[i] + "\"."); + } + parameterTypes = parameterTypes.append(paramType); + } + IProgramMethod pm = javaInfo.getProgramMethod(type, name.trim(), parameterTypes, type); + if (pm == null) { + pm = javaInfo.getConstructor(type, parameterTypes); + if (pm == null) { + throw new IOException("Can't find program method \"" + value + "\"."); + } + } + return pm; + } - /** - * Returns the optional defined precondition. - * @param properties The proof obligation settings to read from. - * @return The precondition or {@code null} if not available. - */ - public static String getPrecondition(Properties properties) { - return properties.getProperty("precondition"); - } + /** + * Returns the optional defined precondition. + * + * @param properties The proof obligation settings to read from. + * @return The precondition or {@code null} if not available. + */ + public static String getPrecondition(Properties properties) { + return properties.getProperty("precondition"); + } @Override - protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, - Term selfTerm, ImmutableList paramTerms, Services services) { + protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, Term selfTerm, + ImmutableList paramTerms, Services services) { // TODO Auto-generated method stub return null; } @@ -395,6 +395,6 @@ protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, */ @Override public KeYJavaType getContainerType() { - return getProgramMethod().getContainerType(); + return getProgramMethod().getContainerType(); } -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodSubsetPO.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodSubsetPO.java index 3ab64a959a7..13b26bbd7ab 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodSubsetPO.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/ProgramMethodSubsetPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.po; import java.io.IOException; @@ -35,30 +38,27 @@ /** *

    - * This proof obligation executes selected statements of the body - * of a given {@link IProgramMethod}. The statements are selected by its - * source location. All statements which ends in the given source range - * ]{@code startPosition}, {@code endPosition}] are executed. + * This proof obligation executes selected statements of the body of a given {@link IProgramMethod}. + * The statements are selected by its source location. All statements which ends in the given source + * range ]{@code startPosition}, {@code endPosition}] are executed. *

    *

    - * To select statements by its end position is required, because KeY's recorder - * includes also leading space and leading comments into a statements position. - * Another drawback is that the end position of the previous statement is - * exactly the start position of the following statement. + * To select statements by its end position is required, because KeY's recorder includes also + * leading space and leading comments into a statements position. Another drawback is that the end + * position of the previous statement is exactly the start position of the following statement. *

    *

    - * Imagine the following snippet: - *

    + * Imagine the following snippet: 
      * int x = 1; // from 3/59 to 4/16
      * int y = 2; // from 4/16 to 5/16
      * int z = 3; // from 5/16 to 6/16
    - * 
    - * To execute only the last two statements a user would select intuitively - * the source range 5/0 to 6/16 (the text without leading white space) which - * matches exactly the used selection definition. + *
    To execute only the last two statements a user would select intuitively the source + * range 5/0 to 6/16 (the text without leading white space) which matches exactly the used selection + * definition. *

    *

    * The generated {@link Sequent} has the following form: + * *

      * 
      * ==>
    @@ -73,347 +73,341 @@
      * 
      * 
    *

    + * * @author Martin Hentschel */ public class ProgramMethodSubsetPO extends ProgramMethodPO { - /** - * Contains all undeclared variables used in the method part to execute. - */ - private UndeclaredProgramVariableCollector undeclaredVariableCollector; + /** + * Contains all undeclared variables used in the method part to execute. + */ + private UndeclaredProgramVariableCollector undeclaredVariableCollector; - /** - * The start position. - */ - private Position startPosition; + /** + * The start position. + */ + private Position startPosition; - /** - * The end position. - */ - private Position endPosition; + /** + * The end position. + */ + private Position endPosition; - /** - * Constructor. - * @param initConfig The {@link InitConfig} to use. - * @param name The name to use. - * @param pm The {@link IProgramMethod} to execute code parts from. - * @param precondition An optional precondition to use. - * @param startPosition The start position. - * @param endPosition The end position. - */ - public ProgramMethodSubsetPO(InitConfig initConfig, - String name, - IProgramMethod pm, - String precondition, - Position startPosition, - Position endPosition) { - super(initConfig, name, pm, precondition); - assert startPosition != null; - assert endPosition != null; - this.startPosition = startPosition; - this.endPosition = endPosition; - } + /** + * Constructor. + * + * @param initConfig The {@link InitConfig} to use. + * @param name The name to use. + * @param pm The {@link IProgramMethod} to execute code parts from. + * @param precondition An optional precondition to use. + * @param startPosition The start position. + * @param endPosition The end position. + */ + public ProgramMethodSubsetPO(InitConfig initConfig, String name, IProgramMethod pm, + String precondition, Position startPosition, Position endPosition) { + super(initConfig, name, pm, precondition); + assert startPosition != null; + assert endPosition != null; + this.startPosition = startPosition; + this.endPosition = endPosition; + } - /** - * Constructor. - * @param initConfig The {@link InitConfig} to use. - * @param name The name to use. - * @param pm The {@link IProgramMethod} to execute code parts from. - * @param precondition An optional precondition to use. - * @param startPosition The start position. - * @param endPosition The end position. - * @param addUninterpretedPredicate {@code true} postcondition contains uninterpreted predicate, {@code false} uninterpreted predicate is not contained in postcondition. - * @param addSymbolicExecutionLabel {@code true} to add the {@link SymbolicExecutionTermLabel} to the modality, {@code false} to not label the modality. - */ - public ProgramMethodSubsetPO(InitConfig initConfig, - String name, - IProgramMethod pm, - String precondition, - Position startPosition, - Position endPosition, - boolean addUninterpretedPredicate, - boolean addSymbolicExecutionLabel) { - super(initConfig, name, pm, precondition, addUninterpretedPredicate, addSymbolicExecutionLabel); - assert startPosition != null; - assert endPosition != null; - this.startPosition = startPosition; - this.endPosition = endPosition; - } + /** + * Constructor. + * + * @param initConfig The {@link InitConfig} to use. + * @param name The name to use. + * @param pm The {@link IProgramMethod} to execute code parts from. + * @param precondition An optional precondition to use. + * @param startPosition The start position. + * @param endPosition The end position. + * @param addUninterpretedPredicate {@code true} postcondition contains uninterpreted predicate, + * {@code false} uninterpreted predicate is not contained in postcondition. + * @param addSymbolicExecutionLabel {@code true} to add the {@link SymbolicExecutionTermLabel} + * to the modality, {@code false} to not label the modality. + */ + public ProgramMethodSubsetPO(InitConfig initConfig, String name, IProgramMethod pm, + String precondition, Position startPosition, Position endPosition, + boolean addUninterpretedPredicate, boolean addSymbolicExecutionLabel) { + super(initConfig, name, pm, precondition, addUninterpretedPredicate, + addSymbolicExecutionLabel); + assert startPosition != null; + assert endPosition != null; + this.startPosition = startPosition; + this.endPosition = endPosition; + } - /** - * {@inheritDoc} - */ - @Override - protected ImmutableList buildOperationBlocks(ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, Services services) { - // Get program method to execute - KeYJavaType type = getCalleeKeYJavaType(); - IProgramMethod pm = getProgramMethod(); - // Extracts code parts of the method - List statementsToExecute = new LinkedList(); - collectStatementsToExecute(statementsToExecute, pm.getBody()); - Statement[] statements = statementsToExecute.toArray(new Statement[statementsToExecute.size()]); - StatementBlock blockToExecute = new StatementBlock(statements); - MethodFrame mf = new MethodFrame(endsWithReturn(statements) ? resultVar : null, - new ExecutionContext(new TypeRef(type), pm, selfVar), - blockToExecute); - StatementBlock result = new StatementBlock(mf); - // Collect undeclared variables - undeclaredVariableCollector = new UndeclaredProgramVariableCollector(result, services); - undeclaredVariableCollector.start(); - // Register undeclared variables - Set undeclaredVariables = undeclaredVariableCollector.result(); - for (LocationVariable x : undeclaredVariables) { - register(x, services); - } - return ImmutableSLList.nil().prepend(null, result, null, null); - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableList buildOperationBlocks( + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + // Get program method to execute + KeYJavaType type = getCalleeKeYJavaType(); + IProgramMethod pm = getProgramMethod(); + // Extracts code parts of the method + List statementsToExecute = new LinkedList(); + collectStatementsToExecute(statementsToExecute, pm.getBody()); + Statement[] statements = + statementsToExecute.toArray(new Statement[statementsToExecute.size()]); + StatementBlock blockToExecute = new StatementBlock(statements); + MethodFrame mf = new MethodFrame(endsWithReturn(statements) ? resultVar : null, + new ExecutionContext(new TypeRef(type), pm, selfVar), blockToExecute); + StatementBlock result = new StatementBlock(mf); + // Collect undeclared variables + undeclaredVariableCollector = new UndeclaredProgramVariableCollector(result, services); + undeclaredVariableCollector.start(); + // Register undeclared variables + Set undeclaredVariables = undeclaredVariableCollector.result(); + for (LocationVariable x : undeclaredVariables) { + register(x, services); + } + return ImmutableSLList.nil().prepend(null, result, null, null); + } - /** - * Collects recursive the {@link Statement}s which are in the given source range - * defined by {@link #startPosition} and {@link #endPosition}. - * @param toFill The result {@link List} to fill. - * @param container The {@link StatementContainer} to seach in. - */ - protected void collectStatementsToExecute(List toFill, StatementContainer container) { - for (int i = 0; i < container.getStatementCount(); i++) { - Statement s = container.getStatementAt(i); - if (s.getEndPosition().compareTo(startPosition) > 0 && - s.getEndPosition().compareTo(endPosition) <= 0) { - // Statement found which ends in the interval ]startPosition, endPosition] - toFill.add(s); - } - else { - // Continue search in children - if (s instanceof StatementContainer) { - collectStatementsToExecute(toFill, (StatementContainer)s); + /** + * Collects recursive the {@link Statement}s which are in the given source range defined by + * {@link #startPosition} and {@link #endPosition}. + * + * @param toFill The result {@link List} to fill. + * @param container The {@link StatementContainer} to seach in. + */ + protected void collectStatementsToExecute(List toFill, + StatementContainer container) { + for (int i = 0; i < container.getStatementCount(); i++) { + Statement s = container.getStatementAt(i); + if (s.getEndPosition().compareTo(startPosition) > 0 + && s.getEndPosition().compareTo(endPosition) <= 0) { + // Statement found which ends in the interval ]startPosition, endPosition] + toFill.add(s); + } else { + // Continue search in children + if (s instanceof StatementContainer) { + collectStatementsToExecute(toFill, (StatementContainer) s); + } else if (s instanceof BranchStatement) { + BranchStatement bs = (BranchStatement) s; + for (int j = 0; j < bs.getBranchCount(); j++) { + Branch branch = bs.getBranchAt(j); + collectStatementsToExecute(toFill, branch); + } + } } - else if (s instanceof BranchStatement) { - BranchStatement bs = (BranchStatement)s; - for (int j = 0; j < bs.getBranchCount(); j++) { - Branch branch = bs.getBranchAt(j); - collectStatementsToExecute(toFill, branch); - } - } - } - } - } + } + } - /** - * Checks if the last statement is a {@link Return} statement. - * @param statements The statements to check. - * @return {@code true} last statement is {@link Return}, {@code false} statements are empty or last statement is something else. - */ - protected boolean endsWithReturn(Statement[] statements) { - if (statements != null && statements.length >= 1) { - return statements[statements.length - 1] instanceof Return; - } - else { - return false; - } - } + /** + * Checks if the last statement is a {@link Return} statement. + * + * @param statements The statements to check. + * @return {@code true} last statement is {@link Return}, {@code false} statements are empty or + * last statement is something else. + */ + protected boolean endsWithReturn(Statement[] statements) { + if (statements != null && statements.length >= 1) { + return statements[statements.length - 1] instanceof Return; + } else { + return false; + } + } - /** - * {@inheritDoc} - */ - @Override - protected Term getPre(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - Map atPreVars, - Services services) { - ImmutableList paramVarsList = convert(undeclaredVariableCollector.result()); - return super.getPre(modHeaps, selfVar, paramVarsList, atPreVars, services); - } + /** + * {@inheritDoc} + */ + @Override + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, + Map atPreVars, Services services) { + ImmutableList paramVarsList = + convert(undeclaredVariableCollector.result()); + return super.getPre(modHeaps, selfVar, paramVarsList, atPreVars, services); + } - /** - * {@inheritDoc} - */ - @Override - protected Term buildFreePre(ProgramVariable selfVar, - KeYJavaType selfKJT, - ImmutableList paramVars, - List heaps, - Services proofServices) { - ImmutableList paramVarsList = convert(undeclaredVariableCollector.result()); - return super.buildFreePre(selfVar, selfKJT, paramVarsList, heaps, proofServices); - } + /** + * {@inheritDoc} + */ + @Override + protected Term buildFreePre(ProgramVariable selfVar, KeYJavaType selfKJT, + ImmutableList paramVars, List heaps, + Services proofServices) { + ImmutableList paramVarsList = + convert(undeclaredVariableCollector.result()); + return super.buildFreePre(selfVar, selfKJT, paramVarsList, heaps, proofServices); + } - /** - * {@inheritDoc} - */ - @Override - protected Term ensureUninterpretedPredicateExists(ImmutableList paramVars, - ImmutableList formalParamVars, - ProgramVariable exceptionVar, - String name, - Services proofServices) { - ImmutableList paramVarsList = convert(undeclaredVariableCollector.result()); - return super.ensureUninterpretedPredicateExists(paramVarsList, formalParamVars, exceptionVar, name, proofServices); - } + /** + * {@inheritDoc} + */ + @Override + protected Term ensureUninterpretedPredicateExists(ImmutableList paramVars, + ImmutableList formalParamVars, ProgramVariable exceptionVar, + String name, Services proofServices) { + ImmutableList paramVarsList = + convert(undeclaredVariableCollector.result()); + return super.ensureUninterpretedPredicateExists(paramVarsList, formalParamVars, + exceptionVar, name, proofServices); + } - /** - * Converts the given {@link Collection} into an {@link ImmutableList}. - * @param c The {@link Collection} to convert. - * @return The created {@link ImmutableList}. - */ - protected static ImmutableList convert(Collection c) { - ImmutableList result = ImmutableSLList.nil(); - for (LocationVariable var : c) { - result = result.append(var); - } - return result; - } + /** + * Converts the given {@link Collection} into an {@link ImmutableList}. + * + * @param c The {@link Collection} to convert. + * @return The created {@link ImmutableList}. + */ + protected static ImmutableList convert(Collection c) { + ImmutableList result = ImmutableSLList.nil(); + for (LocationVariable var : c) { + result = result.append(var); + } + return result; + } - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return super.hashCode() + - (getStartPosition() != null ? getStartPosition().hashCode() : 0) + - (getEndPosition() != null ? getEndPosition().hashCode() : 0); - } + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return super.hashCode() + (getStartPosition() != null ? getStartPosition().hashCode() : 0) + + (getEndPosition() != null ? getEndPosition().hashCode() : 0); + } - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof ProgramMethodSubsetPO) { - ProgramMethodSubsetPO other = (ProgramMethodSubsetPO)obj; - return super.equals(obj) && - ObjectUtil.equals(getStartPosition(), other.getStartPosition()) && - ObjectUtil.equals(getEndPosition(), other.getEndPosition()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ProgramMethodSubsetPO) { + ProgramMethodSubsetPO other = (ProgramMethodSubsetPO) obj; + return super.equals(obj) + && ObjectUtil.equals(getStartPosition(), other.getStartPosition()) + && ObjectUtil.equals(getEndPosition(), other.getEndPosition()); + } else { + return false; + } + } - /** - * Returns the start position. - * @return The start position. - */ - public Position getStartPosition() { - return startPosition; - } + /** + * Returns the start position. + * + * @return The start position. + */ + public Position getStartPosition() { + return startPosition; + } - /** - * Returns the end position. - * @return The end position. - */ - public Position getEndPosition() { - return endPosition; - } + /** + * Returns the end position. + * + * @return The end position. + */ + public Position getEndPosition() { + return endPosition; + } - /** - * {@inheritDoc} - */ - @Override - public void fillSaveProperties(Properties properties) throws IOException { - super.fillSaveProperties(properties); - if (getStartPosition() != null) { - properties.setProperty("startLine", getStartPosition().getLine() + ""); - properties.setProperty("startColumn", getStartPosition().getColumn() + ""); - } - if (getEndPosition() != null) { - properties.setProperty("endLine", getEndPosition().getLine() + ""); - properties.setProperty("endColumn", getEndPosition().getColumn() + ""); - } - } + /** + * {@inheritDoc} + */ + @Override + public void fillSaveProperties(Properties properties) throws IOException { + super.fillSaveProperties(properties); + if (getStartPosition() != null) { + properties.setProperty("startLine", getStartPosition().getLine() + ""); + properties.setProperty("startColumn", getStartPosition().getColumn() + ""); + } + if (getEndPosition() != null) { + properties.setProperty("endLine", getEndPosition().getLine() + ""); + properties.setProperty("endColumn", getEndPosition().getColumn() + ""); + } + } - /** - * Instantiates a new proof obligation with the given settings. - * @param initConfig The already load {@link InitConfig}. - * @param properties The settings of the proof obligation to instantiate. - * @return The instantiated proof obligation. - * @throws IOException Occurred Exception. - */ - public static LoadedPOContainer loadFrom(InitConfig initConfig, Properties properties) throws IOException { - return new LoadedPOContainer(new ProgramMethodSubsetPO(initConfig, - getName(properties), - getProgramMethod(initConfig, properties), - getPrecondition(properties), - getStartPosition(properties), - getEndPosition(properties), - isAddUninterpretedPredicate(properties), - isAddSymbolicExecutionLabel(properties))); - } + /** + * Instantiates a new proof obligation with the given settings. + * + * @param initConfig The already load {@link InitConfig}. + * @param properties The settings of the proof obligation to instantiate. + * @return The instantiated proof obligation. + * @throws IOException Occurred Exception. + */ + public static LoadedPOContainer loadFrom(InitConfig initConfig, Properties properties) + throws IOException { + return new LoadedPOContainer(new ProgramMethodSubsetPO(initConfig, getName(properties), + getProgramMethod(initConfig, properties), getPrecondition(properties), + getStartPosition(properties), getEndPosition(properties), + isAddUninterpretedPredicate(properties), isAddSymbolicExecutionLabel(properties))); + } - /** - * Extracts the start position from the given {@link Properties}. - * @param properties The proof obligation settings to read from. - * @return The defined start {@link Position}. - * @throws IOException Occurred Exception if it was not possible to read the start position. - */ - protected static Position getStartPosition(Properties properties) throws IOException{ - String line = properties.getProperty("startLine"); - if (line == null || line.isEmpty()) { - throw new IOException("Start line property \"startLine\" is not available or empty."); - } - String column = properties.getProperty("startColumn"); - if (column == null || column.isEmpty()) { - throw new IOException("Start column property \"startColumn\" is not available or empty."); - } - int lineValue; - try { - lineValue = Integer.parseInt(line); - } - catch (NumberFormatException e) { - throw new IOException("Start line \"" + line + "\" is no valid integer."); - } - if (lineValue < 0) { - throw new IOException("Start line \"" + line + "\" is a negative integer."); - } - int columnValue; - try { - columnValue = Integer.parseInt(column); - } - catch (NumberFormatException e) { - throw new IOException("Start column \"" + column + "\" is no valid integer."); - } - if (columnValue < 0) { - throw new IOException("Start column \"" + column + "\" is a negative integer."); - } - return new Position(lineValue, columnValue); - } + /** + * Extracts the start position from the given {@link Properties}. + * + * @param properties The proof obligation settings to read from. + * @return The defined start {@link Position}. + * @throws IOException Occurred Exception if it was not possible to read the start position. + */ + protected static Position getStartPosition(Properties properties) throws IOException { + String line = properties.getProperty("startLine"); + if (line == null || line.isEmpty()) { + throw new IOException("Start line property \"startLine\" is not available or empty."); + } + String column = properties.getProperty("startColumn"); + if (column == null || column.isEmpty()) { + throw new IOException( + "Start column property \"startColumn\" is not available or empty."); + } + int lineValue; + try { + lineValue = Integer.parseInt(line); + } catch (NumberFormatException e) { + throw new IOException("Start line \"" + line + "\" is no valid integer."); + } + if (lineValue < 0) { + throw new IOException("Start line \"" + line + "\" is a negative integer."); + } + int columnValue; + try { + columnValue = Integer.parseInt(column); + } catch (NumberFormatException e) { + throw new IOException("Start column \"" + column + "\" is no valid integer."); + } + if (columnValue < 0) { + throw new IOException("Start column \"" + column + "\" is a negative integer."); + } + return new Position(lineValue, columnValue); + } - /** - * Extracts the end position from the given {@link Properties}. - * @param properties The proof obligation settings to read from. - * @return The defined end {@link Position}. - * @throws IOException Occurred Exception if it was not possible to read the end position. - */ - protected static Position getEndPosition(Properties properties) throws IOException { - String line = properties.getProperty("endLine"); - if (line == null || line.isEmpty()) { - throw new IOException("End line property \"endLine\" is not available or empty."); - } - String column = properties.getProperty("endColumn"); - if (column == null || column.isEmpty()) { - throw new IOException("End column property \"endColumn\" is not available or empty."); - } - int lineValue; - try { - lineValue = Integer.parseInt(line); - } - catch (NumberFormatException e) { - throw new IOException("End line \"" + line + "\" is no valid integer."); - } - if (lineValue < 0) { - throw new IOException("End line \"" + line + "\" is a negative integer."); - } - int columnValue; - try { - columnValue = Integer.parseInt(column); - } - catch (NumberFormatException e) { - throw new IOException("End column \"" + column + "\" is no valid integer."); - } - if (columnValue < 0) { - throw new IOException("End column \"" + column + "\" is a negative integer."); - } - return new Position(lineValue, columnValue); - } -} \ No newline at end of file + /** + * Extracts the end position from the given {@link Properties}. + * + * @param properties The proof obligation settings to read from. + * @return The defined end {@link Position}. + * @throws IOException Occurred Exception if it was not possible to read the end position. + */ + protected static Position getEndPosition(Properties properties) throws IOException { + String line = properties.getProperty("endLine"); + if (line == null || line.isEmpty()) { + throw new IOException("End line property \"endLine\" is not available or empty."); + } + String column = properties.getProperty("endColumn"); + if (column == null || column.isEmpty()) { + throw new IOException("End column property \"endColumn\" is not available or empty."); + } + int lineValue; + try { + lineValue = Integer.parseInt(line); + } catch (NumberFormatException e) { + throw new IOException("End line \"" + line + "\" is no valid integer."); + } + if (lineValue < 0) { + throw new IOException("End line \"" + line + "\" is a negative integer."); + } + int columnValue; + try { + columnValue = Integer.parseInt(column); + } catch (NumberFormatException e) { + throw new IOException("End column \"" + column + "\" is no valid integer."); + } + if (columnValue < 0) { + throw new IOException("End column \"" + column + "\" is a negative integer."); + } + return new Position(lineValue, columnValue); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/TruthValuePOExtension.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/TruthValuePOExtension.java index f7f0ba32483..69ef8f88cc5 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/TruthValuePOExtension.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/po/TruthValuePOExtension.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.po; import org.key_project.util.collection.ImmutableArray; @@ -16,64 +19,67 @@ /** * Implementation of {@link POExtension} to support truth value evaluation. + * * @author Martin Hentschel */ public class TruthValuePOExtension implements POExtension { - /** - * {@inheritDoc} - */ - @Override - public boolean isPOSupported(ProofOblInput po) { - return po instanceof AbstractOperationPO; - } - - /** - * {@inheritDoc} - */ - @Override - public Term modifyPostTerm(InitConfig proofConfig, Services services, Term postTerm) { - if (SymbolicExecutionJavaProfile.isTruthValueEvaluationEnabled(proofConfig)) { - return labelPostTerm(services, postTerm); - } - else { - return postTerm; - } - } - - /** - * Labels all predicates in the given {@link Term} and its children with - * a {@link FormulaTermLabel}. - * @param services The {@link Services} to use. - * @param term The {@link Term} to label. - * @return The labeled {@link Term}. - */ - protected Term labelPostTerm(Services services, Term term) { - if (term != null) { - final TermFactory tf = services.getTermFactory(); - // Label children of operator - if (TruthValueTracingUtil.isLogicOperator(term)) { - Term[] newSubs = new Term[term.arity()]; - boolean subsChanged = false; - for (int i = 0; i < newSubs.length; i++) { - Term oldTerm = term.sub(i); - newSubs[i] = labelPostTerm(services, oldTerm); - if (oldTerm != newSubs[i]) { - subsChanged = true; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isPOSupported(ProofOblInput po) { + return po instanceof AbstractOperationPO; + } + + /** + * {@inheritDoc} + */ + @Override + public Term modifyPostTerm(InitConfig proofConfig, Services services, Term postTerm) { + if (SymbolicExecutionJavaProfile.isTruthValueEvaluationEnabled(proofConfig)) { + return labelPostTerm(services, postTerm); + } else { + return postTerm; + } + } + + /** + * Labels all predicates in the given {@link Term} and its children with a + * {@link FormulaTermLabel}. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to label. + * @return The labeled {@link Term}. + */ + protected Term labelPostTerm(Services services, Term term) { + if (term != null) { + final TermFactory tf = services.getTermFactory(); + // Label children of operator + if (TruthValueTracingUtil.isLogicOperator(term)) { + Term[] newSubs = new Term[term.arity()]; + boolean subsChanged = false; + for (int i = 0; i < newSubs.length; i++) { + Term oldTerm = term.sub(i); + newSubs[i] = labelPostTerm(services, oldTerm); + if (oldTerm != newSubs[i]) { + subsChanged = true; + } + } + term = subsChanged + ? tf.createTerm(term.op(), new ImmutableArray(newSubs), + term.boundVars(), term.javaBlock(), term.getLabels()) + : term; } - term = subsChanged ? - tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), term.getLabels()) : - term; - } - ImmutableArray oldLabels = term.getLabels(); - TermLabel[] newLabels = oldLabels.toArray(new TermLabel[oldLabels.size() + 1]); - int labelID = services.getCounter(FormulaTermLabel.PROOF_COUNTER_NAME).getCountPlusPlus(); - int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); - newLabels[oldLabels.size()] = new FormulaTermLabel(labelID, labelSubID); - return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock(), new ImmutableArray(newLabels)); - } - else { - return null; - } - } + ImmutableArray oldLabels = term.getLabels(); + TermLabel[] newLabels = oldLabels.toArray(new TermLabel[oldLabels.size() + 1]); + int labelID = + services.getCounter(FormulaTermLabel.PROOF_COUNTER_NAME).getCountPlusPlus(); + int labelSubID = FormulaTermLabel.newLabelSubID(services, labelID); + newLabels[oldLabels.size()] = new FormulaTermLabel(labelID, labelSubID); + return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock(), + new ImmutableArray(newLabels)); + } else { + return null; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SimplifyTermProfile.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SimplifyTermProfile.java index c57861b5eb0..e43505c9878 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SimplifyTermProfile.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SimplifyTermProfile.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.profile; import org.key_project.util.collection.DefaultImmutableSet; @@ -29,106 +32,102 @@ /** * An extended {@link JavaProfile} used in side proofs to simplify a {@link Term}. + * * @author Martin Hentschel */ public class SimplifyTermProfile extends JavaProfile { - /** - * The {@link Name} of this {@link Profile}. - */ - public static final String NAME = "Java Profile for Term Simplification"; - - /** - * The used {@link StrategyFactory} of the {@link SymbolicExecutionStrategy}. - */ - private final static StrategyFactory SIDE_PROOF_FACTORY = new SimplifyTermStrategy.Factory(); - - /** - *

    - * The default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - */ - public static SimplifyTermProfile defaultInstance; + /** + * The {@link Name} of this {@link Profile}. + */ + public static final String NAME = "Java Profile for Term Simplification"; - /** - * Constructor. - */ - public SimplifyTermProfile() { - } + /** + * The used {@link StrategyFactory} of the {@link SymbolicExecutionStrategy}. + */ + private final static StrategyFactory SIDE_PROOF_FACTORY = new SimplifyTermStrategy.Factory(); - /** - * {@inheritDoc} - */ - @Override - protected ImmutableList computeTermLabelConfiguration() { - ImmutableList result = super.computeTermLabelConfiguration(); - ImmutableList symExcPolicies = ImmutableSLList.nil().prepend(new TermLabelPolicy() { - @Override - public TermLabel keepLabel(TermLabelState state, Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, Object hint, - Term tacletTerm, Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, ImmutableArray newTermOriginalLabels, TermLabel label) { - return label; - } - }); - result = result.prepend(new TermLabelConfiguration(SymbolicExecutionUtil.RESULT_LABEL_NAME, - new SingletonLabelFactory(SymbolicExecutionUtil.RESULT_LABEL), - null, - symExcPolicies, - null, - null, - null, - null, - null)); - return result; - } + /** + *

    + * The default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + */ + public static SimplifyTermProfile defaultInstance; - /** - * {@inheritDoc} - */ - @Override - protected ImmutableSet getStrategyFactories() { - return DefaultImmutableSet.nil().add(SIDE_PROOF_FACTORY); - } + /** + * Constructor. + */ + public SimplifyTermProfile() {} - /** - * {@inheritDoc} - */ - @Override - public StrategyFactory getDefaultStrategyFactory() { - return SIDE_PROOF_FACTORY; - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableList computeTermLabelConfiguration() { + ImmutableList result = super.computeTermLabelConfiguration(); + ImmutableList symExcPolicies = + ImmutableSLList.nil().prepend(new TermLabelPolicy() { + @Override + public TermLabel keepLabel(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, + Rule rule, Goal goal, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, + ImmutableArray newTermOriginalLabels, TermLabel label) { + return label; + } + }); + result = result.prepend(new TermLabelConfiguration(SymbolicExecutionUtil.RESULT_LABEL_NAME, + new SingletonLabelFactory(SymbolicExecutionUtil.RESULT_LABEL), null, + symExcPolicies, null, null, null, null, null)); + return result; + } - /** - * {@inheritDoc} - */ - @Override - public String name() { - return NAME; - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableSet getStrategyFactories() { + return DefaultImmutableSet.nil().add(SIDE_PROOF_FACTORY); + } - /** - *

    - * Returns the default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - * @return The default instance for usage in the {@link Thread} of the user interface. - */ - public static synchronized SimplifyTermProfile getDefaultInstance() { - if (defaultInstance == null) { - defaultInstance = new SimplifyTermProfile(); - } - return defaultInstance; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public StrategyFactory getDefaultStrategyFactory() { + return SIDE_PROOF_FACTORY; + } + + /** + * {@inheritDoc} + */ + @Override + public String name() { + return NAME; + } + + /** + *

    + * Returns the default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + * + * @return The default instance for usage in the {@link Thread} of the user interface. + */ + public static synchronized SimplifyTermProfile getDefaultInstance() { + if (defaultInstance == null) { + defaultInstance = new SimplifyTermProfile(); + } + return defaultInstance; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfile.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfile.java index 980bbb26852..18bd19b3dd9 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfile.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfile.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.profile; import org.key_project.util.collection.ImmutableList; @@ -43,276 +46,283 @@ /** * An extended {@link JavaProfile} used by the symbolic execution API. + * * @author Martin Hentschel */ public class SymbolicExecutionJavaProfile extends JavaProfile { - /** - * The {@link Name} of this {@link Profile}. - */ - public static final String NAME = "Java Profile for Symbolic Execution"; - - /** - * The used {@link StrategyFactory} of the {@link SymbolicExecutionStrategy}. - */ - private final static StrategyFactory SYMBOLIC_EXECUTION_FACTORY = new SymbolicExecutionStrategy.Factory(); - - /** - * {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - */ - private final Boolean truthValueEvaluationEnabled; - - /** - *

    - * The default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - */ - public static SymbolicExecutionJavaProfile defaultInstance; - - /** - *

    - * The default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - */ - public static SymbolicExecutionJavaProfile defaultInstanceWithTruthValueEvaluation; + /** + * The {@link Name} of this {@link Profile}. + */ + public static final String NAME = "Java Profile for Symbolic Execution"; - /** - * Constructor. - * @param predicateEvaluationEnabled {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is disabled. - */ - public SymbolicExecutionJavaProfile(boolean predicateEvaluationEnabled) { - this.truthValueEvaluationEnabled = predicateEvaluationEnabled; - initTermLabelManager(); - } + /** + * The used {@link StrategyFactory} of the {@link SymbolicExecutionStrategy}. + */ + private final static StrategyFactory SYMBOLIC_EXECUTION_FACTORY = + new SymbolicExecutionStrategy.Factory(); - /** - * {@inheritDoc} - */ - @Override - protected ImmutableSet computeSupportedGoalChooserBuilder() { - return super.computeSupportedGoalChooserBuilder().add(new SymbolicExecutionGoalChooserBuilder()); - } + /** + * {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is + * disabled. + */ + private final Boolean truthValueEvaluationEnabled; - /** - * {@inheritDoc} - */ - @Override - protected void initTermLabelManager() { - if (truthValueEvaluationEnabled != null) { - // Create TermLabelManager only after predicate evaluation enabled flag is set. - super.initTermLabelManager(); - } - } + /** + *

    + * The default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + */ + public static SymbolicExecutionJavaProfile defaultInstance; - /** - * {@inheritDoc} - */ - @Override - protected ImmutableList computeTermLabelConfiguration() { - ImmutableList result = super.computeTermLabelConfiguration(); - result = result.prepend(getSymbolicExecutionTermLabelConfigurations(truthValueEvaluationEnabled)); - return result; - } + /** + *

    + * The default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + */ + public static SymbolicExecutionJavaProfile defaultInstanceWithTruthValueEvaluation; - /** - * Returns the additional {@link TermLabelFactory} instances used for symbolic execution. - * @param predicateEvaluationEnabled {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is disabled. - * @return The additional {@link TermLabelFactory} instances used for symbolic execution. - */ - public static ImmutableList getSymbolicExecutionTermLabelConfigurations(boolean predicateEvaluationEnabled) { - ImmutableList symExcPolicies = ImmutableSLList.nil().prepend(new StayOnOperatorTermLabelPolicy()); + /** + * Constructor. + * + * @param predicateEvaluationEnabled {@code true} predicate evaluation is enabled, {@code false} + * predicate evaluation is disabled. + */ + public SymbolicExecutionJavaProfile(boolean predicateEvaluationEnabled) { + this.truthValueEvaluationEnabled = predicateEvaluationEnabled; + initTermLabelManager(); + } - ImmutableList bcUps = ImmutableSLList.nil().prepend(new BlockContractValidityTermLabelUpdate()); - ImmutableList lbUps = ImmutableSLList.nil().prepend(new LoopBodyTermLabelUpdate()); - ImmutableList nbUps = ImmutableSLList.nil().prepend(new LoopInvariantNormalBehaviorTermLabelUpdate()); - ImmutableList seUps = ImmutableSLList.nil().prepend(new SymbolicExecutionTermLabelUpdate()); + /** + * {@inheritDoc} + */ + @Override + protected ImmutableSet computeSupportedGoalChooserBuilder() { + return super.computeSupportedGoalChooserBuilder() + .add(new SymbolicExecutionGoalChooserBuilder()); + } - ImmutableList bcRefs = ImmutableSLList.nil().prepend(new RemoveInCheckBranchesTermLabelRefactoring(BlockContractValidityTermLabel.NAME)); - ImmutableList lbRefs = ImmutableSLList.nil().prepend(new RemoveInCheckBranchesTermLabelRefactoring(SymbolicExecutionUtil.LOOP_BODY_LABEL_NAME)); - ImmutableList nbRefs = ImmutableSLList.nil().prepend(new RemoveInCheckBranchesTermLabelRefactoring(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME)); - ImmutableList seRefs = ImmutableSLList.nil().prepend(new RemoveInCheckBranchesTermLabelRefactoring(SymbolicExecutionTermLabel.NAME)); - - ImmutableList result = ImmutableSLList.nil(); - result = result.prepend(new TermLabelConfiguration(BlockContractValidityTermLabel.NAME, - new BlockContractValidityTermLabelFactory(), - null, - symExcPolicies, - null, - null, - bcUps, - bcRefs, - null)); - result = result.prepend(new TermLabelConfiguration(SymbolicExecutionUtil.LOOP_BODY_LABEL_NAME, - new SingletonLabelFactory(SymbolicExecutionUtil.LOOP_BODY_LABEL), - null, - symExcPolicies, - null, - null, - lbUps, - lbRefs, - null)); - result = result.prepend(new TermLabelConfiguration(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME, - new SingletonLabelFactory(SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL), - null, - symExcPolicies, - null, - null, - nbUps, - nbRefs, - null)); - result = result.prepend(new TermLabelConfiguration(SymbolicExecutionTermLabel.NAME, - new SymbolicExecutionTermLabelFactory(), - null, - symExcPolicies, - null, - null, - seUps, - seRefs, - null)); - if (predicateEvaluationEnabled) { - ImmutableList predPolicies = ImmutableSLList.nil().prepend(new StayOnFormulaTermLabelPolicy()); - ImmutableList predUpdates = ImmutableSLList.nil().prepend(new FormulaTermLabelUpdate()); - ImmutableList predRefs = ImmutableSLList.nil().prepend(new FormulaTermLabelRefactoring()); - result = result.prepend(new TermLabelConfiguration(FormulaTermLabel.NAME, - new FormulaTermLabelFactory(), - null, - predPolicies, - null, - null, - predUpdates, - predRefs, - new FormulaTermLabelMerger())); - } - return result; - } + /** + * {@inheritDoc} + */ + @Override + protected void initTermLabelManager() { + if (truthValueEvaluationEnabled != null) { + // Create TermLabelManager only after predicate evaluation enabled flag is set. + super.initTermLabelManager(); + } + } - /** - * {@inheritDoc} - */ - @Override - protected ImmutableSet getStrategyFactories() { - ImmutableSet set = super.getStrategyFactories(); - set = set.add(SYMBOLIC_EXECUTION_FACTORY); - return set; - } - - /** - * {@inheritDoc} - */ - @Override - protected ImmutableList initBuiltInRules() { - ImmutableList builtInRules = super.initBuiltInRules(); - builtInRules = builtInRules.prepend(QuerySideProofRule.INSTANCE); - builtInRules = builtInRules.prepend(ModalitySideProofRule.INSTANCE); - return builtInRules; - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableList computeTermLabelConfiguration() { + ImmutableList result = super.computeTermLabelConfiguration(); + result = result + .prepend(getSymbolicExecutionTermLabelConfigurations(truthValueEvaluationEnabled)); + return result; + } - /** - * {@inheritDoc} - */ - @Override - public String name() { - return NAME; - } + /** + * Returns the additional {@link TermLabelFactory} instances used for symbolic execution. + * + * @param predicateEvaluationEnabled {@code true} predicate evaluation is enabled, {@code false} + * predicate evaluation is disabled. + * @return The additional {@link TermLabelFactory} instances used for symbolic execution. + */ + public static ImmutableList getSymbolicExecutionTermLabelConfigurations( + boolean predicateEvaluationEnabled) { + ImmutableList symExcPolicies = + ImmutableSLList.nil().prepend(new StayOnOperatorTermLabelPolicy()); - /** - * Checks if predicate evaluation is enabled or not. - * @return {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is disabled. - */ - public boolean isPredicateEvaluationEnabled() { - return truthValueEvaluationEnabled; - } + ImmutableList bcUps = ImmutableSLList.nil() + .prepend(new BlockContractValidityTermLabelUpdate()); + ImmutableList lbUps = + ImmutableSLList.nil().prepend(new LoopBodyTermLabelUpdate()); + ImmutableList nbUps = ImmutableSLList.nil() + .prepend(new LoopInvariantNormalBehaviorTermLabelUpdate()); + ImmutableList seUps = ImmutableSLList.nil() + .prepend(new SymbolicExecutionTermLabelUpdate()); - /** - *

    - * Returns the default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - * @return The default instance for usage in the {@link Thread} of the user interface. - */ - public static synchronized SymbolicExecutionJavaProfile getDefaultInstance() { - return getDefaultInstance(false); - } + ImmutableList bcRefs = ImmutableSLList.nil() + .prepend(new RemoveInCheckBranchesTermLabelRefactoring( + BlockContractValidityTermLabel.NAME)); + ImmutableList lbRefs = ImmutableSLList.nil() + .prepend(new RemoveInCheckBranchesTermLabelRefactoring( + SymbolicExecutionUtil.LOOP_BODY_LABEL_NAME)); + ImmutableList nbRefs = ImmutableSLList.nil() + .prepend(new RemoveInCheckBranchesTermLabelRefactoring( + SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME)); + ImmutableList seRefs = ImmutableSLList.nil() + .prepend(new RemoveInCheckBranchesTermLabelRefactoring( + SymbolicExecutionTermLabel.NAME)); - /** - *

    - * Returns the default instance of this class. - *

    - *

    - * It is typically used in the {@link Thread} of the user interface. - * Other instances of this class are typically only required to - * use them in different {@link Thread}s (not the UI {@link Thread}). - *

    - * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - * @return The default instance for usage in the {@link Thread} of the user interface. - */ - public static synchronized SymbolicExecutionJavaProfile getDefaultInstance(boolean truthValueEvaluationEnabled) { - if (!truthValueEvaluationEnabled) { - if (defaultInstance == null) { - defaultInstance = new SymbolicExecutionJavaProfile(false); - } - return defaultInstance; - } - else { - if (defaultInstanceWithTruthValueEvaluation == null) { - defaultInstanceWithTruthValueEvaluation = new SymbolicExecutionJavaProfile(true); - } - return defaultInstanceWithTruthValueEvaluation; - } - } + ImmutableList result = ImmutableSLList.nil(); + result = result.prepend(new TermLabelConfiguration(BlockContractValidityTermLabel.NAME, + new BlockContractValidityTermLabelFactory(), null, symExcPolicies, null, null, + bcUps, bcRefs, null)); + result = result + .prepend(new TermLabelConfiguration(SymbolicExecutionUtil.LOOP_BODY_LABEL_NAME, + new SingletonLabelFactory(SymbolicExecutionUtil.LOOP_BODY_LABEL), + null, symExcPolicies, null, null, lbUps, lbRefs, null)); + result = result.prepend(new TermLabelConfiguration( + SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME, + new SingletonLabelFactory( + SymbolicExecutionUtil.LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL), + null, symExcPolicies, null, null, nbUps, nbRefs, null)); + result = result.prepend(new TermLabelConfiguration(SymbolicExecutionTermLabel.NAME, + new SymbolicExecutionTermLabelFactory(), null, symExcPolicies, null, null, seUps, + seRefs, null)); + if (predicateEvaluationEnabled) { + ImmutableList predPolicies = ImmutableSLList.nil() + .prepend(new StayOnFormulaTermLabelPolicy()); + ImmutableList predUpdates = + ImmutableSLList.nil().prepend(new FormulaTermLabelUpdate()); + ImmutableList predRefs = ImmutableSLList + .nil().prepend(new FormulaTermLabelRefactoring()); + result = result.prepend(new TermLabelConfiguration(FormulaTermLabel.NAME, + new FormulaTermLabelFactory(), null, predPolicies, null, null, predUpdates, + predRefs, new FormulaTermLabelMerger())); + } + return result; + } - /** - * Checks if truth value evaluation is enabled in the given {@link Proof}. - * @param proof The {@link Proof} to check. - * @return {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - */ - public static boolean isTruthValueTracingEnabled(Proof proof) { - if (proof != null && !proof.isDisposed()) { - return isTruthValueEvaluationEnabled(proof.getInitConfig()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableSet getStrategyFactories() { + ImmutableSet set = super.getStrategyFactories(); + set = set.add(SYMBOLIC_EXECUTION_FACTORY); + return set; + } - /** - * Checks if truth value evaluation is enabled in the given {@link InitConfig}. - * @param initConfig The {@link InitConfig} to check. - * @return {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - */ - public static boolean isTruthValueEvaluationEnabled(InitConfig initConfig) { - if (initConfig != null) { - return isTruthValueEvaluationEnabled(initConfig.getProfile()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + protected ImmutableList initBuiltInRules() { + ImmutableList builtInRules = super.initBuiltInRules(); + builtInRules = builtInRules.prepend(QuerySideProofRule.INSTANCE); + builtInRules = builtInRules.prepend(ModalitySideProofRule.INSTANCE); + return builtInRules; + } - /** - * Checks if predicate evaluation is enabled in the given {@link Profile}. - * @param profile The {@link Profile} to check. - * @return {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is disabled. - */ - public static boolean isTruthValueEvaluationEnabled(Profile profile) { - if (profile instanceof SymbolicExecutionJavaProfile) { - return ((SymbolicExecutionJavaProfile) profile).isPredicateEvaluationEnabled(); - } - else { - return false; - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String name() { + return NAME; + } + + /** + * Checks if predicate evaluation is enabled or not. + * + * @return {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is + * disabled. + */ + public boolean isPredicateEvaluationEnabled() { + return truthValueEvaluationEnabled; + } + + /** + *

    + * Returns the default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + * + * @return The default instance for usage in the {@link Thread} of the user interface. + */ + public static synchronized SymbolicExecutionJavaProfile getDefaultInstance() { + return getDefaultInstance(false); + } + + /** + *

    + * Returns the default instance of this class. + *

    + *

    + * It is typically used in the {@link Thread} of the user interface. Other instances of this + * class are typically only required to use them in different {@link Thread}s (not the UI + * {@link Thread}). + *

    + * + * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, + * {@code false} truth value evaluation is disabled. + * @return The default instance for usage in the {@link Thread} of the user interface. + */ + public static synchronized SymbolicExecutionJavaProfile getDefaultInstance( + boolean truthValueEvaluationEnabled) { + if (!truthValueEvaluationEnabled) { + if (defaultInstance == null) { + defaultInstance = new SymbolicExecutionJavaProfile(false); + } + return defaultInstance; + } else { + if (defaultInstanceWithTruthValueEvaluation == null) { + defaultInstanceWithTruthValueEvaluation = new SymbolicExecutionJavaProfile(true); + } + return defaultInstanceWithTruthValueEvaluation; + } + } + + /** + * Checks if truth value evaluation is enabled in the given {@link Proof}. + * + * @param proof The {@link Proof} to check. + * @return {@code true} truth value evaluation is enabled, {@code false} truth value evaluation + * is disabled. + */ + public static boolean isTruthValueTracingEnabled(Proof proof) { + if (proof != null && !proof.isDisposed()) { + return isTruthValueEvaluationEnabled(proof.getInitConfig()); + } else { + return false; + } + } + + /** + * Checks if truth value evaluation is enabled in the given {@link InitConfig}. + * + * @param initConfig The {@link InitConfig} to check. + * @return {@code true} truth value evaluation is enabled, {@code false} truth value evaluation + * is disabled. + */ + public static boolean isTruthValueEvaluationEnabled(InitConfig initConfig) { + if (initConfig != null) { + return isTruthValueEvaluationEnabled(initConfig.getProfile()); + } else { + return false; + } + } + + /** + * Checks if predicate evaluation is enabled in the given {@link Profile}. + * + * @param profile The {@link Profile} to check. + * @return {@code true} predicate evaluation is enabled, {@code false} predicate evaluation is + * disabled. + */ + public static boolean isTruthValueEvaluationEnabled(Profile profile) { + if (profile instanceof SymbolicExecutionJavaProfile) { + return ((SymbolicExecutionJavaProfile) profile).isPredicateEvaluationEnabled(); + } else { + return false; + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfileDefaultProfileResolver.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfileDefaultProfileResolver.java index 25828bdf414..11572df1a0c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfileDefaultProfileResolver.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/profile/SymbolicExecutionJavaProfileDefaultProfileResolver.java @@ -1,26 +1,31 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.profile; import de.uka.ilkd.key.proof.init.DefaultProfileResolver; import de.uka.ilkd.key.proof.init.Profile; /** - * A {@link DefaultProfileResolver} which returns {@link SymbolicExecutionJavaProfile#getDefaultInstance()}. + * A {@link DefaultProfileResolver} which returns + * {@link SymbolicExecutionJavaProfile#getDefaultInstance()}. + * * @author Martin Hentschel */ public class SymbolicExecutionJavaProfileDefaultProfileResolver implements DefaultProfileResolver { - /** - * {@inheritDoc} - */ - @Override - public String getProfileName() { - return SymbolicExecutionJavaProfile.NAME; - } + /** + * {@inheritDoc} + */ + @Override + public String getProfileName() { + return SymbolicExecutionJavaProfile.NAME; + } - /** - * {@inheritDoc} - */ - @Override - public Profile getDefaultProfile() { - return SymbolicExecutionJavaProfile.getDefaultInstance(); - } + /** + * {@inheritDoc} + */ + @Override + public Profile getDefaultProfile() { + return SymbolicExecutionJavaProfile.getDefaultInstance(); + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java index 0d78d164ac7..0d1d26eddef 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.rule; import java.util.Deque; @@ -27,106 +30,105 @@ import de.uka.ilkd.key.util.Triple; /** - * Provides the basic functionality of {@link BuiltInRule} which - * computes something in a side proof. + * Provides the basic functionality of {@link BuiltInRule} which computes something in a side proof. + * * @author Martin Hentschel */ public abstract class AbstractSideProofRule implements BuiltInRule { - /** - *

    - * Creates a constant which is used in the original {@link Proof} to - * store the computed result in form of {@code QueryResult = ...} - *

    - *

    - * The used name is registered in the {@link Namespace} of the {@link Services}. - *

    - * @param services The {@link Services} to use- - * @param sort The {@link Sort} to use. - * @return The created constant. - */ - protected Function createResultConstant(Services services, Sort sort) { - String functionName = services.getTermBuilder().newName("QueryResult"); - Function function = new Function(new Name(functionName), sort); - services.getNamespaces().functions().addSafely(function); - return function; - } - - /** - * Creates the result {@link Function} used in a predicate to compute the result in the side proof. - * @param services The {@link Services} to use. - * @param sort The {@link Sort} to use. - * @return The created result {@link Function}. - */ - protected Function createResultFunction(Services services, Sort sort) { - return new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, sort); - } - - /** - *

    - * Starts the side proof and extracts the result {@link Term} and conditions. - *

    - *

    - * New used names are automatically added to the {@link Namespace} of the {@link Services}. - *

    - * @param services The {@link Services} to use. - * @param goal The {@link Goal} on which this {@link BuiltInRule} should be applied on. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to prove in a side proof. - * @param newPredicate The {@link Function} which is used to compute the result. - * @return The found result {@link Term} and the conditions. - * @throws ProofInputException Occurred Exception. - */ - protected List, Node>> computeResultsAndConditions(Services services, - Goal goal, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - Function newPredicate) throws ProofInputException { - return SymbolicExecutionSideProofUtil.computeResultsAndConditions(services, - goal.proof(), - sideProofEnvironment, - sequentToProve, - newPredicate, - "Side proof rule on node " + goal.node().serialNr() + ".", - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_DELAYED, - true); - } - - /** - * Replaces the {@link Term} defined by the given {@link PosInOccurrence} - * with the given new {@link Term}. - * @param pio The {@link PosInOccurrence} which defines the {@link Term} to replace. - * @param newTerm The new {@link Term}. - * @return The created {@link SequentFormula} in which the {@link Term} is replaced. - */ - protected static SequentFormula replace(PosInOccurrence pio, Term newTerm, Services services) { - // Iterate along the PosInOccurrence and collect the parents and indices - Deque> indexAndParents = new LinkedList>(); - Term root = pio.sequentFormula().formula(); - final PosInTerm pit = pio.posInTerm(); - for (int i = 0, sz=pit.depth(); i(Integer.valueOf(next), root)); - root = root.sub(next); - } - // Iterate over the collected parents and replace terms - root = newTerm; - for (Pair pair : indexAndParents) { - Term parent = pair.second; - Term[] newSubs = parent.subs().toArray(new Term[parent.arity()]); - newSubs[pair.first] = root; - root = services.getTermFactory().createTerm(parent.op(), newSubs, parent.boundVars(), parent.javaBlock(), parent.getLabels()); - } - return new SequentFormula(root); - } + /** + *

    + * Creates a constant which is used in the original {@link Proof} to store the computed result + * in form of {@code QueryResult = ...} + *

    + *

    + * The used name is registered in the {@link Namespace} of the {@link Services}. + *

    + * + * @param services The {@link Services} to use- + * @param sort The {@link Sort} to use. + * @return The created constant. + */ + protected Function createResultConstant(Services services, Sort sort) { + String functionName = services.getTermBuilder().newName("QueryResult"); + Function function = new Function(new Name(functionName), sort); + services.getNamespaces().functions().addSafely(function); + return function; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicableOnSubTerms() { - return false; - } -} \ No newline at end of file + /** + * Creates the result {@link Function} used in a predicate to compute the result in the side + * proof. + * + * @param services The {@link Services} to use. + * @param sort The {@link Sort} to use. + * @return The created result {@link Function}. + */ + protected Function createResultFunction(Services services, Sort sort) { + return new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), + Sort.FORMULA, sort); + } + + /** + *

    + * Starts the side proof and extracts the result {@link Term} and conditions. + *

    + *

    + * New used names are automatically added to the {@link Namespace} of the {@link Services}. + *

    + * + * @param services The {@link Services} to use. + * @param goal The {@link Goal} on which this {@link BuiltInRule} should be applied on. + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to prove in a side proof. + * @param newPredicate The {@link Function} which is used to compute the result. + * @return The found result {@link Term} and the conditions. + * @throws ProofInputException Occurred Exception. + */ + protected List, Node>> computeResultsAndConditions(Services services, + Goal goal, ProofEnvironment sideProofEnvironment, Sequent sequentToProve, + Function newPredicate) throws ProofInputException { + return SymbolicExecutionSideProofUtil.computeResultsAndConditions(services, goal.proof(), + sideProofEnvironment, sequentToProve, newPredicate, + "Side proof rule on node " + goal.node().serialNr() + ".", + StrategyProperties.METHOD_CONTRACT, StrategyProperties.LOOP_INVARIANT, + StrategyProperties.QUERY_ON, StrategyProperties.SPLITTING_DELAYED, true); + } + + /** + * Replaces the {@link Term} defined by the given {@link PosInOccurrence} with the given new + * {@link Term}. + * + * @param pio The {@link PosInOccurrence} which defines the {@link Term} to replace. + * @param newTerm The new {@link Term}. + * @return The created {@link SequentFormula} in which the {@link Term} is replaced. + */ + protected static SequentFormula replace(PosInOccurrence pio, Term newTerm, Services services) { + // Iterate along the PosInOccurrence and collect the parents and indices + Deque> indexAndParents = new LinkedList>(); + Term root = pio.sequentFormula().formula(); + final PosInTerm pit = pio.posInTerm(); + for (int i = 0, sz = pit.depth(); i < sz; i++) { + int next = pit.getIndexAt(i); + indexAndParents.addFirst(new Pair(Integer.valueOf(next), root)); + root = root.sub(next); + } + // Iterate over the collected parents and replace terms + root = newTerm; + for (Pair pair : indexAndParents) { + Term parent = pair.second; + Term[] newSubs = parent.subs().toArray(new Term[parent.arity()]); + newSubs[pair.first] = root; + root = services.getTermFactory().createTerm(parent.op(), newSubs, parent.boundVars(), + parent.javaBlock(), parent.getLabels()); + } + return new SequentFormula(root); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isApplicableOnSubTerms() { + return false; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java index 5aded9192c3..cc5f18684ab 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.rule; import java.util.LinkedHashSet; @@ -40,198 +43,219 @@ * A {@link BuiltInRule} which evaluates a modality in a side proof. *

    *

    - * This rule is applicable on top level terms ({@link SequentFormula}) of the form. + * This rule is applicable on top level terms ({@link SequentFormula}) of the form. *

      - *
    • {@code {...}\[...\]( = )} or
    • - *
    • {@code {...}\<...\>( = )} or
    • - *
    • {@code {...}\[...\]( = )} or
    • - *
    • {@code {...}\<...\>( = )}
    • + *
    • {@code {...}\[...\]( = )} or
    • + *
    • {@code {...}\<...\>( = )} or
    • + *
    • {@code {...}\[...\]( = )} or
    • + *
    • {@code {...}\<...\>( = )}
    • *
    * The leading updates are optional and any {@link Modality} is supported. - *

    + *

    *

    - * The original {@link SequentFormula} which contains the equality is always - * removed in the following {@link Goal}. - * For each possible result value is a {@link SequentFormula} added to the {@link Sequent} of the form: + * The original {@link SequentFormula} which contains the equality is always removed in the + * following {@link Goal}. For each possible result value is a {@link SequentFormula} added to the + * {@link Sequent} of the form: *

      - *
    • Antecedent: {@code -> = } or
    • - *
    • Antecedent: {@code -> = } or
    • - *
    • Succedent: {@code & = } or
    • - *
    • Succedent: {@code & = }
    • + *
    • Antecedent: {@code -> = } or
    • + *
    • Antecedent: {@code -> = } or
    • + *
    • Succedent: {@code & = } or
    • + *
    • Succedent: {@code & = }
    • *
    - * The side proof uses the default side proof settings (splitting = delayed) and is started - * via {@link SymbolicExecutionUtil#startSideProof(de.uka.ilkd.key.proof.Proof, Sequent, String)}. - * In case that at least one result branch has applicable rules an exception is thrown and the rule is aborted. + * The side proof uses the default side proof settings (splitting = delayed) and is started via + * {@link SymbolicExecutionUtil#startSideProof(de.uka.ilkd.key.proof.Proof, Sequent, String)}. In + * case that at least one result branch has applicable rules an exception is thrown and the rule is + * aborted. *

    + * * @author Martin Hentschel */ public class ModalitySideProofRule extends AbstractSideProofRule { - /** - * The singleton instance of this class. - */ - public static final ModalitySideProofRule INSTANCE = new ModalitySideProofRule(); - - /** - * The {@link Name} of this rule. - */ - private static final Name NAME = new Name("Evaluate Modality in Side Proof"); + /** + * The singleton instance of this class. + */ + public static final ModalitySideProofRule INSTANCE = new ModalitySideProofRule(); + + /** + * The {@link Name} of this rule. + */ + private static final Name NAME = new Name("Evaluate Modality in Side Proof"); - /** - * Constructor to forbid multiple instances. - */ - private ModalitySideProofRule() { - } + /** + * Constructor to forbid multiple instances. + */ + private ModalitySideProofRule() {} - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(Goal goal, PosInOccurrence pio) { - boolean applicable = false; - if (pio != null && pio.isTopLevel()) { - // abort if inside of transformer - if (Transformer.inTransformer(pio)) { - return false; - } - Term term = pio.subTerm(); - term = TermBuilder.goBelowUpdates(term); - if (term.op() instanceof Modality && SymbolicExecutionUtil.getSymbolicExecutionLabel(term) == null) { - Term equalityTerm = term.sub(0); - if (equalityTerm.op() == Junctor.IMP) { - equalityTerm = equalityTerm.sub(0); - } - if (equalityTerm.op() == Junctor.NOT) { - equalityTerm = equalityTerm.sub(0); - } - if (equalityTerm.op() == Equality.EQUALS) { - if (equalityTerm.sub(0).op() instanceof IProgramVariable || - equalityTerm.sub(1).op() instanceof IProgramVariable) { + /** + * {@inheritDoc} + */ + @Override + public boolean isApplicable(Goal goal, PosInOccurrence pio) { + boolean applicable = false; + if (pio != null && pio.isTopLevel()) { + // abort if inside of transformer + if (Transformer.inTransformer(pio)) { + return false; + } + Term term = pio.subTerm(); + term = TermBuilder.goBelowUpdates(term); + if (term.op() instanceof Modality + && SymbolicExecutionUtil.getSymbolicExecutionLabel(term) == null) { + Term equalityTerm = term.sub(0); + if (equalityTerm.op() == Junctor.IMP) { + equalityTerm = equalityTerm.sub(0); + } + if (equalityTerm.op() == Junctor.NOT) { + equalityTerm = equalityTerm.sub(0); + } + if (equalityTerm.op() == Equality.EQUALS) { + if (equalityTerm.sub(0).op() instanceof IProgramVariable + || equalityTerm.sub(1).op() instanceof IProgramVariable) { - applicable = true; - } - } - } - } - return applicable; - } + applicable = true; + } + } + } + } + return applicable; + } - /** - * {@inheritDoc} - */ - @Override - public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { - return new DefaultBuiltInRuleApp(this, pos); - } + /** + * {@inheritDoc} + */ + @Override + public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { + return new DefaultBuiltInRuleApp(this, pos); + } - /** - * {@inheritDoc} - */ - @Override - public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) throws RuleAbortException { - try { - // Extract required Terms from goal - PosInOccurrence pio = ruleApp.posInOccurrence(); - Term topLevelTerm = pio.subTerm(); - Pair,Term> updatesAndTerm = TermBuilder.goBelowUpdates2(topLevelTerm); - Term modalityTerm = updatesAndTerm.second; - ImmutableList updates = updatesAndTerm.first; - boolean inImplication = false; - Term equalityTerm = modalityTerm.sub(0); - if (equalityTerm.op() == Junctor.IMP) { - inImplication = true; - equalityTerm = equalityTerm.sub(0); - } - boolean negation = false; - if (equalityTerm.op() == Junctor.NOT) { - negation = true; - equalityTerm = equalityTerm.sub(0); - } - Term otherTerm; - Term varTerm; - boolean varFirst; - if (equalityTerm.sub(0).op() instanceof LocationVariable) { - otherTerm = equalityTerm.sub(1); - varTerm = equalityTerm.sub(0); - varFirst = true; - } - else { - otherTerm = equalityTerm.sub(0); - varTerm = equalityTerm.sub(1); - varFirst = false; - } - // Compute sequent for side proof to compute query in. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(goal.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - final Services sideProofServices = sideProofEnv.getServicesForEnvironment(); - Sequent sequentToProve = SymbolicExecutionSideProofUtil.computeGeneralSequentToProve(goal.sequent(), pio.sequentFormula()); - Function newPredicate = createResultFunction(sideProofServices, varTerm.sort()); - final TermBuilder tb = sideProofServices.getTermBuilder(); - Term newTerm = tb.func(newPredicate, varTerm); - Term newModalityTerm = sideProofServices.getTermFactory().createTerm(modalityTerm.op(), new ImmutableArray(newTerm), modalityTerm.boundVars(), modalityTerm.javaBlock(), modalityTerm.getLabels()); - Term newModalityWithUpdatesTerm = tb.applySequential(updates, newModalityTerm); - sequentToProve = sequentToProve.addFormula(new SequentFormula(newModalityWithUpdatesTerm), false, false).sequent(); - // Compute results and their conditions - List, Node>> conditionsAndResultsMap = computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, newPredicate); - // Create new single goal in which the query is replaced by the possible results - ImmutableList goals = goal.split(1); - Goal resultGoal = goals.head(); - resultGoal.removeFormula(pio); - // Create results - Set resultTerms = new LinkedHashSet(); - for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { - Term conditionTerm = tb.and(conditionsAndResult.second); - Term resultEqualityTerm = varFirst ? - tb.equals(conditionsAndResult.first, otherTerm) : - tb.equals(otherTerm, conditionsAndResult.first); - Term resultTerm = pio.isInAntec() ? - tb.imp(conditionTerm, resultEqualityTerm) : - tb.and(conditionTerm, resultEqualityTerm); - resultTerms.add(resultTerm); - } - // Add results to goal - if (inImplication) { - // Change implication - Term newCondition = tb.or(resultTerms); - if (negation) { - newCondition = tb.not(newCondition); + /** + * {@inheritDoc} + */ + @Override + public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) + throws RuleAbortException { + try { + // Extract required Terms from goal + PosInOccurrence pio = ruleApp.posInOccurrence(); + Term topLevelTerm = pio.subTerm(); + Pair, Term> updatesAndTerm = + TermBuilder.goBelowUpdates2(topLevelTerm); + Term modalityTerm = updatesAndTerm.second; + ImmutableList updates = updatesAndTerm.first; + boolean inImplication = false; + Term equalityTerm = modalityTerm.sub(0); + if (equalityTerm.op() == Junctor.IMP) { + inImplication = true; + equalityTerm = equalityTerm.sub(0); + } + boolean negation = false; + if (equalityTerm.op() == Junctor.NOT) { + negation = true; + equalityTerm = equalityTerm.sub(0); + } + Term otherTerm; + Term varTerm; + boolean varFirst; + if (equalityTerm.sub(0).op() instanceof LocationVariable) { + otherTerm = equalityTerm.sub(1); + varTerm = equalityTerm.sub(0); + varFirst = true; + } else { + otherTerm = equalityTerm.sub(0); + varTerm = equalityTerm.sub(1); + varFirst = false; + } + // Compute sequent for side proof to compute query in. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(goal.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it has an + // internal + // state and + // the + // default + // instance + // can't be + // used + // parallel. + final Services sideProofServices = sideProofEnv.getServicesForEnvironment(); + Sequent sequentToProve = SymbolicExecutionSideProofUtil + .computeGeneralSequentToProve(goal.sequent(), pio.sequentFormula()); + Function newPredicate = createResultFunction(sideProofServices, varTerm.sort()); + final TermBuilder tb = sideProofServices.getTermBuilder(); + Term newTerm = tb.func(newPredicate, varTerm); + Term newModalityTerm = sideProofServices.getTermFactory().createTerm(modalityTerm.op(), + new ImmutableArray(newTerm), modalityTerm.boundVars(), + modalityTerm.javaBlock(), modalityTerm.getLabels()); + Term newModalityWithUpdatesTerm = tb.applySequential(updates, newModalityTerm); + sequentToProve = sequentToProve + .addFormula(new SequentFormula(newModalityWithUpdatesTerm), false, false) + .sequent(); + // Compute results and their conditions + List, Node>> conditionsAndResultsMap = + computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, + newPredicate); + // Create new single goal in which the query is replaced by the possible results + ImmutableList goals = goal.split(1); + Goal resultGoal = goals.head(); + resultGoal.removeFormula(pio); + // Create results + Set resultTerms = new LinkedHashSet(); + for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.second); + Term resultEqualityTerm = varFirst ? tb.equals(conditionsAndResult.first, otherTerm) + : tb.equals(otherTerm, conditionsAndResult.first); + Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, resultEqualityTerm) + : tb.and(conditionTerm, resultEqualityTerm); + resultTerms.add(resultTerm); } - Term newImplication = tb.imp(newCondition, modalityTerm.sub(0).sub(1)); - Term newImplicationWithUpdates = tb.applySequential(updates, newImplication); - resultGoal.addFormula(new SequentFormula(newImplicationWithUpdates), pio.isInAntec(), false); - } - else { - // Add result directly as new top level formula - for (Term result : resultTerms) { - resultGoal.addFormula(new SequentFormula(result), pio.isInAntec(), false); + // Add results to goal + if (inImplication) { + // Change implication + Term newCondition = tb.or(resultTerms); + if (negation) { + newCondition = tb.not(newCondition); + } + Term newImplication = tb.imp(newCondition, modalityTerm.sub(0).sub(1)); + Term newImplicationWithUpdates = tb.applySequential(updates, newImplication); + resultGoal.addFormula(new SequentFormula(newImplicationWithUpdates), + pio.isInAntec(), false); + } else { + // Add result directly as new top level formula + for (Term result : resultTerms) { + resultGoal.addFormula(new SequentFormula(result), pio.isInAntec(), false); + } } - } - return goals; - } - catch (Exception e) { - throw new RuleAbortException(e.getMessage()); - } - } + return goals; + } catch (Exception e) { + throw new RuleAbortException(e.getMessage()); + } + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return NAME; - } + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return NAME; + } - /** - * {@inheritDoc} - */ - @Override - public String displayName() { - return NAME.toString(); - } + /** + * {@inheritDoc} + */ + @Override + public String displayName() { + return NAME.toString(); + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return displayName(); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return displayName(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java index 90220b144f7..954f45a8864 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.rule; import java.util.List; @@ -41,234 +44,279 @@ * A {@link BuiltInRule} which evaluates a query in a side proof. *

    *

    - * This rule is applicable on each equality which contains a query: + * This rule is applicable on each equality which contains a query: *

      - *
    • {@code ...( = )...} or
    • - *
    • {@code ...( = )...}
    • + *
    • {@code ...( = )...} or
    • + *
    • {@code ...( = )...}
    • *
    *

    *

    - * The original {@link SequentFormula} which contains the equality is always - * removed in the following {@link Goal}. How the result of the query computed - * in the side proof is represented depends on the occurrence of the equality: + * The original {@link SequentFormula} which contains the equality is always removed in the + * following {@link Goal}. How the result of the query computed in the side proof is represented + * depends on the occurrence of the equality: *

      - *
    1. - * top level {@code = } or {@code = }
      - * For each possible result value is a {@link SequentFormula} added to the {@link Sequent} of the form: - *
        - *
      • Antecedent: {@code -> = } or
      • - *
      • Antecedent: {@code -> = } or
      • - *
      • Succedent: {@code & = } or
      • - *
      • Succedent: {@code & = }
      • - *
      - *
    2. - *
    3. - * right side of an implication on top level {@code -> = } or {@code -> = }
      - * For each possible result value is a {@link SequentFormula} added to the {@link Sequent} of the form: - *
        - *
      • Antecedent: {@code
         -> ( ->  = )} or 
      • - *
      • Antecedent: {@code
         -> ( ->  = )} or
      • - *
      • Succedent: {@code
         -> ( &  = )} or 
      • - *
      • Succedent: {@code
         -> ( &  = )}
      • - *
      - *
    4. - *
    5. - * everywhere else {@code ...( = )...} or {@code ...( = )...}
      - * In the original {@link SequentFormula} is the {@code } replaced by a new constant function named {@code QueryResult} and added to the antecedent/succedent in which it was contained before. - * For each possible result value is an additional {@link SequentFormula} added to the antecedent of the form: - *
        - *
      • {@code -> QueryResult = } or
      • - *
      • {@code -> = QueryResult}
      • - *
      - *
    6. + *
    7. top level {@code = } or {@code = }
      + * For each possible result value is a {@link SequentFormula} added to the {@link Sequent} of the + * form: + *
        + *
      • Antecedent: {@code -> = } or
      • + *
      • Antecedent: {@code -> = } or
      • + *
      • Succedent: {@code & = } or
      • + *
      • Succedent: {@code & = }
      • + *
      + *
    8. + *
    9. right side of an implication on top level + * {@code -> = } or + * {@code -> = }
      + * For each possible result value is a {@link SequentFormula} added to the {@link Sequent} of the + * form: + *
        + *
      • Antecedent: {@code + * + * + +
        + *  -> ( ->  = )} or
      • + *
      • Antecedent: {@code + * + * + +
        + *  -> ( ->  = )} or
      • + *
      • Succedent: {@code + * + * + +
        + *  -> ( &  = )} or
      • + *
      • Succedent: {@code + * + * + +
        + *  -> ( &  = )}
      • + *
      + *
    10. + *
    11. everywhere else {@code ...( = )...} or + * {@code ...( = )...}
      + * In the original {@link SequentFormula} is the {@code } replaced by a new constant function + * named {@code QueryResult} and added to the antecedent/succedent in which it was contained before. + * For each possible result value is an additional {@link SequentFormula} added to the + * antecedent of the form: + *
        + *
      • {@code -> QueryResult = } or
      • + *
      • {@code -> = QueryResult}
      • + *
      + *
    12. *
    - * The side proof uses the default side proof settings (splitting = delayed) and is started - * via {@link SymbolicExecutionUtil#startSideProof(de.uka.ilkd.key.proof.Proof, Sequent, String)}. - * In case that at least one result branch has applicable rules an exception is thrown and the rule is aborted. + * The side proof uses the default side proof settings (splitting = delayed) and is started via + * {@link SymbolicExecutionUtil#startSideProof(de.uka.ilkd.key.proof.Proof, Sequent, String)}. In + * case that at least one result branch has applicable rules an exception is thrown and the rule is + * aborted. *

    + * * @author Martin Hentschel */ public final class QuerySideProofRule extends AbstractSideProofRule { - /** - * The singleton instance of this class. - */ - public static final QuerySideProofRule INSTANCE = new QuerySideProofRule(); - - /** - * The {@link Name} of this rule. - */ - private static final Name NAME = new Name("Evaluate Query in Side Proof"); + /** + * The singleton instance of this class. + */ + public static final QuerySideProofRule INSTANCE = new QuerySideProofRule(); + + /** + * The {@link Name} of this rule. + */ + private static final Name NAME = new Name("Evaluate Query in Side Proof"); + + /** + * Constructor to forbid multiple instances. + */ + private QuerySideProofRule() {} + + /** + * {@inheritDoc} + */ + @Override + public boolean isApplicable(Goal goal, PosInOccurrence pio) { + boolean applicable = false; + if (pio != null) { + // abort if inside of transformer + if (Transformer.inTransformer(pio)) { + return false; + } + Term term = pio.subTerm(); + if (term != null) { + if (term.op() == Equality.EQUALS) { + applicable = isApplicableQuery(goal, term.sub(0), pio) + || isApplicableQuery(goal, term.sub(1), pio); + } + } + } + return applicable; + } - /** - * Constructor to forbid multiple instances. - */ - private QuerySideProofRule() { - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(Goal goal, PosInOccurrence pio) { - boolean applicable = false; - if (pio != null) { - // abort if inside of transformer - if (Transformer.inTransformer(pio)) { - return false; - } - Term term = pio.subTerm(); - if (term != null) { - if (term.op() == Equality.EQUALS) { - applicable = isApplicableQuery(goal, term.sub(0), pio) || - isApplicableQuery(goal, term.sub(1), pio); + /** + * Checks if the query term is supported. The functionality is identical to + * {@link QueryExpand#isApplicable(Goal, PosInOccurrence)}. + * + * @param goal The {@link Goal}. + * @param pmTerm The {@link Term} to with the query to check. + * @param pio The {@link PosInOccurrence} in the {@link Goal}. + * @return {@code true} is applicable, {@code false} is not applicable + */ + protected boolean isApplicableQuery(Goal goal, Term pmTerm, PosInOccurrence pio) { + if (pmTerm.op() instanceof IProgramMethod && pmTerm.freeVars().isEmpty()) { + IProgramMethod pm = (IProgramMethod) pmTerm.op(); + final Sort nullSort = goal.proof().getJavaInfo().nullSort(); + if (pm.isStatic() + || (pmTerm.sub(1).sort().extendsTrans(goal.proof().getJavaInfo().objectSort()) + && !pmTerm.sub(1).sort().extendsTrans(nullSort))) { + PIOPathIterator it = pio.iterator(); + while (it.next() != -1) { + Term focus = it.getSubTerm(); + if (focus.op() instanceof UpdateApplication || focus.op() instanceof Modality) { + return false; + } + } + return true; } - } - } - return applicable; - } - - /** - * Checks if the query term is supported. The functionality is identical to - * {@link QueryExpand#isApplicable(Goal, PosInOccurrence)}. - * @param goal The {@link Goal}. - * @param pmTerm The {@link Term} to with the query to check. - * @param pio The {@link PosInOccurrence} in the {@link Goal}. - * @return {@code true} is applicable, {@code false} is not applicable - */ - protected boolean isApplicableQuery(Goal goal, Term pmTerm, PosInOccurrence pio) { - if (pmTerm.op() instanceof IProgramMethod && pmTerm.freeVars().isEmpty()) { - IProgramMethod pm = (IProgramMethod) pmTerm.op(); - final Sort nullSort = goal.proof().getJavaInfo().nullSort(); - if (pm.isStatic() || (pmTerm.sub(1).sort().extendsTrans(goal.proof().getJavaInfo().objectSort()) && - !pmTerm.sub(1).sort().extendsTrans(nullSort))) { - PIOPathIterator it = pio.iterator(); - while ( it.next() != -1 ) { - Term focus = it.getSubTerm(); - if (focus.op() instanceof UpdateApplication || focus.op() instanceof Modality) { - return false; - } - } - return true; - } - } - return false; - } + } + return false; + } - /** - * {@inheritDoc} - */ - @Override - public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { - return new DefaultBuiltInRuleApp(this, pos); - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) throws RuleAbortException { - try { - // Extract required Terms from goal - PosInOccurrence pio = ruleApp.posInOccurrence(); - Sequent goalSequent = goal.sequent(); - SequentFormula equalitySF = pio.sequentFormula(); - Term equalityTerm = pio.subTerm(); - Term queryTerm; - Term varTerm; - boolean varFirst; - if (equalityTerm.sub(0).op() instanceof LocationVariable) { - queryTerm = equalityTerm.sub(1); - varTerm = equalityTerm.sub(0); - varFirst = true; - } - else { - queryTerm = equalityTerm.sub(0); - varTerm = equalityTerm.sub(1); - varFirst = false; - } - Term queryConditionTerm = null; - if (equalitySF.formula().op() == Junctor.IMP && equalitySF.formula().sub(1) == equalityTerm) { - queryConditionTerm = equalitySF.formula().sub(0); - } - // Compute sequent for side proof to compute query in. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(goal.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - final Services sideProofServices = sideProofEnv.getServicesForEnvironment(); - Sequent sequentToProve = SymbolicExecutionSideProofUtil.computeGeneralSequentToProve(goalSequent, equalitySF); - Function newPredicate = createResultFunction(sideProofServices, queryTerm.sort()); - Term newTerm = sideProofServices.getTermBuilder().func(newPredicate, queryTerm); - sequentToProve = sequentToProve.addFormula(new SequentFormula(newTerm), false, false).sequent(); - // Compute results and their conditions - List, Node>> conditionsAndResultsMap = computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, newPredicate); - // Create new single goal in which the query is replaced by the possible results - ImmutableList goals = goal.split(1); - Goal resultGoal = goals.head(); - final TermBuilder tb = services.getTermBuilder(); - resultGoal.removeFormula(pio); - if (pio.isTopLevel() || queryConditionTerm != null) { - for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { - Term conditionTerm = tb.and(conditionsAndResult.second); - Term newEqualityTerm = varFirst ? - tb.equals(varTerm, conditionsAndResult.first) : - tb.equals(conditionsAndResult.first, varTerm); - Term resultTerm = pio.isInAntec() ? - tb.imp(conditionTerm, newEqualityTerm) : - tb.and(conditionTerm, newEqualityTerm); - if (queryConditionTerm != null) { - resultTerm = tb.imp(queryConditionTerm, resultTerm); - } - resultGoal.addFormula(new SequentFormula(resultTerm), pio.isInAntec(), false); + /** + * {@inheritDoc} + */ + @Override + public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { + return new DefaultBuiltInRuleApp(this, pos); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) + throws RuleAbortException { + try { + // Extract required Terms from goal + PosInOccurrence pio = ruleApp.posInOccurrence(); + Sequent goalSequent = goal.sequent(); + SequentFormula equalitySF = pio.sequentFormula(); + Term equalityTerm = pio.subTerm(); + Term queryTerm; + Term varTerm; + boolean varFirst; + if (equalityTerm.sub(0).op() instanceof LocationVariable) { + queryTerm = equalityTerm.sub(1); + varTerm = equalityTerm.sub(0); + varFirst = true; + } else { + queryTerm = equalityTerm.sub(0); + varTerm = equalityTerm.sub(1); + varFirst = false; + } + Term queryConditionTerm = null; + if (equalitySF.formula().op() == Junctor.IMP + && equalitySF.formula().sub(1) == equalityTerm) { + queryConditionTerm = equalitySF.formula().sub(0); } - } - else { - Function resultFunction = createResultConstant(services, varTerm.sort()); - Term resultFunctionTerm = tb.func(resultFunction); - resultGoal.addFormula(replace(pio, - varFirst ? tb.equals(resultFunctionTerm, varTerm) : tb.equals(resultFunctionTerm, varTerm), - services), - pio.isInAntec(), - false); - for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { - Term conditionTerm = tb.and(conditionsAndResult.second); - Term resultTerm = tb.imp(conditionTerm, varFirst ? tb.equals(resultFunctionTerm, conditionsAndResult.first) : tb.equals(conditionsAndResult.first, resultFunctionTerm)); - resultGoal.addFormula(new SequentFormula(resultTerm), true, false); + // Compute sequent for side proof to compute query in. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(goal.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it has an + // internal + // state and + // the + // default + // instance + // can't be + // used + // parallel. + final Services sideProofServices = sideProofEnv.getServicesForEnvironment(); + Sequent sequentToProve = SymbolicExecutionSideProofUtil + .computeGeneralSequentToProve(goalSequent, equalitySF); + Function newPredicate = createResultFunction(sideProofServices, queryTerm.sort()); + Term newTerm = sideProofServices.getTermBuilder().func(newPredicate, queryTerm); + sequentToProve = + sequentToProve.addFormula(new SequentFormula(newTerm), false, false).sequent(); + // Compute results and their conditions + List, Node>> conditionsAndResultsMap = + computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, + newPredicate); + // Create new single goal in which the query is replaced by the possible results + ImmutableList goals = goal.split(1); + Goal resultGoal = goals.head(); + final TermBuilder tb = services.getTermBuilder(); + resultGoal.removeFormula(pio); + if (pio.isTopLevel() || queryConditionTerm != null) { + for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.second); + Term newEqualityTerm = varFirst ? tb.equals(varTerm, conditionsAndResult.first) + : tb.equals(conditionsAndResult.first, varTerm); + Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, newEqualityTerm) + : tb.and(conditionTerm, newEqualityTerm); + if (queryConditionTerm != null) { + resultTerm = tb.imp(queryConditionTerm, resultTerm); + } + resultGoal.addFormula(new SequentFormula(resultTerm), pio.isInAntec(), false); + } + } else { + Function resultFunction = createResultConstant(services, varTerm.sort()); + Term resultFunctionTerm = tb.func(resultFunction); + resultGoal.addFormula( + replace(pio, + varFirst ? tb.equals(resultFunctionTerm, varTerm) + : tb.equals(resultFunctionTerm, varTerm), + services), + pio.isInAntec(), false); + for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.second); + Term resultTerm = tb.imp(conditionTerm, + varFirst ? tb.equals(resultFunctionTerm, conditionsAndResult.first) + : tb.equals(conditionsAndResult.first, resultFunctionTerm)); + resultGoal.addFormula(new SequentFormula(resultTerm), true, false); + } } - } - return goals; - } - catch (Exception e) { - throw new RuleAbortException(e.getMessage()); - } - } + return goals; + } catch (Exception e) { + throw new RuleAbortException(e.getMessage()); + } + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return NAME; - } + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return NAME; + } - /** - * {@inheritDoc} - */ - @Override - public String displayName() { - return NAME.toString(); - } + /** + * {@inheritDoc} + */ + @Override + public String displayName() { + return NAME.toString(); + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return displayName(); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return displayName(); + } - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicableOnSubTerms() { - return true; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean isApplicableOnSubTerms() { + return true; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractBackwardSlicer.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractBackwardSlicer.java index 233b285428f..126ec1a0675 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractBackwardSlicer.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractBackwardSlicer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.slicing; import java.util.HashSet; @@ -26,166 +29,173 @@ /** * Provides a basic implementation of backward slicing algorithms. + * * @author Martin Hentschel */ public abstract class AbstractBackwardSlicer extends AbstractSlicer { - /** - * {@inheritDoc} - */ - @Override - public ImmutableArray doSlicing(Node seedNode, Location seedLocation, ImmutableList sec) throws ProofInputException { - final Services services = seedNode.proof().getServices(); - Set relevantLocations = null; - List result = new LinkedList(); - Map> oldAliases = null; - Node previousChild = null; - while (seedNode != null && (relevantLocations == null || !relevantLocations.isEmpty())) { - if (NodeInfo.isSymbolicExecutionRuleApplied(seedNode)) { - SequentInfo info = analyzeSequent(seedNode, sec); - if (info != null) { // Modality of interest - SourceElement activeStatement = seedNode.getNodeInfo().getActiveStatement(); - Map> aliases = info.getAliases(); - ReferencePrefix thisReference = info.getThisReference(); - if (relevantLocations == null) { - // Initialize relevant locations if required - relevantLocations = new HashSet(); - relevantLocations.add(normalizeAlias(services, seedLocation, info)); - } - // Check if current node is part of the slice or not - if (accept(seedNode, previousChild, services, relevantLocations, info, activeStatement)) { - result.add(seedNode); - } - if (oldAliases != null) { - try { - // Update relevant locations if required - if (activeStatement instanceof CopyAssignment) { - SourceElement originalTarget = ((CopyAssignment) activeStatement).getArguments().get(0); - ReferencePrefix relevantTarget = toReferencePrefix(originalTarget); - Location normalizedPrefix = normalizeAlias(services, relevantTarget, info); - relevantLocations = updateOutdatedLocations(services, relevantLocations, aliases, oldAliases, normalizedPrefix, thisReference); - } - } - catch (IllegalArgumentException e) { - // Nothing to do, expression with side effects is evaluated - } - } - oldAliases = aliases; + /** + * {@inheritDoc} + */ + @Override + public ImmutableArray doSlicing(Node seedNode, Location seedLocation, + ImmutableList sec) throws ProofInputException { + final Services services = seedNode.proof().getServices(); + Set relevantLocations = null; + List result = new LinkedList(); + Map> oldAliases = null; + Node previousChild = null; + while (seedNode != null && (relevantLocations == null || !relevantLocations.isEmpty())) { + if (NodeInfo.isSymbolicExecutionRuleApplied(seedNode)) { + SequentInfo info = analyzeSequent(seedNode, sec); + if (info != null) { // Modality of interest + SourceElement activeStatement = seedNode.getNodeInfo().getActiveStatement(); + Map> aliases = info.getAliases(); + ReferencePrefix thisReference = info.getThisReference(); + if (relevantLocations == null) { + // Initialize relevant locations if required + relevantLocations = new HashSet(); + relevantLocations.add(normalizeAlias(services, seedLocation, info)); + } + // Check if current node is part of the slice or not + if (accept(seedNode, previousChild, services, relevantLocations, info, + activeStatement)) { + result.add(seedNode); + } + if (oldAliases != null) { + try { + // Update relevant locations if required + if (activeStatement instanceof CopyAssignment) { + SourceElement originalTarget = + ((CopyAssignment) activeStatement).getArguments().get(0); + ReferencePrefix relevantTarget = toReferencePrefix(originalTarget); + Location normalizedPrefix = + normalizeAlias(services, relevantTarget, info); + relevantLocations = updateOutdatedLocations(services, + relevantLocations, aliases, oldAliases, normalizedPrefix, + thisReference); + } + } catch (IllegalArgumentException e) { + // Nothing to do, expression with side effects is evaluated + } + } + oldAliases = aliases; + } } - } - previousChild = seedNode; - seedNode = seedNode.parent(); - } - return new ImmutableArray(result); - } + previousChild = seedNode; + seedNode = seedNode.parent(); + } + return new ImmutableArray(result); + } - /** - * Decides if the given {@link Node} is part of the slice or not. - * @param node The {@link Node} to check. - * @param previousChild The previously visited child {@link Node} or {@code null} the first time. - * @param services The {@link Services} to use. - * @param relevantLocations The relevant locations. - * @param info The {@link SequentInfo} with the aliases and so on. - * @param activeStatement The currently active statement. - * @return {@code true} {@link Node} should be part of slice, {@code false} {@link Node} should not be part of slice. - */ - protected abstract boolean accept(Node node, - Node previousChild, - Services services, - Set relevantLocations, - SequentInfo info, - SourceElement activeStatement) throws ProofInputException; + /** + * Decides if the given {@link Node} is part of the slice or not. + * + * @param node The {@link Node} to check. + * @param previousChild The previously visited child {@link Node} or {@code null} the first + * time. + * @param services The {@link Services} to use. + * @param relevantLocations The relevant locations. + * @param info The {@link SequentInfo} with the aliases and so on. + * @param activeStatement The currently active statement. + * @return {@code true} {@link Node} should be part of slice, {@code false} {@link Node} should + * not be part of slice. + */ + protected abstract boolean accept(Node node, Node previousChild, Services services, + Set relevantLocations, SequentInfo info, SourceElement activeStatement) + throws ProofInputException; - /** - * Updates the relevant locations. - * @param read The {@link Expression} which provides new relevant locations. - * @param relevantLocations The relevant locations to update. - * @param info The {@link SequentInfo} with the aliases and so on. - * @param services The {@link Services} to use. - */ - protected void updateRelevantLocations(final ProgramElement read, - final Set relevantLocations, - final SequentInfo info, - final Services services) { - ReferencePrefix relevantElement = toReferencePrefix(read); - if (relevantElement != null) { - Location normalizedElement = normalizeAlias(services, relevantElement, info); - relevantLocations.add(normalizedElement); - } - else if (read instanceof NonTerminalProgramElement) { - NonTerminalProgramElement ntpe = (NonTerminalProgramElement) read; - for (int i = 0; i < ntpe.getChildCount(); i++) { - updateRelevantLocations(ntpe.getChildAt(i), relevantLocations, info, services); - } - } - } + /** + * Updates the relevant locations. + * + * @param read The {@link Expression} which provides new relevant locations. + * @param relevantLocations The relevant locations to update. + * @param info The {@link SequentInfo} with the aliases and so on. + * @param services The {@link Services} to use. + */ + protected void updateRelevantLocations(final ProgramElement read, + final Set relevantLocations, final SequentInfo info, + final Services services) { + ReferencePrefix relevantElement = toReferencePrefix(read); + if (relevantElement != null) { + Location normalizedElement = normalizeAlias(services, relevantElement, info); + relevantLocations.add(normalizedElement); + } else if (read instanceof NonTerminalProgramElement) { + NonTerminalProgramElement ntpe = (NonTerminalProgramElement) read; + for (int i = 0; i < ntpe.getChildCount(); i++) { + updateRelevantLocations(ntpe.getChildAt(i), relevantLocations, info, services); + } + } + } - /** - * Updates the outdated locations. This means that locations with the given - * prefix are replaced with another previously (old) available alternative. - * @param services The {@link Services} to use. - * @param oldLocationsToUpdate The locations to update. - * @param newAliases The new aliases. - * @param oldAliases The old aliases. - * @param outdatedPrefix The prefix of outdated locations. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - * @return The updated locations. - */ - protected Set updateOutdatedLocations(Services services, - Set oldLocationsToUpdate, - Map> newAliases, - Map> oldAliases, - Location outdatedPrefix, - ReferencePrefix thisReference) { - // Ensure that at least one possibly outdated location is available. - if (!oldLocationsToUpdate.isEmpty()) { - // Ensure that alternatives are different - SortedSet newAlternatives = newAliases.get(outdatedPrefix); - if (newAlternatives == null) { - newAlternatives = createSortedSet(); - newAlternatives.add(outdatedPrefix); - } - SortedSet oldAlternatives = oldAliases.get(outdatedPrefix); - if (oldAlternatives == null) { - oldAlternatives = createSortedSet(); - oldAlternatives.add(outdatedPrefix); - } - if (!newAlternatives.equals(oldAlternatives)) { - // Compute old variables - ImmutableList> newAlternativeVariables = ImmutableSLList.nil(); - for (Location newALternative : newAlternatives) { - newAlternativeVariables = newAlternativeVariables.prepend(newALternative.getAccesses()); + /** + * Updates the outdated locations. This means that locations with the given prefix are replaced + * with another previously (old) available alternative. + * + * @param services The {@link Services} to use. + * @param oldLocationsToUpdate The locations to update. + * @param newAliases The new aliases. + * @param oldAliases The old aliases. + * @param outdatedPrefix The prefix of outdated locations. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + * @return The updated locations. + */ + protected Set updateOutdatedLocations(Services services, + Set oldLocationsToUpdate, Map> newAliases, + Map> oldAliases, Location outdatedPrefix, + ReferencePrefix thisReference) { + // Ensure that at least one possibly outdated location is available. + if (!oldLocationsToUpdate.isEmpty()) { + // Ensure that alternatives are different + SortedSet newAlternatives = newAliases.get(outdatedPrefix); + if (newAlternatives == null) { + newAlternatives = createSortedSet(); + newAlternatives.add(outdatedPrefix); + } + SortedSet oldAlternatives = oldAliases.get(outdatedPrefix); + if (oldAlternatives == null) { + oldAlternatives = createSortedSet(); + oldAlternatives.add(outdatedPrefix); } - // Compute new alternative - Location newAlternative = findNewAlternative(oldAlternatives, newAlternatives); - // Compute new locations - Set newLocations = new HashSet(); - for (Location oldLocation : oldLocationsToUpdate) { - ImmutableList oldVariables = oldLocation.getAccesses(); - int commonPrefixLength = computeFirstCommonPrefixLength(newAlternativeVariables, oldVariables); - if (commonPrefixLength >= 1) { - if (newAlternative != null) { // Otherwise the relevant location is dropped because it was not known before - if (commonPrefixLength == oldVariables.size()) { - newLocations.add(newAlternative); - } - else { - ImmutableList oldRemainignVariables = oldVariables.take(commonPrefixLength); - ImmutableList newAccesses = newAlternative.getAccesses().append(oldRemainignVariables); - newLocations.add(new Location(newAccesses)); - } - } - } - else { - newLocations.add(oldLocation); // Maintain location - } + if (!newAlternatives.equals(oldAlternatives)) { + // Compute old variables + ImmutableList> newAlternativeVariables = + ImmutableSLList.nil(); + for (Location newALternative : newAlternatives) { + newAlternativeVariables = + newAlternativeVariables.prepend(newALternative.getAccesses()); + } + // Compute new alternative + Location newAlternative = findNewAlternative(oldAlternatives, newAlternatives); + // Compute new locations + Set newLocations = new HashSet(); + for (Location oldLocation : oldLocationsToUpdate) { + ImmutableList oldVariables = oldLocation.getAccesses(); + int commonPrefixLength = + computeFirstCommonPrefixLength(newAlternativeVariables, oldVariables); + if (commonPrefixLength >= 1) { + if (newAlternative != null) { // Otherwise the relevant location is dropped + // because it was not known before + if (commonPrefixLength == oldVariables.size()) { + newLocations.add(newAlternative); + } else { + ImmutableList oldRemainignVariables = + oldVariables.take(commonPrefixLength); + ImmutableList newAccesses = + newAlternative.getAccesses().append(oldRemainignVariables); + newLocations.add(new Location(newAccesses)); + } + } + } else { + newLocations.add(oldLocation); // Maintain location + } + } + return newLocations; + } else { + return oldLocationsToUpdate; } - return newLocations; - } - else { + } else { return oldLocationsToUpdate; - } - } - else { - return oldLocationsToUpdate; - } - } + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractSlicer.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractSlicer.java index 311f80ed087..de80ce8bbcf 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractSlicer.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/AbstractSlicer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.slicing; import java.util.ArrayList; @@ -62,991 +65,1066 @@ /** * Defines the basic functionality for slicing algorithms. + * * @author Martin Hentschel */ public abstract class AbstractSlicer { - /** - * Computes the slice. - * @param seedNode The seed {@link Node} to start slicing at. - * @param term The seed {@link Term}. - * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. - * @return The computed slice. - */ - public ImmutableArray slice(Node seedNode, Term term, ImmutableList sec) throws ProofInputException { - return slice(seedNode, toLocation(seedNode.proof().getServices(), term), sec); - } + /** + * Computes the slice. + * + * @param seedNode The seed {@link Node} to start slicing at. + * @param term The seed {@link Term}. + * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. + * @return The computed slice. + */ + public ImmutableArray slice(Node seedNode, Term term, + ImmutableList sec) throws ProofInputException { + return slice(seedNode, toLocation(seedNode.proof().getServices(), term), sec); + } - /** - * Computes the slice. - * @param seedNode The seed {@link Node} to start slicing at. - * @param seedLocation The seed {@link ReferencePrefix}. - * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. - * @return The computed slice. - */ - public ImmutableArray slice(Node seedNode, ReferencePrefix seedLocation, ImmutableList sec) throws ProofInputException { - // Solve this reference - PosInOccurrence pio = seedNode.getAppliedRuleApp().posInOccurrence(); - Term topLevel = pio.sequentFormula().formula(); - Term modalityTerm = TermBuilder.goBelowUpdates(topLevel); - Services services = seedNode.proof().getServices(); - ExecutionContext ec = JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), services); - ReferencePrefix thisReference = ec != null ? ec.getRuntimeInstance() : null; - // Perform slicing - return slice(seedNode, toLocation(services, seedLocation, ec, thisReference), sec); - } + /** + * Computes the slice. + * + * @param seedNode The seed {@link Node} to start slicing at. + * @param seedLocation The seed {@link ReferencePrefix}. + * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. + * @return The computed slice. + */ + public ImmutableArray slice(Node seedNode, ReferencePrefix seedLocation, + ImmutableList sec) throws ProofInputException { + // Solve this reference + PosInOccurrence pio = seedNode.getAppliedRuleApp().posInOccurrence(); + Term topLevel = pio.sequentFormula().formula(); + Term modalityTerm = TermBuilder.goBelowUpdates(topLevel); + Services services = seedNode.proof().getServices(); + ExecutionContext ec = + JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), services); + ReferencePrefix thisReference = ec != null ? ec.getRuntimeInstance() : null; + // Perform slicing + return slice(seedNode, toLocation(services, seedLocation, ec, thisReference), sec); + } - /** - * Computes the slice. - * @param seedNode The seed {@link Node} to start slicing at. - * @param seedLocation The seed {@link ReferencePrefix}. - * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. - * @return The computed slice. - */ - public ImmutableArray slice(Node seedNode, Location seedLocation, ImmutableList sec) throws ProofInputException { - // Ensure that seed node is valid - if (seedNode.getAppliedRuleApp() == null) { - throw new IllegalStateException("No rule applied on seed Node '" + seedNode.serialNr() + "'."); - } - PosInOccurrence pio = seedNode.getAppliedRuleApp().posInOccurrence(); - Term applicationTerm = pio.subTerm(); - Pair,Term> pair = TermBuilder.goBelowUpdates2(applicationTerm); - Term modalityTerm = pair.second; - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); - if (label == null) { - throw new IllegalStateException("Modality at applied rule does not have the " + SymbolicExecutionTermLabel.NAME + " term label."); - } - // Perform slicing - return doSlicing(seedNode, seedLocation, sec); - } + /** + * Computes the slice. + * + * @param seedNode The seed {@link Node} to start slicing at. + * @param seedLocation The seed {@link ReferencePrefix}. + * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. + * @return The computed slice. + */ + public ImmutableArray slice(Node seedNode, Location seedLocation, + ImmutableList sec) throws ProofInputException { + // Ensure that seed node is valid + if (seedNode.getAppliedRuleApp() == null) { + throw new IllegalStateException( + "No rule applied on seed Node '" + seedNode.serialNr() + "'."); + } + PosInOccurrence pio = seedNode.getAppliedRuleApp().posInOccurrence(); + Term applicationTerm = pio.subTerm(); + Pair, Term> pair = TermBuilder.goBelowUpdates2(applicationTerm); + Term modalityTerm = pair.second; + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); + if (label == null) { + throw new IllegalStateException("Modality at applied rule does not have the " + + SymbolicExecutionTermLabel.NAME + " term label."); + } + // Perform slicing + return doSlicing(seedNode, seedLocation, sec); + } - /** - * Performs the slicing. - * @param seedNode The seed {@link Node} to start slicing at. - * @param seedLocation The seed {@link Location}. - * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. - * @return The computed slice. - */ - protected abstract ImmutableArray doSlicing(Node seedNode, Location seedLocation, ImmutableList sec) throws ProofInputException; - - /** - * The result returned by {@link AbstractSlicer#analyzeSequent(Node)}. - * @author Martin Hentschel - */ - protected static class SequentInfo { - /** - * The found aliases. - */ - private final Map> aliases; - - /** - * The local values. - */ - private final Map localValues; + /** + * Performs the slicing. + * + * @param seedNode The seed {@link Node} to start slicing at. + * @param seedLocation The seed {@link Location}. + * @param sec The optional {@link ISymbolicEquivalenceClass}es to consider. + * @return The computed slice. + */ + protected abstract ImmutableArray doSlicing(Node seedNode, Location seedLocation, + ImmutableList sec) throws ProofInputException; - /** - * The current {@link ExecutionContext}. - */ - private final ExecutionContext executionContext; - - /** - * The this reference if available. - */ - private final ReferencePrefix thisReference; + /** + * The result returned by {@link AbstractSlicer#analyzeSequent(Node)}. + * + * @author Martin Hentschel + */ + protected static class SequentInfo { + /** + * The found aliases. + */ + private final Map> aliases; - /** - * Constructor. - * @param aliases The found aliases. - * @param thisReference The this reference if available. - */ - public SequentInfo(Map> aliases, - Map localValues, - ExecutionContext executionContext, - ReferencePrefix thisReference) { - assert aliases != null; - assert localValues != null; - this.aliases = aliases; - this.localValues = localValues; - this.executionContext = executionContext; - this.thisReference = thisReference; - } + /** + * The local values. + */ + private final Map localValues; - /** - * Returns the found aliases. - * @return The found aliases. - */ - public Map> getAliases() { - return aliases; - } + /** + * The current {@link ExecutionContext}. + */ + private final ExecutionContext executionContext; - /** - * Returns the local values. - * @return The local values. - */ - public Map getLocalValues() { - return localValues; - } + /** + * The this reference if available. + */ + private final ReferencePrefix thisReference; - /** - * Returns the current {@link ExecutionContext}. - * @return The current {@link ExecutionContext}. - */ - public ExecutionContext getExecutionContext() { - return executionContext; - } + /** + * Constructor. + * + * @param aliases The found aliases. + * @param thisReference The this reference if available. + */ + public SequentInfo(Map> aliases, + Map localValues, ExecutionContext executionContext, + ReferencePrefix thisReference) { + assert aliases != null; + assert localValues != null; + this.aliases = aliases; + this.localValues = localValues; + this.executionContext = executionContext; + this.thisReference = thisReference; + } - /** - * Returns the this reference if available. - * @return The this reference if available. - */ - public ReferencePrefix getThisReference() { - return thisReference; - } - } - - /** - * Computes the aliases specified by the updates of the current {@link Node} - * at the application {@link PosInOccurrence} and computes the current {@code this} reference. - * @param node The {@link Node} to analyze. - * @return The computed {@link SequentInfo} or {@code null} if the {@link Node} is not supported. - */ - protected SequentInfo analyzeSequent(Node node, ImmutableList sec) { - PosInOccurrence pio = node.getAppliedRuleApp().posInOccurrence(); - Term topLevel = pio.sequentFormula().formula(); - Pair,Term> pair = TermBuilder.goBelowUpdates2(topLevel); - Term modalityTerm = pair.second; - SymbolicExecutionTermLabel label = SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); - Services services = node.proof().getServices(); - HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - if (label != null) { - // Solve this reference - ExecutionContext ec = JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), services); - ReferencePrefix thisReference = ec != null ? ec.getRuntimeInstance() : null; - // Compute aliases - Map> aliases = new HashMap>(); - Map localValues = new HashMap(); - analyzeEquivalenceClasses(services, sec, aliases, thisReference); - analyzeSequent(services, node.sequent(), aliases, thisReference); - analyzeUpdates(pair.first, services, heapLDT, aliases, localValues, ec, thisReference); - return new SequentInfo(aliases, localValues, ec, thisReference); - } - else { - return null; // Not the modality of interest. - } - } - - /** - * Analyzes the gievn {@link ISymbolicEquivalenceClass}es. - * @param services The {@link Services} to use. - * @param sec The {@link ISymbolicEquivalenceClass} to analyze. - * @param aliases The alias {@link Map} to fill. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeEquivalenceClasses(Services services, ImmutableList sec, Map> aliases, ReferencePrefix thisReference) { - if (sec != null) { - for (ISymbolicEquivalenceClass eq : sec) { - ImmutableList terms = eq.getTerms(); - List locations = new ArrayList(terms.size()); - for (Term term : terms) { - if (SymbolicExecutionUtil.hasReferenceSort(services, term)) { - Location location = toLocation(services, term); - if (location != null) { - locations.add(location); - } - } + /** + * Returns the found aliases. + * + * @return The found aliases. + */ + public Map> getAliases() { + return aliases; + } + + /** + * Returns the local values. + * + * @return The local values. + */ + public Map getLocalValues() { + return localValues; + } + + /** + * Returns the current {@link ExecutionContext}. + * + * @return The current {@link ExecutionContext}. + */ + public ExecutionContext getExecutionContext() { + return executionContext; + } + + /** + * Returns the this reference if available. + * + * @return The this reference if available. + */ + public ReferencePrefix getThisReference() { + return thisReference; + } + } + + /** + * Computes the aliases specified by the updates of the current {@link Node} at the application + * {@link PosInOccurrence} and computes the current {@code this} reference. + * + * @param node The {@link Node} to analyze. + * @return The computed {@link SequentInfo} or {@code null} if the {@link Node} is not + * supported. + */ + protected SequentInfo analyzeSequent(Node node, ImmutableList sec) { + PosInOccurrence pio = node.getAppliedRuleApp().posInOccurrence(); + Term topLevel = pio.sequentFormula().formula(); + Pair, Term> pair = TermBuilder.goBelowUpdates2(topLevel); + Term modalityTerm = pair.second; + SymbolicExecutionTermLabel label = + SymbolicExecutionUtil.getSymbolicExecutionLabel(modalityTerm); + Services services = node.proof().getServices(); + HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + if (label != null) { + // Solve this reference + ExecutionContext ec = + JavaTools.getInnermostExecutionContext(modalityTerm.javaBlock(), services); + ReferencePrefix thisReference = ec != null ? ec.getRuntimeInstance() : null; + // Compute aliases + Map> aliases = + new HashMap>(); + Map localValues = new HashMap(); + analyzeEquivalenceClasses(services, sec, aliases, thisReference); + analyzeSequent(services, node.sequent(), aliases, thisReference); + analyzeUpdates(pair.first, services, heapLDT, aliases, localValues, ec, thisReference); + return new SequentInfo(aliases, localValues, ec, thisReference); + } else { + return null; // Not the modality of interest. + } + } + + /** + * Analyzes the gievn {@link ISymbolicEquivalenceClass}es. + * + * @param services The {@link Services} to use. + * @param sec The {@link ISymbolicEquivalenceClass} to analyze. + * @param aliases The alias {@link Map} to fill. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeEquivalenceClasses(Services services, + ImmutableList sec, + Map> aliases, ReferencePrefix thisReference) { + if (sec != null) { + for (ISymbolicEquivalenceClass eq : sec) { + ImmutableList terms = eq.getTerms(); + List locations = new ArrayList(terms.size()); + for (Term term : terms) { + if (SymbolicExecutionUtil.hasReferenceSort(services, term)) { + Location location = toLocation(services, term); + if (location != null) { + locations.add(location); + } + } + } + if (locations.size() >= 2) { + Location first = null; + for (Location location : locations) { + if (first == null) { + first = location; + } else { + updateAliases(services, first, location, aliases, thisReference); + } + } + } } - if (locations.size() >= 2) { - Location first = null; - for (Location location : locations) { - if (first == null) { - first = location; - } - else { - updateAliases(services, first, location, aliases, thisReference); - } - } + } + } + + /** + * Analyzes the given {@link Sequent} for equalities specified by top level formulas. + * + * @param services The {@link Services} to use. + * @param sequent The {@link Sequent} to analyze. + * @param aliases The alias {@link Map} to fill. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeSequent(Services services, Sequent sequent, + Map> aliases, ReferencePrefix thisReference) { + for (SequentFormula sf : sequent.antecedent()) { + Term term = sf.formula(); + if (Equality.EQUALS == term.op()) { + analyzeEquality(services, term, aliases, thisReference); } - } - } - } + } + for (SequentFormula sf : sequent.succedent()) { + Term term = sf.formula(); + if (Junctor.NOT == term.op()) { + Term negatedTerm = term.sub(0); + if (Equality.EQUALS == negatedTerm.op()) { + analyzeEquality(services, negatedTerm, aliases, thisReference); + } + } + } + } - /** - * Analyzes the given {@link Sequent} for equalities specified by top level formulas. - * @param services The {@link Services} to use. - * @param sequent The {@link Sequent} to analyze. - * @param aliases The alias {@link Map} to fill. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeSequent(Services services, Sequent sequent, Map> aliases, ReferencePrefix thisReference) { - for (SequentFormula sf : sequent.antecedent()) { - Term term = sf.formula(); - if (Equality.EQUALS == term.op()) { - analyzeEquality(services, term, aliases, thisReference); - } - } - for (SequentFormula sf : sequent.succedent()) { - Term term = sf.formula(); - if (Junctor.NOT == term.op()) { - Term negatedTerm = term.sub(0); - if (Equality.EQUALS == negatedTerm.op()) { - analyzeEquality(services, negatedTerm, aliases, thisReference); + /** + * Analyzes the given equality {@link Term} for aliased locations. + * + * @param services The {@link Services} to use. + * @param equality The equality {@link Term} to analyze. + * @param aliases The alias {@link Map} to fill. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeEquality(Services services, Term equality, + Map> aliases, ReferencePrefix thisReference) { + Term firstSub = equality.sub(0); + Term secondSub = equality.sub(1); + if (SymbolicExecutionUtil.hasReferenceSort(services, firstSub) + && SymbolicExecutionUtil.hasReferenceSort(services, secondSub)) { + Location first = toLocation(services, firstSub); + Location second = toLocation(services, secondSub); + if (first != null && second != null) { + updateAliases(services, first, second, aliases, thisReference); } - } - } - } - - /** - * Analyzes the given equality {@link Term} for aliased locations. - * @param services The {@link Services} to use. - * @param equality The equality {@link Term} to analyze. - * @param aliases The alias {@link Map} to fill. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeEquality(Services services, Term equality, Map> aliases, ReferencePrefix thisReference) { - Term firstSub = equality.sub(0); - Term secondSub = equality.sub(1); - if (SymbolicExecutionUtil.hasReferenceSort(services, firstSub) && - SymbolicExecutionUtil.hasReferenceSort(services, secondSub)) { - Location first = toLocation(services, firstSub); - Location second = toLocation(services, secondSub); - if (first != null && second != null) { - updateAliases(services, first, second, aliases, thisReference); - } - } - } + } + } - /** - * Utility method used by {@link #analyzeSequent(Node)} to analyze the given updates. - * @param updates The update {@link Term}s to analyze. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} of the {@link Services}. - * @param aliases The alias {@link Map} to fill. - * @param localValues The local values to fill. - * @param ec The current {@link ExecutionContext}. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeUpdates(ImmutableList updates, - Services services, - HeapLDT heapLDT, - Map> aliases, - Map localValues, - ExecutionContext ec, - ReferencePrefix thisReference) { - for (Term update : updates) { - analyzeUpdate(update, services, heapLDT, aliases, localValues, ec, thisReference); - } - } - - /** - * Recursive utility method used by {@link #analyzeUpdates(ImmutableList, Services, HeapLDT, Map)} to analyze a given update. - * @param term The update {@link Term} to analyze. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} of the {@link Services}. - * @param aliases The alias {@link Map} to fill. - * @param localValues The local values to fill. - * @param ec The current {@link ExecutionContext}. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeUpdate(Term term, - Services services, - HeapLDT heapLDT, - Map> aliases, - Map localValues, - ExecutionContext ec, - ReferencePrefix thisReference) { - if (term.op() == UpdateJunctor.PARALLEL_UPDATE || - term.op() == UpdateApplication.UPDATE_APPLICATION) { - for (int i = 0 ; i < term.arity(); i++) { - analyzeUpdate(term.sub(i), services, heapLDT, aliases, localValues, ec, thisReference); - } - } - else if (term.op() instanceof ElementaryUpdate) { - UpdateableOperator target = ((ElementaryUpdate) term.op()).lhs(); - if (SymbolicExecutionUtil.isHeap(target, heapLDT)) { - analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); - } - else { - if (target instanceof ProgramVariable) { - localValues.put((ProgramVariable) target, term.sub(0)); + /** + * Utility method used by {@link #analyzeSequent(Node)} to analyze the given updates. + * + * @param updates The update {@link Term}s to analyze. + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} of the {@link Services}. + * @param aliases The alias {@link Map} to fill. + * @param localValues The local values to fill. + * @param ec The current {@link ExecutionContext}. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeUpdates(ImmutableList updates, Services services, HeapLDT heapLDT, + Map> aliases, Map localValues, + ExecutionContext ec, ReferencePrefix thisReference) { + for (Term update : updates) { + analyzeUpdate(update, services, heapLDT, aliases, localValues, ec, thisReference); + } + } + + /** + * Recursive utility method used by + * {@link #analyzeUpdates(ImmutableList, Services, HeapLDT, Map)} to analyze a given update. + * + * @param term The update {@link Term} to analyze. + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} of the {@link Services}. + * @param aliases The alias {@link Map} to fill. + * @param localValues The local values to fill. + * @param ec The current {@link ExecutionContext}. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeUpdate(Term term, Services services, HeapLDT heapLDT, + Map> aliases, Map localValues, + ExecutionContext ec, ReferencePrefix thisReference) { + if (term.op() == UpdateJunctor.PARALLEL_UPDATE + || term.op() == UpdateApplication.UPDATE_APPLICATION) { + for (int i = 0; i < term.arity(); i++) { + analyzeUpdate(term.sub(i), services, heapLDT, aliases, localValues, ec, + thisReference); } - Location sourceLocation = toLocation(services, term.sub(0)); - if (target instanceof ReferencePrefix && sourceLocation != null) { - Location targetLocation = toLocation(services, (ReferencePrefix) target, ec, thisReference); - updateAliases(services, targetLocation, sourceLocation, aliases, thisReference); + } else if (term.op() instanceof ElementaryUpdate) { + UpdateableOperator target = ((ElementaryUpdate) term.op()).lhs(); + if (SymbolicExecutionUtil.isHeap(target, heapLDT)) { + analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); + } else { + if (target instanceof ProgramVariable) { + localValues.put((ProgramVariable) target, term.sub(0)); + } + Location sourceLocation = toLocation(services, term.sub(0)); + if (target instanceof ReferencePrefix && sourceLocation != null) { + Location targetLocation = + toLocation(services, (ReferencePrefix) target, ec, thisReference); + updateAliases(services, targetLocation, sourceLocation, aliases, thisReference); + } } - } - } - else { - throw new IllegalArgumentException("Can not analyze update '" + term + "'."); - } - } + } else { + throw new IllegalArgumentException("Can not analyze update '" + term + "'."); + } + } + + /** + * Recursive utility method used by {@link #analyzeUpdate(Term, Services, HeapLDT, Map)} to + * analyze a given update. + * + * @param term The heap update {@link Term} to analyze. + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} of the {@link Services}. + * @param aliases The alias {@link Map} to fill. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void analyzeHeapUpdate(Term term, Services services, HeapLDT heapLDT, + Map> aliases, ReferencePrefix thisReference) { + final Function store = heapLDT.getStore(); + final Function create = heapLDT.getCreate(); + if (term.op() == store) { + // Analyze parent heap + analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); + // Check for alias in current store + if (SymbolicExecutionUtil.hasReferenceSort(services, term.sub(3))) { + Location source = toLocation(services, term.sub(3)); + if (source != null) { + Location targetPrefix = toLocation(services, term.sub(1)); + Location targetVariable = toLocation(services, term.sub(2)); + updateAliases(services, + targetPrefix != null ? targetPrefix.append(targetVariable) + : targetVariable, + source, aliases, thisReference); + } + } + } else if (term.op() == create) { + // Analyze parent heap + analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); + } else if (term.op() instanceof IProgramVariable) { + // Nothing to do, root of heap reached. + } else if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { + // Nothing to do, just another heap + } else { + throw new IllegalStateException("Can not analyze heap update '" + term + "'."); + } + } - /** - * Recursive utility method used by {@link #analyzeUpdate(Term, Services, HeapLDT, Map)} to analyze a given update. - * @param term The heap update {@link Term} to analyze. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} of the {@link Services}. - * @param aliases The alias {@link Map} to fill. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void analyzeHeapUpdate(Term term, - Services services, - HeapLDT heapLDT, - Map> aliases, - ReferencePrefix thisReference) { - final Function store = heapLDT.getStore(); - final Function create = heapLDT.getCreate(); - if (term.op() == store) { - // Analyze parent heap - analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); - // Check for alias in current store - if (SymbolicExecutionUtil.hasReferenceSort(services, term.sub(3))) { - Location source = toLocation(services, term.sub(3)); - if (source != null) { - Location targetPrefix = toLocation(services, term.sub(1)); - Location targetVariable = toLocation(services, term.sub(2)); - updateAliases(services, targetPrefix != null ? targetPrefix.append(targetVariable) : targetVariable, source, aliases, thisReference); + /** + * Recursive method to list all modified {@link Location}s in the given {@link Term}. + * + * @param term The update {@link Term} to analyze. + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} of the {@link Services}. + * @param listToFill The result {@link List} with {@link Location}s to fill. + * @param ec The current {@link ExecutionContext}. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void listModifiedLocations(Term term, Services services, HeapLDT heapLDT, + List listToFill, ExecutionContext ec, ReferencePrefix thisReference, + Set relevantLocations, Node node) throws ProofInputException { + if (term.op() == UpdateJunctor.PARALLEL_UPDATE + || term.op() == UpdateApplication.UPDATE_APPLICATION) { + for (int i = 0; i < term.arity(); i++) { + listModifiedLocations(term.sub(i), services, heapLDT, listToFill, ec, thisReference, + relevantLocations, node); } - } - } - else if (term.op() == create) { - // Analyze parent heap - analyzeHeapUpdate(term.sub(0), services, heapLDT, aliases, thisReference); - } - else if (term.op() instanceof IProgramVariable) { - // Nothing to do, root of heap reached. - } - else if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { - // Nothing to do, just another heap - } - else { - throw new IllegalStateException("Can not analyze heap update '" + term + "'."); - } - } - - /** - * Recursive method to list all modified {@link Location}s in the given {@link Term}. - * @param term The update {@link Term} to analyze. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} of the {@link Services}. - * @param listToFill The result {@link List} with {@link Location}s to fill. - * @param ec The current {@link ExecutionContext}. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void listModifiedLocations(Term term, - Services services, - HeapLDT heapLDT, - List listToFill, - ExecutionContext ec, - ReferencePrefix thisReference, - Set relevantLocations, - Node node) throws ProofInputException { - if (term.op() == UpdateJunctor.PARALLEL_UPDATE || - term.op() == UpdateApplication.UPDATE_APPLICATION) { - for (int i = 0 ; i < term.arity(); i++) { - listModifiedLocations(term.sub(i), services, heapLDT, listToFill, ec, thisReference, relevantLocations, node); - } - } - else if (term.op() instanceof ElementaryUpdate) { - UpdateableOperator target = ((ElementaryUpdate) term.op()).lhs(); - if (SymbolicExecutionUtil.isBaseHeap(target, heapLDT)) { - listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, relevantLocations, node); - } - else { - if (target instanceof ProgramVariable) { - listToFill.add(toLocation(services, (ProgramVariable) target, ec, thisReference)); + } else if (term.op() instanceof ElementaryUpdate) { + UpdateableOperator target = ((ElementaryUpdate) term.op()).lhs(); + if (SymbolicExecutionUtil.isBaseHeap(target, heapLDT)) { + listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, + relevantLocations, node); + } else { + if (target instanceof ProgramVariable) { + listToFill + .add(toLocation(services, (ProgramVariable) target, ec, thisReference)); + } } - } - } - else { - throw new IllegalArgumentException("Can not analyze update '" + term + "'."); - } - } + } else { + throw new IllegalArgumentException("Can not analyze update '" + term + "'."); + } + } - /** - * Recursive utility method used by {@link #listModifiedLocations(Term, Services, HeapLDT, List, ReferencePrefix)} to analyze a given update. - * @param term The heap update {@link Term} to analyze. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} of the {@link Services}. - * @param listToFill The result {@link List} with {@link Location}s to fill. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void listModifiedHeapLocations(Term term, - Services services, - HeapLDT heapLDT, - List listToFill, - ReferencePrefix thisReference, - Set relevantLocations, - Node node) throws ProofInputException { - if (term.op() == heapLDT.getStore()) { - // Analyze parent heap - listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, relevantLocations, node); - // Check for alias in current store - if (SymbolicExecutionUtil.hasReferenceSort(services, term.sub(3))) { - Location source = toLocation(services, term.sub(3)); - if (source != null) { - Location targetPrefix = toLocation(services, term.sub(1)); - listToFill.add(targetPrefix); + /** + * Recursive utility method used by + * {@link #listModifiedLocations(Term, Services, HeapLDT, List, ReferencePrefix)} to analyze a + * given update. + * + * @param term The heap update {@link Term} to analyze. + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} of the {@link Services}. + * @param listToFill The result {@link List} with {@link Location}s to fill. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void listModifiedHeapLocations(Term term, Services services, HeapLDT heapLDT, + List listToFill, ReferencePrefix thisReference, + Set relevantLocations, Node node) throws ProofInputException { + if (term.op() == heapLDT.getStore()) { + // Analyze parent heap + listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, + relevantLocations, node); + // Check for alias in current store + if (SymbolicExecutionUtil.hasReferenceSort(services, term.sub(3))) { + Location source = toLocation(services, term.sub(3)); + if (source != null) { + Location targetPrefix = toLocation(services, term.sub(1)); + listToFill.add(targetPrefix); + } } - } - } - else if (term.op() == heapLDT.getCreate()) { - // Analyze parent heap - listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, relevantLocations, node); - } - else if (term.op() instanceof IProgramVariable) { - // Nothing to do, root of heap reached. - } - else if (term.op() == heapLDT.getAnon()) { - if (!relevantLocations.isEmpty()) { // Nothing to do if relevant locations are empty - Term anonHeap = term.sub(2); - // Idea: Compute all values of relevant locations in a side proof. Modified locations are anonymized. - ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - ApplyStrategyInfo info = null; - try { - // Create location terms - List resultLocations = new ArrayList(relevantLocations.size()); - List resultTerms = new ArrayList(relevantLocations.size()); - List resultSorts = new ArrayList(relevantLocations.size()); - for (Location location : relevantLocations) { - Term locationTerm = location.toTerm(sideProofEnv.getServicesForEnvironment()); - if (!(locationTerm.op() instanceof IProgramVariable)) { // Ignore local variables. - resultLocations.add(location); - resultTerms.add(locationTerm); - resultSorts.add(locationTerm.sort()); - } - } - if (!resultTerms.isEmpty()) { - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(sideProofEnv.getServicesForEnvironment().getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, new ImmutableArray(resultSorts)); - // Create formula which contains the value interested in. - Term newTerm = sideProofEnv.getServicesForEnvironment().getTermBuilder().func(newPredicate, resultTerms.toArray(new Term[resultTerms.size()])); + } else if (term.op() == heapLDT.getCreate()) { + // Analyze parent heap + listModifiedHeapLocations(term.sub(0), services, heapLDT, listToFill, thisReference, + relevantLocations, node); + } else if (term.op() instanceof IProgramVariable) { + // Nothing to do, root of heap reached. + } else if (term.op() == heapLDT.getAnon()) { + if (!relevantLocations.isEmpty()) { // Nothing to do if relevant locations are empty + Term anonHeap = term.sub(2); + // Idea: Compute all values of relevant locations in a side proof. Modified + // locations are anonymized. + ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + ApplyStrategyInfo info = null; + try { + // Create location terms + List resultLocations = + new ArrayList(relevantLocations.size()); + List resultTerms = new ArrayList(relevantLocations.size()); + List resultSorts = new ArrayList(relevantLocations.size()); + for (Location location : relevantLocations) { + Term locationTerm = + location.toTerm(sideProofEnv.getServicesForEnvironment()); + if (!(locationTerm.op() instanceof IProgramVariable)) { // Ignore local + // variables. + resultLocations.add(location); + resultTerms.add(locationTerm); + resultSorts.add(locationTerm.sort()); + } + } + if (!resultTerms.isEmpty()) { + // Create predicate which will be used in formulas to store the value + // interested in. + Function newPredicate = new Function( + new Name(sideProofEnv.getServicesForEnvironment().getTermBuilder() + .newName("ResultPredicate")), + Sort.FORMULA, new ImmutableArray(resultSorts)); + // Create formula which contains the value interested in. + Term newTerm = sideProofEnv.getServicesForEnvironment().getTermBuilder() + .func(newPredicate, + resultTerms.toArray(new Term[resultTerms.size()])); - Sequent sequentToProve = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, node.getAppliedRuleApp().posInOccurrence(), newTerm); - ProofStarter starter = SideProofUtil.createSideProof(sideProofEnv, sequentToProve, "Analyze Anon Update"); - info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), - starter, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_NORMAL); - // Check for anonymized values in the side proof goals - assert !info.getProof().closed(); - for (Goal goal : info.getProof().openGoals()) { - Term operatorTerm = SymbolicExecutionSideProofUtil.extractOperatorTerm(goal, newPredicate); - assert operatorTerm != null; - for (int i = 0; i < operatorTerm.arity(); i++) { - Term valueTerm = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), operatorTerm.sub(i), services); - if (valueTerm.arity() >= 1) { - Term heap = valueTerm.sub(0); - if (anonHeap.equals(heap)) { - listToFill.add(resultLocations.get(i)); - } + Sequent sequentToProve = + SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, + node.getAppliedRuleApp().posInOccurrence(), newTerm); + ProofStarter starter = SideProofUtil.createSideProof(sideProofEnv, + sequentToProve, "Analyze Anon Update"); + info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), starter, + StrategyProperties.METHOD_CONTRACT, + StrategyProperties.LOOP_INVARIANT, StrategyProperties.QUERY_ON, + StrategyProperties.SPLITTING_NORMAL); + // Check for anonymized values in the side proof goals + assert !info.getProof().closed(); + for (Goal goal : info.getProof().openGoals()) { + Term operatorTerm = SymbolicExecutionSideProofUtil + .extractOperatorTerm(goal, newPredicate); + assert operatorTerm != null; + for (int i = 0; i < operatorTerm.arity(); i++) { + Term valueTerm = SymbolicExecutionUtil.replaceSkolemConstants( + goal.sequent(), operatorTerm.sub(i), services); + if (valueTerm.arity() >= 1) { + Term heap = valueTerm.sub(0); + if (anonHeap.equals(heap)) { + listToFill.add(resultLocations.get(i)); + } + } + } } - } - } - } - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Analyze Anon Update", info); + } + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore("Analyze Anon Update", info); + } } - } - } - else if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { - if (!relevantLocations.isEmpty()) { // Nothing to do if relevant locations are empty - // Idea: Compute all values of relevant locations in a side proof. Modified locations are anonymized. - ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - ApplyStrategyInfo info = null; - try { - // Create location terms - List resultLocations = new ArrayList(relevantLocations.size()); - List resultTerms = new ArrayList(relevantLocations.size()); - List resultSorts = new ArrayList(relevantLocations.size()); - for (Location location : relevantLocations) { - Term locationTerm = location.toTerm(sideProofEnv.getServicesForEnvironment()); - if (!(locationTerm.op() instanceof IProgramVariable)) { // Ignore local variables. - resultLocations.add(location); - resultTerms.add(locationTerm); - resultSorts.add(locationTerm.sort()); - } - } - if (!resultTerms.isEmpty()) { - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(sideProofEnv.getServicesForEnvironment().getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, new ImmutableArray(resultSorts)); - // Create formula which contains the value interested in. - TermBuilder tb = sideProofEnv.getServicesForEnvironment().getTermBuilder(); - Term newTerm = tb.func(newPredicate, resultTerms.toArray(new Term[resultTerms.size()])); - newTerm = tb.apply(tb.elementary(heapLDT.getHeapForName(HeapLDT.BASE_HEAP_NAME), term), newTerm); - Sequent sequentToProve = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, null, newTerm); - ProofStarter starter = SideProofUtil.createSideProof(sideProofEnv, sequentToProve, "Analyze Anon Update"); - info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), - starter, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_NORMAL); - // Check for anonymized values in the side proof goals - assert !info.getProof().closed(); - for (Goal goal : info.getProof().openGoals()) { - Term operatorTerm = SymbolicExecutionSideProofUtil.extractOperatorTerm(goal, newPredicate); - assert operatorTerm != null; - for (int i = 0; i < operatorTerm.arity(); i++) { - Term valueTerm = SymbolicExecutionUtil.replaceSkolemConstants(goal.sequent(), operatorTerm.sub(i), services); - if (valueTerm.arity() >= 1) { - Term heap = valueTerm.sub(0); - if (heap.containsLabel(ParameterlessTermLabel.ANON_HEAP_LABEL)) { - listToFill.add(resultLocations.get(i)); - } + } else if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { + if (!relevantLocations.isEmpty()) { // Nothing to do if relevant locations are empty + // Idea: Compute all values of relevant locations in a side proof. Modified + // locations are anonymized. + ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + ApplyStrategyInfo info = null; + try { + // Create location terms + List resultLocations = + new ArrayList(relevantLocations.size()); + List resultTerms = new ArrayList(relevantLocations.size()); + List resultSorts = new ArrayList(relevantLocations.size()); + for (Location location : relevantLocations) { + Term locationTerm = + location.toTerm(sideProofEnv.getServicesForEnvironment()); + if (!(locationTerm.op() instanceof IProgramVariable)) { // Ignore local + // variables. + resultLocations.add(location); + resultTerms.add(locationTerm); + resultSorts.add(locationTerm.sort()); } - } - } - } + } + if (!resultTerms.isEmpty()) { + // Create predicate which will be used in formulas to store the value + // interested in. + Function newPredicate = new Function( + new Name(sideProofEnv.getServicesForEnvironment().getTermBuilder() + .newName("ResultPredicate")), + Sort.FORMULA, new ImmutableArray(resultSorts)); + // Create formula which contains the value interested in. + TermBuilder tb = sideProofEnv.getServicesForEnvironment().getTermBuilder(); + Term newTerm = tb.func(newPredicate, + resultTerms.toArray(new Term[resultTerms.size()])); + newTerm = tb.apply( + tb.elementary(heapLDT.getHeapForName(HeapLDT.BASE_HEAP_NAME), term), + newTerm); + Sequent sequentToProve = SymbolicExecutionUtil + .createSequentToProveWithNewSuccedent(node, null, newTerm); + ProofStarter starter = SideProofUtil.createSideProof(sideProofEnv, + sequentToProve, "Analyze Anon Update"); + info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), starter, + StrategyProperties.METHOD_CONTRACT, + StrategyProperties.LOOP_INVARIANT, StrategyProperties.QUERY_ON, + StrategyProperties.SPLITTING_NORMAL); + // Check for anonymized values in the side proof goals + assert !info.getProof().closed(); + for (Goal goal : info.getProof().openGoals()) { + Term operatorTerm = SymbolicExecutionSideProofUtil + .extractOperatorTerm(goal, newPredicate); + assert operatorTerm != null; + for (int i = 0; i < operatorTerm.arity(); i++) { + Term valueTerm = SymbolicExecutionUtil.replaceSkolemConstants( + goal.sequent(), operatorTerm.sub(i), services); + if (valueTerm.arity() >= 1) { + Term heap = valueTerm.sub(0); + if (heap.containsLabel( + ParameterlessTermLabel.ANON_HEAP_LABEL)) { + listToFill.add(resultLocations.get(i)); + } + } + } + } + } + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore("Analyze Heap Assignment", info); + } } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Analyze Heap Assignment", info); + } else { + throw new IllegalStateException("Can not analyze update '" + term + "'."); + } + } + + /** + * Adds the found alias consisting of first and second {@link ReferencePrefix} to the alias + * {@link Map}. If required, all participating entries in the {@link Map} are updated to ensure + * consistency. + * + * @param services The {@link Services} to use. + * @param first The first alias. + * @param second The second alias. + * @param aliases The alias {@link Map} to update. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + */ + protected void updateAliases(Services services, Location first, Location second, + Map> aliases, ReferencePrefix thisReference) { + // Try to get Set for key + SortedSet firstValues = aliases.get(first); + SortedSet secondValues = aliases.get(second); + SortedSet values = null; + if (firstValues == null && secondValues == null) { + values = createSortedSet(); + aliases.put(first, values); + aliases.put(second, values); + } else if (firstValues != null && secondValues == null) { + values = firstValues; + aliases.put(second, values); + } else if (firstValues == null && secondValues != null) { + values = secondValues; + aliases.put(first, values); + } else if (firstValues != null && secondValues != null) { // both are not null + values = firstValues; + for (Location existingLocation : secondValues) { + aliases.put(existingLocation, values); } - } - } - else { - throw new IllegalStateException("Can not analyze update '" + term + "'."); - } - } + values.addAll(secondValues); + } else { + throw new IllegalStateException("Reached a state which should never happen."); // Can + // not + // happen! + } + values.add(first); + values.add(second); + } - /** - * Adds the found alias consisting of first and second {@link ReferencePrefix} to the alias {@link Map}. - * If required, all participating entries in the {@link Map} are updated to ensure consistency. - * @param services The {@link Services} to use. - * @param first The first alias. - * @param second The second alias. - * @param aliases The alias {@link Map} to update. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - */ - protected void updateAliases(Services services, - Location first, - Location second, - Map> aliases, - ReferencePrefix thisReference) { - // Try to get Set for key - SortedSet firstValues = aliases.get(first); - SortedSet secondValues = aliases.get(second); - SortedSet values = null; - if (firstValues == null && secondValues == null) { - values = createSortedSet(); - aliases.put(first, values); - aliases.put(second, values); - } - else if (firstValues != null && secondValues == null) { - values = firstValues; - aliases.put(second, values); - } - else if (firstValues == null && secondValues != null) { - values = secondValues; - aliases.put(first, values); - } - else if (firstValues != null && secondValues != null) { // both are not null - values = firstValues; - for (Location existingLocation : secondValues) { - aliases.put(existingLocation, values); - } - values.addAll(secondValues); - } - else { - throw new IllegalStateException("Reached a state which should never happen."); // Can not happen! - } - values.add(first); - values.add(second); - } - - /** - * Creates a {@link SortedSet} which ensures that the elements are sorted. - * @return The new created {@link SortedSet}. - */ - protected SortedSet createSortedSet() { - return new TreeSet(new Comparator() { - /** - * {@inheritDoc} - */ - @Override - public int compare(Location o1, Location o2) { - int o1DotCount = o1.getDepth(); - int o2DotCount = o2.getDepth(); - if (o1DotCount < o2DotCount) { - return 1; + /** + * Creates a {@link SortedSet} which ensures that the elements are sorted. + * + * @return The new created {@link SortedSet}. + */ + protected SortedSet createSortedSet() { + return new TreeSet(new Comparator() { + /** + * {@inheritDoc} + */ + @Override + public int compare(Location o1, Location o2) { + int o1DotCount = o1.getDepth(); + int o2DotCount = o2.getDepth(); + if (o1DotCount < o2DotCount) { + return 1; + } else if (o1DotCount > o2DotCount) { + return -1; + } else { + return o1.toString().compareTo(o2.toString()); + } } - else if (o1DotCount > o2DotCount) { - return -1; + }); // Order is important for normalization; + } + + /** + * Returns the representative alias for the given {@link ReferencePrefix}. + * + * @param services The {@link Services} to use. + * @param referencePrefix The {@link ReferencePrefix}. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return The representative alias. + */ + protected Location normalizeAlias(Services services, ReferencePrefix referencePrefix, + SequentInfo info) { + Location location = toLocation(services, referencePrefix, info.getExecutionContext(), + info.getThisReference()); + return normalizeAlias(services, location, info); + } + + /** + * Returns the representative alias for the given {@link Location}. + * + * @param services The {@link Services} to use. + * @param location The {@link Location}. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return The representative alias. + */ + protected Location normalizeAlias(Services services, Location location, SequentInfo info) { + ImmutableList normalizedAccesses = ImmutableSLList.nil(); + for (Access access : location.getAccesses()) { + if (access.isArrayIndex()) { + access = normalizeArrayIndex(access, info); } - else { - return o1.toString().compareTo(o2.toString()); + normalizedAccesses = normalizedAccesses.append(access); + Location oldLocation = new Location(normalizedAccesses); + Location newLocation = computeRepresentativeAlias(oldLocation, info.getAliases()); + if (!oldLocation.equals(newLocation)) { + normalizedAccesses = normalizeAlias(services, newLocation, info).getAccesses(); } - } - }); // Order is important for normalization; - } - - /** - * Returns the representative alias for the given {@link ReferencePrefix}. - * @param services The {@link Services} to use. - * @param referencePrefix The {@link ReferencePrefix}. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return The representative alias. - */ - protected Location normalizeAlias(Services services, - ReferencePrefix referencePrefix, - SequentInfo info) { - Location location = toLocation(services, referencePrefix, info.getExecutionContext(), info.getThisReference()); - return normalizeAlias(services, location, info); - } - - /** - * Returns the representative alias for the given {@link Location}. - * @param services The {@link Services} to use. - * @param location The {@link Location}. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return The representative alias. - */ - protected Location normalizeAlias(Services services, - Location location, - SequentInfo info) { - ImmutableList normalizedAccesses = ImmutableSLList.nil(); - for (Access access : location.getAccesses()) { - if (access.isArrayIndex()) { - access = normalizeArrayIndex(access, info); - } - normalizedAccesses = normalizedAccesses.append(access); - Location oldLocation = new Location(normalizedAccesses); - Location newLocation = computeRepresentativeAlias(oldLocation, info.getAliases()); - if (!oldLocation.equals(newLocation)) { - normalizedAccesses = normalizeAlias(services, newLocation, info).getAccesses(); - } - } - return new Location(normalizedAccesses); - } - - /** - * Normalizes the given array index. - * @param access The {@link Access} representing an array index. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return The normalized array access. - */ - protected Access normalizeArrayIndex(Access access, SequentInfo info) { - ImmutableArray oldTerms = access.getDimensionExpressions(); - Term[] newTerms = new Term[oldTerms.size()]; - for (int i = 0; i < newTerms.length; i++) { - Term oldTerm = oldTerms.get(i); - if (oldTerm.op() instanceof ProgramVariable) { - Term value = info.getLocalValues().get((ProgramVariable) oldTerm.op()); - if (value != null) { - oldTerm = value; + } + return new Location(normalizedAccesses); + } + + /** + * Normalizes the given array index. + * + * @param access The {@link Access} representing an array index. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return The normalized array access. + */ + protected Access normalizeArrayIndex(Access access, SequentInfo info) { + ImmutableArray oldTerms = access.getDimensionExpressions(); + Term[] newTerms = new Term[oldTerms.size()]; + for (int i = 0; i < newTerms.length; i++) { + Term oldTerm = oldTerms.get(i); + if (oldTerm.op() instanceof ProgramVariable) { + Term value = info.getLocalValues().get((ProgramVariable) oldTerm.op()); + if (value != null) { + oldTerm = value; + } } - } - newTerms[i] = oldTerm; - } - return new Access(new ImmutableArray(newTerms)); - } + newTerms[i] = oldTerm; + } + return new Access(new ImmutableArray(newTerms)); + } - /** - * Computes the representative alias of the given {@link Location}. - * @param location The given {@link Location}. - * @param aliases The available aliases. - * @return The representative alias. - */ - protected Location computeRepresentativeAlias(Location location, - Map> aliases) { - Set alternatives = aliases.get(location); - if (alternatives != null) { - return alternatives.iterator().next(); // Return first alternative - } - else { - return location; - } - } + /** + * Computes the representative alias of the given {@link Location}. + * + * @param location The given {@link Location}. + * @param aliases The available aliases. + * @return The representative alias. + */ + protected Location computeRepresentativeAlias(Location location, + Map> aliases) { + Set alternatives = aliases.get(location); + if (alternatives != null) { + return alternatives.iterator().next(); // Return first alternative + } else { + return location; + } + } - /** - * Computes the {@link ReferencePrefix} of the given {@link SourceElement}. - * @param sourceElement The {@link SourceElement} to work with. - * @return The {@link ReferencePrefix} or {@code null} if the {@link SourceElement} can't be represented as {@link ReferencePrefix}. - */ - protected ReferencePrefix toReferencePrefix(SourceElement sourceElement) { - if (sourceElement instanceof PassiveExpression) { - if (((PassiveExpression) sourceElement).getChildCount() != 1) { - throw new IllegalStateException("PassiveExpression '" + sourceElement + "' has not exactly one child."); - } - sourceElement = ((PassiveExpression) sourceElement).getChildAt(0); - } - if (sourceElement instanceof FieldReference) { - return (FieldReference) sourceElement; - } - else if (sourceElement instanceof ProgramVariable) { - return (ProgramVariable) sourceElement; - } - else if (sourceElement instanceof ArrayReference) { - return (ArrayReference) sourceElement; - } - else { - return null; - } - } + /** + * Computes the {@link ReferencePrefix} of the given {@link SourceElement}. + * + * @param sourceElement The {@link SourceElement} to work with. + * @return The {@link ReferencePrefix} or {@code null} if the {@link SourceElement} can't be + * represented as {@link ReferencePrefix}. + */ + protected ReferencePrefix toReferencePrefix(SourceElement sourceElement) { + if (sourceElement instanceof PassiveExpression) { + if (((PassiveExpression) sourceElement).getChildCount() != 1) { + throw new IllegalStateException( + "PassiveExpression '" + sourceElement + "' has not exactly one child."); + } + sourceElement = ((PassiveExpression) sourceElement).getChildAt(0); + } + if (sourceElement instanceof FieldReference) { + return (FieldReference) sourceElement; + } else if (sourceElement instanceof ProgramVariable) { + return (ProgramVariable) sourceElement; + } else if (sourceElement instanceof ArrayReference) { + return (ArrayReference) sourceElement; + } else { + return null; + } + } - /** - * Checks if the given {@link SourceElement} is directly or indirectly - * contained (aliased) in the {@link Set} of relevant locations. - * If it is contained, the element will be removed. - * @param services The {@link Services} to use. - * @param sourceElement The {@link SourceElement} to check. - * @param relevantLocations The {@link Set} with locations of interest. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing has changed. - */ - protected boolean removeRelevant(Services services, - ReferencePrefix sourceElement, - Set relevantLocations, - SequentInfo info) { - Location normalized = normalizeAlias(services, sourceElement, info); - return performRemoveRelevant(services, normalized, relevantLocations, info); - } + /** + * Checks if the given {@link SourceElement} is directly or indirectly contained (aliased) in + * the {@link Set} of relevant locations. If it is contained, the element will be removed. + * + * @param services The {@link Services} to use. + * @param sourceElement The {@link SourceElement} to check. + * @param relevantLocations The {@link Set} with locations of interest. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing + * has changed. + */ + protected boolean removeRelevant(Services services, ReferencePrefix sourceElement, + Set relevantLocations, SequentInfo info) { + Location normalized = normalizeAlias(services, sourceElement, info); + return performRemoveRelevant(services, normalized, relevantLocations, info); + } - /** - * Checks if the given {@link Location} is directly or indirectly - * contained (aliased) in the {@link Set} of relevant locations. - * If it is contained, the element will be removed. - * @param services The {@link Services} to use. - * @param location The {@link Location} to check. - * @param relevantLocations The {@link Set} with locations of interest. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing has changed. - */ - protected boolean removeRelevant(Services services, - Location location, - Set relevantLocations, - SequentInfo info) { - Location normalized = normalizeAlias(services, location, info); - return performRemoveRelevant(services, normalized, relevantLocations, info); - } + /** + * Checks if the given {@link Location} is directly or indirectly contained (aliased) in the + * {@link Set} of relevant locations. If it is contained, the element will be removed. + * + * @param services The {@link Services} to use. + * @param location The {@link Location} to check. + * @param relevantLocations The {@link Set} with locations of interest. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing + * has changed. + */ + protected boolean removeRelevant(Services services, Location location, + Set relevantLocations, SequentInfo info) { + Location normalized = normalizeAlias(services, location, info); + return performRemoveRelevant(services, normalized, relevantLocations, info); + } - /** - * Checks if the given {@link Location} is directly or indirectly - * contained (aliased) in the {@link Set} of relevant locations. - * If it is contained, the element will be removed. - * @param services The {@link Services} to use. - * @param normalized The {@link Location} to check. - * @param relevantLocations The {@link Set} with locations of interest. - * @param info The {@link SequentInfo} with the aliases and so on. - * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing has changed. - */ - protected boolean performRemoveRelevant(Services services, - Location normalized, - Set relevantLocations, - SequentInfo info) { - boolean relevant = false; - Iterator iterator = relevantLocations.iterator(); - while (!relevant && iterator.hasNext()) { - Location next = iterator.next(); - Location nextNormalized = normalizeAlias(services, next, info); - if (normalized.equals(nextNormalized)) { - iterator.remove(); - relevant = true; - } - } - return relevant; - } + /** + * Checks if the given {@link Location} is directly or indirectly contained (aliased) in the + * {@link Set} of relevant locations. If it is contained, the element will be removed. + * + * @param services The {@link Services} to use. + * @param normalized The {@link Location} to check. + * @param relevantLocations The {@link Set} with locations of interest. + * @param info The {@link SequentInfo} with the aliases and so on. + * @return {@code true} is relevant and was removed, {@code false} is not relevant and nothing + * has changed. + */ + protected boolean performRemoveRelevant(Services services, Location normalized, + Set relevantLocations, SequentInfo info) { + boolean relevant = false; + Iterator iterator = relevantLocations.iterator(); + while (!relevant && iterator.hasNext()) { + Location next = iterator.next(); + Location nextNormalized = normalizeAlias(services, next, info); + if (normalized.equals(nextNormalized)) { + iterator.remove(); + relevant = true; + } + } + return relevant; + } - /** - * Converts the given {@link ReferencePrefix} into a {@link Location}. - * @param services The {@link Services} to use. - * @param prefix The {@link ReferencePrefix} to convert. - * @param ec The current {@link ExecutionContext}. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - * @return The {@link Location} representing the given {@link ReferencePrefix}. - */ - protected Location toLocation(Services services, - ReferencePrefix prefix, - ExecutionContext ec, - ReferencePrefix thisReference) { - ImmutableList accesses = toLocationRecursive(services, prefix, ec, thisReference, ImmutableSLList.nil()); - return new Location(accesses); - } - - /** - * Utility method used by {@link #toLocation(Services, ReferencePrefix, ReferencePrefix)} - * to recursively extract the {@link Access} instances. - * @param services The {@link Services} to use. - * @param prefix The {@link ReferencePrefix} to work with. - * @param ec The current {@link ExecutionContext}. - * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} ({@link ThisReference}). - * @param children The already known child {@link Access}s. - * @return An {@link ImmutableList} containing all {@link Access}s of the {@link ReferencePrefix} in the order of access. - */ - protected ImmutableList toLocationRecursive(Services services, - ReferencePrefix prefix, - ExecutionContext ec, - ReferencePrefix thisReference, - ImmutableList children) { - if (prefix instanceof ProgramVariable) { - return children.prepend(new Access((ProgramVariable) prefix)); - } - else if (prefix instanceof FieldReference) { - FieldReference fr = (FieldReference) prefix; - ReferencePrefix parent = fr.getReferencePrefix(); - children = children.prepend(new Access(fr.getProgramVariable())); - if (parent != null) { - return toLocationRecursive(services, parent, ec, thisReference, children); - } - else { - return children; - } - } - else if (prefix instanceof ThisReference) { - if (thisReference instanceof ProgramVariable) { - return children.prepend(new Access((ProgramVariable) thisReference)); - } - else if (thisReference instanceof FieldReference) { - return toLocationRecursive(services, thisReference, ec, thisReference, children); - } - else { - throw new IllegalStateException("Unsupported this reference '" + thisReference + "'."); - } - } - else if (prefix instanceof ArrayReference) { - ArrayReference ar = (ArrayReference) prefix; - children = children.prepend(new Access(toTerm(services, ar.getDimensionExpressions(), ec))); - return toLocationRecursive(services, ar.getReferencePrefix(), ec, thisReference, children); - } - else { - throw new IllegalStateException("Unsupported prefix '" + prefix + "'."); - } - } - - /** - * Converts the given {@link Expression}s into {@link Term}s. - * @param services The {@link Services} to use. - * @param expressions The {@link Expression}s to convert. - * @param ec The current {@link ExecutionContext}. - * @return The created {@link Term}s. - */ - public static ImmutableArray toTerm(Services services, - ImmutableArray expressions, - ExecutionContext ec) { - Term[] terms = new Term[expressions.size()]; - int i = 0; - for (Expression expression : expressions) { - terms[i] = AbstractSlicer.toTerm(services, expression, ec); - i++; - } - return new ImmutableArray(terms); - } - - /** - * Converts the given {@link Expression} into a {@link Term}. - * @param services The {@link Services} to use. - * @param expression The {@link Expression} to convert. - * @param ec The current {@link ExecutionContext}. - * @return The created {@link Term}. - */ - public static Term toTerm(Services services, - Expression expression, - ExecutionContext ec) { - return services.getTypeConverter().convertToLogicElement(expression, ec); - } + /** + * Converts the given {@link ReferencePrefix} into a {@link Location}. + * + * @param services The {@link Services} to use. + * @param prefix The {@link ReferencePrefix} to convert. + * @param ec The current {@link ExecutionContext}. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + * @return The {@link Location} representing the given {@link ReferencePrefix}. + */ + protected Location toLocation(Services services, ReferencePrefix prefix, ExecutionContext ec, + ReferencePrefix thisReference) { + ImmutableList accesses = toLocationRecursive(services, prefix, ec, thisReference, + ImmutableSLList.nil()); + return new Location(accesses); + } - /** - * Converts the given {@link Term} into a {@link Location}. - * @param services The {@link Services} to use. - * @param term The {@link Term} to convert. - * @return The {@link Location} or {@code null} if the {@link Term} could not be represented as {@link Location}. - */ - public static Location toLocation(Services services, Term term) { - if (term.op() instanceof ProgramVariable) { - return new Location(new Access((ProgramVariable) term.op())); - } - else if (SymbolicExecutionUtil.isNullSort(term.sort(), services)) { - return null; - } - else { - HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - if (term.op() == heapLDT.getSelect(term.sort(), services)) { - Location prefix = toLocation(services, term.sub(1)); - Term arrayIndex = SymbolicExecutionUtil.getArrayIndex(services, heapLDT, term.sub(2)); - if (arrayIndex != null) { - return prefix.append(new Access(arrayIndex)); - } - else { - Location variable = toLocation(services, term.sub(2)); - return prefix != null ? prefix.append(variable) : variable; + /** + * Utility method used by {@link #toLocation(Services, ReferencePrefix, ReferencePrefix)} to + * recursively extract the {@link Access} instances. + * + * @param services The {@link Services} to use. + * @param prefix The {@link ReferencePrefix} to work with. + * @param ec The current {@link ExecutionContext}. + * @param thisReference The {@link ReferencePrefix} which is represented by {@code this} + * ({@link ThisReference}). + * @param children The already known child {@link Access}s. + * @return An {@link ImmutableList} containing all {@link Access}s of the + * {@link ReferencePrefix} in the order of access. + */ + protected ImmutableList toLocationRecursive(Services services, ReferencePrefix prefix, + ExecutionContext ec, ReferencePrefix thisReference, ImmutableList children) { + if (prefix instanceof ProgramVariable) { + return children.prepend(new Access((ProgramVariable) prefix)); + } else if (prefix instanceof FieldReference) { + FieldReference fr = (FieldReference) prefix; + ReferencePrefix parent = fr.getReferencePrefix(); + children = children.prepend(new Access(fr.getProgramVariable())); + if (parent != null) { + return toLocationRecursive(services, parent, ec, thisReference, children); + } else { + return children; } - } - else { - String name = term.op().name().toString(); - int index = name.toString().indexOf("::"); - if (index >= 0) { - String fullTypeName = name.substring(0, index); - String fieldName = name.substring(index + 3); - ProgramVariable pv = services.getJavaInfo().getAttribute(fullTypeName + "::" + fieldName); - assert term.op() == services.getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable) pv, services); - return new Location(new Access(pv)); + } else if (prefix instanceof ThisReference) { + if (thisReference instanceof ProgramVariable) { + return children.prepend(new Access((ProgramVariable) thisReference)); + } else if (thisReference instanceof FieldReference) { + return toLocationRecursive(services, thisReference, ec, thisReference, children); + } else { + throw new IllegalStateException( + "Unsupported this reference '" + thisReference + "'."); } - else { - return null; + } else if (prefix instanceof ArrayReference) { + ArrayReference ar = (ArrayReference) prefix; + children = children + .prepend(new Access(toTerm(services, ar.getDimensionExpressions(), ec))); + return toLocationRecursive(services, ar.getReferencePrefix(), ec, thisReference, + children); + } else { + throw new IllegalStateException("Unsupported prefix '" + prefix + "'."); + } + } + + /** + * Converts the given {@link Expression}s into {@link Term}s. + * + * @param services The {@link Services} to use. + * @param expressions The {@link Expression}s to convert. + * @param ec The current {@link ExecutionContext}. + * @return The created {@link Term}s. + */ + public static ImmutableArray toTerm(Services services, + ImmutableArray expressions, ExecutionContext ec) { + Term[] terms = new Term[expressions.size()]; + int i = 0; + for (Expression expression : expressions) { + terms[i] = AbstractSlicer.toTerm(services, expression, ec); + i++; + } + return new ImmutableArray(terms); + } + + /** + * Converts the given {@link Expression} into a {@link Term}. + * + * @param services The {@link Services} to use. + * @param expression The {@link Expression} to convert. + * @param ec The current {@link ExecutionContext}. + * @return The created {@link Term}. + */ + public static Term toTerm(Services services, Expression expression, ExecutionContext ec) { + return services.getTypeConverter().convertToLogicElement(expression, ec); + } + + /** + * Converts the given {@link Term} into a {@link Location}. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to convert. + * @return The {@link Location} or {@code null} if the {@link Term} could not be represented as + * {@link Location}. + */ + public static Location toLocation(Services services, Term term) { + if (term.op() instanceof ProgramVariable) { + return new Location(new Access((ProgramVariable) term.op())); + } else if (SymbolicExecutionUtil.isNullSort(term.sort(), services)) { + return null; + } else { + HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + if (term.op() == heapLDT.getSelect(term.sort(), services)) { + Location prefix = toLocation(services, term.sub(1)); + Term arrayIndex = + SymbolicExecutionUtil.getArrayIndex(services, heapLDT, term.sub(2)); + if (arrayIndex != null) { + return prefix.append(new Access(arrayIndex)); + } else { + Location variable = toLocation(services, term.sub(2)); + return prefix != null ? prefix.append(variable) : variable; + } + } else { + String name = term.op().name().toString(); + int index = name.toString().indexOf("::"); + if (index >= 0) { + String fullTypeName = name.substring(0, index); + String fieldName = name.substring(index + 3); + ProgramVariable pv = + services.getJavaInfo().getAttribute(fullTypeName + "::" + fieldName); + assert term.op() == services.getTypeConverter().getHeapLDT() + .getFieldSymbolForPV((LocationVariable) pv, services); + return new Location(new Access(pv)); + } else { + return null; + } } - } - } - } + } + } - /** - * Returns the first found alternative which is still valid. - * @param oldAlternatives The old alternatives. - * @param newAlternatives The new alternatives. - * @return The found alternative or {@code null} if not available. - */ - protected Location findNewAlternative(final SortedSet oldAlternatives, - final SortedSet newAlternatives) { - return CollectionUtil.search(oldAlternatives, new IFilter() { - @Override - public boolean select(Location element) { - return !newAlternatives.contains(element); - } - }); - } + /** + * Returns the first found alternative which is still valid. + * + * @param oldAlternatives The old alternatives. + * @param newAlternatives The new alternatives. + * @return The found alternative or {@code null} if not available. + */ + protected Location findNewAlternative(final SortedSet oldAlternatives, + final SortedSet newAlternatives) { + return CollectionUtil.search(oldAlternatives, new IFilter() { + @Override + public boolean select(Location element) { + return !newAlternatives.contains(element); + } + }); + } - /** - * Computes the length of a common prefix. - * @param candidates The possible candidates. - * @param toCheck The {@link ImmutableList} to check. - * @return The common prefix length which is {@code 0} if no elements are common. - */ - public static int computeFirstCommonPrefixLength(ImmutableList> candidates, - ImmutableList toCheck) { - int commonLength = 0; - Iterator> iter = candidates.iterator(); - while (commonLength < 1 && iter.hasNext()) { - ImmutableList next = iter.next(); - if (startsWith(toCheck, next)) { - commonLength = next.size(); - } - } - return commonLength; - } + /** + * Computes the length of a common prefix. + * + * @param candidates The possible candidates. + * @param toCheck The {@link ImmutableList} to check. + * @return The common prefix length which is {@code 0} if no elements are common. + */ + public static int computeFirstCommonPrefixLength(ImmutableList> candidates, + ImmutableList toCheck) { + int commonLength = 0; + Iterator> iter = candidates.iterator(); + while (commonLength < 1 && iter.hasNext()) { + ImmutableList next = iter.next(); + if (startsWith(toCheck, next)) { + commonLength = next.size(); + } + } + return commonLength; + } - /** - * Checks if the given {@link ImmutableList} starts with the given prefix. - * @param list The {@link List} to check. - * @param prefix The prefix to check. - * @return {@code true} the first elements in the {@link ImmutableList} are the prefix, {@code false} if the first elements are not equal to the prefix. - */ - public static boolean startsWith(ImmutableList list, ImmutableList prefix) { - if (list.size() >= prefix.size()) { - Iterator listIter = list.iterator(); - Iterator prefixIter = prefix.iterator(); - boolean same = true; - while (same && prefixIter.hasNext()) { - T listNext = listIter.next(); - T prefixNext = prefixIter.next(); - if (!ObjectUtil.equals(listNext, prefixNext)) { - same = false; + /** + * Checks if the given {@link ImmutableList} starts with the given prefix. + * + * @param list The {@link List} to check. + * @param prefix The prefix to check. + * @return {@code true} the first elements in the {@link ImmutableList} are the prefix, + * {@code false} if the first elements are not equal to the prefix. + */ + public static boolean startsWith(ImmutableList list, ImmutableList prefix) { + if (list.size() >= prefix.size()) { + Iterator listIter = list.iterator(); + Iterator prefixIter = prefix.iterator(); + boolean same = true; + while (same && prefixIter.hasNext()) { + T listNext = listIter.next(); + T prefixNext = prefixIter.next(); + if (!ObjectUtil.equals(listNext, prefixNext)) { + same = false; + } } - } - return same; - } - else { - return false; - } - } + return same; + } else { + return false; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Access.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Access.java index f0b0b0e457c..cf098010678 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Access.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Access.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.slicing; import org.key_project.util.collection.ImmutableArray; @@ -7,109 +10,113 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; public class Access { - /** - * The {@link ProgramVariable} or {@code null} if an array index is accessed. - */ - private final ProgramVariable programVariable; - - /** - * The accessed array index or {@code null} if it is not an array access. - */ - private final ImmutableArray dimensionExpressions; + /** + * The {@link ProgramVariable} or {@code null} if an array index is accessed. + */ + private final ProgramVariable programVariable; - /** - * Constructor. - * @param programVariable The accessed {@link ProgramVariable}. - */ - public Access(ProgramVariable programVariable) { - assert programVariable != null; - this.programVariable = programVariable; - this.dimensionExpressions = null; - } + /** + * The accessed array index or {@code null} if it is not an array access. + */ + private final ImmutableArray dimensionExpressions; - /** - * Constructor. - * @param dimensionExpressions The accessed array index. - */ - public Access(ImmutableArray dimensionExpressions) { - assert dimensionExpressions != null; - this.programVariable = null; - this.dimensionExpressions = dimensionExpressions; - } + /** + * Constructor. + * + * @param programVariable The accessed {@link ProgramVariable}. + */ + public Access(ProgramVariable programVariable) { + assert programVariable != null; + this.programVariable = programVariable; + this.dimensionExpressions = null; + } - /** - * Constructor. - * @param dimensionExpressions The accessed array index. - */ - public Access(Term... dimensionExpressions) { - assert dimensionExpressions != null; - this.programVariable = null; - this.dimensionExpressions = new ImmutableArray(dimensionExpressions); - } + /** + * Constructor. + * + * @param dimensionExpressions The accessed array index. + */ + public Access(ImmutableArray dimensionExpressions) { + assert dimensionExpressions != null; + this.programVariable = null; + this.dimensionExpressions = dimensionExpressions; + } - /** - * Returns the {@link ProgramVariable} or {@code null} if an array index is accessed. - * @return The {@link ProgramVariable} or {@code null} if an array index is accessed. - */ - public ProgramVariable getProgramVariable() { - return programVariable; - } + /** + * Constructor. + * + * @param dimensionExpressions The accessed array index. + */ + public Access(Term... dimensionExpressions) { + assert dimensionExpressions != null; + this.programVariable = null; + this.dimensionExpressions = new ImmutableArray(dimensionExpressions); + } - /** - * Returns the accessed array index or {@code null} if it is not an array access. - * @return The accessed array index or {@code null} if it is not an array access. - */ - public ImmutableArray getDimensionExpressions() { - return dimensionExpressions; - } + /** + * Returns the {@link ProgramVariable} or {@code null} if an array index is accessed. + * + * @return The {@link ProgramVariable} or {@code null} if an array index is accessed. + */ + public ProgramVariable getProgramVariable() { + return programVariable; + } - /** - * Checks if an array index is accessed. - * @return {@code true} array index is accessed, {@code false} otherwise. - */ - public boolean isArrayIndex() { - return dimensionExpressions != null; - } + /** + * Returns the accessed array index or {@code null} if it is not an array access. + * + * @return The accessed array index or {@code null} if it is not an array access. + */ + public ImmutableArray getDimensionExpressions() { + return dimensionExpressions; + } - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int hashcode = 5; - hashcode = hashcode * 17 + (programVariable != null ? programVariable.hashCode() : 0); - hashcode = hashcode * 17 + (dimensionExpressions != null ? dimensionExpressions.hashCode() : 0); - return hashcode; - } + /** + * Checks if an array index is accessed. + * + * @return {@code true} array index is accessed, {@code false} otherwise. + */ + public boolean isArrayIndex() { + return dimensionExpressions != null; + } - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof Access) { - Access other = (Access) obj; - return ObjectUtil.equals(programVariable, other.getProgramVariable()) && - ObjectUtil.equals(dimensionExpressions, other.getDimensionExpressions()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int hashcode = 5; + hashcode = hashcode * 17 + (programVariable != null ? programVariable.hashCode() : 0); + hashcode = hashcode * 17 + + (dimensionExpressions != null ? dimensionExpressions.hashCode() : 0); + return hashcode; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - if (programVariable != null) { - return programVariable.toString(); - } - else if (dimensionExpressions != null) { - return dimensionExpressions.toString(); - } - else { - return "Undefined"; - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Access) { + Access other = (Access) obj; + return ObjectUtil.equals(programVariable, other.getProgramVariable()) + && ObjectUtil.equals(dimensionExpressions, other.getDimensionExpressions()); + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + if (programVariable != null) { + return programVariable.toString(); + } else if (dimensionExpressions != null) { + return dimensionExpressions.toString(); + } else { + return "Undefined"; + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Location.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Location.java index b3a745052bf..00cf92617b6 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Location.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/Location.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.slicing; import org.key_project.util.collection.ImmutableList; @@ -11,149 +14,156 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * Represents a location like a local variable, method parameter, static field - * or an instance field on a specified object. + * Represents a location like a local variable, method parameter, static field or an instance field + * on a specified object. + * * @author Martin Hentschel */ public class Location { - /** - * The {@link Access} path. - */ - private final ImmutableList accesses; + /** + * The {@link Access} path. + */ + private final ImmutableList accesses; - /** - * Constructor. - * @param accesses The {@link Access} path. - */ - public Location(ImmutableList accesses) { - assert accesses != null; - this.accesses = accesses; - } + /** + * Constructor. + * + * @param accesses The {@link Access} path. + */ + public Location(ImmutableList accesses) { + assert accesses != null; + this.accesses = accesses; + } - /** - * Constructor. - * @param accesses The {@link Access} path. - */ - public Location(Access... accesses) { - assert accesses != null; - this.accesses = ImmutableSLList.nil().append(accesses); - } + /** + * Constructor. + * + * @param accesses The {@link Access} path. + */ + public Location(Access... accesses) { + assert accesses != null; + this.accesses = ImmutableSLList.nil().append(accesses); + } - /** - * Returns the {@link Access} path. - * @return The {@link Access} path. - */ - public ImmutableList getAccesses() { - return accesses; - } - - /** - * Returns the access depth. - * @return The access depth. - */ - public int getDepth() { - return accesses.size(); - } + /** + * Returns the {@link Access} path. + * + * @return The {@link Access} path. + */ + public ImmutableList getAccesses() { + return accesses; + } - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int hashcode = 5; - hashcode = hashcode * 17 + (accesses != null ? accesses.hashCode() : 0); - return hashcode; - } + /** + * Returns the access depth. + * + * @return The access depth. + */ + public int getDepth() { + return accesses.size(); + } - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof Location) { - Location other = (Location) obj; - return ObjectUtil.equals(accesses, other.getAccesses()); - } - else { - return false; - } - } + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int hashcode = 5; + hashcode = hashcode * 17 + (accesses != null ? accesses.hashCode() : 0); + return hashcode; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - boolean afterFirst = false; - for (Access access : accesses) { - if (afterFirst) { - sb.append('.'); - } - else { - afterFirst = true; - } - sb.append(access); - } - return sb.toString(); - } + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Location) { + Location other = (Location) obj; + return ObjectUtil.equals(accesses, other.getAccesses()); + } else { + return false; + } + } - /** - * Creates a new {@link Location} in which the sub is appended. - * @param sub The {@link Location} to append. - * @return The new {@link Location}. - */ - public Location append(Location sub) { - return new Location(accesses.append(sub.getAccesses())); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + boolean afterFirst = false; + for (Access access : accesses) { + if (afterFirst) { + sb.append('.'); + } else { + afterFirst = true; + } + sb.append(access); + } + return sb.toString(); + } - /** - * Creates a new {@link Location} in which the sub is appended. - * @param sub The {@link Access} to append. - * @return The new {@link Location}. - */ - public Location append(Access sub) { - return new Location(accesses.append(sub)); - } + /** + * Creates a new {@link Location} in which the sub is appended. + * + * @param sub The {@link Location} to append. + * @return The new {@link Location}. + */ + public Location append(Location sub) { + return new Location(accesses.append(sub.getAccesses())); + } - /** - * Converts this {@link Location} into a {@link Term}. - * @param services The {@link Services} to use. - * @return The created {@link Term}. - */ - public Term toTerm(Services services) { - Term parent = null; - for (Access access : accesses) { - if (access.isArrayIndex()) { - // Special handling for array indices. - assert parent != null; - assert access.getDimensionExpressions().size() == 1; - parent = services.getTermBuilder().dotArr(parent, access.getDimensionExpressions().get(0)); - } - else if (SymbolicExecutionUtil.isStaticVariable(access.getProgramVariable())) { - // Static field access - assert parent == null; - Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)access.getProgramVariable(), services); - parent = services.getTermBuilder().staticDot(access.getProgramVariable().sort(), function); - } - else if (parent == null) { - // Direct access to a variable - assert parent == null; - parent = services.getTermBuilder().var(access.getProgramVariable()); - } - else if (services.getJavaInfo().getArrayLength() == access.getProgramVariable()) { - // Special handling for length attribute of arrays - assert parent != null; - Function function = services.getTypeConverter().getHeapLDT().getLength(); - parent = services.getTermBuilder().func(function, parent); - } - else { - // Field access on the parent variable - assert parent != null; - Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)access.getProgramVariable(), services); - parent = services.getTermBuilder().dot(access.getProgramVariable().sort(), parent, function); - } - } - return parent; - } -} \ No newline at end of file + /** + * Creates a new {@link Location} in which the sub is appended. + * + * @param sub The {@link Access} to append. + * @return The new {@link Location}. + */ + public Location append(Access sub) { + return new Location(accesses.append(sub)); + } + + /** + * Converts this {@link Location} into a {@link Term}. + * + * @param services The {@link Services} to use. + * @return The created {@link Term}. + */ + public Term toTerm(Services services) { + Term parent = null; + for (Access access : accesses) { + if (access.isArrayIndex()) { + // Special handling for array indices. + assert parent != null; + assert access.getDimensionExpressions().size() == 1; + parent = services.getTermBuilder().dotArr(parent, + access.getDimensionExpressions().get(0)); + } else if (SymbolicExecutionUtil.isStaticVariable(access.getProgramVariable())) { + // Static field access + assert parent == null; + Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV( + (LocationVariable) access.getProgramVariable(), services); + parent = services.getTermBuilder().staticDot(access.getProgramVariable().sort(), + function); + } else if (parent == null) { + // Direct access to a variable + assert parent == null; + parent = services.getTermBuilder().var(access.getProgramVariable()); + } else if (services.getJavaInfo().getArrayLength() == access.getProgramVariable()) { + // Special handling for length attribute of arrays + assert parent != null; + Function function = services.getTypeConverter().getHeapLDT().getLength(); + parent = services.getTermBuilder().func(function, parent); + } else { + // Field access on the parent variable + assert parent != null; + Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV( + (LocationVariable) access.getProgramVariable(), services); + parent = services.getTermBuilder().dot(access.getProgramVariable().sort(), parent, + function); + } + } + return parent; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/ThinBackwardSlicer.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/ThinBackwardSlicer.java index 08adcab9b88..9788b93f426 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/ThinBackwardSlicer.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/slicing/ThinBackwardSlicer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.slicing; import java.util.LinkedList; @@ -22,78 +25,75 @@ /** * Implementation of thin backward slicing. + * * @author Martin Hentschel */ public class ThinBackwardSlicer extends AbstractBackwardSlicer { - /** - * {@inheritDoc} - */ - @Override - protected boolean accept(Node node, - Node previousChild, - Services services, - Set relevantLocations, - SequentInfo info, - SourceElement activeStatement) throws ProofInputException { - try { - boolean accept = false; - if (activeStatement instanceof CopyAssignment) { - CopyAssignment copyAssignment = (CopyAssignment) activeStatement; - ImmutableArray arguments = copyAssignment.getArguments(); - if (arguments.size() >= 1) { - SourceElement originalTarget = arguments.get(0); - ReferencePrefix relevantTarget = toReferencePrefix(originalTarget); - if (relevantTarget != null && removeRelevant(services, relevantTarget, relevantLocations, info)) { - accept = true; - for (int i = 1; i < arguments.size(); i++) { - Expression read = arguments.get(i); - updateRelevantLocations(read, relevantLocations, info, services); - } - } + /** + * {@inheritDoc} + */ + @Override + protected boolean accept(Node node, Node previousChild, Services services, + Set relevantLocations, SequentInfo info, SourceElement activeStatement) + throws ProofInputException { + try { + boolean accept = false; + if (activeStatement instanceof CopyAssignment) { + CopyAssignment copyAssignment = (CopyAssignment) activeStatement; + ImmutableArray arguments = copyAssignment.getArguments(); + if (arguments.size() >= 1) { + SourceElement originalTarget = arguments.get(0); + ReferencePrefix relevantTarget = toReferencePrefix(originalTarget); + if (relevantTarget != null + && removeRelevant(services, relevantTarget, relevantLocations, info)) { + accept = true; + for (int i = 1; i < arguments.size(); i++) { + Expression read = arguments.get(i); + updateRelevantLocations(read, relevantLocations, info, services); + } + } + } + } else if (activeStatement instanceof MethodBodyStatement) { + MethodBodyStatement mbs = (MethodBodyStatement) activeStatement; + IProgramVariable resultVariable = mbs.getResultVariable(); + ReferencePrefix relevantTarget = toReferencePrefix(resultVariable); + if (relevantTarget != null + && removeRelevant(services, relevantTarget, relevantLocations, info)) { + accept = true; + } + } else if (SymbolicExecutionUtil.isLoopInvariant(node, node.getAppliedRuleApp()) + || SymbolicExecutionUtil.isOperationContract(node, node.getAppliedRuleApp()) + || SymbolicExecutionUtil.isBlockSpecificationElement(node, + node.getAppliedRuleApp())) { + // Compute this reference + PosInOccurrence pio = node.getAppliedRuleApp().posInOccurrence(); + // Compute modified locations + List modifiedLocations = new LinkedList(); + Term loopConditionModalityTerm = + SymbolicExecutionUtil.posInOccurrenceInOtherNode(node, pio, previousChild); + if (loopConditionModalityTerm.op() != UpdateApplication.UPDATE_APPLICATION) { + throw new IllegalStateException( + "Use Loop Invariant/Operation Contract rule implementation has changed at node " + + node.serialNr() + "."); + } + Term updateTerm = UpdateApplication.getTarget(loopConditionModalityTerm); + while (updateTerm.op() == UpdateApplication.UPDATE_APPLICATION) { + listModifiedLocations(UpdateApplication.getUpdate(updateTerm), services, + services.getTypeConverter().getHeapLDT(), modifiedLocations, + info.getExecutionContext(), info.getThisReference(), relevantLocations, + previousChild); + updateTerm = UpdateApplication.getTarget(updateTerm); + } + // Check modified locations + for (Location location : modifiedLocations) { + if (removeRelevant(services, location, relevantLocations, info)) { + accept = true; + } + } } - } - else if (activeStatement instanceof MethodBodyStatement) { - MethodBodyStatement mbs = (MethodBodyStatement) activeStatement; - IProgramVariable resultVariable = mbs.getResultVariable(); - ReferencePrefix relevantTarget = toReferencePrefix(resultVariable); - if (relevantTarget != null && removeRelevant(services, relevantTarget, relevantLocations, info)) { - accept = true; - } - } - else if (SymbolicExecutionUtil.isLoopInvariant(node, node.getAppliedRuleApp()) || - SymbolicExecutionUtil.isOperationContract(node, node.getAppliedRuleApp()) || - SymbolicExecutionUtil.isBlockSpecificationElement(node, node.getAppliedRuleApp())) { - // Compute this reference - PosInOccurrence pio = node.getAppliedRuleApp().posInOccurrence(); - // Compute modified locations - List modifiedLocations = new LinkedList(); - Term loopConditionModalityTerm = SymbolicExecutionUtil.posInOccurrenceInOtherNode(node, pio, previousChild); - if (loopConditionModalityTerm.op() != UpdateApplication.UPDATE_APPLICATION) { - throw new IllegalStateException("Use Loop Invariant/Operation Contract rule implementation has changed at node " + node.serialNr() + "."); - } - Term updateTerm = UpdateApplication.getTarget(loopConditionModalityTerm); - while (updateTerm.op() == UpdateApplication.UPDATE_APPLICATION) { - listModifiedLocations(UpdateApplication.getUpdate(updateTerm), - services, - services.getTypeConverter().getHeapLDT(), - modifiedLocations, - info.getExecutionContext(), - info.getThisReference(), - relevantLocations, - previousChild); - updateTerm = UpdateApplication.getTarget(updateTerm); - } - // Check modified locations - for (Location location : modifiedLocations) { - if (removeRelevant(services, location, relevantLocations, info)) { - accept = true; - } - } - } - return accept; - } - catch (IllegalArgumentException e) { - return false; // Do not accept, expression with side effects is evaluated - } - } + return accept; + } catch (IllegalArgumentException e) { + return false; // Do not accept, expression with side effects is evaluated + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/AbstractCallStackBasedStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/AbstractCallStackBasedStopCondition.java index 6d7d75539c9..6bb4c3479d7 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/AbstractCallStackBasedStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/AbstractCallStackBasedStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Iterator; @@ -13,195 +16,192 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * Provides the basic functionality for {@link StopCondition}s which stops - * the auto mode when the call stack size of the starting set node has - * a special difference to the call stack size of the current set node, e.g. - * "step over" or "step return". + * Provides the basic functionality for {@link StopCondition}s which stops the auto mode when the + * call stack size of the starting set node has a special difference to the call stack size of the + * current set node, e.g. "step over" or "step return". + * * @author Martin Hentschel * @see StepOverSymbolicExecutionTreeNodesStopCondition * @see StepReturnSymbolicExecutionTreeNodesStopCondition */ public abstract class AbstractCallStackBasedStopCondition implements StopCondition { - /** - * Maps a {@link Goal} to the initial call stack size at which the auto mode was started. - */ - private Map startingCallStackSizePerGoal = new LinkedHashMap(); + /** + * Maps a {@link Goal} to the initial call stack size at which the auto mode was started. + */ + private Map startingCallStackSizePerGoal = + new LinkedHashMap(); - /** - * {@inheritDoc} - */ - @Override - public int getMaximalWork(int maxApplications, - long timeout, - Proof proof) { - startingCallStackSizePerGoal.clear(); // Reset initial call stack size of all goals. Will be filled in isGoalAllowed. - return 0; // Return unknown because there is no relation between applied rules and step over functionality. - } + /** + * {@inheritDoc} + */ + @Override + public int getMaximalWork(int maxApplications, long timeout, Proof proof) { + startingCallStackSizePerGoal.clear(); // Reset initial call stack size of all goals. Will be + // filled in isGoalAllowed. + return 0; // Return unknown because there is no relation between applied rules and step over + // functionality. + } - /** - * {@inheritDoc} - */ - @Override - public boolean isGoalAllowed(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - if (goal != null) { - Node node = goal.node(); - // Check if goal is allowed - RuleApp ruleApp = goal.getRuleAppManager().peekNext(); - if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { - // Check if goal is treated the first time - NodeStartEntry startingCallStackSizeEntry = startingCallStackSizePerGoal.get(goal); - if (startingCallStackSizeEntry == null) { - Node parentSetNode = SymbolicExecutionUtil.findParentSetNode(node); - int startingCallStackSize = SymbolicExecutionUtil.computeStackSize(parentSetNode != null ? parentSetNode.getAppliedRuleApp() : null); - startingCallStackSizeEntry = new NodeStartEntry(node, startingCallStackSize); - startingCallStackSizePerGoal.put(goal, startingCallStackSizeEntry); - return true; // Initial check, no need to stop + /** + * {@inheritDoc} + */ + @Override + public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + if (goal != null) { + Node node = goal.node(); + // Check if goal is allowed + RuleApp ruleApp = goal.getRuleAppManager().peekNext(); + if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { + // Check if goal is treated the first time + NodeStartEntry startingCallStackSizeEntry = startingCallStackSizePerGoal.get(goal); + if (startingCallStackSizeEntry == null) { + Node parentSetNode = SymbolicExecutionUtil.findParentSetNode(node); + int startingCallStackSize = SymbolicExecutionUtil.computeStackSize( + parentSetNode != null ? parentSetNode.getAppliedRuleApp() : null); + startingCallStackSizeEntry = new NodeStartEntry(node, startingCallStackSize); + startingCallStackSizePerGoal.put(goal, startingCallStackSizeEntry); + return true; // Initial check, no need to stop + } else { + if (node != startingCallStackSizeEntry.getNode()) { + // Check if current call stack size matches the end condition + int currentCallStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); + if (isCallStackSizeReached( + startingCallStackSizeEntry.getNodeCallStackSize(), + currentCallStackSize)) { + // Get parent node to make sure that already one node was executed which + // does not match the end condition + Node parentSetNode = SymbolicExecutionUtil.findParentSetNode(node); + int parentStackSize = SymbolicExecutionUtil + .computeStackSize(parentSetNode.getAppliedRuleApp()); + if (isCallStackSizeReached( + startingCallStackSizeEntry.getNodeCallStackSize(), + parentStackSize)) { + // Parent node also don't fulfill the call stack limit, stop now + return false; + } else { + // Parent node is deeper in call stack, so continue + return true; + } + } else { + // Currently deeper in call stack, continue + return true; + } + } else { + return true; // Initial node + } + } + } else { + // Internal proof node, allow rule + return true; } - else { - if (node != startingCallStackSizeEntry.getNode()) { - // Check if current call stack size matches the end condition - int currentCallStackSize = SymbolicExecutionUtil.computeStackSize(ruleApp); - if (isCallStackSizeReached(startingCallStackSizeEntry.getNodeCallStackSize(), currentCallStackSize)) { - // Get parent node to make sure that already one node was executed which does not match the end condition - Node parentSetNode = SymbolicExecutionUtil.findParentSetNode(node); - int parentStackSize = SymbolicExecutionUtil.computeStackSize(parentSetNode.getAppliedRuleApp()); - if (isCallStackSizeReached(startingCallStackSizeEntry.getNodeCallStackSize(), parentStackSize)) { - // Parent node also don't fulfill the call stack limit, stop now - return false; - } - else { - // Parent node is deeper in call stack, so continue - return true; - } - } - else { - // Currently deeper in call stack, continue - return true; - } - } - else { - return true; // Initial node - } - } - } - else { - // Internal proof node, allow rule - return true; - } - } - else { - return true; // Allowed, because ApplyStrategy will handle the null case - } - } - - /** - * Checks if the call stack size limit is reached. - * @param initialCallStackSize The call stack size of the initial set node. - * @param currentCallStackSize The call stack size of the current set node. - * @return {@code true} limit reached, {@code false} limit node reached. - */ - protected abstract boolean isCallStackSizeReached(int initialCallStackSize, int currentCallStackSize); + } else { + return true; // Allowed, because ApplyStrategy will handle the null case + } + } + + /** + * Checks if the call stack size limit is reached. + * + * @param initialCallStackSize The call stack size of the initial set node. + * @param currentCallStackSize The call stack size of the current set node. + * @return {@code true} limit reached, {@code false} limit node reached. + */ + protected abstract boolean isCallStackSizeReached(int initialCallStackSize, + int currentCallStackSize); - /** - * {@inheritDoc} - */ - @Override - public boolean shouldStop(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - // Check if a rule was applied - if (singleRuleApplicationInfo != null) { - // Get the node on which a rule was applied. - Goal goal = singleRuleApplicationInfo.getGoal(); - Node goalNode = goal.node(); - assert goalNode.childrenCount() == 0; // Make sure that this is the current goal node - Node updatedNode = goalNode.parent(); - // Check if multiple branches where created. - if (updatedNode.childrenCount() >= 2) { - // If an initial call stack size is available for the goal it must be used for all other new created goals. - NodeStartEntry startingCallStackSizeValue = startingCallStackSizePerGoal.get(goal); - if (startingCallStackSizeValue != null) { - // Reuse initial call stack size for new created goals - Iterator childIter = updatedNode.childrenIterator(); - while (childIter.hasNext()) { - Node next = childIter.next(); - Goal nextGoal = next.proof().getGoal(next); - // Check if the current goal is a new one - if (nextGoal != goal) { - // New goal found, use the initial call stack size for it. - startingCallStackSizePerGoal.put(nextGoal, startingCallStackSizeValue); - } - } + /** + * {@inheritDoc} + */ + @Override + public boolean shouldStop(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + // Check if a rule was applied + if (singleRuleApplicationInfo != null) { + // Get the node on which a rule was applied. + Goal goal = singleRuleApplicationInfo.getGoal(); + Node goalNode = goal.node(); + assert goalNode.childrenCount() == 0; // Make sure that this is the current goal node + Node updatedNode = goalNode.parent(); + // Check if multiple branches where created. + if (updatedNode.childrenCount() >= 2) { + // If an initial call stack size is available for the goal it must be used for all + // other new created goals. + NodeStartEntry startingCallStackSizeValue = startingCallStackSizePerGoal.get(goal); + if (startingCallStackSizeValue != null) { + // Reuse initial call stack size for new created goals + Iterator childIter = updatedNode.childrenIterator(); + while (childIter.hasNext()) { + Node next = childIter.next(); + Goal nextGoal = next.proof().getGoal(next); + // Check if the current goal is a new one + if (nextGoal != goal) { + // New goal found, use the initial call stack size for it. + startingCallStackSizePerGoal.put(nextGoal, startingCallStackSizeValue); + } + } + } } - } - } - return false; - } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public String getStopMessage(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + return null; + } + + /** + * Instances of this class are used in + * {@link AbstractCallStackBasedStopCondition#startingCallStackSizePerGoal} to represent the + * initial {@link Node} of {@link Goal} on which the auto mode was started together with its + * call stack size. + * + * @author Martin Hentschel + */ + private static class NodeStartEntry { + /** + * The initial {@link Node} of a {@link Goal} on that the auto mode was started. + */ + private Node node; - /** - * {@inheritDoc} - */ - @Override - public String getStopMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - return null; - } - - /** - * Instances of this class are used in - * {@link AbstractCallStackBasedStopCondition#startingCallStackSizePerGoal} - * to represent the initial {@link Node} of {@link Goal} on which - * the auto mode was started together with its call stack size. - * @author Martin Hentschel - */ - private static class NodeStartEntry { - /** - * The initial {@link Node} of a {@link Goal} on that the auto mode was started. - */ - private Node node; - - /** - * The call stack size of {@link #node}. - */ - private int nodeCallStackSize; + /** + * The call stack size of {@link #node}. + */ + private int nodeCallStackSize; - /** - * Constructor. - * @param node The initial {@link Node} of a {@link Goal} on that the auto mode was started. - * @param nodeCallStackSize The call stack size of {@link #node}. - */ - public NodeStartEntry(Node node, int nodeCallStackSize) { - super(); - this.node = node; - this.nodeCallStackSize = nodeCallStackSize; - } + /** + * Constructor. + * + * @param node The initial {@link Node} of a {@link Goal} on that the auto mode was started. + * @param nodeCallStackSize The call stack size of {@link #node}. + */ + public NodeStartEntry(Node node, int nodeCallStackSize) { + super(); + this.node = node; + this.nodeCallStackSize = nodeCallStackSize; + } - /** - * Returns the initial {@link Node} of a {@link Goal} on that the auto mode was started. - * @return The initial {@link Node} of a {@link Goal} on that the auto mode was started. - */ - public Node getNode() { - return node; - } + /** + * Returns the initial {@link Node} of a {@link Goal} on that the auto mode was started. + * + * @return The initial {@link Node} of a {@link Goal} on that the auto mode was started. + */ + public Node getNode() { + return node; + } - /** - * Returns the call stack size of {@link #getNode()}. - * @return The call stack size of {@link #getNode()}. - */ - public int getNodeCallStackSize() { - return nodeCallStackSize; - } - } + /** + * Returns the call stack size of {@link #getNode()}. + * + * @return The call stack size of {@link #getNode()}. + */ + public int getNodeCallStackSize() { + return nodeCallStackSize; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/BreakpointStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/BreakpointStopCondition.java index 65195d1d9b3..7af3fbd5dba 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/BreakpointStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/BreakpointStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.HashSet; @@ -16,121 +19,131 @@ /** * An {@link IBreakpointStopCondition} which can be used during proof. + * * @author Martin Hentschel */ public class BreakpointStopCondition implements IBreakpointStopCondition { - /** - * The used {@link IBreakpoint}s. - */ - private final Set breakpoints = new HashSet(); + /** + * The used {@link IBreakpoint}s. + */ + private final Set breakpoints = new HashSet(); - /** - * Indicates that a breakpoint is hit. - */ - private boolean breakpointHit = false; - - /** - * Creates a new {@link BreakpointStopCondition}. - * @param breakpoints The {@link IBreakpoint} to use. - */ - public BreakpointStopCondition(IBreakpoint... breakpoints) { - if (breakpoints != null) { - for (IBreakpoint breakpoint : breakpoints) { - this.breakpoints.add(breakpoint); - } - } - } + /** + * Indicates that a breakpoint is hit. + */ + private boolean breakpointHit = false; - /** - * {@inheritDoc} - */ - @Override - public int getMaximalWork(int maxApplications, long timeout, Proof proof) { - breakpointHit = false; - return 0; - } + /** + * Creates a new {@link BreakpointStopCondition}. + * + * @param breakpoints The {@link IBreakpoint} to use. + */ + public BreakpointStopCondition(IBreakpoint... breakpoints) { + if (breakpoints != null) { + for (IBreakpoint breakpoint : breakpoints) { + this.breakpoints.add(breakpoint); + } + } + } - /** - * {@inheritDoc} - */ - @Override - public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, int countApplied, Goal goal) { - for (IBreakpoint breakpoint : breakpoints) { - breakpoint.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); - } - if (goal != null) { - Node node = goal.node(); - // Check if goal is allowed - RuleApp ruleApp = goal.getRuleAppManager().peekNext(); - SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); - breakpointHit = isBreakpointHit(activeStatement, ruleApp, proof, node); - } - return countApplied == 0 || !breakpointHit; - } + /** + * {@inheritDoc} + */ + @Override + public int getMaximalWork(int maxApplications, long timeout, Proof proof) { + breakpointHit = false; + return 0; + } - /** - * {@inheritDoc} - */ - @Override - public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, long startTime, int countApplied, Goal goal) { - return "Breakpoint hit!"; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + for (IBreakpoint breakpoint : breakpoints) { + breakpoint.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); + } + if (goal != null) { + Node node = goal.node(); + // Check if goal is allowed + RuleApp ruleApp = goal.getRuleAppManager().peekNext(); + SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); + breakpointHit = isBreakpointHit(activeStatement, ruleApp, proof, node); + } + return countApplied == 0 || !breakpointHit; + } - /** - * {@inheritDoc} - */ - @Override - public boolean shouldStop(int maxApplications, long timeout, Proof proof, long startTime, int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { - return false; - } + /** + * {@inheritDoc} + */ + @Override + public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal) { + return "Breakpoint hit!"; + } - /** - * Checks if a breakpoint is hit. - * @param activeStatement the activeStatement of the node - * @param ruleApp the applied {@link RuleApp} - * @param proof the current proof - * @param node the current node - * @return {@code true} at least one breakpoint is hit, {@code false} all breakpoints are not hit. - */ - protected boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - boolean result = false; - Iterator iter = breakpoints.iterator(); - while (!result && iter.hasNext()) { - IBreakpoint next = iter.next(); - result = next.isEnabled() && next.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - return result; - } + /** + * {@inheritDoc} + */ + @Override + public boolean shouldStop(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + return false; + } - /** - * {@inheritDoc} - */ - @Override - public String getStopMessage(int maxApplications, long timeout, Proof proof, long startTime, int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { - return "Breakpoint hit!"; - } - - /** - * {@inheritDoc} - */ - @Override - public void addBreakpoint(IBreakpoint breakpoint) { - breakpoints.add(breakpoint); - } - - /** - * {@inheritDoc} - */ - @Override - public void removeBreakpoint(IBreakpoint breakpoint) { - breakpoints.remove(breakpoint); - } + /** + * Checks if a breakpoint is hit. + * + * @param activeStatement the activeStatement of the node + * @param ruleApp the applied {@link RuleApp} + * @param proof the current proof + * @param node the current node + * @return {@code true} at least one breakpoint is hit, {@code false} all breakpoints are not + * hit. + */ + protected boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + boolean result = false; + Iterator iter = breakpoints.iterator(); + while (!result && iter.hasNext()) { + IBreakpoint next = iter.next(); + result = next.isEnabled() + && next.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + return result; + } - /** - * {@inheritDoc} - */ - @Override - public Set getBreakpoints() { - return breakpoints; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getStopMessage(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + return "Breakpoint hit!"; + } + + /** + * {@inheritDoc} + */ + @Override + public void addBreakpoint(IBreakpoint breakpoint) { + breakpoints.add(breakpoint); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeBreakpoint(IBreakpoint breakpoint) { + breakpoints.remove(breakpoint); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getBreakpoints() { + return breakpoints; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CompoundStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CompoundStopCondition.java index c64a51ac5c1..5c0809294ef 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CompoundStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CompoundStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Collections; @@ -13,133 +16,125 @@ import de.uka.ilkd.key.prover.impl.SingleRuleApplicationInfo; /** - * This {@link StopCondition} contains other {@link StopCondition} as - * children and stops the auto mode if at least on of its children force it. + * This {@link StopCondition} contains other {@link StopCondition} as children and stops the auto + * mode if at least on of its children force it. + * * @author Martin Hentschel */ public class CompoundStopCondition implements StopCondition { - /** - * The child {@link StopCondition}s to use. - */ - private List children = new LinkedList(); - - /** - * The last {@link StopCondition} treated in {@link #isGoalAllowed(ApplyStrategy, int, long, Proof, GoalChooser, long, int, Goal)} - * which will provide the reason via {@link #getGoalNotAllowedMessage(ApplyStrategy, int, long, Proof, GoalChooser, long, int, Goal)}. - */ - private StopCondition lastGoalAllowedChild; - - /** - * The last {@link StopCondition} treated in {@link #shouldStop(ApplyStrategy, int, long, Proof, GoalChooser, long, int, SingleRuleApplicationInfo)} - * which will provide the reason via {@link #getStopMessage(ApplyStrategy, int, long, Proof, GoalChooser, long, int, SingleRuleApplicationInfo)}. - */ - private StopCondition lastShouldStopChild; + /** + * The child {@link StopCondition}s to use. + */ + private List children = new LinkedList(); - /** - * Constructor. - * @param children The child {@link StopCondition}s to use. - */ - public CompoundStopCondition(StopCondition... children) { - Collections.addAll(this.children, children); - } - - /** - * Adds new child {@link StopCondition}s. - * @param children The child {@link StopCondition}s to use. - */ - public void addChildren(StopCondition... children) { - Collections.addAll(this.children, children); - } - - public void removeChild(StopCondition child){ - children.remove(child); - } + /** + * The last {@link StopCondition} treated in + * {@link #isGoalAllowed(ApplyStrategy, int, long, Proof, GoalChooser, long, int, Goal)} which + * will provide the reason via + * {@link #getGoalNotAllowedMessage(ApplyStrategy, int, long, Proof, GoalChooser, long, int, Goal)}. + */ + private StopCondition lastGoalAllowedChild; - /** - * {@inheritDoc} - */ - @Override - public int getMaximalWork(int maxApplications, - long timeout, - Proof proof) { - // Get maximal work on each child because they might use this method for initialization purpose. - for (StopCondition child : children) { - child.getMaximalWork(maxApplications, timeout, proof); - } - lastGoalAllowedChild = null; - lastShouldStopChild = null; - return 0; - } + /** + * The last {@link StopCondition} treated in + * {@link #shouldStop(ApplyStrategy, int, long, Proof, GoalChooser, long, int, SingleRuleApplicationInfo)} + * which will provide the reason via + * {@link #getStopMessage(ApplyStrategy, int, long, Proof, GoalChooser, long, int, SingleRuleApplicationInfo)}. + */ + private StopCondition lastShouldStopChild; - /** - * {@inheritDoc} - */ - @Override - public boolean isGoalAllowed(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - boolean allowed = true; - Iterator childIter = children.iterator(); - while (allowed && childIter.hasNext()) { - lastGoalAllowedChild = childIter.next(); - allowed = lastGoalAllowedChild.isGoalAllowed(maxApplications, timeout, proof, startTime, countApplied, goal); - } - return allowed; - } + /** + * Constructor. + * + * @param children The child {@link StopCondition}s to use. + */ + public CompoundStopCondition(StopCondition... children) { + Collections.addAll(this.children, children); + } - /** - * {@inheritDoc} - */ - @Override - public String getGoalNotAllowedMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - return lastGoalAllowedChild != null ? - lastGoalAllowedChild.getGoalNotAllowedMessage(maxApplications, timeout, proof, startTime, countApplied, goal) : - null; - } + /** + * Adds new child {@link StopCondition}s. + * + * @param children The child {@link StopCondition}s to use. + */ + public void addChildren(StopCondition... children) { + Collections.addAll(this.children, children); + } - /** - * {@inheritDoc} - */ - @Override - public boolean shouldStop(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - boolean stop = false; - Iterator childIter = children.iterator(); - while (!stop && childIter.hasNext()) { - lastShouldStopChild = childIter.next(); - stop = lastShouldStopChild.shouldStop(maxApplications, timeout, proof, startTime, countApplied, singleRuleApplicationInfo); - } - return stop; - } + public void removeChild(StopCondition child) { + children.remove(child); + } - /** - * {@inheritDoc} - */ - @Override - public String getStopMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - return lastShouldStopChild != null ? - lastShouldStopChild.getStopMessage(maxApplications, timeout, proof, startTime, countApplied, singleRuleApplicationInfo) : - null; - } + /** + * {@inheritDoc} + */ + @Override + public int getMaximalWork(int maxApplications, long timeout, Proof proof) { + // Get maximal work on each child because they might use this method for initialization + // purpose. + for (StopCondition child : children) { + child.getMaximalWork(maxApplications, timeout, proof); + } + lastGoalAllowedChild = null; + lastShouldStopChild = null; + return 0; + } - public List getChildren() { - return children; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + boolean allowed = true; + Iterator childIter = children.iterator(); + while (allowed && childIter.hasNext()) { + lastGoalAllowedChild = childIter.next(); + allowed = lastGoalAllowedChild.isGoalAllowed(maxApplications, timeout, proof, startTime, + countApplied, goal); + } + return allowed; + } + + /** + * {@inheritDoc} + */ + @Override + public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal) { + return lastGoalAllowedChild != null ? lastGoalAllowedChild.getGoalNotAllowedMessage( + maxApplications, timeout, proof, startTime, countApplied, goal) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean shouldStop(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + boolean stop = false; + Iterator childIter = children.iterator(); + while (!stop && childIter.hasNext()) { + lastShouldStopChild = childIter.next(); + stop = lastShouldStopChild.shouldStop(maxApplications, timeout, proof, startTime, + countApplied, singleRuleApplicationInfo); + } + return stop; + } + + /** + * {@inheritDoc} + */ + @Override + public String getStopMessage(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + return lastShouldStopChild != null + ? lastShouldStopChild.getStopMessage(maxApplications, timeout, proof, startTime, + countApplied, singleRuleApplicationInfo) + : null; + } + + public List getChildren() { + return children; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsFeature.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsFeature.java index a08c3c7f0e3..46859bf7ebe 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsFeature.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsFeature.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Iterator; @@ -16,57 +19,56 @@ /** *

    - * This {@link BinaryFeature} checks if a cut with an equality for - * an alias check should be done or not. + * This {@link BinaryFeature} checks if a cut with an equality for an alias check should be done or + * not. *

    *

    - * This means the cut is only applied if the cut formula is not an equality - * or if it is not a negated formula or if the (negated) equality is not contained - * as top term ({@link SequentFormula}) in the {@link Sequent} ignoring - * the order of the equality children. + * This means the cut is only applied if the cut formula is not an equality or if it is not a + * negated formula or if the (negated) equality is not contained as top term + * ({@link SequentFormula}) in the {@link Sequent} ignoring the order of the equality children. *

    + * * @author Martin Hentschel */ public class CutHeapObjectsFeature extends BinaryFeature { - /** - * {@inheritDoc} - */ - @Override - protected boolean filter(RuleApp app, PosInOccurrence pos, Goal goal) { - Term cutFormula = SVInstantiationProjection.create(new Name("cutFormula"), false).toTerm(app, pos, goal); - if (cutFormula != null) { - if (cutFormula.op() == Junctor.NOT) { - cutFormula = cutFormula.sub(0); - } - if (cutFormula.op() == Equality.EQUALS) { - Term cutFormulaC0 = cutFormula.sub(0); - Term cutFormulaC1 = cutFormula.sub(1); - boolean contains = false; - Iterator iter = goal.sequent().iterator(); - while (!contains && iter.hasNext()) { - Term formula = iter.next().formula(); - if (formula.op() == Junctor.NOT) { - formula = formula.sub(0); - } - if (formula.op() == Equality.EQUALS) { - // Check equality ignore order of equality sub terms - if (cutFormulaC0.equals(formula.sub(0))) { - contains = cutFormulaC1.equals(formula.sub(1)); - } - else { - contains = cutFormulaC0.equals(formula.sub(1)) && - cutFormulaC1.equals(formula.sub(0)); - } - } + /** + * {@inheritDoc} + */ + @Override + protected boolean filter(RuleApp app, PosInOccurrence pos, Goal goal) { + Term cutFormula = SVInstantiationProjection.create(new Name("cutFormula"), false) + .toTerm(app, pos, goal); + if (cutFormula != null) { + if (cutFormula.op() == Junctor.NOT) { + cutFormula = cutFormula.sub(0); } - return !contains; // Perform cut only if equality is not already part of the sequent's top formulas - } - else { - return true; // Unknown cut type - } - } - else { - return false; // Cut without cutFormula is not possible - } - } -} \ No newline at end of file + if (cutFormula.op() == Equality.EQUALS) { + Term cutFormulaC0 = cutFormula.sub(0); + Term cutFormulaC1 = cutFormula.sub(1); + boolean contains = false; + Iterator iter = goal.sequent().iterator(); + while (!contains && iter.hasNext()) { + Term formula = iter.next().formula(); + if (formula.op() == Junctor.NOT) { + formula = formula.sub(0); + } + if (formula.op() == Equality.EQUALS) { + // Check equality ignore order of equality sub terms + if (cutFormulaC0.equals(formula.sub(0))) { + contains = cutFormulaC1.equals(formula.sub(1)); + } else { + contains = cutFormulaC0.equals(formula.sub(1)) + && cutFormulaC1.equals(formula.sub(0)); + } + } + } + return !contains; // Perform cut only if equality is not already part of the + // sequent's top formulas + } else { + return true; // Unknown cut type + } + } else { + return false; // Cut without cutFormula is not possible + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsTermGenerator.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsTermGenerator.java index 376a5e01e45..58917badf2e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsTermGenerator.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/CutHeapObjectsTermGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Iterator; @@ -17,77 +20,104 @@ import de.uka.ilkd.key.strategy.termgenerator.TermGenerator; /** - * This {@link TermGenerator} is used by the {@link SymbolicExecutionStrategy} - * to add early alias checks of used objects as target of store operations - * on heaps. To achieve this, this {@link TermGenerator} generates equality - * {@link Term}s for each possible combination of objects. + * This {@link TermGenerator} is used by the {@link SymbolicExecutionStrategy} to add early alias + * checks of used objects as target of store operations on heaps. To achieve this, this + * {@link TermGenerator} generates equality {@link Term}s for each possible combination of objects. + * * @author Martin Hentschel */ public class CutHeapObjectsTermGenerator implements TermGenerator { - /** - * {@inheritDoc} - */ - @Override - public Iterator generate(RuleApp app, PosInOccurrence pos, Goal goal) { - // Compute collect terms of sequent formulas - Sequent sequent = goal.sequent(); - Set topTerms = new LinkedHashSet(); - for (SequentFormula sf : sequent) { - topTerms.add(sf.formula()); - } - // Compute equality terms - HeapLDT heapLDT = goal.node().proof().getServices().getTypeConverter().getHeapLDT(); - Set equalityTerms = new LinkedHashSet(); - for (SequentFormula sf : sequent) { - collectEqualityTerms(sf, equalityTerms, topTerms, heapLDT, goal.node().proof().getServices()); - } - return equalityTerms.iterator(); - } - - /** - * Computes all possible equality terms between objects in the given {@link SequentFormula}. - * @param sf The {@link SequentFormula} to work with. - * @param equalityTerms The result {@link Set} with the equality {@link Term}s to fill. - * @param topTerms The terms of all sequent formulas - * @param heapLDT The {@link HeapLDT} to use. - * @param services TODO - */ - protected void collectEqualityTerms(SequentFormula sf, Set equalityTerms, Set topTerms, HeapLDT heapLDT, Services services) { - // Collect objects (target of store operations on heap) - Set storeLocations = new LinkedHashSet(); - collectStoreLocations(sf.formula(), storeLocations, heapLDT); - // Check if equality checks are possible - if (storeLocations.size() >= 2) { - // Generate all possible equality checks - Term[] storeLocationsArray = storeLocations.toArray(new Term[storeLocations.size()]); - for (int i = 0; i < storeLocationsArray.length; i++) { - for (int j = i + 1; j < storeLocationsArray.length; j++) { - Term equality = services.getTermBuilder().equals(storeLocationsArray[i], storeLocationsArray[j]); - if (!topTerms.contains(equality)) { - Term negatedEquality = services.getTermBuilder().not(equality); // The not is because the order of the branches is nicer (assumption: default case that objects are different is shown in symbolic execution trees on the left) - if (!topTerms.contains(negatedEquality)) { - equalityTerms.add(negatedEquality); // Do equality cut only if knowledge is not already part of the sequent - } - } + /** + * {@inheritDoc} + */ + @Override + public Iterator generate(RuleApp app, PosInOccurrence pos, Goal goal) { + // Compute collect terms of sequent formulas + Sequent sequent = goal.sequent(); + Set topTerms = new LinkedHashSet(); + for (SequentFormula sf : sequent) { + topTerms.add(sf.formula()); + } + // Compute equality terms + HeapLDT heapLDT = goal.node().proof().getServices().getTypeConverter().getHeapLDT(); + Set equalityTerms = new LinkedHashSet(); + for (SequentFormula sf : sequent) { + collectEqualityTerms(sf, equalityTerms, topTerms, heapLDT, + goal.node().proof().getServices()); + } + return equalityTerms.iterator(); + } + + /** + * Computes all possible equality terms between objects in the given {@link SequentFormula}. + * + * @param sf The {@link SequentFormula} to work with. + * @param equalityTerms The result {@link Set} with the equality {@link Term}s to fill. + * @param topTerms The terms of all sequent formulas + * @param heapLDT The {@link HeapLDT} to use. + * @param services TODO + */ + protected void collectEqualityTerms(SequentFormula sf, Set equalityTerms, + Set topTerms, HeapLDT heapLDT, Services services) { + // Collect objects (target of store operations on heap) + Set storeLocations = new LinkedHashSet(); + collectStoreLocations(sf.formula(), storeLocations, heapLDT); + // Check if equality checks are possible + if (storeLocations.size() >= 2) { + // Generate all possible equality checks + Term[] storeLocationsArray = storeLocations.toArray(new Term[storeLocations.size()]); + for (int i = 0; i < storeLocationsArray.length; i++) { + for (int j = i + 1; j < storeLocationsArray.length; j++) { + Term equality = services.getTermBuilder().equals(storeLocationsArray[i], + storeLocationsArray[j]); + if (!topTerms.contains(equality)) { + Term negatedEquality = services.getTermBuilder().not(equality); // The not + // is + // because + // the order + // of the + // branches + // is nicer + // (assumption: + // default + // case that + // objects + // are + // different + // is shown + // in + // symbolic + // execution + // trees on + // the left) + if (!topTerms.contains(negatedEquality)) { + equalityTerms.add(negatedEquality); // Do equality cut only if knowledge + // is not already part of the + // sequent + } + } + } } - } - } - } + } + } - /** - * Collects recursive all possible targets of store operations on a heap. - * @param term The {@link Term} to start search in. - * @param storeLocations The result {@link Set} to fill. - * @param heapLDT The {@link HeapLDT} to use (it provides the store and create {@link Function}). - */ - protected void collectStoreLocations(Term term, final Set storeLocations, final HeapLDT heapLDT) { - term.execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - if (visited.op() == heapLDT.getStore()) { - storeLocations.add(visited.sub(1)); + /** + * Collects recursive all possible targets of store operations on a heap. + * + * @param term The {@link Term} to start search in. + * @param storeLocations The result {@link Set} to fill. + * @param heapLDT The {@link HeapLDT} to use (it provides the store and create + * {@link Function}). + */ + protected void collectStoreLocations(Term term, final Set storeLocations, + final HeapLDT heapLDT) { + term.execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + if (visited.op() == heapLDT.getStore()) { + storeLocations.add(visited.sub(1)); + } } - } - }); - } + }); + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/ExecutedSymbolicExecutionTreeNodesStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/ExecutedSymbolicExecutionTreeNodesStopCondition.java index 50a1eb5fb24..561c4e0546e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/ExecutedSymbolicExecutionTreeNodesStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/ExecutedSymbolicExecutionTreeNodesStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Iterator; @@ -16,276 +19,269 @@ /** *

    - * This {@link StopCondition} stops the auto mode ({@link ApplyStrategy}) if - * a given number ({@link #getMaximalNumberOfSetNodesToExecutePerGoal()}) of maximal - * executed symbolic execution tree nodes is reached in a goal. + * This {@link StopCondition} stops the auto mode ({@link ApplyStrategy}) if a given number + * ({@link #getMaximalNumberOfSetNodesToExecutePerGoal()}) of maximal executed symbolic execution + * tree nodes is reached in a goal. *

    *

    - * If a {@link Node} in - * KeY's proof tree is also a node in a symbolic execution tree is computed - * via {@link SymbolicExecutionUtil#isSymbolicExecutionTreeNode(Node)}. + * If a {@link Node} in KeY's proof tree is also a node in a symbolic execution tree is computed via + * {@link SymbolicExecutionUtil#isSymbolicExecutionTreeNode(Node)}. *

    *

    - * The auto mode is stopped exactly in the open goal {@link Node} which - * will become the next symbolic execution tree node. + * The auto mode is stopped exactly in the open goal {@link Node} which will become the next + * symbolic execution tree node. *

    + * * @author Martin Hentschel */ public class ExecutedSymbolicExecutionTreeNodesStopCondition implements StopCondition { - /** - * The default maximal number of steps to simulate a complete program execution. - */ - public static final int MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN = 1000; + /** + * The default maximal number of steps to simulate a complete program execution. + */ + public static final int MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN = 1000; - /** - * The default maximal number of steps to do exactly one step in each goal. - */ - public static final int MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP = 1; + /** + * The default maximal number of steps to do exactly one step in each goal. + */ + public static final int MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP = 1; - /** - * The maximal number of allowed symbolic execution tree nodes per goal. - * The auto mode will stop exactly in the open goal proof node which - * becomes the next symbolic execution tree node. - */ - private int maximalNumberOfSetNodesToExecutePerGoal; - - /** - * Maps a {@link Goal} to the number of executed symbolic execution tree nodes. - */ - private final Map executedNumberOfSetNodesPerGoal = new LinkedHashMap(); - - /** - * Stores for each {@link Node} which is a symbolic execution tree node the computed result - * of {@link #isGoalAllowed(int, long, Proof, long, int, Goal)} to make - * sure that it is only computed once and that the number of executed set statements is - * not increased multiple times for the same {@link Node}. - */ - private final Map goalAllowedResultPerSetNode = new LinkedHashMap(); - - /** - * Constructor to stop after one executed symbolic execution tree node. - */ - public ExecutedSymbolicExecutionTreeNodesStopCondition() { - this(1); - } + /** + * The maximal number of allowed symbolic execution tree nodes per goal. The auto mode will stop + * exactly in the open goal proof node which becomes the next symbolic execution tree node. + */ + private int maximalNumberOfSetNodesToExecutePerGoal; - /** - * Constructor to stop after the given number of symbolic execution tree nodes. - * @param maximalNumberOfSetNodesToExecutePerGoal The maximal number of allowed symbolic execution tree nodes per goal. - */ - public ExecutedSymbolicExecutionTreeNodesStopCondition(int maximalNumberOfSetNodesToExecutePerGoal) { - this.maximalNumberOfSetNodesToExecutePerGoal = maximalNumberOfSetNodesToExecutePerGoal; - } + /** + * Maps a {@link Goal} to the number of executed symbolic execution tree nodes. + */ + private final Map executedNumberOfSetNodesPerGoal = + new LinkedHashMap(); - /** - * {@inheritDoc} - */ - @Override - public int getMaximalWork(int maxApplications, - long timeout, - Proof proof) { - executedNumberOfSetNodesPerGoal.clear(); // Reset number of already detected symbolic execution tree nodes for all goals. - goalAllowedResultPerSetNode.clear(); // Remove no longer needed references. - return 0; // Return unknown because there is no relation between applied rules and executed symbolic execution tree nodes. - } + /** + * Stores for each {@link Node} which is a symbolic execution tree node the computed result of + * {@link #isGoalAllowed(int, long, Proof, long, int, Goal)} to make sure that it is only + * computed once and that the number of executed set statements is not increased multiple times + * for the same {@link Node}. + */ + private final Map goalAllowedResultPerSetNode = + new LinkedHashMap(); - /** - * {@inheritDoc} - */ - @Override - public boolean isGoalAllowed(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - if (goal != null) { - Node node = goal.node(); - // Check if goal is allowed - RuleApp ruleApp = goal.getRuleAppManager().peekNext(); - if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { - // Check if the result for the current node was already computed. - Boolean value = goalAllowedResultPerSetNode.get(node); - if (value == null) { - // Get the number of executed set nodes on the current goal - Integer executedNumberOfSetNodes = executedNumberOfSetNodesPerGoal.get(goal); - if (executedNumberOfSetNodes == null) { - executedNumberOfSetNodes = Integer.valueOf(0); - } - // Check if limit of set nodes of the current goal is exceeded - if (executedNumberOfSetNodes.intValue() + 1 > maximalNumberOfSetNodesToExecutePerGoal) { - handleNodeLimitExceeded(maxApplications, timeout, proof, startTime, countApplied, goal, node, ruleApp, executedNumberOfSetNodes); - return false; // Limit of set nodes of this goal exceeded - } - else { - // Increase number of set nodes on this goal and allow rule application - executedNumberOfSetNodes = Integer.valueOf(executedNumberOfSetNodes.intValue() + 1); - executedNumberOfSetNodesPerGoal.put(goal, executedNumberOfSetNodes); - handleNodeLimitNotExceeded(maxApplications, timeout, proof, startTime, countApplied, goal, node, ruleApp, executedNumberOfSetNodes); - return true; - } - } - else { - // Reuse already computed result. - return value.booleanValue(); + /** + * Constructor to stop after one executed symbolic execution tree node. + */ + public ExecutedSymbolicExecutionTreeNodesStopCondition() { + this(1); + } + + /** + * Constructor to stop after the given number of symbolic execution tree nodes. + * + * @param maximalNumberOfSetNodesToExecutePerGoal The maximal number of allowed symbolic + * execution tree nodes per goal. + */ + public ExecutedSymbolicExecutionTreeNodesStopCondition( + int maximalNumberOfSetNodesToExecutePerGoal) { + this.maximalNumberOfSetNodesToExecutePerGoal = maximalNumberOfSetNodesToExecutePerGoal; + } + + /** + * {@inheritDoc} + */ + @Override + public int getMaximalWork(int maxApplications, long timeout, Proof proof) { + executedNumberOfSetNodesPerGoal.clear(); // Reset number of already detected symbolic + // execution tree nodes for all goals. + goalAllowedResultPerSetNode.clear(); // Remove no longer needed references. + return 0; // Return unknown because there is no relation between applied rules and executed + // symbolic execution tree nodes. + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + if (goal != null) { + Node node = goal.node(); + // Check if goal is allowed + RuleApp ruleApp = goal.getRuleAppManager().peekNext(); + if (SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { + // Check if the result for the current node was already computed. + Boolean value = goalAllowedResultPerSetNode.get(node); + if (value == null) { + // Get the number of executed set nodes on the current goal + Integer executedNumberOfSetNodes = executedNumberOfSetNodesPerGoal.get(goal); + if (executedNumberOfSetNodes == null) { + executedNumberOfSetNodes = Integer.valueOf(0); + } + // Check if limit of set nodes of the current goal is exceeded + if (executedNumberOfSetNodes.intValue() + + 1 > maximalNumberOfSetNodesToExecutePerGoal) { + handleNodeLimitExceeded(maxApplications, timeout, proof, startTime, + countApplied, goal, node, ruleApp, executedNumberOfSetNodes); + return false; // Limit of set nodes of this goal exceeded + } else { + // Increase number of set nodes on this goal and allow rule application + executedNumberOfSetNodes = + Integer.valueOf(executedNumberOfSetNodes.intValue() + 1); + executedNumberOfSetNodesPerGoal.put(goal, executedNumberOfSetNodes); + handleNodeLimitNotExceeded(maxApplications, timeout, proof, startTime, + countApplied, goal, node, ruleApp, executedNumberOfSetNodes); + return true; + } + } else { + // Reuse already computed result. + return value.booleanValue(); + } + } else { + return true; } - } - else { - return true; - } - } - else { - return true; // Allowed, because ApplyStrategy will handle the null case - } - } + } else { + return true; // Allowed, because ApplyStrategy will handle the null case + } + } - /** - * Handles the state that the node limit is exceeded. - * @param maxApplications The defined maximal number of rules to apply. Can be different to {@link StrategySettings#getMaxSteps()} in side proofs. - * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to {@link StrategySettings#getTimeout()} in side proofs. - * @param proof The current {@link Proof}. - * @param startTime The timestamp when the apply strategy has started, computed via {@link System#nanoTime()} - * @param countApplied The number of already applied rules. - * @param goal The current {@link Goal} on which the next rule will be applied. - * @param node The {@link Node} of the current {@link Goal}. - * @param ruleApp The current {@link RuleApp}. - * @param executedNumberOfSetNodes The executed number of SET nodes. - */ - protected void handleNodeLimitExceeded(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal, - Node node, - RuleApp ruleApp, - Integer executedNumberOfSetNodes) { - goalAllowedResultPerSetNode.put(node, Boolean.FALSE); - } - - /** - * Handles the state that the node limit is not exceeded. - * @param maxApplications The defined maximal number of rules to apply. Can be different to {@link StrategySettings#getMaxSteps()} in side proofs. - * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to {@link StrategySettings#getTimeout()} in side proofs. - * @param proof The current {@link Proof}. - * @param startTime The timestamp when the apply strategy has started, computed via {@link System#nanoTime()} - * @param countApplied The number of already applied rules. - * @param goal The current {@link Goal} on which the next rule will be applied. - * @param node The {@link Node} of the current {@link Goal}. - * @param ruleApp The current {@link RuleApp}. - * @param executedNumberOfSetNodes The executed number of SET nodes. - */ - protected void handleNodeLimitNotExceeded(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal, - Node node, - RuleApp ruleApp, - Integer executedNumberOfSetNodes) { - goalAllowedResultPerSetNode.put(node, Boolean.TRUE); - } + /** + * Handles the state that the node limit is exceeded. + * + * @param maxApplications The defined maximal number of rules to apply. Can be different to + * {@link StrategySettings#getMaxSteps()} in side proofs. + * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to + * {@link StrategySettings#getTimeout()} in side proofs. + * @param proof The current {@link Proof}. + * @param startTime The timestamp when the apply strategy has started, computed via + * {@link System#nanoTime()} + * @param countApplied The number of already applied rules. + * @param goal The current {@link Goal} on which the next rule will be applied. + * @param node The {@link Node} of the current {@link Goal}. + * @param ruleApp The current {@link RuleApp}. + * @param executedNumberOfSetNodes The executed number of SET nodes. + */ + protected void handleNodeLimitExceeded(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal, Node node, RuleApp ruleApp, + Integer executedNumberOfSetNodes) { + goalAllowedResultPerSetNode.put(node, Boolean.FALSE); + } - /** - * {@inheritDoc} - */ - @Override - public String getGoalNotAllowedMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - if (maximalNumberOfSetNodesToExecutePerGoal > 1) { - return "Maximal limit of " + maximalNumberOfSetNodesToExecutePerGoal + " symbolic execution tree nodes reached."; - } - else { - return "Maximal limit of one symbolic execution tree node reached."; - } - } + /** + * Handles the state that the node limit is not exceeded. + * + * @param maxApplications The defined maximal number of rules to apply. Can be different to + * {@link StrategySettings#getMaxSteps()} in side proofs. + * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to + * {@link StrategySettings#getTimeout()} in side proofs. + * @param proof The current {@link Proof}. + * @param startTime The timestamp when the apply strategy has started, computed via + * {@link System#nanoTime()} + * @param countApplied The number of already applied rules. + * @param goal The current {@link Goal} on which the next rule will be applied. + * @param node The {@link Node} of the current {@link Goal}. + * @param ruleApp The current {@link RuleApp}. + * @param executedNumberOfSetNodes The executed number of SET nodes. + */ + protected void handleNodeLimitNotExceeded(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal, Node node, RuleApp ruleApp, + Integer executedNumberOfSetNodes) { + goalAllowedResultPerSetNode.put(node, Boolean.TRUE); + } - /** - * {@inheritDoc} - */ - @Override - public boolean shouldStop(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - // Check if a rule was applied - if (singleRuleApplicationInfo != null) { - // Get the node on which a rule was applied. - Goal goal = singleRuleApplicationInfo.getGoal(); - Node goalNode = goal.node(); - assert goalNode.childrenCount() == 0; // Make sure that this is the current goal node - Node updatedNode = goalNode.parent(); - // Check if multiple branches where created. - if (updatedNode.childrenCount() >= 2) { - // If a number of executed set nodes is available for the goal it must be used for all other new created goals. - Integer executedValue = executedNumberOfSetNodesPerGoal.get(goal); - if (executedValue != null) { - // Reuse number of set nodes for new created goals - Iterator childIter = updatedNode.childrenIterator(); - while (childIter.hasNext()) { - Node next = childIter.next(); - Goal nextGoal = next.proof().getGoal(next); - // Check if the current goal is a new one - if (nextGoal != goal) { - // New goal found, use the number of set nodes for it. - executedNumberOfSetNodesPerGoal.put(nextGoal, executedValue); - } - } + /** + * {@inheritDoc} + */ + @Override + public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal) { + if (maximalNumberOfSetNodesToExecutePerGoal > 1) { + return "Maximal limit of " + maximalNumberOfSetNodesToExecutePerGoal + + " symbolic execution tree nodes reached."; + } else { + return "Maximal limit of one symbolic execution tree node reached."; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean shouldStop(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + // Check if a rule was applied + if (singleRuleApplicationInfo != null) { + // Get the node on which a rule was applied. + Goal goal = singleRuleApplicationInfo.getGoal(); + Node goalNode = goal.node(); + assert goalNode.childrenCount() == 0; // Make sure that this is the current goal node + Node updatedNode = goalNode.parent(); + // Check if multiple branches where created. + if (updatedNode.childrenCount() >= 2) { + // If a number of executed set nodes is available for the goal it must be used for + // all other new created goals. + Integer executedValue = executedNumberOfSetNodesPerGoal.get(goal); + if (executedValue != null) { + // Reuse number of set nodes for new created goals + Iterator childIter = updatedNode.childrenIterator(); + while (childIter.hasNext()) { + Node next = childIter.next(); + Goal nextGoal = next.proof().getGoal(next); + // Check if the current goal is a new one + if (nextGoal != goal) { + // New goal found, use the number of set nodes for it. + executedNumberOfSetNodesPerGoal.put(nextGoal, executedValue); + } + } + } } - } - } - return false; - } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public String getStopMessage(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, SingleRuleApplicationInfo singleRuleApplicationInfo) { + return null; + } + + /** + * Returns the maximal number of executed symbolic execution tree nodes per goal per auto mode + * run. + * + * @return The maximal number of executed symbolic execution tree nodes per goal per auto mode + * run. + */ + public int getMaximalNumberOfSetNodesToExecutePerGoal() { + return maximalNumberOfSetNodesToExecutePerGoal; + } + + /** + * Sets the maximal number of executed symbolic execution tree nodes per goal per auto mode run. + * + * @param maximalNumberOfSetNodesToExecute The maximal number of executed symbolic execution + * tree nodes per per goal auto mode run. + */ + public void setMaximalNumberOfSetNodesToExecutePerGoal(int maximalNumberOfSetNodesToExecute) { + this.maximalNumberOfSetNodesToExecutePerGoal = maximalNumberOfSetNodesToExecute; + } - /** - * {@inheritDoc} - */ - @Override - public String getStopMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - SingleRuleApplicationInfo singleRuleApplicationInfo) { - return null; - } + /** + * Checks if at least one symbolic execution tree node was executed. + * + * @return {@code true} at least one symbolic execution tree node was executed, {@code false} no + * symbolic execution tree node was executed. + */ + public boolean wasSetNodeExecuted() { + return !executedNumberOfSetNodesPerGoal.isEmpty(); + } - /** - * Returns the maximal number of executed symbolic execution tree nodes per goal per auto mode run. - * @return The maximal number of executed symbolic execution tree nodes per goal per auto mode run. - */ - public int getMaximalNumberOfSetNodesToExecutePerGoal() { - return maximalNumberOfSetNodesToExecutePerGoal; - } - - /** - * Sets the maximal number of executed symbolic execution tree nodes per goal per auto mode run. - * @param maximalNumberOfSetNodesToExecute The maximal number of executed symbolic execution tree nodes per per goal auto mode run. - */ - public void setMaximalNumberOfSetNodesToExecutePerGoal(int maximalNumberOfSetNodesToExecute) { - this.maximalNumberOfSetNodesToExecutePerGoal = maximalNumberOfSetNodesToExecute; - } - - /** - * Checks if at least one symbolic execution tree node was executed. - * @return {@code true} at least one symbolic execution tree node was executed, {@code false} no symbolic execution tree node was executed. - */ - public boolean wasSetNodeExecuted() { - return !executedNumberOfSetNodesPerGoal.isEmpty(); - } - - /** - * Returns the number of executed symbolic execution tree nodes per {@link Goal}. - * @return The number of executed symbolic execution tree nodes per {@link Goal}. - */ - public Map getExectuedSetNodesPerGoal() { - return executedNumberOfSetNodesPerGoal; - } -} \ No newline at end of file + /** + * Returns the number of executed symbolic execution tree nodes per {@link Goal}. + * + * @return The number of executed symbolic execution tree nodes per {@link Goal}. + */ + public Map getExectuedSetNodesPerGoal() { + return executedNumberOfSetNodesPerGoal; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SimplifyTermStrategy.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SimplifyTermStrategy.java index 6384eebbee2..7fe2c1b59c3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SimplifyTermStrategy.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SimplifyTermStrategy.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import de.uka.ilkd.key.logic.Name; @@ -22,89 +25,95 @@ /** * {@link Strategy} used to simplify {@link Term}s in side proofs. + * * @author Martin Hentschel */ public class SimplifyTermStrategy extends JavaCardDLStrategy { - /** - * The {@link Name} of the side proof {@link Strategy}. - */ - public static final Name name = new Name("Simplify Term Strategy"); - - /** - * Constructor. - * @param proof The proof. - * @param sp The {@link StrategyProperties} to use. - */ - private SimplifyTermStrategy(Proof proof, StrategyProperties sp) { - super(proof, sp); - } + /** + * The {@link Name} of the side proof {@link Strategy}. + */ + public static final Name name = new Name("Simplify Term Strategy"); - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return name; - } - - /** - * {@inheritDoc} - */ - @Override - protected Feature setupApprovalF() { - Feature superFeature = super.setupApprovalF(); - Feature labelFeature = new Feature() { - @Override - public RuleAppCost computeCost(RuleApp app, PosInOccurrence pos, Goal goal) { - boolean hasLabel = false; - if (pos != null && app instanceof TacletApp) { - Term findTerm = pos.subTerm(); - if (!findTerm.containsLabel(SymbolicExecutionUtil.RESULT_LABEL)) { - // Term with result label is not used in find term and thus is not allowed to be used in an assumes clause - TacletApp ta = (TacletApp)app; - if (ta.ifFormulaInstantiations() != null) { - for (IfFormulaInstantiation ifi : ta.ifFormulaInstantiations()) { - if (ifi.getConstrainedFormula().formula().containsLabel(SymbolicExecutionUtil.RESULT_LABEL)) { - hasLabel = true; + /** + * Constructor. + * + * @param proof The proof. + * @param sp The {@link StrategyProperties} to use. + */ + private SimplifyTermStrategy(Proof proof, StrategyProperties sp) { + super(proof, sp); + } + + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + protected Feature setupApprovalF() { + Feature superFeature = super.setupApprovalF(); + Feature labelFeature = new Feature() { + @Override + public RuleAppCost computeCost(RuleApp app, PosInOccurrence pos, Goal goal) { + boolean hasLabel = false; + if (pos != null && app instanceof TacletApp) { + Term findTerm = pos.subTerm(); + if (!findTerm.containsLabel(SymbolicExecutionUtil.RESULT_LABEL)) { + // Term with result label is not used in find term and thus is not allowed + // to be used in an assumes clause + TacletApp ta = (TacletApp) app; + if (ta.ifFormulaInstantiations() != null) { + for (IfFormulaInstantiation ifi : ta.ifFormulaInstantiations()) { + if (ifi.getConstrainedFormula().formula() + .containsLabel(SymbolicExecutionUtil.RESULT_LABEL)) { + hasLabel = true; + } + } } - } - } - } + } + } + return hasLabel ? TopRuleAppCost.INSTANCE : NumberRuleAppCost.create(0); } - return hasLabel ? TopRuleAppCost.INSTANCE : NumberRuleAppCost.create(0); - } - }; - // The label feature ensures that Taclets mapping an assumes to a Term with a result label are only applicable if also a Term with the result label is used in the find clause - return add(labelFeature, superFeature); - } + }; + // The label feature ensures that Taclets mapping an assumes to a Term with a result label + // are only applicable if also a Term with the result label is used in the find clause + return add(labelFeature, superFeature); + } - /** - * The {@link StrategyFactory} to create instances of {@link SimplifyTermStrategy}. - * @author Martin Hentschel - */ - public static class Factory implements StrategyFactory { - /** - * {@inheritDoc} - */ - @Override - public Strategy create(Proof proof, StrategyProperties sp) { - return new SimplifyTermStrategy(proof, sp); - } + /** + * The {@link StrategyFactory} to create instances of {@link SimplifyTermStrategy}. + * + * @author Martin Hentschel + */ + public static class Factory implements StrategyFactory { + /** + * {@inheritDoc} + */ + @Override + public Strategy create(Proof proof, StrategyProperties sp) { + return new SimplifyTermStrategy(proof, sp); + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return name; - } + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return name; + } - /** - * {@inheritDoc} - */ - @Override - public StrategySettingsDefinition getSettingsDefinition() { - return JavaProfile.DEFAULT.getSettingsDefinition(); - } - } + /** + * {@inheritDoc} + */ + @Override + public StrategySettingsDefinition getSettingsDefinition() { + return JavaProfile.DEFAULT.getSettingsDefinition(); + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepOverSymbolicExecutionTreeNodesStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepOverSymbolicExecutionTreeNodesStopCondition.java index edf2450eb49..b2aaf43c42b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepOverSymbolicExecutionTreeNodesStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepOverSymbolicExecutionTreeNodesStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import de.uka.ilkd.key.proof.Goal; @@ -5,31 +8,29 @@ import de.uka.ilkd.key.prover.StopCondition; /** - * This {@link StopCondition} stops the auto mode when a "step over" is completed. - * This is the case when the next symbolic execution tree node was executed on a {@link Goal} - * which has the same call or lower stack size as the symbolic execution tree node of the {@link Goal} - * on which the auto mode was started. + * This {@link StopCondition} stops the auto mode when a "step over" is completed. This is the case + * when the next symbolic execution tree node was executed on a {@link Goal} which has the same call + * or lower stack size as the symbolic execution tree node of the {@link Goal} on which the auto + * mode was started. + * * @author Martin Hentschel */ -public class StepOverSymbolicExecutionTreeNodesStopCondition extends AbstractCallStackBasedStopCondition { - /** - * {@inheritDoc} - */ - @Override - protected boolean isCallStackSizeReached(int initialCallStackSize, int currentCallStackSize) { - return currentCallStackSize <= initialCallStackSize; - } +public class StepOverSymbolicExecutionTreeNodesStopCondition + extends AbstractCallStackBasedStopCondition { + /** + * {@inheritDoc} + */ + @Override + protected boolean isCallStackSizeReached(int initialCallStackSize, int currentCallStackSize) { + return currentCallStackSize <= initialCallStackSize; + } - /** - * {@inheritDoc} - */ - @Override - public String getGoalNotAllowedMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - return "Step over completed."; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal) { + return "Step over completed."; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepReturnSymbolicExecutionTreeNodesStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepReturnSymbolicExecutionTreeNodesStopCondition.java index e3788af626f..c5af3b0ea5d 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepReturnSymbolicExecutionTreeNodesStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/StepReturnSymbolicExecutionTreeNodesStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import de.uka.ilkd.key.proof.Goal; @@ -5,31 +8,28 @@ import de.uka.ilkd.key.prover.StopCondition; /** - * This {@link StopCondition} stops the auto mode when a "step over" is completed. - * This is the case when the next symbolic execution tree node was executed on a {@link Goal} - * which has a lower stack size as the symbolic execution tree node of the {@link Goal} - * on which the auto mode was started. + * This {@link StopCondition} stops the auto mode when a "step over" is completed. This is the case + * when the next symbolic execution tree node was executed on a {@link Goal} which has a lower stack + * size as the symbolic execution tree node of the {@link Goal} on which the auto mode was started. + * * @author Martin Hentschel */ -public class StepReturnSymbolicExecutionTreeNodesStopCondition extends AbstractCallStackBasedStopCondition { - /** - * {@inheritDoc} - */ - @Override - protected boolean isCallStackSizeReached(int initialCallStackSize, int currentCallStackSize) { - return currentCallStackSize < initialCallStackSize; - } +public class StepReturnSymbolicExecutionTreeNodesStopCondition + extends AbstractCallStackBasedStopCondition { + /** + * {@inheritDoc} + */ + @Override + protected boolean isCallStackSizeReached(int initialCallStackSize, int currentCallStackSize) { + return currentCallStackSize < initialCallStackSize; + } - /** - * {@inheritDoc} - */ - @Override - public String getGoalNotAllowedMessage(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - return "Step return completed."; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String getGoalNotAllowedMessage(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal) { + return "Step return completed."; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionBreakpointStopCondition.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionBreakpointStopCondition.java index c0ba1127bdc..af90db98822 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionBreakpointStopCondition.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionBreakpointStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.HashSet; @@ -15,108 +18,109 @@ /** * An {@link IBreakpointStopCondition} which can be used during symbolic execution. + * * @author Martin Hentschel */ -public class SymbolicExecutionBreakpointStopCondition extends ExecutedSymbolicExecutionTreeNodesStopCondition implements IBreakpointStopCondition { - /** - * The used {@link IBreakpoint}s. - */ - private final Set breakpoints = new HashSet(); +public class SymbolicExecutionBreakpointStopCondition extends + ExecutedSymbolicExecutionTreeNodesStopCondition implements IBreakpointStopCondition { + /** + * The used {@link IBreakpoint}s. + */ + private final Set breakpoints = new HashSet(); - /** - * Creates a new {@link SymbolicExecutionBreakpointStopCondition}. - * @param breakpoints The {@link IBreakpoint} to use. - */ - public SymbolicExecutionBreakpointStopCondition(IBreakpoint... breakpoints) { - super(Integer.MAX_VALUE); - if (breakpoints != null) { - for (IBreakpoint breakpoint : breakpoints) { - this.breakpoints.add(breakpoint); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public int getMaximalWork(int maxApplications, - long timeout, - Proof proof) { - setMaximalNumberOfSetNodesToExecutePerGoal(Integer.MAX_VALUE); - return super.getMaximalWork(maxApplications, timeout, proof); - } + /** + * Creates a new {@link SymbolicExecutionBreakpointStopCondition}. + * + * @param breakpoints The {@link IBreakpoint} to use. + */ + public SymbolicExecutionBreakpointStopCondition(IBreakpoint... breakpoints) { + super(Integer.MAX_VALUE); + if (breakpoints != null) { + for (IBreakpoint breakpoint : breakpoints) { + this.breakpoints.add(breakpoint); + } + } + } - /** - * {@inheritDoc} - */ - @Override - public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, int countApplied, Goal goal) { - for (IBreakpoint breakpoint : breakpoints) { - breakpoint.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); - } - return super.isGoalAllowed(maxApplications, timeout, proof, startTime, countApplied, goal); - } + /** + * {@inheritDoc} + */ + @Override + public int getMaximalWork(int maxApplications, long timeout, Proof proof) { + setMaximalNumberOfSetNodesToExecutePerGoal(Integer.MAX_VALUE); + return super.getMaximalWork(maxApplications, timeout, proof); + } - /** - * {@inheritDoc} - */ - @Override - protected void handleNodeLimitNotExceeded(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal, - Node node, - RuleApp ruleApp, - Integer executedNumberOfSetNodes) { - super.handleNodeLimitNotExceeded(maxApplications, timeout, proof, startTime, countApplied, goal, node, ruleApp, executedNumberOfSetNodes); - SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); - if (isBreakpointHit(activeStatement, ruleApp, proof, node)) { - setMaximalNumberOfSetNodesToExecutePerGoal(executedNumberOfSetNodes.intValue()); - } - } - - /** - * Checks if a breakpoint is hit. - * @param activeStatement the activeStatement of the node - * @param ruleApp the applied {@link RuleApp} - * @param proof the current proof - * @param node the current node - * @return {@code true} at least one breakpoint is hit, {@code false} all breakpoints are not hit. - */ - protected boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - boolean result = false; - Iterator iter = breakpoints.iterator(); - while (!result && iter.hasNext()) { - IBreakpoint next = iter.next(); - result = next.isEnabled() && next.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public void addBreakpoint(IBreakpoint breakpoint) { - breakpoints.add(breakpoint); - } - - /** - * {@inheritDoc} - */ - @Override - public void removeBreakpoint(IBreakpoint breakpoint) { - breakpoints.remove(breakpoint); - } + /** + * {@inheritDoc} + */ + @Override + public boolean isGoalAllowed(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + for (IBreakpoint breakpoint : breakpoints) { + breakpoint.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); + } + return super.isGoalAllowed(maxApplications, timeout, proof, startTime, countApplied, goal); + } - /** - * {@inheritDoc} - */ - @Override - public Set getBreakpoints() { - return breakpoints; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + protected void handleNodeLimitNotExceeded(int maxApplications, long timeout, Proof proof, + long startTime, int countApplied, Goal goal, Node node, RuleApp ruleApp, + Integer executedNumberOfSetNodes) { + super.handleNodeLimitNotExceeded(maxApplications, timeout, proof, startTime, countApplied, + goal, node, ruleApp, executedNumberOfSetNodes); + SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); + if (isBreakpointHit(activeStatement, ruleApp, proof, node)) { + setMaximalNumberOfSetNodesToExecutePerGoal(executedNumberOfSetNodes.intValue()); + } + } + + /** + * Checks if a breakpoint is hit. + * + * @param activeStatement the activeStatement of the node + * @param ruleApp the applied {@link RuleApp} + * @param proof the current proof + * @param node the current node + * @return {@code true} at least one breakpoint is hit, {@code false} all breakpoints are not + * hit. + */ + protected boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + boolean result = false; + Iterator iter = breakpoints.iterator(); + while (!result && iter.hasNext()) { + IBreakpoint next = iter.next(); + result = next.isEnabled() + && next.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public void addBreakpoint(IBreakpoint breakpoint) { + breakpoints.add(breakpoint); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeBreakpoint(IBreakpoint breakpoint) { + breakpoints.remove(breakpoint); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getBreakpoints() { + return breakpoints; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooser.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooser.java index e01c6cc8856..0d024511c12 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooser.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooser.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.Iterator; @@ -18,163 +21,160 @@ /** *

    * This {@link GoalChooser} is a special implementation of the default - * {@link DepthFirstGoalChooser}. The difference is that a rule which - * creates a new symbolic execution tree node on a {@link Goal} is only applied - * if all other {@link Goal}s will also creates new symbolic execution tree - * nodes. This has the advantage that invalid branches may closed before - * new symbolic execution tree nodes are created. + * {@link DepthFirstGoalChooser}. The difference is that a rule which creates a new symbolic + * execution tree node on a {@link Goal} is only applied if all other {@link Goal}s will also + * creates new symbolic execution tree nodes. This has the advantage that invalid branches may + * closed before new symbolic execution tree nodes are created. *

    *

    - * The order in which new symbolic execution tree nodes are created is also - * managed by this {@link GoalChooser}. The idea is that on each {@link Goal} - * a new symbolic execution tree node is created before on one {@link Goal} - * a second one will be created. This has the affect that for instance on all - * branches of a branch statement the next statement is evaluated before the first + * The order in which new symbolic execution tree nodes are created is also managed by this + * {@link GoalChooser}. The idea is that on each {@link Goal} a new symbolic execution tree node is + * created before on one {@link Goal} a second one will be created. This has the affect that for + * instance on all branches of a branch statement the next statement is evaluated before the first * branch executes the second statement. *

    *

    - * A second criteria is the used custom {@link StopCondition} of the current - * {@link Proof}. {@link Goal}s on that the next set node is allowed are - * preferred to branches on which is not allowed. This is required to make - * sure that for instance a step over or step return result is completely - * performed on all {@link Goal}s before on one {@link Goal} a further - * set node is executed. + * A second criteria is the used custom {@link StopCondition} of the current {@link Proof}. + * {@link Goal}s on that the next set node is allowed are preferred to branches on which is not + * allowed. This is required to make sure that for instance a step over or step return result is + * completely performed on all {@link Goal}s before on one {@link Goal} a further set node is + * executed. *

    + * * @author Martin Hentschel * @see SymbolicExecutionGoalChooserBuilder */ public class SymbolicExecutionGoalChooser extends DepthFirstGoalChooser { - /** - * This {@link Set} is used to count on which {@link Goal}s a - * symbolic execution node was executed. Initially it is filled in - * {@link #getNextGoal()} with all possible {@link Goal}s. Every call - * of {@link #getNextGoal()} will then remove a {@link Goal} from this list. - * If a {@link Goal} is not contained in this list it is skipped in - * {@link #getNextGoal()} until the {@link Set} is empty which indicates - * that on all {@link Goal}s a symbolic execution tree node was created. - * Then the process starts again. - */ - private Set goalsToPrefer = new LinkedHashSet(); - - /** - * The optional custom stop condition used in the current proof. - */ - private StopCondition stopCondition; - - /** - * {@inheritDoc} - */ - @Override - public Goal getNextGoal() { - if (selectedList.size() >= 2) { - Goal goal = null; - // Reinitialize preferred set if required: Only with the goals where the stop condition accepts the next rule - if (stopCondition != null && goalsToPrefer.isEmpty()) { - for (Goal goalToPrefer: selectedList) { - if (stopCondition.isGoalAllowed(-1, -1l, proof, -1l, -1, goalToPrefer)) { - goalsToPrefer.add(goalToPrefer); - } - } - } - // Reinitialize preferred set if required: With all goals - if (goalsToPrefer.isEmpty()) { - for (Goal goalToPrefer: selectedList) { - goalsToPrefer.add(goalToPrefer); - } - } - // Select goal - Set goalsWhereStopConditionDoNotAllowNextRule = new LinkedHashSet(); - do { - Goal next = super.getNextGoal(); - if (next == null) { - return null; + /** + * This {@link Set} is used to count on which {@link Goal}s a symbolic execution node was + * executed. Initially it is filled in {@link #getNextGoal()} with all possible {@link Goal}s. + * Every call of {@link #getNextGoal()} will then remove a {@link Goal} from this list. If a + * {@link Goal} is not contained in this list it is skipped in {@link #getNextGoal()} until the + * {@link Set} is empty which indicates that on all {@link Goal}s a symbolic execution tree node + * was created. Then the process starts again. + */ + private Set goalsToPrefer = new LinkedHashSet(); + + /** + * The optional custom stop condition used in the current proof. + */ + private StopCondition stopCondition; + + /** + * {@inheritDoc} + */ + @Override + public Goal getNextGoal() { + if (selectedList.size() >= 2) { + Goal goal = null; + // Reinitialize preferred set if required: Only with the goals where the stop condition + // accepts the next rule + if (stopCondition != null && goalsToPrefer.isEmpty()) { + for (Goal goalToPrefer : selectedList) { + if (stopCondition.isGoalAllowed(-1, -1l, proof, -1l, -1, goalToPrefer)) { + goalsToPrefer.add(goalToPrefer); + } + } } - Node node = next.node(); - RuleApp ruleApp = next.getRuleAppManager().peekNext(); - if (!SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { - // Internal proof node, goal from super class can be used - goal = next; + // Reinitialize preferred set if required: With all goals + if (goalsToPrefer.isEmpty()) { + for (Goal goalToPrefer : selectedList) { + goalsToPrefer.add(goalToPrefer); + } } - else { - // Preferred goals should be used first, check if goal from super class is preferred - if (goalsToPrefer.remove(next) || goalsToPrefer.isEmpty()) { - // Goal is preferred, so check if next rule is allowed - if (stopCondition == null || - stopCondition.isGoalAllowed(-1, -1l, proof, -1l, -1, next)) { - // Next rule allowed, goal is preferred so return it as result - goal = next; - } - else { - // Goal is not preferred so collect internal to avoid endless loops - if (goalsWhereStopConditionDoNotAllowNextRule.add(next)) { + // Select goal + Set goalsWhereStopConditionDoNotAllowNextRule = new LinkedHashSet(); + do { + Goal next = super.getNextGoal(); + if (next == null) { + return null; + } + Node node = next.node(); + RuleApp ruleApp = next.getRuleAppManager().peekNext(); + if (!SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp)) { + // Internal proof node, goal from super class can be used + goal = next; + } else { + // Preferred goals should be used first, check if goal from super class is + // preferred + if (goalsToPrefer.remove(next) || goalsToPrefer.isEmpty()) { + // Goal is preferred, so check if next rule is allowed + if (stopCondition == null + || stopCondition.isGoalAllowed(-1, -1l, proof, -1l, -1, next)) { + // Next rule allowed, goal is preferred so return it as result + goal = next; + } else { + // Goal is not preferred so collect internal to avoid endless loops + if (goalsWhereStopConditionDoNotAllowNextRule.add(next)) { + // Update selected list to get a new goal in next loop iteration + Goal head = selectedList.head(); + selectedList = selectedList.take(1); + selectedList = selectedList.append(head); + } else { + // Next rule not allowed, but all other goals also don't allow it, + // so return it + goal = next; + } + } + } + // Check if a goal was found in this loop iteration, if not change order of + // goals in super class + if (goal == null) { // Update selected list to get a new goal in next loop iteration Goal head = selectedList.head(); selectedList = selectedList.take(1); selectedList = selectedList.append(head); - } - else { - // Next rule not allowed, but all other goals also don't allow it, so return it - goal = next; - } - } - } - // Check if a goal was found in this loop iteration, if not change order of goals in super class - if (goal == null) { - // Update selected list to get a new goal in next loop iteration - Goal head = selectedList.head(); - selectedList = selectedList.take(1); - selectedList = selectedList.append(head); - } - } - } while (goal == null); - return goal; - } - else { - // Return the only goal - return super.getNextGoal(); - } - } + } + } + } while (goal == null); + return goal; + } else { + // Return the only goal + return super.getNextGoal(); + } + } - /** - * {@inheritDoc} - */ - @Override - public void init(Proof p_proof, ImmutableList p_goals) { - // Clear preferred set to make sure that it is refilled when the first Goal should be selected and no old state is used. - goalsToPrefer.clear(); - // Update stop condition - stopCondition = p_proof != null ? - p_proof.getSettings().getStrategySettings().getCustomApplyStrategyStopCondition() : - null; - // Update available goals in super class - super.init(p_proof, p_goals); - } + /** + * {@inheritDoc} + */ + @Override + public void init(Proof p_proof, ImmutableList p_goals) { + // Clear preferred set to make sure that it is refilled when the first Goal should be + // selected and no old state is used. + goalsToPrefer.clear(); + // Update stop condition + stopCondition = p_proof != null + ? p_proof.getSettings().getStrategySettings().getCustomApplyStrategyStopCondition() + : null; + // Update available goals in super class + super.init(p_proof, p_goals); + } - /** - * {@inheritDoc} - */ - @Override - public void removeGoal(Goal p_goal) { - // Update available goals in super class - super.removeGoal(p_goal); - // Remove no longer relevant goal from preferred set - goalsToPrefer.remove(p_goal); - } + /** + * {@inheritDoc} + */ + @Override + public void removeGoal(Goal p_goal) { + // Update available goals in super class + super.removeGoal(p_goal); + // Remove no longer relevant goal from preferred set + goalsToPrefer.remove(p_goal); + } - /** - * {@inheritDoc} - */ - @Override - public void updateGoalList(Node node, ImmutableList newGoals) { - // Update available goals in super class - super.updateGoalList(node, newGoals); - // Remove no longer relevant goals from preferred set - Iterator preferredIter = goalsToPrefer.iterator(); - while (preferredIter.hasNext()) { - Goal next = preferredIter.next(); - if (!proof.openGoals().contains(next)) { - preferredIter.remove(); - } - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void updateGoalList(Node node, ImmutableList newGoals) { + // Update available goals in super class + super.updateGoalList(node, newGoals); + // Remove no longer relevant goals from preferred set + Iterator preferredIter = goalsToPrefer.iterator(); + while (preferredIter.hasNext()) { + Goal next = preferredIter.next(); + if (!proof.openGoals().contains(next)) { + preferredIter.remove(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooserBuilder.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooserBuilder.java index 23d8ee2063a..4065bb8e0b0 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooserBuilder.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionGoalChooserBuilder.java @@ -1,41 +1,44 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import de.uka.ilkd.key.prover.GoalChooserBuilder; import de.uka.ilkd.key.prover.GoalChooser; /** - * This {@link GoalChooserBuilder} creates a special {@link GoalChooser} - * for symbolic execution. + * This {@link GoalChooserBuilder} creates a special {@link GoalChooser} for symbolic execution. + * * @author Martin Hentschel * @see SymbolicExecutionGoalChooser */ public class SymbolicExecutionGoalChooserBuilder implements GoalChooserBuilder { - /** - * The name of this goal chooser. - */ - public static final String NAME = "Symbolic Execution Goal Chooser"; + /** + * The name of this goal chooser. + */ + public static final String NAME = "Symbolic Execution Goal Chooser"; - /** - * {@inheritDoc} - */ - @Override - public GoalChooser create() { - return new SymbolicExecutionGoalChooser(); - } + /** + * {@inheritDoc} + */ + @Override + public GoalChooser create() { + return new SymbolicExecutionGoalChooser(); + } - /** - * {@inheritDoc} - */ - @Override - public GoalChooserBuilder copy() { - return new SymbolicExecutionGoalChooserBuilder(); - } + /** + * {@inheritDoc} + */ + @Override + public GoalChooserBuilder copy() { + return new SymbolicExecutionGoalChooserBuilder(); + } - /** - * {@inheritDoc} - */ - @Override - public String name() { - return NAME; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public String name() { + return NAME; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionStrategy.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionStrategy.java index 32badf6db7e..01d550dfe9b 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionStrategy.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/SymbolicExecutionStrategy.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy; import java.util.ArrayList; @@ -34,268 +37,301 @@ * {@link Strategy} to use for symbolic execution. */ public class SymbolicExecutionStrategy extends JavaCardDLStrategy { - /** - * The {@link Name} of the symbolic execution {@link Strategy}. - */ - public static final Name name = new Name("Symbolic Execution Strategy"); - - /** - * The default factory. - */ - public static IDefaultStrategyPropertiesFactory DEFAULT_FACTORY = new IDefaultStrategyPropertiesFactory() { - @Override - public StrategyProperties createDefaultStrategyProperties() { - return SymbolicExecutionStrategy.getSymbolicExecutionStrategyProperties(true, false, false, false, false, false); - } - }; - - /** - * Constructor. - * @param proof The proof. - * @param sp The {@link StrategyProperties} to use. - */ - private SymbolicExecutionStrategy(Proof proof, StrategyProperties sp) { - super(proof, sp); - // Update cost dispatcher - RuleSetDispatchFeature costRsd = getCostComputationDispatcher(); + /** + * The {@link Name} of the symbolic execution {@link Strategy}. + */ + public static final Name name = new Name("Symbolic Execution Strategy"); - clearRuleSetBindings (costRsd, "simplify_prog" ); - bindRuleSet (costRsd, "simplify_prog",10000); - - clearRuleSetBindings (costRsd, "simplify_prog_subset" ); - bindRuleSet (costRsd, "simplify_prog_subset",10000); - - Feature splitF = ScaleFeature.createScaled(CountBranchFeature.INSTANCE, -4000); - bindRuleSet(costRsd, "split_if", splitF); // The costs of rules in heuristic "split_if" is reduced at runtime by numberOfBranches * -400. The result is that rules of "split_if" preferred to "split_cond" and run and step into has the same behavior - bindRuleSet(costRsd, "instanceof_to_exists", inftyConst()); - - // Update instantiation dispatcher - if (StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY.equals(sp.get(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY))) { - // Make sure that an immediately alias check is performed by doing cuts of objects to find out if they can be the same or not - RuleSetDispatchFeature instRsd = getInstantiationDispatcher(); - enableInstantiate(); - final TermBuffer buffer = new TermBuffer(); - Feature originalCut = instRsd.get(getHeuristic("cut")); - Feature newCut = forEach(buffer, new CutHeapObjectsTermGenerator(), add(instantiate ("cutFormula", buffer), longConst(-10000))); - if (originalCut instanceof OneOfCP) { - clearRuleSetBindings (instRsd, "cut" ); - bindRuleSet (instRsd, "cut", oneOf(originalCut, newCut)); - } - else { - bindRuleSet (instRsd, "cut", newCut); - } - disableInstantiate(); - } - // TODO: For delayed similar to sequentContainsNoPrograms() - } - - /** - * {@inheritDoc} - */ - @Override - protected Feature setupApprovalF() { - Feature result = super.setupApprovalF(); - // Make sure that cuts are only applied if the cut term is not already part of the sequent. This check is performed exactly before the rule is applied because the sequent might has changed in the time after the schema variable instantiation was instantiated. - SetRuleFilter depFilter = new SetRuleFilter(); - depFilter.addRuleToSet(getProof().getInitConfig().lookupActiveTaclet(new Name("cut"))); - result = add(result, ConditionalFeature.createConditional(depFilter, new CutHeapObjectsFeature())); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - protected Feature setupGlobalF(Feature dispatcher) { - Feature globalF = super.setupGlobalF(dispatcher); - // Make sure that modalities without symbolic execution label are executed first because they might forbid rule application on modalities with symbolic execution label (see loop body branches) - globalF = add(globalF, ifZero(not(new BinaryFeature() { - @Override - protected boolean filter(RuleApp app, PosInOccurrence pos, Goal goal) { - return pos != null && SymbolicExecutionUtil.hasSymbolicExecutionLabel(pos.subTerm()); - } - }), longConst(-3000))); - // Make sure that the modality which executes a loop body is preferred against the modalities which executes special loop terminations like return, exceptions or break. - globalF = add(globalF, ifZero(new ContainsLabelFeature(SymbolicExecutionUtil.LOOP_BODY_LABEL), longConst(-2000))); - globalF = add(globalF, querySideProofFeature()); - globalF = add(globalF, modalitySideProofFeature()); - return globalF; - } - - /** - * Computes the cost {@link Feature} for the {@link ModalitySideProofRule}. - * @return The cost {@link Feature} for the {@link ModalitySideProofRule}. - */ - protected Feature modalitySideProofFeature() { - SetRuleFilter filter = new SetRuleFilter(); - filter.addRuleToSet(ModalitySideProofRule.INSTANCE); - if (StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF.equals(strategyProperties.get(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY))) { - return ConditionalFeature.createConditional(filter, longConst(-3050)); - } - else { - return ConditionalFeature.createConditional(filter, inftyConst()); - } - } - - /** - * Computes the cost {@link Feature} for the {@link QuerySideProofRule}. - * @return The cost {@link Feature} for the {@link QuerySideProofRule}. - */ - protected Feature querySideProofFeature() { - SetRuleFilter filter = new SetRuleFilter(); - filter.addRuleToSet(QuerySideProofRule.INSTANCE); - if (StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF.equals(strategyProperties.get(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY))) { - return ConditionalFeature.createConditional(filter, longConst(-3050)); // Rule must be preferred to rules with heuristic "query_axiom" and rule QueryExpand - } - else { - return ConditionalFeature.createConditional(filter, inftyConst()); - } - } + /** + * The default factory. + */ + public static IDefaultStrategyPropertiesFactory DEFAULT_FACTORY = + new IDefaultStrategyPropertiesFactory() { + @Override + public StrategyProperties createDefaultStrategyProperties() { + return SymbolicExecutionStrategy.getSymbolicExecutionStrategyProperties(true, + false, false, false, false, false); + } + }; - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return name; - } - - /** - * Returns the default {@link StrategyProperties} of symbolic execution. - * @param quantifierInstantiationWithSplitting Instantiate quantifiers? - * @param methodTreatmentContract Use method contracts or inline method bodies otherwise? - * @param loopTreatmentInvariant Use loop invariants or unrole loops otherwise? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @return The default {@link StrategyProperties} for symbolic execution. - */ - public static StrategyProperties getSymbolicExecutionStrategyProperties(boolean quantifierInstantiationWithSplitting, - boolean methodTreatmentContract, - boolean loopTreatmentInvariant, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks) { - StrategyProperties sp = new StrategyProperties(); - StrategyProperties.setDefaultStrategyProperties(sp, - quantifierInstantiationWithSplitting, - methodTreatmentContract, - loopTreatmentInvariant, - blockTreatmentContract, - nonExecutionBranchHidingSideProofs, - aliasChecks); - return sp; - } + /** + * Constructor. + * + * @param proof The proof. + * @param sp The {@link StrategyProperties} to use. + */ + private SymbolicExecutionStrategy(Proof proof, StrategyProperties sp) { + super(proof, sp); + // Update cost dispatcher + RuleSetDispatchFeature costRsd = getCostComputationDispatcher(); - /** - * The {@link StrategyFactory} to create instances of {@link SymbolicExecutionStrategy}. - * @author Martin Hentschel - */ - public static class Factory implements StrategyFactory { - /** - * Shown string for method treatment "Expand". - */ - public static final String METHOD_TREATMENT_EXPAND = "Inline Methods"; + clearRuleSetBindings(costRsd, "simplify_prog"); + bindRuleSet(costRsd, "simplify_prog", 10000); - /** - * Shown string for method treatment "Contract". - */ - public static final String METHOD_TREATMENT_CONTRACT = "Use Contracts"; + clearRuleSetBindings(costRsd, "simplify_prog_subset"); + bindRuleSet(costRsd, "simplify_prog_subset", 10000); - /** - * Shown string for loop treatment "Expand". - */ - public static final String LOOP_TREATMENT_EXPAND = "Unroll Loops"; + Feature splitF = ScaleFeature.createScaled(CountBranchFeature.INSTANCE, -4000); + bindRuleSet(costRsd, "split_if", splitF); // The costs of rules in heuristic "split_if" is + // reduced at runtime by numberOfBranches * -400. + // The result is that rules of "split_if" + // preferred to "split_cond" and run and step into + // has the same behavior + bindRuleSet(costRsd, "instanceof_to_exists", inftyConst()); - /** - * Shown string for loop treatment "Invariant". - */ - public static final String LOOP_TREATMENT_INVARIANT = "Use Loop Invariants"; + // Update instantiation dispatcher + if (StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY + .equals(sp.get(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY))) { + // Make sure that an immediately alias check is performed by doing cuts of objects to + // find out if they can be the same or not + RuleSetDispatchFeature instRsd = getInstantiationDispatcher(); + enableInstantiate(); + final TermBuffer buffer = new TermBuffer(); + Feature originalCut = instRsd.get(getHeuristic("cut")); + Feature newCut = forEach(buffer, new CutHeapObjectsTermGenerator(), + add(instantiate("cutFormula", buffer), longConst(-10000))); + if (originalCut instanceof OneOfCP) { + clearRuleSetBindings(instRsd, "cut"); + bindRuleSet(instRsd, "cut", oneOf(originalCut, newCut)); + } else { + bindRuleSet(instRsd, "cut", newCut); + } + disableInstantiate(); + } + // TODO: For delayed similar to sequentContainsNoPrograms() + } - /** - * Shown string for block treatment "Expand". - */ - public static final String BLOCK_TREATMENT_EXPAND = "Expand Blocks"; + /** + * {@inheritDoc} + */ + @Override + protected Feature setupApprovalF() { + Feature result = super.setupApprovalF(); + // Make sure that cuts are only applied if the cut term is not already part of the sequent. + // This check is performed exactly before the rule is applied because the sequent might has + // changed in the time after the schema variable instantiation was instantiated. + SetRuleFilter depFilter = new SetRuleFilter(); + depFilter.addRuleToSet(getProof().getInitConfig().lookupActiveTaclet(new Name("cut"))); + result = add(result, + ConditionalFeature.createConditional(depFilter, new CutHeapObjectsFeature())); + return result; + } - /** - * Shown string for block treatment "Invariant". - */ - public static final String BLOCK_TREATMENT_INVARIANT = "Use Contracts"; + /** + * {@inheritDoc} + */ + @Override + protected Feature setupGlobalF(Feature dispatcher) { + Feature globalF = super.setupGlobalF(dispatcher); + // Make sure that modalities without symbolic execution label are executed first because + // they might forbid rule application on modalities with symbolic execution label (see loop + // body branches) + globalF = add(globalF, ifZero(not(new BinaryFeature() { + @Override + protected boolean filter(RuleApp app, PosInOccurrence pos, Goal goal) { + return pos != null + && SymbolicExecutionUtil.hasSymbolicExecutionLabel(pos.subTerm()); + } + }), longConst(-3000))); + // Make sure that the modality which executes a loop body is preferred against the + // modalities which executes special loop terminations like return, exceptions or break. + globalF = + add(globalF, ifZero(new ContainsLabelFeature(SymbolicExecutionUtil.LOOP_BODY_LABEL), + longConst(-2000))); + globalF = add(globalF, querySideProofFeature()); + globalF = add(globalF, modalitySideProofFeature()); + return globalF; + } - /** - * Shown string for alias check "Never". - */ - public static final String NON_EXECUTION_BRANCH_HIDING_OFF = "Off"; + /** + * Computes the cost {@link Feature} for the {@link ModalitySideProofRule}. + * + * @return The cost {@link Feature} for the {@link ModalitySideProofRule}. + */ + protected Feature modalitySideProofFeature() { + SetRuleFilter filter = new SetRuleFilter(); + filter.addRuleToSet(ModalitySideProofRule.INSTANCE); + if (StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF + .equals(strategyProperties.get( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY))) { + return ConditionalFeature.createConditional(filter, longConst(-3050)); + } else { + return ConditionalFeature.createConditional(filter, inftyConst()); + } + } - /** - * Shown string for alias check "Immediately". - */ - public static final String NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF = "On"; + /** + * Computes the cost {@link Feature} for the {@link QuerySideProofRule}. + * + * @return The cost {@link Feature} for the {@link QuerySideProofRule}. + */ + protected Feature querySideProofFeature() { + SetRuleFilter filter = new SetRuleFilter(); + filter.addRuleToSet(QuerySideProofRule.INSTANCE); + if (StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF + .equals(strategyProperties.get( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY))) { + return ConditionalFeature.createConditional(filter, longConst(-3050)); // Rule must be + // preferred to + // rules with + // heuristic + // "query_axiom" + // and rule + // QueryExpand + } else { + return ConditionalFeature.createConditional(filter, inftyConst()); + } + } - /** - * Shown string for alias check "Never". - */ - public static final String ALIAS_CHECK_NEVER = "Never"; + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return name; + } - /** - * Shown string for alias check "Immediately". - */ - public static final String ALIAS_CHECK_IMMEDIATELY = "Immediately"; - - /** - * {@inheritDoc} - */ - @Override - public Strategy create(Proof proof, StrategyProperties sp) { - return new SymbolicExecutionStrategy(proof, sp); - } + /** + * Returns the default {@link StrategyProperties} of symbolic execution. + * + * @param quantifierInstantiationWithSplitting Instantiate quantifiers? + * @param methodTreatmentContract Use method contracts or inline method bodies otherwise? + * @param loopTreatmentInvariant Use loop invariants or unrole loops otherwise? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @return The default {@link StrategyProperties} for symbolic execution. + */ + public static StrategyProperties getSymbolicExecutionStrategyProperties( + boolean quantifierInstantiationWithSplitting, boolean methodTreatmentContract, + boolean loopTreatmentInvariant, boolean blockTreatmentContract, + boolean nonExecutionBranchHidingSideProofs, boolean aliasChecks) { + StrategyProperties sp = new StrategyProperties(); + StrategyProperties.setDefaultStrategyProperties(sp, quantifierInstantiationWithSplitting, + methodTreatmentContract, loopTreatmentInvariant, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + return sp; + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return name; - } + /** + * The {@link StrategyFactory} to create instances of {@link SymbolicExecutionStrategy}. + * + * @author Martin Hentschel + */ + public static class Factory implements StrategyFactory { + /** + * Shown string for method treatment "Expand". + */ + public static final String METHOD_TREATMENT_EXPAND = "Inline Methods"; - /** - * {@inheritDoc} - */ - @Override - public StrategySettingsDefinition getSettingsDefinition() { - // Properties - OneOfStrategyPropertyDefinition methodTreatment = new OneOfStrategyPropertyDefinition(StrategyProperties.METHOD_OPTIONS_KEY, - "Method Treatment", - new StrategyPropertyValueDefinition(StrategyProperties.METHOD_EXPAND, METHOD_TREATMENT_EXPAND, null), - new StrategyPropertyValueDefinition(StrategyProperties.METHOD_CONTRACT, METHOD_TREATMENT_CONTRACT, null)); - OneOfStrategyPropertyDefinition loopTreatment = new OneOfStrategyPropertyDefinition(StrategyProperties.LOOP_OPTIONS_KEY, - "Loop Treatment", - new StrategyPropertyValueDefinition(StrategyProperties.LOOP_EXPAND, LOOP_TREATMENT_EXPAND, null), - new StrategyPropertyValueDefinition(StrategyProperties.LOOP_INVARIANT, LOOP_TREATMENT_INVARIANT, null)); - OneOfStrategyPropertyDefinition blockTreatment = new OneOfStrategyPropertyDefinition(StrategyProperties.BLOCK_OPTIONS_KEY, - "Block Treatment", - new StrategyPropertyValueDefinition(StrategyProperties.BLOCK_EXPAND, BLOCK_TREATMENT_EXPAND, null), - new StrategyPropertyValueDefinition(StrategyProperties.BLOCK_CONTRACT_INTERNAL, BLOCK_TREATMENT_INVARIANT, null)); - OneOfStrategyPropertyDefinition branchHiding = new OneOfStrategyPropertyDefinition(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY, - "Non Execution Branch Hiding", - new StrategyPropertyValueDefinition(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OFF, NON_EXECUTION_BRANCH_HIDING_OFF, null), - new StrategyPropertyValueDefinition(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF, NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF, null)); - OneOfStrategyPropertyDefinition aliasChecks = new OneOfStrategyPropertyDefinition(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY, - "Alias Checks", - new StrategyPropertyValueDefinition(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_NEVER, ALIAS_CHECK_NEVER, null), - new StrategyPropertyValueDefinition(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY, ALIAS_CHECK_IMMEDIATELY, null)); - // Model - return new StrategySettingsDefinition(false, - null, - 1000, - "Symbolic Execution Options", - SymbolicExecutionStrategy.DEFAULT_FACTORY, - new ArrayList>(), - methodTreatment, - loopTreatment, - blockTreatment, - branchHiding, - aliasChecks); - } - } -} \ No newline at end of file + /** + * Shown string for method treatment "Contract". + */ + public static final String METHOD_TREATMENT_CONTRACT = "Use Contracts"; + + /** + * Shown string for loop treatment "Expand". + */ + public static final String LOOP_TREATMENT_EXPAND = "Unroll Loops"; + + /** + * Shown string for loop treatment "Invariant". + */ + public static final String LOOP_TREATMENT_INVARIANT = "Use Loop Invariants"; + + /** + * Shown string for block treatment "Expand". + */ + public static final String BLOCK_TREATMENT_EXPAND = "Expand Blocks"; + + /** + * Shown string for block treatment "Invariant". + */ + public static final String BLOCK_TREATMENT_INVARIANT = "Use Contracts"; + + /** + * Shown string for alias check "Never". + */ + public static final String NON_EXECUTION_BRANCH_HIDING_OFF = "Off"; + + /** + * Shown string for alias check "Immediately". + */ + public static final String NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF = "On"; + + /** + * Shown string for alias check "Never". + */ + public static final String ALIAS_CHECK_NEVER = "Never"; + + /** + * Shown string for alias check "Immediately". + */ + public static final String ALIAS_CHECK_IMMEDIATELY = "Immediately"; + + /** + * {@inheritDoc} + */ + @Override + public Strategy create(Proof proof, StrategyProperties sp) { + return new SymbolicExecutionStrategy(proof, sp); + } + + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return name; + } + + /** + * {@inheritDoc} + */ + @Override + public StrategySettingsDefinition getSettingsDefinition() { + // Properties + OneOfStrategyPropertyDefinition methodTreatment = new OneOfStrategyPropertyDefinition( + StrategyProperties.METHOD_OPTIONS_KEY, "Method Treatment", + new StrategyPropertyValueDefinition(StrategyProperties.METHOD_EXPAND, + METHOD_TREATMENT_EXPAND, null), + new StrategyPropertyValueDefinition(StrategyProperties.METHOD_CONTRACT, + METHOD_TREATMENT_CONTRACT, null)); + OneOfStrategyPropertyDefinition loopTreatment = new OneOfStrategyPropertyDefinition( + StrategyProperties.LOOP_OPTIONS_KEY, "Loop Treatment", + new StrategyPropertyValueDefinition(StrategyProperties.LOOP_EXPAND, + LOOP_TREATMENT_EXPAND, null), + new StrategyPropertyValueDefinition(StrategyProperties.LOOP_INVARIANT, + LOOP_TREATMENT_INVARIANT, null)); + OneOfStrategyPropertyDefinition blockTreatment = new OneOfStrategyPropertyDefinition( + StrategyProperties.BLOCK_OPTIONS_KEY, "Block Treatment", + new StrategyPropertyValueDefinition(StrategyProperties.BLOCK_EXPAND, + BLOCK_TREATMENT_EXPAND, null), + new StrategyPropertyValueDefinition(StrategyProperties.BLOCK_CONTRACT_INTERNAL, + BLOCK_TREATMENT_INVARIANT, null)); + OneOfStrategyPropertyDefinition branchHiding = new OneOfStrategyPropertyDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY, + "Non Execution Branch Hiding", + new StrategyPropertyValueDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OFF, + NON_EXECUTION_BRANCH_HIDING_OFF, null), + new StrategyPropertyValueDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF, + NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF, null)); + OneOfStrategyPropertyDefinition aliasChecks = new OneOfStrategyPropertyDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY, "Alias Checks", + new StrategyPropertyValueDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_NEVER, + ALIAS_CHECK_NEVER, null), + new StrategyPropertyValueDefinition( + StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY, + ALIAS_CHECK_IMMEDIATELY, null)); + // Model + return new StrategySettingsDefinition(false, null, 1000, "Symbolic Execution Options", + SymbolicExecutionStrategy.DEFAULT_FACTORY, + new ArrayList>(), + methodTreatment, loopTreatment, blockTreatment, branchHiding, aliasChecks); + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractBreakpoint.java index 6a15648c5d3..6af18f2050e 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import de.uka.ilkd.key.proof.Goal; @@ -5,61 +8,59 @@ /** * Provides the basic implementation of an {@link IBreakpoint}. + * * @author Martin Hentschel */ public abstract class AbstractBreakpoint implements IBreakpoint { - /** - * The proof this stop condition is associated with. - */ - private final Proof proof; + /** + * The proof this stop condition is associated with. + */ + private final Proof proof; - /** - * The flag if the Breakpoint is enabled. - */ - private boolean enabled; - - /** - * Constructor. - * @param proof The {@link Proof} in which this {@link IBreakpoint} is used. - * @param enabled The enabled state. - */ - public AbstractBreakpoint(Proof proof, boolean enabled) { - this.proof = proof; - this.enabled = enabled; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateState(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isEnabled() { - return enabled; - } + /** + * The flag if the Breakpoint is enabled. + */ + private boolean enabled; - /** - * Sets the new enabled value. - * @param enabled the new value - */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + /** + * Constructor. + * + * @param proof The {@link Proof} in which this {@link IBreakpoint} is used. + * @param enabled The enabled state. + */ + public AbstractBreakpoint(Proof proof, boolean enabled) { + this.proof = proof; + this.enabled = enabled; + } - /** - * @return the proof - */ - public Proof getProof() { - return proof; - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public void updateState(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) {} + + /** + * {@inheritDoc} + */ + @Override + public boolean isEnabled() { + return enabled; + } + + /** + * Sets the new enabled value. + * + * @param enabled the new value + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /** + * @return the proof + */ + public Proof getProof() { + return proof; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractConditionalBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractConditionalBreakpoint.java index d5b1289fe5d..5b33bb97849 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractConditionalBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractConditionalBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import de.uka.ilkd.key.java.*; @@ -32,472 +35,526 @@ /** * Adds the funtionality to breakpoints to evaluate conditions. + * * @author Martin Hentschel */ public abstract class AbstractConditionalBreakpoint extends AbstractHitCountBreakpoint { - /** - * The condition for this Breakpoint (set by user). - */ - private Term condition; - - /** - * The flag if the the condition for the associated Breakpoint is enabled - */ - private boolean conditionEnabled; - - /** - * The condition of the associated breakpoint saved as a String - */ - private String conditionString; - - /** - * A list of {@link ProgramVariable}s containing all variables that were parsed and have to be possibly replaced during runtime. - */ - private ImmutableList varsForCondition; - - /** - * The KeYJavaType of the container of the element associated with the breakpoint. - */ - private KeYJavaType containerType; - - /** - * A list of variables KeY has to hold to evaluate the condition - */ - private Set toKeep; - - /** - * A {@link Map} mapping from relevant variables for the condition to their runtime equivalent in KeY - */ - private Map variableNamingMap; - - /** - * The list of parameter variables of the method that contains the associated breakpoint - */ - private Set paramVars; - - /** - * A {@link ProgramVariable} representing the instance the class KeY is working on - */ - private ProgramVariable selfVar; - - /** - * The {@link IProgramMethod} this Breakpoint lies within - */ - private IProgramMethod pm; - - /** - * Creates a new {@link AbstractConditionalBreakpoint}. Call setCondition immediately after calling the constructor! - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located at - * @param proof the {@link Proof} that will be executed and should stop - * @param enabled flag if the Breakpoint is enabled - * @param conditionEnabled flag if the condition is enabled - * @param methodStart the line the containing method of this breakpoint starts at - * @param methodEnd the line the containing method of this breakpoint ends at - * @param containerType the type of the element containing the breakpoint - */ - public AbstractConditionalBreakpoint(int hitCount, IProgramMethod pm, Proof proof, boolean enabled, boolean conditionEnabled, int methodStart, int methodEnd, KeYJavaType containerType){ - super(hitCount, proof,enabled); - this.setPm(pm); - paramVars= new HashSet(); - setVariableNamingMap(new HashMap()); - toKeep = new HashSet(); - this.containerType=containerType; - this.conditionEnabled = conditionEnabled; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateState(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - super.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); - if (goal != null) { - Node node = goal.node(); - RuleApp ruleApp = goal.getRuleAppManager().peekNext(); - if (getVarsForCondition() != null && ruleApp != null && node != null) { - refreshVarMaps(ruleApp, node); - } - } - } - - /** - * put values in toKeep and variableNamingMap that can be found in the global variables of the node - * - * @param varForCondition - * @param node - * @param inScope - */ - private void putValuesFromGlobalVars(ProgramVariable varForCondition, Node node, boolean inScope) { - for(IProgramVariable progVar : node.getLocalProgVars()){ - if(inScope&&varForCondition.name().equals(progVar.name())&&(getVariableNamingMap().get(varForCondition)==null||getVariableNamingMap().get(varForCondition).equals(varForCondition))){ - toKeep.add((LocationVariable) progVar); - getVariableNamingMap().put(varForCondition, progVar); - } - } - } - - /** - * Returns a map containing the same entries as the variableNamingMap changes in one map do not effect the other map - * @return the cloned map - */ - private Map getOldMap() { - Map oldMap = new HashMap(); - Iterator iter = getVariableNamingMap().entrySet().iterator(); - while(iter.hasNext()){ - Map.Entry oldEntry = (Entry) iter.next(); - if(oldEntry.getKey() instanceof SVSubstitute && oldEntry.getValue() instanceof SVSubstitute){ - oldMap.put((SVSubstitute)oldEntry.getKey(), (SVSubstitute)oldEntry.getValue()); - } - } - return oldMap; - } - - /** - * removes all stored parameters in to Keep when the ruleApp on the current node would induce a method return - * @param node - * @param ruleApp - * @param inScope - */ - private void freeVariablesAfterReturn(Node node, RuleApp ruleApp,boolean inScope) { - if ((SymbolicExecutionUtil.isMethodReturnNode(node, ruleApp) || - SymbolicExecutionUtil.isExceptionalMethodReturnNode(node, ruleApp)) && - inScope) { - toKeep.clear(); - } - } - - /** - * put relevant values from the current nodes renamings in toKeep and variableNamingMap - * @param varForCondition the variable that might be relevant for the condition - * @param node the current - * @param inScope the flag to determine if the current statement is in the scope of the breakpoint - * @param oldMap the oldMap variableNamings - */ - private void putValuesFromRenamings(ProgramVariable varForCondition, Node node, boolean inScope, Map oldMap, RuleApp ruleApp) { - // look for renamings KeY did - boolean found = false; - //get current renaming tables - ImmutableList renamingTables = node.getRenamingTable(); - if (renamingTables != null && renamingTables.size() > 0) { - //iterate over renaming tables - Iterator itr = renamingTables.iterator(); - while (itr.hasNext() && !found) { - RenamingTable renamingTable = itr.next(); - //iterate over renamings within table - Iterator renameItr = renamingTable.getHashMap().entrySet().iterator(); - while (renameItr.hasNext()) { - Map.Entry entry = (Entry) renameItr.next(); - if (entry.getKey() instanceof LocationVariable && entry.getValue()instanceof SVSubstitute) { - if ((VariableNamer.getBasename(((LocationVariable) entry - .getKey()).name())).equals(varForCondition.name()) - && ((LocationVariable) entry.getKey()).name().toString().contains("#") - && paramVars.contains(varForCondition)) { - //found relevant renaming for a parameter variable - if (oldMap.get(varForCondition) != entry.getValue()) { - //remove old value from toKeep - toKeep.remove((LocationVariable) oldMap.get(varForCondition)); - } - //add new value - toKeep.add((LocationVariable) entry.getValue()); - getVariableNamingMap().put(varForCondition, (SVSubstitute) entry.getValue()); - found = true; - break; - } - else if (inScope && ((LocationVariable) entry.getKey()).name().equals(varForCondition.name())) { - //found relevant renaming for local variable - if (oldMap.get(varForCondition) != entry.getValue()) { - //remove old value from toKeep - toKeep.remove((LocationVariable) oldMap.get(varForCondition)); - } - //add new value - toKeep.add((LocationVariable) entry.getValue()); - getVariableNamingMap().put(varForCondition, (SVSubstitute) entry.getValue()); - found = true; - break; - } - } + /** + * The condition for this Breakpoint (set by user). + */ + private Term condition; + + /** + * The flag if the the condition for the associated Breakpoint is enabled + */ + private boolean conditionEnabled; + + /** + * The condition of the associated breakpoint saved as a String + */ + private String conditionString; + + /** + * A list of {@link ProgramVariable}s containing all variables that were parsed and have to be + * possibly replaced during runtime. + */ + private ImmutableList varsForCondition; + + /** + * The KeYJavaType of the container of the element associated with the breakpoint. + */ + private KeYJavaType containerType; + + /** + * A list of variables KeY has to hold to evaluate the condition + */ + private Set toKeep; + + /** + * A {@link Map} mapping from relevant variables for the condition to their runtime equivalent + * in KeY + */ + private Map variableNamingMap; + + /** + * The list of parameter variables of the method that contains the associated breakpoint + */ + private Set paramVars; + + /** + * A {@link ProgramVariable} representing the instance the class KeY is working on + */ + private ProgramVariable selfVar; + + /** + * The {@link IProgramMethod} this Breakpoint lies within + */ + private IProgramMethod pm; + + /** + * Creates a new {@link AbstractConditionalBreakpoint}. Call setCondition immediately after + * calling the constructor! + * + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located + * at + * @param proof the {@link Proof} that will be executed and should stop + * @param enabled flag if the Breakpoint is enabled + * @param conditionEnabled flag if the condition is enabled + * @param methodStart the line the containing method of this breakpoint starts at + * @param methodEnd the line the containing method of this breakpoint ends at + * @param containerType the type of the element containing the breakpoint + */ + public AbstractConditionalBreakpoint(int hitCount, IProgramMethod pm, Proof proof, + boolean enabled, boolean conditionEnabled, int methodStart, int methodEnd, + KeYJavaType containerType) { + super(hitCount, proof, enabled); + this.setPm(pm); + paramVars = new HashSet(); + setVariableNamingMap(new HashMap()); + toKeep = new HashSet(); + this.containerType = containerType; + this.conditionEnabled = conditionEnabled; + } + + /** + * {@inheritDoc} + */ + @Override + public void updateState(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + super.updateState(maxApplications, timeout, proof, startTime, countApplied, goal); + if (goal != null) { + Node node = goal.node(); + RuleApp ruleApp = goal.getRuleAppManager().peekNext(); + if (getVarsForCondition() != null && ruleApp != null && node != null) { + refreshVarMaps(ruleApp, node); + } + } + } + + /** + * put values in toKeep and variableNamingMap that can be found in the global variables of the + * node + * + * @param varForCondition + * @param node + * @param inScope + */ + private void putValuesFromGlobalVars(ProgramVariable varForCondition, Node node, + boolean inScope) { + for (IProgramVariable progVar : node.getLocalProgVars()) { + if (inScope && varForCondition.name().equals(progVar.name()) + && (getVariableNamingMap().get(varForCondition) == null + || getVariableNamingMap().get(varForCondition) + .equals(varForCondition))) { + toKeep.add((LocationVariable) progVar); + getVariableNamingMap().put(varForCondition, progVar); + } + } + } + + /** + * Returns a map containing the same entries as the variableNamingMap changes in one map do not + * effect the other map + * + * @return the cloned map + */ + private Map getOldMap() { + Map oldMap = new HashMap(); + Iterator iter = getVariableNamingMap().entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry oldEntry = (Entry) iter.next(); + if (oldEntry.getKey() instanceof SVSubstitute + && oldEntry.getValue() instanceof SVSubstitute) { + oldMap.put((SVSubstitute) oldEntry.getKey(), (SVSubstitute) oldEntry.getValue()); + } + } + return oldMap; + } + + /** + * removes all stored parameters in to Keep when the ruleApp on the current node would induce a + * method return + * + * @param node + * @param ruleApp + * @param inScope + */ + private void freeVariablesAfterReturn(Node node, RuleApp ruleApp, boolean inScope) { + if ((SymbolicExecutionUtil.isMethodReturnNode(node, ruleApp) + || SymbolicExecutionUtil.isExceptionalMethodReturnNode(node, ruleApp)) && inScope) { + toKeep.clear(); + } + } + + /** + * put relevant values from the current nodes renamings in toKeep and variableNamingMap + * + * @param varForCondition the variable that might be relevant for the condition + * @param node the current + * @param inScope the flag to determine if the current statement is in the scope of the + * breakpoint + * @param oldMap the oldMap variableNamings + */ + private void putValuesFromRenamings(ProgramVariable varForCondition, Node node, boolean inScope, + Map oldMap, RuleApp ruleApp) { + // look for renamings KeY did + boolean found = false; + // get current renaming tables + ImmutableList renamingTables = node.getRenamingTable(); + if (renamingTables != null && renamingTables.size() > 0) { + // iterate over renaming tables + Iterator itr = renamingTables.iterator(); + while (itr.hasNext() && !found) { + RenamingTable renamingTable = itr.next(); + // iterate over renamings within table + Iterator renameItr = renamingTable.getHashMap().entrySet().iterator(); + while (renameItr.hasNext()) { + Map.Entry entry = (Entry) renameItr.next(); + if (entry.getKey() instanceof LocationVariable + && entry.getValue() instanceof SVSubstitute) { + if ((VariableNamer.getBasename(((LocationVariable) entry.getKey()).name())) + .equals(varForCondition.name()) + && ((LocationVariable) entry.getKey()).name().toString() + .contains("#") + && paramVars.contains(varForCondition)) { + // found relevant renaming for a parameter variable + if (oldMap.get(varForCondition) != entry.getValue()) { + // remove old value from toKeep + toKeep.remove((LocationVariable) oldMap.get(varForCondition)); + } + // add new value + toKeep.add((LocationVariable) entry.getValue()); + getVariableNamingMap().put(varForCondition, + (SVSubstitute) entry.getValue()); + found = true; + break; + } else if (inScope && ((LocationVariable) entry.getKey()).name() + .equals(varForCondition.name())) { + // found relevant renaming for local variable + if (oldMap.get(varForCondition) != entry.getValue()) { + // remove old value from toKeep + toKeep.remove((LocationVariable) oldMap.get(varForCondition)); + } + // add new value + toKeep.add((LocationVariable) entry.getValue()); + getVariableNamingMap().put(varForCondition, + (SVSubstitute) entry.getValue()); + found = true; + break; + } + } + } + } + } + } + + + /** + * Modifies toKeep and variableNamingMap to hold the correct parameters after execution of the + * given ruleApp on the given node + * + * @param ruleApp the applied rule app + * @param nodethe current node + */ + protected void refreshVarMaps(RuleApp ruleApp, Node node) { + boolean inScope = isInScope(node); + // collect old values + Map oldMap = getOldMap(); + // put values into map which have to be replaced + for (ProgramVariable varForCondition : getVarsForCondition()) { + // put global variables only done when a variable is instantiated by + // KeY for the first time + putValuesFromGlobalVars(varForCondition, node, inScope); + // put renamings into map and tokeep remove no longer need vars from + // tokeep + putValuesFromRenamings(varForCondition, node, isInScopeForCondition(node), oldMap, + ruleApp); + } + freeVariablesAfterReturn(node, ruleApp, inScope); + } + + /** + * Computes the Term that can be evaluated, from the user given condition + * + * @param condition the condition given by the user + * @return the {@link Term} that represents the condition + */ + private Term computeTermForCondition(String condition) { + if (condition == null) { + return getProof().getServices().getTermBuilder().tt(); + } + // collect all variables needed to parse the condition + setSelfVar(new LocationVariable( + new ProgramElementName(getProof().getServices().getTermBuilder().newName("self")), + containerType, null, false, false)); + ImmutableList varsForCondition = ImmutableSLList.nil(); + if (getPm() != null) { + // collect parameter variables + for (ParameterDeclaration pd : getPm().getParameters()) { + for (VariableSpecification vs : pd.getVariables()) { + this.paramVars.add((LocationVariable) vs.getProgramVariable()); + varsForCondition = + varsForCondition.append((ProgramVariable) vs.getProgramVariable()); + } + } + // Collect local variables + StatementBlock result = getStatementBlock(getPm().getBody()); + ProgramVariableCollector variableCollector = + new ProgramVariableCollector(result, getProof().getServices()); + variableCollector.start(); + Set undeclaredVariables = variableCollector.result(); + for (LocationVariable x : undeclaredVariables) { + varsForCondition = saveAddVariable(x, varsForCondition); } - } - } - } - - - /** - * Modifies toKeep and variableNamingMap to hold the correct parameters after execution of the given ruleApp on the given node - * @param ruleApp the applied rule app - * @param nodethe current node - */ - protected void refreshVarMaps(RuleApp ruleApp, Node node) { - boolean inScope = isInScope(node); - // collect old values - Map oldMap = getOldMap(); - // put values into map which have to be replaced - for (ProgramVariable varForCondition : getVarsForCondition()) { - // put global variables only done when a variable is instantiated by - // KeY for the first time - putValuesFromGlobalVars(varForCondition, node, inScope); - // put renamings into map and tokeep remove no longer need vars from - // tokeep - putValuesFromRenamings(varForCondition, node, isInScopeForCondition(node), oldMap, ruleApp); - } - freeVariablesAfterReturn(node, ruleApp, inScope); - } - - /** - * Computes the Term that can be evaluated, from the user given condition - * @param condition the condition given by the user - * @return the {@link Term} that represents the condition - */ - private Term computeTermForCondition(String condition) { - if(condition==null){ - return getProof().getServices().getTermBuilder().tt(); - } - //collect all variables needed to parse the condition - setSelfVar(new LocationVariable(new ProgramElementName(getProof().getServices().getTermBuilder().newName("self")), containerType, null, false, false)); - ImmutableList varsForCondition = ImmutableSLList.nil(); - if(getPm()!=null){ - //collect parameter variables - for (ParameterDeclaration pd : getPm().getParameters()) { - for (VariableSpecification vs : pd.getVariables()) { - this.paramVars.add((LocationVariable) vs.getProgramVariable()); - varsForCondition = varsForCondition.append((ProgramVariable) vs.getProgramVariable()); + } + JavaInfo info = getProof().getServices().getJavaInfo(); + ImmutableList kjts = info.getAllSupertypes(containerType); + ImmutableList globalVars = ImmutableSLList.nil(); + for (KeYJavaType kjtloc : kjts) { + if (kjtloc.getJavaType() instanceof TypeDeclaration) { + ImmutableList fields = + info.getAllFields((TypeDeclaration) kjtloc.getJavaType()); + for (Field field : fields) { + if ((kjtloc.equals(containerType) || !field.isPrivate()) + && !((LocationVariable) field.getProgramVariable()).isImplicit()) + globalVars = + globalVars.append((ProgramVariable) field.getProgramVariable()); + } } - } - // Collect local variables - StatementBlock result = getStatementBlock(getPm().getBody()); - ProgramVariableCollector variableCollector = new ProgramVariableCollector(result, getProof().getServices()); - variableCollector.start(); - Set undeclaredVariables = variableCollector.result(); - for (LocationVariable x : undeclaredVariables) { - varsForCondition = saveAddVariable(x, varsForCondition); - } - } - JavaInfo info = getProof().getServices().getJavaInfo(); - ImmutableList kjts = info.getAllSupertypes(containerType); - ImmutableList globalVars = ImmutableSLList.nil(); - for(KeYJavaType kjtloc: kjts){ - if (kjtloc.getJavaType() instanceof TypeDeclaration) { - ImmutableList fields = info.getAllFields((TypeDeclaration)kjtloc.getJavaType()); - for(Field field : fields){ - if((kjtloc.equals(containerType)||!field.isPrivate())&&!((LocationVariable) field.getProgramVariable()).isImplicit()) - globalVars = globalVars.append((ProgramVariable) field.getProgramVariable()); + } + varsForCondition = varsForCondition.append(globalVars); + this.setVarsForCondition(varsForCondition); + // parse string + PositionedString ps = new PositionedString(condition); + + JmlIO io = new JmlIO().services(getProof().getServices()).classType(containerType) + .selfVar(getSelfVar()).parameters(varsForCondition); + + return io.parseExpression(ps); + } + + /** + * Checks if the condition, that was given by the user, evaluates to true with the current of + * the proof + * + * @param ruleApp the {@link RuleApp} to be executed next + * @param proof the current {@link Proof} + * @param node the current {@link Node} + * @return true if the condition evaluates to true + */ + protected boolean conditionMet(RuleApp ruleApp, Proof proof, Node node) { + ApplyStrategyInfo info = null; + try { + // initialize values + PosInOccurrence pio = ruleApp.posInOccurrence(); + Term term = pio.subTerm(); + getProof().getServices().getTermBuilder(); + term = TermBuilder.goBelowUpdates(term); + IExecutionContext ec = + JavaTools.getInnermostExecutionContext(term.javaBlock(), proof.getServices()); + // put values into map which have to be replaced + if (ec != null) { + getVariableNamingMap().put(getSelfVar(), ec.getRuntimeInstance()); + } + // replace renamings etc. + OpReplacer replacer = new OpReplacer(getVariableNamingMap(), + getProof().getServices().getTermFactory()); + Term termForSideProof = replacer.replace(condition); + // start side proof + Term toProof = getProof().getServices().getTermBuilder() + .equals(getProof().getServices().getTermBuilder().tt(), termForSideProof); + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), false); // New + // OneStepSimplifier + // is + // required + // because it + // has an + // internal + // state and + // the + // default + // instance + // can't be + // used + // parallel. + Sequent sequent = + SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, pio, toProof); + info = SymbolicExecutionSideProofUtil.startSideProof(proof, sideProofEnv, sequent, + StrategyProperties.METHOD_CONTRACT, StrategyProperties.LOOP_INVARIANT, + StrategyProperties.QUERY_ON, StrategyProperties.SPLITTING_DELAYED); + return info.getProof().closed(); + } catch (ProofInputException e) { + return false; + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "Breakpoint condition computation on node " + node.serialNr() + ".", info); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + return (!conditionEnabled || conditionMet(ruleApp, proof, node)) + && super.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + + /** + * For a given {@link StatementContainer} this method computes the {@link StatementBlock} that + * contains all lines before the line the Breakpoint is at, including the line itself. + * + * @param statementContainer the {@link StatementContainer} to build the block from + * @return the {@link StatementBlock} representing the container without the line below the + * Breakpoint + */ + protected abstract StatementBlock getStatementBlock(StatementContainer statementContainer); + + /** + * Checks if the statement of a given {@link Node} is in the scope of this breakpoint. + * + * @param node the {@link Node} to be checked + * @return true if the node represents a statement in the scope of this breakpoint. + */ + protected abstract boolean isInScope(Node node); + + /** + * Checks if the statement of a given {@link Node} is in the scope of this breakpoint. + * + * @param node the {@link Node} to be checked + * @return true if the node represents a statement in the scope of this breakpoint. + */ + protected abstract boolean isInScopeForCondition(Node node); + + private ImmutableList saveAddVariable(LocationVariable x, + ImmutableList varsForCondition) { + boolean contains = false; + for (ProgramVariable paramVar : varsForCondition) { + if (paramVar.toString().equals(x.toString())) { + contains = true; + break; } - } - } - varsForCondition = varsForCondition.append(globalVars); - this.setVarsForCondition(varsForCondition); - //parse string - PositionedString ps = new PositionedString(condition); - - JmlIO io = new JmlIO() - .services(getProof().getServices()) - .classType(containerType) - .selfVar(getSelfVar()) - .parameters(varsForCondition); - - return io.parseExpression(ps); - } - - /** - * Checks if the condition, that was given by the user, evaluates to true with the current of the proof - * @param ruleApp the {@link RuleApp} to be executed next - * @param proof the current {@link Proof} - * @param node the current {@link Node} - * @return true if the condition evaluates to true - */ - protected boolean conditionMet(RuleApp ruleApp, Proof proof, Node node) { - ApplyStrategyInfo info = null; - try { - //initialize values - PosInOccurrence pio = ruleApp.posInOccurrence(); - Term term = pio.subTerm(); - getProof().getServices().getTermBuilder(); - term = TermBuilder.goBelowUpdates(term); - IExecutionContext ec = JavaTools.getInnermostExecutionContext(term.javaBlock(), proof.getServices()); - //put values into map which have to be replaced - if(ec!=null){ - getVariableNamingMap().put(getSelfVar(), ec.getRuntimeInstance()); - } - //replace renamings etc. - OpReplacer replacer = new OpReplacer(getVariableNamingMap(), getProof().getServices().getTermFactory()); - Term termForSideProof = replacer.replace(condition); - //start side proof - Term toProof = getProof().getServices().getTermBuilder().equals(getProof().getServices().getTermBuilder().tt(), termForSideProof); - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), false); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, pio, toProof); - info = SymbolicExecutionSideProofUtil.startSideProof(proof, - sideProofEnv, - sequent, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_DELAYED); - return info.getProof().closed(); - } - catch (ProofInputException e) { - return false; - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Breakpoint condition computation on node " + node.serialNr() + ".", info); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - return (!conditionEnabled || conditionMet(ruleApp, proof, node)) && - super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - - /** - * For a given {@link StatementContainer} this method computes the {@link StatementBlock} that contains all lines before the line the Breakpoint is at, including the line itself. - * - * @param statementContainer the {@link StatementContainer} to build the block from - * @return the {@link StatementBlock} representing the container without the line below the Breakpoint - */ - protected abstract StatementBlock getStatementBlock(StatementContainer statementContainer); - - /** - * Checks if the statement of a given {@link Node} is in the scope of this breakpoint. - * - * @param node the {@link Node} to be checked - * @return true if the node represents a statement in the scope of this breakpoint. - */ - protected abstract boolean isInScope(Node node); - - /** - * Checks if the statement of a given {@link Node} is in the scope of this breakpoint. - * - * @param node the {@link Node} to be checked - * @return true if the node represents a statement in the scope of this breakpoint. - */ - protected abstract boolean isInScopeForCondition(Node node); - - private ImmutableList saveAddVariable(LocationVariable x, ImmutableList varsForCondition) { - boolean contains = false; - for(ProgramVariable paramVar : varsForCondition){ - if(paramVar.toString().equals(x.toString())){ - contains = true; - break; - } - } - if(!contains&&!x.isMember()){ - varsForCondition = varsForCondition.append(x); - } - return varsForCondition; - } - - /** - * Sets the new conditionEnabled value. - * @param conditionEnabled the new value - */ - public void setConditionEnabled(boolean conditionEnabled) { - this.conditionEnabled = conditionEnabled; - } - - /** - * Returns the condition of the associated Breakpoint. - * @return the condition of the associated Breakpoint - */ - public Term getCondition() { - return condition; - } - - /** - * Checks if the condition for the associated Breakpoint is enabled. - * @param conditionEnabled true if the condition for the associated Breakpoint is enabled - */ - public boolean isConditionEnabled() { - return conditionEnabled; - } - - /** - * Sets the condition to the Term that is parsed from the given String. - * @param condition the String to be parsed - * @throws SLTranslationException if the parsing failed - */ - public void setCondition(String condition) throws SLTranslationException { - this.conditionString = condition; - this.condition = conditionEnabled? computeTermForCondition(condition) : getProof().getServices().getTermBuilder().tt(); - } - - /** - * Returns the condition represented as a String. - * @return the condition represented as a String - */ - public String getConditionString() { - return conditionString; - } - - /** - * Returns the variables KeY should keep to evaluate the condition. - * @return the variables KeY should keep to evaluate the condition - */ - public Set getToKeep() { - return toKeep; - } - - /** - * @return the variableNamingMap - */ - public Map getVariableNamingMap() { - return variableNamingMap; - } - - /** - * @param variableNamingMap the variableNamingMap to set - */ - public void setVariableNamingMap(Map variableNamingMap) { - this.variableNamingMap = variableNamingMap; - } - - /** - * @return the selfVar - */ - public ProgramVariable getSelfVar() { - return selfVar; - } - - /** - * @param selfVar the selfVar to set - */ - public void setSelfVar(ProgramVariable selfVar) { - this.selfVar = selfVar; - } - - /** - * @return the varsForCondition - */ - public ImmutableList getVarsForCondition() { - return varsForCondition; - } - - /** - * @param varsForCondition the varsForCondition to set - */ - public void setVarsForCondition(ImmutableList varsForCondition) { - this.varsForCondition = varsForCondition; - } - - /** - * @return the pm - */ - public IProgramMethod getPm() { - return pm; - } - - /** - * @param pm the pm to set - */ - public void setPm(IProgramMethod pm) { - this.pm = pm; - } -} \ No newline at end of file + } + if (!contains && !x.isMember()) { + varsForCondition = varsForCondition.append(x); + } + return varsForCondition; + } + + /** + * Sets the new conditionEnabled value. + * + * @param conditionEnabled the new value + */ + public void setConditionEnabled(boolean conditionEnabled) { + this.conditionEnabled = conditionEnabled; + } + + /** + * Returns the condition of the associated Breakpoint. + * + * @return the condition of the associated Breakpoint + */ + public Term getCondition() { + return condition; + } + + /** + * Checks if the condition for the associated Breakpoint is enabled. + * + * @param conditionEnabled true if the condition for the associated Breakpoint is enabled + */ + public boolean isConditionEnabled() { + return conditionEnabled; + } + + /** + * Sets the condition to the Term that is parsed from the given String. + * + * @param condition the String to be parsed + * @throws SLTranslationException if the parsing failed + */ + public void setCondition(String condition) throws SLTranslationException { + this.conditionString = condition; + this.condition = conditionEnabled ? computeTermForCondition(condition) + : getProof().getServices().getTermBuilder().tt(); + } + + /** + * Returns the condition represented as a String. + * + * @return the condition represented as a String + */ + public String getConditionString() { + return conditionString; + } + + /** + * Returns the variables KeY should keep to evaluate the condition. + * + * @return the variables KeY should keep to evaluate the condition + */ + public Set getToKeep() { + return toKeep; + } + + /** + * @return the variableNamingMap + */ + public Map getVariableNamingMap() { + return variableNamingMap; + } + + /** + * @param variableNamingMap the variableNamingMap to set + */ + public void setVariableNamingMap(Map variableNamingMap) { + this.variableNamingMap = variableNamingMap; + } + + /** + * @return the selfVar + */ + public ProgramVariable getSelfVar() { + return selfVar; + } + + /** + * @param selfVar the selfVar to set + */ + public void setSelfVar(ProgramVariable selfVar) { + this.selfVar = selfVar; + } + + /** + * @return the varsForCondition + */ + public ImmutableList getVarsForCondition() { + return varsForCondition; + } + + /** + * @param varsForCondition the varsForCondition to set + */ + public void setVarsForCondition(ImmutableList varsForCondition) { + this.varsForCondition = varsForCondition; + } + + /** + * @return the pm + */ + public IProgramMethod getPm() { + return pm; + } + + /** + * @param pm the pm to set + */ + public void setPm(IProgramMethod pm) { + this.pm = pm; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractHitCountBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractHitCountBreakpoint.java index 43d79d49981..a91be5ac2b3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractHitCountBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/AbstractHitCountBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import java.util.HashMap; @@ -10,89 +13,92 @@ /** * Adds the hit count functionality to an {@link AbstractBreakpoint}. + * * @author Martin Hentschel */ public abstract class AbstractHitCountBreakpoint extends AbstractBreakpoint { - /** - * The HitCount of the Breakpoint (set by user). - */ - private int hitCount; - - /** - * Counter for how often the Breakpoint was hit. - */ - private int hitted = 0; + /** + * The HitCount of the Breakpoint (set by user). + */ + private int hitCount; - /** - * Map to save the nodes that already have been reached, so nodes are not counted twice for the hitcount - */ - private final Map hittedNodes = new HashMap(); + /** + * Counter for how often the Breakpoint was hit. + */ + private int hitted = 0; - /** - * Creates a new {@link AbstractHitCountBreakpoint}. - * - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param proof the {@link Proof} that will be executed and should stop - * @param enabled flag if the Breakpoint is enabled - */ - public AbstractHitCountBreakpoint(int hitCount, Proof proof, boolean enabled){ - super(proof, enabled); - this.hitCount = hitCount; - } - - /** - * Checks if the Hitcount is exceeded for the given {@link JavaLineBreakpoint}. - * If the Hitcount is not exceeded the hitted counter is incremented, otherwise its set to 0. - * - * @return true if the Hitcount is exceeded or the {@link JavaLineBreakpoint} has no Hitcount. - */ - protected boolean hitcountExceeded(Node node){ - if (!(hitCount == -1)) { - if(!hittedNodes.containsKey(node.serialNr())){ - if (hitCount == hitted + 1) { - hitted=0; - hittedNodes.put(node.serialNr(), Boolean.TRUE); - return true; - } - else { - hittedNodes.put(node.serialNr(), Boolean.FALSE); - hitted++; + /** + * Map to save the nodes that already have been reached, so nodes are not counted twice for the + * hitcount + */ + private final Map hittedNodes = new HashMap(); + + /** + * Creates a new {@link AbstractHitCountBreakpoint}. + * + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param proof the {@link Proof} that will be executed and should stop + * @param enabled flag if the Breakpoint is enabled + */ + public AbstractHitCountBreakpoint(int hitCount, Proof proof, boolean enabled) { + super(proof, enabled); + this.hitCount = hitCount; + } + + /** + * Checks if the Hitcount is exceeded for the given {@link JavaLineBreakpoint}. If the Hitcount + * is not exceeded the hitted counter is incremented, otherwise its set to 0. + * + * @return true if the Hitcount is exceeded or the {@link JavaLineBreakpoint} has no Hitcount. + */ + protected boolean hitcountExceeded(Node node) { + if (!(hitCount == -1)) { + if (!hittedNodes.containsKey(node.serialNr())) { + if (hitCount == hitted + 1) { + hitted = 0; + hittedNodes.put(node.serialNr(), Boolean.TRUE); + return true; + } else { + hittedNodes.put(node.serialNr(), Boolean.FALSE); + hitted++; + } + } else { + return hittedNodes.get(node.serialNr()); } - }else { - return hittedNodes.get(node.serialNr()); - } - } - else { - return true; - } - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - return hitcountExceeded(node); - } + } else { + return true; + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + return hitcountExceeded(node); + } + + /** + * Returns the hitCount of the associated Breakpoint. + * + * @return the hitCount of the associated Breakpoint + */ + public int getHitCount() { + return hitCount; + } - /** - * Returns the hitCount of the associated Breakpoint. - * @return the hitCount of the associated Breakpoint - */ - public int getHitCount() { - return hitCount; - } - - /** - * Set the hitCount to the new value - * @param hitCount the new value - */ - public void setHitCount(int hitCount) { - if (this.hitCount != hitCount) { - this.hitCount = hitCount; - this.hitted = 0; - hittedNodes.clear(); - } - } -} \ No newline at end of file + /** + * Set the hitCount to the new value + * + * @param hitCount the new value + */ + public void setHitCount(int hitCount) { + if (this.hitCount != hitCount) { + this.hitCount = hitCount; + this.hitted = 0; + hittedNodes.clear(); + } + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/ExceptionBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/ExceptionBreakpoint.java index c3e5c9c0916..26b8ca5da52 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/ExceptionBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/ExceptionBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import java.util.HashSet; @@ -16,153 +19,157 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * This{@link ExceptionBreakpoint} represents an exception breakpoint and is responsible to tell the debugger to stop execution when the respective - * breakpoint is hit. - * + * This{@link ExceptionBreakpoint} represents an exception breakpoint and is responsible to tell the + * debugger to stop execution when the respective breakpoint is hit. + * * @author Marco Drebing */ public class ExceptionBreakpoint extends AbstractHitCountBreakpoint { - /** - * The exception to watch for - */ - private String exceptionName; - - /** - * a list of nodes of the Symbolic Execution Tree whose children represent exceptions - */ - private Set exceptionParentNodes; - - /** - * a flag whether to watch for an uncaught exception - */ - private boolean caught; - - /** - * a flag whether to suspend on subclasses of the exception aswell - */ - private boolean suspendOnSubclasses; - - /** - * a flag to tell whether to stop at uncaught exceptions or not - */ - private boolean uncaught; - - /** - * Creates a new {@link AbstractHitCountBreakpoint}. - * - * @param proof the {@link Proof} that will be executed and should stop - * @param exceptionName the name of the exception to watch for - * @param caught flag to tell if caught exceptions lead to a stop - * @param uncaught flag to tell if uncaught exceptions lead to a stop - * @param suspendOnSubclasses flag to tell if the execution should suspend on subclasses of the exception aswell - * @param enabled flag if the Breakpoint is enabled - * @param hitCount the number of hits after which the execution should hold at this breakpoint - */ - public ExceptionBreakpoint(Proof proof, String exceptionName, boolean caught, boolean uncaught, boolean suspendOnSubclasses, boolean enabled, int hitCount){ - super(hitCount, proof, enabled); - this.exceptionName = exceptionName; - exceptionParentNodes = new HashSet(); - this.caught=caught; - this.uncaught=uncaught; - this.suspendOnSubclasses=suspendOnSubclasses; - } - - /** - * Checks if the given node is a parent of the other given node. - * @param node The {@link Node} to start search in. - * @param node The {@link Node} that is thought to be the parent. - * @return true if the parent node is one of the nodes parents - */ - public boolean isParentNode(Node node, Node parent) { - if (node != null) { - Node parentIter = node.parent(); - boolean result = false; - while (parentIter != null && !result) { - if (parentIter.equals(parent)) { - result = true; - } - else { - parentIter = parentIter.parent(); + /** + * The exception to watch for + */ + private String exceptionName; + + /** + * a list of nodes of the Symbolic Execution Tree whose children represent exceptions + */ + private Set exceptionParentNodes; + + /** + * a flag whether to watch for an uncaught exception + */ + private boolean caught; + + /** + * a flag whether to suspend on subclasses of the exception aswell + */ + private boolean suspendOnSubclasses; + + /** + * a flag to tell whether to stop at uncaught exceptions or not + */ + private boolean uncaught; + + /** + * Creates a new {@link AbstractHitCountBreakpoint}. + * + * @param proof the {@link Proof} that will be executed and should stop + * @param exceptionName the name of the exception to watch for + * @param caught flag to tell if caught exceptions lead to a stop + * @param uncaught flag to tell if uncaught exceptions lead to a stop + * @param suspendOnSubclasses flag to tell if the execution should suspend on subclasses of the + * exception aswell + * @param enabled flag if the Breakpoint is enabled + * @param hitCount the number of hits after which the execution should hold at this breakpoint + */ + public ExceptionBreakpoint(Proof proof, String exceptionName, boolean caught, boolean uncaught, + boolean suspendOnSubclasses, boolean enabled, int hitCount) { + super(hitCount, proof, enabled); + this.exceptionName = exceptionName; + exceptionParentNodes = new HashSet(); + this.caught = caught; + this.uncaught = uncaught; + this.suspendOnSubclasses = suspendOnSubclasses; + } + + /** + * Checks if the given node is a parent of the other given node. + * + * @param node The {@link Node} to start search in. + * @param node The {@link Node} that is thought to be the parent. + * @return true if the parent node is one of the nodes parents + */ + public boolean isParentNode(Node node, Node parent) { + if (node != null) { + Node parentIter = node.parent(); + boolean result = false; + while (parentIter != null && !result) { + if (parentIter.equals(parent)) { + result = true; + } else { + parentIter = parentIter.parent(); + } } - } - return result; - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - Node SETParent = SymbolicExecutionUtil.findParentSetNode(node); - if(activeStatement!=null&&activeStatement instanceof Throw&&isEnabled()){ - Throw throwStatement = (Throw)activeStatement; - for(int i = 0; i kjts = info.getAllSupertypes(kjt); - for(KeYJavaType kjtloc: kjts){ - if(kjtloc.getSort().toString().equals(exceptionName)&&!exceptionParentNodes.contains(SETParent)){ + return result; + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + Node SETParent = SymbolicExecutionUtil.findParentSetNode(node); + if (activeStatement != null && activeStatement instanceof Throw && isEnabled()) { + Throw throwStatement = (Throw) activeStatement; + for (int i = 0; i < throwStatement.getChildCount(); i++) { + SourceElement childElement = throwStatement.getChildAt(i); + if (childElement instanceof LocationVariable) { + LocationVariable locVar = (LocationVariable) childElement; + if (locVar.getKeYJavaType().getSort().toString().equals(exceptionName) + && !exceptionParentNodes.contains(SETParent)) { exceptionParentNodes.add(SETParent); return true; - } - } - } + } else if (suspendOnSubclasses) { + JavaInfo info = proof.getServices().getJavaInfo(); + KeYJavaType kjt = locVar.getKeYJavaType(); + ImmutableList kjts = info.getAllSupertypes(kjt); + for (KeYJavaType kjtloc : kjts) { + if (kjtloc.getSort().toString().equals(exceptionName) + && !exceptionParentNodes.contains(SETParent)) { + exceptionParentNodes.add(SETParent); + return true; + } + } + } + } } - } - } - return false; - } - - /** - * @return the isCaught - */ - public boolean isCaught() { - return caught; - } - - /** - * @param isCaught the isCaught to set - */ - public void setCaught(boolean isCaught) { - this.caught = isCaught; - } - - /** - * @return the isUncaught - */ - public boolean isUncaught() { - return uncaught; - } - - /** - * @param isUncaught the isUncaught to set - */ - public void setUncaught(boolean isUncaught) { - this.uncaught = isUncaught; - } - - /** - * @return the suspendOnSubclasses - */ - public boolean isSuspendOnSubclasses() { - return suspendOnSubclasses; - } - - /** - * @param suspendOnSubclasses the suspendOnSubclasses to set - */ - public void setSuspendOnSubclasses(boolean suspendOnSubclasses) { - this.suspendOnSubclasses = suspendOnSubclasses; - } -} \ No newline at end of file + } + return false; + } + + /** + * @return the isCaught + */ + public boolean isCaught() { + return caught; + } + + /** + * @param isCaught the isCaught to set + */ + public void setCaught(boolean isCaught) { + this.caught = isCaught; + } + + /** + * @return the isUncaught + */ + public boolean isUncaught() { + return uncaught; + } + + /** + * @param isUncaught the isUncaught to set + */ + public void setUncaught(boolean isUncaught) { + this.uncaught = isUncaught; + } + + /** + * @return the suspendOnSubclasses + */ + public boolean isSuspendOnSubclasses() { + return suspendOnSubclasses; + } + + /** + * @param suspendOnSubclasses the suspendOnSubclasses to set + */ + public void setSuspendOnSubclasses(boolean suspendOnSubclasses) { + this.suspendOnSubclasses = suspendOnSubclasses; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/FieldWatchpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/FieldWatchpoint.java index 9e56c6d2c17..7972337ed8c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/FieldWatchpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/FieldWatchpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import de.uka.ilkd.key.java.NonTerminalProgramElement; @@ -14,128 +17,128 @@ import de.uka.ilkd.key.rule.RuleApp; /** - * This{@link FieldWatchpoint} represents a Java watchpoint and is responsible to tell the debugger to stop execution when the respective - * variable is accessed or modified. - * + * This{@link FieldWatchpoint} represents a Java watchpoint and is responsible to tell the debugger + * to stop execution when the respective variable is accessed or modified. + * * @author Marco Drebing */ public class FieldWatchpoint extends AbstractHitCountBreakpoint { - private boolean isAccess; + private boolean isAccess; - private boolean isModification; + private boolean isModification; - private String fullFieldName; + private String fullFieldName; - /** - * Creates a new {@link FieldWatchpoint}. - * - * @param enabled flag if the Breakpoint is enabled - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param fieldName the field to watch - * @param isAcces flag to watch for accesses - * @param isModification flag to watch for modifications - * @param containerType the type of the element containing the breakpoint - * @param proof the {@link Proof} that will be executed and should stop - */ - public FieldWatchpoint(boolean enabled, int hitCount, String fieldName, boolean isAcces, boolean isModification, KeYJavaType containerKJT, Proof proof) { - super(hitCount, proof, enabled); - this.isAccess = isAcces; - this.isModification = isModification; - this.fullFieldName = containerKJT.getSort().toString()+"::"+fieldName; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - if (activeStatement != null && activeStatement instanceof Assignment) { - Assignment assignment = (Assignment) activeStatement; - SourceElement firstElement = assignment.getChildAt(0); - if(firstElement instanceof FieldReference){ - PosInOccurrence pio = ruleApp.posInOccurrence(); - Term term = pio.subTerm(); - getProof().getServices().getTermBuilder(); - term = TermBuilder.goBelowUpdates(term); - if(((FieldReference) firstElement).getProgramVariable().name().toString().equals(fullFieldName)&&isModification&&hitcountExceeded(node)){ - return super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - } - if(checkChildrenOfSourceElement(assignment)&&hitcountExceeded(node)){ - return super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - }else if (activeStatement != null) { - if(checkChildrenOfSourceElement(activeStatement)&&hitcountExceeded(node)){ - return super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - } - return false; - } + /** + * Creates a new {@link FieldWatchpoint}. + * + * @param enabled flag if the Breakpoint is enabled + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param fieldName the field to watch + * @param isAcces flag to watch for accesses + * @param isModification flag to watch for modifications + * @param containerType the type of the element containing the breakpoint + * @param proof the {@link Proof} that will be executed and should stop + */ + public FieldWatchpoint(boolean enabled, int hitCount, String fieldName, boolean isAcces, + boolean isModification, KeYJavaType containerKJT, Proof proof) { + super(hitCount, proof, enabled); + this.isAccess = isAcces; + this.isModification = isModification; + this.fullFieldName = containerKJT.getSort().toString() + "::" + fieldName; + } - private boolean checkChildrenOfSourceElement(SourceElement sourceElement) { - boolean found = false; - if (sourceElement instanceof Assignment) { - Assignment assignment = (Assignment) sourceElement; - for (int i = 1; i < assignment.getChildCount(); i++) { - SourceElement childElement = assignment.getChildAt(i); - if (childElement instanceof FieldReference - && ((FieldReference) childElement).getProgramVariable().name().toString().equals(fullFieldName)) { - FieldReference field = (FieldReference) childElement; - ProgramVariable progVar = field.getProgramVariable(); - if (fullFieldName.equals(progVar.toString())) { - return isAccess; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + if (activeStatement != null && activeStatement instanceof Assignment) { + Assignment assignment = (Assignment) activeStatement; + SourceElement firstElement = assignment.getChildAt(0); + if (firstElement instanceof FieldReference) { + PosInOccurrence pio = ruleApp.posInOccurrence(); + Term term = pio.subTerm(); + getProof().getServices().getTermBuilder(); + term = TermBuilder.goBelowUpdates(term); + if (((FieldReference) firstElement).getProgramVariable().name().toString() + .equals(fullFieldName) && isModification && hitcountExceeded(node)) { + return super.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + } + if (checkChildrenOfSourceElement(assignment) && hitcountExceeded(node)) { + return super.isBreakpointHit(activeStatement, ruleApp, proof, node); } - else if (childElement instanceof NonTerminalProgramElement) { - found = found || checkChildrenOfSourceElement(childElement); + } else if (activeStatement != null) { + if (checkChildrenOfSourceElement(activeStatement) && hitcountExceeded(node)) { + return super.isBreakpointHit(activeStatement, ruleApp, proof, node); } - } - } - else if (sourceElement instanceof NonTerminalProgramElement) { - NonTerminalProgramElement programElement = (NonTerminalProgramElement) sourceElement; - for (int i = 0; i < programElement.getChildCount(); i++) { - SourceElement childElement = programElement.getChildAt(i); - if (childElement instanceof FieldReference - && ((FieldReference) childElement).getProgramVariable().name().toString().equals(fullFieldName)) { - FieldReference field = (FieldReference) childElement; - ProgramVariable progVar = field.getProgramVariable(); - if (fullFieldName.equals(progVar.toString())) { - return isAccess; - } + } + return false; + } + + private boolean checkChildrenOfSourceElement(SourceElement sourceElement) { + boolean found = false; + if (sourceElement instanceof Assignment) { + Assignment assignment = (Assignment) sourceElement; + for (int i = 1; i < assignment.getChildCount(); i++) { + SourceElement childElement = assignment.getChildAt(i); + if (childElement instanceof FieldReference && ((FieldReference) childElement) + .getProgramVariable().name().toString().equals(fullFieldName)) { + FieldReference field = (FieldReference) childElement; + ProgramVariable progVar = field.getProgramVariable(); + if (fullFieldName.equals(progVar.toString())) { + return isAccess; + } + } else if (childElement instanceof NonTerminalProgramElement) { + found = found || checkChildrenOfSourceElement(childElement); + } } - else if (childElement instanceof NonTerminalProgramElement) { - found = found || checkChildrenOfSourceElement(childElement); + } else if (sourceElement instanceof NonTerminalProgramElement) { + NonTerminalProgramElement programElement = (NonTerminalProgramElement) sourceElement; + for (int i = 0; i < programElement.getChildCount(); i++) { + SourceElement childElement = programElement.getChildAt(i); + if (childElement instanceof FieldReference && ((FieldReference) childElement) + .getProgramVariable().name().toString().equals(fullFieldName)) { + FieldReference field = (FieldReference) childElement; + ProgramVariable progVar = field.getProgramVariable(); + if (fullFieldName.equals(progVar.toString())) { + return isAccess; + } + } else if (childElement instanceof NonTerminalProgramElement) { + found = found || checkChildrenOfSourceElement(childElement); + } } - } - } - return found; - } - - /** - * @return the isAccess - */ - public boolean isAccess() { - return isAccess; - } + } + return found; + } + + /** + * @return the isAccess + */ + public boolean isAccess() { + return isAccess; + } - /** - * @param isAccess the isAccess to set - */ - public void setAccess(boolean isAccess) { - this.isAccess = isAccess; - } + /** + * @param isAccess the isAccess to set + */ + public void setAccess(boolean isAccess) { + this.isAccess = isAccess; + } - /** - * @return the isModification - */ - public boolean isModification() { - return isModification; - } + /** + * @return the isModification + */ + public boolean isModification() { + return isModification; + } - /** - * @param isModification the isModification to set - */ - public void setModification(boolean isModification) { - this.isModification = isModification; - } -} \ No newline at end of file + /** + * @param isModification the isModification to set + */ + public void setModification(boolean isModification) { + this.isModification = isModification; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/IBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/IBreakpoint.java index a18b47ed5af..80d660e7c70 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/IBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/IBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import de.uka.ilkd.key.java.SourceElement; @@ -10,44 +13,45 @@ /** * Defines the basic functionality of a breakpoint. + * * @author Martin Hentschel */ public interface IBreakpoint { - /** - * Checks if the Breakpoint is enabled. - * @return true if Breakpoint is enabled - */ - public boolean isEnabled(); - - /** - * This method is called from - * {@link StopCondition#isGoalAllowed(int, long, Proof, long, int, Goal)} - * and can be used to update the state of the {@link IBreakpoint}. - * @param maxApplications The defined maximal number of rules to apply. Can be different to {@link StrategySettings#getMaxSteps()} in side proofs. - * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to {@link StrategySettings#getTimeout()} in side proofs. - * @param proof The current {@link Proof}. - * @param startTime The timestamp when the apply strategy has started, computed via {@link System#currentTimeMillis()} - * @param countApplied The number of already applied rules. - * @param goal The current {@link Goal} on which the next rule will be applied. - */ - public void updateState(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal); - - /** - * Determines if the breakpoint represented by this BreakpointStopConition is triggered. - * Override this method in order to suspend execution when a breakpoint is hit. - * @param activeStatement the activeStatement of the node - * @param ruleApp the applied {@link RuleApp} - * @param proof the current proof - * @param node the current node - * @return true if execution should hold - */ - public boolean isBreakpointHit(SourceElement activeStatement, - RuleApp ruleApp, - Proof proof, - Node node); -} \ No newline at end of file + /** + * Checks if the Breakpoint is enabled. + * + * @return true if Breakpoint is enabled + */ + public boolean isEnabled(); + + /** + * This method is called from + * {@link StopCondition#isGoalAllowed(int, long, Proof, long, int, Goal)} and can be used to + * update the state of the {@link IBreakpoint}. + * + * @param maxApplications The defined maximal number of rules to apply. Can be different to + * {@link StrategySettings#getMaxSteps()} in side proofs. + * @param timeout The defined timeout in ms or {@code -1} if disabled. Can be different to + * {@link StrategySettings#getTimeout()} in side proofs. + * @param proof The current {@link Proof}. + * @param startTime The timestamp when the apply strategy has started, computed via + * {@link System#currentTimeMillis()} + * @param countApplied The number of already applied rules. + * @param goal The current {@link Goal} on which the next rule will be applied. + */ + public void updateState(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal); + + /** + * Determines if the breakpoint represented by this BreakpointStopConition is triggered. + * Override this method in order to suspend execution when a breakpoint is hit. + * + * @param activeStatement the activeStatement of the node + * @param ruleApp the applied {@link RuleApp} + * @param proof the current proof + * @param node the current node + * @return true if execution should hold + */ + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node); +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/KeYWatchpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/KeYWatchpoint.java index 46b5a9e1c55..84f7d337bc6 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/KeYWatchpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/KeYWatchpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import de.uka.ilkd.key.java.JavaTools; @@ -26,107 +29,129 @@ /** - * This{@link KeYWatchpoint} represents a KeY watchpoint and is responsible to tell the debugger to stop execution when the respective - * watchpoint evaluates its condition to true. - * + * This{@link KeYWatchpoint} represents a KeY watchpoint and is responsible to tell the debugger to + * stop execution when the respective watchpoint evaluates its condition to true. + * * @author Marco Drebing */ -public class KeYWatchpoint extends AbstractConditionalBreakpoint{ - /** - * a flag to tell whether the condition should evaluate to true or just be satisfiable - */ - private boolean suspendOnTrue; +public class KeYWatchpoint extends AbstractConditionalBreakpoint { + /** + * a flag to tell whether the condition should evaluate to true or just be satisfiable + */ + private boolean suspendOnTrue; - /** - * Creates a new {@link AbstractConditionalBreakpoint}. Call setCondition immediately after calling the constructor! - * - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located at - * @param proof the {@link Proof} that will be executed and should stop - * @param condition the condition as given by the user - * @param enabled flag if the Breakpoint is enabled - * @param conditionEnabled flag if the condition is enabled - * @param containerType the type of the element containing the breakpoint - * @param suspendOnTrue the flag if the condition needs to evaluate to true or just be satisfiable - * @throws SLTranslationException if the condition could not be parsed to a valid Term - */ - public KeYWatchpoint(int hitCount, Proof proof, String condition, boolean enabled, boolean conditionEnabled, KeYJavaType containerType, boolean suspendOnTrue) throws SLTranslationException { - super(hitCount, null, proof, enabled, conditionEnabled, -1, -1, containerType); - setSuspendOnTrue(suspendOnTrue); - this.setCondition(condition); - } - - @Override - protected StatementBlock getStatementBlock( - StatementContainer statementContainer) { - return (StatementBlock) statementContainer; - } - - @Override - protected boolean isInScope(Node node) { - return true; - } - - @Override - protected boolean isInScopeForCondition(Node node) { - return true; - } - - @Override - protected boolean conditionMet(RuleApp ruleApp, Proof proof, Node node) { - if(suspendOnTrue){ - return super.conditionMet(ruleApp, proof, node); - }else{ - ApplyStrategyInfo info = null; - try { - Term negatedCondition = getProof().getServices().getTermBuilder().not(getCondition()); - //initialize values - PosInOccurrence pio = ruleApp.posInOccurrence(); - Term term = pio.subTerm(); - term = TermBuilder.goBelowUpdates(term); - IExecutionContext ec = JavaTools.getInnermostExecutionContext(term.javaBlock(), proof.getServices()); - //put values into map which have to be replaced - if(ec!=null){ - getVariableNamingMap().put(getSelfVar(), ec.getRuntimeInstance()); + /** + * Creates a new {@link AbstractConditionalBreakpoint}. Call setCondition immediately after + * calling the constructor! + * + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located + * at + * @param proof the {@link Proof} that will be executed and should stop + * @param condition the condition as given by the user + * @param enabled flag if the Breakpoint is enabled + * @param conditionEnabled flag if the condition is enabled + * @param containerType the type of the element containing the breakpoint + * @param suspendOnTrue the flag if the condition needs to evaluate to true or just be + * satisfiable + * @throws SLTranslationException if the condition could not be parsed to a valid Term + */ + public KeYWatchpoint(int hitCount, Proof proof, String condition, boolean enabled, + boolean conditionEnabled, KeYJavaType containerType, boolean suspendOnTrue) + throws SLTranslationException { + super(hitCount, null, proof, enabled, conditionEnabled, -1, -1, containerType); + setSuspendOnTrue(suspendOnTrue); + this.setCondition(condition); + } + + @Override + protected StatementBlock getStatementBlock(StatementContainer statementContainer) { + return (StatementBlock) statementContainer; + } + + @Override + protected boolean isInScope(Node node) { + return true; + } + + @Override + protected boolean isInScopeForCondition(Node node) { + return true; + } + + @Override + protected boolean conditionMet(RuleApp ruleApp, Proof proof, Node node) { + if (suspendOnTrue) { + return super.conditionMet(ruleApp, proof, node); + } else { + ApplyStrategyInfo info = null; + try { + Term negatedCondition = + getProof().getServices().getTermBuilder().not(getCondition()); + // initialize values + PosInOccurrence pio = ruleApp.posInOccurrence(); + Term term = pio.subTerm(); + term = TermBuilder.goBelowUpdates(term); + IExecutionContext ec = JavaTools.getInnermostExecutionContext(term.javaBlock(), + proof.getServices()); + // put values into map which have to be replaced + if (ec != null) { + getVariableNamingMap().put(getSelfVar(), ec.getRuntimeInstance()); + } + // replace renamings etc. + OpReplacer replacer = new OpReplacer(getVariableNamingMap(), + getProof().getServices().getTermFactory()); + Term termForSideProof = replacer.replace(negatedCondition); + // start side proof + Term toProof = getProof().getServices().getTermBuilder() + .equals(getProof().getServices().getTermBuilder().tt(), termForSideProof); + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), false); // New + // OneStepSimplifier + // is + // required + // because + // it has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, + pio, toProof); + info = SymbolicExecutionSideProofUtil.startSideProof(proof, sideProofEnv, sequent, + StrategyProperties.METHOD_CONTRACT, StrategyProperties.LOOP_INVARIANT, + StrategyProperties.QUERY_ON, StrategyProperties.SPLITTING_DELAYED); + return !info.getProof().closed(); + } catch (ProofInputException e) { + return false; + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "KeY Watchpoint evaluation on node " + node.serialNr() + ".", info); } - //replace renamings etc. - OpReplacer replacer = new OpReplacer(getVariableNamingMap(), getProof().getServices().getTermFactory()); - Term termForSideProof = replacer.replace(negatedCondition); - //start side proof - Term toProof = getProof().getServices().getTermBuilder().equals(getProof().getServices().getTermBuilder().tt(), termForSideProof); - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(getProof(), false); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent sequent = SymbolicExecutionUtil.createSequentToProveWithNewSuccedent(node, pio, toProof); - info = SymbolicExecutionSideProofUtil.startSideProof(proof, - sideProofEnv, - sequent, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_DELAYED); - return !info.getProof().closed(); - } - catch (ProofInputException e) { - return false; - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("KeY Watchpoint evaluation on node " + node.serialNr() + ".", info); - } - } - } - - public boolean isSuspendOnTrue() { - return suspendOnTrue; - } - - public void setSuspendOnTrue(boolean suspendOnTrue) { - this.suspendOnTrue = suspendOnTrue; - } - - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - if(activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED){ - return super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - return false; - } -} \ No newline at end of file + } + } + + public boolean isSuspendOnTrue() { + return suspendOnTrue; + } + + public void setSuspendOnTrue(boolean suspendOnTrue) { + this.suspendOnTrue = suspendOnTrue; + } + + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { + return super.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + return false; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/LineBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/LineBreakpoint.java index 143448c4c13..e31baac8792 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/LineBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/LineBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import org.key_project.util.ExtList; @@ -16,166 +19,184 @@ import de.uka.ilkd.key.speclang.translation.SLTranslationException; public class LineBreakpoint extends AbstractConditionalBreakpoint { - /** - * The path of the class this {@link LineBreakpoint} is associated with. - */ - private String classPath; - - /** - * The line of the Breakpoint in the respective class. - */ - private int lineNumber; - - /** - * The start of the method containing the associated Breakpoint - */ - protected int methodStart; - - /** - * The end of the method containing the associated Breakpoint - */ - protected int methodEnd; - - /** - * Creates a new {@link LineBreakpoint}. - * - * @param classPath the path of the class the associated Breakpoint lies within - * @param lineNumber the line where the associated Breakpoint is located in the class - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located at - * @param proof the {@link Proof} that will be executed and should stop - * @param condition the condition as given by the user - * @param enabled flag if the Breakpoint is enabled - * @param conditionEnabled flag if the condition is enabled - * @param methodStart the line the containing method of this breakpoint starts at - * @param methodEnd the line the containing method of this breakpoint ends at - * @throws SLTranslationException if the condition could not be parsed to a valid Term - */ - public LineBreakpoint(String classPath, int lineNumber, int hitCount, IProgramMethod pm, Proof proof, String condition, boolean enabled, boolean conditionEnabled, int methodStart, int methodEnd) throws SLTranslationException { - super(hitCount, pm, proof, enabled, conditionEnabled, methodStart, methodEnd, pm.getContainerType()); - this.classPath=classPath; - this.methodEnd=methodEnd; - this.methodStart=methodStart; - this.lineNumber=lineNumber; - this.setCondition(condition); - } - - - - /** - * For a given {@link StatementContainer} this method computes the {@link StatementBlock} that contains all lines before the line the Breakpoint is at, including the line itself. - * - * @param statementContainer the {@link StatementContainer} to build the block from - * @return the {@link StatementBlock} representing the container without the line below the Breakpoint - */ - @Override - protected StatementBlock getStatementBlock(StatementContainer statementContainer) { - //list of all statements - ExtList nextResult=new ExtList(); - for(int i = 0; i=i;j--){ - nextResult.remove(statementContainer.getChildAt(j)); - } + /** + * The path of the class this {@link LineBreakpoint} is associated with. + */ + private String classPath; + + /** + * The line of the Breakpoint in the respective class. + */ + private int lineNumber; + + /** + * The start of the method containing the associated Breakpoint + */ + protected int methodStart; + + /** + * The end of the method containing the associated Breakpoint + */ + protected int methodEnd; + + /** + * Creates a new {@link LineBreakpoint}. + * + * @param classPath the path of the class the associated Breakpoint lies within + * @param lineNumber the line where the associated Breakpoint is located in the class + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located + * at + * @param proof the {@link Proof} that will be executed and should stop + * @param condition the condition as given by the user + * @param enabled flag if the Breakpoint is enabled + * @param conditionEnabled flag if the condition is enabled + * @param methodStart the line the containing method of this breakpoint starts at + * @param methodEnd the line the containing method of this breakpoint ends at + * @throws SLTranslationException if the condition could not be parsed to a valid Term + */ + public LineBreakpoint(String classPath, int lineNumber, int hitCount, IProgramMethod pm, + Proof proof, String condition, boolean enabled, boolean conditionEnabled, + int methodStart, int methodEnd) throws SLTranslationException { + super(hitCount, pm, proof, enabled, conditionEnabled, methodStart, methodEnd, + pm.getContainerType()); + this.classPath = classPath; + this.methodEnd = methodEnd; + this.methodStart = methodStart; + this.lineNumber = lineNumber; + this.setCondition(condition); + } + + + + /** + * For a given {@link StatementContainer} this method computes the {@link StatementBlock} that + * contains all lines before the line the Breakpoint is at, including the line itself. + * + * @param statementContainer the {@link StatementContainer} to build the block from + * @return the {@link StatementBlock} representing the container without the line below the + * Breakpoint + */ + @Override + protected StatementBlock getStatementBlock(StatementContainer statementContainer) { + // list of all statements + ExtList nextResult = new ExtList(); + for (int i = 0; i < statementContainer.getStatementCount(); i++) { + nextResult.add(statementContainer.getStatementAt(i)); + } + // find last interesting statement + for (int i = 0; i < nextResult.size(); i++) { + if (!(((SourceElement) nextResult.get(i)).getEndPosition().getLine() <= lineNumber)) { + if (nextResult.get(i) instanceof StatementContainer) { + // go into inner scope + nextResult.set(i, getStatementBlock((StatementContainer) nextResult.get(i))); + } else { + // cut below last interesting statement + for (int j = nextResult.size() - 1; j >= i; j--) { + nextResult.remove(statementContainer.getChildAt(j)); + } + } } - } - } - return new StatementBlock(nextResult); - } - - /** - * Checks if the execution should stop in the given line for the given class. - * - * @param line The current line of code, that the auto mode is evaluating - * @param path The path of the Class, that contains the currently evaluated code - * @return true if a {@link JavaLineBreakpoint} is in the given line and the condition evaluates to true and the Hitcount is exceeded, false otherwise - */ - protected boolean shouldStopInLine(int line, String path) { - if (lineNumber == line && getClassPath().equals(path)) { - return true; - } - return false; - } - - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - if (ruleApp instanceof LoopInvariantBuiltInRuleApp) { - activeStatement = ((LoopInvariantBuiltInRuleApp) ruleApp).getLoopStatement(); - } - return isInLine(activeStatement)&&super.isBreakpointHit(activeStatement, ruleApp, proof, node); - } - - private boolean isInLine(SourceElement activeStatement){ - if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { - String path = activeStatement.getPositionInfo().getParentClass(); - int startLine = activeStatement.getStartPosition().getLine(); - int endLine = activeStatement.getEndPosition().getLine(); - boolean isInLine = endLine>startLine+1 ? shouldStopInLine(startLine, path) : shouldStopInLine(endLine, path); - return isInLine; - } - return false; - } - - /** - * Returns the line number of the associated Breakpoint. - * @return the line number of the associated Breakpoint - */ - public int getLineNumber() { - return lineNumber; - } - - @Override - protected boolean isInScope(Node node) { - Node checkNode = node; - while (checkNode != null) { - SourceElement activeStatement = NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); - if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { - if (activeStatement.getStartPosition().getLine() >= methodStart && activeStatement.getEndPosition().getLine() <= methodEnd) { - return true; + } + return new StatementBlock(nextResult); + } + + /** + * Checks if the execution should stop in the given line for the given class. + * + * @param line The current line of code, that the auto mode is evaluating + * @param path The path of the Class, that contains the currently evaluated code + * @return true if a {@link JavaLineBreakpoint} is in the given line and the condition evaluates + * to true and the Hitcount is exceeded, false otherwise + */ + protected boolean shouldStopInLine(int line, String path) { + if (lineNumber == line && getClassPath().equals(path)) { + return true; + } + return false; + } + + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + if (ruleApp instanceof LoopInvariantBuiltInRuleApp) { + activeStatement = ((LoopInvariantBuiltInRuleApp) ruleApp).getLoopStatement(); + } + return isInLine(activeStatement) + && super.isBreakpointHit(activeStatement, ruleApp, proof, node); + } + + private boolean isInLine(SourceElement activeStatement) { + if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { + String path = activeStatement.getPositionInfo().getParentClass(); + int startLine = activeStatement.getStartPosition().getLine(); + int endLine = activeStatement.getEndPosition().getLine(); + boolean isInLine = endLine > startLine + 1 ? shouldStopInLine(startLine, path) + : shouldStopInLine(endLine, path); + return isInLine; + } + return false; + } + + /** + * Returns the line number of the associated Breakpoint. + * + * @return the line number of the associated Breakpoint + */ + public int getLineNumber() { + return lineNumber; + } + + @Override + protected boolean isInScope(Node node) { + Node checkNode = node; + while (checkNode != null) { + SourceElement activeStatement = + NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); + if (activeStatement != null + && activeStatement.getStartPosition() != Position.UNDEFINED) { + if (activeStatement.getStartPosition().getLine() >= methodStart + && activeStatement.getEndPosition().getLine() <= methodEnd) { + return true; + } + break; } - break; - } - checkNode = checkNode.parent(); - } - return false; - } - - @Override - protected boolean isInScopeForCondition(Node node) { - Node checkNode = node; - while (checkNode != null) { - SourceElement activeStatement = NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); - if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { - if (activeStatement.getStartPosition().getLine() >= methodStart && activeStatement.getEndPosition().getLine() <= methodEnd && activeStatement instanceof LocalVariableDeclaration) { - return true; + checkNode = checkNode.parent(); + } + return false; + } + + @Override + protected boolean isInScopeForCondition(Node node) { + Node checkNode = node; + while (checkNode != null) { + SourceElement activeStatement = + NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); + if (activeStatement != null + && activeStatement.getStartPosition() != Position.UNDEFINED) { + if (activeStatement.getStartPosition().getLine() >= methodStart + && activeStatement.getEndPosition().getLine() <= methodEnd + && activeStatement instanceof LocalVariableDeclaration) { + return true; + } + break; } - break; - } - checkNode = checkNode.parent(); - } - return false; - } - - /** - * @return the classPath - */ - public String getClassPath() { - return classPath; - } - - /** - * @param classPath the classPath to set - */ - public void setClassPath(String classPath) { - this.classPath = classPath; - } -} \ No newline at end of file + checkNode = checkNode.parent(); + } + return false; + } + + /** + * @return the classPath + */ + public String getClassPath() { + return classPath; + } + + /** + * @param classPath the classPath to set + */ + public void setClassPath(String classPath) { + this.classPath = classPath; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/MethodBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/MethodBreakpoint.java index 50ddc7e98b3..d0da118c18f 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/MethodBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/MethodBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import org.key_project.util.java.ObjectUtil; @@ -24,189 +27,204 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; public class MethodBreakpoint extends AbstractConditionalBreakpoint { - /** - * flag to tell whether to stop on method entry - */ - private boolean isEntry; - - /** - * flag to tell whether to stop on method exit - */ - private boolean isExit; - - /** - * The start of the method containing the associated Breakpoint - */ - protected int methodStart; - - /** - * The end of the method containing the associated Breakpoint - */ - protected int methodEnd; - - /** - * The path of the class this {@link LineBreakpoint} is associated with. - */ - private String classPath; - - /** - * Creates a new {@link LineBreakpoint}. - * - * @param classPath the path of the class the associated Breakpoint lies within - * @param lineNumber the line where the associated Breakpoint is located in the class - * @param hitCount the number of hits after which the execution should hold at this breakpoint - * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located at - * @param proof the {@link Proof} that will be executed and should stop - * @param condition the condition as given by the user - * @param enabled flag if the Breakpoint is enabled - * @param conditionEnabled flag if the condition is enabled - * @param methodStart the line the containing method of this breakpoint starts at - * @param methodEnd the line the containing method of this breakpoint ends at - * @param containerType the type of the element containing the breakpoint - * @param isEntry flag to tell whether to stop on method entry - * @param isExit flag to tell whether to stop on method exit - * @throws SLTranslationException if the condition could not be parsed to a valid Term - */ - public MethodBreakpoint(String classPath, int lineNumber, int hitCount, IProgramMethod pm, Proof proof, String condition, boolean enabled, boolean conditionEnabled, int methodStart, int methodEnd, boolean isEntry, boolean isExit) throws SLTranslationException { - super(hitCount, pm, proof, enabled, conditionEnabled, methodStart, methodEnd, pm.getContainerType()); - this.isEntry = isEntry; - this.isExit = isExit; - this.setClassPath(classPath); - this.methodEnd=methodEnd; - this.methodStart=methodStart; - this.setCondition(condition); - } - - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - return !proof.isDisposed() && - ((isEntry && isMethodCallNode(node, ruleApp)) || (isExit && isMethodReturnNode(node, ruleApp))) && - (!isConditionEnabled() || conditionMet(ruleApp, proof, node)) && - isEnabled() && - hitcountExceeded(node); - } - - /** - * @param node to check - * @param ruleApp the applied rule app - * @return true if the node represents a method call - */ - private boolean isMethodCallNode(Node node, RuleApp ruleApp){ - SourceElement statement = NodeInfo.computeActiveStatement(ruleApp); - IProgramMethod currentPm=null; - if (statement instanceof MethodBodyStatement) { - MethodBodyStatement mbs = (MethodBodyStatement)statement; - currentPm = mbs.getProgramMethod(getProof().getServices()); - } - if(currentPm != null&¤tPm.equals(getPm())&&SymbolicExecutionUtil.isMethodCallNode(node, ruleApp, statement)){ + /** + * flag to tell whether to stop on method entry + */ + private boolean isEntry; + + /** + * flag to tell whether to stop on method exit + */ + private boolean isExit; + + /** + * The start of the method containing the associated Breakpoint + */ + protected int methodStart; + + /** + * The end of the method containing the associated Breakpoint + */ + protected int methodEnd; + + /** + * The path of the class this {@link LineBreakpoint} is associated with. + */ + private String classPath; + + /** + * Creates a new {@link LineBreakpoint}. + * + * @param classPath the path of the class the associated Breakpoint lies within + * @param lineNumber the line where the associated Breakpoint is located in the class + * @param hitCount the number of hits after which the execution should hold at this breakpoint + * @param pm the {@link IProgramMethod} representing the Method which the Breakpoint is located + * at + * @param proof the {@link Proof} that will be executed and should stop + * @param condition the condition as given by the user + * @param enabled flag if the Breakpoint is enabled + * @param conditionEnabled flag if the condition is enabled + * @param methodStart the line the containing method of this breakpoint starts at + * @param methodEnd the line the containing method of this breakpoint ends at + * @param containerType the type of the element containing the breakpoint + * @param isEntry flag to tell whether to stop on method entry + * @param isExit flag to tell whether to stop on method exit + * @throws SLTranslationException if the condition could not be parsed to a valid Term + */ + public MethodBreakpoint(String classPath, int lineNumber, int hitCount, IProgramMethod pm, + Proof proof, String condition, boolean enabled, boolean conditionEnabled, + int methodStart, int methodEnd, boolean isEntry, boolean isExit) + throws SLTranslationException { + super(hitCount, pm, proof, enabled, conditionEnabled, methodStart, methodEnd, + pm.getContainerType()); + this.isEntry = isEntry; + this.isExit = isExit; + this.setClassPath(classPath); + this.methodEnd = methodEnd; + this.methodStart = methodStart; + this.setCondition(condition); + } + + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + return !proof.isDisposed() + && ((isEntry && isMethodCallNode(node, ruleApp)) + || (isExit && isMethodReturnNode(node, ruleApp))) + && (!isConditionEnabled() || conditionMet(ruleApp, proof, node)) && isEnabled() + && hitcountExceeded(node); + } + + /** + * @param node to check + * @param ruleApp the applied rule app + * @return true if the node represents a method call + */ + private boolean isMethodCallNode(Node node, RuleApp ruleApp) { + SourceElement statement = NodeInfo.computeActiveStatement(ruleApp); + IProgramMethod currentPm = null; + if (statement instanceof MethodBodyStatement) { + MethodBodyStatement mbs = (MethodBodyStatement) statement; + currentPm = mbs.getProgramMethod(getProof().getServices()); + } + if (currentPm != null && currentPm.equals(getPm()) + && SymbolicExecutionUtil.isMethodCallNode(node, ruleApp, statement)) { return true; - }else if(ruleApp instanceof ContractRuleApp){ - ContractRuleApp methodRuleApp = (ContractRuleApp) ruleApp; - Contract contract = methodRuleApp.getInstantiation(); - if(contract instanceof FunctionalOperationContract){ - FunctionalOperationContract methodContract = (FunctionalOperationContract)contract; - if(methodContract.getTarget().equals(getPm())){ - return true; + } else if (ruleApp instanceof ContractRuleApp) { + ContractRuleApp methodRuleApp = (ContractRuleApp) ruleApp; + Contract contract = methodRuleApp.getInstantiation(); + if (contract instanceof FunctionalOperationContract) { + FunctionalOperationContract methodContract = (FunctionalOperationContract) contract; + if (methodContract.getTarget().equals(getPm())) { + return true; + } } - } - } - return false; - } - - /** - * @param node to check - * @param ruleApp the applied rule app - * @return true if the node represents a method return - */ - private boolean isMethodReturnNode(Node node, RuleApp ruleApp){ - if ((SymbolicExecutionUtil.isMethodReturnNode(node, ruleApp) || SymbolicExecutionUtil.isExceptionalMethodReturnNode(node, ruleApp)) && - isCorrectMethodReturn(node, ruleApp)) { - return true; - } - else if(ruleApp instanceof ContractRuleApp) { - ContractRuleApp methodRuleApp = (ContractRuleApp) ruleApp; - Contract contract = methodRuleApp.getInstantiation(); - if(contract instanceof FunctionalOperationContract){ - FunctionalOperationContract methodContract = (FunctionalOperationContract)contract; - if(methodContract.getTarget().equals(getPm())){ - return true; + } + return false; + } + + /** + * @param node to check + * @param ruleApp the applied rule app + * @return true if the node represents a method return + */ + private boolean isMethodReturnNode(Node node, RuleApp ruleApp) { + if ((SymbolicExecutionUtil.isMethodReturnNode(node, ruleApp) + || SymbolicExecutionUtil.isExceptionalMethodReturnNode(node, ruleApp)) + && isCorrectMethodReturn(node, ruleApp)) { + return true; + } else if (ruleApp instanceof ContractRuleApp) { + ContractRuleApp methodRuleApp = (ContractRuleApp) ruleApp; + Contract contract = methodRuleApp.getInstantiation(); + if (contract instanceof FunctionalOperationContract) { + FunctionalOperationContract methodContract = (FunctionalOperationContract) contract; + if (methodContract.getTarget().equals(getPm())) { + return true; + } } - } - } - return false; - } - - private boolean isCorrectMethodReturn(Node node, RuleApp ruleApp){ - Term term = ruleApp.posInOccurrence().subTerm(); - term = TermBuilder.goBelowUpdates(term); - MethodFrame mf = JavaTools.getInnermostMethodFrame(term.javaBlock(), node.proof().getServices()); - return ObjectUtil.equals(getPm(), mf.getProgramMethod()); - } - - @Override - protected StatementBlock getStatementBlock(StatementContainer statementContainer) { - return (StatementBlock) statementContainer; - } - - public boolean isEntry() { - return isEntry; - } - - public void setEntry(boolean isEntry) { - this.isEntry = isEntry; - } - - public boolean isExit() { - return isExit; - } - - public void setExit(boolean isExit) { - this.isExit = isExit; - } - - @Override - protected boolean isInScope(Node node) { - Node checkNode = node; - while (checkNode != null) { - SourceElement activeStatement = NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); - if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { - if (activeStatement.getStartPosition().getLine() >= methodStart && activeStatement.getEndPosition().getLine() <= methodEnd) { - return true; + } + return false; + } + + private boolean isCorrectMethodReturn(Node node, RuleApp ruleApp) { + Term term = ruleApp.posInOccurrence().subTerm(); + term = TermBuilder.goBelowUpdates(term); + MethodFrame mf = + JavaTools.getInnermostMethodFrame(term.javaBlock(), node.proof().getServices()); + return ObjectUtil.equals(getPm(), mf.getProgramMethod()); + } + + @Override + protected StatementBlock getStatementBlock(StatementContainer statementContainer) { + return (StatementBlock) statementContainer; + } + + public boolean isEntry() { + return isEntry; + } + + public void setEntry(boolean isEntry) { + this.isEntry = isEntry; + } + + public boolean isExit() { + return isExit; + } + + public void setExit(boolean isExit) { + this.isExit = isExit; + } + + @Override + protected boolean isInScope(Node node) { + Node checkNode = node; + while (checkNode != null) { + SourceElement activeStatement = + NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); + if (activeStatement != null + && activeStatement.getStartPosition() != Position.UNDEFINED) { + if (activeStatement.getStartPosition().getLine() >= methodStart + && activeStatement.getEndPosition().getLine() <= methodEnd) { + return true; + } + break; } - break; - } - checkNode = checkNode.parent(); - } - return false; - } - - @Override - protected boolean isInScopeForCondition(Node node) { - Node checkNode = node; - while (checkNode != null) { - SourceElement activeStatement = NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); - if (activeStatement != null && activeStatement.getStartPosition() != Position.UNDEFINED) { - if (activeStatement.getStartPosition().getLine() >= methodStart && activeStatement.getEndPosition().getLine() <= methodEnd && activeStatement instanceof LocalVariableDeclaration) { - return true; + checkNode = checkNode.parent(); + } + return false; + } + + @Override + protected boolean isInScopeForCondition(Node node) { + Node checkNode = node; + while (checkNode != null) { + SourceElement activeStatement = + NodeInfo.computeActiveStatement(checkNode.getAppliedRuleApp()); + if (activeStatement != null + && activeStatement.getStartPosition() != Position.UNDEFINED) { + if (activeStatement.getStartPosition().getLine() >= methodStart + && activeStatement.getEndPosition().getLine() <= methodEnd + && activeStatement instanceof LocalVariableDeclaration) { + return true; + } + break; } - break; - } - checkNode = checkNode.parent(); - } - return false; - } - - /** - * @return the classPath - */ - public String getClassPath() { - return classPath; - } - - /** - * @param classPath the classPath to set - */ - public void setClassPath(String classPath) { - this.classPath = classPath; - } -} \ No newline at end of file + checkNode = checkNode.parent(); + } + return false; + } + + /** + * @return the classPath + */ + public String getClassPath() { + return classPath; + } + + /** + * @param classPath the classPath to set + */ + public void setClassPath(String classPath) { + this.classPath = classPath; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/SymbolicExecutionExceptionBreakpoint.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/SymbolicExecutionExceptionBreakpoint.java index c01ab2e6322..cf03b1abb4c 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/SymbolicExecutionExceptionBreakpoint.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/strategy/breakpoint/SymbolicExecutionExceptionBreakpoint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.strategy.breakpoint; import java.util.HashSet; @@ -18,200 +21,198 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; /** - * This{@link SymbolicExecutionExceptionBreakpoint} represents an exception breakpoint and is responsible to tell the debugger to stop execution when the respective - * breakpoint is hit. - * + * This{@link SymbolicExecutionExceptionBreakpoint} represents an exception breakpoint and is + * responsible to tell the debugger to stop execution when the respective breakpoint is hit. + * * @author Marco Drebing */ public class SymbolicExecutionExceptionBreakpoint extends AbstractHitCountBreakpoint { - /** - * The exception to watch for - */ - private String exceptionName; - - /** - * a Set of Nodes that represent exceptions - */ - private Set exceptionNodes; - - /** - * a list of nodes of the Symbolic Execution Tree whose children represent exceptions - */ - private Set exceptionParentNodes; - - /** - * a flag whether to watch for an uncaught exception - */ - private boolean caught; - - /** - * a flag whether to suspend on subclasses of the exception aswell - */ - private boolean suspendOnSubclasses; - - /** - * a flag to tell whether to stop at uncaught exceptions or not - */ - private boolean uncaught; - - /** - * Creates a new {@link AbstractHitCountBreakpoint}. - * - * @param proof the {@link Proof} that will be executed and should stop - * @param exceptionName the name of the exception to watch for - * @param caught flag to tell if caught exceptions lead to a stop - * @param uncaught flag to tell if uncaught exceptions lead to a stop - * @param suspendOnSubclasses flag to tell if the execution should suspend on subclasses of the exception aswell - * @param enabled flag if the Breakpoint is enabled - * @param hitCount the number of hits after which the execution should hold at this breakpoint - */ - public SymbolicExecutionExceptionBreakpoint(Proof proof, String exceptionName, boolean caught, boolean uncaught, boolean suspendOnSubclasses, boolean enabled, int hitCount){ - super(hitCount, proof, enabled); - this.exceptionName = exceptionName; - exceptionNodes = new HashSet(); - exceptionParentNodes = new HashSet(); - this.caught=caught; - this.uncaught=uncaught; - this.suspendOnSubclasses=suspendOnSubclasses; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateState(int maxApplications, - long timeout, - Proof proof, - long startTime, - int countApplied, - Goal goal) { - if (goal != null) { - Node node = goal.node(); - // Check if goal is allowed - RuleApp ruleApp = goal.getRuleAppManager().peekNext(); - SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); - Node SETParent = SymbolicExecutionUtil.findParentSetNode(node); - if(activeStatement!=null&&activeStatement instanceof Throw&&isEnabled()){ - Throw throwStatement = (Throw)activeStatement; - for(int i = 0; i kjts = info.getAllSupertypes(kjt); - for(KeYJavaType kjtloc: kjts){ - if(kjtloc.getSort().toString().equals(exceptionName)&&!exceptionParentNodes.contains(SETParent)){ - exceptionNodes.add(node); - exceptionParentNodes.add(SETParent); + /** + * The exception to watch for + */ + private String exceptionName; + + /** + * a Set of Nodes that represent exceptions + */ + private Set exceptionNodes; + + /** + * a list of nodes of the Symbolic Execution Tree whose children represent exceptions + */ + private Set exceptionParentNodes; + + /** + * a flag whether to watch for an uncaught exception + */ + private boolean caught; + + /** + * a flag whether to suspend on subclasses of the exception aswell + */ + private boolean suspendOnSubclasses; + + /** + * a flag to tell whether to stop at uncaught exceptions or not + */ + private boolean uncaught; + + /** + * Creates a new {@link AbstractHitCountBreakpoint}. + * + * @param proof the {@link Proof} that will be executed and should stop + * @param exceptionName the name of the exception to watch for + * @param caught flag to tell if caught exceptions lead to a stop + * @param uncaught flag to tell if uncaught exceptions lead to a stop + * @param suspendOnSubclasses flag to tell if the execution should suspend on subclasses of the + * exception aswell + * @param enabled flag if the Breakpoint is enabled + * @param hitCount the number of hits after which the execution should hold at this breakpoint + */ + public SymbolicExecutionExceptionBreakpoint(Proof proof, String exceptionName, boolean caught, + boolean uncaught, boolean suspendOnSubclasses, boolean enabled, int hitCount) { + super(hitCount, proof, enabled); + this.exceptionName = exceptionName; + exceptionNodes = new HashSet(); + exceptionParentNodes = new HashSet(); + this.caught = caught; + this.uncaught = uncaught; + this.suspendOnSubclasses = suspendOnSubclasses; + } + + /** + * {@inheritDoc} + */ + @Override + public void updateState(int maxApplications, long timeout, Proof proof, long startTime, + int countApplied, Goal goal) { + if (goal != null) { + Node node = goal.node(); + // Check if goal is allowed + RuleApp ruleApp = goal.getRuleAppManager().peekNext(); + SourceElement activeStatement = NodeInfo.computeActiveStatement(ruleApp); + Node SETParent = SymbolicExecutionUtil.findParentSetNode(node); + if (activeStatement != null && activeStatement instanceof Throw && isEnabled()) { + Throw throwStatement = (Throw) activeStatement; + for (int i = 0; i < throwStatement.getChildCount(); i++) { + SourceElement childElement = throwStatement.getChildAt(i); + if (childElement instanceof LocationVariable) { + LocationVariable locVar = (LocationVariable) childElement; + if (locVar.getKeYJavaType().getSort().toString().equals(exceptionName) + && !exceptionParentNodes.contains(SETParent)) { + exceptionNodes.add(node); + exceptionParentNodes.add(SETParent); + } else if (suspendOnSubclasses) { + JavaInfo info = proof.getServices().getJavaInfo(); + KeYJavaType kjt = locVar.getKeYJavaType(); + ImmutableList kjts = info.getAllSupertypes(kjt); + for (KeYJavaType kjtloc : kjts) { + if (kjtloc.getSort().toString().equals(exceptionName) + && !exceptionParentNodes.contains(SETParent)) { + exceptionNodes.add(node); + exceptionParentNodes.add(SETParent); + } + } } - } - } - } - } - } - } - } - - /** - * Checks if the given node is a parent of the other given node. - * @param node The {@link Node} to start search in. - * @param node The {@link Node} that is thought to be the parent. - * @return true if the parent node is one of the nodes parents - */ - public boolean isParentNode(Node node, Node parent) { - if (node != null) { - Node parentIter = node.parent(); - boolean result = false; - while (parentIter != null && !result) { - if (parentIter.equals(parent)) { - result = true; + } + } } - else { - parentIter = parentIter.parent(); + } + } + + /** + * Checks if the given node is a parent of the other given node. + * + * @param node The {@link Node} to start search in. + * @param node The {@link Node} that is thought to be the parent. + * @return true if the parent node is one of the nodes parents + */ + public boolean isParentNode(Node node, Node parent) { + if (node != null) { + Node parentIter = node.parent(); + boolean result = false; + while (parentIter != null && !result) { + if (parentIter.equals(parent)) { + result = true; + } else { + parentIter = parentIter.parent(); + } } - } - return result; - } - else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, Node node) { - Node parent = null; - for(Node parents : exceptionNodes){ - if(isParentNode(node, parents)){ - parent = parents; - } - } - if(parent!=null - && SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp) - &&!exceptionParentNodes.isEmpty()){ - if(SymbolicExecutionUtil.isTerminationNode(node, ruleApp)&&uncaught){ - if(hitcountExceeded(node)){ - exceptionNodes.remove(parent); - return true; + return result; + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isBreakpointHit(SourceElement activeStatement, RuleApp ruleApp, Proof proof, + Node node) { + Node parent = null; + for (Node parents : exceptionNodes) { + if (isParentNode(node, parents)) { + parent = parents; } - } - else if(!SymbolicExecutionUtil.isTerminationNode(node, ruleApp)&&caught){ - if(hitcountExceeded(node)){ - exceptionNodes.remove(parent); - return true; + } + if (parent != null && SymbolicExecutionUtil.isSymbolicExecutionTreeNode(node, ruleApp) + && !exceptionParentNodes.isEmpty()) { + if (SymbolicExecutionUtil.isTerminationNode(node, ruleApp) && uncaught) { + if (hitcountExceeded(node)) { + exceptionNodes.remove(parent); + return true; + } + } else if (!SymbolicExecutionUtil.isTerminationNode(node, ruleApp) && caught) { + if (hitcountExceeded(node)) { + exceptionNodes.remove(parent); + return true; + } } - } - exceptionNodes.remove(parent); - } - return false; - } - - /** - * @return the isCaught - */ - public boolean isCaught() { - return caught; - } - - /** - * @param isCaught the isCaught to set - */ - public void setCaught(boolean isCaught) { - this.caught = isCaught; - } - - /** - * @return the isUncaught - */ - public boolean isUncaught() { - return uncaught; - } - - /** - * @param isUncaught the isUncaught to set - */ - public void setUncaught(boolean isUncaught) { - this.uncaught = isUncaught; - } - - /** - * @return the suspendOnSubclasses - */ - public boolean isSuspendOnSubclasses() { - return suspendOnSubclasses; - } - - /** - * @param suspendOnSubclasses the suspendOnSubclasses to set - */ - public void setSuspendOnSubclasses(boolean suspendOnSubclasses) { - this.suspendOnSubclasses = suspendOnSubclasses; - } -} \ No newline at end of file + exceptionNodes.remove(parent); + } + return false; + } + + /** + * @return the isCaught + */ + public boolean isCaught() { + return caught; + } + + /** + * @param isCaught the isCaught to set + */ + public void setCaught(boolean isCaught) { + this.caught = isCaught; + } + + /** + * @return the isUncaught + */ + public boolean isUncaught() { + return uncaught; + } + + /** + * @param isUncaught the isUncaught to set + */ + public void setUncaught(boolean isUncaught) { + this.uncaught = isUncaught; + } + + /** + * @return the suspendOnSubclasses + */ + public boolean isSuspendOnSubclasses() { + return suspendOnSubclasses; + } + + /** + * @param suspendOnSubclasses the suspendOnSubclasses to set + */ + public void setSuspendOnSubclasses(boolean suspendOnSubclasses) { + this.suspendOnSubclasses = suspendOnSubclasses; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/DefaultEntry.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/DefaultEntry.java index e8127604844..a97b25a3b0f 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/DefaultEntry.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/DefaultEntry.java @@ -1,32 +1,35 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import java.util.Map.Entry; public class DefaultEntry implements Entry { - private K key; - - private V value; + private K key; - public DefaultEntry(K key, V value) { - super(); - this.key = key; - this.value = value; - } + private V value; - @Override - public K getKey() { - return key; - } + public DefaultEntry(K key, V value) { + super(); + this.key = key; + this.value = value; + } - @Override - public V getValue() { - return value; - } + @Override + public K getKey() { + return key; + } - @Override - public V setValue(V value) { - V oldValue = this.value; - this.value = value; - return oldValue; - } -} \ No newline at end of file + @Override + public V getValue() { + return value; + } + + @Override + public V setValue(V value) { + V oldValue = this.value; + this.value = value; + return oldValue; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/EqualsHashCodeResetter.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/EqualsHashCodeResetter.java index 6d85e8c52ce..ef5ca3e4334 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/EqualsHashCodeResetter.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/EqualsHashCodeResetter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import java.util.Collection; @@ -5,65 +8,68 @@ /** *

    - * Instances of this class are used to reset overwritten {@link Object#equals(Object)} - * and {@link Object#hashCode()} methods of the wrapped child element to the - * default Java implementation with referenced based equality. + * Instances of this class are used to reset overwritten {@link Object#equals(Object)} and + * {@link Object#hashCode()} methods of the wrapped child element to the default Java implementation + * with referenced based equality. *

    *

    - * A possible use case of this class is for instance the usage in {@link Collection} - * like {@link Map}s. Imagine the following scenario: A {@code Map} maps - * {@code Customer} instances to something. Each customer has a unique ID and {@link Object#equals(Object)} - * and {@link Object#hashCode()} is overwritten to compare instances by their unique ID. - * If now a clone of a {@code Customer} instance exists the {@link Map} will return the value object - * for the original {@code Customer} instance. The {@link Map} can not separate between original and clone. - * If instead a {@code Map, ...>} is used original and clone are different - * because the default Java implementation with referenced based equality is used. + * A possible use case of this class is for instance the usage in {@link Collection} like + * {@link Map}s. Imagine the following scenario: A {@code Map} maps {@code Customer} + * instances to something. Each customer has a unique ID and {@link Object#equals(Object)} and + * {@link Object#hashCode()} is overwritten to compare instances by their unique ID. If now a clone + * of a {@code Customer} instance exists the {@link Map} will return the value object for the + * original {@code Customer} instance. The {@link Map} can not separate between original and clone. + * If instead a {@code Map, ...>} is used original and clone are + * different because the default Java implementation with referenced based equality is used. *

    + * * @author Martin Hentschel */ public class EqualsHashCodeResetter { - /** - * The wrapped elements on that {@link #equals(Object)} and - * {@link #hashCode()} is reset to default Java implementation. - */ - private T wrappedElement; + /** + * The wrapped elements on that {@link #equals(Object)} and {@link #hashCode()} is reset to + * default Java implementation. + */ + private T wrappedElement; - /** - * Constructor - * @param wrappedElement the wrapped elements on that {@link #equals(Object)} and {@link #hashCode()} is reset to default Java implementation. - */ - public EqualsHashCodeResetter(T wrappedElement) { - super(); - this.wrappedElement = wrappedElement; - } + /** + * Constructor + * + * @param wrappedElement the wrapped elements on that {@link #equals(Object)} and + * {@link #hashCode()} is reset to default Java implementation. + */ + public EqualsHashCodeResetter(T wrappedElement) { + super(); + this.wrappedElement = wrappedElement; + } - /** - * Overwritten to restore default Java implementation with reference based equality. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof EqualsHashCodeResetter) { - return getWrappedElement() == ((EqualsHashCodeResetter)obj).getWrappedElement(); - } - else { - return false; - } - } + /** + * Overwritten to restore default Java implementation with reference based equality. + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof EqualsHashCodeResetter) { + return getWrappedElement() == ((EqualsHashCodeResetter) obj).getWrappedElement(); + } else { + return false; + } + } - /** - * Overwritten to restore default Java implementation with reference based equality. - */ - @Override - public int hashCode() { - return System.identityHashCode(getWrappedElement()); - } + /** + * Overwritten to restore default Java implementation with reference based equality. + */ + @Override + public int hashCode() { + return System.identityHashCode(getWrappedElement()); + } - /** - * Returns the wrapped elements on that {@link #equals(Object)} and - * {@link #hashCode()} is reset to default Java implementation. - * @return The wrapped element. - */ - public T getWrappedElement() { - return wrappedElement; - } -} \ No newline at end of file + /** + * Returns the wrapped elements on that {@link #equals(Object)} and {@link #hashCode()} is reset + * to default Java implementation. + * + * @return The wrapped element. + */ + public T getWrappedElement() { + return wrappedElement; + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SideProofStore.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SideProofStore.java index 80b8405661e..ac95af46b39 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SideProofStore.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SideProofStore.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import java.beans.PropertyChangeListener; @@ -19,315 +22,342 @@ /** *

    - * The only instance of this class {@link #DEFAULT_INSTANCE} is used - * to manage performed side proofs. + * The only instance of this class {@link #DEFAULT_INSTANCE} is used to manage performed side + * proofs. *

    *

    - * Side proofs are added via {@link #disposeOrStore(String, ApplyStrategyInfo)} - * when they are no longer needed. If the {@link SideProofStore} is enabled ({@link #isEnabled()}) - * the side {@link Proof} is not disposed; instead it is added via {@link #addProof(String, Proof)} - * and available for a later access until it is removed via {@link #removeEntries(Collection)}. + * Side proofs are added via {@link #disposeOrStore(String, ApplyStrategyInfo)} when they are no + * longer needed. If the {@link SideProofStore} is enabled ({@link #isEnabled()}) the side + * {@link Proof} is not disposed; instead it is added via {@link #addProof(String, Proof)} and + * available for a later access until it is removed via {@link #removeEntries(Collection)}. *

    + * * @author Martin Hentschel */ public final class SideProofStore { - /** - * Property {@link #isEnabled()}. - */ - public static final String PROP_ENABLED = "enabled"; - - /** - * The default and only instance of this class. - */ - public static final SideProofStore DEFAULT_INSTANCE = new SideProofStore(); - - /** - * All contained {@link Entry}s. - */ - private final List entries = new LinkedList(); - - /** - * All available {@link ISideProofStoreListener}. - */ - private final List listener = new LinkedList(); - - /** - * The enabled state. - */ - private boolean enabled = false; - - /** - * The {@link PropertyChangeSupport}. - */ - private PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - /** - * Forbid other instances. - */ - private SideProofStore() { - } - - /** - * Checks if the {@link SideProofStore} is enabled or not. - * @return {@code true} enabled, {@code false} disabled. - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Defines the enabled state. - * @param enabled {@code true} enabled, {@code false} disabled. - */ - public void setEnabled(boolean enabled) { - boolean oldValue = isEnabled(); - this.enabled = enabled; - pcs.firePropertyChange(PROP_ENABLED, oldValue, isEnabled()); - } - - /** - * Adds a new {@link Proof}. - * @param description The description. - * @param proof The {@link Proof} to add. - */ - public void addProof(String description, Proof proof) { - synchronized (entries) { - if (!containsEntry(proof)) { - Entry entry = new Entry(description, proof); - ProofUserManager.getInstance().addUser(entry.getProof(), entry.getEnvironment(), this); - entries.add(entry); - fireEntriesAdded(new SideProofStoreEvent(this, new Entry[] {entry})); - } - } - } - - /** - * Removes the given {@link Entry}s. - * @param entries The {@link Entry}s to remove. - */ - public void removeEntries(Collection entries) { - synchronized (entries) { - if (this.entries.removeAll(entries)) { - for (Entry entry : entries) { - ProofUserManager.getInstance().removeUserAndDispose(entry.getProof(), this); + /** + * Property {@link #isEnabled()}. + */ + public static final String PROP_ENABLED = "enabled"; + + /** + * The default and only instance of this class. + */ + public static final SideProofStore DEFAULT_INSTANCE = new SideProofStore(); + + /** + * All contained {@link Entry}s. + */ + private final List entries = new LinkedList(); + + /** + * All available {@link ISideProofStoreListener}. + */ + private final List listener = + new LinkedList(); + + /** + * The enabled state. + */ + private boolean enabled = false; + + /** + * The {@link PropertyChangeSupport}. + */ + private PropertyChangeSupport pcs = new PropertyChangeSupport(this); + + /** + * Forbid other instances. + */ + private SideProofStore() {} + + /** + * Checks if the {@link SideProofStore} is enabled or not. + * + * @return {@code true} enabled, {@code false} disabled. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Defines the enabled state. + * + * @param enabled {@code true} enabled, {@code false} disabled. + */ + public void setEnabled(boolean enabled) { + boolean oldValue = isEnabled(); + this.enabled = enabled; + pcs.firePropertyChange(PROP_ENABLED, oldValue, isEnabled()); + } + + /** + * Adds a new {@link Proof}. + * + * @param description The description. + * @param proof The {@link Proof} to add. + */ + public void addProof(String description, Proof proof) { + synchronized (entries) { + if (!containsEntry(proof)) { + Entry entry = new Entry(description, proof); + ProofUserManager.getInstance().addUser(entry.getProof(), entry.getEnvironment(), + this); + entries.add(entry); + fireEntriesAdded(new SideProofStoreEvent(this, new Entry[] { entry })); } - fireEntriesRemoved(new SideProofStoreEvent(this, entries.toArray(new Entry[entries.size()]))); - } - } - } - - /** - * Removes all {@link Entry}s. - */ - public void clearProofs() { - removeEntries(new LinkedList(entries)); - } - - /** - * Checks if an {@link Entry} for the given {@link Proof} exist. - * @param proof The {@link Proof} to check. - * @return {@code true} {@link Entry} for {@link Proof} exist, {@code false} otherwise. - */ - public boolean containsEntry(Proof proof) { - return getEntry(proof) != null; - } - - /** - * Returns the {@link Entry} for the given {@link Proof}. - * @param proof The {@link Proof} for which the {@link Entry} is requested. - * @return The {@link Entry} with the given {@link Proof} or {@code null} if not available. - */ - public Entry getEntry(final Proof proof) { - return CollectionUtil.search(entries, new IFilter() { - @Override - public boolean select(Entry element) { - return element != null && element.getProof() == proof; - } - }); - } - - /** - * Checks if the given {@link Entry} is contained. - * @param entry The {@link Entry} to check. - * @return {@code true} {@link Entry} is contained, {@code false} {@link Entry} is not contained. - */ - public boolean containsEntry(Entry entry) { - return entries.contains(entry); - } - - /** - * Returns the number of contained {@link Entry}s. - * @return The number of contained {@link Entry}s. - */ - public int countEntries() { - return entries.size(); - } - - /** - * Returns the {@link Entry} at the given index. - * @param index The index. - * @return The {@link Entry} at the given index. - */ - public Entry getEntryAt(int index) { - return index >= 0 && index < entries.size() ? - entries.get(index) : - null; - } - - /** - * Returns all available {@link Entry}s. - * @return All available {@link Entry}s. - */ - public Entry[] getEntries() { - return entries.toArray(new Entry[entries.size()]); - } - - /** - * Registers the {@link ISideProofStoreListener}. - * @param l The {@link ISideProofStoreListener} to register. - */ - public void addProofStoreListener(ISideProofStoreListener l) { - if (l != null) { - listener.add(l); - } - } - - /** - * Unregisters the {@link ISideProofStoreListener}. - * @param l The {@link ISideProofStoreListener} to unregister. - */ - public void removeProofStoreListener(ISideProofStoreListener l) { - if (l != null) { - listener.remove(l); - } - } - - /** - * Returns all registered {@link ISideProofStoreListener}. - * @return All registered {@link ISideProofStoreListener}. - */ - public ISideProofStoreListener[] getProofStoreListener() { - return listener.toArray(new ISideProofStoreListener[listener.size()]); - } - - /** - * Fires the event {@link ISideProofStoreListener#entriesAdded(SideProofStoreEvent)}. - * @param e The event. - */ - protected void fireEntriesAdded(SideProofStoreEvent e) { - ISideProofStoreListener[] listener = getProofStoreListener(); - for (ISideProofStoreListener l : listener) { - l.entriesAdded(e); - } - } - - /** - * Fires the event {@link ISideProofStoreListener#entriesRemoved(SideProofStoreEvent)}. - * @param e The event. - */ - protected void fireEntriesRemoved(SideProofStoreEvent e) { - ISideProofStoreListener[] listener = getProofStoreListener(); - for (ISideProofStoreListener l : listener) { - l.entriesRemoved(e); - } - } - - /** - * Adds the given listener. - * @param listener The listener to add. - */ - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - /** - * Adds the given listener for the given property only. - * @param propertyName The property to observe. - * @param listener The listener to add. - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - /** - * Removes the given listener. - * @param listener The listener to remove. - */ - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - /** - * Removes the given listener from the given property. - * @param propertyName The property to no longer observe. - * @param listener The listener to remove. - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - /** - * An {@link Entry} of a {@link SideProofStore}. - * @author Martin Hentschel - */ - public static class Entry { - /** - * The description. - */ - private final String description; - - /** - * The {@link Proof}. - */ - private final Proof proof; - - /** - * The {@link KeYEnvironment}. - */ - private final KeYEnvironment environment; - - /** - * Constructor. - * @param description The description. - * @param proof The {@link Proof}. - */ - public Entry(String description, Proof proof) { - this.description = description; - this.proof = proof; - DefaultUserInterfaceControl ui = new DefaultUserInterfaceControl(); - this.environment = new KeYEnvironment(ui, proof.getInitConfig(), proof, null, null); - } - - /** - * Returns the description. - * @return The description. - */ - public String getDescription() { - return description; - } - - /** - * Returns the {@link Proof}. - * @return The {@link Proof}. - */ - public Proof getProof() { - return proof; - } - - /** - * Returns the {@link KeYEnvironment}. - * @return The {@link KeYEnvironment}. - */ - public KeYEnvironment getEnvironment() { - return environment; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return description; - } - } + } + } + + /** + * Removes the given {@link Entry}s. + * + * @param entries The {@link Entry}s to remove. + */ + public void removeEntries(Collection entries) { + synchronized (entries) { + if (this.entries.removeAll(entries)) { + for (Entry entry : entries) { + ProofUserManager.getInstance().removeUserAndDispose(entry.getProof(), this); + } + fireEntriesRemoved( + new SideProofStoreEvent(this, entries.toArray(new Entry[entries.size()]))); + } + } + } + + /** + * Removes all {@link Entry}s. + */ + public void clearProofs() { + removeEntries(new LinkedList(entries)); + } + + /** + * Checks if an {@link Entry} for the given {@link Proof} exist. + * + * @param proof The {@link Proof} to check. + * @return {@code true} {@link Entry} for {@link Proof} exist, {@code false} otherwise. + */ + public boolean containsEntry(Proof proof) { + return getEntry(proof) != null; + } + + /** + * Returns the {@link Entry} for the given {@link Proof}. + * + * @param proof The {@link Proof} for which the {@link Entry} is requested. + * @return The {@link Entry} with the given {@link Proof} or {@code null} if not available. + */ + public Entry getEntry(final Proof proof) { + return CollectionUtil.search(entries, new IFilter() { + @Override + public boolean select(Entry element) { + return element != null && element.getProof() == proof; + } + }); + } + + /** + * Checks if the given {@link Entry} is contained. + * + * @param entry The {@link Entry} to check. + * @return {@code true} {@link Entry} is contained, {@code false} {@link Entry} is not + * contained. + */ + public boolean containsEntry(Entry entry) { + return entries.contains(entry); + } + + /** + * Returns the number of contained {@link Entry}s. + * + * @return The number of contained {@link Entry}s. + */ + public int countEntries() { + return entries.size(); + } + + /** + * Returns the {@link Entry} at the given index. + * + * @param index The index. + * @return The {@link Entry} at the given index. + */ + public Entry getEntryAt(int index) { + return index >= 0 && index < entries.size() ? entries.get(index) : null; + } + + /** + * Returns all available {@link Entry}s. + * + * @return All available {@link Entry}s. + */ + public Entry[] getEntries() { + return entries.toArray(new Entry[entries.size()]); + } + + /** + * Registers the {@link ISideProofStoreListener}. + * + * @param l The {@link ISideProofStoreListener} to register. + */ + public void addProofStoreListener(ISideProofStoreListener l) { + if (l != null) { + listener.add(l); + } + } + + /** + * Unregisters the {@link ISideProofStoreListener}. + * + * @param l The {@link ISideProofStoreListener} to unregister. + */ + public void removeProofStoreListener(ISideProofStoreListener l) { + if (l != null) { + listener.remove(l); + } + } + + /** + * Returns all registered {@link ISideProofStoreListener}. + * + * @return All registered {@link ISideProofStoreListener}. + */ + public ISideProofStoreListener[] getProofStoreListener() { + return listener.toArray(new ISideProofStoreListener[listener.size()]); + } + + /** + * Fires the event {@link ISideProofStoreListener#entriesAdded(SideProofStoreEvent)}. + * + * @param e The event. + */ + protected void fireEntriesAdded(SideProofStoreEvent e) { + ISideProofStoreListener[] listener = getProofStoreListener(); + for (ISideProofStoreListener l : listener) { + l.entriesAdded(e); + } + } + + /** + * Fires the event {@link ISideProofStoreListener#entriesRemoved(SideProofStoreEvent)}. + * + * @param e The event. + */ + protected void fireEntriesRemoved(SideProofStoreEvent e) { + ISideProofStoreListener[] listener = getProofStoreListener(); + for (ISideProofStoreListener l : listener) { + l.entriesRemoved(e); + } + } + + /** + * Adds the given listener. + * + * @param listener The listener to add. + */ + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + /** + * Adds the given listener for the given property only. + * + * @param propertyName The property to observe. + * @param listener The listener to add. + */ + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + /** + * Removes the given listener. + * + * @param listener The listener to remove. + */ + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + /** + * Removes the given listener from the given property. + * + * @param propertyName The property to no longer observe. + * @param listener The listener to remove. + */ + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + /** + * An {@link Entry} of a {@link SideProofStore}. + * + * @author Martin Hentschel + */ + public static class Entry { + /** + * The description. + */ + private final String description; + + /** + * The {@link Proof}. + */ + private final Proof proof; + + /** + * The {@link KeYEnvironment}. + */ + private final KeYEnvironment environment; + + /** + * Constructor. + * + * @param description The description. + * @param proof The {@link Proof}. + */ + public Entry(String description, Proof proof) { + this.description = description; + this.proof = proof; + DefaultUserInterfaceControl ui = new DefaultUserInterfaceControl(); + this.environment = new KeYEnvironment(ui, + proof.getInitConfig(), proof, null, null); + } + + /** + * Returns the description. + * + * @return The description. + */ + public String getDescription() { + return description; + } + + /** + * Returns the {@link Proof}. + * + * @return The {@link Proof}. + */ + public Proof getProof() { + return proof; + } + + /** + * Returns the {@link KeYEnvironment}. + * + * @return The {@link KeYEnvironment}. + */ + public KeYEnvironment getEnvironment() { + return environment; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return description; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionEnvironment.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionEnvironment.java index 776e444fa8c..ae38da2d986 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionEnvironment.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionEnvironment.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import de.uka.ilkd.key.control.KeYEnvironment; @@ -12,112 +15,132 @@ import de.uka.ilkd.key.symbolic_execution.strategy.SymbolicExecutionStrategy; /** - * Instances of this class are used to collect and access all - * relevant information for symbolic execution tree extraction of {@link Proof}s - * via an {@link SymbolicExecutionTreeBuilder}. + * Instances of this class are used to collect and access all relevant information for symbolic + * execution tree extraction of {@link Proof}s via an {@link SymbolicExecutionTreeBuilder}. + * * @author Martin Hentschel */ -public class SymbolicExecutionEnvironment extends KeYEnvironment { - /** - * The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. - */ - private SymbolicExecutionTreeBuilder builder; - - /** - * Constructor. - * @param environment The parent {@link KeYEnvironment}. - * @param builder The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. - */ - public SymbolicExecutionEnvironment(KeYEnvironment environment, SymbolicExecutionTreeBuilder builder) { - this(environment.getUi(), - environment.getInitConfig(), - builder); - } +public class SymbolicExecutionEnvironment + extends KeYEnvironment { + /** + * The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. + */ + private SymbolicExecutionTreeBuilder builder; - /** - * Constructor. - * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. - * @param initConfig The loaded project. - * @param builder The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. - */ - public SymbolicExecutionEnvironment(U ui, - InitConfig initConfig, - SymbolicExecutionTreeBuilder builder) { - super(ui, initConfig); - this.builder = builder; - } + /** + * Constructor. + * + * @param environment The parent {@link KeYEnvironment}. + * @param builder The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. + */ + public SymbolicExecutionEnvironment(KeYEnvironment environment, + SymbolicExecutionTreeBuilder builder) { + this(environment.getUi(), environment.getInitConfig(), builder); + } - /** - * Returns the {@link SymbolicExecutionTreeBuilder} for execution tree extraction. - * @return The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. - */ - public SymbolicExecutionTreeBuilder getBuilder() { - return builder; - } - - /** - * Returns the {@link Proof} of {@link #getBuilder()}. - * @return The {@link Proof} of {@link #getBuilder()}. - */ - public Proof getProof() { - return getBuilder().getProof(); - } + /** + * Constructor. + * + * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. + * @param initConfig The loaded project. + * @param builder The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. + */ + public SymbolicExecutionEnvironment(U ui, InitConfig initConfig, + SymbolicExecutionTreeBuilder builder) { + super(ui, initConfig); + this.builder = builder; + } - /** - * Configures the given {@link Proof} to use the symbolic execution strategy - * by reusing the default {@link StrategyProperties}. - * @param proof The {@link Proof} to configure. - * @param maximalNumberOfNodesPerBranch The maximal number of nodes per branch. - */ - public static void configureProofForSymbolicExecution(Proof proof, - int maximalNumberOfNodesPerBranch) { - StrategyProperties sp = ProofSettings.DEFAULT_SETTINGS.getStrategySettings().getActiveStrategyProperties(); - boolean methodTreatmentContract = StrategyProperties.METHOD_CONTRACT.equals(sp.get(StrategyProperties.METHOD_OPTIONS_KEY)); - boolean loopTreatmentInvariant = StrategyProperties.LOOP_INVARIANT.equals(sp.get(StrategyProperties.LOOP_OPTIONS_KEY)); - boolean blockTreatmentContract = StrategyProperties.BLOCK_CONTRACT_INTERNAL.equals(sp.get(StrategyProperties.BLOCK_OPTIONS_KEY)); - boolean aliasChecks = StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY.equals(sp.get(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY)); - boolean nonExecutionBranchHidingSideProofs = StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF.equals(sp.get(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY)); - configureProofForSymbolicExecution(proof, maximalNumberOfNodesPerBranch, methodTreatmentContract, loopTreatmentInvariant, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - } - - /** - * Configures the given {@link Proof} to use the symbolic execution strategy. - * @param proof The {@link Proof} to configure. - * @param maximalNumberOfNodesPerBranch The maximal number of nodes per branch. - * @param methodTreatmentContract {@code true} use operation contracts, {@code false} expand methods. - * @param loopTreatmentInvariant {@code true} use invariants, {@code false} expand loops. - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - */ - public static void configureProofForSymbolicExecution(Proof proof, - int maximalNumberOfNodesPerBranch, - boolean methodTreatmentContract, - boolean loopTreatmentInvariant, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks) { - if (proof != null) { - StrategyProperties strategyProperties = SymbolicExecutionStrategy.getSymbolicExecutionStrategyProperties(true, methodTreatmentContract, loopTreatmentInvariant, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - proof.setActiveStrategy(proof.getActiveStrategyFactory().create(proof, strategyProperties)); - proof.getSettings().getStrategySettings().setCustomApplyStrategyGoalChooser(new SymbolicExecutionGoalChooser()); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(new ExecutedSymbolicExecutionTreeNodesStopCondition(maximalNumberOfNodesPerBranch)); - SymbolicExecutionUtil.updateStrategySettings(proof, strategyProperties); - } - } + /** + * Returns the {@link SymbolicExecutionTreeBuilder} for execution tree extraction. + * + * @return The {@link SymbolicExecutionTreeBuilder} for execution tree extraction. + */ + public SymbolicExecutionTreeBuilder getBuilder() { + return builder; + } - /** - * {@inheritDoc} - */ - @Override - public void dispose() { - Proof proof = getProof(); - if (builder != null) { - builder.dispose(); - } - if (proof != null && !proof.isDisposed() && proof != getLoadedProof()) { - proof.dispose(); - } - super.dispose(); - } -} \ No newline at end of file + /** + * Returns the {@link Proof} of {@link #getBuilder()}. + * + * @return The {@link Proof} of {@link #getBuilder()}. + */ + public Proof getProof() { + return getBuilder().getProof(); + } + + /** + * Configures the given {@link Proof} to use the symbolic execution strategy by reusing the + * default {@link StrategyProperties}. + * + * @param proof The {@link Proof} to configure. + * @param maximalNumberOfNodesPerBranch The maximal number of nodes per branch. + */ + public static void configureProofForSymbolicExecution(Proof proof, + int maximalNumberOfNodesPerBranch) { + StrategyProperties sp = + ProofSettings.DEFAULT_SETTINGS.getStrategySettings().getActiveStrategyProperties(); + boolean methodTreatmentContract = StrategyProperties.METHOD_CONTRACT + .equals(sp.get(StrategyProperties.METHOD_OPTIONS_KEY)); + boolean loopTreatmentInvariant = StrategyProperties.LOOP_INVARIANT + .equals(sp.get(StrategyProperties.LOOP_OPTIONS_KEY)); + boolean blockTreatmentContract = StrategyProperties.BLOCK_CONTRACT_INTERNAL + .equals(sp.get(StrategyProperties.BLOCK_OPTIONS_KEY)); + boolean aliasChecks = StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY + .equals(sp.get(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY)); + boolean nonExecutionBranchHidingSideProofs = + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF.equals( + sp.get(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY)); + configureProofForSymbolicExecution(proof, maximalNumberOfNodesPerBranch, + methodTreatmentContract, loopTreatmentInvariant, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + } + + /** + * Configures the given {@link Proof} to use the symbolic execution strategy. + * + * @param proof The {@link Proof} to configure. + * @param maximalNumberOfNodesPerBranch The maximal number of nodes per branch. + * @param methodTreatmentContract {@code true} use operation contracts, {@code false} expand + * methods. + * @param loopTreatmentInvariant {@code true} use invariants, {@code false} expand loops. + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + */ + public static void configureProofForSymbolicExecution(Proof proof, + int maximalNumberOfNodesPerBranch, boolean methodTreatmentContract, + boolean loopTreatmentInvariant, boolean blockTreatmentContract, + boolean nonExecutionBranchHidingSideProofs, boolean aliasChecks) { + if (proof != null) { + StrategyProperties strategyProperties = + SymbolicExecutionStrategy.getSymbolicExecutionStrategyProperties(true, + methodTreatmentContract, loopTreatmentInvariant, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + proof.setActiveStrategy( + proof.getActiveStrategyFactory().create(proof, strategyProperties)); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyGoalChooser(new SymbolicExecutionGoalChooser()); + proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition( + new ExecutedSymbolicExecutionTreeNodesStopCondition( + maximalNumberOfNodesPerBranch)); + SymbolicExecutionUtil.updateStrategySettings(proof, strategyProperties); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void dispose() { + Proof proof = getProof(); + if (builder != null) { + builder.dispose(); + } + if (proof != null && !proof.isDisposed() && proof != getLoadedProof()) { + proof.dispose(); + } + super.dispose(); + } +} diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java index 54f0618bdfa..bf8436425f3 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import java.util.HashMap; @@ -60,770 +63,846 @@ /** * Provides utility methods for side proofs. + * * @author Martin Hentschel */ public final class SymbolicExecutionSideProofUtil { - /** - * Forbid instances. - */ - private SymbolicExecutionSideProofUtil() { - } - - /** - * Computes a general {@link Sequent} to prove in a side proof which - * contains all {@link SequentFormula} of the original {@link Sequent} - * except the given current {@link SequentFormula} and those which - * contains modalities and queries. - * @param goalSequent The original {@link Sequent} of the current {@link Goal}. - * @param currentSF The {@link SequentFormula} to ignore. - * @return The general initial {@link Sequent}. - */ - public static Sequent computeGeneralSequentToProve(Sequent goalSequent, SequentFormula currentSF) { - Sequent sequentToProve = Sequent.EMPTY_SEQUENT; - for (SequentFormula sf : goalSequent.antecedent()) { - if (sf != currentSF) { - if (!containsModalityOrQuery(sf)) { - sequentToProve = sequentToProve.addFormula(sf, true, false).sequent(); - } - } - } - for (SequentFormula sf : goalSequent.succedent()) { - if (sf != currentSF) { - if (!containsModalityOrQuery(sf)) { - sequentToProve = sequentToProve.addFormula(sf, false, false).sequent(); - } - } - } - return sequentToProve; - } - - /** - *

    - * Starts the side proof and extracts the result {@link Term}. - *

    - *

    - * New used names are automatically added to the {@link Namespace} of the {@link Services}. - *

    - * @param services The {@link Services} to use. - * @param proof The {@link Proof} from on which the side proof si performed. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to prove in a side proof. - * @param label The {@link TermLabel} which is used to compute the result. - * @param description The side proof description. - * @param splittingOption The splitting options to use. - * @param addNamesToServices {@code true} defines that used names in result and conditions are added to the namespace of the given {@link Services}, {@code false} means that names are not added. - * @return The found result {@link Term} and the conditions. - * @throws ProofInputException Occurred Exception. - */ - public static List> computeResults(Services services, - Proof proof, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - TermLabel label, - String description, - String methodTreatment, - String loopTreatment, - String queryTreatment, - String splittingOption, - boolean addNamesToServices) throws ProofInputException { - // Execute side proof - ApplyStrategyInfo info = startSideProof(proof, sideProofEnvironment, sequentToProve, methodTreatment, loopTreatment, queryTreatment, splittingOption); - try { - // Extract results and conditions from side proof - List> conditionsAndResultsMap = new LinkedList>(); - for (Goal resultGoal : info.getProof().openGoals()) { - if (SymbolicExecutionUtil.hasApplicableRules(resultGoal)) { - throw new IllegalStateException("Not all applicable rules are applied."); - } - Sequent sequent = resultGoal.sequent(); - List results = new LinkedList(); - for (SequentFormula sf : sequent.antecedent()) { - if (sf.formula().containsLabel(label)) { - Term result = sf.formula(); - result = services.getTermBuilder().not(result); - results.add(result); - } - } - for (SequentFormula sf : sequent.succedent()) { - if (sf.formula().containsLabel(label)) { - Term result = sf.formula(); - results.add(result); - } + /** + * Forbid instances. + */ + private SymbolicExecutionSideProofUtil() {} + + /** + * Computes a general {@link Sequent} to prove in a side proof which contains all + * {@link SequentFormula} of the original {@link Sequent} except the given current + * {@link SequentFormula} and those which contains modalities and queries. + * + * @param goalSequent The original {@link Sequent} of the current {@link Goal}. + * @param currentSF The {@link SequentFormula} to ignore. + * @return The general initial {@link Sequent}. + */ + public static Sequent computeGeneralSequentToProve(Sequent goalSequent, + SequentFormula currentSF) { + Sequent sequentToProve = Sequent.EMPTY_SEQUENT; + for (SequentFormula sf : goalSequent.antecedent()) { + if (sf != currentSF) { + if (!containsModalityOrQuery(sf)) { + sequentToProve = sequentToProve.addFormula(sf, true, false).sequent(); + } } - Term result; - if (results.isEmpty()) { - result = services.getTermBuilder().tt(); + } + for (SequentFormula sf : goalSequent.succedent()) { + if (sf != currentSF) { + if (!containsModalityOrQuery(sf)) { + sequentToProve = sequentToProve.addFormula(sf, false, false).sequent(); + } } - else { - result = services.getTermBuilder().or(results); + } + return sequentToProve; + } + + /** + *

    + * Starts the side proof and extracts the result {@link Term}. + *

    + *

    + * New used names are automatically added to the {@link Namespace} of the {@link Services}. + *

    + * + * @param services The {@link Services} to use. + * @param proof The {@link Proof} from on which the side proof si performed. + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to prove in a side proof. + * @param label The {@link TermLabel} which is used to compute the result. + * @param description The side proof description. + * @param splittingOption The splitting options to use. + * @param addNamesToServices {@code true} defines that used names in result and conditions are + * added to the namespace of the given {@link Services}, {@code false} means that names + * are not added. + * @return The found result {@link Term} and the conditions. + * @throws ProofInputException Occurred Exception. + */ + public static List> computeResults(Services services, Proof proof, + ProofEnvironment sideProofEnvironment, Sequent sequentToProve, TermLabel label, + String description, String methodTreatment, String loopTreatment, String queryTreatment, + String splittingOption, boolean addNamesToServices) throws ProofInputException { + // Execute side proof + ApplyStrategyInfo info = startSideProof(proof, sideProofEnvironment, sequentToProve, + methodTreatment, loopTreatment, queryTreatment, splittingOption); + try { + // Extract results and conditions from side proof + List> conditionsAndResultsMap = new LinkedList>(); + for (Goal resultGoal : info.getProof().openGoals()) { + if (SymbolicExecutionUtil.hasApplicableRules(resultGoal)) { + throw new IllegalStateException("Not all applicable rules are applied."); + } + Sequent sequent = resultGoal.sequent(); + List results = new LinkedList(); + for (SequentFormula sf : sequent.antecedent()) { + if (sf.formula().containsLabel(label)) { + Term result = sf.formula(); + result = services.getTermBuilder().not(result); + results.add(result); + } + } + for (SequentFormula sf : sequent.succedent()) { + if (sf.formula().containsLabel(label)) { + Term result = sf.formula(); + results.add(result); + } + } + Term result; + if (results.isEmpty()) { + result = services.getTermBuilder().tt(); + } else { + result = services.getTermBuilder().or(results); + } + conditionsAndResultsMap.add(new Pair(result, resultGoal.node())); } - conditionsAndResultsMap.add(new Pair(result, resultGoal.node())); - } - return conditionsAndResultsMap; - } - finally { - disposeOrStore(description, info); - } - } - - /** - *

    - * Starts the side proof and extracts the result {@link Term} and conditions. - *

    - *

    - * New used names are automatically added to the {@link Namespace} of the {@link Services}. - *

    - * @param services The {@link Services} to use. - * @param proof The {@link Proof} from on which the side proof si performed. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to prove in a side proof. - * @param operator The {@link Operator} which is used to compute the result. - * @param description The side proof description. - * @param splittingOption The splitting options to use. - * @param addNamesToServices {@code true} defines that used names in result and conditions are added to the namespace of the given {@link Services}, {@code false} means that names are not added. - * @return The found result {@link Term} and the conditions. - * @throws ProofInputException Occurred Exception. - */ - public static List, Node>> computeResultsAndConditions(Services services, - Proof proof, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - Operator operator, - String description, - String methodTreatment, - String loopTreatment, - String queryTreatment, - String splittingOption, - boolean addNamesToServices) throws ProofInputException { - // Execute side proof - ApplyStrategyInfo info = startSideProof(proof, sideProofEnvironment, sequentToProve, methodTreatment, loopTreatment, queryTreatment, splittingOption); - try { - // Extract relevant things - Set relevantThingsInSequentToProve = extractRelevantThings(info.getProof().getServices(), sequentToProve); - // Extract results and conditions from side proof - List, Node>> conditionsAndResultsMap = new LinkedList, Node>>(); - for (Goal resultGoal : info.getProof().openGoals()) { - if (SymbolicExecutionUtil.hasApplicableRules(resultGoal)) { - throw new IllegalStateException("Not all applicable rules are applied."); + return conditionsAndResultsMap; + } finally { + disposeOrStore(description, info); + } + } + + /** + *

    + * Starts the side proof and extracts the result {@link Term} and conditions. + *

    + *

    + * New used names are automatically added to the {@link Namespace} of the {@link Services}. + *

    + * + * @param services The {@link Services} to use. + * @param proof The {@link Proof} from on which the side proof si performed. + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to prove in a side proof. + * @param operator The {@link Operator} which is used to compute the result. + * @param description The side proof description. + * @param splittingOption The splitting options to use. + * @param addNamesToServices {@code true} defines that used names in result and conditions are + * added to the namespace of the given {@link Services}, {@code false} means that names + * are not added. + * @return The found result {@link Term} and the conditions. + * @throws ProofInputException Occurred Exception. + */ + public static List, Node>> computeResultsAndConditions(Services services, + Proof proof, ProofEnvironment sideProofEnvironment, Sequent sequentToProve, + Operator operator, String description, String methodTreatment, String loopTreatment, + String queryTreatment, String splittingOption, boolean addNamesToServices) + throws ProofInputException { + // Execute side proof + ApplyStrategyInfo info = startSideProof(proof, sideProofEnvironment, sequentToProve, + methodTreatment, loopTreatment, queryTreatment, splittingOption); + try { + // Extract relevant things + Set relevantThingsInSequentToProve = + extractRelevantThings(info.getProof().getServices(), sequentToProve); + // Extract results and conditions from side proof + List, Node>> conditionsAndResultsMap = + new LinkedList, Node>>(); + for (Goal resultGoal : info.getProof().openGoals()) { + if (SymbolicExecutionUtil.hasApplicableRules(resultGoal)) { + throw new IllegalStateException("Not all applicable rules are applied."); + } + Sequent sequent = resultGoal.sequent(); + boolean newPredicateIsSequentFormula = isOperatorASequentFormula(sequent, operator); + Set resultConditions = new LinkedHashSet(); + Term result = null; + for (SequentFormula sf : sequent.antecedent()) { + if (newPredicateIsSequentFormula) { + if (sf.formula().op() == operator) { + throw new IllegalStateException( + "Result predicate found in antecedent."); + } else { + Term constructedResult = + constructResultIfContained(services, sf, operator); + if (constructedResult != null) { + throw new IllegalStateException( + "Result predicate found in antecedent."); + } + } + } + if (!isIrrelevantCondition(services, sequentToProve, + relevantThingsInSequentToProve, sf)) { + if (resultConditions.add(sf.formula()) && addNamesToServices) { + addNewNamesToNamespace(services, sf.formula()); + } + } + } + for (SequentFormula sf : sequent.succedent()) { + if (newPredicateIsSequentFormula) { + if (sf.formula().op() == operator) { + if (result != null) { + throw new IllegalStateException( + "Result predicate found multiple times in succedent."); + } + result = sf.formula().sub(0); + } + } else { + Term constructedResult = constructResultIfContained(services, sf, operator); + if (constructedResult != null) { + if (result != null) { + throw new IllegalStateException( + "Result predicate found multiple times in succedent."); + } + result = constructedResult; + } + } + if (result == null) { + if (!isIrrelevantCondition(services, sequentToProve, + relevantThingsInSequentToProve, sf)) { + if (resultConditions.add(services.getTermBuilder().not(sf.formula())) + && addNamesToServices) { + addNewNamesToNamespace(services, sf.formula()); + } + } + } + } + if (result == null) { + result = services.getTermBuilder().ff(); + } + conditionsAndResultsMap.add(new Triple, Node>(result, + resultConditions, resultGoal.node())); } - Sequent sequent = resultGoal.sequent(); - boolean newPredicateIsSequentFormula = isOperatorASequentFormula(sequent, operator); - Set resultConditions = new LinkedHashSet(); + return conditionsAndResultsMap; + } finally { + disposeOrStore(description, info); + } + } + + private static Term constructResultIfContained(Services services, SequentFormula sf, + Operator operator) { + return constructResultIfContained(services, sf.formula(), operator); + } + + private static Term constructResultIfContained(Services services, Term term, + Operator operator) { + if (term.op() == operator) { + return term.sub(0); + } else { Term result = null; - for (SequentFormula sf : sequent.antecedent()) { - if (newPredicateIsSequentFormula) { - if (sf.formula().op() == operator) { - throw new IllegalStateException("Result predicate found in antecedent."); - } - else { - Term constructedResult = constructResultIfContained(services, sf, operator); - if (constructedResult != null) { - throw new IllegalStateException("Result predicate found in antecedent."); - } - } - } - if (!isIrrelevantCondition(services, sequentToProve, relevantThingsInSequentToProve, sf)) { - if (resultConditions.add(sf.formula()) && addNamesToServices) { - addNewNamesToNamespace(services, sf.formula()); - } - } - } - for (SequentFormula sf : sequent.succedent()) { - if (newPredicateIsSequentFormula) { - if (sf.formula().op() == operator) { - if (result != null) { - throw new IllegalStateException("Result predicate found multiple times in succedent."); - } - result = sf.formula().sub(0); - } - } - else { - Term constructedResult = constructResultIfContained(services, sf, operator); - if (constructedResult != null) { - if (result != null) { - throw new IllegalStateException("Result predicate found multiple times in succedent."); - } - result = constructedResult; - } - } - if (result == null) { - if (!isIrrelevantCondition(services, sequentToProve, relevantThingsInSequentToProve, sf)) { - if (resultConditions.add(services.getTermBuilder().not(sf.formula())) && addNamesToServices) { - addNewNamesToNamespace(services, sf.formula()); - } - } - } + int i = 0; + while (result == null && i < term.arity()) { + result = constructResultIfContained(services, term.sub(i), operator); + i++; } - if (result == null) { - result = services.getTermBuilder().ff(); + if (result != null) { + List newSubs = new LinkedList(); + for (int j = 0; j < term.arity(); j++) { + if (j == i - 1) { + newSubs.add(result); + } else { + newSubs.add(term.sub(j)); + } + } + result = services.getTermFactory().createTerm(term.op(), + new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), + term.getLabels()); } - conditionsAndResultsMap.add(new Triple, Node>(result, resultConditions, resultGoal.node())); - } - return conditionsAndResultsMap; - } - finally { - disposeOrStore(description, info); - } - } - - private static Term constructResultIfContained(Services services, SequentFormula sf, Operator operator) { - return constructResultIfContained(services, sf.formula(), operator); - } - - private static Term constructResultIfContained(Services services, Term term, Operator operator) { - if (term.op() == operator) { - return term.sub(0); - } - else { - Term result = null; - int i = 0; - while (result == null && i < term.arity()) { - result = constructResultIfContained(services, term.sub(i), operator); - i++; - } - if (result != null) { - List newSubs = new LinkedList(); - for (int j = 0; j < term.arity(); j++) { - if (j == i - 1) { - newSubs.add(result); - } - else { - newSubs.add(term.sub(j)); - } - } - result = services.getTermFactory().createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), term.getLabels()); - } - return result; - } - } - - private static boolean isOperatorASequentFormula(Sequent sequent, final Operator operator) { - return CollectionUtil.search(sequent, new IFilter() { - @Override - public boolean select(SequentFormula element) { - return element.formula().op() == operator; - } - }) != null; - } - - /** - * Makes sure that all used {@link Name}s in the given {@link Term} - * are registered in the {@link Namespace}s of the given {@link Services}. - * @param services The {@link Services} to use. - * @param term The {@link Term} to check its {@link Name}s. - */ - public static void addNewNamesToNamespace(Services services, Term term) { - final Namespace functions = services.getNamespaces().functions(); - final Namespace progVars = services.getNamespaces().programVariables(); - // LogicVariables are always local bound - term.execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - if (visited.op() instanceof Function) { - functions.add((Function) visited.op()); - } - else if (visited.op() instanceof IProgramVariable) { - progVars.add((IProgramVariable) visited.op()); + return result; + } + } + + private static boolean isOperatorASequentFormula(Sequent sequent, final Operator operator) { + return CollectionUtil.search(sequent, new IFilter() { + @Override + public boolean select(SequentFormula element) { + return element.formula().op() == operator; } - } - }); - } - - /** - * Checks if the given {@link SequentFormula} contains a modality or query. - * @param sf The {@link SequentFormula} to check. - * @return {@code true} contains at least one modality or query, {@code false} contains no modalities and no queries. - */ - public static boolean containsModalityOrQuery(SequentFormula sf) { - return containsModalityOrQuery(sf.formula()); - } - - /** - * Checks if the given {@link Term} contains a modality or query. - * @param term The {@link Term} to check. - * @return {@code true} contains at least one modality or query, {@code false} contains no modalities and no queries. - */ - public static boolean containsModalityOrQuery(Term term) { - ContainsModalityOrQueryVisitor visitor = new ContainsModalityOrQueryVisitor(); - term.execPostOrder(visitor); - return visitor.isContainsModalityOrQuery(); - } - - /** - * Utility method used by {@link QuerySideProofRule#containsModalityOrQuery(Term)}. - * @author Martin Hentschel - */ - protected static class ContainsModalityOrQueryVisitor extends DefaultVisitor { - /** - * The result. - */ - boolean containsModalityOrQuery = false; - - /** - * {@inheritDoc} - */ - @Override - public void visit(Term visited) { - if (visited.op() instanceof Modality) { - containsModalityOrQuery = true; - } - else if (visited.op() instanceof IProgramMethod) { - containsModalityOrQuery = true; - } - } - - /** - * Returns the result. - * @return {@code true} contains at least one modality or query, {@code false} contains no modalities and no queries. - */ - public boolean isContainsModalityOrQuery() { - return containsModalityOrQuery; - } - } - - /** - * Extracts all {@link Operator}s from the given {@link Sequent} which - * represents relevant things. - * @param services The {@link Services} to use. - * @param sequentToProve The {@link Sequent} to extract relevant things from. - * @return The found relevant things. - */ - public static Set extractRelevantThings(final Services services, - Sequent sequentToProve) { - final Set result = new HashSet(); - for (SequentFormula sf : sequentToProve) { - sf.formula().execPreOrder(new DefaultVisitor() { + }) != null; + } + + /** + * Makes sure that all used {@link Name}s in the given {@link Term} are registered in the + * {@link Namespace}s of the given {@link Services}. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to check its {@link Name}s. + */ + public static void addNewNamesToNamespace(Services services, Term term) { + final Namespace functions = services.getNamespaces().functions(); + final Namespace progVars = services.getNamespaces().programVariables(); + // LogicVariables are always local bound + term.execPreOrder(new DefaultVisitor() { @Override public void visit(Term visited) { - if (isRelevantThing(services, visited)) { - result.add(visited.op()); - } + if (visited.op() instanceof Function) { + functions.add((Function) visited.op()); + } else if (visited.op() instanceof IProgramVariable) { + progVars.add((IProgramVariable) visited.op()); + } + } + }); + } + + /** + * Checks if the given {@link SequentFormula} contains a modality or query. + * + * @param sf The {@link SequentFormula} to check. + * @return {@code true} contains at least one modality or query, {@code false} contains no + * modalities and no queries. + */ + public static boolean containsModalityOrQuery(SequentFormula sf) { + return containsModalityOrQuery(sf.formula()); + } + + /** + * Checks if the given {@link Term} contains a modality or query. + * + * @param term The {@link Term} to check. + * @return {@code true} contains at least one modality or query, {@code false} contains no + * modalities and no queries. + */ + public static boolean containsModalityOrQuery(Term term) { + ContainsModalityOrQueryVisitor visitor = new ContainsModalityOrQueryVisitor(); + term.execPostOrder(visitor); + return visitor.isContainsModalityOrQuery(); + } + + /** + * Utility method used by {@link QuerySideProofRule#containsModalityOrQuery(Term)}. + * + * @author Martin Hentschel + */ + protected static class ContainsModalityOrQueryVisitor extends DefaultVisitor { + /** + * The result. + */ + boolean containsModalityOrQuery = false; + + /** + * {@inheritDoc} + */ + @Override + public void visit(Term visited) { + if (visited.op() instanceof Modality) { + containsModalityOrQuery = true; + } else if (visited.op() instanceof IProgramMethod) { + containsModalityOrQuery = true; } - }); - } - return result; - } - - /** - * Checks if the given {@link Term} describes a relevant thing. - * Relevant things are: - *
      - *
    • IProgramVariable
    • - *
    • Functions of type Heap
    • - *
    • Functions of a Java type
    • - *
    - * @param services The {@link Services} to use. - * @param term The {@link Term} to check. - * @return {@code true} is relevant thing, {@code false} is not relevant. - */ - protected static boolean isRelevantThing(Services services, Term term) { - if (term.op() instanceof IProgramVariable) { - return true; - } - else if (term.op() instanceof Function) { - HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { + } + + /** + * Returns the result. + * + * @return {@code true} contains at least one modality or query, {@code false} contains no + * modalities and no queries. + */ + public boolean isContainsModalityOrQuery() { + return containsModalityOrQuery; + } + } + + /** + * Extracts all {@link Operator}s from the given {@link Sequent} which represents relevant + * things. + * + * @param services The {@link Services} to use. + * @param sequentToProve The {@link Sequent} to extract relevant things from. + * @return The found relevant things. + */ + public static Set extractRelevantThings(final Services services, + Sequent sequentToProve) { + final Set result = new HashSet(); + for (SequentFormula sf : sequentToProve) { + sf.formula().execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + if (isRelevantThing(services, visited)) { + result.add(visited.op()); + } + } + }); + } + return result; + } + + /** + * Checks if the given {@link Term} describes a relevant thing. Relevant things are: + *
      + *
    • IProgramVariable
    • + *
    • Functions of type Heap
    • + *
    • Functions of a Java type
    • + *
    + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to check. + * @return {@code true} is relevant thing, {@code false} is not relevant. + */ + protected static boolean isRelevantThing(Services services, Term term) { + if (term.op() instanceof IProgramVariable) { return true; - } - else { - KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(term.sort()); - return kjt != null; - } - } - else { - return false; - } - } - - /** - * Checks if the given {@link SequentFormula} is a relevant condition. - * @param services The {@link Services} to use. - * @param initialSequent The initial {@link Sequent} of the side proof. - * @param relevantThingsInSequentToProve The relevant things found in the initial {@link Sequent}. - * @param sf The {@link SequentFormula} to check. - * @return {@code true} {@link SequentFormula} is relevant condition, {@code false} {@link SequentFormula} is not a relevant condition. - */ - public static boolean isIrrelevantCondition(Services services, - Sequent initialSequent, - Set relevantThingsInSequentToProve, - SequentFormula sf) { - return initialSequent.antecedent().contains(sf) || // Conditions which already exist in the initial sequent are irrelevant - initialSequent.succedent().contains(sf) || // Conditions which already exist in the initial sequent are irrelevant -// isInOrOfAntecedent(initialSequent, sf) || - containsModalityOrQuery(sf) || // Conditions with modalities or queries are irrelevant - containsIrrelevantThings(services, sf, relevantThingsInSequentToProve); // Conditions which contains not relevant things are irrelevant - } - -// public static boolean isInOrOfAntecedent(Sequent initialSequent, SequentFormula sf) { -// Term term = sf.formula(); -// boolean result = false; -// Iterator iter = initialSequent.antecedent().iterator(); -// while (!result && iter.hasNext()) { -// SequentFormula next = iter.next(); -// if (isInOr(next.formula(), term)) { -// result = true; -// } -// } -// return result; -// } -// -// public static boolean isInOr(Term term, Term toCheck) { -// if (term.op() == Junctor.OR) { -// boolean result = false; -// Iterator iter = term.subs().iterator(); -// while (!result && iter.hasNext()) { -// result = isInOr(iter.next(), toCheck); -// } -// return result; -// } -// else { -// return term == toCheck; -// } -// } - - /** - * Checks if the given {@link SequentFormula} contains irrelevant things - * (things which are not contained in the relevantThingsToProve and are no Java types) - * @param services The {@link Services} to use. - * @param sf The {@link SequentFormula} to check. - * @param relevantThings The relevant things. - * @return {@code true} The {@link SequentFormula} contains irrelevant things, {@code false} the {@link SequentFormula} contains no irrelevant things. - */ - public static boolean containsIrrelevantThings(Services services, - SequentFormula sf, - Set relevantThings) { - ContainsIrrelevantThingsVisitor visitor = new ContainsIrrelevantThingsVisitor(services, relevantThings); - sf.formula().execPostOrder(visitor); - return visitor.isContainsIrrelevantThings(); - } - - /** - * Utility class used by {@link QuerySideProofRule#containsIrrelevantThings(Services, SequentFormula, Set)}. - * @author Martin Hentschel - */ - protected static class ContainsIrrelevantThingsVisitor extends DefaultVisitor { - /** - * The {@link Services} to use. - */ - private Services services; - - /** - * The relevant things. - */ - private Set relevantThings; - - /** - * The result. - */ - boolean containsIrrelevantThings = false; - - /** - * Constructor. - * @param services The {@link Services} to use. - * @param relevantThings The relevant things. - */ - public ContainsIrrelevantThingsVisitor(Services services, Set relevantThings) { - this.services = services; - this.relevantThings = relevantThings; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Term visited) { - if (isRelevantThing(services, visited)) { - if (!SymbolicExecutionUtil.isSelect(services, visited) && - !SymbolicExecutionUtil.isBoolean(services, visited.op()) && - !SymbolicExecutionUtil.isNumber(visited.op())) { - if (!relevantThings.contains(visited.op())) { - containsIrrelevantThings = true; - } + } else if (term.op() instanceof Function) { + HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + if (SymbolicExecutionUtil.isHeap(term.op(), heapLDT)) { + return true; + } else { + KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(term.sort()); + return kjt != null; } - } - } - - /** - * Returns the result. - * @return The {@link SequentFormula} contains irrelevant things, {@code false} the {@link SequentFormula} contains no irrelevant things. - */ - public boolean isContainsIrrelevantThings() { - return containsIrrelevantThings; - } - } - - /** - * Starts a site proof for the given {@link Sequent}. - * @param proof The parent {@link Proof} of the site proof to do. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to prove. - * @return The proof result represented as {@link ApplyStrategyInfo} instance. - * @throws ProofInputException Occurred Exception - */ - public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve) throws ProofInputException { - return startSideProof(proof, - sideProofEnvironment, - sequentToProve, - StrategyProperties.METHOD_NONE, - StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, - StrategyProperties.SPLITTING_OFF); - } - - /** - * Starts a site proof for the given {@link Sequent}. - * @param proof The parent {@link Proof} of the site proof to do. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to prove. - * @return The proof result represented as {@link ApplyStrategyInfo} instance. - * @throws ProofInputException Occurred Exception - */ - public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - String methodTreatment, - String loopTreatment, - String queryTreatment, - String splittingOption) throws ProofInputException { - ProofStarter starter = createSideProof(sideProofEnvironment, sequentToProve, null); - return startSideProof(proof, starter, methodTreatment, loopTreatment, queryTreatment, splittingOption); - } - - /** - * Creates a new {@link ProofStarter} which contains a new site proof - * of the given {@link Proof}. - * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. - * @param sequentToProve The {@link Sequent} to proof in a new site proof. - * @param proofName An optional name for the newly created {@link Proof}. - * @return The created {@link ProofStarter} with the site proof. - * @throws ProofInputException Occurred Exception. - */ - public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - String proofName) throws ProofInputException { - return SideProofUtil.createSideProof(sideProofEnvironment, sequentToProve, proofName); - } - - /** - * Starts a site proof. - * @param proof The original {@link Proof}. - * @param starter The {@link ProofStarter} with the site proof. - * @param splittingOption The splitting option to use. - * @return The site proof result. - */ - public static ApplyStrategyInfo startSideProof(Proof proof, - ProofStarter starter, - String methodTreatment, - String loopTreatment, - String queryTreatment, - String splittingOption) { - assert starter != null; - starter.setMaxRuleApplications(10000); - StrategyProperties sp = proof != null && !proof.isDisposed() ? - proof.getSettings().getStrategySettings().getActiveStrategyProperties() : // Is a clone that can be modified - new StrategyProperties(); - StrategyProperties.setDefaultStrategyProperties(sp, false, true, true, false, false, false); - sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, methodTreatment); - sp.setProperty(StrategyProperties.LOOP_OPTIONS_KEY, loopTreatment); - sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, queryTreatment); - sp.setProperty(StrategyProperties.SPLITTING_OPTIONS_KEY, splittingOption); - sp.setProperty(StrategyProperties.QUANTIFIERS_OPTIONS_KEY, StrategyProperties.QUANTIFIERS_NON_SPLITTING); - starter.setStrategyProperties(sp); - // Execute proof in the current thread - return starter.start(); - } - - /** - * Extracts the value for the formula with the given {@link Operator} - * from the given {@link Goal}. - * @param goal The {@link Goal} to search the {@link Operator} in. - * @param operator The {@link Operator} for the formula which should be extracted. - * @return The value of the formula with the given {@link Operator}. - */ - public static Term extractOperatorValue(Goal goal, final Operator operator) { - assert goal != null; - return extractOperatorValue(goal.node(), operator); - } - - /** - * Extracts the value for the formula with the given {@link Operator} - * from the given {@link Node}. - * @param node The {@link Node} to search the {@link Operator} in. - * @param operator The {@link Operator} for the formula which should be extracted. - * @return The value of the formula with the given {@link Operator}. - */ - public static Term extractOperatorValue(Node node, final Operator operator) { - Term operatorTerm = extractOperatorTerm(node, operator); - return operatorTerm != null ? operatorTerm.sub(0) : null; - } - - /** - * Extracts the operator term for the formula with the given {@link Operator} - * from the site proof result ({@link ApplyStrategyInfo}). - * @param info The site proof result. - * @param operator The {@link Operator} for the formula which should be extracted. - * @return The operator term of the formula with the given {@link Operator}. - * @throws ProofInputException Occurred Exception. - */ - public static Term extractOperatorTerm(ApplyStrategyInfo info, Operator operator) throws ProofInputException { - // Make sure that valid parameters are given - assert info != null; - if (info.getProof().openGoals().size() != 1) { - throw new ProofInputException("Assumption that return value extraction has one goal does not hold because " + info.getProof().openGoals().size() + " goals are available."); - } - // Get node of open goal - return extractOperatorTerm(info.getProof().openGoals().head(), operator); - } - - /** - * Extracts the operator term for the formula with the given {@link Operator} - * from the given {@link Goal}. - * @param goal The {@link Goal} to search the {@link Operator} in. - * @param operator The {@link Operator} for the formula which should be extracted. - * @return The operator term of the formula with the given {@link Operator}. - */ - public static Term extractOperatorTerm(Goal goal, final Operator operator) { - assert goal != null; - return extractOperatorTerm(goal.node(), operator); - } - - /** - * Extracts the operator term for the formula with the given {@link Operator} - * from the given {@link Node}. - * @param node The {@link Node} to search the {@link Operator} in. - * @param operator The {@link Operator} for the formula which should be extracted. - * @return The operator term of the formula with the given {@link Operator}. - */ - public static Term extractOperatorTerm(Node node, final Operator operator) { - assert node != null; - // Search formula with the given operator in sequent (or in some cases below the updates) - SequentFormula sf = CollectionUtil.search(node.sequent(), new IFilter() { - @Override - public boolean select(SequentFormula element) { - Term term = element.formula(); - term = TermBuilder.goBelowUpdates(term); - return ObjectUtil.equals(term.op(), operator); - } - }); - if (sf != null) { - Term term = sf.formula(); - term = TermBuilder.goBelowUpdates(term); - return term; - } - else { - return null; - } - } - - /** - * Creates a copy of the {@link ProofEnvironment} of the given {@link Proof} - * which has his own {@link OneStepSimplifier} instance. Such copies are - * required for instance during parallel usage of site proofs because - * {@link OneStepSimplifier} has an internal state. - * @param source The {@link Proof} to copy its {@link ProofEnvironment}. - * @return The created {@link ProofEnvironment} which is a copy of the environment of the given {@link Proof} but with its own {@link OneStepSimplifier} instance. - */ - public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier(final Proof source, final boolean useSimplifyTermProfile) { - assert source != null; - assert !source.isDisposed(); - return cloneProofEnvironmentWithOwnOneStepSimplifier(source.getInitConfig(), useSimplifyTermProfile); - } - - /** - * Creates a copy of the {@link ProofEnvironment} of the given {@link Proof} - * which has his own {@link OneStepSimplifier} instance. Such copies are - * required for instance during parallel usage of site proofs because - * {@link OneStepSimplifier} has an internal state. - * @param sourceInitConfig The {@link InitConfig} to copy its {@link ProofEnvironment}. - * @return The created {@link ProofEnvironment} which is a copy of the environment of the given {@link Proof} but with its own {@link OneStepSimplifier} instance. - */ - @SuppressWarnings("unchecked") -public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier(final InitConfig sourceInitConfig, final boolean useSimplifyTermProfile) { - // Get required source instances - final RuleJustificationInfo sourceJustiInfo = sourceInitConfig.getJustifInfo(); - // Create new profile which has separate OneStepSimplifier instance - JavaProfile profile; - if (useSimplifyTermProfile) { - profile = new SimplifyTermProfile() { - @Override - protected ImmutableList computeTermLabelConfiguration() { - Profile sourceProfile = sourceInitConfig.getProfile(); - if (sourceProfile instanceof SymbolicExecutionJavaProfile) { - ImmutableList result = super.computeTermLabelConfiguration(); - result = result.prepend(SymbolicExecutionJavaProfile.getSymbolicExecutionTermLabelConfigurations(SymbolicExecutionJavaProfile.isTruthValueEvaluationEnabled(sourceInitConfig))); // Make sure that the term labels of symbolic execution are also supported by the new environment. - return result; - } - else { - return super.computeTermLabelConfiguration(); - } + } else { + return false; + } + } + + /** + * Checks if the given {@link SequentFormula} is a relevant condition. + * + * @param services The {@link Services} to use. + * @param initialSequent The initial {@link Sequent} of the side proof. + * @param relevantThingsInSequentToProve The relevant things found in the initial + * {@link Sequent}. + * @param sf The {@link SequentFormula} to check. + * @return {@code true} {@link SequentFormula} is relevant condition, {@code false} + * {@link SequentFormula} is not a relevant condition. + */ + public static boolean isIrrelevantCondition(Services services, Sequent initialSequent, + Set relevantThingsInSequentToProve, SequentFormula sf) { + return initialSequent.antecedent().contains(sf) || // Conditions which already exist in the + // initial sequent are irrelevant + initialSequent.succedent().contains(sf) || // Conditions which already exist in the + // initial sequent are irrelevant + // isInOrOfAntecedent(initialSequent, sf) || + containsModalityOrQuery(sf) || // Conditions with modalities or queries are + // irrelevant + containsIrrelevantThings(services, sf, relevantThingsInSequentToProve); // Conditions + // which + // contains + // not + // relevant + // things + // are + // irrelevant + } + + // public static boolean isInOrOfAntecedent(Sequent initialSequent, SequentFormula sf) { + // Term term = sf.formula(); + // boolean result = false; + // Iterator iter = initialSequent.antecedent().iterator(); + // while (!result && iter.hasNext()) { + // SequentFormula next = iter.next(); + // if (isInOr(next.formula(), term)) { + // result = true; + // } + // } + // return result; + // } + // + // public static boolean isInOr(Term term, Term toCheck) { + // if (term.op() == Junctor.OR) { + // boolean result = false; + // Iterator iter = term.subs().iterator(); + // while (!result && iter.hasNext()) { + // result = isInOr(iter.next(), toCheck); + // } + // return result; + // } + // else { + // return term == toCheck; + // } + // } + + /** + * Checks if the given {@link SequentFormula} contains irrelevant things (things which are not + * contained in the relevantThingsToProve and are no Java types) + * + * @param services The {@link Services} to use. + * @param sf The {@link SequentFormula} to check. + * @param relevantThings The relevant things. + * @return {@code true} The {@link SequentFormula} contains irrelevant things, {@code false} the + * {@link SequentFormula} contains no irrelevant things. + */ + public static boolean containsIrrelevantThings(Services services, SequentFormula sf, + Set relevantThings) { + ContainsIrrelevantThingsVisitor visitor = + new ContainsIrrelevantThingsVisitor(services, relevantThings); + sf.formula().execPostOrder(visitor); + return visitor.isContainsIrrelevantThings(); + } + + /** + * Utility class used by + * {@link QuerySideProofRule#containsIrrelevantThings(Services, SequentFormula, Set)}. + * + * @author Martin Hentschel + */ + protected static class ContainsIrrelevantThingsVisitor extends DefaultVisitor { + /** + * The {@link Services} to use. + */ + private Services services; + + /** + * The relevant things. + */ + private Set relevantThings; + + /** + * The result. + */ + boolean containsIrrelevantThings = false; + + /** + * Constructor. + * + * @param services The {@link Services} to use. + * @param relevantThings The relevant things. + */ + public ContainsIrrelevantThingsVisitor(Services services, Set relevantThings) { + this.services = services; + this.relevantThings = relevantThings; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Term visited) { + if (isRelevantThing(services, visited)) { + if (!SymbolicExecutionUtil.isSelect(services, visited) + && !SymbolicExecutionUtil.isBoolean(services, visited.op()) + && !SymbolicExecutionUtil.isNumber(visited.op())) { + if (!relevantThings.contains(visited.op())) { + containsIrrelevantThings = true; + } + } } - }; - } - else { - profile = new JavaProfile() { + } + + /** + * Returns the result. + * + * @return The {@link SequentFormula} contains irrelevant things, {@code false} the + * {@link SequentFormula} contains no irrelevant things. + */ + public boolean isContainsIrrelevantThings() { + return containsIrrelevantThings; + } + } + + /** + * Starts a site proof for the given {@link Sequent}. + * + * @param proof The parent {@link Proof} of the site proof to do. + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to prove. + * @return The proof result represented as {@link ApplyStrategyInfo} instance. + * @throws ProofInputException Occurred Exception + */ + public static ApplyStrategyInfo startSideProof(Proof proof, + ProofEnvironment sideProofEnvironment, Sequent sequentToProve) + throws ProofInputException { + return startSideProof(proof, sideProofEnvironment, sequentToProve, + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_OFF); + } + + /** + * Starts a site proof for the given {@link Sequent}. + * + * @param proof The parent {@link Proof} of the site proof to do. + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to prove. + * @return The proof result represented as {@link ApplyStrategyInfo} instance. + * @throws ProofInputException Occurred Exception + */ + public static ApplyStrategyInfo startSideProof(Proof proof, + ProofEnvironment sideProofEnvironment, Sequent sequentToProve, String methodTreatment, + String loopTreatment, String queryTreatment, String splittingOption) + throws ProofInputException { + ProofStarter starter = createSideProof(sideProofEnvironment, sequentToProve, null); + return startSideProof(proof, starter, methodTreatment, loopTreatment, queryTreatment, + splittingOption); + } + + /** + * Creates a new {@link ProofStarter} which contains a new site proof of the given + * {@link Proof}. + * + * @param sideProofEnvironment The given {@link ProofEnvironment} of the side proof. + * @param sequentToProve The {@link Sequent} to proof in a new site proof. + * @param proofName An optional name for the newly created {@link Proof}. + * @return The created {@link ProofStarter} with the site proof. + * @throws ProofInputException Occurred Exception. + */ + public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment, + Sequent sequentToProve, String proofName) throws ProofInputException { + return SideProofUtil.createSideProof(sideProofEnvironment, sequentToProve, proofName); + } + + /** + * Starts a site proof. + * + * @param proof The original {@link Proof}. + * @param starter The {@link ProofStarter} with the site proof. + * @param splittingOption The splitting option to use. + * @return The site proof result. + */ + public static ApplyStrategyInfo startSideProof(Proof proof, ProofStarter starter, + String methodTreatment, String loopTreatment, String queryTreatment, + String splittingOption) { + assert starter != null; + starter.setMaxRuleApplications(10000); + StrategyProperties sp = proof != null && !proof.isDisposed() + ? proof.getSettings().getStrategySettings().getActiveStrategyProperties() + : // Is a clone that can be modified + new StrategyProperties(); + StrategyProperties.setDefaultStrategyProperties(sp, false, true, true, false, false, false); + sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, methodTreatment); + sp.setProperty(StrategyProperties.LOOP_OPTIONS_KEY, loopTreatment); + sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, queryTreatment); + sp.setProperty(StrategyProperties.SPLITTING_OPTIONS_KEY, splittingOption); + sp.setProperty(StrategyProperties.QUANTIFIERS_OPTIONS_KEY, + StrategyProperties.QUANTIFIERS_NON_SPLITTING); + starter.setStrategyProperties(sp); + // Execute proof in the current thread + return starter.start(); + } + + /** + * Extracts the value for the formula with the given {@link Operator} from the given + * {@link Goal}. + * + * @param goal The {@link Goal} to search the {@link Operator} in. + * @param operator The {@link Operator} for the formula which should be extracted. + * @return The value of the formula with the given {@link Operator}. + */ + public static Term extractOperatorValue(Goal goal, final Operator operator) { + assert goal != null; + return extractOperatorValue(goal.node(), operator); + } + + /** + * Extracts the value for the formula with the given {@link Operator} from the given + * {@link Node}. + * + * @param node The {@link Node} to search the {@link Operator} in. + * @param operator The {@link Operator} for the formula which should be extracted. + * @return The value of the formula with the given {@link Operator}. + */ + public static Term extractOperatorValue(Node node, final Operator operator) { + Term operatorTerm = extractOperatorTerm(node, operator); + return operatorTerm != null ? operatorTerm.sub(0) : null; + } + + /** + * Extracts the operator term for the formula with the given {@link Operator} from the site + * proof result ({@link ApplyStrategyInfo}). + * + * @param info The site proof result. + * @param operator The {@link Operator} for the formula which should be extracted. + * @return The operator term of the formula with the given {@link Operator}. + * @throws ProofInputException Occurred Exception. + */ + public static Term extractOperatorTerm(ApplyStrategyInfo info, Operator operator) + throws ProofInputException { + // Make sure that valid parameters are given + assert info != null; + if (info.getProof().openGoals().size() != 1) { + throw new ProofInputException( + "Assumption that return value extraction has one goal does not hold because " + + info.getProof().openGoals().size() + " goals are available."); + } + // Get node of open goal + return extractOperatorTerm(info.getProof().openGoals().head(), operator); + } + + /** + * Extracts the operator term for the formula with the given {@link Operator} from the given + * {@link Goal}. + * + * @param goal The {@link Goal} to search the {@link Operator} in. + * @param operator The {@link Operator} for the formula which should be extracted. + * @return The operator term of the formula with the given {@link Operator}. + */ + public static Term extractOperatorTerm(Goal goal, final Operator operator) { + assert goal != null; + return extractOperatorTerm(goal.node(), operator); + } + + /** + * Extracts the operator term for the formula with the given {@link Operator} from the given + * {@link Node}. + * + * @param node The {@link Node} to search the {@link Operator} in. + * @param operator The {@link Operator} for the formula which should be extracted. + * @return The operator term of the formula with the given {@link Operator}. + */ + public static Term extractOperatorTerm(Node node, final Operator operator) { + assert node != null; + // Search formula with the given operator in sequent (or in some cases below the updates) + SequentFormula sf = CollectionUtil.search(node.sequent(), new IFilter() { @Override - protected ImmutableList computeTermLabelConfiguration() { - Profile sourceProfile = sourceInitConfig.getProfile(); - if (sourceProfile instanceof SymbolicExecutionJavaProfile) { - ImmutableList result = super.computeTermLabelConfiguration(); - result = result.prepend(SymbolicExecutionJavaProfile.getSymbolicExecutionTermLabelConfigurations(SymbolicExecutionJavaProfile.isTruthValueEvaluationEnabled(sourceInitConfig))); // Make sure that the term labels of symbolic execution are also supported by the new environment. - return result; - } - else { - return super.computeTermLabelConfiguration(); - } + public boolean select(SequentFormula element) { + Term term = element.formula(); + term = TermBuilder.goBelowUpdates(term); + return ObjectUtil.equals(term.op(), operator); + } + }); + if (sf != null) { + Term term = sf.formula(); + term = TermBuilder.goBelowUpdates(term); + return term; + } else { + return null; + } + } + + /** + * Creates a copy of the {@link ProofEnvironment} of the given {@link Proof} which has his own + * {@link OneStepSimplifier} instance. Such copies are required for instance during parallel + * usage of site proofs because {@link OneStepSimplifier} has an internal state. + * + * @param source The {@link Proof} to copy its {@link ProofEnvironment}. + * @return The created {@link ProofEnvironment} which is a copy of the environment of the given + * {@link Proof} but with its own {@link OneStepSimplifier} instance. + */ + public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier(final Proof source, + final boolean useSimplifyTermProfile) { + assert source != null; + assert !source.isDisposed(); + return cloneProofEnvironmentWithOwnOneStepSimplifier(source.getInitConfig(), + useSimplifyTermProfile); + } + + /** + * Creates a copy of the {@link ProofEnvironment} of the given {@link Proof} which has his own + * {@link OneStepSimplifier} instance. Such copies are required for instance during parallel + * usage of site proofs because {@link OneStepSimplifier} has an internal state. + * + * @param sourceInitConfig The {@link InitConfig} to copy its {@link ProofEnvironment}. + * @return The created {@link ProofEnvironment} which is a copy of the environment of the given + * {@link Proof} but with its own {@link OneStepSimplifier} instance. + */ + @SuppressWarnings("unchecked") + public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier( + final InitConfig sourceInitConfig, final boolean useSimplifyTermProfile) { + // Get required source instances + final RuleJustificationInfo sourceJustiInfo = sourceInitConfig.getJustifInfo(); + // Create new profile which has separate OneStepSimplifier instance + JavaProfile profile; + if (useSimplifyTermProfile) { + profile = new SimplifyTermProfile() { + @Override + protected ImmutableList computeTermLabelConfiguration() { + Profile sourceProfile = sourceInitConfig.getProfile(); + if (sourceProfile instanceof SymbolicExecutionJavaProfile) { + ImmutableList result = + super.computeTermLabelConfiguration(); + result = result.prepend(SymbolicExecutionJavaProfile + .getSymbolicExecutionTermLabelConfigurations( + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); // Make + // sure + // that + // the + // term + // labels + // of + // symbolic + // execution + // are + // also + // supported + // by + // the + // new + // environment. + return result; + } else { + return super.computeTermLabelConfiguration(); + } + } + }; + } else { + profile = new JavaProfile() { + @Override + protected ImmutableList computeTermLabelConfiguration() { + Profile sourceProfile = sourceInitConfig.getProfile(); + if (sourceProfile instanceof SymbolicExecutionJavaProfile) { + ImmutableList result = + super.computeTermLabelConfiguration(); + result = result.prepend(SymbolicExecutionJavaProfile + .getSymbolicExecutionTermLabelConfigurations( + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); // Make + // sure + // that + // the + // term + // labels + // of + // symbolic + // execution + // are + // also + // supported + // by + // the + // new + // environment. + return result; + } else { + return super.computeTermLabelConfiguration(); + } + } + }; + } + // Create new InitConfig + final InitConfig initConfig = + new InitConfig(sourceInitConfig.getServices().copy(profile, false)); + // Set modified taclet options in which runtime exceptions are banned. + Choice runtimeExceptionTreatment = new Choice("ban", "runtimeExceptions"); + ImmutableSet choices = SideProofUtil + .activateChoice(sourceInitConfig.getActivatedChoices(), runtimeExceptionTreatment); + initConfig.setActivatedChoices(choices); + // Initialize InitConfig with settings from the original InitConfig. + final ProofSettings clonedSettings = sourceInitConfig.getSettings() != null + ? new ProofSettings(sourceInitConfig.getSettings()) + : null; + initConfig.setSettings(clonedSettings); + initConfig.setTaclet2Builder( + (HashMap>) sourceInitConfig + .getTaclet2Builder().clone()); + initConfig.setTaclets(sourceInitConfig.getTaclets()); + // Create new ProofEnvironment and initialize it with values from initial one. + ProofEnvironment env = new ProofEnvironment(initConfig); + for (Taclet taclet : initConfig.activatedTaclets()) { + initConfig.getJustifInfo().addJustification(taclet, + sourceJustiInfo.getJustification(taclet)); + } + for (BuiltInRule rule : initConfig.builtInRules()) { + RuleJustification origJusti = sourceJustiInfo.getJustification(rule); + if (origJusti == null) { + assert rule instanceof OneStepSimplifier; + origJusti = AxiomJustification.INSTANCE; + } + initConfig.getJustifInfo().addJustification(rule, origJusti); + } + return env; + } + + /** + *

    + * Stores or disposes the {@link Proof} of the {@link ApplyStrategyInfo} in + * {@link SideProofStore#DEFAULT_INSTANCE}. + *

    + *

    + * This method should be called whenever a side proof is no longer needed and should be disposed + * or stored for debugging purposes. + *

    + * + * @param description The description. + * @param info The {@link ApplyStrategyInfo} to store or dispose its {@link Proof}. + */ + public static void disposeOrStore(String description, ApplyStrategyInfo info) { + if (info != null) { + if (SideProofStore.DEFAULT_INSTANCE.isEnabled()) { + SideProofStore.DEFAULT_INSTANCE.addProof(description, info.getProof()); + } else { + info.getProof().dispose(); } - }; - } - // Create new InitConfig - final InitConfig initConfig = new InitConfig(sourceInitConfig.getServices().copy(profile, false)); - // Set modified taclet options in which runtime exceptions are banned. - Choice runtimeExceptionTreatment = new Choice("ban", "runtimeExceptions"); - ImmutableSet choices = SideProofUtil.activateChoice(sourceInitConfig.getActivatedChoices(), - runtimeExceptionTreatment); - initConfig.setActivatedChoices(choices); - // Initialize InitConfig with settings from the original InitConfig. - final ProofSettings clonedSettings = sourceInitConfig.getSettings() != null ? new ProofSettings(sourceInitConfig.getSettings()) : null; - initConfig.setSettings(clonedSettings); - initConfig.setTaclet2Builder((HashMap>) sourceInitConfig.getTaclet2Builder().clone()); - initConfig.setTaclets(sourceInitConfig.getTaclets()); - // Create new ProofEnvironment and initialize it with values from initial one. - ProofEnvironment env = new ProofEnvironment(initConfig); - for (Taclet taclet : initConfig.activatedTaclets()) { - initConfig.getJustifInfo().addJustification(taclet, sourceJustiInfo.getJustification(taclet)); - } - for (BuiltInRule rule : initConfig.builtInRules()) { - RuleJustification origJusti = sourceJustiInfo.getJustification(rule); - if (origJusti == null) { - assert rule instanceof OneStepSimplifier; - origJusti = AxiomJustification.INSTANCE; - } - initConfig.getJustifInfo().addJustification(rule, origJusti); - } - return env; - } - - /** - *

    - * Stores or disposes the {@link Proof} of the {@link ApplyStrategyInfo} in {@link SideProofStore#DEFAULT_INSTANCE}. - *

    - *

    - * This method should be called whenever a side proof is no longer needed - * and should be disposed or stored for debugging purposes. - *

    - * @param description The description. - * @param info The {@link ApplyStrategyInfo} to store or dispose its {@link Proof}. - */ - public static void disposeOrStore(String description, ApplyStrategyInfo info) { - if (info != null) { - if (SideProofStore.DEFAULT_INSTANCE.isEnabled()) { - SideProofStore.DEFAULT_INSTANCE.addProof(description, info.getProof()); - } - else { - info.getProof().dispose(); - } - } - } + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionUtil.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionUtil.java index 3875c07ae40..20406608ec7 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionUtil.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util; import java.io.IOException; @@ -148,4036 +151,4390 @@ /** * Provides utility methods for symbolic execution with KeY. + * * @author Martin Hentschel */ public final class SymbolicExecutionUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(SymbolicExecutionUtil.class); - - - /** - * Key for the choice option "runtimeExceptions". - */ - public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS = "runtimeExceptions"; - - /** - * Value in choice option "runtimeExceptions" to ban exceptions. - */ - public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN = "runtimeExceptions:ban"; - - /** - * Value in choice option "runtimeExceptions" to allow exceptions. - */ - public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW = "runtimeExceptions:allow"; - - /** - * Name of {@link #RESULT_LABEL}. - */ - public static final Name RESULT_LABEL_NAME = new Name("RES"); - - /** - * Label attached to a {@link Term} to evaluate in a side proof. - */ - public static final TermLabel RESULT_LABEL = new ParameterlessTermLabel(RESULT_LABEL_NAME); - - /** - * Name of {@link #LOOP_BODY_LABEL}. - */ - public static final Name LOOP_BODY_LABEL_NAME = new Name("LoopBody"); - - /** - * Label attached to the modality which executes a loop body in branch - * "Body Preserves Invariant" of applied "Loop Invariant" rules. - */ - public static final TermLabel LOOP_BODY_LABEL = new ParameterlessTermLabel(LOOP_BODY_LABEL_NAME); - - /** - * Name of {@link #LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL}. - */ - public static final Name LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME = new Name("LoopInvariantNormalBehavior"); - - /** - * Label attached to the implication when a loop body execution terminated - * normally without any exceptions, returns or breaks in branch - * "Body Preserves Invariant" of applied "Loop Invariant" rules to show the - * loop invariant. - */ - public static final TermLabel LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL = new ParameterlessTermLabel(LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME); - - /** - * Forbid instances. - */ - private SymbolicExecutionUtil() { - } - - /** - * Simplifies the given {@link Term} in a side proof. - * @param initConfig The {@link InitConfig} to use. - * @param term The {@link Term} to simplify. - * @return The simplified {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public static Term simplify(InitConfig initConfig, - Term term) throws ProofInputException { - return simplify(initConfig, null, term); - } - - /** - * Simplifies the given {@link Term} in a side proof. - * @param parentProof The parent {@link Proof}. - * @param term The {@link Term} to simplify. - * @return The simplified {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public static Term simplify(Proof parentProof, - Term term) throws ProofInputException { - assert !parentProof.isDisposed(); - return simplify(parentProof.getInitConfig(), parentProof, term); - } - - /** - * Simplifies the given {@link Term} in a side proof. - * @param initConfig The {@link InitConfig} to use. - * @param parentProof The parent {@link Proof} which provides the {@link StrategySettings}. - * @param term The {@link Term} to simplify. - * @return The simplified {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - public static Term simplify(InitConfig initConfig, - Proof parentProof, - Term term) throws ProofInputException { - final Services services = initConfig.getServices(); - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - // Create Sequent to prove - Sequent sequentToProve = Sequent.EMPTY_SEQUENT.addFormula(new SequentFormula(term), false, true).sequent(); - // Return created Sequent and the used predicate to identify the value interested in. - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(parentProof, sideProofEnv, sequentToProve); - try { - // The simplified formula is the conjunction of all open goals - ImmutableList openGoals = info.getProof().openEnabledGoals(); - final TermBuilder tb = services.getTermBuilder(); - if (openGoals.isEmpty()) { - return tb.tt(); - } - else { - ImmutableList goalImplications = ImmutableSLList.nil(); - for (Goal goal : openGoals) { - Term goalImplication = sequentToImplication(goal.sequent(), goal.proof().getServices()); - goalImplication = tb.not(goalImplication); - goalImplications = goalImplications.append(goalImplication); + private static final Logger LOGGER = LoggerFactory.getLogger(SymbolicExecutionUtil.class); + + + /** + * Key for the choice option "runtimeExceptions". + */ + public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS = "runtimeExceptions"; + + /** + * Value in choice option "runtimeExceptions" to ban exceptions. + */ + public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN = + "runtimeExceptions:ban"; + + /** + * Value in choice option "runtimeExceptions" to allow exceptions. + */ + public static final String CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW = + "runtimeExceptions:allow"; + + /** + * Name of {@link #RESULT_LABEL}. + */ + public static final Name RESULT_LABEL_NAME = new Name("RES"); + + /** + * Label attached to a {@link Term} to evaluate in a side proof. + */ + public static final TermLabel RESULT_LABEL = new ParameterlessTermLabel(RESULT_LABEL_NAME); + + /** + * Name of {@link #LOOP_BODY_LABEL}. + */ + public static final Name LOOP_BODY_LABEL_NAME = new Name("LoopBody"); + + /** + * Label attached to the modality which executes a loop body in branch "Body Preserves + * Invariant" of applied "Loop Invariant" rules. + */ + public static final TermLabel LOOP_BODY_LABEL = + new ParameterlessTermLabel(LOOP_BODY_LABEL_NAME); + + /** + * Name of {@link #LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL}. + */ + public static final Name LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME = + new Name("LoopInvariantNormalBehavior"); + + /** + * Label attached to the implication when a loop body execution terminated normally without any + * exceptions, returns or breaks in branch "Body Preserves Invariant" of applied "Loop + * Invariant" rules to show the loop invariant. + */ + public static final TermLabel LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL = + new ParameterlessTermLabel(LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL_NAME); + + /** + * Forbid instances. + */ + private SymbolicExecutionUtil() {} + + /** + * Simplifies the given {@link Term} in a side proof. + * + * @param initConfig The {@link InitConfig} to use. + * @param term The {@link Term} to simplify. + * @return The simplified {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public static Term simplify(InitConfig initConfig, Term term) throws ProofInputException { + return simplify(initConfig, null, term); + } + + /** + * Simplifies the given {@link Term} in a side proof. + * + * @param parentProof The parent {@link Proof}. + * @param term The {@link Term} to simplify. + * @return The simplified {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public static Term simplify(Proof parentProof, Term term) throws ProofInputException { + assert !parentProof.isDisposed(); + return simplify(parentProof.getInitConfig(), parentProof, term); + } + + /** + * Simplifies the given {@link Term} in a side proof. + * + * @param initConfig The {@link InitConfig} to use. + * @param parentProof The parent {@link Proof} which provides the {@link StrategySettings}. + * @param term The {@link Term} to simplify. + * @return The simplified {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + public static Term simplify(InitConfig initConfig, Proof parentProof, Term term) + throws ProofInputException { + final Services services = initConfig.getServices(); + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(initConfig, true); // New + // OneStepSimplifier + // is required + // because it has + // an internal + // state and the + // default + // instance can't + // be used + // parallel. + // Create Sequent to prove + Sequent sequentToProve = + Sequent.EMPTY_SEQUENT.addFormula(new SequentFormula(term), false, true).sequent(); + // Return created Sequent and the used predicate to identify the value interested in. + ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(parentProof, + sideProofEnv, sequentToProve); + try { + // The simplified formula is the conjunction of all open goals + ImmutableList openGoals = info.getProof().openEnabledGoals(); + final TermBuilder tb = services.getTermBuilder(); + if (openGoals.isEmpty()) { + return tb.tt(); + } else { + ImmutableList goalImplications = ImmutableSLList.nil(); + for (Goal goal : openGoals) { + Term goalImplication = + sequentToImplication(goal.sequent(), goal.proof().getServices()); + goalImplication = tb.not(goalImplication); + goalImplications = goalImplications.append(goalImplication); + } + return tb.not(tb.or(goalImplications)); } - return tb.not(tb.or(goalImplications)); - } - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Simplification of " + ProofSaver.printAnything(term, services), info); - } - } - - /** - * Converts the given {@link Sequent} into an implication. - * @param sequent The {@link Sequent} to convert. - * @param services The {@link Services} to use. - * @return The created implication. - */ - public static Term sequentToImplication(Sequent sequent, Services services) { - if (sequent != null) { - ImmutableList antecedents = listSemisequentTerms(sequent.antecedent()); - ImmutableList succedents = listSemisequentTerms(sequent.succedent()); - // Construct branch condition from created antecedent and succedent terms as new implication - Term left = services.getTermBuilder().and(antecedents); - Term right = services.getTermBuilder().or(succedents); - return services.getTermBuilder().imp(left, right); - } - else { - return services.getTermBuilder().tt(); - } - } - - /** - * Lists the {@link Term}s contained in the given {@link Semisequent}. - * @param semisequent The {@link Semisequent} to list terms of. - * @return The list with all contained {@link Term}s. - */ - public static ImmutableList listSemisequentTerms(Semisequent semisequent) { - ImmutableList terms = ImmutableSLList.nil(); - if (semisequent != null) { - for (SequentFormula sf : semisequent) { - terms = terms.append(sf.formula()); - } - } - return terms; - } - - /** - * Improves the {@link Term} to increase its readability. - * The following changes will be performed: - *
      - *
    • {@code a < 1 + b} => {@code a <= b}
    • - *
    • {@code a < b + 1} => {@code a <= b}
    • - * - *
    • {@code a >= 1 + b} => {@code a > b}
    • - *
    • {@code a >= b + 1} => {@code a > b}
    • - * - *
    • {@code a <= -1 + b} => {@code a < b}
    • - *
    • {@code a <= b + -1} => {@code a < b}
    • - *
    • {@code a <= b - 1} => {@code a < b}
    • - * - *
    • {@code a > -1 + b} => {@code a >= b}
    • - *
    • {@code a > b + -1} => {@code a >= b}
    • - *
    • {@code a > b - 1} => {@code a >= b}
    • - * - *
    • {@code a >= 1 + b} => {@code a > b}
    • - *
    • {@code a >= b + 1} => {@code a > b}
    • - *
    • {@code !a >= b} => {@code a < b}
    • - *
    • {@code !a > b} => {@code a <= b}
    • - *
    • {@code !a <= b} => {@code a > b}
    • - *
    • {@code !a < b} => {@code a >= b}
    • - *
    - * @param term The {@link Term} to improve. - * @param services The {@link Services} to use. - * @return The improved {@link Term} or the {@link Term} itself if no improvements are possible. - */ - public static Term improveReadability(Term term, Services services) { - if (term != null && services != null) { - IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); - term = improveReadabilityRecursive(term, services, integerLDT); - } - return term; - } - - /** - * Helper method of {@link #improveReadability(Term, Services)}. - * @param term The {@link Term} to improve. - * @param services The {@link Services} to use. - * @param integerLDT The {@link IntegerLDT} to use. - * @return The improved {@link Term} or the {@link Term} itself if no improvements are possible. - */ - private static Term improveReadabilityRecursive(Term term, - Services services, - IntegerLDT integerLDT) { - // Improve children - boolean subChanged = false; - List newSubs = new LinkedList(); - for (Term sub : term.subs()) { - Term newSub = improveReadabilityRecursive(sub, services, integerLDT); - if (newSub != sub) { - newSubs.add(newSub); - subChanged = true; - } - else { - newSubs.add(sub); - } - } - if (subChanged) { - term = services.getTermFactory().createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), term.getLabels()); - } - // Improve readability: a < 1 + b, a < b + 1 - final TermBuilder tb = services.getTermBuilder(); - if (term.op() == integerLDT.getLessThan()) { - Term subOne = term.sub(1); - if (subOne.op() == integerLDT.getAdd()) { - if (isOne(subOne.sub(0), integerLDT)) { - term = tb.leq(term.sub(0), subOne.sub(1)); + } finally { + SymbolicExecutionSideProofUtil.disposeOrStore( + "Simplification of " + ProofSaver.printAnything(term, services), info); + } + } + + /** + * Converts the given {@link Sequent} into an implication. + * + * @param sequent The {@link Sequent} to convert. + * @param services The {@link Services} to use. + * @return The created implication. + */ + public static Term sequentToImplication(Sequent sequent, Services services) { + if (sequent != null) { + ImmutableList antecedents = listSemisequentTerms(sequent.antecedent()); + ImmutableList succedents = listSemisequentTerms(sequent.succedent()); + // Construct branch condition from created antecedent and succedent terms as new + // implication + Term left = services.getTermBuilder().and(antecedents); + Term right = services.getTermBuilder().or(succedents); + return services.getTermBuilder().imp(left, right); + } else { + return services.getTermBuilder().tt(); + } + } + + /** + * Lists the {@link Term}s contained in the given {@link Semisequent}. + * + * @param semisequent The {@link Semisequent} to list terms of. + * @return The list with all contained {@link Term}s. + */ + public static ImmutableList listSemisequentTerms(Semisequent semisequent) { + ImmutableList terms = ImmutableSLList.nil(); + if (semisequent != null) { + for (SequentFormula sf : semisequent) { + terms = terms.append(sf.formula()); } - else if (isOne(subOne.sub(1), integerLDT)) { - term = tb.leq(term.sub(0), subOne.sub(0)); + } + return terms; + } + + /** + * Improves the {@link Term} to increase its readability. The following changes will be + * performed: + *
      + *
    • {@code a < 1 + b} => {@code a <= b}
    • + *
    • {@code a < b + 1} => {@code a <= b}
    • + * + *
    • {@code a >= 1 + b} => {@code a > b}
    • + *
    • {@code a >= b + 1} => {@code a > b}
    • + * + *
    • {@code a <= -1 + b} => {@code a < b}
    • + *
    • {@code a <= b + -1} => {@code a < b}
    • + *
    • {@code a <= b - 1} => {@code a < b}
    • + * + *
    • {@code a > -1 + b} => {@code a >= b}
    • + *
    • {@code a > b + -1} => {@code a >= b}
    • + *
    • {@code a > b - 1} => {@code a >= b}
    • + * + *
    • {@code a >= 1 + b} => {@code a > b}
    • + *
    • {@code a >= b + 1} => {@code a > b}
    • + *
    • {@code !a >= b} => {@code a < b}
    • + *
    • {@code !a > b} => {@code a <= b}
    • + *
    • {@code !a <= b} => {@code a > b}
    • + *
    • {@code !a < b} => {@code a >= b}
    • + *
    + * + * @param term The {@link Term} to improve. + * @param services The {@link Services} to use. + * @return The improved {@link Term} or the {@link Term} itself if no improvements are possible. + */ + public static Term improveReadability(Term term, Services services) { + if (term != null && services != null) { + IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + term = improveReadabilityRecursive(term, services, integerLDT); + } + return term; + } + + /** + * Helper method of {@link #improveReadability(Term, Services)}. + * + * @param term The {@link Term} to improve. + * @param services The {@link Services} to use. + * @param integerLDT The {@link IntegerLDT} to use. + * @return The improved {@link Term} or the {@link Term} itself if no improvements are possible. + */ + private static Term improveReadabilityRecursive(Term term, Services services, + IntegerLDT integerLDT) { + // Improve children + boolean subChanged = false; + List newSubs = new LinkedList(); + for (Term sub : term.subs()) { + Term newSub = improveReadabilityRecursive(sub, services, integerLDT); + if (newSub != sub) { + newSubs.add(newSub); + subChanged = true; + } else { + newSubs.add(sub); } - } - } - // Improve readability: a >= 1 + b, a >= b + 1 - else if (term.op() == integerLDT.getGreaterOrEquals()) { - Term subOne = term.sub(1); - if (subOne.op() == integerLDT.getAdd()) { - if (isOne(subOne.sub(0), integerLDT)) { - term = tb.gt(term.sub(0), subOne.sub(1)); + } + if (subChanged) { + term = services.getTermFactory().createTerm(term.op(), + new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), + term.getLabels()); + } + // Improve readability: a < 1 + b, a < b + 1 + final TermBuilder tb = services.getTermBuilder(); + if (term.op() == integerLDT.getLessThan()) { + Term subOne = term.sub(1); + if (subOne.op() == integerLDT.getAdd()) { + if (isOne(subOne.sub(0), integerLDT)) { + term = tb.leq(term.sub(0), subOne.sub(1)); + } else if (isOne(subOne.sub(1), integerLDT)) { + term = tb.leq(term.sub(0), subOne.sub(0)); + } } - else if (isOne(subOne.sub(1), integerLDT)) { - term = tb.gt(term.sub(0), subOne.sub(0)); + } + // Improve readability: a >= 1 + b, a >= b + 1 + else if (term.op() == integerLDT.getGreaterOrEquals()) { + Term subOne = term.sub(1); + if (subOne.op() == integerLDT.getAdd()) { + if (isOne(subOne.sub(0), integerLDT)) { + term = tb.gt(term.sub(0), subOne.sub(1)); + } else if (isOne(subOne.sub(1), integerLDT)) { + term = tb.gt(term.sub(0), subOne.sub(0)); + } } - } - } - // Improve readability: a <= -1 + b, a <= 1 + -b, a <= 1 - b - else if (term.op() == integerLDT.getLessOrEquals()) { - Term subOne = term.sub(1); - if (subOne.op() == integerLDT.getAdd()) { - if (isMinusOne(subOne.sub(0), integerLDT)) { - term = tb.lt(term.sub(0), subOne.sub(1)); + } + // Improve readability: a <= -1 + b, a <= 1 + -b, a <= 1 - b + else if (term.op() == integerLDT.getLessOrEquals()) { + Term subOne = term.sub(1); + if (subOne.op() == integerLDT.getAdd()) { + if (isMinusOne(subOne.sub(0), integerLDT)) { + term = tb.lt(term.sub(0), subOne.sub(1)); + } else if (isMinusOne(subOne.sub(1), integerLDT)) { + term = tb.lt(term.sub(0), subOne.sub(0)); + } + } else if (subOne.op() == integerLDT.getSub()) { + if (isOne(subOne.sub(1), integerLDT)) { + term = tb.lt(term.sub(0), subOne.sub(0)); + } } - else if (isMinusOne(subOne.sub(1), integerLDT)) { - term = tb.lt(term.sub(0), subOne.sub(0)); + } + // Improve readability: a > -1 + b, a > 1 + -b, a > 1 - b + else if (term.op() == integerLDT.getGreaterThan()) { + Term subOne = term.sub(1); + if (subOne.op() == integerLDT.getAdd()) { + if (isMinusOne(subOne.sub(0), integerLDT)) { + term = tb.geq(term.sub(0), subOne.sub(1)); + } else if (isMinusOne(subOne.sub(1), integerLDT)) { + term = tb.geq(term.sub(0), subOne.sub(0)); + } + } else if (subOne.op() == integerLDT.getSub()) { + if (isOne(subOne.sub(1), integerLDT)) { + term = tb.geq(term.sub(0), subOne.sub(0)); + } } - } - else if (subOne.op() == integerLDT.getSub()) { - if (isOne(subOne.sub(1), integerLDT)) { - term = tb.lt(term.sub(0), subOne.sub(0)); + } + // Improve readability: !a >= b, !a > b, !a <= b, !a < b + else if (term.op() == Junctor.NOT) { + Term sub = term.sub(0); + if (sub.op() == integerLDT.getLessOrEquals()) { + term = tb.gt(sub.sub(0), sub.sub(1)); + } else if (sub.op() == integerLDT.getLessThan()) { + term = tb.geq(sub.sub(0), sub.sub(1)); + } else if (sub.op() == integerLDT.getGreaterOrEquals()) { + term = tb.lt(sub.sub(0), sub.sub(1)); + } else if (sub.op() == integerLDT.getGreaterThan()) { + term = tb.leq(sub.sub(0), sub.sub(1)); } - } - } - // Improve readability: a > -1 + b, a > 1 + -b, a > 1 - b - else if (term.op() == integerLDT.getGreaterThan()) { - Term subOne = term.sub(1); - if (subOne.op() == integerLDT.getAdd()) { - if (isMinusOne(subOne.sub(0), integerLDT)) { - term = tb.geq(term.sub(0), subOne.sub(1)); + } + return term; + } + + /** + * Checks if the given term represent the number one + * + * @param subOne the term to be checked + * @param integerLDT the LDT for integers + * @return true if the term represents the one + */ + private static boolean isOne(Term subOne, IntegerLDT integerLDT) { + return subOne.equalsModIrrelevantTermLabels(integerLDT.one()); + } + + /** + * Checks if the given {@link Term} represents the integer constant {@code -1}. + * + * @param term The {@link Term} to check. + * @param integerLDT The {@link IntegerLDT} to use. + * @return {@code true} {@link Term} represents {@code -1}, {@code false} {@link Term} is + * something else. + */ + private static boolean isMinusOne(Term term, IntegerLDT integerLDT) { + if (term.op() == integerLDT.getNumberSymbol()) { + term = term.sub(0); + if (term.op() == integerLDT.getNegativeNumberSign()) { + term = term.sub(0); + if (term.op() == integerLDT.getNumberLiteralFor(1)) { + term = term.sub(0); + if (term.op() == integerLDT.getNumberTerminator()) { + return true; + } + } } - else if (isMinusOne(subOne.sub(1), integerLDT)) { - term = tb.geq(term.sub(0), subOne.sub(0)); + } + return false; + } + + /** + * Creates a {@link Sequent} which can be used in site proofs to extract the return value of the + * given {@link IProgramVariable} from the sequent of the given {@link Node}. + * + * @param services The {@link Services} to use. + * @param contextObjectType The type of the current object (this reference). + * @param contextMethod The current method. + * @param contextObject The current object (this reference). + * @param methodReturnNode The method return {@link Node} which provides the sequent to extract + * updates and return expression from. + * @param methodCallEmptyNode The method call empty {@link Node} which provides the sequent to + * start site proof in. + * @param variable The {@link IProgramVariable} of the value which is interested. + * @return The created {@link SiteProofVariableValueInput} with the created sequent and the + * predicate which will contain the value. + */ + public static SiteProofVariableValueInput createExtractReturnVariableValueSequent( + Services services, TypeReference contextObjectType, IProgramMethod contextMethod, + ReferencePrefix contextObject, Node methodReturnNode, Node methodCallEmptyNode, + IProgramVariable variable) { + // Create execution context in that the method was called. + IExecutionContext context = + new ExecutionContext(contextObjectType, contextMethod, contextObject); + // Create sequent + return createExtractReturnVariableValueSequent(services, context, methodReturnNode, + methodCallEmptyNode, variable); + } + + /** + * Creates a {@link Sequent} which can be used in site proofs to extract the return value of the + * given {@link IProgramVariable} from the sequent of the given {@link Node}. + * + * @param services The {@link Services} to use. + * @param context The {@link IExecutionContext} that defines the current object (this + * reference). + * @param methodReturnNode The method return {@link Node} which provides the sequent to extract + * updates and return expression from. + * @param methodCallEmptyNode The method call empty {@link Node} which provides the sequent to + * start site proof in. + * @param variable The {@link IProgramVariable} of the value which is interested. + * @return The created {@link SiteProofVariableValueInput} with the created sequent and the + * predicate which will contain the value. + */ + public static SiteProofVariableValueInput createExtractReturnVariableValueSequent( + Services services, IExecutionContext context, Node methodReturnNode, + Node methodCallEmptyNode, IProgramVariable variable) { + // Make sure that correct parameters are given + assert context != null; + assert methodReturnNode != null; + assert methodCallEmptyNode != null; + assert variable instanceof ProgramVariable; + // Create method frame which will be executed in site proof + Statement originalReturnStatement = + (Statement) methodReturnNode.getNodeInfo().getActiveStatement(); + MethodFrame newMethodFrame = + new MethodFrame(variable, context, new StatementBlock(originalReturnStatement)); + JavaBlock newJavaBlock = JavaBlock.createJavaBlock(new StatementBlock(newMethodFrame)); + // Create predicate which will be used in formulas to store the value interested in. + Function newPredicate = + new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), + Sort.FORMULA, variable.sort()); + // Create formula which contains the value interested in. + Term newTerm = services.getTermBuilder().func(newPredicate, + services.getTermBuilder().var((ProgramVariable) variable)); + // Combine method frame with value formula in a modality. + Term modalityTerm = services.getTermBuilder().dia(newJavaBlock, newTerm); + // Get the updates from the return node which includes the value interested in. + Term originalModifiedFormula = + methodReturnNode.getAppliedRuleApp().posInOccurrence().sequentFormula().formula(); + ImmutableList originalUpdates = + TermBuilder.goBelowUpdates2(originalModifiedFormula).first; + // Create Sequent to prove with new succedent. + Sequent sequentToProve = createSequentToProveWithNewSuccedent(methodCallEmptyNode, null, + modalityTerm, originalUpdates, false); + // Return created sequent and the used predicate to identify the value interested in. + return new SiteProofVariableValueInput(sequentToProve, newPredicate); + } + + /** + * Creates a {@link Sequent} which can be used in site proofs to extract the value of the given + * {@link IProgramVariable} from the sequent of the given {@link Node}. + * + * @param services The {@link Services} to use. + * @param node The original {@link Node} which provides the sequent to extract from. + * @param pio The {@link PosInOccurrence} of the SE modality. + * @param additionalConditions Optional additional conditions. + * @param variable The {@link IProgramVariable} of the value which is interested. + * @return The created {@link SiteProofVariableValueInput} with the created sequent and the + * predicate which will contain the value. + */ + public static SiteProofVariableValueInput createExtractVariableValueSequent(Services services, + Node node, PosInOccurrence pio, Term additionalConditions, IProgramVariable variable) { + // Make sure that correct parameters are given + assert node != null; + assert variable instanceof ProgramVariable; + // Create predicate which will be used in formulas to store the value interested in. + Function newPredicate = + new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), + Sort.FORMULA, variable.sort()); + // Create formula which contains the value interested in. + Term newTerm = services.getTermBuilder().func(newPredicate, + services.getTermBuilder().var((ProgramVariable) variable)); + // Create Sequent to prove with new succedent. + Sequent sequentToProve = createSequentToProveWithNewSuccedent(node, pio, + additionalConditions, newTerm, false); + // Return created sequent and the used predicate to identify the value interested in. + return new SiteProofVariableValueInput(sequentToProve, newPredicate); + } + + /** + * Creates a {@link Sequent} which can be used in site proofs to extract the value of the given + * {@link IProgramVariable} from the sequent of the given {@link Node}. + * + * @param sideProofServices The {@link Services} of the side proof to use. + * @param node The original {@link Node} which provides the sequent to extract from. + * @param pio The {@link PosInOccurrence} of the modality or its updates. + * @param additionalConditions Additional conditions to add to the antecedent. + * @param term The new succedent term. + * @param keepUpdates {@code true} keep updates, {@code false} throw updates away. + * @return The created {@link SiteProofVariableValueInput} with the created sequent and the + * predicate which will contain the value. + */ + public static SiteProofVariableValueInput createExtractTermSequent(Services sideProofServices, + Node node, PosInOccurrence pio, Term additionalConditions, Term term, + boolean keepUpdates) { + // Make sure that correct parameters are given + assert node != null; + assert term != null; + // Create predicate which will be used in formulas to store the value interested in. + Function newPredicate = new Function( + new Name(sideProofServices.getTermBuilder().newName("ResultPredicate")), + Sort.FORMULA, term.sort()); + // Create formula which contains the value interested in. + Term newTerm = sideProofServices.getTermBuilder().func(newPredicate, term); + // Create Sequent to prove with new succedent. + Sequent sequentToProve = keepUpdates + ? createSequentToProveWithNewSuccedent(node, pio, additionalConditions, newTerm, + false) + : createSequentToProveWithNewSuccedent(node, pio, additionalConditions, newTerm, + null, false); + // Return created sequent and the used predicate to identify the value interested in. + return new SiteProofVariableValueInput(sequentToProve, newPredicate); + } + + /** + * Helper class which represents the return value of + * {@link ExecutionMethodReturn#createExtractReturnVariableValueSequent(TypeReference, ReferencePrefix, Node, IProgramVariable)} + * and + * {@link ExecutionMethodReturn#createExtractVariableValueSequent(IExecutionContext, Node, IProgramVariable)}. + * + * @author Martin Hentschel + */ + public static class SiteProofVariableValueInput { + /** + * The sequent to prove. + */ + private Sequent sequentToProve; + + /** + * The {@link Operator} which is the predicate that contains the value interested in. + */ + private Operator operator; + + /** + * Constructor. + * + * @param sequentToProve he sequent to prove. + * @param operator The {@link Operator} which is the predicate that contains the value + * interested in. + */ + public SiteProofVariableValueInput(Sequent sequentToProve, Operator operator) { + super(); + this.sequentToProve = sequentToProve; + this.operator = operator; + } + + /** + * Returns the sequent to prove. + * + * @return The sequent to prove. + */ + public Sequent getSequentToProve() { + return sequentToProve; + } + + /** + * Returns the {@link Operator} which is the predicate that contains the value interested + * in. + * + * @return The {@link Operator} which is the predicate that contains the value interested + * in. + */ + public Operator getOperator() { + return operator; + } + } + + /** + * Checks if the given {@link Term} represents a heap update, in particular a store or create + * operation on a heap. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to check. + * @return {@code true} is heap update, {@code false} is something else. + */ + public static boolean isHeapUpdate(Services services, Term term) { + boolean heapUpdate = false; + if (term != null) { + ImmutableArray subs = term.subs(); + if (subs.size() == 1) { + Term sub = subs.get(0); + if (sub.op() == services.getTypeConverter().getHeapLDT().getStore() + || sub.op() == services.getTypeConverter().getHeapLDT().getCreate()) { + heapUpdate = true; + } } - } - else if (subOne.op() == integerLDT.getSub()) { - if (isOne(subOne.sub(1), integerLDT)) { - term = tb.geq(term.sub(0), subOne.sub(0)); + } + return heapUpdate; + } + + /** + * Checks if it is right now possible to compute the variables of the given + * {@link IExecutionNode} via {@link IExecutionNode#getVariables()}. + * + * @param node The {@link IExecutionNode} to check. + * @param services The {@link Services} to use. + * @return {@code true} right now it is possible to compute variables, {@code false} it is not + * possible to compute variables. + * @throws ProofInputException Occurred Exception. + */ + public static boolean canComputeVariables(IExecutionNode node, Services services) + throws ProofInputException { + return node != null && !node.isDisposed() + && !services.getTermBuilder().ff().equals(node.getPathCondition()); + } + + /** + * Creates for the given {@link IExecutionNode} the contained {@link IExecutionConstraint}s. + * + * @param node The {@link IExecutionNode} to create constraints for. + * @return The created {@link IExecutionConstraint}s. + */ + public static IExecutionConstraint[] createExecutionConstraints(IExecutionNode node) { + if (node != null && !node.isDisposed()) { + TermBuilder tb = node.getServices().getTermBuilder(); + List constraints = new LinkedList(); + Node proofNode = node.getProofNode(); + Sequent sequent = proofNode.sequent(); + for (SequentFormula sf : sequent.antecedent()) { + if (!containsSymbolicExecutionLabel(sf.formula())) { + constraints.add(new ExecutionConstraint(node.getSettings(), proofNode, + node.getModalityPIO(), sf.formula())); + } } - } - } - // Improve readability: !a >= b, !a > b, !a <= b, !a < b - else if (term.op() == Junctor.NOT) { - Term sub = term.sub(0); - if (sub.op() == integerLDT.getLessOrEquals()) { - term = tb.gt(sub.sub(0), sub.sub(1)); - } - else if (sub.op() == integerLDT.getLessThan()) { - term = tb.geq(sub.sub(0), sub.sub(1)); - } - else if (sub.op() == integerLDT.getGreaterOrEquals()) { - term = tb.lt(sub.sub(0), sub.sub(1)); - } - else if (sub.op() == integerLDT.getGreaterThan()) { - term = tb.leq(sub.sub(0), sub.sub(1)); - } - } - return term; - } - - /** - * Checks if the given term represent the number one - * @param subOne the term to be checked - * @param integerLDT the LDT for integers - * @return true if the term represents the one - */ - private static boolean isOne(Term subOne, IntegerLDT integerLDT) { - return subOne.equalsModIrrelevantTermLabels(integerLDT.one()); - } - - /** - * Checks if the given {@link Term} represents the integer constant {@code -1}. - * @param term The {@link Term} to check. - * @param integerLDT The {@link IntegerLDT} to use. - * @return {@code true} {@link Term} represents {@code -1}, {@code false} {@link Term} is something else. - */ - private static boolean isMinusOne(Term term, IntegerLDT integerLDT) { - if (term.op() == integerLDT.getNumberSymbol()) { - term = term.sub(0); - if (term.op() == integerLDT.getNegativeNumberSign()) { - term = term.sub(0); - if (term.op() == integerLDT.getNumberLiteralFor(1)) { - term = term.sub(0); - if (term.op() == integerLDT.getNumberTerminator()) { - return true; - } + for (SequentFormula sf : sequent.succedent()) { + if (!containsSymbolicExecutionLabel(sf.formula())) { + constraints.add(new ExecutionConstraint(node.getSettings(), proofNode, + node.getModalityPIO(), tb.not(sf.formula()))); + } } - } - } - return false; - } - - /** - * Creates a {@link Sequent} which can be used in site proofs to - * extract the return value of the given {@link IProgramVariable} from the - * sequent of the given {@link Node}. - * @param services The {@link Services} to use. - * @param contextObjectType The type of the current object (this reference). - * @param contextMethod The current method. - * @param contextObject The current object (this reference). - * @param methodReturnNode The method return {@link Node} which provides the sequent to extract updates and return expression from. - * @param methodCallEmptyNode The method call empty {@link Node} which provides the sequent to start site proof in. - * @param variable The {@link IProgramVariable} of the value which is interested. - * @return The created {@link SiteProofVariableValueInput} with the created sequent and the predicate which will contain the value. - */ - public static SiteProofVariableValueInput createExtractReturnVariableValueSequent(Services services, - TypeReference contextObjectType, - IProgramMethod contextMethod, - ReferencePrefix contextObject, - Node methodReturnNode, - Node methodCallEmptyNode, - IProgramVariable variable) { - // Create execution context in that the method was called. - IExecutionContext context = new ExecutionContext(contextObjectType, contextMethod, contextObject); - // Create sequent - return createExtractReturnVariableValueSequent(services, context, methodReturnNode, methodCallEmptyNode, variable); - } - - /** - * Creates a {@link Sequent} which can be used in site proofs to - * extract the return value of the given {@link IProgramVariable} from the - * sequent of the given {@link Node}. - * @param services The {@link Services} to use. - * @param context The {@link IExecutionContext} that defines the current object (this reference). - * @param methodReturnNode The method return {@link Node} which provides the sequent to extract updates and return expression from. - * @param methodCallEmptyNode The method call empty {@link Node} which provides the sequent to start site proof in. - * @param variable The {@link IProgramVariable} of the value which is interested. - * @return The created {@link SiteProofVariableValueInput} with the created sequent and the predicate which will contain the value. - */ - public static SiteProofVariableValueInput createExtractReturnVariableValueSequent(Services services, - IExecutionContext context, - Node methodReturnNode, - Node methodCallEmptyNode, - IProgramVariable variable) { - // Make sure that correct parameters are given - assert context != null; - assert methodReturnNode != null; - assert methodCallEmptyNode != null; - assert variable instanceof ProgramVariable; - // Create method frame which will be executed in site proof - Statement originalReturnStatement = (Statement)methodReturnNode.getNodeInfo().getActiveStatement(); - MethodFrame newMethodFrame = new MethodFrame(variable, context, new StatementBlock(originalReturnStatement)); - JavaBlock newJavaBlock = JavaBlock.createJavaBlock(new StatementBlock(newMethodFrame)); - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, variable.sort()); - // Create formula which contains the value interested in. - Term newTerm = services.getTermBuilder().func(newPredicate, services.getTermBuilder().var((ProgramVariable)variable)); - // Combine method frame with value formula in a modality. - Term modalityTerm = services.getTermBuilder().dia(newJavaBlock, newTerm); - // Get the updates from the return node which includes the value interested in. - Term originalModifiedFormula = methodReturnNode.getAppliedRuleApp().posInOccurrence().sequentFormula().formula(); - ImmutableList originalUpdates = TermBuilder.goBelowUpdates2(originalModifiedFormula).first; - // Create Sequent to prove with new succedent. - Sequent sequentToProve = createSequentToProveWithNewSuccedent(methodCallEmptyNode, null, modalityTerm, originalUpdates, false); - // Return created sequent and the used predicate to identify the value interested in. - return new SiteProofVariableValueInput(sequentToProve, newPredicate); - } - - /** - * Creates a {@link Sequent} which can be used in site proofs to - * extract the value of the given {@link IProgramVariable} from the - * sequent of the given {@link Node}. - * @param services The {@link Services} to use. - * @param node The original {@link Node} which provides the sequent to extract from. - * @param pio The {@link PosInOccurrence} of the SE modality. - * @param additionalConditions Optional additional conditions. - * @param variable The {@link IProgramVariable} of the value which is interested. - * @return The created {@link SiteProofVariableValueInput} with the created sequent and the predicate which will contain the value. - */ - public static SiteProofVariableValueInput createExtractVariableValueSequent(Services services, - Node node, - PosInOccurrence pio, - Term additionalConditions, - IProgramVariable variable) { - // Make sure that correct parameters are given - assert node != null; - assert variable instanceof ProgramVariable; - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(services.getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, variable.sort()); - // Create formula which contains the value interested in. - Term newTerm = services.getTermBuilder().func(newPredicate, services.getTermBuilder().var((ProgramVariable)variable)); - // Create Sequent to prove with new succedent. - Sequent sequentToProve = createSequentToProveWithNewSuccedent(node, pio, additionalConditions, newTerm, false); - // Return created sequent and the used predicate to identify the value interested in. - return new SiteProofVariableValueInput(sequentToProve, newPredicate); - } - - /** - * Creates a {@link Sequent} which can be used in site proofs to - * extract the value of the given {@link IProgramVariable} from the - * sequent of the given {@link Node}. - * @param sideProofServices The {@link Services} of the side proof to use. - * @param node The original {@link Node} which provides the sequent to extract from. - * @param pio The {@link PosInOccurrence} of the modality or its updates. - * @param additionalConditions Additional conditions to add to the antecedent. - * @param term The new succedent term. - * @param keepUpdates {@code true} keep updates, {@code false} throw updates away. - * @return The created {@link SiteProofVariableValueInput} with the created sequent and the predicate which will contain the value. - */ - public static SiteProofVariableValueInput createExtractTermSequent(Services sideProofServices, - Node node, - PosInOccurrence pio, - Term additionalConditions, - Term term, - boolean keepUpdates) { - // Make sure that correct parameters are given - assert node != null; - assert term != null; - // Create predicate which will be used in formulas to store the value interested in. - Function newPredicate = new Function(new Name(sideProofServices.getTermBuilder().newName("ResultPredicate")), Sort.FORMULA, term.sort()); - // Create formula which contains the value interested in. - Term newTerm = sideProofServices.getTermBuilder().func(newPredicate, term); - // Create Sequent to prove with new succedent. - Sequent sequentToProve = keepUpdates ? - createSequentToProveWithNewSuccedent(node, pio, additionalConditions, newTerm, false) : - createSequentToProveWithNewSuccedent(node, pio, additionalConditions, newTerm, null, false); - // Return created sequent and the used predicate to identify the value interested in. - return new SiteProofVariableValueInput(sequentToProve, newPredicate); - } - - /** - * Helper class which represents the return value of - * {@link ExecutionMethodReturn#createExtractReturnVariableValueSequent(TypeReference, ReferencePrefix, Node, IProgramVariable)} and - * {@link ExecutionMethodReturn#createExtractVariableValueSequent(IExecutionContext, Node, IProgramVariable)}. - * @author Martin Hentschel - */ - public static class SiteProofVariableValueInput { - /** - * The sequent to prove. - */ - private Sequent sequentToProve; - - /** - * The {@link Operator} which is the predicate that contains the value interested in. - */ - private Operator operator; - - /** - * Constructor. - * @param sequentToProve he sequent to prove. - * @param operator The {@link Operator} which is the predicate that contains the value interested in. - */ - public SiteProofVariableValueInput(Sequent sequentToProve, Operator operator) { - super(); - this.sequentToProve = sequentToProve; - this.operator = operator; - } - - /** - * Returns the sequent to prove. - * @return The sequent to prove. - */ - public Sequent getSequentToProve() { - return sequentToProve; - } - - /** - * Returns the {@link Operator} which is the predicate that contains the value interested in. - * @return The {@link Operator} which is the predicate that contains the value interested in. - */ - public Operator getOperator() { - return operator; - } - } - - /** - * Checks if the given {@link Term} represents a heap update, - * in particular a store or create operation on a heap. - * @param services The {@link Services} to use. - * @param term The {@link Term} to check. - * @return {@code true} is heap update, {@code false} is something else. - */ - public static boolean isHeapUpdate(Services services, Term term) { - boolean heapUpdate = false; - if (term != null) { - ImmutableArray subs = term.subs(); - if (subs.size() == 1) { - Term sub = subs.get(0); - if (sub.op() == services.getTypeConverter().getHeapLDT().getStore() || - sub.op() == services.getTypeConverter().getHeapLDT().getCreate()) { - heapUpdate = true; + return constraints.toArray(new IExecutionConstraint[constraints.size()]); + } else { + return new IExecutionConstraint[0]; + } + } + + /** + * Checks if the {@link Term} or one of its sub terms contains a symbolic execution label. + * + * @param term The {@link Term} to check. + * @return {@code true} SE label is somewhere contained, {@code false} SE label is not contained + * at all. + */ + public static boolean containsSymbolicExecutionLabel(Term term) { + boolean hasModality = false; + term = TermBuilder.goBelowUpdates(term); + if (term.op() instanceof Modality) { + hasModality = hasSymbolicExecutionLabel(term); + } + if (!hasModality) { + int i = 0; + while (!hasModality && i < term.arity()) { + hasModality = containsSymbolicExecutionLabel(term.sub(i)); + i++; } - } - } - return heapUpdate; - } - - /** - * Checks if it is right now possible to compute the variables of the given {@link IExecutionNode} - * via {@link IExecutionNode#getVariables()}. - * @param node The {@link IExecutionNode} to check. - * @param services The {@link Services} to use. - * @return {@code true} right now it is possible to compute variables, {@code false} it is not possible to compute variables. - * @throws ProofInputException Occurred Exception. - */ - public static boolean canComputeVariables(IExecutionNode node, Services services) throws ProofInputException { - return node != null && - !node.isDisposed() && - !services.getTermBuilder().ff().equals(node.getPathCondition()); - } - - /** - * Creates for the given {@link IExecutionNode} the contained - * {@link IExecutionConstraint}s. - * @param node The {@link IExecutionNode} to create constraints for. - * @return The created {@link IExecutionConstraint}s. - */ - public static IExecutionConstraint[] createExecutionConstraints(IExecutionNode node) { - if (node != null && !node.isDisposed()) { - TermBuilder tb = node.getServices().getTermBuilder(); - List constraints = new LinkedList(); - Node proofNode = node.getProofNode(); - Sequent sequent = proofNode.sequent(); - for (SequentFormula sf : sequent.antecedent()) { - if (!containsSymbolicExecutionLabel(sf.formula())) { - constraints.add(new ExecutionConstraint(node.getSettings(), proofNode, node.getModalityPIO(), sf.formula())); + } + return hasModality; + } + + /** + * Creates for the given {@link IExecutionNode} the contained root {@link IExecutionVariable}s. + * + * @param node The {@link IExecutionNode} to create variables for. + * @return The created {@link IExecutionVariable}s. + * @throws ProofInputException + */ + public static IExecutionVariable[] createExecutionVariables(IExecutionNode node) + throws ProofInputException { + return createExecutionVariables(node, null); + } + + /** + * Creates for the given {@link IExecutionNode} the contained root {@link IExecutionVariable}s. + * + * @param node The {@link IExecutionNode} to create variables for. + * @param condition A {@link Term} specifying some additional constraints to consider. + * @return The created {@link IExecutionVariable}s. + * @throws ProofInputException + */ + public static IExecutionVariable[] createExecutionVariables(IExecutionNode node, + Term condition) throws ProofInputException { + if (node != null) { + return createExecutionVariables(node, node.getProofNode(), node.getModalityPIO(), + condition); + } else { + return new IExecutionVariable[0]; + } + } + + /** + * Creates for the given {@link IExecutionNode} the contained root {@link IExecutionVariable}s. + * + * @param node The {@link IExecutionNode} to create variables for. + * @param proofNode The proof {@link Node} to work with. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + * @param condition A {@link Term} specifying some additional constraints to consider. + * @return The created {@link IExecutionVariable}s. + * @throws ProofInputException + */ + public static IExecutionVariable[] createExecutionVariables(IExecutionNode node, + Node proofNode, PosInOccurrence modalityPIO, Term condition) + throws ProofInputException { + if (node.getSettings().isVariablesAreOnlyComputedFromUpdates()) { + ExecutionVariableExtractor extractor = new ExecutionVariableExtractor(proofNode, + modalityPIO, node, condition, node.getSettings().isSimplifyConditions()); + return extractor.analyse(); + } else { + return createAllExecutionVariables(node, proofNode, modalityPIO, condition); + } + } + + /** + * Creates for the given {@link IExecutionNode} the contained root {@link IExecutionVariable}s. + * + * @param node The {@link IExecutionNode} to create variables for. + * @param proofNode The proof {@link Node} to work with. + * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. + * @param condition A {@link Term} specifying some additional constraints to consider. + * @return The created {@link IExecutionVariable}s. + */ + public static IExecutionVariable[] createAllExecutionVariables(IExecutionNode node, + Node proofNode, PosInOccurrence modalityPIO, Term condition) { + if (proofNode != null) { + List variables = new LinkedList(); + // Add self variable + IProgramVariable selfVar = findSelfTerm(proofNode, modalityPIO); + if (selfVar != null) { + variables.add(selfVar); } - } - for (SequentFormula sf : sequent.succedent()) { - if (!containsSymbolicExecutionLabel(sf.formula())) { - constraints.add(new ExecutionConstraint(node.getSettings(), proofNode, node.getModalityPIO(), tb.not(sf.formula()))); + // Add method parameters + Node callNode = findMethodCallNode(proofNode, modalityPIO); + if (callNode != null + && callNode.getNodeInfo().getActiveStatement() instanceof MethodBodyStatement) { + MethodBodyStatement mbs = + (MethodBodyStatement) callNode.getNodeInfo().getActiveStatement(); + for (Expression e : mbs.getArguments()) { + if (e instanceof IProgramVariable) { + variables.add((IProgramVariable) e); + } + } } - } - return constraints.toArray(new IExecutionConstraint[constraints.size()]); - } - else { - return new IExecutionConstraint[0]; - } - } - - /** - * Checks if the {@link Term} or one of its sub terms contains - * a symbolic execution label. - * @param term The {@link Term} to check. - * @return {@code true} SE label is somewhere contained, {@code false} SE label is not contained at all. - */ - public static boolean containsSymbolicExecutionLabel(Term term) { - boolean hasModality = false; - term = TermBuilder.goBelowUpdates(term); - if (term.op() instanceof Modality) { - hasModality = hasSymbolicExecutionLabel(term); - } - if (!hasModality) { - int i = 0; - while (!hasModality && i < term.arity()) { - hasModality = containsSymbolicExecutionLabel(term.sub(i)); - i++; - } - } - return hasModality; - } - - /** - * Creates for the given {@link IExecutionNode} the contained - * root {@link IExecutionVariable}s. - * @param node The {@link IExecutionNode} to create variables for. - * @return The created {@link IExecutionVariable}s. - * @throws ProofInputException - */ - public static IExecutionVariable[] createExecutionVariables(IExecutionNode node) throws ProofInputException { - return createExecutionVariables(node, null); - } - - /** - * Creates for the given {@link IExecutionNode} the contained - * root {@link IExecutionVariable}s. - * @param node The {@link IExecutionNode} to create variables for. - * @param condition A {@link Term} specifying some additional constraints to consider. - * @return The created {@link IExecutionVariable}s. - * @throws ProofInputException - */ - public static IExecutionVariable[] createExecutionVariables(IExecutionNode node, Term condition) throws ProofInputException { - if (node != null) { - return createExecutionVariables(node, node.getProofNode(), node.getModalityPIO(), condition); - } - else { - return new IExecutionVariable[0]; - } - } - - /** - * Creates for the given {@link IExecutionNode} the contained - * root {@link IExecutionVariable}s. - * @param node The {@link IExecutionNode} to create variables for. - * @param proofNode The proof {@link Node} to work with. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - * @param condition A {@link Term} specifying some additional constraints to consider. - * @return The created {@link IExecutionVariable}s. - * @throws ProofInputException - */ - public static IExecutionVariable[] createExecutionVariables(IExecutionNode node, - Node proofNode, - PosInOccurrence modalityPIO, - Term condition) throws ProofInputException { - if (node.getSettings().isVariablesAreOnlyComputedFromUpdates()) { - ExecutionVariableExtractor extractor = new ExecutionVariableExtractor(proofNode, modalityPIO, node, condition, node.getSettings().isSimplifyConditions()); - return extractor.analyse(); - } - else { - return createAllExecutionVariables(node, proofNode, modalityPIO, condition); - } - } - - /** - * Creates for the given {@link IExecutionNode} the contained - * root {@link IExecutionVariable}s. - * @param node The {@link IExecutionNode} to create variables for. - * @param proofNode The proof {@link Node} to work with. - * @param modalityPIO The {@link PosInOccurrence} of the modality of interest. - * @param condition A {@link Term} specifying some additional constraints to consider. - * @return The created {@link IExecutionVariable}s. - */ - public static IExecutionVariable[] createAllExecutionVariables(IExecutionNode node, - Node proofNode, - PosInOccurrence modalityPIO, - Term condition) { - if (proofNode != null) { - List variables = new LinkedList(); - // Add self variable - IProgramVariable selfVar = findSelfTerm(proofNode, modalityPIO); - if (selfVar != null) { - variables.add(selfVar); - } - // Add method parameters - Node callNode = findMethodCallNode(proofNode, modalityPIO); - if (callNode != null && callNode.getNodeInfo().getActiveStatement() instanceof MethodBodyStatement) { - MethodBodyStatement mbs = (MethodBodyStatement)callNode.getNodeInfo().getActiveStatement(); - for (Expression e : mbs.getArguments()) { - if (e instanceof IProgramVariable) { - variables.add((IProgramVariable)e); - } + // Collect variables from updates + List variablesFromUpdates = + collectAllElementaryUpdateTerms(proofNode); + for (IProgramVariable variable : variablesFromUpdates) { + if (!variables.contains(variable)) { + variables.add(variable); + } } - } - // Collect variables from updates - List variablesFromUpdates = collectAllElementaryUpdateTerms(proofNode); - for (IProgramVariable variable : variablesFromUpdates) { - if (!variables.contains(variable)) { - variables.add(variable); + IExecutionVariable[] result = new IExecutionVariable[variables.size()]; + int i = 0; + for (IProgramVariable var : variables) { + result[i] = new ExecutionVariable(node, proofNode, modalityPIO, var, condition); + i++; } - } - IExecutionVariable[] result = new IExecutionVariable[variables.size()]; - int i = 0; - for (IProgramVariable var : variables) { - result[i] = new ExecutionVariable(node, proofNode, modalityPIO, var, condition); - i++; - } - return result; - } - else { - return new IExecutionVariable[0]; - } - } - - /** - * Collects all {@link IProgramVariable} used in {@link ElementaryUpdate}s. - * @param node The {@link Node} to search in. - * @return The found {@link IProgramVariable} which are used in {@link ElementaryUpdate}s. - */ - public static List collectAllElementaryUpdateTerms(Node node) { - if (node != null) { - Services services = node.proof().getServices(); - List result = new LinkedList(); - for (SequentFormula sf : node.sequent().antecedent()) { - internalCollectAllElementaryUpdateTerms(services, result, sf.formula()); - } - for (SequentFormula sf : node.sequent().succedent()) { - internalCollectAllElementaryUpdateTerms(services, result, sf.formula()); - } - return result; - } - else { - return Collections.emptyList(); - } - } - - /** - * Utility method of {@link #collectAllElementaryUpdateTerms(Node)} which - * collects all {@link IProgramVariable}s of {@link ElementaryUpdate}s - * and static field manipulations. - * @param services The {@link Services} to use. - * @param result The result {@link List} to fill. - * @param term The current term to analyze. - */ - private static void internalCollectAllElementaryUpdateTerms(Services services, - List result, - Term term) { - if (term != null) { - if (term.op() instanceof ElementaryUpdate) { - if (SymbolicExecutionUtil.isHeapUpdate(services, term)) { - // Extract static variables from heap - Set staticAttributes = new LinkedHashSet(); - internalCollectStaticProgramVariablesOnHeap(services, staticAttributes, term); - result.addAll(staticAttributes); + return result; + } else { + return new IExecutionVariable[0]; + } + } + + /** + * Collects all {@link IProgramVariable} used in {@link ElementaryUpdate}s. + * + * @param node The {@link Node} to search in. + * @return The found {@link IProgramVariable} which are used in {@link ElementaryUpdate}s. + */ + public static List collectAllElementaryUpdateTerms(Node node) { + if (node != null) { + Services services = node.proof().getServices(); + List result = new LinkedList(); + for (SequentFormula sf : node.sequent().antecedent()) { + internalCollectAllElementaryUpdateTerms(services, result, sf.formula()); } - else { - // Local variable - ElementaryUpdate eu = (ElementaryUpdate)term.op(); - if (eu.lhs() instanceof IProgramVariable) { - result.add((IProgramVariable)eu.lhs()); - } + for (SequentFormula sf : node.sequent().succedent()) { + internalCollectAllElementaryUpdateTerms(services, result, sf.formula()); } - } - else { - for (Term sub : term.subs()) { - internalCollectAllElementaryUpdateTerms(services, result, sub); + return result; + } else { + return Collections.emptyList(); + } + } + + /** + * Utility method of {@link #collectAllElementaryUpdateTerms(Node)} which collects all + * {@link IProgramVariable}s of {@link ElementaryUpdate}s and static field manipulations. + * + * @param services The {@link Services} to use. + * @param result The result {@link List} to fill. + * @param term The current term to analyze. + */ + private static void internalCollectAllElementaryUpdateTerms(Services services, + List result, Term term) { + if (term != null) { + if (term.op() instanceof ElementaryUpdate) { + if (SymbolicExecutionUtil.isHeapUpdate(services, term)) { + // Extract static variables from heap + Set staticAttributes = new LinkedHashSet(); + internalCollectStaticProgramVariablesOnHeap(services, staticAttributes, term); + result.addAll(staticAttributes); + } else { + // Local variable + ElementaryUpdate eu = (ElementaryUpdate) term.op(); + if (eu.lhs() instanceof IProgramVariable) { + result.add((IProgramVariable) eu.lhs()); + } + } + } else { + for (Term sub : term.subs()) { + internalCollectAllElementaryUpdateTerms(services, result, sub); + } } - } - } - } - - /** - * Utility method of {@link #internalCollectAllElementaryUpdateTerms(Services, List, Term)} - * which collects static field manipulations on the given heap update. - * @param services The {@link Services} to use. - * @param result The result {@link List} to fill. - * @param term The current term to analyze. - */ - private static void internalCollectStaticProgramVariablesOnHeap(Services services, - Set result, - Term term) { - final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - try { - if (term.op() == heapLDT.getStore()) { - ImmutableArray subs = term.subs(); - if (term.arity() == 4) { - Term innerMostSelect = findInnerMostSelect(subs.get(1), services); - Term locationTerm = innerMostSelect != null ? innerMostSelect.sub(2) : subs.get(2); - ProgramVariable attribute = getProgramVariable(services, heapLDT, locationTerm); - if (attribute != null && attribute.isStatic()) { - result.add(attribute); - } + } + } + + /** + * Utility method of {@link #internalCollectAllElementaryUpdateTerms(Services, List, Term)} + * which collects static field manipulations on the given heap update. + * + * @param services The {@link Services} to use. + * @param result The result {@link List} to fill. + * @param term The current term to analyze. + */ + private static void internalCollectStaticProgramVariablesOnHeap(Services services, + Set result, Term term) { + final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + try { + if (term.op() == heapLDT.getStore()) { + ImmutableArray subs = term.subs(); + if (term.arity() == 4) { + Term innerMostSelect = findInnerMostSelect(subs.get(1), services); + Term locationTerm = + innerMostSelect != null ? innerMostSelect.sub(2) : subs.get(2); + ProgramVariable attribute = getProgramVariable(services, heapLDT, locationTerm); + if (attribute != null && attribute.isStatic()) { + result.add(attribute); + } + } } - } - } - catch (Exception e) { - // Can go wrong, nothing to do - } - for (Term sub : term.subs()) { - internalCollectStaticProgramVariablesOnHeap(services, result, sub); - } - } - - private static Term findInnerMostSelect(Term term, Services services) { - if (isSelect(services, term)) { - while (isSelect(services, term.sub(1))) { - term = term.sub(1); - } - return term; - } - else { - return null; - } - } - - /** - * Returns the {@link ProgramVariable} defined by the given {@link Term}. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} to use. - * @param locationTerm The {@link Term} to extract {@link ProgramVariable} from. - * @return The {@link Term}s {@link ProgramVariable} or {@code null} if not available. - */ - public static ProgramVariable getProgramVariable(Services services, HeapLDT heapLDT, - Term locationTerm) { - ProgramVariable result = null; - if (locationTerm.op() instanceof Function) { - Function function = (Function)locationTerm.op(); - // Make sure that the function is not an array - if (heapLDT.getArr() != function) { - String typeName = HeapLDT.getClassName(function); - KeYJavaType type = services.getJavaInfo().getKeYJavaType(typeName); - if (type != null) { - String fieldName = HeapLDT.getPrettyFieldName(function); - result = services.getJavaInfo().getAttribute(fieldName, type); + } catch (Exception e) { + // Can go wrong, nothing to do + } + for (Term sub : term.subs()) { + internalCollectStaticProgramVariablesOnHeap(services, result, sub); + } + } + + private static Term findInnerMostSelect(Term term, Services services) { + if (isSelect(services, term)) { + while (isSelect(services, term.sub(1))) { + term = term.sub(1); } - } - } - return result; - } - - /** - * Returns the array index defined by the given {@link Term}. - * @param services The {@link Services} to use. - * @param heapLDT The {@link HeapLDT} to use. - * @param arrayIndexTerm The {@link Term} to extract the array index from. - * @return The array index or {@code null} if the term defines no array index. - */ - public static Term getArrayIndex(Services services, HeapLDT heapLDT, Term arrayIndexTerm) { - // Make sure that the term is an array index - if (arrayIndexTerm.op() == heapLDT.getArr() && arrayIndexTerm.arity() == 1) { - return arrayIndexTerm.sub(0); - } - else { - return null; - } - } - - /** - * Searches the {@link IProgramVariable} of the current {@code this}/{@code self} reference. - * @param node The {@link Node} to search in. - * @param pio The {@link PosInOccurrence} describing the location of the modality of interest. - * @return The found {@link IProgramVariable} with the current {@code this}/{@code self} reference or {@code null} if no one is available. - */ - public static IProgramVariable findSelfTerm(Node node, PosInOccurrence pio) { - if (pio != null) { - Term term = pio.subTerm(); - term = TermBuilder.goBelowUpdates(term); - JavaBlock jb = term.javaBlock(); - Services services = node.proof().getServices(); - IExecutionContext context = JavaTools.getInnermostExecutionContext(jb, services); - if (context instanceof ExecutionContext) { - ReferencePrefix prefix = context.getRuntimeInstance(); - return prefix instanceof IProgramVariable ? (IProgramVariable)prefix : null; - } - else { + return term; + } else { return null; - } - } - else { - return null; - } - } - - /** - * Checks if the given node should be represented as method call. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The statement ({@link SourceElement}). - * @return {@code true} represent node as method call, {@code false} represent node as something else. - */ - public static boolean isMethodCallNode(Node node, RuleApp ruleApp, SourceElement statement) { - return isMethodCallNode(node, ruleApp, statement, false); - } - - /** - * Checks if the given node should be represented as method call. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The statement ({@link SourceElement}). - * @param allowImpliciteMethods {@code true} implicit methods are included, {@code false} implicit methods are outfiltered. - * @return {@code true} represent node as method call, {@code false} represent node as something else. - */ - public static boolean isMethodCallNode(Node node, RuleApp ruleApp, - SourceElement statement, boolean allowImpliciteMethods) { - if (ruleApp != null) { // Do not handle open goal nodes without applied rule - if (statement instanceof MethodBodyStatement) { - if (allowImpliciteMethods) { - return true; + } + } + + /** + * Returns the {@link ProgramVariable} defined by the given {@link Term}. + * + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} to use. + * @param locationTerm The {@link Term} to extract {@link ProgramVariable} from. + * @return The {@link Term}s {@link ProgramVariable} or {@code null} if not available. + */ + public static ProgramVariable getProgramVariable(Services services, HeapLDT heapLDT, + Term locationTerm) { + ProgramVariable result = null; + if (locationTerm.op() instanceof Function) { + Function function = (Function) locationTerm.op(); + // Make sure that the function is not an array + if (heapLDT.getArr() != function) { + String typeName = HeapLDT.getClassName(function); + KeYJavaType type = services.getJavaInfo().getKeYJavaType(typeName); + if (type != null) { + String fieldName = HeapLDT.getPrettyFieldName(function); + result = services.getJavaInfo().getAttribute(fieldName, type); + } + } + } + return result; + } + + /** + * Returns the array index defined by the given {@link Term}. + * + * @param services The {@link Services} to use. + * @param heapLDT The {@link HeapLDT} to use. + * @param arrayIndexTerm The {@link Term} to extract the array index from. + * @return The array index or {@code null} if the term defines no array index. + */ + public static Term getArrayIndex(Services services, HeapLDT heapLDT, Term arrayIndexTerm) { + // Make sure that the term is an array index + if (arrayIndexTerm.op() == heapLDT.getArr() && arrayIndexTerm.arity() == 1) { + return arrayIndexTerm.sub(0); + } else { + return null; + } + } + + /** + * Searches the {@link IProgramVariable} of the current {@code this}/{@code self} reference. + * + * @param node The {@link Node} to search in. + * @param pio The {@link PosInOccurrence} describing the location of the modality of interest. + * @return The found {@link IProgramVariable} with the current {@code this}/{@code self} + * reference or {@code null} if no one is available. + */ + public static IProgramVariable findSelfTerm(Node node, PosInOccurrence pio) { + if (pio != null) { + Term term = pio.subTerm(); + term = TermBuilder.goBelowUpdates(term); + JavaBlock jb = term.javaBlock(); + Services services = node.proof().getServices(); + IExecutionContext context = JavaTools.getInnermostExecutionContext(jb, services); + if (context instanceof ExecutionContext) { + ReferencePrefix prefix = context.getRuntimeInstance(); + return prefix instanceof IProgramVariable ? (IProgramVariable) prefix : null; + } else { + return null; + } + } else { + return null; + } + } + + /** + * Checks if the given node should be represented as method call. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The statement ({@link SourceElement}). + * @return {@code true} represent node as method call, {@code false} represent node as something + * else. + */ + public static boolean isMethodCallNode(Node node, RuleApp ruleApp, SourceElement statement) { + return isMethodCallNode(node, ruleApp, statement, false); + } + + /** + * Checks if the given node should be represented as method call. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The statement ({@link SourceElement}). + * @param allowImpliciteMethods {@code true} implicit methods are included, {@code false} + * implicit methods are outfiltered. + * @return {@code true} represent node as method call, {@code false} represent node as something + * else. + */ + public static boolean isMethodCallNode(Node node, RuleApp ruleApp, SourceElement statement, + boolean allowImpliciteMethods) { + if (ruleApp != null) { // Do not handle open goal nodes without applied rule + if (statement instanceof MethodBodyStatement) { + if (allowImpliciteMethods) { + return true; + } else { + MethodBodyStatement mbs = (MethodBodyStatement) statement; + IProgramMethod pm = mbs.getProgramMethod(node.proof().getServices()); + return isNotImplicit(node.proof().getServices(), pm); + } + } else { + return false; + } + } else { + return false; + } + } + + /** + * Checks if the given {@link IProgramMethod} is not implicit. + * + * @param services The {@link Services} to use. + * @param pm The {@link IProgramMethod} to check. + * @return {@code true} is not implicit, {@code false} is implicit + */ + public static boolean isNotImplicit(Services services, IProgramMethod pm) { + if (pm != null) { + if (KeYTypeUtil.isImplicitConstructor(pm)) { + IProgramMethod explicitConstructor = + KeYTypeUtil.findExplicitConstructor(services, pm); + return explicitConstructor != null + && !KeYTypeUtil.isLibraryClass(explicitConstructor.getContainerType()); + } else { + return !pm.isImplicit() && // Do not include implicit methods, but always + // constructors + !KeYTypeUtil.isLibraryClass(pm.getContainerType()); } - else { - MethodBodyStatement mbs = (MethodBodyStatement)statement; - IProgramMethod pm = mbs.getProgramMethod(node.proof().getServices()); - return isNotImplicit(node.proof().getServices(), pm); + } else { + return true; + } + } + + /** + * Checks if the given node should be represented as branch statement. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The statement ({@link SourceElement}). + * @param posInfo The {@link PositionInfo}. + * @return {@code true} represent node as branch statement, {@code false} represent node as + * something else. + */ + public static boolean isBranchStatement(Node node, RuleApp ruleApp, SourceElement statement, + PositionInfo posInfo) { + return isStatementNode(node, ruleApp, statement, posInfo) + && (statement instanceof BranchStatement); + } + + /** + * Checks if the given node should be represented as loop statement. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The statement ({@link SourceElement}). + * @param posInfo The {@link PositionInfo}. + * @return {@code true} represent node as loop statement, {@code false} represent node as + * something else. + */ + public static boolean isLoopStatement(Node node, RuleApp ruleApp, SourceElement statement, + PositionInfo posInfo) { + return isStatementNode(node, ruleApp, statement, posInfo) + && (statement instanceof LoopStatement); + } + + /** + * Checks if the given node should be represented as statement. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The statement ({@link SourceElement}). + * @param posInfo The {@link PositionInfo}. + * @return {@code true} represent node as statement, {@code false} represent node as something + * else. + */ + public static boolean isStatementNode(Node node, RuleApp ruleApp, SourceElement statement, + PositionInfo posInfo) { + return ruleApp != null && // Do not handle the open goal node which has no applied rule + posInfo != null && posInfo.getEndPosition() != Position.UNDEFINED + && posInfo.getEndPosition().getLine() >= 0 && // Filter out statements where source + // code is missing. + !(statement instanceof EmptyStatement) && // Filter out empty statements + !(statement instanceof StatementBlock && ((StatementBlock) statement).isEmpty()); // Filter + // out + // empty + // blocks + } + + /** + * Checks if the given node should be represented as termination. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as termination, {@code false} represent node as something + * else. + */ + public static boolean isTerminationNode(Node node, RuleApp ruleApp) { + return "emptyModality".equals(MiscTools.getRuleDisplayName(ruleApp)); + } + + /** + * Checks if the given node should be represented as operation contract. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as operation contract, {@code false} represent node as + * something else. + */ + public static boolean isOperationContract(Node node, RuleApp ruleApp) { + if (ruleApp instanceof AbstractContractRuleApp) { + Contract contract = ((AbstractContractRuleApp) ruleApp).getInstantiation(); + if (contract instanceof OperationContract) { + IProgramMethod target = ((OperationContract) contract).getTarget(); + return isNotImplicit(node.proof().getServices(), target); + } else { + return false; } - } - else { + } else { return false; - } - } - else { - return false; - } - } - - /** - * Checks if the given {@link IProgramMethod} is not implicit. - * @param services The {@link Services} to use. - * @param pm The {@link IProgramMethod} to check. - * @return {@code true} is not implicit, {@code false} is implicit - */ - public static boolean isNotImplicit(Services services, IProgramMethod pm) { - if (pm != null) { - if (KeYTypeUtil.isImplicitConstructor(pm)) { - IProgramMethod explicitConstructor = KeYTypeUtil.findExplicitConstructor(services, pm); - return explicitConstructor != null && - !KeYTypeUtil.isLibraryClass(explicitConstructor.getContainerType()); - } - else { - return !pm.isImplicit() && // Do not include implicit methods, but always constructors - !KeYTypeUtil.isLibraryClass(pm.getContainerType()); - } - } - else { - return true; - } - } - - /** - * Checks if the given node should be represented as branch statement. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The statement ({@link SourceElement}). - * @param posInfo The {@link PositionInfo}. - * @return {@code true} represent node as branch statement, {@code false} represent node as something else. - */ - public static boolean isBranchStatement(Node node, RuleApp ruleApp, - SourceElement statement, PositionInfo posInfo) { - return isStatementNode(node, ruleApp, statement, posInfo) && - (statement instanceof BranchStatement); - } - - /** - * Checks if the given node should be represented as loop statement. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The statement ({@link SourceElement}). - * @param posInfo The {@link PositionInfo}. - * @return {@code true} represent node as loop statement, {@code false} represent node as something else. - */ - public static boolean isLoopStatement(Node node, RuleApp ruleApp, - SourceElement statement, PositionInfo posInfo) { - return isStatementNode(node, ruleApp, statement, posInfo) && - (statement instanceof LoopStatement); - } - - /** - * Checks if the given node should be represented as statement. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The statement ({@link SourceElement}). - * @param posInfo The {@link PositionInfo}. - * @return {@code true} represent node as statement, {@code false} represent node as something else. - */ - public static boolean isStatementNode(Node node, RuleApp ruleApp, SourceElement statement, PositionInfo posInfo) { - return ruleApp != null && // Do not handle the open goal node which has no applied rule - posInfo != null && - posInfo.getEndPosition() != Position.UNDEFINED && - posInfo.getEndPosition().getLine() >= 0 && // Filter out statements where source code is missing. - !(statement instanceof EmptyStatement) && // Filter out empty statements - !(statement instanceof StatementBlock && ((StatementBlock)statement).isEmpty()); // Filter out empty blocks - } - - /** - * Checks if the given node should be represented as termination. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as termination, {@code false} represent node as something else. - */ - public static boolean isTerminationNode(Node node, RuleApp ruleApp) { - return "emptyModality".equals(MiscTools.getRuleDisplayName(ruleApp)); - } - - /** - * Checks if the given node should be represented as operation contract. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as operation contract, {@code false} represent node as something else. - */ - public static boolean isOperationContract(Node node, RuleApp ruleApp) { - if (ruleApp instanceof AbstractContractRuleApp) { - Contract contract = ((AbstractContractRuleApp)ruleApp).getInstantiation(); - if (contract instanceof OperationContract) { - IProgramMethod target = ((OperationContract)contract).getTarget(); - return isNotImplicit(node.proof().getServices(), target); - } - else { + } + } + + /** + * Checks if the given node should be represented as block/loop contract. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as block contract, {@code false} represent node as + * something else. + */ + public static boolean isBlockSpecificationElement(Node node, RuleApp ruleApp) { + return ruleApp instanceof AbstractAuxiliaryContractBuiltInRuleApp; + } + + /** + * Checks if the given node should be represented as loop invariant. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as use loop invariant, {@code false} represent node as + * something else. + */ + public static boolean isLoopInvariant(Node node, RuleApp ruleApp) { + return "Loop Invariant".equals(MiscTools.getRuleDisplayName(ruleApp)); + } + + /** + * Checks if the given node should be represented as method return. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as method return, {@code false} represent node as + * something else. + */ + public static boolean isMethodReturnNode(Node node, RuleApp ruleApp) { + String displayName = MiscTools.getRuleDisplayName(ruleApp); + String ruleName = MiscTools.getRuleName(ruleApp); + return "methodCallEmpty".equals(displayName) || "methodCallEmptyReturn".equals(ruleName) + || "methodCallReturnIgnoreResult".equals(ruleName); + } + + /** + * Checks if the given node should be represented as exceptional method return. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as exceptional method return, {@code false} represent + * node as something else. + */ + public static boolean isExceptionalMethodReturnNode(Node node, RuleApp ruleApp) { + String ruleName = MiscTools.getRuleName(ruleApp); + return "methodCallParamThrow".equals(ruleName) || "methodCallThrow".equals(ruleName); + } + + /** + * Checks if the given {@link Node} has a loop condition. + * + * @param node The {@link Node} to check. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @param statement The actual statement ({@link SourceElement}). + * @return {@code true} has loop condition, {@code false} has no loop condition. + */ + public static boolean hasLoopCondition(Node node, RuleApp ruleApp, SourceElement statement) { + return ruleApp != null && // Do not handle open goal nodes without applied rule + statement instanceof LoopStatement && !(statement instanceof EnhancedFor); // For + // each + // loops + // have + // no + // loop + // condition + } + + /** + * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a + * {@link SymbolicExecutionTermLabel}. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not + * contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is + * {@code null}. + */ + public static boolean hasLoopBodyLabel(RuleApp ruleApp) { + if (ruleApp != null && ruleApp.posInOccurrence() != null) { + Term term = ruleApp.posInOccurrence().subTerm(); + if (term != null) { + term = TermBuilder.goBelowUpdates(term); + return term.containsLabel(LOOP_BODY_LABEL); + } else { + return false; + } + } else { return false; - } - } - else { - return false; - } - } - - /** - * Checks if the given node should be represented as block/loop contract. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as block contract, {@code false} represent node as something else. - */ - public static boolean isBlockSpecificationElement(Node node, RuleApp ruleApp) { - return ruleApp instanceof AbstractAuxiliaryContractBuiltInRuleApp; - } - - /** - * Checks if the given node should be represented as loop invariant. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as use loop invariant, {@code false} represent node as something else. - */ - public static boolean isLoopInvariant(Node node, RuleApp ruleApp) { - return "Loop Invariant".equals(MiscTools.getRuleDisplayName(ruleApp)); - } - - /** - * Checks if the given node should be represented as method return. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as method return, {@code false} represent node as something else. - */ - public static boolean isMethodReturnNode(Node node, RuleApp ruleApp) { - String displayName = MiscTools.getRuleDisplayName(ruleApp); - String ruleName = MiscTools.getRuleName(ruleApp); - return "methodCallEmpty".equals(displayName) || - "methodCallEmptyReturn".equals(ruleName) || - "methodCallReturnIgnoreResult".equals(ruleName); - } - - /** - * Checks if the given node should be represented as exceptional method return. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as exceptional method return, {@code false} represent node as something else. - */ - public static boolean isExceptionalMethodReturnNode(Node node, RuleApp ruleApp) { - String ruleName = MiscTools.getRuleName(ruleApp); - return "methodCallParamThrow".equals(ruleName) || "methodCallThrow".equals(ruleName); - } - - /** - * Checks if the given {@link Node} has a loop condition. - * @param node The {@link Node} to check. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @param statement The actual statement ({@link SourceElement}). - * @return {@code true} has loop condition, {@code false} has no loop condition. - */ - public static boolean hasLoopCondition(Node node, RuleApp ruleApp, SourceElement statement) { - return ruleApp != null && // Do not handle open goal nodes without applied rule - statement instanceof LoopStatement && - !(statement instanceof EnhancedFor); // For each loops have no loop condition - } - - /** - * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a {@link SymbolicExecutionTermLabel}. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is {@code null}. - */ - public static boolean hasLoopBodyLabel(RuleApp ruleApp) { - if (ruleApp != null && ruleApp.posInOccurrence() != null) { - Term term = ruleApp.posInOccurrence().subTerm(); - if (term != null) { - term = TermBuilder.goBelowUpdates(term); - return term.containsLabel(LOOP_BODY_LABEL); - } - else { + } + } + + /** + * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a + * {@link SymbolicExecutionTermLabel}. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not + * contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is + * {@code null}. + */ + public static boolean hasLoopBodyTerminationLabel(RuleApp ruleApp) { + if (ruleApp != null && ruleApp.posInOccurrence() != null) { + Term term = ruleApp.posInOccurrence().subTerm(); + return term.containsLabel(LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL); + } else { return false; - } - } - else { - return false; - } - } - - /** - * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a {@link SymbolicExecutionTermLabel}. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is {@code null}. - */ - public static boolean hasLoopBodyTerminationLabel(RuleApp ruleApp) { - if (ruleApp != null && ruleApp.posInOccurrence() != null) { - Term term = ruleApp.posInOccurrence().subTerm(); - return term.containsLabel(LOOP_INVARIANT_NORMAL_BEHAVIOR_LABEL); - } - else { - return false; - } - } - - /** - * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a {@link SymbolicExecutionTermLabel}. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is {@code null}. - */ - public static boolean hasSymbolicExecutionLabel(RuleApp ruleApp) { - return getSymbolicExecutionLabel(ruleApp) != null; - } - - /** - * Returns the contained {@link SymbolicExecutionTermLabel} if available. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return The first found {@link SymbolicExecutionTermLabel} or {@code null} if no {@link SymbolicExecutionTermLabel} is provided. - */ - public static SymbolicExecutionTermLabel getSymbolicExecutionLabel(RuleApp ruleApp) { - if (ruleApp != null && ruleApp.posInOccurrence() != null) { - return getSymbolicExecutionLabel(ruleApp.posInOccurrence().subTerm()); - } - else { - return null; - } - } - - /** - * Checks if the given {@link Term} contains a {@link SymbolicExecutionTermLabel}. - * @param term The {@link Term} to check. - * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not contain a {@link SymbolicExecutionTermLabel} or the given {@link Term} is {@code null}. - */ - public static boolean hasSymbolicExecutionLabel(Term term) { - return getSymbolicExecutionLabel(term) != null; - } - - /** - * Returns the contained {@link SymbolicExecutionTermLabel} if available. - * @param term The {@link Term} to search in. - * @return The first found {@link SymbolicExecutionTermLabel} or {@code null} if no {@link SymbolicExecutionTermLabel} is provided. - */ - public static SymbolicExecutionTermLabel getSymbolicExecutionLabel(Term term) { - if (term != null) { - term = TermBuilder.goBelowUpdates(term); - return (SymbolicExecutionTermLabel)CollectionUtil.search(term.getLabels(), - new IFilter() { - @Override - public boolean select(TermLabel element) { - return element instanceof SymbolicExecutionTermLabel; + } + } + + /** + * Checks if the {@link Term} on which the {@link RuleApp} was applied contains a + * {@link SymbolicExecutionTermLabel}. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not + * contain a {@link SymbolicExecutionTermLabel} or the given {@link RuleApp} is + * {@code null}. + */ + public static boolean hasSymbolicExecutionLabel(RuleApp ruleApp) { + return getSymbolicExecutionLabel(ruleApp) != null; + } + + /** + * Returns the contained {@link SymbolicExecutionTermLabel} if available. + * + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return The first found {@link SymbolicExecutionTermLabel} or {@code null} if no + * {@link SymbolicExecutionTermLabel} is provided. + */ + public static SymbolicExecutionTermLabel getSymbolicExecutionLabel(RuleApp ruleApp) { + if (ruleApp != null && ruleApp.posInOccurrence() != null) { + return getSymbolicExecutionLabel(ruleApp.posInOccurrence().subTerm()); + } else { + return null; + } + } + + /** + * Checks if the given {@link Term} contains a {@link SymbolicExecutionTermLabel}. + * + * @param term The {@link Term} to check. + * @return {@code true} contains a {@link SymbolicExecutionTermLabel}, {@code false} does not + * contain a {@link SymbolicExecutionTermLabel} or the given {@link Term} is + * {@code null}. + */ + public static boolean hasSymbolicExecutionLabel(Term term) { + return getSymbolicExecutionLabel(term) != null; + } + + /** + * Returns the contained {@link SymbolicExecutionTermLabel} if available. + * + * @param term The {@link Term} to search in. + * @return The first found {@link SymbolicExecutionTermLabel} or {@code null} if no + * {@link SymbolicExecutionTermLabel} is provided. + */ + public static SymbolicExecutionTermLabel getSymbolicExecutionLabel(Term term) { + if (term != null) { + term = TermBuilder.goBelowUpdates(term); + return (SymbolicExecutionTermLabel) CollectionUtil.search(term.getLabels(), + new IFilter() { + @Override + public boolean select(TermLabel element) { + return element instanceof SymbolicExecutionTermLabel; + } + }); + } else { + return null; + } + } + + /** + * Searches the modality {@link PosInOccurrence} with the maximal + * {@link SymbolicExecutionTermLabel} ID {@link SymbolicExecutionTermLabel#getId()} in the given + * {@link Sequent}. + * + * @param sequent The {@link Sequent} to search in. + * @return The modality {@link PosInOccurrence} with the maximal ID if available or {@code null} + * otherwise. + */ + public static PosInOccurrence findModalityWithMaxSymbolicExecutionLabelId(Sequent sequent) { + if (sequent != null) { + PosInOccurrence nextAntecedent = + findModalityWithMaxSymbolicExecutionLabelId(sequent.antecedent(), true); + PosInOccurrence nextSuccedent = + findModalityWithMaxSymbolicExecutionLabelId(sequent.succedent(), false); + if (nextAntecedent != null) { + if (nextSuccedent != null) { + SymbolicExecutionTermLabel antecedentLabel = + getSymbolicExecutionLabel(nextAntecedent.subTerm()); + SymbolicExecutionTermLabel succedentLabel = + getSymbolicExecutionLabel(nextSuccedent.subTerm()); + return antecedentLabel.getId() > succedentLabel.getId() ? nextAntecedent + : nextSuccedent; + } else { + return nextAntecedent; + } + } else { + return nextSuccedent; } - }); - } - else { - return null; - } - } - - /** - * Searches the modality {@link PosInOccurrence} with the maximal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Sequent}. - * @param sequent The {@link Sequent} to search in. - * @return The modality {@link PosInOccurrence} with the maximal ID if available or {@code null} otherwise. - */ - public static PosInOccurrence findModalityWithMaxSymbolicExecutionLabelId(Sequent sequent) { - if (sequent != null) { - PosInOccurrence nextAntecedent = findModalityWithMaxSymbolicExecutionLabelId(sequent.antecedent(), true); - PosInOccurrence nextSuccedent = findModalityWithMaxSymbolicExecutionLabelId(sequent.succedent(), false); - if (nextAntecedent != null) { - if (nextSuccedent != null) { - SymbolicExecutionTermLabel antecedentLabel = getSymbolicExecutionLabel(nextAntecedent.subTerm()); - SymbolicExecutionTermLabel succedentLabel = getSymbolicExecutionLabel(nextSuccedent.subTerm()); - return antecedentLabel.getId() > succedentLabel.getId() ? - nextAntecedent : nextSuccedent; + } else { + return null; + } + } + + /** + * Searches the modality {@link Term} with the maximal {@link SymbolicExecutionTermLabel} ID + * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Semisequent}. + * + * @param semisequent The {@link Semisequent} to search in. + * @param inAntec {@code true} antecedent, {@code false} succedent. + * @return The modality {@link Term} with the maximal ID if available or {@code null} otherwise. + */ + public static PosInOccurrence findModalityWithMaxSymbolicExecutionLabelId( + Semisequent semisequent, boolean inAntec) { + if (semisequent != null) { + int maxId = Integer.MIN_VALUE; + PosInOccurrence maxPio = null; + for (SequentFormula sf : semisequent) { + PosInTerm current = findModalityWithMaxSymbolicExecutionLabelId(sf.formula()); + if (current != null) { + PosInOccurrence pio = new PosInOccurrence(sf, current, inAntec); + SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(pio.subTerm()); + if (maxPio == null || label.getId() > maxId) { + maxPio = pio; + maxId = label.getId(); + } + } } - else { - return nextAntecedent; + return maxPio; + } else { + return null; + } + } + + /** + * Searches the modality {@link PosInTerm} with the maximal {@link SymbolicExecutionTermLabel} + * ID {@link SymbolicExecutionTermLabel#getId()} in the given {@link Term}. + * + * @param term The {@link Term} to search in. + * @return The modality {@link PosInTerm} with the maximal ID if available or {@code null} + * otherwise. + */ + public static PosInTerm findModalityWithMaxSymbolicExecutionLabelId(Term term) { + if (term != null) { + FindModalityWithSymbolicExecutionLabelId visitor = + new FindModalityWithSymbolicExecutionLabelId(true); + term.execPreOrder(visitor); + return visitor.getPosInTerm(); + } else { + return null; + } + } + + /** + * Searches the modality {@link PosInOccurrence} with the minimal + * {@link SymbolicExecutionTermLabel} ID {@link SymbolicExecutionTermLabel#getId()} in the given + * {@link Sequent}. + * + * @param sequent The {@link Sequent} to search in. + * @return The modality {@link PosInOccurrence} with the maximal ID if available or {@code null} + * otherwise. + */ + public static PosInOccurrence findModalityWithMinSymbolicExecutionLabelId(Sequent sequent) { + if (sequent != null) { + PosInOccurrence nextAntecedent = + findModalityWithMinSymbolicExecutionLabelId(sequent.antecedent(), true); + PosInOccurrence nextSuccedent = + findModalityWithMinSymbolicExecutionLabelId(sequent.succedent(), false); + if (nextAntecedent != null) { + if (nextSuccedent != null) { + SymbolicExecutionTermLabel antecedentLabel = + getSymbolicExecutionLabel(nextAntecedent.subTerm()); + SymbolicExecutionTermLabel succedentLabel = + getSymbolicExecutionLabel(nextSuccedent.subTerm()); + return antecedentLabel.getId() < succedentLabel.getId() ? nextAntecedent + : nextSuccedent; + } else { + return nextAntecedent; + } + } else { + return nextSuccedent; } - } - else { - return nextSuccedent; - } - } - else { - return null; - } - } - - /** - * Searches the modality {@link Term} with the maximal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Semisequent}. - * @param semisequent The {@link Semisequent} to search in. - * @param inAntec {@code true} antecedent, {@code false} succedent. - * @return The modality {@link Term} with the maximal ID if available or {@code null} otherwise. - */ - public static PosInOccurrence findModalityWithMaxSymbolicExecutionLabelId(Semisequent semisequent, boolean inAntec) { - if (semisequent != null) { - int maxId = Integer.MIN_VALUE; - PosInOccurrence maxPio = null; - for (SequentFormula sf : semisequent) { - PosInTerm current = findModalityWithMaxSymbolicExecutionLabelId(sf.formula()); - if (current != null) { - PosInOccurrence pio = new PosInOccurrence(sf, current, inAntec); - SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(pio.subTerm()); - if (maxPio == null || label.getId() > maxId) { - maxPio = pio; - maxId = label.getId(); - } + } else { + return null; + } + } + + /** + * Searches the modality {@link PosInOccurrence} with the minimal + * {@link SymbolicExecutionTermLabel} ID {@link SymbolicExecutionTermLabel#getId()} in the given + * {@link Semisequent}. + * + * @param semisequent The {@link Semisequent} to search in. + * @param inAntec {@code true} antecedent, {@code false} succedent. + * @return The modality {@link PosInOccurrence} with the minimal ID if available or {@code null} + * otherwise. + */ + public static PosInOccurrence findModalityWithMinSymbolicExecutionLabelId( + Semisequent semisequent, boolean inAntec) { + if (semisequent != null) { + int maxId = Integer.MIN_VALUE; + PosInOccurrence minPio = null; + for (SequentFormula sf : semisequent) { + PosInTerm current = findModalityWithMinSymbolicExecutionLabelId(sf.formula()); + if (current != null) { + PosInOccurrence pio = new PosInOccurrence(sf, current, inAntec); + SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(pio.subTerm()); + if (minPio == null || label.getId() < maxId) { + minPio = pio; + maxId = label.getId(); + } + } } - } - return maxPio; - } - else { - return null; - } - } - - /** - * Searches the modality {@link PosInTerm} with the maximal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Term}. - * @param term The {@link Term} to search in. - * @return The modality {@link PosInTerm} with the maximal ID if available or {@code null} otherwise. - */ - public static PosInTerm findModalityWithMaxSymbolicExecutionLabelId(Term term) { - if (term != null) { - FindModalityWithSymbolicExecutionLabelId visitor = new FindModalityWithSymbolicExecutionLabelId(true); - term.execPreOrder(visitor); - return visitor.getPosInTerm(); - } - else { - return null; - } - } - - /** - * Searches the modality {@link PosInOccurrence} with the minimal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Sequent}. - * @param sequent The {@link Sequent} to search in. - * @return The modality {@link PosInOccurrence} with the maximal ID if available or {@code null} otherwise. - */ - public static PosInOccurrence findModalityWithMinSymbolicExecutionLabelId(Sequent sequent) { - if (sequent != null) { - PosInOccurrence nextAntecedent = findModalityWithMinSymbolicExecutionLabelId(sequent.antecedent(), true); - PosInOccurrence nextSuccedent = findModalityWithMinSymbolicExecutionLabelId(sequent.succedent(), false); - if (nextAntecedent != null) { - if (nextSuccedent != null) { - SymbolicExecutionTermLabel antecedentLabel = getSymbolicExecutionLabel(nextAntecedent.subTerm()); - SymbolicExecutionTermLabel succedentLabel = getSymbolicExecutionLabel(nextSuccedent.subTerm()); - return antecedentLabel.getId() < succedentLabel.getId() ? nextAntecedent : nextSuccedent; + return minPio; + } else { + return null; + } + } + + /** + * Searches the modality {@link PosInTerm} with the minimal {@link SymbolicExecutionTermLabel} + * ID {@link SymbolicExecutionTermLabel#getId()} in the given {@link Term}. + * + * @param term The {@link Term} to search in. + * @return The modality {@link PosInTerm} with the maximal ID if available or {@code null} + * otherwise. + */ + public static PosInTerm findModalityWithMinSymbolicExecutionLabelId(Term term) { + if (term != null) { + FindModalityWithSymbolicExecutionLabelId visitor = + new FindModalityWithSymbolicExecutionLabelId(false); + term.execPreOrder(visitor); + return visitor.getPosInTerm(); + } else { + return null; + } + } + + /** + * Utility class used to find the maximal modality Term used by + * {@link SymbolicExecutionUtil#findModalityWithMaxSymbolicExecutionLabelId(Term)}. + * + * @author Martin Hentschel + */ + private static final class FindModalityWithSymbolicExecutionLabelId extends DefaultVisitor { + /** + * The modality {@link PosInTerm} with the maximal ID. + */ + private PosInTerm posInTerm; + + /** + * The maximal ID. + */ + private int maxId; + + /** + * {@code true} search maximal ID, {@code false} search minimal ID. + */ + private boolean maximum; + + /** + * The current {@link PosInTerm}. + */ + private PosInTerm currentPosInTerm = null; + + private Deque indexStack = new LinkedList(); + + /** + * Constructor. + * + * @param maximum {@code true} search maximal ID, {@code false} search minimal ID. + */ + public FindModalityWithSymbolicExecutionLabelId(boolean maximum) { + this.maximum = maximum; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Term visited) { + SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(visited); + if (label != null) { + if (posInTerm == null + || (maximum ? label.getId() > maxId : label.getId() < maxId)) { + posInTerm = currentPosInTerm; + maxId = label.getId(); + } } - else { - return nextAntecedent; + } + + /** + * {@inheritDoc} + */ + @Override + public void subtreeEntered(Term subtreeRoot) { + if (currentPosInTerm == null) { + currentPosInTerm = PosInTerm.getTopLevel(); + } else { + int index = indexStack.getFirst(); + currentPosInTerm = currentPosInTerm.down(index); } - } - else { - return nextSuccedent; - } - } - else { - return null; - } - } - - /** - * Searches the modality {@link PosInOccurrence} with the minimal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Semisequent}. - * @param semisequent The {@link Semisequent} to search in. - * @param inAntec {@code true} antecedent, {@code false} succedent. - * @return The modality {@link PosInOccurrence} with the minimal ID if available or {@code null} otherwise. - */ - public static PosInOccurrence findModalityWithMinSymbolicExecutionLabelId(Semisequent semisequent, boolean inAntec) { - if (semisequent != null) { - int maxId = Integer.MIN_VALUE; - PosInOccurrence minPio = null; - for (SequentFormula sf : semisequent) { - PosInTerm current = findModalityWithMinSymbolicExecutionLabelId(sf.formula()); - if (current != null) { - PosInOccurrence pio = new PosInOccurrence(sf, current, inAntec); - SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(pio.subTerm()); - if (minPio == null || label.getId() < maxId) { - minPio = pio; - maxId = label.getId(); - } + indexStack.addFirst(0); + } + + /** + * {@inheritDoc} + */ + @Override + public void subtreeLeft(Term subtreeRoot) { + currentPosInTerm = currentPosInTerm.up(); + indexStack.removeFirst(); + if (!indexStack.isEmpty()) { + Integer nextIndex = indexStack.removeFirst(); + indexStack.addFirst(nextIndex + 1); } - } - return minPio; - } - else { - return null; - } - } - - /** - * Searches the modality {@link PosInTerm} with the minimal {@link SymbolicExecutionTermLabel} ID - * {@link SymbolicExecutionTermLabel#getId()} in the given {@link Term}. - * @param term The {@link Term} to search in. - * @return The modality {@link PosInTerm} with the maximal ID if available or {@code null} otherwise. - */ - public static PosInTerm findModalityWithMinSymbolicExecutionLabelId(Term term) { - if (term != null) { - FindModalityWithSymbolicExecutionLabelId visitor = new FindModalityWithSymbolicExecutionLabelId(false); - term.execPreOrder(visitor); - return visitor.getPosInTerm(); - } - else { - return null; - } - } - - /** - * Utility class used to find the maximal modality Term - * used by {@link SymbolicExecutionUtil#findModalityWithMaxSymbolicExecutionLabelId(Term)}. - * @author Martin Hentschel - */ - private static final class FindModalityWithSymbolicExecutionLabelId extends DefaultVisitor { - /** - * The modality {@link PosInTerm} with the maximal ID. - */ - private PosInTerm posInTerm; - - /** - * The maximal ID. - */ - private int maxId; - - /** - * {@code true} search maximal ID, {@code false} search minimal ID. - */ - private boolean maximum; - - /** - * The current {@link PosInTerm}. - */ - private PosInTerm currentPosInTerm = null; - - private Deque indexStack = new LinkedList(); - - /** - * Constructor. - * @param maximum {@code true} search maximal ID, {@code false} search minimal ID. - */ - public FindModalityWithSymbolicExecutionLabelId(boolean maximum) { - this.maximum = maximum; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Term visited) { - SymbolicExecutionTermLabel label = getSymbolicExecutionLabel(visited); - if (label != null) { - if (posInTerm == null || (maximum ? label.getId() > maxId : label.getId() < maxId)) { - posInTerm = currentPosInTerm; - maxId = label.getId(); + } + + /** + * Returns the modality {@link PosInTerm} with the maximal ID. + * + * @return The modality {@link PosInTerm} with the maximal ID. + */ + public PosInTerm getPosInTerm() { + return posInTerm; + } + } + + /** + * Checks if the given {@link Node} in KeY's proof tree represents also a {@link Node} in a + * symbolic execution tree. + * + * @param node The {@link Node} of KeY's proof tree to check. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} is also symbolic execution tree node, {@code false} is no node in a + * symbolic execution tree. + */ + public static boolean isSymbolicExecutionTreeNode(Node node, RuleApp ruleApp) { + if (node != null && !isRuleAppToIgnore(ruleApp) && hasSymbolicExecutionLabel(ruleApp)) { + SourceElement statement = NodeInfo.computeActiveStatement(ruleApp); + PositionInfo posInfo = statement != null ? statement.getPositionInfo() : null; + if (isMethodReturnNode(node, ruleApp)) { + return !isInImplicitMethod(node, ruleApp); + } else if (isExceptionalMethodReturnNode(node, ruleApp)) { + return !isInImplicitMethod(node, ruleApp); + } else if (isLoopStatement(node, ruleApp, statement, posInfo)) { // This check is + // redundant to the + // loop iteration + // check, but is faster + return true; + } else if (isBranchStatement(node, ruleApp, statement, posInfo) + || isMethodCallNode(node, ruleApp, statement) + || isStatementNode(node, ruleApp, statement, posInfo) + || isTerminationNode(node, ruleApp)) { + return true; + } else if (hasLoopCondition(node, ruleApp, statement)) { + return ((LoopStatement) statement).getGuardExpression() + .getPositionInfo() != PositionInfo.UNDEFINED + && !isDoWhileLoopCondition(node, statement) + && !isForLoopCondition(node, statement); + } else if (isOperationContract(node, ruleApp)) { + return true; + } else if (isLoopInvariant(node, ruleApp)) { + return true; + } else if (isBlockSpecificationElement(node, ruleApp)) { + return true; + } else { + return false; } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void subtreeEntered(Term subtreeRoot) { - if (currentPosInTerm == null) { - currentPosInTerm = PosInTerm.getTopLevel(); - } - else { - int index = indexStack.getFirst(); - currentPosInTerm = currentPosInTerm.down(index); - } - indexStack.addFirst(0); - } - - /** - * {@inheritDoc} - */ - @Override - public void subtreeLeft(Term subtreeRoot) { - currentPosInTerm = currentPosInTerm.up(); - indexStack.removeFirst(); - if (!indexStack.isEmpty()) { - Integer nextIndex = indexStack.removeFirst(); - indexStack.addFirst(nextIndex + 1); - } - } - - /** - * Returns the modality {@link PosInTerm} with the maximal ID. - * @return The modality {@link PosInTerm} with the maximal ID. - */ - public PosInTerm getPosInTerm() { - return posInTerm; - } - } - - /** - * Checks if the given {@link Node} in KeY's proof tree represents - * also a {@link Node} in a symbolic execution tree. - * @param node The {@link Node} of KeY's proof tree to check. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} is also symbolic execution tree node, {@code false} is no node in a symbolic execution tree. - */ - public static boolean isSymbolicExecutionTreeNode(Node node, RuleApp ruleApp) { - if (node != null && !isRuleAppToIgnore(ruleApp) && hasSymbolicExecutionLabel(ruleApp)) { - SourceElement statement = NodeInfo.computeActiveStatement(ruleApp); - PositionInfo posInfo = statement != null ? statement.getPositionInfo() : null; - if (isMethodReturnNode(node, ruleApp)) { - return !isInImplicitMethod(node, ruleApp); - } - else if (isExceptionalMethodReturnNode(node, ruleApp)) { - return !isInImplicitMethod(node, ruleApp); - } - else if (isLoopStatement(node, ruleApp, statement, posInfo)) { // This check is redundant to the loop iteration check, but is faster - return true; - } - else if (isBranchStatement(node, ruleApp, statement, posInfo) || - isMethodCallNode(node, ruleApp, statement) || - isStatementNode(node, ruleApp, statement, posInfo) || - isTerminationNode(node, ruleApp)) { + } else if (isLoopBodyTermination(node, ruleApp)) { return true; - } - else if (hasLoopCondition(node, ruleApp, statement)) { - return ((LoopStatement)statement).getGuardExpression().getPositionInfo() != PositionInfo.UNDEFINED && - !isDoWhileLoopCondition(node, statement) && - !isForLoopCondition(node, statement); - } - else if (isOperationContract(node, ruleApp)) { - return true; - } - else if (isLoopInvariant(node, ruleApp)) { - return true; - } - else if (isBlockSpecificationElement(node, ruleApp)) { - return true; - } - else { + } else { return false; - } - } - else if (isLoopBodyTermination(node, ruleApp)) { - return true; - } - else { - return false; - } - } - - /** - * Checks if the given {@link RuleApp} should be ignored or - * checked for possible symbolic execution tree node representation. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} ignore {@link RuleApp}, {@code false} check if the {@link RuleApp} represents a symbolic execution tree node. - */ - public static boolean isRuleAppToIgnore(RuleApp ruleApp) { + } + } + + /** + * Checks if the given {@link RuleApp} should be ignored or checked for possible symbolic + * execution tree node representation. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} ignore {@link RuleApp}, {@code false} check if the {@link RuleApp} + * represents a symbolic execution tree node. + */ + public static boolean isRuleAppToIgnore(RuleApp ruleApp) { return "unusedLabel".equals(MiscTools.getRuleDisplayName(ruleApp)) || "elim_double_block".equals(MiscTools.getRuleDisplayName(ruleApp)); - } - - /** - * Checks if the currently executed code is in an implicit method - * ({@link IProgramMethod#isImplicit()} is {@code true}). - * @param node The {@link Node} of KeY's proof tree to check. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} is in implicit method, {@code false} is not in implicit method. - */ - public static boolean isInImplicitMethod(Node node, RuleApp ruleApp) { - Term term = ruleApp.posInOccurrence().subTerm(); - term = TermBuilder.goBelowUpdates(term); - JavaBlock block = term.javaBlock(); - IExecutionContext context = - JavaTools.getInnermostExecutionContext(block, node.proof().getServices()); - return context != null && context.getMethodContext() != null - && context.getMethodContext().isImplicit(); - } - - /** - * Compute the stack size of the given {@link Term} described by the given {@link RuleApp}. - * @param ruleApp The {@link RuleApp} which defines the {@link Term} to compute its stack size. - * @return The stack size. - */ - public static int computeStackSize(RuleApp ruleApp) { - int result = 0; - if (ruleApp != null) { - PosInOccurrence posInOc = ruleApp.posInOccurrence(); - if (posInOc != null) { - Term subTerm = posInOc.subTerm(); - if (subTerm != null) { - Term modality = TermBuilder.goBelowUpdates(subTerm); - if (modality != null) { - JavaBlock block = modality.javaBlock(); - if (block != null) { - JavaProgramElement element = block.program(); - if (element instanceof StatementBlock) { - StatementBlock b = (StatementBlock)block.program(); - ImmutableArray prefix = b.getPrefixElements(); - result = CollectionUtil.count(prefix, new IFilter() { - @Override - public boolean select(ProgramPrefix element) { - return element instanceof MethodFrame; - } - }); - } - } - } + } + + /** + * Checks if the currently executed code is in an implicit method + * ({@link IProgramMethod#isImplicit()} is {@code true}). + * + * @param node The {@link Node} of KeY's proof tree to check. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} is in implicit method, {@code false} is not in implicit method. + */ + public static boolean isInImplicitMethod(Node node, RuleApp ruleApp) { + Term term = ruleApp.posInOccurrence().subTerm(); + term = TermBuilder.goBelowUpdates(term); + JavaBlock block = term.javaBlock(); + IExecutionContext context = + JavaTools.getInnermostExecutionContext(block, node.proof().getServices()); + return context != null && context.getMethodContext() != null + && context.getMethodContext().isImplicit(); + } + + /** + * Compute the stack size of the given {@link Term} described by the given {@link RuleApp}. + * + * @param ruleApp The {@link RuleApp} which defines the {@link Term} to compute its stack size. + * @return The stack size. + */ + public static int computeStackSize(RuleApp ruleApp) { + int result = 0; + if (ruleApp != null) { + PosInOccurrence posInOc = ruleApp.posInOccurrence(); + if (posInOc != null) { + Term subTerm = posInOc.subTerm(); + if (subTerm != null) { + Term modality = TermBuilder.goBelowUpdates(subTerm); + if (modality != null) { + JavaBlock block = modality.javaBlock(); + if (block != null) { + JavaProgramElement element = block.program(); + if (element instanceof StatementBlock) { + StatementBlock b = (StatementBlock) block.program(); + ImmutableArray prefix = b.getPrefixElements(); + result = CollectionUtil.count(prefix, new IFilter() { + @Override + public boolean select(ProgramPrefix element) { + return element instanceof MethodFrame; + } + }); + } + } + } + } + } + } + return result; + } + + /** + * Checks if the given {@link SourceElement} is a do while loop. + * + * @param node The {@link Node} to check. + * @param statement The actual statement ({@link SourceElement}). + * @return {@code true} is do while loop, {@code false} is something else. + */ + public static boolean isDoWhileLoopCondition(Node node, SourceElement statement) { + return statement instanceof Do; + } + + /** + * Checks if the given {@link SourceElement} is a for loop. + * + * @param node The {@link Node} to check. + * @param statement The actual statement ({@link SourceElement}). + * @return {@code true} is for loop, {@code false} is something else. + */ + public static boolean isForLoopCondition(Node node, SourceElement statement) { + return statement instanceof For; + } + + /** + * Collects all {@link Goal}s in the subtree of the given {@link IExecutionElement}. + * + * @param executionElement The {@link IExecutionElement} to collect {@link Goal}s in. + * @return The found {@link Goal}s. + */ + public static ImmutableList collectGoalsInSubtree(IExecutionElement executionElement) { + if (executionElement != null) { + return collectGoalsInSubtree(executionElement.getProofNode()); + } else { + return ImmutableSLList.nil(); + } + } + + /** + * Collects all {@link Goal}s in the subtree of the given {@link Node}. + * + * @param node The {@link Node} to collect {@link Goal}s in. + * @return The found {@link Goal}s. + */ + public static ImmutableList collectGoalsInSubtree(Node node) { + Proof proof = node.proof(); + return proof.getSubtreeEnabledGoals(node); + } + + /** + * Searches for the given {@link Node} the parent node which also represents a symbolic + * execution tree node (checked via {@link #isSymbolicExecutionTreeNode(Node, RuleApp)}). + * + * @param node The {@link Node} to start search in. + * @param pio The {@link PosInOccurrence} of the modality. + * @return The parent {@link Node} of the given {@link Node} which is also a set node or + * {@code null} if no parent node was found. + */ + public static Node findMethodCallNode(Node node, PosInOccurrence pio) { + if (node != null && pio != null) { + // Get current program method + Term term = pio.subTerm(); + term = TermBuilder.goBelowUpdates(term); + Services services = node.proof().getServices(); + MethodFrame mf = JavaTools.getInnermostMethodFrame(term.javaBlock(), services); + if (mf != null) { + // Find call node + Node parent = node.parent(); + Node result = null; + while (parent != null && result == null) { + SourceElement activeStatement = parent.getNodeInfo().getActiveStatement(); + if (activeStatement instanceof MethodBodyStatement + && ((MethodBodyStatement) activeStatement) + .getProgramMethod(services) == mf.getProgramMethod()) { + result = parent; + } else { + parent = parent.parent(); + } + } + return result; + } else { + return null; } - } - } - return result; - } - - /** - * Checks if the given {@link SourceElement} is a do while loop. - * @param node The {@link Node} to check. - * @param statement The actual statement ({@link SourceElement}). - * @return {@code true} is do while loop, {@code false} is something else. - */ - public static boolean isDoWhileLoopCondition(Node node, SourceElement statement) { - return statement instanceof Do; - } - - /** - * Checks if the given {@link SourceElement} is a for loop. - * @param node The {@link Node} to check. - * @param statement The actual statement ({@link SourceElement}). - * @return {@code true} is for loop, {@code false} is something else. - */ - public static boolean isForLoopCondition(Node node, SourceElement statement) { - return statement instanceof For; - } - - /** - * Collects all {@link Goal}s in the subtree of the given {@link IExecutionElement}. - * @param executionElement The {@link IExecutionElement} to collect {@link Goal}s in. - * @return The found {@link Goal}s. - */ - public static ImmutableList collectGoalsInSubtree(IExecutionElement executionElement) { - if (executionElement != null) { - return collectGoalsInSubtree(executionElement.getProofNode()); - } - else { - return ImmutableSLList.nil(); - } - } - - /** - * Collects all {@link Goal}s in the subtree of the given {@link Node}. - * @param node The {@link Node} to collect {@link Goal}s in. - * @return The found {@link Goal}s. - */ - public static ImmutableList collectGoalsInSubtree(Node node) { - Proof proof = node.proof(); - return proof.getSubtreeEnabledGoals(node); - } - - /** - * Searches for the given {@link Node} the parent node - * which also represents a symbolic execution tree node - * (checked via {@link #isSymbolicExecutionTreeNode(Node, RuleApp)}). - * @param node The {@link Node} to start search in. - * @param pio The {@link PosInOccurrence} of the modality. - * @return The parent {@link Node} of the given {@link Node} which is also a set node or {@code null} if no parent node was found. - */ - public static Node findMethodCallNode(Node node, PosInOccurrence pio) { - if (node != null && pio != null) { - // Get current program method - Term term = pio.subTerm(); - term = TermBuilder.goBelowUpdates(term); - Services services = node.proof().getServices(); - MethodFrame mf = JavaTools.getInnermostMethodFrame(term.javaBlock(), services); - if (mf != null) { - // Find call node + } else { + return null; + } + } + + /** + * Searches for the given {@link Node} the parent node which also represents a symbolic + * execution tree node (checked via {@link #isSymbolicExecutionTreeNode(Node, RuleApp)}). + * + * @param node The {@link Node} to start search in. + * @return The parent {@link Node} of the given {@link Node} which is also a set node or + * {@code null} if no parent node was found. + */ + public static Node findParentSetNode(Node node) { + if (node != null) { Node parent = node.parent(); Node result = null; while (parent != null && result == null) { - SourceElement activeStatement = parent.getNodeInfo().getActiveStatement(); - if (activeStatement instanceof MethodBodyStatement && - ((MethodBodyStatement)activeStatement).getProgramMethod(services) == mf.getProgramMethod()) { - result = parent; - } - else { - parent = parent.parent(); - } + if (isSymbolicExecutionTreeNode(parent, parent.getAppliedRuleApp())) { + result = parent; + } else { + parent = parent.parent(); + } } return result; - } - else { + } else { return null; - } - } - else { - return null; - } - } - - /** - * Searches for the given {@link Node} the parent node - * which also represents a symbolic execution tree node - * (checked via {@link #isSymbolicExecutionTreeNode(Node, RuleApp)}). - * @param node The {@link Node} to start search in. - * @return The parent {@link Node} of the given {@link Node} which is also a set node or {@code null} if no parent node was found. - */ - public static Node findParentSetNode(Node node) { - if (node != null) { - Node parent = node.parent(); - Node result = null; - while (parent != null && result == null) { - if (isSymbolicExecutionTreeNode(parent, parent.getAppliedRuleApp())) { - result = parent; + } + } + + /** + * Computes the branch condition of the given {@link Node}. + * + * @param node The {@link Node} to compute its branch condition. + * @param simplify {@code true} simplify condition in a side proof, {@code false} do not + * simplify condition. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + public static Term computeBranchCondition(Node node, boolean simplify, + boolean improveReadability) throws ProofInputException { + // Get applied taclet on parent proof node + Node parent = node.parent(); + if (parent.getAppliedRuleApp() instanceof TacletApp) { + return computeTacletAppBranchCondition(parent, node, simplify, improveReadability); + } else if (parent.getAppliedRuleApp() instanceof ContractRuleApp) { + return computeContractRuleAppBranchCondition(parent, node, simplify, + improveReadability); + } else if (parent.getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp) { + return computeLoopInvariantBuiltInRuleAppBranchCondition(parent, node, simplify, + improveReadability); + } else if (parent.getAppliedRuleApp() instanceof AbstractBlockContractBuiltInRuleApp) { + return computeBlockContractBuiltInRuleAppBranchCondition(parent, node, simplify, + improveReadability); + } else { + throw new ProofInputException("Unsupported RuleApp in branch computation \"" + + parent.getAppliedRuleApp() + "\"."); + } + } + + /** + *

    + * Computes the branch condition of the given {@link Node} which was constructed by a + * {@link ContractRuleApp}. + *

    + *

    + * The branch conditions are: + *

      + *
    • Post: caller != null & exc_0 = null & (pre1 | .. | preN)
    • + *
    • ExcPost: caller != null & exc_0 != null & (excPre1 | ... | excPreM)
    • + *
    • Pre: caller != null & !(pre1 | ... | preN | excPre1 | ... | excPreM) because the branch + * is only open if all conditions are false
    • + *
    • NPE: caller = null
    • + *
    + *

    + *

    + * Idea: + *

      + *
    • Last semisequent in antecedent contains contract
    • + *
    • Contract is defined as {@code exc_0 = null} and + * {@code pre -> post}/{@code excPre -> !exc_0 = null & signals} terms
    • + *
    • Find {@code exc_0 = null} Term
    • + *
    • List all implications
    • + *
    • Filter implications for post/exceptional post branch based on the negation of + * {@code exc_0 = null}
    • + *
    • Return disjunction of all filtered implication conditions or return true if no + * implications were found
    • + *
    + *

    + * + * @param parent The parent {@link Node} of the given one. + * @param node The {@link Node} to compute its branch condition. + * @param simplify {@code true} simplify condition in a side proof, {@code false} do not + * simplify condition. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + private static Term computeContractRuleAppBranchCondition(Node parent, Node node, + boolean simplify, boolean improveReadability) throws ProofInputException { + final Services services = node.proof().getServices(); + // Make sure that a computation is possible + if (!(parent.getAppliedRuleApp() instanceof ContractRuleApp)) { + throw new ProofInputException( + "Only ContractRuleApp is allowed in branch computation but rule \"" + + parent.getAppliedRuleApp() + "\" was found."); + } + int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); + if (childIndex >= 3) { + throw new ProofInputException( + "Branch condition of null pointer check is not supported."); + } else if (childIndex == 2) { + // Assumption: Original formula in parent is replaced + PosInOccurrence pio = parent.getAppliedRuleApp().posInOccurrence(); + Term workingTerm = posInOccurrenceInOtherNode(parent, pio, node); + if (workingTerm == null) { + throw new ProofInputException( + "Term not find in precondition branch, implementation of UseOperationContractRule might have changed!"); } - else { - parent = parent.parent(); + workingTerm = TermBuilder.goBelowUpdates(workingTerm); + if (workingTerm.op() != Junctor.AND) { + throw new ProofInputException( + "And operation expected, implementation of UseOperationContractRule might have changed!"); } - } - return result; - } - else { - return null; - } - } - - /** - * Computes the branch condition of the given {@link Node}. - * @param node The {@link Node} to compute its branch condition. - * @param simplify {@code true} simplify condition in a side proof, {@code false} do not simplify condition. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - public static Term computeBranchCondition(Node node, - boolean simplify, - boolean improveReadability) throws ProofInputException { - // Get applied taclet on parent proof node - Node parent = node.parent(); - if (parent.getAppliedRuleApp() instanceof TacletApp) { - return computeTacletAppBranchCondition(parent, node, simplify, improveReadability); - } - else if (parent.getAppliedRuleApp() instanceof ContractRuleApp) { - return computeContractRuleAppBranchCondition(parent, node, simplify, improveReadability); - } - else if (parent.getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp) { - return computeLoopInvariantBuiltInRuleAppBranchCondition(parent, node, simplify, improveReadability); - } - else if (parent.getAppliedRuleApp() instanceof AbstractBlockContractBuiltInRuleApp) { - return computeBlockContractBuiltInRuleAppBranchCondition(parent, node, simplify, improveReadability); - } - else { - throw new ProofInputException("Unsupported RuleApp in branch computation \"" + parent.getAppliedRuleApp() + "\"."); - } - } - /** - *

    - * Computes the branch condition of the given {@link Node} which was constructed by a {@link ContractRuleApp}. - *

    - *

    - * The branch conditions are: - *

      - *
    • Post: caller != null & exc_0 = null & (pre1 | .. | preN)
    • - *
    • ExcPost: caller != null & exc_0 != null & (excPre1 | ... | excPreM)
    • - *
    • Pre: caller != null & !(pre1 | ... | preN | excPre1 | ... | excPreM) because the branch is only open if all conditions are false
    • - *
    • NPE: caller = null
    • - *
    - *

    - *

    - * Idea: - *

      - *
    • Last semisequent in antecedent contains contract
    • - *
    • Contract is defined as {@code exc_0 = null} and {@code pre -> post}/{@code excPre -> !exc_0 = null & signals} terms
    • - *
    • Find {@code exc_0 = null} Term
    • - *
    • List all implications
    • - *
    • Filter implications for post/exceptional post branch based on the negation of {@code exc_0 = null}
    • - *
    • Return disjunction of all filtered implication conditions or return true if no implications were found
    • - *
    - *

    - * @param parent The parent {@link Node} of the given one. - * @param node The {@link Node} to compute its branch condition. - * @param simplify {@code true} simplify condition in a side proof, {@code false} do not simplify condition. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - private static Term computeContractRuleAppBranchCondition(Node parent, - Node node, - boolean simplify, - boolean improveReadability) throws ProofInputException { - final Services services = node.proof().getServices(); - // Make sure that a computation is possible - if (!(parent.getAppliedRuleApp() instanceof ContractRuleApp)) { - throw new ProofInputException("Only ContractRuleApp is allowed in branch computation but rule \"" + parent.getAppliedRuleApp() + "\" was found."); - } - int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); - if (childIndex >= 3) { - throw new ProofInputException("Branch condition of null pointer check is not supported."); - } - else if (childIndex == 2) { - // Assumption: Original formula in parent is replaced - PosInOccurrence pio = parent.getAppliedRuleApp().posInOccurrence(); - Term workingTerm = posInOccurrenceInOtherNode(parent, pio, node); - if (workingTerm == null) { - throw new ProofInputException("Term not find in precondition branch, implementation of UseOperationContractRule might have changed!"); - } - workingTerm = TermBuilder.goBelowUpdates(workingTerm); - if (workingTerm.op() != Junctor.AND) { - throw new ProofInputException("And operation expected, implementation of UseOperationContractRule might have changed!"); - } - Term preconditions = workingTerm.sub(0); - return services.getTermBuilder().not(preconditions); - } - else { - // Assumption: Pre -> Post & ExcPre -> Signals terms are added to last semisequent in antecedent. - // Find Term to extract implications from. - ContractPostOrExcPostExceptionVariableResult search = searchContractPostOrExcPostExceptionVariable(node, node.proof().getServices()); - - List normalConditions = new LinkedList(); - List exceptinalConditions = new LinkedList(); - collectContractPreconditions(services, search, normalConditions, exceptinalConditions); - List relevantConditions = childIndex == 1 ? // Exceptional case - exceptinalConditions : - normalConditions; - Term result; - if (relevantConditions.isEmpty()) { - result = services.getTermBuilder().tt(); - } - else { - result = services.getTermBuilder().or(relevantConditions); - } - // Add exception equality - Term excEquality = search.getExceptionEquality(); - if (childIndex == 1) { // exception branch - excEquality = services.getTermBuilder().not(excEquality); - } - result = services.getTermBuilder().and(excEquality, result); - // Add caller not null to condition - if (parent.childrenCount() == 4) { - Term callerNotNullTerm = posInOccurrenceInOtherNode(parent, parent.getAppliedRuleApp().posInOccurrence(), parent.child(3)); - callerNotNullTerm = TermBuilder.goBelowUpdates(callerNotNullTerm); - if (callerNotNullTerm.op() != Junctor.NOT) { - throw new ProofInputException("Not operation expected, implementation of UseOperationContractRule might have changed!"); + Term preconditions = workingTerm.sub(0); + return services.getTermBuilder().not(preconditions); + } else { + // Assumption: Pre -> Post & ExcPre -> Signals terms are added to last semisequent in + // antecedent. + // Find Term to extract implications from. + ContractPostOrExcPostExceptionVariableResult search = + searchContractPostOrExcPostExceptionVariable(node, node.proof().getServices()); + + List normalConditions = new LinkedList(); + List exceptinalConditions = new LinkedList(); + collectContractPreconditions(services, search, normalConditions, exceptinalConditions); + List relevantConditions = childIndex == 1 ? // Exceptional case + exceptinalConditions : normalConditions; + Term result; + if (relevantConditions.isEmpty()) { + result = services.getTermBuilder().tt(); + } else { + result = services.getTermBuilder().or(relevantConditions); } - if (callerNotNullTerm.sub(0).op() != Equality.EQUALS) { - throw new ProofInputException("Equals operation expected, implementation of UseOperationContractRule might have changed!"); + // Add exception equality + Term excEquality = search.getExceptionEquality(); + if (childIndex == 1) { // exception branch + excEquality = services.getTermBuilder().not(excEquality); } - if (!(callerNotNullTerm.sub(0).sub(0).op() instanceof ProgramVariable)) { - throw new ProofInputException("ProgramVariable expected, implementation of UseOperationContractRule might have changed!"); + result = services.getTermBuilder().and(excEquality, result); + // Add caller not null to condition + if (parent.childrenCount() == 4) { + Term callerNotNullTerm = posInOccurrenceInOtherNode(parent, + parent.getAppliedRuleApp().posInOccurrence(), parent.child(3)); + callerNotNullTerm = TermBuilder.goBelowUpdates(callerNotNullTerm); + if (callerNotNullTerm.op() != Junctor.NOT) { + throw new ProofInputException( + "Not operation expected, implementation of UseOperationContractRule might have changed!"); + } + if (callerNotNullTerm.sub(0).op() != Equality.EQUALS) { + throw new ProofInputException( + "Equals operation expected, implementation of UseOperationContractRule might have changed!"); + } + if (!(callerNotNullTerm.sub(0).sub(0).op() instanceof ProgramVariable)) { + throw new ProofInputException( + "ProgramVariable expected, implementation of UseOperationContractRule might have changed!"); + } + if (!isNullSort(callerNotNullTerm.sub(0).sub(1).sort(), + parent.proof().getServices())) { + throw new ProofInputException( + "Null expected, implementation of UseOperationContractRule might have changed!"); + } + result = services.getTermBuilder().and(callerNotNullTerm, result); } - if (!isNullSort(callerNotNullTerm.sub(0).sub(1).sort(), parent.proof().getServices())) { - throw new ProofInputException("Null expected, implementation of UseOperationContractRule might have changed!"); + // Create formula which contains the value interested in. + Term condition; + if (simplify) { + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + Sequent newSequent = + createSequentToProveWithNewSuccedent(parent, (Term) null, result, true); + condition = evaluateInSideProof(services, parent.proof(), sideProofEnv, newSequent, + RESULT_LABEL, + "Operation contract branch condition computation on node " + + parent.serialNr() + " for branch " + node.serialNr() + ".", + StrategyProperties.SPLITTING_OFF); + } else { + // Add updates (in the simplify branch the updates are added during side proof + // construction) + condition = services.getTermBuilder() + .applyParallel(search.getUpdatesAndTerm().first, result); } - result = services.getTermBuilder().and(callerNotNullTerm, result); - } - // Create formula which contains the value interested in. - Term condition; - if (simplify) { - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent newSequent = createSequentToProveWithNewSuccedent(parent, (Term)null, result, true); - condition = evaluateInSideProof(services, - parent.proof(), - sideProofEnv, - newSequent, - RESULT_LABEL, - "Operation contract branch condition computation on node " + parent.serialNr() + " for branch " + node.serialNr() + ".", - StrategyProperties.SPLITTING_OFF); - } - else { - // Add updates (in the simplify branch the updates are added during side proof construction) - condition = services.getTermBuilder().applyParallel(search.getUpdatesAndTerm().first, result); - } - if (improveReadability) { - condition = improveReadability(condition, services); - } - return condition; - } - } - - /** - * Collects the preconditions of an applied operation contract. - * @param services The {@link Services} to use. - * @param search The {@link ContractPostOrExcPostExceptionVariableResult}. - * @param normalConditions The {@link List} with the normal case conditions to fill. - * @param exceptinalConditions The {@link List} with the exceptional case conditions to fill. - * @throws ProofInputException Occurred Exception. - */ - private static void collectContractPreconditions(Services services, - ContractPostOrExcPostExceptionVariableResult search, - List normalConditions, - List exceptinalConditions) throws ProofInputException { - // Treat general conditions - if (search.getWorkingTerm().op() != Junctor.AND) { - throw new ProofInputException("And operation expected, implementation of UseOperationContractRule might has changed!"); - } - Term specificationCasesTerm = search.getWorkingTerm().sub(1); - Term excDefinition = search.getExceptionDefinition(); - Term normalExcDefinition; - Term exceptionalExcDefinition; - if (excDefinition.op() == Junctor.NOT) { - exceptionalExcDefinition = excDefinition; - normalExcDefinition = search.getExceptionEquality(); - } - else { - normalExcDefinition = excDefinition; - exceptionalExcDefinition = services.getTermBuilder().not(excDefinition); - } - collectSpecifcationCasesPreconditions(normalExcDefinition, exceptionalExcDefinition, specificationCasesTerm, normalConditions, exceptinalConditions); - } - - /** - * Collects recursively the preconditions of specification cases. - * @param normalExcDefinition The normal exception equality. - * @param exceptionalExcDefinition The exceptional equality. - * @param term The current {@link Term}. - * @param normalConditions The {@link List} with the normal case conditions to fill. - * @param exceptinalConditions The {@link List} with the exceptional case conditions to fill. - * @throws ProofInputException Occurred Exception. - */ - private static void collectSpecifcationCasesPreconditions(Term normalExcDefinition, - Term exceptionalExcDefinition, - Term term, - List normalConditions, - List exceptinalConditions) throws ProofInputException { - if (term.op() == Junctor.AND) { - Term lastChild = term.sub(term.arity() - 1); - if (lastChild.equalsModIrrelevantTermLabels(normalExcDefinition) || lastChild.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - // Nothing to do, condition is just true - } - else { - Term firstChild = term.sub(0); - if (firstChild.equalsModIrrelevantTermLabels(normalExcDefinition) || firstChild.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - // Nothing to do, condition is just true + if (improveReadability) { + condition = improveReadability(condition, services); } - else { - for (int i = 0; i < term.arity(); i++) { - collectSpecifcationCasesPreconditions(normalExcDefinition, exceptionalExcDefinition, term.sub(i), normalConditions, exceptinalConditions); - } + return condition; + } + } + + /** + * Collects the preconditions of an applied operation contract. + * + * @param services The {@link Services} to use. + * @param search The {@link ContractPostOrExcPostExceptionVariableResult}. + * @param normalConditions The {@link List} with the normal case conditions to fill. + * @param exceptinalConditions The {@link List} with the exceptional case conditions to fill. + * @throws ProofInputException Occurred Exception. + */ + private static void collectContractPreconditions(Services services, + ContractPostOrExcPostExceptionVariableResult search, List normalConditions, + List exceptinalConditions) throws ProofInputException { + // Treat general conditions + if (search.getWorkingTerm().op() != Junctor.AND) { + throw new ProofInputException( + "And operation expected, implementation of UseOperationContractRule might has changed!"); + } + Term specificationCasesTerm = search.getWorkingTerm().sub(1); + Term excDefinition = search.getExceptionDefinition(); + Term normalExcDefinition; + Term exceptionalExcDefinition; + if (excDefinition.op() == Junctor.NOT) { + exceptionalExcDefinition = excDefinition; + normalExcDefinition = search.getExceptionEquality(); + } else { + normalExcDefinition = excDefinition; + exceptionalExcDefinition = services.getTermBuilder().not(excDefinition); + } + collectSpecifcationCasesPreconditions(normalExcDefinition, exceptionalExcDefinition, + specificationCasesTerm, normalConditions, exceptinalConditions); + } + + /** + * Collects recursively the preconditions of specification cases. + * + * @param normalExcDefinition The normal exception equality. + * @param exceptionalExcDefinition The exceptional equality. + * @param term The current {@link Term}. + * @param normalConditions The {@link List} with the normal case conditions to fill. + * @param exceptinalConditions The {@link List} with the exceptional case conditions to fill. + * @throws ProofInputException Occurred Exception. + */ + private static void collectSpecifcationCasesPreconditions(Term normalExcDefinition, + Term exceptionalExcDefinition, Term term, List normalConditions, + List exceptinalConditions) throws ProofInputException { + if (term.op() == Junctor.AND) { + Term lastChild = term.sub(term.arity() - 1); + if (lastChild.equalsModIrrelevantTermLabels(normalExcDefinition) + || lastChild.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + // Nothing to do, condition is just true + } else { + Term firstChild = term.sub(0); + if (firstChild.equalsModIrrelevantTermLabels(normalExcDefinition) + || firstChild.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + // Nothing to do, condition is just true + } else { + for (int i = 0; i < term.arity(); i++) { + collectSpecifcationCasesPreconditions(normalExcDefinition, + exceptionalExcDefinition, term.sub(i), normalConditions, + exceptinalConditions); + } + } } - } - } - else if (term.op() == Junctor.IMP) { - Term leftTerm = term.sub(0); - if (leftTerm.equalsModIrrelevantTermLabels(normalExcDefinition) || leftTerm.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - // Nothing to do, condition is just true - } - else { - Term rightTerm = term.sub(1); - // Deal with heavy weight specification cases - if (rightTerm.op() == Junctor.AND && - rightTerm.sub(0).op() == Junctor.IMP && - rightTerm.sub(0).sub(0).equalsModIrrelevantTermLabels(normalExcDefinition)) { - normalConditions.add(leftTerm); + } else if (term.op() == Junctor.IMP) { + Term leftTerm = term.sub(0); + if (leftTerm.equalsModIrrelevantTermLabels(normalExcDefinition) + || leftTerm.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + // Nothing to do, condition is just true + } else { + Term rightTerm = term.sub(1); + // Deal with heavy weight specification cases + if (rightTerm.op() == Junctor.AND && rightTerm.sub(0).op() == Junctor.IMP + && rightTerm.sub(0).sub(0) + .equalsModIrrelevantTermLabels(normalExcDefinition)) { + normalConditions.add(leftTerm); + } else if (rightTerm.op() == Junctor.AND && rightTerm.sub(1).op() == Junctor.IMP + && rightTerm.sub(1).sub(0) + .equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + exceptinalConditions.add(leftTerm); + } + // Deal with light weight specification cases + else if (rightTerm.op() == Junctor.IMP + && rightTerm.sub(0).equalsModIrrelevantTermLabels(normalExcDefinition)) { + normalConditions.add(leftTerm); + } else if (rightTerm.op() == Junctor.IMP && rightTerm.sub(0) + .equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + exceptinalConditions.add(leftTerm); + } else { + Term excCondition = rightTerm; + // Check if right child is exception definition + if (excCondition.op() == Junctor.AND) { + excCondition = excCondition.sub(excCondition.arity() - 1); + } + if (excCondition.equalsModIrrelevantTermLabels(normalExcDefinition)) { + normalConditions.add(leftTerm); + } else if (excCondition + .equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + exceptinalConditions.add(leftTerm); + } else { + // Check if left child is exception definition + if (rightTerm.op() == Junctor.AND) { + excCondition = rightTerm.sub(0); + if (excCondition.equalsModIrrelevantTermLabels(normalExcDefinition)) { + normalConditions.add(leftTerm); + } else if (excCondition + .equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { + exceptinalConditions.add(leftTerm); + } else { + throw new ProofInputException( + "Exeptional condition expected, implementation of UseOperationContractRule might has changed!"); + } + } else { + throw new ProofInputException( + "Exeptional condition expected, implementation of UseOperationContractRule might has changed!"); + } + } + } } - else if (rightTerm.op() == Junctor.AND && - rightTerm.sub(1).op() == Junctor.IMP && - rightTerm.sub(1).sub(0).equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - exceptinalConditions.add(leftTerm); + } + } + + /** + * Searches the used exception variable in the post or exceptional post branch of an applied + * {@link ContractRuleApp} on the parent of the given {@link Node}. + * + * @param node The {@link Node} which is the post or exceptional post branch of an applied + * {@link ContractRuleApp}. + * @param services The {@link Services} to use. + * @return The result. + * @throws ProofInputException Occurred exception if something is not as expected. + */ + public static ContractPostOrExcPostExceptionVariableResult searchContractPostOrExcPostExceptionVariable( + Node node, Services services) throws ProofInputException { + Semisequent antecedent = node.sequent().antecedent(); + SequentFormula sf = antecedent.get(antecedent.size() - 1); + Term workingTerm = sf.formula(); + Pair, Term> updatesAndTerm = TermBuilder.goBelowUpdates2(workingTerm); + workingTerm = updatesAndTerm.second; + if (workingTerm.op() != Junctor.AND) { + throw new ProofInputException( + "And operation expected, implementation of UseOperationContractRule might has changed!"); + } + workingTerm = workingTerm.sub(1); // First part is heap equality, use second part which is + // the combination of all normal and exceptional + // preconditon postcondition implications + workingTerm = TermBuilder.goBelowUpdates(workingTerm); + // Find Term exc_n = null which is added (maybe negated) to all exceptional preconditions + Term exceptionDefinition = searchExceptionDefinition(workingTerm, services); + if (exceptionDefinition == null) { + throw new ProofInputException( + "Exception definition not found, implementation of UseOperationContractRule might has changed!"); + } + // Make sure that exception equality was found + Term exceptionEquality = + exceptionDefinition.op() == Junctor.NOT ? exceptionDefinition.sub(0) + : exceptionDefinition; + return new ContractPostOrExcPostExceptionVariableResult(workingTerm, updatesAndTerm, + exceptionDefinition, exceptionEquality); + } + + /** + * Searches the exception definition. + * + * @param term The {@link Term} to start search in. + * @param services the {@link Services} to use. + * @return The found exception definition or {@code null} if not available. + */ + private static Term searchExceptionDefinition(Term term, Services services) { + if (term.op() == Equality.EQUALS && term.sub(0).op() instanceof LocationVariable + && term.sub(0).toString().startsWith("exc_") + && isNullSort(term.sub(1).sort(), services) + && services.getJavaInfo().isSubtype( + services.getJavaInfo().getKeYJavaType(term.sub(0).sort()), + services.getJavaInfo().getKeYJavaType("java.lang.Throwable"))) { + return term; + } else { + Term result = null; + int i = term.arity() - 1; + while (result == null && i >= 0) { + result = searchExceptionDefinition(term.sub(i), services); + i--; } - // Deal with light weight specification cases - else if (rightTerm.op() == Junctor.IMP && - rightTerm.sub(0).equalsModIrrelevantTermLabels(normalExcDefinition)) { - normalConditions.add(leftTerm); + return result; + } + } + + /** + * The result of + * {@link SymbolicExecutionUtil#searchContractPostOrExcPostExceptionVariable(Node, Services)}. + * + * @author Martin Hentschel + */ + public static class ContractPostOrExcPostExceptionVariableResult { + /** + * The working {@link Term}. + */ + private Term workingTerm; + + /** + * The updates. + */ + private Pair, Term> updatesAndTerm; + + /** + * The exception definition. + */ + private Term exceptionDefinition; + + /** + * The equality which contains the equality. + */ + private Term exceptionEquality; + + /** + * Constructor. + * + * @param workingTerm The working {@link Term}. + * @param updatesAndTerm The updates. + * @param exceptionDefinition The exception definition. + * @param exceptionEquality The equality which contains the equality. + */ + public ContractPostOrExcPostExceptionVariableResult(Term workingTerm, + Pair, Term> updatesAndTerm, Term exceptionDefinition, + Term exceptionEquality) { + this.workingTerm = workingTerm; + this.updatesAndTerm = updatesAndTerm; + this.exceptionDefinition = exceptionDefinition; + this.exceptionEquality = exceptionEquality; + } + + /** + * Returns the working {@link Term}. + * + * @return The working {@link Term}. + */ + public Term getWorkingTerm() { + return workingTerm; + } + + /** + * Returns the updates. + * + * @return The updates. + */ + public Pair, Term> getUpdatesAndTerm() { + return updatesAndTerm; + } + + /** + * Returns the exception definition. + * + * @return The exception definition. + */ + public Term getExceptionDefinition() { + return exceptionDefinition; + } + + /** + * Returns the equality which contains the equality. + * + * @return The equality which contains the equality. + */ + public Term getExceptionEquality() { + return exceptionEquality; + } + } + + /** + *

    + * Computes the branch condition of the given {@link Node} which was constructed by a + * {@link LoopInvariantBuiltInRuleApp}. + *

    + *

    + * The branch conditions are: + *

      + *
    • Preserves Branch: Invariant + LoopCondition
    • + *
    • Use Branch: Invariant + !LoopCondition
    • + *
    + *

    + * + * @param parent The parent {@link Node} of the given one. + * @param node The {@link Node} to compute its branch condition. + * @param simplify {@code true} simplify condition in a side proof, {@code false} do not + * simplify condition. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + private static Term computeLoopInvariantBuiltInRuleAppBranchCondition(Node parent, Node node, + boolean simplify, boolean improveReadability) throws ProofInputException { + // Make sure that a computation is possible + if (!(parent.getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp)) { + throw new ProofInputException( + "Only LoopInvariantBuiltInRuleApp is allowed in branch computation but rule \"" + + parent.getAppliedRuleApp() + "\" was found."); + } + // Make sure that branch is supported + int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); + if (childIndex == 1 || childIndex == 2) { // Body Preserves Invariant or Use Case + LoopInvariantBuiltInRuleApp app = + (LoopInvariantBuiltInRuleApp) parent.getAppliedRuleApp(); + // Compute invariant (last antecedent formula of the use branch) + Services services = parent.proof().getServices(); + Node useNode = parent.child(2); + Semisequent antecedent = useNode.sequent().antecedent(); + Term invTerm = antecedent.get(antecedent.size() - 1).formula(); + // Extract loop condition from child + Term loopConditionModalityTerm = + posInOccurrenceInOtherNode(parent, app.posInOccurrence(), node); + Pair, Term> pair = + TermBuilder.goBelowUpdates2(loopConditionModalityTerm); + loopConditionModalityTerm = pair.second; + if (childIndex == 1) { // Body Preserves Invariant + if (loopConditionModalityTerm.op() != Junctor.IMP) { + throw new ProofInputException( + "Implementation of WhileInvariantRule has changed."); + } + loopConditionModalityTerm = loopConditionModalityTerm.sub(0); + } else { // Use Case + if (loopConditionModalityTerm.op() != Modality.BOX) { + throw new ProofInputException( + "Implementation of WhileInvariantRule has changed."); + } + Term sub = loopConditionModalityTerm.sub(0); + if (sub.op() != Junctor.IMP) { + throw new ProofInputException( + "Implementation of WhileInvariantRule has changed."); + } + loopConditionModalityTerm = services.getTermBuilder() + .box(loopConditionModalityTerm.javaBlock(), sub.sub(0)); } - else if (rightTerm.op() == Junctor.IMP && - rightTerm.sub(0).equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - exceptinalConditions.add(leftTerm); + if (loopConditionModalityTerm.op() != Modality.BOX + || loopConditionModalityTerm.sub(0).op() != Equality.EQUALS + || !(loopConditionModalityTerm.sub(0).sub(0).op() instanceof LocationVariable) + || loopConditionModalityTerm.sub(0).sub(1) + .op() != (childIndex == 1 ? services.getTermBuilder().TRUE().op() + : services.getTermBuilder().FALSE().op())) { + throw new ProofInputException("Implementation of WhileInvariantRule has changed."); } - else { - Term excCondition = rightTerm; - // Check if right child is exception definition - if (excCondition.op() == Junctor.AND) { - excCondition = excCondition.sub(excCondition.arity() - 1); - } - if (excCondition.equalsModIrrelevantTermLabels(normalExcDefinition)) { - normalConditions.add(leftTerm); - } - else if (excCondition.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - exceptinalConditions.add(leftTerm); - } - else { - // Check if left child is exception definition - if (rightTerm.op() == Junctor.AND) { - excCondition = rightTerm.sub(0); - if (excCondition.equalsModIrrelevantTermLabels(normalExcDefinition)) { - normalConditions.add(leftTerm); - } - else if (excCondition.equalsModIrrelevantTermLabels(exceptionalExcDefinition)) { - exceptinalConditions.add(leftTerm); - } - else { - throw new ProofInputException("Exeptional condition expected, implementation of UseOperationContractRule might has changed!"); - } - } - else { - throw new ProofInputException("Exeptional condition expected, implementation of UseOperationContractRule might has changed!"); - } - } + // Create formula which contains the value interested in. + invTerm = TermBuilder.goBelowUpdates(invTerm); + Term loopCondAndInv = + services.getTermBuilder().and(loopConditionModalityTerm.sub(0), invTerm); + Term newTerm = loopCondAndInv; + Term modalityTerm = childIndex == 1 + ? services.getTermBuilder().box(loopConditionModalityTerm.javaBlock(), newTerm) + : services.getTermBuilder().dia(loopConditionModalityTerm.javaBlock(), newTerm); + Term condition; + if (simplify) { + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + Sequent newSequent = createSequentToProveWithNewSuccedent(parent, (Term) null, + modalityTerm, pair.first, true); + condition = evaluateInSideProof(services, parent.proof(), sideProofEnv, newSequent, + RESULT_LABEL, + "Loop invariant branch condition computation on node " + parent.serialNr() + + " for branch " + node.serialNr() + ".", + StrategyProperties.SPLITTING_OFF); + } else { + condition = services.getTermBuilder().applySequential(pair.first, modalityTerm); } - } - } - } - - /** - * Searches the used exception variable in the post or exceptional post branch of an applied {@link ContractRuleApp} on the parent of the given {@link Node}. - * @param node The {@link Node} which is the post or exceptional post branch of an applied {@link ContractRuleApp}. - * @param services The {@link Services} to use. - * @return The result. - * @throws ProofInputException Occurred exception if something is not as expected. - */ - public static ContractPostOrExcPostExceptionVariableResult searchContractPostOrExcPostExceptionVariable(Node node, Services services) throws ProofInputException { - Semisequent antecedent = node.sequent().antecedent(); - SequentFormula sf = antecedent.get(antecedent.size() - 1); - Term workingTerm = sf.formula(); - Pair,Term> updatesAndTerm = TermBuilder.goBelowUpdates2(workingTerm); - workingTerm = updatesAndTerm.second; - if (workingTerm.op() != Junctor.AND) { - throw new ProofInputException("And operation expected, implementation of UseOperationContractRule might has changed!"); - } - workingTerm = workingTerm.sub(1); // First part is heap equality, use second part which is the combination of all normal and exceptional preconditon postcondition implications - workingTerm = TermBuilder.goBelowUpdates(workingTerm); - // Find Term exc_n = null which is added (maybe negated) to all exceptional preconditions - Term exceptionDefinition = searchExceptionDefinition(workingTerm, services); - if (exceptionDefinition == null) { - throw new ProofInputException("Exception definition not found, implementation of UseOperationContractRule might has changed!"); - } - // Make sure that exception equality was found - Term exceptionEquality = exceptionDefinition.op() == Junctor.NOT ? - exceptionDefinition.sub(0) : - exceptionDefinition; - return new ContractPostOrExcPostExceptionVariableResult(workingTerm, updatesAndTerm, exceptionDefinition, exceptionEquality); - } - - /** - * Searches the exception definition. - * @param term The {@link Term} to start search in. - * @param services the {@link Services} to use. - * @return The found exception definition or {@code null} if not available. - */ - private static Term searchExceptionDefinition(Term term, Services services) { - if (term.op() == Equality.EQUALS && - term.sub(0).op() instanceof LocationVariable && - term.sub(0).toString().startsWith("exc_") && - isNullSort(term.sub(1).sort(), services) && - services.getJavaInfo().isSubtype(services.getJavaInfo().getKeYJavaType(term.sub(0).sort()), services.getJavaInfo().getKeYJavaType("java.lang.Throwable"))) { - return term; - } - else { - Term result = null; - int i = term.arity() - 1; - while (result == null && i >= 0) { - result = searchExceptionDefinition(term.sub(i), services); - i--; - } - return result; - } - } - - /** - * The result of {@link SymbolicExecutionUtil#searchContractPostOrExcPostExceptionVariable(Node, Services)}. - * @author Martin Hentschel - */ - public static class ContractPostOrExcPostExceptionVariableResult { - /** - * The working {@link Term}. - */ - private Term workingTerm; - - /** - * The updates. - */ - private Pair,Term> updatesAndTerm; - - /** - * The exception definition. - */ - private Term exceptionDefinition; - - /** - * The equality which contains the equality. - */ - private Term exceptionEquality; - - /** - * Constructor. - * @param workingTerm The working {@link Term}. - * @param updatesAndTerm The updates. - * @param exceptionDefinition The exception definition. - * @param exceptionEquality The equality which contains the equality. - */ - public ContractPostOrExcPostExceptionVariableResult(Term workingTerm, - Pair, Term> updatesAndTerm, - Term exceptionDefinition, - Term exceptionEquality) { - this.workingTerm = workingTerm; - this.updatesAndTerm = updatesAndTerm; - this.exceptionDefinition = exceptionDefinition; - this.exceptionEquality = exceptionEquality; - } - - /** - * Returns the working {@link Term}. - * @return The working {@link Term}. - */ - public Term getWorkingTerm() { - return workingTerm; - } - - /** - * Returns the updates. - * @return The updates. - */ - public Pair, Term> getUpdatesAndTerm() { - return updatesAndTerm; - } - - /** - * Returns the exception definition. - * @return The exception definition. - */ - public Term getExceptionDefinition() { - return exceptionDefinition; - } - - /** - * Returns the equality which contains the equality. - * @return The equality which contains the equality. - */ - public Term getExceptionEquality() { - return exceptionEquality; - } - } - - /** - *

    - * Computes the branch condition of the given {@link Node} which was constructed by a {@link LoopInvariantBuiltInRuleApp}. - *

    - *

    - * The branch conditions are: - *

      - *
    • Preserves Branch: Invariant + LoopCondition
    • - *
    • Use Branch: Invariant + !LoopCondition
    • - *
    - *

    - * @param parent The parent {@link Node} of the given one. - * @param node The {@link Node} to compute its branch condition. - * @param simplify {@code true} simplify condition in a side proof, {@code false} do not simplify condition. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - private static Term computeLoopInvariantBuiltInRuleAppBranchCondition(Node parent, - Node node, - boolean simplify, - boolean improveReadability) throws ProofInputException { - // Make sure that a computation is possible - if (!(parent.getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp)) { - throw new ProofInputException("Only LoopInvariantBuiltInRuleApp is allowed in branch computation but rule \"" + parent.getAppliedRuleApp() + "\" was found."); - } - // Make sure that branch is supported - int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); - if (childIndex == 1 || childIndex == 2) { // Body Preserves Invariant or Use Case - LoopInvariantBuiltInRuleApp app = (LoopInvariantBuiltInRuleApp)parent.getAppliedRuleApp(); - // Compute invariant (last antecedent formula of the use branch) - Services services = parent.proof().getServices(); - Node useNode = parent.child(2); - Semisequent antecedent = useNode.sequent().antecedent(); - Term invTerm = antecedent.get(antecedent.size() - 1).formula(); - // Extract loop condition from child - Term loopConditionModalityTerm = posInOccurrenceInOtherNode(parent, app.posInOccurrence(), node); - Pair,Term> pair = TermBuilder.goBelowUpdates2(loopConditionModalityTerm); - loopConditionModalityTerm = pair.second; - if (childIndex == 1) { // Body Preserves Invariant - if (loopConditionModalityTerm.op() != Junctor.IMP) { - throw new ProofInputException("Implementation of WhileInvariantRule has changed."); + if (improveReadability) { + condition = improveReadability(condition, services); } - loopConditionModalityTerm = loopConditionModalityTerm.sub(0); - } - else { // Use Case - if (loopConditionModalityTerm.op() != Modality.BOX) { - throw new ProofInputException("Implementation of WhileInvariantRule has changed."); + return condition; + } else { + throw new ProofInputException( + "Branch condition of initially valid check is not supported."); + } + } + + /** + *

    + * Computes the branch condition of the given {@link Node} which was constructed by an + * {@link AbstractBlockContractBuiltInRuleApp}. + *

    + *

    + * The branch conditions are: + *

      + *
    • Validity: true
    • + *
    • Usage: Postcondition (added antecedent top level formula)
    • + *
    + *

    + * + * @param parent The parent {@link Node} of the given one. + * @param node The {@link Node} to compute its branch condition. + * @param simplify {@code true} simplify condition in a side proof, {@code false} do not + * simplify condition. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + private static Term computeBlockContractBuiltInRuleAppBranchCondition(Node parent, Node node, + boolean simplify, boolean improveReadability) throws ProofInputException { + // Make sure that a computation is possible + if (!(parent.getAppliedRuleApp() instanceof AbstractBlockContractBuiltInRuleApp)) { + throw new ProofInputException( + "Only AbstractBlockContractBuiltInRuleApp is allowed in branch computation but rule \"" + + parent.getAppliedRuleApp() + "\" was found."); + } + + RuleApp app = parent.getAppliedRuleApp(); + + // Make sure that branch is supported + int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); + if (app instanceof BlockContractInternalBuiltInRuleApp && childIndex == 0) { + // Validity branch + return parent.proof().getServices().getTermBuilder().tt(); + } else if ((app instanceof BlockContractInternalBuiltInRuleApp && childIndex == 2) + || (app instanceof BlockContractExternalBuiltInRuleApp && childIndex == 1)) { + // Usage branch + // Compute invariant (last antecedent formula of the use branch) + Services services = parent.proof().getServices(); + Semisequent antecedent = node.sequent().antecedent(); + Term condition = antecedent.get(antecedent.size() - 1).formula(); + if (simplify) { + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it + // has + // an + // internal + // state + // and + // the + // default + // instance + // can't + // be + // used + // parallel. + Sequent newSequent = createSequentToProveWithNewSuccedent(parent, (Term) null, + condition, null, true); + condition = evaluateInSideProof(services, parent.proof(), sideProofEnv, newSequent, + RESULT_LABEL, + "Block contract branch condition computation on node " + parent.serialNr() + + " for branch " + node.serialNr() + ".", + StrategyProperties.SPLITTING_OFF); } - Term sub = loopConditionModalityTerm.sub(0); - if (sub.op() != Junctor.IMP) { - throw new ProofInputException("Implementation of WhileInvariantRule has changed."); + if (improveReadability) { + condition = improveReadability(condition, services); } - loopConditionModalityTerm = services.getTermBuilder().box(loopConditionModalityTerm.javaBlock(), sub.sub(0)); - } - if (loopConditionModalityTerm.op() != Modality.BOX || - loopConditionModalityTerm.sub(0).op() != Equality.EQUALS || - !(loopConditionModalityTerm.sub(0).sub(0).op() instanceof LocationVariable) || - loopConditionModalityTerm.sub(0).sub(1).op() != (childIndex == 1 ? services.getTermBuilder().TRUE().op() : services.getTermBuilder().FALSE().op())) { - throw new ProofInputException("Implementation of WhileInvariantRule has changed."); - } - // Create formula which contains the value interested in. - invTerm = TermBuilder.goBelowUpdates(invTerm); - Term loopCondAndInv = services.getTermBuilder().and(loopConditionModalityTerm.sub(0), invTerm); - Term newTerm = loopCondAndInv; - Term modalityTerm = childIndex == 1 ? - services.getTermBuilder().box(loopConditionModalityTerm.javaBlock(), newTerm) : - services.getTermBuilder().dia(loopConditionModalityTerm.javaBlock(), newTerm); - Term condition; - if (simplify) { - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent newSequent = createSequentToProveWithNewSuccedent(parent, (Term)null, modalityTerm, pair.first, true); - condition = evaluateInSideProof(services, - parent.proof(), - sideProofEnv, - newSequent, - RESULT_LABEL, - "Loop invariant branch condition computation on node " + parent.serialNr() + " for branch " + node.serialNr() + ".", - StrategyProperties.SPLITTING_OFF); - } - else { - condition = services.getTermBuilder().applySequential(pair.first, modalityTerm); - } - if (improveReadability) { - condition = improveReadability(condition, services); - } - return condition; - } - else { - throw new ProofInputException("Branch condition of initially valid check is not supported."); - } - } - - /** - *

    - * Computes the branch condition of the given {@link Node} which was constructed by an - * {@link AbstractBlockContractBuiltInRuleApp}. - *

    - *

    - * The branch conditions are: - *

      - *
    • Validity: true
    • - *
    • Usage: Postcondition (added antecedent top level formula)
    • - *
    - *

    - * @param parent The parent {@link Node} of the given one. - * @param node The {@link Node} to compute its branch condition. - * @param simplify {@code true} simplify condition in a side proof, {@code false} do not simplify condition. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - private static Term computeBlockContractBuiltInRuleAppBranchCondition( - Node parent, Node node, boolean simplify, boolean improveReadability) - throws ProofInputException { - // Make sure that a computation is possible - if (!(parent.getAppliedRuleApp() instanceof AbstractBlockContractBuiltInRuleApp)) { - throw new ProofInputException("Only AbstractBlockContractBuiltInRuleApp is allowed in branch computation but rule \"" + parent.getAppliedRuleApp() + "\" was found."); - } - - RuleApp app = parent.getAppliedRuleApp(); - - // Make sure that branch is supported - int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); - if (app instanceof BlockContractInternalBuiltInRuleApp && childIndex == 0) { - // Validity branch - return parent.proof().getServices().getTermBuilder().tt(); - } - else if ((app instanceof BlockContractInternalBuiltInRuleApp && childIndex == 2) - || (app instanceof BlockContractExternalBuiltInRuleApp && childIndex == 1)) { - // Usage branch - // Compute invariant (last antecedent formula of the use branch) - Services services = parent.proof().getServices(); - Semisequent antecedent = node.sequent().antecedent(); - Term condition = antecedent.get(antecedent.size() - 1).formula(); - if (simplify) { - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent newSequent = createSequentToProveWithNewSuccedent(parent, (Term)null, condition, null, true); - condition = evaluateInSideProof(services, - parent.proof(), - sideProofEnv, - newSequent, - RESULT_LABEL, - "Block contract branch condition computation on node " + parent.serialNr() + " for branch " + node.serialNr() + ".", - StrategyProperties.SPLITTING_OFF); - } - if (improveReadability) { + return condition; + } else { + throw new ProofInputException( + "Branch condition of precondition check is not supported."); + } + } + + /** + * Returns the {@link Term} described by the given {@link PosInOccurrence} of the original + * {@link Node} in the {@link Node} to apply on. + * + * @param original The original {@link Node} on which the given {@link PosInOccurrence} works. + * @param pio The given {@link PosInOccurrence}. + * @param toApplyOn The new {@link Node} to apply the {@link PosInOccurrence} on. + * @return The {@link Term} in the other {@link Node} described by the {@link PosInOccurrence} + * or {@code null} if not available. + */ + public static Term posInOccurrenceInOtherNode(Node original, PosInOccurrence pio, + Node toApplyOn) { + PosInOccurrence appliedPIO = posInOccurrenceToOtherSequent(original, pio, toApplyOn); + if (appliedPIO != null) { + return appliedPIO.subTerm(); + } else { + return null; + } + } + + /** + * Returns the {@link Term} described by the given {@link PosInOccurrence} of the original + * {@link Sequent} in the {@link Sequent} to apply on. + * + * @param original The original {@link Sequent} on which the given {@link PosInOccurrence} + * works. + * @param pio The given {@link PosInOccurrence}. + * @param toApplyOn The new {@link Sequent} to apply the {@link PosInOccurrence} on. + * @return The {@link Term} in the other {@link Sequent} described by the + * {@link PosInOccurrence} or {@code null} if not available. + */ + public static Term posInOccurrenceInOtherNode(Sequent original, PosInOccurrence pio, + Sequent toApplyOn) { + PosInOccurrence appliedPIO = posInOccurrenceToOtherSequent(original, pio, toApplyOn); + if (appliedPIO != null) { + return appliedPIO.subTerm(); + } else { + return null; + } + } + + /** + * Returns the {@link PosInOccurrence} described by the given {@link PosInOccurrence} of the + * original {@link Node} in the {@link Node} to apply too. + * + * @param original The original {@link Node} on which the given {@link PosInOccurrence} works. + * @param pio The given {@link PosInOccurrence}. + * @param toApplyTo The new {@link Node} to apply the {@link PosInOccurrence} to. + * @return The {@link PosInOccurrence} in the other {@link Node} described by the + * {@link PosInOccurrence} or {@code null} if not available. + */ + public static PosInOccurrence posInOccurrenceToOtherSequent(Node original, PosInOccurrence pio, + Node toApplyTo) { + if (original != null && toApplyTo != null) { + return posInOccurrenceToOtherSequent(original.sequent(), pio, toApplyTo.sequent()); + } else { + return null; + } + } + + /** + * Returns the {@link PosInOccurrence} described by the given {@link PosInOccurrence} of the + * original {@link Sequent} in the {@link Sequent} to apply too. + * + * @param original The original {@link Sequent} on which the given {@link PosInOccurrence} + * works. + * @param pio The given {@link PosInOccurrence}. + * @param toApplyTo The new {@link Sequent} to apply the {@link PosInOccurrence} to. + * @return The {@link PosInOccurrence} in the other {@link Sequent} described by the + * {@link PosInOccurrence} or {@code null} if not available. + */ + public static PosInOccurrence posInOccurrenceToOtherSequent(Sequent original, + PosInOccurrence pio, Sequent toApplyTo) { + if (original != null && pio != null && toApplyTo != null) { + // Search index of formula in original sequent + SequentFormula originalSF = pio.sequentFormula(); + boolean antecendet = pio.isInAntec(); + int index; + if (antecendet) { + index = original.antecedent().indexOf(originalSF); + } else { + index = original.succedent().indexOf(originalSF); + } + if (index >= 0) { + final SequentFormula toApplyToSF = + (antecendet ? toApplyTo.antecedent() : toApplyTo.succedent()).get(index); + return new PosInOccurrence(toApplyToSF, pio.posInTerm(), antecendet); + } else { + return null; + } + } else { + return null; + } + } + + /** + * Computes the branch condition of the given {@link Node} which was constructed by a + * {@link TacletApp}. + * + * @param parent The parent {@link Node} of the given one. + * @param node The {@link Node} to compute its branch condition. + * @param simplify {@code true} simplify condition in a side proof, {@code false} do not + * simplify condition. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed branch condition. + * @throws ProofInputException Occurred Exception. + */ + private static Term computeTacletAppBranchCondition(Node parent, Node node, boolean simplify, + boolean improveReadability) throws ProofInputException { + if (!(parent.getAppliedRuleApp() instanceof TacletApp)) { + throw new ProofInputException( + "Only TacletApp is allowed in branch computation but rule \"" + + parent.getAppliedRuleApp() + "\" was found."); + } + TacletApp app = (TacletApp) parent.getAppliedRuleApp(); + Services services = node.proof().getServices(); + // List new sequent formulas in the child node. + ImmutableList newAntecedents = + listNewSemisequentTerms(parent.sequent().antecedent(), node.sequent().antecedent()); + ImmutableList newSuccedents = + listNewSemisequentTerms(parent.sequent().succedent(), node.sequent().succedent()); + // Find goal template which has created the represented proof node + int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); + TacletGoalTemplate goalTemplate; + if (app.taclet().goalTemplates().size() + 1 == parent.childrenCount()) { + if (childIndex == 0) { + goalTemplate = null; + } else { + goalTemplate = app.taclet().goalTemplates() + .take(app.taclet().goalTemplates().size() - childIndex).head(); + } + } else { + goalTemplate = app.taclet().goalTemplates() + .take(app.taclet().goalTemplates().size() - 1 - childIndex).head(); + } + // Instantiate replace object if required + if (goalTemplate != null) { + if (goalTemplate.replaceWithExpressionAsObject() instanceof Sequent) { + // Remove replace part of symbolic execution rules + if (NodeInfo.isSymbolicExecution(app.taclet())) { + Sequent sequent = (Sequent) goalTemplate.replaceWithExpressionAsObject(); + for (SequentFormula sf : sequent.antecedent()) { + Term replaceTerm = instantiateTerm(node, sf.formula(), app, services); + replaceTerm = services.getTermBuilder().applyUpdatePairsSequential( + app.instantiations().getUpdateContext(), replaceTerm); + Term originalTerm = findReplacement(node.sequent().antecedent(), + app.posInOccurrence(), replaceTerm); + assert originalTerm != null; + newAntecedents = newAntecedents.removeFirst(originalTerm); + } + for (SequentFormula sf : sequent.succedent()) { + Term replaceTerm = instantiateTerm(node, sf.formula(), app, services); + replaceTerm = services.getTermBuilder().applyUpdatePairsSequential( + app.instantiations().getUpdateContext(), replaceTerm); + Term originalTerm = findReplacement(node.sequent().succedent(), + app.posInOccurrence(), replaceTerm); + assert originalTerm != null; + newSuccedents = newSuccedents.removeFirst(originalTerm); + } + } + } else if (goalTemplate.replaceWithExpressionAsObject() instanceof Term) { + Term replaceTerm = (Term) goalTemplate.replaceWithExpressionAsObject(); + replaceTerm = instantiateTerm(node, replaceTerm, app, services); + Term originalTerm = + findReplacement( + app.posInOccurrence().isInAntec() ? node.sequent().antecedent() + : node.sequent().succedent(), + app.posInOccurrence(), replaceTerm); + assert originalTerm != null; + if (app.posInOccurrence().isInAntec()) { + newAntecedents = newAntecedents.removeFirst(originalTerm); + } else { + newSuccedents = newSuccedents.removeFirst(originalTerm); + } + if (!NodeInfo.isSymbolicExecution(app.taclet())) { + // Make sure that an PosTacletApp was applied + if (!(app instanceof PosTacletApp)) { + throw new ProofInputException( + "Only PosTacletApp are allowed with a replace term in branch computation but rule \"" + + app + "\" was found."); + } + // Create new lists + ImmutableList tempAntecedents = ImmutableSLList.nil(); + ImmutableList tempSuccedents = ImmutableSLList.nil(); + // Apply updates on antecedents and add result to new antecedents list + for (Term a : newAntecedents) { + tempAntecedents = tempAntecedents + .append(services.getTermBuilder().applyUpdatePairsSequential( + app.instantiations().getUpdateContext(), a)); + } + // Apply updates on succedents and add result to new succedents list + for (Term suc : newSuccedents) { + tempSuccedents = tempSuccedents + .append(services.getTermBuilder().applyUpdatePairsSequential( + app.instantiations().getUpdateContext(), suc)); + } + // Add additional equivalenz term to antecedent with the replace object which + // must be equal to the find term + replaceTerm = followPosInOccurrence(app.posInOccurrence(), originalTerm); + replaceTerm = services.getTermBuilder().equals(replaceTerm, + app.posInOccurrence().subTerm()); + replaceTerm = services.getTermBuilder().applyUpdatePairsSequential( + app.instantiations().getUpdateContext(), replaceTerm); + if (!tempAntecedents.contains(replaceTerm)) { + tempAntecedents = tempAntecedents.append(replaceTerm); + } + // Replace old with new lists + newAntecedents = tempAntecedents; + newSuccedents = tempSuccedents; + } + } else if (goalTemplate.replaceWithExpressionAsObject() != null) { + throw new ProofInputException( + "Expected replacement as Sequent or Term during branch condition computation but is \"" + + goalTemplate.replaceWithExpressionAsObject() + "\"."); + } + } + // Compute branch condition + Term newLeft = services.getTermBuilder().and(newAntecedents); + Term newRight = services.getTermBuilder().or(newSuccedents); + Term newLeftAndRight = + services.getTermBuilder().and(newLeft, services.getTermBuilder().not(newRight)); + // Simplify condition if required + Term condition; + if (simplify) { + // Create formula which contains the value interested in. + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New + // OneStepSimplifier + // is + // required + // because + // it has + // an + // internal + // state + // and the + // default + // instance + // can't + // be used + // parallel. + Sequent newSequent = createSequentToProveWithNewSuccedent(parent, null, (Term) null, + newLeftAndRight, true); + condition = evaluateInSideProof(services, parent.proof(), sideProofEnv, newSequent, + RESULT_LABEL, + "Taclet branch condition computation on node " + parent.serialNr() + + " for branch " + node.serialNr() + ".", + StrategyProperties.SPLITTING_OFF); + } else { + condition = newLeftAndRight; + } + if (improveReadability) { condition = improveReadability(condition, services); - } - return condition; - } - else { - throw new ProofInputException("Branch condition of precondition check is not supported."); - } - } - - /** - * Returns the {@link Term} described by the given {@link PosInOccurrence} of the original {@link Node} - * in the {@link Node} to apply on. - * @param original The original {@link Node} on which the given {@link PosInOccurrence} works. - * @param pio The given {@link PosInOccurrence}. - * @param toApplyOn The new {@link Node} to apply the {@link PosInOccurrence} on. - * @return The {@link Term} in the other {@link Node} described by the {@link PosInOccurrence} or {@code null} if not available. - */ - public static Term posInOccurrenceInOtherNode(Node original, PosInOccurrence pio, Node toApplyOn) { - PosInOccurrence appliedPIO = posInOccurrenceToOtherSequent(original, pio, toApplyOn); - if (appliedPIO != null) { - return appliedPIO.subTerm(); - } - else { - return null; - } - } - - /** - * Returns the {@link Term} described by the given {@link PosInOccurrence} of the original {@link Sequent} - * in the {@link Sequent} to apply on. - * @param original The original {@link Sequent} on which the given {@link PosInOccurrence} works. - * @param pio The given {@link PosInOccurrence}. - * @param toApplyOn The new {@link Sequent} to apply the {@link PosInOccurrence} on. - * @return The {@link Term} in the other {@link Sequent} described by the {@link PosInOccurrence} or {@code null} if not available. - */ - public static Term posInOccurrenceInOtherNode(Sequent original, PosInOccurrence pio, Sequent toApplyOn) { - PosInOccurrence appliedPIO = posInOccurrenceToOtherSequent(original, pio, toApplyOn); - if (appliedPIO != null) { - return appliedPIO.subTerm(); - } - else { - return null; - } - } - - /** - * Returns the {@link PosInOccurrence} described by the given {@link PosInOccurrence} of the original {@link Node} - * in the {@link Node} to apply too. - * @param original The original {@link Node} on which the given {@link PosInOccurrence} works. - * @param pio The given {@link PosInOccurrence}. - * @param toApplyTo The new {@link Node} to apply the {@link PosInOccurrence} to. - * @return The {@link PosInOccurrence} in the other {@link Node} described by the {@link PosInOccurrence} or {@code null} if not available. - */ - public static PosInOccurrence posInOccurrenceToOtherSequent(Node original, PosInOccurrence pio, Node toApplyTo) { - if (original != null && toApplyTo != null) { - return posInOccurrenceToOtherSequent(original.sequent(), pio, toApplyTo.sequent()); - } - else { - return null; - } - } - - /** - * Returns the {@link PosInOccurrence} described by the given {@link PosInOccurrence} of the original {@link Sequent} - * in the {@link Sequent} to apply too. - * @param original The original {@link Sequent} on which the given {@link PosInOccurrence} works. - * @param pio The given {@link PosInOccurrence}. - * @param toApplyTo The new {@link Sequent} to apply the {@link PosInOccurrence} to. - * @return The {@link PosInOccurrence} in the other {@link Sequent} described by the {@link PosInOccurrence} or {@code null} if not available. - */ - public static PosInOccurrence posInOccurrenceToOtherSequent(Sequent original, PosInOccurrence pio, - Sequent toApplyTo) { - if (original != null && pio != null && toApplyTo != null) { - // Search index of formula in original sequent - SequentFormula originalSF = pio.sequentFormula(); - boolean antecendet = pio.isInAntec(); - int index; - if (antecendet) { - index = original.antecedent().indexOf(originalSF); - } - else { - index = original.succedent().indexOf(originalSF); - } - if (index >= 0) { - final SequentFormula toApplyToSF = (antecendet ? toApplyTo.antecedent() : toApplyTo.succedent()).get(index); - return new PosInOccurrence(toApplyToSF, pio.posInTerm(), antecendet); - } - else { + } + return condition; + } + + /** + * Lists the {@link Term}s of all new {@link SequentFormula} in the child {@link Semisequent}. + * + * @param parent The parent {@link Semisequent}. + * @param child The child {@link Semisequent}. + * @return An {@link ImmutableList} with all new {@link Term}s. + */ + private static ImmutableList listNewSemisequentTerms(Semisequent parent, + Semisequent child) { + Set parentSFs = new HashSet(); + for (SequentFormula sf : parent) { + parentSFs.add(sf); + } + ImmutableList result = ImmutableSLList.nil(); + for (SequentFormula sf : child) { + if (!parentSFs.contains(sf)) { + result = result.append(sf.formula()); + } + } + return result; + } + + /** + * Searches the by {@link Rule} application instantiated replace {@link Term} which is equal + * modulo labels to the given replace {@link Term}. + * + * @param terms The available candidates created by {@link Rule} application. + * @param posInOccurrence The {@link PosInOccurrence} on which the rule was applied. + * @param replaceTerm The {@link Term} to find. + * @return The found {@link Term} or {@code null} if not available. + */ + private static Term findReplacement(Semisequent semisequent, + final PosInOccurrence posInOccurrence, final Term replaceTerm) { + SequentFormula sf = CollectionUtil.search(semisequent, new IFilter() { + @Override + public boolean select(SequentFormula element) { + return checkReplaceTerm(element.formula(), posInOccurrence, replaceTerm); + } + }); + return sf != null ? sf.formula() : null; + } + + /** + * Checks if the given replace {@link Term} is equal module labels to the {@link Term} to check. + * + * @param toCheck The {@link Term} to check. + * @param posInOccurrence The {@link PosInOccurrence} of the {@link Rule} application. + * @param replaceTerm The {@link Term} to compare with. + * @return {@code true} equal modulo labels, {@code false} not equal at all. + */ + private static boolean checkReplaceTerm(Term toCheck, PosInOccurrence posInOccurrence, + Term replaceTerm) { + Term termAtPio = followPosInOccurrence(posInOccurrence, toCheck); + if (termAtPio != null) { + return termAtPio.equalsModRenaming(replaceTerm); + } else { + return false; + } + } + + /** + * Returns the sub {@link Term} at the given {@link PosInOccurrence} but on the given + * {@link Term} instead of the one contained in the {@link PosInOccurrence}. + * + * @param posInOccurrence The {@link PosInOccurrence} which defines the sub term position. + * @param term The {@link Term} to work with. + * @return The found sub {@link Term} or {@code null} if the {@link PosInOccurrence} is not + * compatible. + */ + public static Term followPosInOccurrence(PosInOccurrence posInOccurrence, Term term) { + boolean matches = true; + IntIterator iter = posInOccurrence.posInTerm().iterator(); + while (matches && iter.hasNext()) { + int index = iter.next(); + if (index < term.arity()) { + term = term.sub(index); + } else { + matches = false; + } + } + return matches ? term : null; + } + + /** + * Instantiates the given {@link Term} of the applied {@link TacletApp}. + * + * @param node The current {@link Node}. + * @param term The {@link Term} to instantiate. + * @param tacletApp The {@link TacletApp} to consider. + * @param services The {@link Services} to use. + * @return The instantiated {@link Term} or {@code null} if no {@link Term} was given. + */ + public static Term instantiateTerm(Node node, Term term, TacletApp tacletApp, + Services services) { + if (term != null) { + SyntacticalReplaceVisitor visitor = new SyntacticalReplaceVisitor(new TermLabelState(), + null, tacletApp.posInOccurrence(), tacletApp.instantiations(), null, + tacletApp.taclet(), tacletApp, services); + term.execPostOrder(visitor); + return visitor.getTerm(); + } else { return null; - } - } - else { - return null; - } - } - - /** - * Computes the branch condition of the given {@link Node} which was constructed by a {@link TacletApp}. - * @param parent The parent {@link Node} of the given one. - * @param node The {@link Node} to compute its branch condition. - * @param simplify {@code true} simplify condition in a side proof, {@code false} do not simplify condition. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed branch condition. - * @throws ProofInputException Occurred Exception. - */ - private static Term computeTacletAppBranchCondition(Node parent, - Node node, - boolean simplify, - boolean improveReadability) throws ProofInputException { - if (!(parent.getAppliedRuleApp() instanceof TacletApp)) { - throw new ProofInputException("Only TacletApp is allowed in branch computation but rule \"" + parent.getAppliedRuleApp() + "\" was found."); - } - TacletApp app = (TacletApp)parent.getAppliedRuleApp(); - Services services = node.proof().getServices(); - // List new sequent formulas in the child node. - ImmutableList newAntecedents = listNewSemisequentTerms(parent.sequent().antecedent(), node.sequent().antecedent()); - ImmutableList newSuccedents = listNewSemisequentTerms(parent.sequent().succedent(), node.sequent().succedent()); - // Find goal template which has created the represented proof node - int childIndex = CollectionUtil.indexOf(parent.childrenIterator(), node); - TacletGoalTemplate goalTemplate; - if (app.taclet().goalTemplates().size() + 1 == parent.childrenCount()) { - if (childIndex == 0) { - goalTemplate = null; - } - else { - goalTemplate = app.taclet().goalTemplates().take(app.taclet().goalTemplates().size() - childIndex).head(); - } - } - else { - goalTemplate = app.taclet().goalTemplates().take(app.taclet().goalTemplates().size() - 1 - childIndex).head(); - } - // Instantiate replace object if required - if (goalTemplate != null) { - if (goalTemplate.replaceWithExpressionAsObject() instanceof Sequent) { - // Remove replace part of symbolic execution rules - if (NodeInfo.isSymbolicExecution(app.taclet())) { - Sequent sequent = (Sequent) goalTemplate.replaceWithExpressionAsObject(); - for (SequentFormula sf : sequent.antecedent()) { - Term replaceTerm = instantiateTerm(node, sf.formula(), app, services); - replaceTerm = services.getTermBuilder().applyUpdatePairsSequential(app.instantiations().getUpdateContext(), replaceTerm); - Term originalTerm = findReplacement(node.sequent().antecedent(), app.posInOccurrence(), replaceTerm); - assert originalTerm != null; - newAntecedents = newAntecedents.removeFirst(originalTerm); - } - for (SequentFormula sf : sequent.succedent()) { - Term replaceTerm = instantiateTerm(node, sf.formula(), app, services); - replaceTerm = services.getTermBuilder().applyUpdatePairsSequential(app.instantiations().getUpdateContext(), replaceTerm); - Term originalTerm = findReplacement(node.sequent().succedent(), app.posInOccurrence(), replaceTerm); - assert originalTerm != null; - newSuccedents = newSuccedents.removeFirst(originalTerm); - } + } + } + + /** + * Starts the side proof and evaluates the {@link Sequent} to prove into a single {@link Term}. + * + * @param services The {@link Services} to use. + * @param proof The {@link Proof} from on which the side proof si performed. + * @param sequentToProve The {@link Sequent} to prove in a side proof. + * @param label The {@link TermLabel} which is used to compute the result. + * @param description The side proof description. + * @param splittingOption The splitting options to use. + * @return The result {@link Term}. + * @throws ProofInputException Occurred Exception. + */ + private static Term evaluateInSideProof(Services services, Proof proof, + ProofEnvironment sideProofEnvironment, Sequent sequentToProve, TermLabel label, + String description, String splittingOption) throws ProofInputException { + List> resultValuesAndConditions = + SymbolicExecutionSideProofUtil.computeResults(services, proof, sideProofEnvironment, + sequentToProve, label, description, StrategyProperties.METHOD_NONE, // Stop + // at + // methods + // to + // avoid + // endless + // executions + // and + // scenarios + // in + // which + // a + // precondition + // or + // null + // pointer + // check + // can't + // be + // shown + StrategyProperties.LOOP_NONE, // Stop at loops to avoid endless executions + // and scenarios in which the invariant can't + // be shown to be initially valid or + // preserved. + StrategyProperties.QUERY_OFF, // Stop at queries to to avoid endless + // executions and scenarios in which a + // precondition or null pointer check can't be + // shown + splittingOption, false); + ImmutableList goalCondtions = ImmutableSLList.nil(); + for (Pair pair : resultValuesAndConditions) { + Term goalCondition = pair.first; + goalCondition = SymbolicExecutionUtil.replaceSkolemConstants(pair.second.sequent(), + goalCondition, services); + goalCondition = removeLabelRecursive(services.getTermFactory(), goalCondition, label); + goalCondtions = goalCondtions.append(goalCondition); + } + return services.getTermBuilder().and(goalCondtions); + } + + /** + * Returns the default choice value. Attention: This method returns {@code null} if it + * is called before a proof is instantiated the first time. It can be checked via + * {@link #isChoiceSettingInitialised()}. + * + * @param key The choice key. + * @return The choice value. + */ + public static String getChoiceSetting(String key) { + Map settings = + ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); + return settings.get(key); + } + + /** + * Sets the default choice value. Attention: Settings should not be changed before the + * first proof is instantiated in KeY. Otherwise the default settings are not loaded. If default + * settings are defined can be checked via {@link #isChoiceSettingInitialised()}. + * + * @param key The choice key to modify. + * @param value The new choice value to set. + */ + public static void setChoiceSetting(String key, String value) { + HashMap settings = + ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); + HashMap clone = new LinkedHashMap(); + clone.putAll(settings); + clone.put(key, value); + ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().setDefaultChoices(clone); + } + + /** + * Checks if the given {@link Term} is null in the {@link Sequent} of the given {@link Node}. + * + * @param node The {@link Node} which provides the original {@link Sequent} + * @param additionalAntecedent An additional antecedent. + * @param newSuccedent The {@link Term} to check. + * @return {@code true} {@link Term} was evaluated to null, {@code false} {@link Term} was not + * evaluated to null. + * @throws ProofInputException Occurred Exception + */ + public static boolean isNull(Node node, Term additionalAntecedent, Term newSuccedent) + throws ProofInputException { + return checkNull(node, additionalAntecedent, newSuccedent, true); + } + + /** + * Checks if the given {@link Term} is not null in the {@link Sequent} of the given + * {@link Node}. + * + * @param node The {@link Node} which provides the original {@link Sequent} + * @param additionalAntecedent An additional antecedent. + * @param newSuccedent The {@link Term} to check. + * @return {@code true} {@link Term} was evaluated to not null, {@code false} {@link Term} was + * not evaluated to not null. + * @throws ProofInputException Occurred Exception + */ + public static boolean isNotNull(Node node, Term additionalAntecedent, Term newSuccedent) + throws ProofInputException { + return checkNull(node, additionalAntecedent, newSuccedent, false); + } + + /** + * Checks if the given {@link Term} is null or not in the {@link Sequent} of the given + * {@link Node}. + * + * @param node The {@link Node} which provides the original {@link Sequent} + * @param additionalAntecedent An additional antecedent. + * @param newSuccedent The {@link Term} to check. + * @param nullExpected {@code true} expect that {@link Term} is null, {@code false} expect that + * term is not null. + * @return {@code true} term is null value matches the expected nullExpected value, + * {@code false} otherwise. + * @throws ProofInputException Occurred Exception + */ + private static boolean checkNull(Node node, Term additionalAntecedent, Term newSuccedent, + boolean nullExpected) throws ProofInputException { + // Make sure that correct parameters are given + assert node != null; + assert newSuccedent != null; + // Create Sequent to prove + final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil + .cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New + // OneStepSimplifier + // is required + // because it + // has an + // internal + // state and the + // default + // instance + // can't be used + // parallel. + final TermBuilder tb = sideProofEnv.getServicesForEnvironment().getTermBuilder(); + Term isNull = tb.equals(newSuccedent, tb.NULL()); + Term isNotNull = tb.not(isNull); + Sequent sequentToProve = createSequentToProveWithNewSuccedent(node, additionalAntecedent, + nullExpected ? isNull : isNotNull, false); + // Execute proof in the current thread + ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), + sideProofEnv, sequentToProve, StrategyProperties.METHOD_CONTRACT, + StrategyProperties.LOOP_INVARIANT, StrategyProperties.QUERY_ON, + StrategyProperties.SPLITTING_NORMAL); + try { + return !info.getProof().openEnabledGoals().isEmpty(); + } finally { + SymbolicExecutionSideProofUtil + .disposeOrStore("Null check on node " + node.serialNr() + ".", info); + } + } + + /** + * Creates a new {@link Sequent} which is a modification from the {@link Sequent} of the given + * {@link Node} which contains the same information but a different succedent. + * + * @param node The {@link Node} which provides the original {@link Sequent}. + * @param newSuccedent The new succedent. + * @return The created {@link Sequent}. + */ + public static Sequent createSequentToProveWithNewSuccedent(Node node, PosInOccurrence pio, + Term newSuccedent) { + return createSequentToProveWithNewSuccedent(node, pio, null, newSuccedent, false); + } + + /** + * Creates a new {@link Sequent} which is a modification from the {@link Sequent} of the given + * {@link Node} which contains the same information but a different succedent. + * + * @param node The {@link Node} which provides the original {@link Sequent}. + * @param additionalAntecedent An optional additional antecedents. + * @param newSuccedent The new succedent. + * @return The created {@link Sequent}. + */ + public static Sequent createSequentToProveWithNewSuccedent(Node node, Term additionalAntecedent, + Term newSuccedent, boolean addResultLabel) { + return createSequentToProveWithNewSuccedent(node, + node.getAppliedRuleApp() != null ? node.getAppliedRuleApp().posInOccurrence() + : null, + additionalAntecedent, newSuccedent, addResultLabel); + } + + /** + * Creates a new {@link Sequent} which is a modification from the {@link Sequent} of the given + * {@link Node} which contains the same information but a different succedent. + * + * @param node The {@link Node} which provides the original {@link Sequent}. + * @param additionalAntecedent An optional additional antecedents. + * @param newSuccedent The new succedent. + * @return The created {@link Sequent}. + */ + public static Sequent createSequentToProveWithNewSuccedent(Node node, PosInOccurrence pio, + Term additionalAntecedent, Term newSuccedent, boolean addResultLabel) { + if (pio != null) { + // Get the updates from the return node which includes the value interested in. + ImmutableList originalUpdates; + if (node.proof().root() == node) { + originalUpdates = computeRootElementaryUpdates(node); + } else { + Term originalModifiedFormula = pio.sequentFormula().formula(); + originalUpdates = TermBuilder.goBelowUpdates2(originalModifiedFormula).first; } - } - else if (goalTemplate.replaceWithExpressionAsObject() instanceof Term) { - Term replaceTerm = (Term)goalTemplate.replaceWithExpressionAsObject(); - replaceTerm = instantiateTerm(node, replaceTerm, app, services); - Term originalTerm = findReplacement(app.posInOccurrence().isInAntec() ? node.sequent().antecedent() : node.sequent().succedent(), - app.posInOccurrence(), - replaceTerm); - assert originalTerm != null; - if (app.posInOccurrence().isInAntec()) { - newAntecedents = newAntecedents.removeFirst(originalTerm); + // Create new sequent + return createSequentToProveWithNewSuccedent(node, pio, additionalAntecedent, + newSuccedent, originalUpdates, addResultLabel); + } else { + return createSequentToProveWithNewSuccedent(node, pio, additionalAntecedent, + newSuccedent, null, addResultLabel); + } + } + + /** + * Computes the initial {@link ElementaryUpdate}s on the given root {@link Node}. + * + * @param root The root {@link Node} of the {@link Proof}. + * @return The found initial {@link ElementaryUpdate}s. + */ + public static ImmutableList computeRootElementaryUpdates(Node root) { + ImmutableList result = ImmutableSLList.nil(); + Sequent sequent = root.sequent(); + for (SequentFormula sf : sequent.succedent()) { + Term term = sf.formula(); + if (Junctor.IMP.equals(term.op())) { + result = result.prepend(collectElementaryUpdates(term.sub(1))); } - else { - newSuccedents = newSuccedents.removeFirst(originalTerm); + } + return result; + } + + /** + * Collects the {@link ElementaryUpdate}s in the given {@link Term}. + * + * @param term The {@link Term} to collect its updates. + * @return The found {@link ElementaryUpdate}s. + */ + public static ImmutableList collectElementaryUpdates(Term term) { + if (term.op() instanceof UpdateApplication) { + Term updateTerm = UpdateApplication.getUpdate(term); + return collectElementaryUpdates(updateTerm); + } else if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { + ImmutableList result = ImmutableSLList.nil(); + for (int i = 0; i < term.arity(); i++) { + result = result.prepend(collectElementaryUpdates(term.sub(i))); } - if (!NodeInfo.isSymbolicExecution(app.taclet())) { - // Make sure that an PosTacletApp was applied - if (!(app instanceof PosTacletApp)) { - throw new ProofInputException("Only PosTacletApp are allowed with a replace term in branch computation but rule \"" + app + "\" was found."); - } - // Create new lists - ImmutableList tempAntecedents = ImmutableSLList.nil(); - ImmutableList tempSuccedents = ImmutableSLList.nil(); - // Apply updates on antecedents and add result to new antecedents list - for (Term a : newAntecedents) { - tempAntecedents = tempAntecedents.append(services.getTermBuilder().applyUpdatePairsSequential(app.instantiations().getUpdateContext(), a)); - } - // Apply updates on succedents and add result to new succedents list - for (Term suc : newSuccedents) { - tempSuccedents = tempSuccedents.append(services.getTermBuilder().applyUpdatePairsSequential(app.instantiations().getUpdateContext(), suc)); - } - // Add additional equivalenz term to antecedent with the replace object which must be equal to the find term - replaceTerm = followPosInOccurrence(app.posInOccurrence(), originalTerm); - replaceTerm = services.getTermBuilder().equals(replaceTerm, app.posInOccurrence().subTerm()); - replaceTerm = services.getTermBuilder().applyUpdatePairsSequential(app.instantiations().getUpdateContext(), replaceTerm); - if (!tempAntecedents.contains(replaceTerm)) { - tempAntecedents = tempAntecedents.append(replaceTerm); - } - // Replace old with new lists - newAntecedents = tempAntecedents; - newSuccedents = tempSuccedents; + return result; + } else if (term.op() instanceof ElementaryUpdate) { + return ImmutableSLList.nil().prepend(term); + } else { + return ImmutableSLList.nil(); + } + } + + /** + * Creates a new {@link Sequent} which is a modification from the {@link Sequent} of the given + * {@link Node} which contains the same information but a different succedent. + * + * @param node The {@link Node} which provides the original {@link Sequent}. + * @param additionalAntecedent An optional additional antecedents. + * @param newSuccedent The new succedent. + * @param updates The updates to use. + * @return The created {@link Sequent}. + */ + public static Sequent createSequentToProveWithNewSuccedent(Node node, Term additionalAntecedent, + Term newSuccedent, ImmutableList updates, boolean addResultLabel) { + return createSequentToProveWithNewSuccedent(node, + node.getAppliedRuleApp().posInOccurrence(), additionalAntecedent, newSuccedent, + updates, addResultLabel); + } + + /** + * Creates a new {@link Sequent} which is a modification from the {@link Sequent} of the given + * {@link Node} which contains the same information but a different succedent. + * + * @param node The {@link Node} which provides the original {@link Sequent}. + * @param additionalAntecedent An optional additional antecedents. + * @param newSuccedent The new succedent. + * @param updates The updates to use. + * @return The created {@link Sequent}. + */ + public static Sequent createSequentToProveWithNewSuccedent(Node node, PosInOccurrence pio, + Term additionalAntecedent, Term newSuccedent, ImmutableList updates, + boolean addResultLabel) { + final TermBuilder tb = node.proof().getServices().getTermBuilder(); + // Combine method frame, formula with value predicate and the updates which provides the + // values + Term newSuccedentToProve; + if (updates != null) { + if (newSuccedent != null) { + newSuccedentToProve = tb.applySequential(updates, newSuccedent); + } else { + newSuccedentToProve = newSuccedent; } - } - else if (goalTemplate.replaceWithExpressionAsObject() != null) { - throw new ProofInputException("Expected replacement as Sequent or Term during branch condition computation but is \"" + goalTemplate.replaceWithExpressionAsObject() + "\"."); - } - } - // Compute branch condition - Term newLeft = services.getTermBuilder().and(newAntecedents); - Term newRight = services.getTermBuilder().or(newSuccedents); - Term newLeftAndRight = services.getTermBuilder().and(newLeft, services.getTermBuilder().not(newRight)); - // Simplify condition if required - Term condition; - if (simplify) { - // Create formula which contains the value interested in. - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(parent.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - Sequent newSequent = createSequentToProveWithNewSuccedent(parent, null, (Term)null, newLeftAndRight, true); - condition = evaluateInSideProof(services, - parent.proof(), - sideProofEnv, - newSequent, - RESULT_LABEL, - "Taclet branch condition computation on node " + parent.serialNr() + " for branch " + node.serialNr() + ".", - StrategyProperties.SPLITTING_OFF); - } - else { - condition = newLeftAndRight; - } - if (improveReadability) { - condition = improveReadability(condition, services); - } - return condition; - } - - /** - * Lists the {@link Term}s of all new {@link SequentFormula} in the child {@link Semisequent}. - * @param parent The parent {@link Semisequent}. - * @param child The child {@link Semisequent}. - * @return An {@link ImmutableList} with all new {@link Term}s. - */ - private static ImmutableList listNewSemisequentTerms(Semisequent parent, - Semisequent child) { - Set parentSFs = new HashSet(); - for (SequentFormula sf : parent) { - parentSFs.add(sf); - } - ImmutableList result = ImmutableSLList.nil(); - for (SequentFormula sf : child) { - if (!parentSFs.contains(sf)) { - result = result.append(sf.formula()); - } - } - return result; - } - - /** - * Searches the by {@link Rule} application instantiated replace {@link Term} - * which is equal modulo labels to the given replace {@link Term}. - * @param terms The available candidates created by {@link Rule} application. - * @param posInOccurrence The {@link PosInOccurrence} on which the rule was applied. - * @param replaceTerm The {@link Term} to find. - * @return The found {@link Term} or {@code null} if not available. - */ - private static Term findReplacement(Semisequent semisequent, - final PosInOccurrence posInOccurrence, - final Term replaceTerm) { - SequentFormula sf = CollectionUtil.search(semisequent, new IFilter() { - @Override - public boolean select(SequentFormula element) { - return checkReplaceTerm(element.formula(), posInOccurrence, replaceTerm); - } - }); - return sf != null ? sf.formula() : null; - } - - /** - * Checks if the given replace {@link Term} is equal module labels to the {@link Term} to check. - * @param toCheck The {@link Term} to check. - * @param posInOccurrence The {@link PosInOccurrence} of the {@link Rule} application. - * @param replaceTerm The {@link Term} to compare with. - * @return {@code true} equal modulo labels, {@code false} not equal at all. - */ - private static boolean checkReplaceTerm(Term toCheck, PosInOccurrence posInOccurrence, Term replaceTerm) { - Term termAtPio = followPosInOccurrence(posInOccurrence, toCheck); - if (termAtPio != null) { - return termAtPio.equalsModRenaming(replaceTerm); - } - else { - return false; - } - } - - /** - * Returns the sub {@link Term} at the given {@link PosInOccurrence} - * but on the given {@link Term} instead of the one contained in the {@link PosInOccurrence}. - * @param posInOccurrence The {@link PosInOccurrence} which defines the sub term position. - * @param term The {@link Term} to work with. - * @return The found sub {@link Term} or {@code null} if the {@link PosInOccurrence} is not compatible. - */ - public static Term followPosInOccurrence(PosInOccurrence posInOccurrence, Term term) { - boolean matches = true; - IntIterator iter = posInOccurrence.posInTerm().iterator(); - while (matches && iter.hasNext()) { - int index = iter.next(); - if (index < term.arity()) { - term = term.sub(index); - } - else { - matches = false; - } - } - return matches ? term : null; - } - - /** - * Instantiates the given {@link Term} of the applied {@link TacletApp}. - * @param node The current {@link Node}. - * @param term The {@link Term} to instantiate. - * @param tacletApp The {@link TacletApp} to consider. - * @param services The {@link Services} to use. - * @return The instantiated {@link Term} or {@code null} if no {@link Term} was given. - */ - public static Term instantiateTerm(Node node, - Term term, - TacletApp tacletApp, - Services services) { - if (term != null) { - SyntacticalReplaceVisitor visitor = new SyntacticalReplaceVisitor(new TermLabelState(), null, tacletApp.posInOccurrence(), tacletApp.instantiations(), null, tacletApp.taclet(), tacletApp, services); - term.execPostOrder(visitor); - return visitor.getTerm(); - } - else { - return null; - } - } - - /** - * Starts the side proof and evaluates the {@link Sequent} to prove into a single {@link Term}. - * @param services The {@link Services} to use. - * @param proof The {@link Proof} from on which the side proof si performed. - * @param sequentToProve The {@link Sequent} to prove in a side proof. - * @param label The {@link TermLabel} which is used to compute the result. - * @param description The side proof description. - * @param splittingOption The splitting options to use. - * @return The result {@link Term}. - * @throws ProofInputException Occurred Exception. - */ - private static Term evaluateInSideProof(Services services, - Proof proof, - ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, - TermLabel label, - String description, - String splittingOption) throws ProofInputException { - List> resultValuesAndConditions = SymbolicExecutionSideProofUtil.computeResults(services, - proof, - sideProofEnvironment, - sequentToProve, - label, - description, - StrategyProperties.METHOD_NONE, // Stop at methods to avoid endless executions and scenarios in which a precondition or null pointer check can't be shown - StrategyProperties.LOOP_NONE, // Stop at loops to avoid endless executions and scenarios in which the invariant can't be shown to be initially valid or preserved. - StrategyProperties.QUERY_OFF, // Stop at queries to to avoid endless executions and scenarios in which a precondition or null pointer check can't be shown - splittingOption, - false); - ImmutableList goalCondtions = ImmutableSLList.nil(); - for (Pair pair : resultValuesAndConditions) { - Term goalCondition = pair.first; - goalCondition = SymbolicExecutionUtil.replaceSkolemConstants(pair.second.sequent(), goalCondition, services); - goalCondition = removeLabelRecursive(services.getTermFactory(), goalCondition, label); - goalCondtions = goalCondtions.append(goalCondition); - } - return services.getTermBuilder().and(goalCondtions); - } - - /** - * Returns the default choice value. - * Attention: This method returns {@code null} if it is called before - * a proof is instantiated the first time. It can be checked via - * {@link #isChoiceSettingInitialised()}. - * @param key The choice key. - * @return The choice value. - */ - public static String getChoiceSetting(String key) { - Map settings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); - return settings.get(key); - } - - /** - * Sets the default choice value. - * Attention: Settings should not be changed before the first proof - * is instantiated in KeY. Otherwise the default settings are not loaded. - * If default settings are defined can be checked via {@link #isChoiceSettingInitialised()}. - * @param key The choice key to modify. - * @param value The new choice value to set. - */ - public static void setChoiceSetting(String key, String value) { - HashMap settings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); - HashMap clone = new LinkedHashMap(); - clone.putAll(settings); - clone.put(key, value); - ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().setDefaultChoices(clone); - } - - /** - * Checks if the given {@link Term} is null in the {@link Sequent} of the given {@link Node}. - * @param node The {@link Node} which provides the original {@link Sequent} - * @param additionalAntecedent An additional antecedent. - * @param newSuccedent The {@link Term} to check. - * @return {@code true} {@link Term} was evaluated to null, {@code false} {@link Term} was not evaluated to null. - * @throws ProofInputException Occurred Exception - */ - public static boolean isNull(Node node, - Term additionalAntecedent, - Term newSuccedent) throws ProofInputException { - return checkNull(node, additionalAntecedent, newSuccedent, true); - } - - /** - * Checks if the given {@link Term} is not null in the {@link Sequent} of the given {@link Node}. - * @param node The {@link Node} which provides the original {@link Sequent} - * @param additionalAntecedent An additional antecedent. - * @param newSuccedent The {@link Term} to check. - * @return {@code true} {@link Term} was evaluated to not null, {@code false} {@link Term} was not evaluated to not null. - * @throws ProofInputException Occurred Exception - */ - public static boolean isNotNull(Node node, - Term additionalAntecedent, - Term newSuccedent) throws ProofInputException { - return checkNull(node, additionalAntecedent, newSuccedent, false); - } - - /** - * Checks if the given {@link Term} is null or not in the {@link Sequent} of the given {@link Node}. - * @param node The {@link Node} which provides the original {@link Sequent} - * @param additionalAntecedent An additional antecedent. - * @param newSuccedent The {@link Term} to check. - * @param nullExpected {@code true} expect that {@link Term} is null, {@code false} expect that term is not null. - * @return {@code true} term is null value matches the expected nullExpected value, {@code false} otherwise. - * @throws ProofInputException Occurred Exception - */ - private static boolean checkNull(Node node, - Term additionalAntecedent, - Term newSuccedent, - boolean nullExpected) throws ProofInputException { - // Make sure that correct parameters are given - assert node != null; - assert newSuccedent != null; - // Create Sequent to prove - final ProofEnvironment sideProofEnv = SymbolicExecutionSideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(node.proof(), true); // New OneStepSimplifier is required because it has an internal state and the default instance can't be used parallel. - final TermBuilder tb = sideProofEnv.getServicesForEnvironment().getTermBuilder(); - Term isNull = tb.equals(newSuccedent, tb.NULL()); - Term isNotNull = tb.not(isNull); - Sequent sequentToProve = createSequentToProveWithNewSuccedent(node, additionalAntecedent, nullExpected ? isNull : isNotNull, false); - // Execute proof in the current thread - ApplyStrategyInfo info = SymbolicExecutionSideProofUtil.startSideProof(node.proof(), - sideProofEnv, - sequentToProve, - StrategyProperties.METHOD_CONTRACT, - StrategyProperties.LOOP_INVARIANT, - StrategyProperties.QUERY_ON, - StrategyProperties.SPLITTING_NORMAL); - try { - return !info.getProof().openEnabledGoals().isEmpty(); - } - finally { - SymbolicExecutionSideProofUtil.disposeOrStore("Null check on node " + node.serialNr() + ".", info); - } - } - - /** - * Creates a new {@link Sequent} which is a modification from the {@link Sequent} - * of the given {@link Node} which contains the same information but a different succedent. - * @param node The {@link Node} which provides the original {@link Sequent}. - * @param newSuccedent The new succedent. - * @return The created {@link Sequent}. - */ - public static Sequent createSequentToProveWithNewSuccedent(Node node, - PosInOccurrence pio, - Term newSuccedent) { - return createSequentToProveWithNewSuccedent(node, pio, null, newSuccedent, false); - } - - /** - * Creates a new {@link Sequent} which is a modification from the {@link Sequent} - * of the given {@link Node} which contains the same information but a different succedent. - * @param node The {@link Node} which provides the original {@link Sequent}. - * @param additionalAntecedent An optional additional antecedents. - * @param newSuccedent The new succedent. - * @return The created {@link Sequent}. - */ - public static Sequent createSequentToProveWithNewSuccedent(Node node, - Term additionalAntecedent, - Term newSuccedent, - boolean addResultLabel) { - return createSequentToProveWithNewSuccedent(node, - node.getAppliedRuleApp() != null ? node.getAppliedRuleApp().posInOccurrence() : null, - additionalAntecedent, - newSuccedent, - addResultLabel); - } - - /** - * Creates a new {@link Sequent} which is a modification from the {@link Sequent} - * of the given {@link Node} which contains the same information but a different succedent. - * @param node The {@link Node} which provides the original {@link Sequent}. - * @param additionalAntecedent An optional additional antecedents. - * @param newSuccedent The new succedent. - * @return The created {@link Sequent}. - */ - public static Sequent createSequentToProveWithNewSuccedent(Node node, - PosInOccurrence pio, - Term additionalAntecedent, - Term newSuccedent, - boolean addResultLabel) { - if (pio != null) { - // Get the updates from the return node which includes the value interested in. - ImmutableList originalUpdates; - if (node.proof().root() == node) { - originalUpdates = computeRootElementaryUpdates(node); - } - else { - Term originalModifiedFormula = pio.sequentFormula().formula(); - originalUpdates = TermBuilder.goBelowUpdates2(originalModifiedFormula).first; - } - // Create new sequent - return createSequentToProveWithNewSuccedent(node, pio, additionalAntecedent, newSuccedent, originalUpdates, addResultLabel); - } - else { - return createSequentToProveWithNewSuccedent(node, pio, additionalAntecedent, newSuccedent, null, addResultLabel); - } - } - - /** - * Computes the initial {@link ElementaryUpdate}s on the given root {@link Node}. - * @param root The root {@link Node} of the {@link Proof}. - * @return The found initial {@link ElementaryUpdate}s. - */ - public static ImmutableList computeRootElementaryUpdates(Node root) { - ImmutableList result = ImmutableSLList.nil(); - Sequent sequent = root.sequent(); - for (SequentFormula sf : sequent.succedent()) { - Term term = sf.formula(); - if (Junctor.IMP.equals(term.op())) { - result = result.prepend(collectElementaryUpdates(term.sub(1))); - } - } - return result; - } - - /** - * Collects the {@link ElementaryUpdate}s in the given {@link Term}. - * @param term The {@link Term} to collect its updates. - * @return The found {@link ElementaryUpdate}s. - */ - public static ImmutableList collectElementaryUpdates(Term term) { - if (term.op() instanceof UpdateApplication) { - Term updateTerm = UpdateApplication.getUpdate(term); - return collectElementaryUpdates(updateTerm); - } - else if (term.op() == UpdateJunctor.PARALLEL_UPDATE) { - ImmutableList result = ImmutableSLList.nil(); - for (int i = 0; i < term.arity(); i++) { - result = result.prepend(collectElementaryUpdates(term.sub(i))); - } - return result; - } - else if (term.op() instanceof ElementaryUpdate) { - return ImmutableSLList.nil().prepend(term); - } - else { - return ImmutableSLList.nil(); - } - } - - /** - * Creates a new {@link Sequent} which is a modification from the {@link Sequent} - * of the given {@link Node} which contains the same information but a different succedent. - * @param node The {@link Node} which provides the original {@link Sequent}. - * @param additionalAntecedent An optional additional antecedents. - * @param newSuccedent The new succedent. - * @param updates The updates to use. - * @return The created {@link Sequent}. - */ - public static Sequent createSequentToProveWithNewSuccedent(Node node, - Term additionalAntecedent, - Term newSuccedent, - ImmutableList updates, - boolean addResultLabel) { - return createSequentToProveWithNewSuccedent(node, node.getAppliedRuleApp().posInOccurrence(), additionalAntecedent, newSuccedent, updates, addResultLabel); - } - - /** - * Creates a new {@link Sequent} which is a modification from the {@link Sequent} - * of the given {@link Node} which contains the same information but a different succedent. - * @param node The {@link Node} which provides the original {@link Sequent}. - * @param additionalAntecedent An optional additional antecedents. - * @param newSuccedent The new succedent. - * @param updates The updates to use. - * @return The created {@link Sequent}. - */ - public static Sequent createSequentToProveWithNewSuccedent(Node node, - PosInOccurrence pio, - Term additionalAntecedent, - Term newSuccedent, - ImmutableList updates, - boolean addResultLabel) { - final TermBuilder tb = node.proof().getServices().getTermBuilder(); - // Combine method frame, formula with value predicate and the updates which provides the values - Term newSuccedentToProve; - if (updates != null) { - if (newSuccedent != null) { - newSuccedentToProve = tb.applySequential(updates, newSuccedent); - } - else { + } else { newSuccedentToProve = newSuccedent; - } - } - else { - newSuccedentToProve = newSuccedent; - } - // Create new sequent with the original antecedent and the formulas in the succedent which were not modified by the applied rule - Sequent originalSequentWithoutMethodFrame = SymbolicExecutionSideProofUtil.computeGeneralSequentToProve(node.sequent(), pio != null ? pio.sequentFormula() : null); - Set skolemTerms = newSuccedentToProve != null ? - collectSkolemConstants(originalSequentWithoutMethodFrame, newSuccedentToProve) : - collectSkolemConstants(originalSequentWithoutMethodFrame, tb.parallel(updates)); - originalSequentWithoutMethodFrame = removeAllUnusedSkolemEqualities(originalSequentWithoutMethodFrame, skolemTerms); - if (addResultLabel) { - TermFactory factory = node.proof().getServices().getTermFactory(); - Set skolemInNewTerm = collectSkolemConstantsNonRecursive(newSuccedentToProve); - originalSequentWithoutMethodFrame = labelSkolemConstants(originalSequentWithoutMethodFrame, skolemInNewTerm, factory); - newSuccedentToProve = addLabelRecursiveToNonSkolem(factory, newSuccedentToProve, RESULT_LABEL); - } - Sequent sequentToProve = newSuccedentToProve != null ? - originalSequentWithoutMethodFrame.addFormula(new SequentFormula(newSuccedentToProve), false, true).sequent() : - originalSequentWithoutMethodFrame; - if (additionalAntecedent != null) { - sequentToProve = sequentToProve.addFormula(new SequentFormula(additionalAntecedent), true, false).sequent(); - } - return sequentToProve; - } - - /** - * Labels all specified skolem equalities with the {@link SymbolicExecutionUtil#RESULT_LABEL}. - * @param sequent The {@link Sequent} to modify. - * @param constantsToLabel The skolem constants to label. - * @param factory The {@link TermFactory} to use. - * @return The modified {@link Sequent}. - */ - protected static Sequent labelSkolemConstants(Sequent sequent, - Set constantsToLabel, - TermFactory factory) { - for (SequentFormula sf : sequent.antecedent()) { - int skolemEquality = checkSkolemEquality(sf); - if (skolemEquality == -1) { - Term equality = sf.formula(); - if (constantsToLabel.contains(equality.sub(0))) { - Term definition = addLabelRecursiveToNonSkolem(factory, equality.sub(1), RESULT_LABEL); - Term skolem = addLabelRecursiveToNonSkolem(factory, equality.sub(0), RESULT_LABEL); - List newSubs = new LinkedList(); - newSubs.add(definition); - newSubs.add(skolem); - Term newEquality = factory.createTerm(equality.op(), new ImmutableArray(newSubs), equality.boundVars(), equality.javaBlock(), equality.getLabels()); - sequent = sequent.changeFormula(new SequentFormula(newEquality), new PosInOccurrence(sf, PosInTerm.getTopLevel(), true)).sequent(); + } + // Create new sequent with the original antecedent and the formulas in the succedent which + // were not modified by the applied rule + Sequent originalSequentWithoutMethodFrame = + SymbolicExecutionSideProofUtil.computeGeneralSequentToProve(node.sequent(), + pio != null ? pio.sequentFormula() : null); + Set skolemTerms = newSuccedentToProve != null + ? collectSkolemConstants(originalSequentWithoutMethodFrame, newSuccedentToProve) + : collectSkolemConstants(originalSequentWithoutMethodFrame, tb.parallel(updates)); + originalSequentWithoutMethodFrame = + removeAllUnusedSkolemEqualities(originalSequentWithoutMethodFrame, skolemTerms); + if (addResultLabel) { + TermFactory factory = node.proof().getServices().getTermFactory(); + Set skolemInNewTerm = collectSkolemConstantsNonRecursive(newSuccedentToProve); + originalSequentWithoutMethodFrame = labelSkolemConstants( + originalSequentWithoutMethodFrame, skolemInNewTerm, factory); + newSuccedentToProve = + addLabelRecursiveToNonSkolem(factory, newSuccedentToProve, RESULT_LABEL); + } + Sequent sequentToProve = newSuccedentToProve != null + ? originalSequentWithoutMethodFrame + .addFormula(new SequentFormula(newSuccedentToProve), false, true).sequent() + : originalSequentWithoutMethodFrame; + if (additionalAntecedent != null) { + sequentToProve = sequentToProve + .addFormula(new SequentFormula(additionalAntecedent), true, false).sequent(); + } + return sequentToProve; + } + + /** + * Labels all specified skolem equalities with the {@link SymbolicExecutionUtil#RESULT_LABEL}. + * + * @param sequent The {@link Sequent} to modify. + * @param constantsToLabel The skolem constants to label. + * @param factory The {@link TermFactory} to use. + * @return The modified {@link Sequent}. + */ + protected static Sequent labelSkolemConstants(Sequent sequent, Set constantsToLabel, + TermFactory factory) { + for (SequentFormula sf : sequent.antecedent()) { + int skolemEquality = checkSkolemEquality(sf); + if (skolemEquality == -1) { + Term equality = sf.formula(); + if (constantsToLabel.contains(equality.sub(0))) { + Term definition = + addLabelRecursiveToNonSkolem(factory, equality.sub(1), RESULT_LABEL); + Term skolem = + addLabelRecursiveToNonSkolem(factory, equality.sub(0), RESULT_LABEL); + List newSubs = new LinkedList(); + newSubs.add(definition); + newSubs.add(skolem); + Term newEquality = factory.createTerm(equality.op(), + new ImmutableArray(newSubs), equality.boundVars(), + equality.javaBlock(), equality.getLabels()); + sequent = sequent + .changeFormula(new SequentFormula(newEquality), + new PosInOccurrence(sf, PosInTerm.getTopLevel(), true)) + .sequent(); + } + } else if (skolemEquality == 1) { + Term equality = sf.formula(); + if (constantsToLabel.contains(equality.sub(1))) { + Term definition = + addLabelRecursiveToNonSkolem(factory, equality.sub(0), RESULT_LABEL); + Term skolem = + addLabelRecursiveToNonSkolem(factory, equality.sub(1), RESULT_LABEL); + List newSubs = new LinkedList(); + newSubs.add(definition); + newSubs.add(skolem); + Term newEquality = factory.createTerm(equality.op(), + new ImmutableArray(newSubs), equality.boundVars(), + equality.javaBlock(), equality.getLabels()); + sequent = sequent + .changeFormula(new SequentFormula(newEquality), + new PosInOccurrence(sf, PosInTerm.getTopLevel(), true)) + .sequent(); + } + } + } + return sequent; + } + + /** + * Adds the given {@link TermLabel} to the given {@link Term} and to all of its children. + * + * @param tf The {@link TermFactory} to use. + * @param term The {@link Term} to add label to. + * @param label The {@link TermLabel} to add. + * @return A new {@link Term} with the given {@link TermLabel}. + */ + private static Term addLabelRecursiveToNonSkolem(TermFactory tf, Term term, TermLabel label) { + List newSubs = new LinkedList(); + for (Term oldSub : term.subs()) { + newSubs.add(addLabelRecursiveToNonSkolem(tf, oldSub, label)); + } + if (checkSkolemEquality(term) != 0 || isSkolemConstant(term)) { + // Do not label skolem equality and skolem terms + return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), + term.javaBlock(), term.getLabels()); + } else { + /// Label term which is not a skolem equality and not a skolem term + List newLabels = new LinkedList(); + for (TermLabel oldLabel : term.getLabels()) { + newLabels.add(oldLabel); } - } - else if (skolemEquality == 1) { - Term equality = sf.formula(); - if (constantsToLabel.contains(equality.sub(1))) { - Term definition = addLabelRecursiveToNonSkolem(factory, equality.sub(0), RESULT_LABEL); - Term skolem = addLabelRecursiveToNonSkolem(factory, equality.sub(1), RESULT_LABEL); - List newSubs = new LinkedList(); - newSubs.add(definition); - newSubs.add(skolem); - Term newEquality = factory.createTerm(equality.op(), new ImmutableArray(newSubs), equality.boundVars(), equality.javaBlock(), equality.getLabels()); - sequent = sequent.changeFormula(new SequentFormula(newEquality), new PosInOccurrence(sf, PosInTerm.getTopLevel(), true)).sequent(); + newLabels.add(label); + return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), + term.javaBlock(), new ImmutableArray(newLabels)); + } + } + + /** + * Removes the given {@link TermLabel} from the given {@link Term} and from all of its children. + * + * @param tf The {@link TermFactory} to use. + * @param term The {@link Term} to remove label from. + * @param label The {@link TermLabel} to remove. + * @return A new {@link Term} without the given {@link TermLabel}. + */ + public static Term removeLabelRecursive(TermFactory tf, Term term, TermLabel label) { + // Update children + List newSubs = new LinkedList(); + ImmutableArray oldSubs = term.subs(); + for (Term oldSub : oldSubs) { + newSubs.add(removeLabelRecursive(tf, oldSub, label)); + } + // Update label + List newLabels = new LinkedList(); + ImmutableArray oldLabels = term.getLabels(); + for (TermLabel oldLabel : oldLabels) { + if (oldLabel != label) { + newLabels.add(oldLabel); } - } - } - return sequent; - } - - /** - * Adds the given {@link TermLabel} to the given {@link Term} and to all of its children. - * @param tf The {@link TermFactory} to use. - * @param term The {@link Term} to add label to. - * @param label The {@link TermLabel} to add. - * @return A new {@link Term} with the given {@link TermLabel}. - */ - private static Term addLabelRecursiveToNonSkolem(TermFactory tf, Term term, TermLabel label) { - List newSubs = new LinkedList(); - for (Term oldSub : term.subs()) { - newSubs.add(addLabelRecursiveToNonSkolem(tf, oldSub, label)); - } - if (checkSkolemEquality(term) != 0 || isSkolemConstant(term)) { - // Do not label skolem equality and skolem terms - return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), term.getLabels()); - } - else { - /// Label term which is not a skolem equality and not a skolem term - List newLabels = new LinkedList(); - for (TermLabel oldLabel : term.getLabels()) { - newLabels.add(oldLabel); - } - newLabels.add(label); - return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), new ImmutableArray(newLabels)); - } - } - - /** - * Removes the given {@link TermLabel} from the given {@link Term} and from all of its children. - * @param tf The {@link TermFactory} to use. - * @param term The {@link Term} to remove label from. - * @param label The {@link TermLabel} to remove. - * @return A new {@link Term} without the given {@link TermLabel}. - */ - public static Term removeLabelRecursive(TermFactory tf, Term term, TermLabel label) { - // Update children - List newSubs = new LinkedList(); - ImmutableArray oldSubs = term.subs(); - for (Term oldSub : oldSubs) { - newSubs.add(removeLabelRecursive(tf, oldSub, label)); - } - // Update label - List newLabels = new LinkedList(); - ImmutableArray oldLabels = term.getLabels(); - for (TermLabel oldLabel : oldLabels) { - if (oldLabel != label) { - newLabels.add(oldLabel); - } - } - return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), term.javaBlock(), new ImmutableArray(newLabels)); - } - - /** - * Collects all contained skolem {@link Term}s which fulfill - * {@link #isSkolemConstant(Term)} as well as the skolem constants - * used in the find once recursive. - * @param sequent The {@link Sequent} which provides the skolem equalities. - * @param term The {@link Term} to start collection in. - * @return The found skolem {@link Term}s. - */ - private static Set collectSkolemConstants(Sequent sequent, Term term) { - if (term != null) { - // Collect skolem constants in term - Set result = collectSkolemConstantsNonRecursive(term); - // Collect all skolem constants used in skolem constants - List toCheck = new LinkedList(result); - while (!toCheck.isEmpty()) { - Term skolemConstant = toCheck.remove(0); - List replacements = findSkolemReplacements(sequent, skolemConstant, null); - for (Term replacement : replacements) { - Set checkResult = collectSkolemConstantsNonRecursive(replacement); - for (Term checkConstant : checkResult) { - if (result.add(checkConstant)) { - toCheck.add(checkConstant); - } - } + } + return tf.createTerm(term.op(), new ImmutableArray(newSubs), term.boundVars(), + term.javaBlock(), new ImmutableArray(newLabels)); + } + + /** + * Collects all contained skolem {@link Term}s which fulfill {@link #isSkolemConstant(Term)} as + * well as the skolem constants used in the find once recursive. + * + * @param sequent The {@link Sequent} which provides the skolem equalities. + * @param term The {@link Term} to start collection in. + * @return The found skolem {@link Term}s. + */ + private static Set collectSkolemConstants(Sequent sequent, Term term) { + if (term != null) { + // Collect skolem constants in term + Set result = collectSkolemConstantsNonRecursive(term); + // Collect all skolem constants used in skolem constants + List toCheck = new LinkedList(result); + while (!toCheck.isEmpty()) { + Term skolemConstant = toCheck.remove(0); + List replacements = findSkolemReplacements(sequent, skolemConstant, null); + for (Term replacement : replacements) { + Set checkResult = collectSkolemConstantsNonRecursive(replacement); + for (Term checkConstant : checkResult) { + if (result.add(checkConstant)) { + toCheck.add(checkConstant); + } + } + } } - } - return result; - } - else { - return new HashSet(); - } - } - - /** - * Collects all contained skolem {@link Term}s which fulfill - * {@link #isSkolemConstant(Term)}. - * @param term The {@link Term} to collect in. - * @return The found skolem {@link Term}s. - */ - private static Set collectSkolemConstantsNonRecursive(Term term) { - final Set result = new HashSet(); - term.execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - if (isSkolemConstant(visited)) { - result.add(visited); + return result; + } else { + return new HashSet(); + } + } + + /** + * Collects all contained skolem {@link Term}s which fulfill {@link #isSkolemConstant(Term)}. + * + * @param term The {@link Term} to collect in. + * @return The found skolem {@link Term}s. + */ + private static Set collectSkolemConstantsNonRecursive(Term term) { + final Set result = new HashSet(); + term.execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + if (isSkolemConstant(visited)) { + result.add(visited); + } } - } - }); - return result; - } - - /** - * Checks if the given {@link Term} is a skolem {@link Term} meaning - * that it has the {@link SelectSkolemConstantTermLabel}. - * @param term The {@link Term} to check. - * @return {@code true} is skolem {@link Term}, {@code false} is not a skolem {@link Term}. - */ - public static boolean isSkolemConstant(Term term) { - return term.containsLabel(ParameterlessTermLabel.SELECT_SKOLEM_LABEL); - } - - /** - * Removes all {@link SequentFormula}s with a skolem equality from the given {@link Sequent} - * if the skolem {@link Term} is not contained in the given {@link Collection}. - * @param sequent The {@link Sequent} to modify. - * @param skolemConstants The allowed skolem {@link Term}s. - * @return The modified {@link Sequent} in which all not listed skolem {@link Term} equalites are removed. - */ - private static Sequent removeAllUnusedSkolemEqualities(Sequent sequent, - Collection skolemConstants) { - Sequent result = sequent; - for (SequentFormula sf : sequent.antecedent()) { - result = removeAllUnusedSkolemEqualities(result, sf, true, skolemConstants); - } - for (SequentFormula sf : sequent.succedent()) { - result = removeAllUnusedSkolemEqualities(result, sf, false, skolemConstants); - } - return result; - } - - /** - * Helper method of {@link #removeAllUnusedSkolemEqualities(Sequent, Collection)} - * which removes the given {@link SequentFormula} if required. - * @param sequent The {@link Sequent} to modify. - * @param sf The {@link SequentFormula} to remove if its skolem {@link Term} is not listed. - * @param antecedent {@code true} antecedent, {@code false} succedent. - * @param skolemConstants The allowed skolem {@link Term}s. - * @return The modified {@link Sequent} in which the {@link SequentFormula} might be removed. - */ - private static Sequent removeAllUnusedSkolemEqualities(Sequent sequent, - SequentFormula sf, - boolean antecedent, - Collection skolemConstants) { - Term term = sf.formula(); - boolean remove = false; - if (term.op() == Equality.EQUALS) { - if (isSkolemConstant(term.sub(0))) { - remove = !skolemConstants.contains(term.sub(0)); - } - if (!remove && isSkolemConstant(term.sub(1))) { - remove = !skolemConstants.contains(term.sub(1)); - } - } - if (remove) { - return sequent.removeFormula( - new PosInOccurrence(sf, PosInTerm.getTopLevel(), antecedent)).sequent(); - } - else { - return sequent; - } - } - - /** - * Checks if the given {@link SequentFormula} is a skolem equality. - * @param sf The {@link SequentFormula} to check. - * @return {@code -1} left side of skolem equality, {@code 0} no skolem equality, {@code 1} right side of skolem equality. - */ - public static int checkSkolemEquality(SequentFormula sf) { - return checkSkolemEquality(sf.formula()); - } - - /** - * Checks if the given {@link Term} is a skolem equality. - * @param sf The {@link Term} to check. - * @return {@code -1} left side of skolem equality, {@code 0} no skolem equality, {@code 1} right side of skolem equality. - */ - public static int checkSkolemEquality(Term term) { - if (term.op() == Equality.EQUALS) { - if (isSkolemConstant(term.sub(0))) { - return -1; - } - if (isSkolemConstant(term.sub(1))) { - return 1; - } - } - return 0; - } - - /** - * Replaces all skolem constants in the given {@link Term}. - * @param sequent The {@link Sequent} which provides the skolem equalities. - * @param term The {@link Term} to replace its skolem constants. - * @param services The {@link Services} to use. - * @return The skolem constant free {@link Term}. - */ - public static Term replaceSkolemConstants(Sequent sequent, Term term, Services services) { - int skolemCheck = checkSkolemEquality(term); - if (skolemCheck == -1) { - TermBuilder tb = services.getTermBuilder(); - List replacements = findSkolemReplacements(sequent, term.sub(0), term); - if (!replacements.isEmpty()) { - Term other = term.sub(1); - List newTerms = new LinkedList(); - for (Term replacement : replacements) { - newTerms.add(tb.equals(replacement, other)); + }); + return result; + } + + /** + * Checks if the given {@link Term} is a skolem {@link Term} meaning that it has the + * {@link SelectSkolemConstantTermLabel}. + * + * @param term The {@link Term} to check. + * @return {@code true} is skolem {@link Term}, {@code false} is not a skolem {@link Term}. + */ + public static boolean isSkolemConstant(Term term) { + return term.containsLabel(ParameterlessTermLabel.SELECT_SKOLEM_LABEL); + } + + /** + * Removes all {@link SequentFormula}s with a skolem equality from the given {@link Sequent} if + * the skolem {@link Term} is not contained in the given {@link Collection}. + * + * @param sequent The {@link Sequent} to modify. + * @param skolemConstants The allowed skolem {@link Term}s. + * @return The modified {@link Sequent} in which all not listed skolem {@link Term} equalites + * are removed. + */ + private static Sequent removeAllUnusedSkolemEqualities(Sequent sequent, + Collection skolemConstants) { + Sequent result = sequent; + for (SequentFormula sf : sequent.antecedent()) { + result = removeAllUnusedSkolemEqualities(result, sf, true, skolemConstants); + } + for (SequentFormula sf : sequent.succedent()) { + result = removeAllUnusedSkolemEqualities(result, sf, false, skolemConstants); + } + return result; + } + + /** + * Helper method of {@link #removeAllUnusedSkolemEqualities(Sequent, Collection)} which removes + * the given {@link SequentFormula} if required. + * + * @param sequent The {@link Sequent} to modify. + * @param sf The {@link SequentFormula} to remove if its skolem {@link Term} is not listed. + * @param antecedent {@code true} antecedent, {@code false} succedent. + * @param skolemConstants The allowed skolem {@link Term}s. + * @return The modified {@link Sequent} in which the {@link SequentFormula} might be removed. + */ + private static Sequent removeAllUnusedSkolemEqualities(Sequent sequent, SequentFormula sf, + boolean antecedent, Collection skolemConstants) { + Term term = sf.formula(); + boolean remove = false; + if (term.op() == Equality.EQUALS) { + if (isSkolemConstant(term.sub(0))) { + remove = !skolemConstants.contains(term.sub(0)); } - term = tb.and(newTerms); - return replaceSkolemConstants(sequent, term, services); - } - else { - return services.getTermBuilder().tt(); // If no other term is available the quality is jsut true. - } - } - else if (skolemCheck == 1) { - TermBuilder tb = services.getTermBuilder(); - List replacements = findSkolemReplacements(sequent, term.sub(1), term); - if (!replacements.isEmpty()) { - Term other = term.sub(0); - List newTerms = new LinkedList(); - for (Term replacement : replacements) { - newTerms.add(tb.equals(other, replacement)); + if (!remove && isSkolemConstant(term.sub(1))) { + remove = !skolemConstants.contains(term.sub(1)); } - term = tb.and(newTerms); - return replaceSkolemConstants(sequent, term, services); - } - else { - return services.getTermBuilder().tt(); // If no other term is available the quality is jsut true. - } - } - else { - if (isSkolemConstant(term)) { - // Skolem term - List replacements = findSkolemReplacements(sequent, term, null); - return !replacements.isEmpty() ? - replacements.get(0) : // Any of the replacements can be used, for simplicity use the first one. Alternatively may the one with the lowest depth or with least symbols might be used. - term; - } - else { - // No skolem term - List newChildren = new LinkedList(); - boolean changed = false; - for (int i = 0; i < term.arity(); i++) { - Term oldChild = term.sub(i); - Term newChild = replaceSkolemConstants(sequent, oldChild, services); - if (newChild != oldChild) { - changed = true; - } - newChildren.add(newChild); + } + if (remove) { + return sequent + .removeFormula(new PosInOccurrence(sf, PosInTerm.getTopLevel(), antecedent)) + .sequent(); + } else { + return sequent; + } + } + + /** + * Checks if the given {@link SequentFormula} is a skolem equality. + * + * @param sf The {@link SequentFormula} to check. + * @return {@code -1} left side of skolem equality, {@code 0} no skolem equality, {@code 1} + * right side of skolem equality. + */ + public static int checkSkolemEquality(SequentFormula sf) { + return checkSkolemEquality(sf.formula()); + } + + /** + * Checks if the given {@link Term} is a skolem equality. + * + * @param sf The {@link Term} to check. + * @return {@code -1} left side of skolem equality, {@code 0} no skolem equality, {@code 1} + * right side of skolem equality. + */ + public static int checkSkolemEquality(Term term) { + if (term.op() == Equality.EQUALS) { + if (isSkolemConstant(term.sub(0))) { + return -1; } - if (changed) { - if (term.op() == Junctor.NOT) { - // Create new NOT term using build in simplification of TermBuilder. - assert newChildren.size() == 1; - assert term.boundVars().isEmpty(); - assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; - Term result = services.getTermBuilder().not(newChildren.get(0)); - if (term.hasLabels()) { - result = services.getTermBuilder().label(result, term.getLabels()); - } - return result; - } - else if (term.op() == Junctor.OR) { - // Create new OR term using build in simplification of TermBuilder. - assert term.boundVars().isEmpty(); - assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; - Term result = services.getTermBuilder().or(newChildren); - if (term.hasLabels()) { - result = services.getTermBuilder().label(result, term.getLabels()); - } - return result; - } - else if (term.op() == Junctor.AND) { - // Create new AND term using build in simplification of TermBuilder. - assert term.boundVars().isEmpty(); - assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; - Term result = services.getTermBuilder().and(newChildren); - if (term.hasLabels()) { - result = services.getTermBuilder().label(result, term.getLabels()); - } - return result; - } - else if (term.op() == Junctor.IMP) { - // Create new IMP term using build in simplification of TermBuilder. - assert newChildren.size() == 2; - assert term.boundVars().isEmpty(); - assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; - return services.getTermBuilder().imp(newChildren.get(0), newChildren.get(1), term.getLabels()); - } - else { - // Create new term in general. - return services.getTermFactory().createTerm(term.op(), - new ImmutableArray(newChildren), - term.boundVars(), - term.javaBlock(), - term.getLabels()); - } + if (isSkolemConstant(term.sub(1))) { + return 1; } - else { - return term; + } + return 0; + } + + /** + * Replaces all skolem constants in the given {@link Term}. + * + * @param sequent The {@link Sequent} which provides the skolem equalities. + * @param term The {@link Term} to replace its skolem constants. + * @param services The {@link Services} to use. + * @return The skolem constant free {@link Term}. + */ + public static Term replaceSkolemConstants(Sequent sequent, Term term, Services services) { + int skolemCheck = checkSkolemEquality(term); + if (skolemCheck == -1) { + TermBuilder tb = services.getTermBuilder(); + List replacements = findSkolemReplacements(sequent, term.sub(0), term); + if (!replacements.isEmpty()) { + Term other = term.sub(1); + List newTerms = new LinkedList(); + for (Term replacement : replacements) { + newTerms.add(tb.equals(replacement, other)); + } + term = tb.and(newTerms); + return replaceSkolemConstants(sequent, term, services); + } else { + return services.getTermBuilder().tt(); // If no other term is available the quality + // is jsut true. } - } - } - } - - /** - * Utility method of {@link #replaceSkolemConstants(Sequent, Term, Services)} to - * find all equality parts of the given skolem constant. - * @param sequent The {@link Sequent} which provides the skolem equalities. - * @param skolemConstant The skolem constant to solve. - * @param skolemEquality The optional skolem equality to ignore. - * @return The equality parts of the given skolem equality. - */ - private static List findSkolemReplacements(Sequent sequent, Term skolemConstant, Term skolemEquality) { - List result = new LinkedList(); - for (SequentFormula sf : sequent) { - Term term = sf.formula(); - if (term != skolemEquality) { - int skolemCheck = checkSkolemEquality(term); - if (skolemCheck == -1) { - if (term.sub(0).equalsModIrrelevantTermLabels(skolemConstant)) { - result.add(term.sub(1)); - } + } else if (skolemCheck == 1) { + TermBuilder tb = services.getTermBuilder(); + List replacements = findSkolemReplacements(sequent, term.sub(1), term); + if (!replacements.isEmpty()) { + Term other = term.sub(0); + List newTerms = new LinkedList(); + for (Term replacement : replacements) { + newTerms.add(tb.equals(other, replacement)); + } + term = tb.and(newTerms); + return replaceSkolemConstants(sequent, term, services); + } else { + return services.getTermBuilder().tt(); // If no other term is available the quality + // is jsut true. } - else if (skolemCheck == 1) { - if (term.sub(1).equalsModIrrelevantTermLabels(skolemConstant)) { - result.add(term.sub(0)); - } + } else { + if (isSkolemConstant(term)) { + // Skolem term + List replacements = findSkolemReplacements(sequent, term, null); + return !replacements.isEmpty() ? replacements.get(0) : // Any of the replacements + // can be used, for + // simplicity use the first + // one. Alternatively may the + // one with the lowest depth + // or with least symbols + // might be used. + term; + } else { + // No skolem term + List newChildren = new LinkedList(); + boolean changed = false; + for (int i = 0; i < term.arity(); i++) { + Term oldChild = term.sub(i); + Term newChild = replaceSkolemConstants(sequent, oldChild, services); + if (newChild != oldChild) { + changed = true; + } + newChildren.add(newChild); + } + if (changed) { + if (term.op() == Junctor.NOT) { + // Create new NOT term using build in simplification of TermBuilder. + assert newChildren.size() == 1; + assert term.boundVars().isEmpty(); + assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; + Term result = services.getTermBuilder().not(newChildren.get(0)); + if (term.hasLabels()) { + result = services.getTermBuilder().label(result, term.getLabels()); + } + return result; + } else if (term.op() == Junctor.OR) { + // Create new OR term using build in simplification of TermBuilder. + assert term.boundVars().isEmpty(); + assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; + Term result = services.getTermBuilder().or(newChildren); + if (term.hasLabels()) { + result = services.getTermBuilder().label(result, term.getLabels()); + } + return result; + } else if (term.op() == Junctor.AND) { + // Create new AND term using build in simplification of TermBuilder. + assert term.boundVars().isEmpty(); + assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; + Term result = services.getTermBuilder().and(newChildren); + if (term.hasLabels()) { + result = services.getTermBuilder().label(result, term.getLabels()); + } + return result; + } else if (term.op() == Junctor.IMP) { + // Create new IMP term using build in simplification of TermBuilder. + assert newChildren.size() == 2; + assert term.boundVars().isEmpty(); + assert term.javaBlock() == JavaBlock.EMPTY_JAVABLOCK; + return services.getTermBuilder().imp(newChildren.get(0), newChildren.get(1), + term.getLabels()); + } else { + // Create new term in general. + return services.getTermFactory().createTerm(term.op(), + new ImmutableArray(newChildren), term.boundVars(), + term.javaBlock(), term.getLabels()); + } + } else { + return term; + } } - } - } - return result; - } - - /** - * Checks if the given {@link Sort} represents a {@code null} value in the given {@link Services}. - * @param sort The {@link Sort} to check. - * @param services The {@link Services} to use. - * @return {@code true} is Null-Sort, {@code false} is something else. - */ - public static boolean isNullSort(Sort sort, Services services) { - return sort instanceof NullSort; - } - - /** - * Checks if the given {@link IProgramVariable} is static or not. - * @return {@code true} is static, {@code false} is not static or is array cell. - */ - public static boolean isStaticVariable(IProgramVariable programVariable) { - return programVariable instanceof ProgramVariable && - ((ProgramVariable)programVariable).isStatic(); - } - - /** - * Collects all {@link IProgramVariable}s of the given {@link FieldDeclaration}. - * @param fd The given {@link FieldDeclaration}. - * @return The found {@link IProgramVariable}s for the given {@link FieldDeclaration}. - */ - public static Set getProgramVariables(FieldDeclaration fd) { - Set result = new LinkedHashSet(); - if (fd != null) { - ImmutableArray specifications = fd.getFieldSpecifications(); - for (FieldSpecification spec : specifications) { - result.add(spec.getProgramVariable()); - } - } - return result; - } - - /** - * Computes the path condition of the given {@link Node}. - * @param node The {@link Node} to compute its path condition. - * @param simplify {@code true} simplify each branch condition in a side proof, {@code false} do not simplify branch conditions. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed path condition. - * @throws ProofInputException Occurred Exception. - */ - public static Term computePathCondition(Node node, - boolean simplify, - boolean improveReadability) throws ProofInputException { - return computePathCondition(null, node, simplify, improveReadability); - } - - /** - * Computes the path condition between the given {@link Node}s. - * @param parentNode The {@link Node} to stop path condition computation at. - * @param childNode The {@link Node} to compute its path condition back to the parent. - * @param simplify {@code true} simplify each branch condition in a side proof, {@code false} do not simplify branch conditions. - * @param improveReadability {@code true} improve readability, {@code false} do not improve readability. - * @return The computed path condition. - * @throws ProofInputException Occurred Exception. - */ - public static Term computePathCondition(Node parentNode, - Node childNode, - boolean simplify, - boolean improveReadability) throws ProofInputException { - if (childNode != null) { - final Services services = childNode.proof().getServices(); - Term pathCondition = services.getTermBuilder().tt(); - while (childNode != null && childNode != parentNode) { - Node parent = childNode.parent(); - if (parent != null && parent.childrenCount() >= 2) { - Term branchCondition = computeBranchCondition(childNode, simplify, improveReadability); - pathCondition = services.getTermBuilder().and(branchCondition, pathCondition); + } + } + + /** + * Utility method of {@link #replaceSkolemConstants(Sequent, Term, Services)} to find all + * equality parts of the given skolem constant. + * + * @param sequent The {@link Sequent} which provides the skolem equalities. + * @param skolemConstant The skolem constant to solve. + * @param skolemEquality The optional skolem equality to ignore. + * @return The equality parts of the given skolem equality. + */ + private static List findSkolemReplacements(Sequent sequent, Term skolemConstant, + Term skolemEquality) { + List result = new LinkedList(); + for (SequentFormula sf : sequent) { + Term term = sf.formula(); + if (term != skolemEquality) { + int skolemCheck = checkSkolemEquality(term); + if (skolemCheck == -1) { + if (term.sub(0).equalsModIrrelevantTermLabels(skolemConstant)) { + result.add(term.sub(1)); + } + } else if (skolemCheck == 1) { + if (term.sub(1).equalsModIrrelevantTermLabels(skolemConstant)) { + result.add(term.sub(0)); + } + } } - childNode = parent; - } - if (services.getTermBuilder().ff().equalsModIrrelevantTermLabels(pathCondition)) { - throw new ProofInputException("Path condition computation failed because the result is false."); - } - return pathCondition; - } - else { - return null; - } - } - - /** - * Checks if the {@link Sort} of the given {@link Term} is a reference type. - * @param services The {@link Services} to use. - * @param term The {@link Term} to check. - * @return {@code true} is reference sort, {@code false} is no reference sort. - */ - public static boolean hasReferenceSort(Services services, Term term) { - if (services != null && term != null) { - return hasReferenceSort(services, term.sort()); - } - else { - return false; - } - } - - /** - * Checks if the {@link Sort} of the given {@link IProgramVariable} is a reference type. - * @param services The {@link Services} to use. - * @param var The {@link IProgramVariable} to check. - * @return {@code true} is reference sort, {@code false} is no reference sort. - */ - public static boolean hasReferenceSort(Services services, IProgramVariable var) { - if (services != null && var != null) { - return hasReferenceSort(services, var.sort()); - } - else { - return false; - } - } - - /** - * Checks if the {@link Sort} is a reference type. - * @param services The {@link Services} to use. - * @param sort The {@link Sort} to check. - * @return {@code true} is reference sort, {@code false} is no reference sort. - */ - public static boolean hasReferenceSort(Services services, Sort sort) { - boolean referenceSort = false; - if (services != null && sort != null) { - KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(sort); - if (kjt != null) { - TypeConverter typeConverter = services.getTypeConverter(); - referenceSort = typeConverter.isReferenceType(kjt) && // Check if the value is a reference type - (!(kjt.getJavaType() instanceof TypeDeclaration) || // check if the value is a library class which should be ignored - !((TypeDeclaration)kjt.getJavaType()).isLibraryClass()); - } - } - return referenceSort; - } - - /** - * Returns the human readable name of the given {@link IProgramVariable}. - * @param pv The {@link IProgramVariable} to get its name. - * @return The human readable name of the given {@link IProgramVariable}. - */ - public static String getDisplayString(IProgramVariable pv) { - if (pv != null) { - if (pv.name() instanceof ProgramElementName) { - ProgramElementName name = (ProgramElementName)pv.name(); - if (SymbolicExecutionUtil.isStaticVariable(pv)) { - return name.toString(); + } + return result; + } + + /** + * Checks if the given {@link Sort} represents a {@code null} value in the given + * {@link Services}. + * + * @param sort The {@link Sort} to check. + * @param services The {@link Services} to use. + * @return {@code true} is Null-Sort, {@code false} is something else. + */ + public static boolean isNullSort(Sort sort, Services services) { + return sort instanceof NullSort; + } + + /** + * Checks if the given {@link IProgramVariable} is static or not. + * + * @return {@code true} is static, {@code false} is not static or is array cell. + */ + public static boolean isStaticVariable(IProgramVariable programVariable) { + return programVariable instanceof ProgramVariable + && ((ProgramVariable) programVariable).isStatic(); + } + + /** + * Collects all {@link IProgramVariable}s of the given {@link FieldDeclaration}. + * + * @param fd The given {@link FieldDeclaration}. + * @return The found {@link IProgramVariable}s for the given {@link FieldDeclaration}. + */ + public static Set getProgramVariables(FieldDeclaration fd) { + Set result = new LinkedHashSet(); + if (fd != null) { + ImmutableArray specifications = fd.getFieldSpecifications(); + for (FieldSpecification spec : specifications) { + result.add(spec.getProgramVariable()); } - else { - return name.getProgramName(); + } + return result; + } + + /** + * Computes the path condition of the given {@link Node}. + * + * @param node The {@link Node} to compute its path condition. + * @param simplify {@code true} simplify each branch condition in a side proof, {@code false} do + * not simplify branch conditions. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed path condition. + * @throws ProofInputException Occurred Exception. + */ + public static Term computePathCondition(Node node, boolean simplify, boolean improveReadability) + throws ProofInputException { + return computePathCondition(null, node, simplify, improveReadability); + } + + /** + * Computes the path condition between the given {@link Node}s. + * + * @param parentNode The {@link Node} to stop path condition computation at. + * @param childNode The {@link Node} to compute its path condition back to the parent. + * @param simplify {@code true} simplify each branch condition in a side proof, {@code false} do + * not simplify branch conditions. + * @param improveReadability {@code true} improve readability, {@code false} do not improve + * readability. + * @return The computed path condition. + * @throws ProofInputException Occurred Exception. + */ + public static Term computePathCondition(Node parentNode, Node childNode, boolean simplify, + boolean improveReadability) throws ProofInputException { + if (childNode != null) { + final Services services = childNode.proof().getServices(); + Term pathCondition = services.getTermBuilder().tt(); + while (childNode != null && childNode != parentNode) { + Node parent = childNode.parent(); + if (parent != null && parent.childrenCount() >= 2) { + Term branchCondition = + computeBranchCondition(childNode, simplify, improveReadability); + pathCondition = services.getTermBuilder().and(branchCondition, pathCondition); + } + childNode = parent; } - } - else { - return pv.name().toString(); - } - } - else { - return null; - } - } - - /** - * Returns the root of the given {@link IExecutionNode}. - * @param executionNode The {@link IExecutionNode} to get the root of its symbolic execution tree. - * @return The root of the given {@link IExecutionNode}. - */ - public static IExecutionNode getRoot(IExecutionNode executionNode) { - if (executionNode != null) { - while (executionNode.getParent() != null) { - executionNode = executionNode.getParent(); - } - return executionNode; - } - else { - return null; - } - } - - /** - * Extracts the exception variable which is used to check if the executed program in proof terminates normally. - * @param proof The {@link Proof} to extract variable from. - * @return The extract variable. - */ - public static IProgramVariable extractExceptionVariable(Proof proof) { - Node root = proof.root(); - PosInOccurrence modalityTermPIO = SymbolicExecutionUtil.findModalityWithMinSymbolicExecutionLabelId(root.sequent()); - Term modalityTerm = modalityTermPIO != null ? modalityTermPIO.subTerm() : null; - if (modalityTerm != null) { - modalityTerm = TermBuilder.goBelowUpdates(modalityTerm); - JavaProgramElement updateContent = modalityTerm.javaBlock().program(); - if (updateContent instanceof StatementBlock) { // try catch inclusive - ImmutableArray updateContentBody = - ((StatementBlock)updateContent).getBody(); - Try tryStatement = null; - Iterator iter = updateContentBody.iterator(); - while (tryStatement == null && iter.hasNext()) { - Statement next = iter.next(); - if (next instanceof Try) { - tryStatement = (Try)next; - } + if (services.getTermBuilder().ff().equalsModIrrelevantTermLabels(pathCondition)) { + throw new ProofInputException( + "Path condition computation failed because the result is false."); } - if (tryStatement != null) { - if (tryStatement.getBranchCount() == 1 - && tryStatement.getBranchList().get(0) instanceof Catch) { - Catch catchStatement = (Catch)tryStatement.getBranchList().get(0); - if (catchStatement.getBody() instanceof StatementBlock) { - StatementBlock catchBlock = (StatementBlock)catchStatement.getBody(); - if (catchBlock.getBody().size() == 1 - && catchBlock.getBody().get(0) instanceof Assignment) { - Assignment assignment = (Assignment)catchBlock.getBody().get(0); - if (assignment.getFirstElement() instanceof IProgramVariable) { - IProgramVariable var = (IProgramVariable)assignment.getFirstElement(); - return var; + return pathCondition; + } else { + return null; + } + } + + /** + * Checks if the {@link Sort} of the given {@link Term} is a reference type. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to check. + * @return {@code true} is reference sort, {@code false} is no reference sort. + */ + public static boolean hasReferenceSort(Services services, Term term) { + if (services != null && term != null) { + return hasReferenceSort(services, term.sort()); + } else { + return false; + } + } + + /** + * Checks if the {@link Sort} of the given {@link IProgramVariable} is a reference type. + * + * @param services The {@link Services} to use. + * @param var The {@link IProgramVariable} to check. + * @return {@code true} is reference sort, {@code false} is no reference sort. + */ + public static boolean hasReferenceSort(Services services, IProgramVariable var) { + if (services != null && var != null) { + return hasReferenceSort(services, var.sort()); + } else { + return false; + } + } + + /** + * Checks if the {@link Sort} is a reference type. + * + * @param services The {@link Services} to use. + * @param sort The {@link Sort} to check. + * @return {@code true} is reference sort, {@code false} is no reference sort. + */ + public static boolean hasReferenceSort(Services services, Sort sort) { + boolean referenceSort = false; + if (services != null && sort != null) { + KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(sort); + if (kjt != null) { + TypeConverter typeConverter = services.getTypeConverter(); + referenceSort = typeConverter.isReferenceType(kjt) && // Check if the value is a + // reference type + (!(kjt.getJavaType() instanceof TypeDeclaration) || // check if the value is + // a library class which + // should be ignored + !((TypeDeclaration) kjt.getJavaType()).isLibraryClass()); + } + } + return referenceSort; + } + + /** + * Returns the human readable name of the given {@link IProgramVariable}. + * + * @param pv The {@link IProgramVariable} to get its name. + * @return The human readable name of the given {@link IProgramVariable}. + */ + public static String getDisplayString(IProgramVariable pv) { + if (pv != null) { + if (pv.name() instanceof ProgramElementName) { + ProgramElementName name = (ProgramElementName) pv.name(); + if (SymbolicExecutionUtil.isStaticVariable(pv)) { + return name.toString(); + } else { + return name.getProgramName(); + } + } else { + return pv.name().toString(); + } + } else { + return null; + } + } + + /** + * Returns the root of the given {@link IExecutionNode}. + * + * @param executionNode The {@link IExecutionNode} to get the root of its symbolic execution + * tree. + * @return The root of the given {@link IExecutionNode}. + */ + public static IExecutionNode getRoot(IExecutionNode executionNode) { + if (executionNode != null) { + while (executionNode.getParent() != null) { + executionNode = executionNode.getParent(); + } + return executionNode; + } else { + return null; + } + } + + /** + * Extracts the exception variable which is used to check if the executed program in proof + * terminates normally. + * + * @param proof The {@link Proof} to extract variable from. + * @return The extract variable. + */ + public static IProgramVariable extractExceptionVariable(Proof proof) { + Node root = proof.root(); + PosInOccurrence modalityTermPIO = + SymbolicExecutionUtil.findModalityWithMinSymbolicExecutionLabelId(root.sequent()); + Term modalityTerm = modalityTermPIO != null ? modalityTermPIO.subTerm() : null; + if (modalityTerm != null) { + modalityTerm = TermBuilder.goBelowUpdates(modalityTerm); + JavaProgramElement updateContent = modalityTerm.javaBlock().program(); + if (updateContent instanceof StatementBlock) { // try catch inclusive + ImmutableArray updateContentBody = + ((StatementBlock) updateContent).getBody(); + Try tryStatement = null; + Iterator iter = updateContentBody.iterator(); + while (tryStatement == null && iter.hasNext()) { + Statement next = iter.next(); + if (next instanceof Try) { + tryStatement = (Try) next; + } + } + if (tryStatement != null) { + if (tryStatement.getBranchCount() == 1 + && tryStatement.getBranchList().get(0) instanceof Catch) { + Catch catchStatement = (Catch) tryStatement.getBranchList().get(0); + if (catchStatement.getBody() instanceof StatementBlock) { + StatementBlock catchBlock = (StatementBlock) catchStatement.getBody(); + if (catchBlock.getBody().size() == 1 + && catchBlock.getBody().get(0) instanceof Assignment) { + Assignment assignment = (Assignment) catchBlock.getBody().get(0); + if (assignment.getFirstElement() instanceof IProgramVariable) { + IProgramVariable var = + (IProgramVariable) assignment.getFirstElement(); + return var; + } + } } - } - } - } + } + } } - } - } - throw new IllegalStateException("Can't extract exception variable from proof."); - } - - /** - * Configures the proof to use the given settings. - * @param proof The {@link Proof} to configure. - * @param useOperationContracts {@code true} use operation contracts, {@code false} expand methods. - * @param useLoopInvariants {@code true} use loop invariants, {@code false} expand loops. - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param useLoopInvariants {@code true} immediately alias checks, {@code false} alias checks never. - */ - public static void updateStrategySettings(Proof proof, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecksImmediately) { - if (proof != null && !proof.isDisposed()) { - String methodTreatmentValue = useOperationContracts ? - StrategyProperties.METHOD_CONTRACT : - StrategyProperties.METHOD_EXPAND; - String loopTreatmentValue = useLoopInvariants ? - StrategyProperties.LOOP_INVARIANT : - StrategyProperties.LOOP_EXPAND; - String nonExecutionBranchHidingValue = - nonExecutionBranchHidingSideProofs ? - StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF : - StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OFF; - String aliasChecksValue = aliasChecksImmediately ? - StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY : - StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_NEVER; - StrategyProperties sp = - proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, methodTreatmentValue); - sp.setProperty(StrategyProperties.LOOP_OPTIONS_KEY, loopTreatmentValue); - sp.setProperty(StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY, - nonExecutionBranchHidingValue); - sp.setProperty(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY, - aliasChecksValue); - updateStrategySettings(proof, sp); - } - } - - /** - * Configures the proof to use the given {@link StrategyProperties}. - * @param proof The {@link Proof} to configure. - * @param sb The {@link StrategyProperties} to set. - */ - public static void updateStrategySettings(Proof proof, - StrategyProperties sp) { - if (proof != null && !proof.isDisposed()) { - assert sp != null; - ProofSettings.DEFAULT_SETTINGS.getStrategySettings().setActiveStrategyProperties(sp); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); - } - } - - /** - * Checks if the choice settings are initialized. - * @return {@code true} settings are initialized, {@code false} settings are not initialized. - */ - public static boolean isChoiceSettingInitialised() { - return ProofSettings.isChoiceSettingInitialised(); - } - - /** - * Checks if the given node should be represented as loop body termination. - * @param node The current {@link Node} in the proof tree of KeY. - * @param ruleApp The {@link RuleApp} may used or not used in the rule. - * @return {@code true} represent node as loop body termination, {@code false} represent node as something else. - */ - public static boolean isLoopBodyTermination(final Node node, RuleApp ruleApp) { - boolean result = false; - if (ruleApp instanceof OneStepSimplifierRuleApp) { - // Check applied rules in protocol - OneStepSimplifierRuleApp simplifierApp = (OneStepSimplifierRuleApp)ruleApp; - if (simplifierApp.getProtocol() != null) { - RuleApp terminationApp = - CollectionUtil.search(simplifierApp.getProtocol(), new IFilter() { - @Override - public boolean select(RuleApp element) { - return isLoopBodyTermination(node, element); - } - }); - result = terminationApp != null; - } - } - else if (hasLoopBodyTerminationLabel(ruleApp)) { - if ("impRight".equals(MiscTools.getRuleDisplayName(ruleApp))) { - result = true; // Implication removed (not done if left part is false) - } - else { - Term term = ruleApp.posInOccurrence().subTerm(); - if (term.op() == Junctor.IMP && term.sub(0).op() == Junctor.TRUE) { - result = true; // Left part is true + } + throw new IllegalStateException("Can't extract exception variable from proof."); + } + + /** + * Configures the proof to use the given settings. + * + * @param proof The {@link Proof} to configure. + * @param useOperationContracts {@code true} use operation contracts, {@code false} expand + * methods. + * @param useLoopInvariants {@code true} use loop invariants, {@code false} expand loops. + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param useLoopInvariants {@code true} immediately alias checks, {@code false} alias checks + * never. + */ + public static void updateStrategySettings(Proof proof, boolean useOperationContracts, + boolean useLoopInvariants, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecksImmediately) { + if (proof != null && !proof.isDisposed()) { + String methodTreatmentValue = useOperationContracts ? StrategyProperties.METHOD_CONTRACT + : StrategyProperties.METHOD_EXPAND; + String loopTreatmentValue = useLoopInvariants ? StrategyProperties.LOOP_INVARIANT + : StrategyProperties.LOOP_EXPAND; + String nonExecutionBranchHidingValue = nonExecutionBranchHidingSideProofs + ? StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_SIDE_PROOF + : StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OFF; + String aliasChecksValue = aliasChecksImmediately + ? StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_IMMEDIATELY + : StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_NEVER; + StrategyProperties sp = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + sp.setProperty(StrategyProperties.METHOD_OPTIONS_KEY, methodTreatmentValue); + sp.setProperty(StrategyProperties.LOOP_OPTIONS_KEY, loopTreatmentValue); + sp.setProperty( + StrategyProperties.SYMBOLIC_EXECUTION_NON_EXECUTION_BRANCH_HIDING_OPTIONS_KEY, + nonExecutionBranchHidingValue); + sp.setProperty(StrategyProperties.SYMBOLIC_EXECUTION_ALIAS_CHECK_OPTIONS_KEY, + aliasChecksValue); + updateStrategySettings(proof, sp); + } + } + + /** + * Configures the proof to use the given {@link StrategyProperties}. + * + * @param proof The {@link Proof} to configure. + * @param sb The {@link StrategyProperties} to set. + */ + public static void updateStrategySettings(Proof proof, StrategyProperties sp) { + if (proof != null && !proof.isDisposed()) { + assert sp != null; + ProofSettings.DEFAULT_SETTINGS.getStrategySettings().setActiveStrategyProperties(sp); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(sp); + } + } + + /** + * Checks if the choice settings are initialized. + * + * @return {@code true} settings are initialized, {@code false} settings are not initialized. + */ + public static boolean isChoiceSettingInitialised() { + return ProofSettings.isChoiceSettingInitialised(); + } + + /** + * Checks if the given node should be represented as loop body termination. + * + * @param node The current {@link Node} in the proof tree of KeY. + * @param ruleApp The {@link RuleApp} may used or not used in the rule. + * @return {@code true} represent node as loop body termination, {@code false} represent node as + * something else. + */ + public static boolean isLoopBodyTermination(final Node node, RuleApp ruleApp) { + boolean result = false; + if (ruleApp instanceof OneStepSimplifierRuleApp) { + // Check applied rules in protocol + OneStepSimplifierRuleApp simplifierApp = (OneStepSimplifierRuleApp) ruleApp; + if (simplifierApp.getProtocol() != null) { + RuleApp terminationApp = + CollectionUtil.search(simplifierApp.getProtocol(), new IFilter() { + @Override + public boolean select(RuleApp element) { + return isLoopBodyTermination(node, element); + } + }); + result = terminationApp != null; } - } - } - return result; - } - - /** - * Checks if the given {@link Operator} is a heap. - * @param op The {@link Operator} to check. - * @param heapLDT The {@link HeapLDT} which provides the available heaps. - * @return {@code true} {@link Operator} is heap, {@code false} {@link Operator} is something else. - */ - public static boolean isHeap(Operator op, HeapLDT heapLDT) { - if (op instanceof SortedOperator) { - final Sort opSort = ((SortedOperator) op).sort(); - return CollectionUtil.search(heapLDT.getAllHeaps(), new IFilter() { - @Override - public boolean select(LocationVariable element) { - return opSort == element.sort(); + } else if (hasLoopBodyTerminationLabel(ruleApp)) { + if ("impRight".equals(MiscTools.getRuleDisplayName(ruleApp))) { + result = true; // Implication removed (not done if left part is false) + } else { + Term term = ruleApp.posInOccurrence().subTerm(); + if (term.op() == Junctor.IMP && term.sub(0).op() == Junctor.TRUE) { + result = true; // Left part is true + } } - }) != null; - } - else { - return false; - } - } - - /** - * Checks if the given {@link Operator} is the base heap. - * @param op The {@link Operator} to check. - * @param heapLDT The {@link HeapLDT} which provides the available heaps. - * @return {@code true} {@link Operator} is the base heap, {@code false} {@link Operator} is something else. - */ - public static boolean isBaseHeap(Operator op, HeapLDT heapLDT) { - return op == heapLDT.getHeapForName(HeapLDT.BASE_HEAP_NAME); - } - - /** - * Returns the path to the source file defined by the given {@link PositionInfo}. - * @param posInfo The {@link PositionInfo} to extract source file from. - * @return The source file name or {@code null} if not available. - */ - public static String getSourcePath(PositionInfo posInfo) { - return MiscTools.getSourcePath(posInfo); - } - - /** - * Checks if the given {@link Term} is a select on a heap. - * @param services The {@link Services} to use. - * @param term The {@link Term} to check. - * @return {@code true} is select, {@code false} is something else. - */ - public static boolean isSelect(Services services, Term term) { - if (!isNullSort(term.sort(), services)) { - Function select = services.getTypeConverter().getHeapLDT().getSelect(term.sort(), services); - return select == term.op(); - } - else { - return false; - } - } - - /** - * Checks if the given {@link Operator} is a number. - * @param op The {@link Operator} to check. - * @return {@code true} is number, {@code false} is something else. - */ - public static boolean isNumber(Operator op) { - if (op instanceof Function) { - String[] numbers = {"#", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Z", "neglit"}; - Arrays.sort(numbers); - int index = Arrays.binarySearch(numbers, op.name().toString()); - return index >= 0; - } - else { - return false; - } - } - - /** - * Checks if the given {@link Operator} is a boolean. - * @param op The {@link Operator} to check. - * @return {@code true} is boolean, {@code false} is something else. - */ - public static boolean isBoolean(Services services, Operator op) { - BooleanLDT booleanLDT = services.getTypeConverter().getBooleanLDT(); - return booleanLDT.getFalseConst() == op || - booleanLDT.getTrueConst() == op; - } - - /** - * Returns the default taclet options for symbolic execution. - * @return The default taclet options for symbolic execution. - */ - public static HashMap getDefaultTacletOptions() { - return MiscTools.getDefaultTacletOptions(); - } - - /** - *

    - * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. - *

    - *

    - * The functionality is similar to {@link ProofSaver#printTerm(Term, Services, boolean)} but allows to set custom settings. - *

    - * @param term The {@link Term} to convert. - * @param services The {@link Services} to use. - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @return The {@link String} representation of the given {@link Term}. - */ - public static String formatTerm(Term term, - Services services, - boolean useUnicode, - boolean usePrettyPrinting) { - if ((useUnicode || usePrettyPrinting) && services != null) { - StringBuffer result; - NotationInfo ni = new NotationInfo(); - LogicPrinter logicPrinter = new LogicPrinter(new ProgramPrinter(null), ni, services, true); - logicPrinter.getNotationInfo().refresh(services, usePrettyPrinting, useUnicode); - try { - logicPrinter.printTerm(term); - } catch(IOException ioe) { - LOGGER.debug("", ioe); - } - result = logicPrinter.result(); - if (result.charAt(result.length()-1) == '\n') - result.deleteCharAt(result.length()-1); - return result.toString(); - } - else { - return term != null ? - TermLabel.removeIrrelevantLabels(term, services).toString() - : null; - } - } - - /** - * Checks if pretty printing is enabled or not. - * @return {@code true} pretty printing is enabled, {@code false} pretty printing is disabled. - */ - public static boolean isUsePrettyPrinting() { - return ProofIndependentSettings.isUsePrettyPrinting(); - } - - /** - * Defines if pretty printing is enabled or not. - * @param usePrettyPrinting {@code true} pretty printing is enabled, {@code false} pretty printing is disabled. - */ - public static void setUsePrettyPrinting(boolean usePrettyPrinting) { - ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); - } - - /** - * Checks if the {@link Goal} has applicable rules. - * @param goal The {@link Goal} to check. - * @return {@code true} has applicable rules, {@code false} no rules are applicable. - */ - public static boolean hasApplicableRules(Goal goal) { - return Goal.hasApplicableRules(goal); - } - - /** - * Computes the call stack size and the second statement - * similar to {@link NodeInfo#computeActiveStatement(SourceElement)}. - * @param ruleApp The {@link RuleApp}. - * @return The computed call stack size and the second statement if available. - */ - public static Pair computeSecondStatement(RuleApp ruleApp) { - if (ruleApp != null) { - // Find inner most block - SourceElement firstStatement = NodeInfo.computeFirstStatement(ruleApp); - Deque blocks = new LinkedList(); - int methodFrameCount = 0; - if (firstStatement != null) { - if (firstStatement instanceof StatementBlock) { - blocks.addFirst((StatementBlock) firstStatement); + } + return result; + } + + /** + * Checks if the given {@link Operator} is a heap. + * + * @param op The {@link Operator} to check. + * @param heapLDT The {@link HeapLDT} which provides the available heaps. + * @return {@code true} {@link Operator} is heap, {@code false} {@link Operator} is something + * else. + */ + public static boolean isHeap(Operator op, HeapLDT heapLDT) { + if (op instanceof SortedOperator) { + final Sort opSort = ((SortedOperator) op).sort(); + return CollectionUtil.search(heapLDT.getAllHeaps(), new IFilter() { + @Override + public boolean select(LocationVariable element) { + return opSort == element.sort(); + } + }) != null; + } else { + return false; + } + } + + /** + * Checks if the given {@link Operator} is the base heap. + * + * @param op The {@link Operator} to check. + * @param heapLDT The {@link HeapLDT} which provides the available heaps. + * @return {@code true} {@link Operator} is the base heap, {@code false} {@link Operator} is + * something else. + */ + public static boolean isBaseHeap(Operator op, HeapLDT heapLDT) { + return op == heapLDT.getHeapForName(HeapLDT.BASE_HEAP_NAME); + } + + /** + * Returns the path to the source file defined by the given {@link PositionInfo}. + * + * @param posInfo The {@link PositionInfo} to extract source file from. + * @return The source file name or {@code null} if not available. + */ + public static String getSourcePath(PositionInfo posInfo) { + return MiscTools.getSourcePath(posInfo); + } + + /** + * Checks if the given {@link Term} is a select on a heap. + * + * @param services The {@link Services} to use. + * @param term The {@link Term} to check. + * @return {@code true} is select, {@code false} is something else. + */ + public static boolean isSelect(Services services, Term term) { + if (!isNullSort(term.sort(), services)) { + Function select = + services.getTypeConverter().getHeapLDT().getSelect(term.sort(), services); + return select == term.op(); + } else { + return false; + } + } + + /** + * Checks if the given {@link Operator} is a number. + * + * @param op The {@link Operator} to check. + * @return {@code true} is number, {@code false} is something else. + */ + public static boolean isNumber(Operator op) { + if (op instanceof Function) { + String[] numbers = + { "#", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Z", "neglit" }; + Arrays.sort(numbers); + int index = Arrays.binarySearch(numbers, op.name().toString()); + return index >= 0; + } else { + return false; + } + } + + /** + * Checks if the given {@link Operator} is a boolean. + * + * @param op The {@link Operator} to check. + * @return {@code true} is boolean, {@code false} is something else. + */ + public static boolean isBoolean(Services services, Operator op) { + BooleanLDT booleanLDT = services.getTypeConverter().getBooleanLDT(); + return booleanLDT.getFalseConst() == op || booleanLDT.getTrueConst() == op; + } + + /** + * Returns the default taclet options for symbolic execution. + * + * @return The default taclet options for symbolic execution. + */ + public static HashMap getDefaultTacletOptions() { + return MiscTools.getDefaultTacletOptions(); + } + + /** + *

    + * Converts the given {@link Term} into a {@link String} respecting {@link #isUsePretty()}. + *

    + *

    + * The functionality is similar to {@link ProofSaver#printTerm(Term, Services, boolean)} but + * allows to set custom settings. + *

    + * + * @param term The {@link Term} to convert. + * @param services The {@link Services} to use. + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @return The {@link String} representation of the given {@link Term}. + */ + public static String formatTerm(Term term, Services services, boolean useUnicode, + boolean usePrettyPrinting) { + if ((useUnicode || usePrettyPrinting) && services != null) { + StringBuffer result; + NotationInfo ni = new NotationInfo(); + LogicPrinter logicPrinter = + new LogicPrinter(new ProgramPrinter(null), ni, services, true); + logicPrinter.getNotationInfo().refresh(services, usePrettyPrinting, useUnicode); + try { + logicPrinter.printTerm(term); + } catch (IOException ioe) { + LOGGER.debug("", ioe); } - SourceElement lastStatement = null; - while (firstStatement instanceof ProgramPrefix && - lastStatement != firstStatement) { - lastStatement = firstStatement; - firstStatement = firstStatement.getFirstElementIncludingBlocks(); - if (lastStatement instanceof MethodFrame) { - blocks.clear(); // Only block of inner most method frames are of interest. - methodFrameCount++; - } - if (firstStatement instanceof StatementBlock) { - blocks.addFirst((StatementBlock) firstStatement); - } + result = logicPrinter.result(); + if (result.charAt(result.length() - 1) == '\n') + result.deleteCharAt(result.length() - 1); + return result.toString(); + } else { + return term != null ? TermLabel.removeIrrelevantLabels(term, services).toString() + : null; + } + } + + /** + * Checks if pretty printing is enabled or not. + * + * @return {@code true} pretty printing is enabled, {@code false} pretty printing is disabled. + */ + public static boolean isUsePrettyPrinting() { + return ProofIndependentSettings.isUsePrettyPrinting(); + } + + /** + * Defines if pretty printing is enabled or not. + * + * @param usePrettyPrinting {@code true} pretty printing is enabled, {@code false} pretty + * printing is disabled. + */ + public static void setUsePrettyPrinting(boolean usePrettyPrinting) { + ProofIndependentSettings.setUsePrettyPrinting(usePrettyPrinting); + } + + /** + * Checks if the {@link Goal} has applicable rules. + * + * @param goal The {@link Goal} to check. + * @return {@code true} has applicable rules, {@code false} no rules are applicable. + */ + public static boolean hasApplicableRules(Goal goal) { + return Goal.hasApplicableRules(goal); + } + + /** + * Computes the call stack size and the second statement similar to + * {@link NodeInfo#computeActiveStatement(SourceElement)}. + * + * @param ruleApp The {@link RuleApp}. + * @return The computed call stack size and the second statement if available. + */ + public static Pair computeSecondStatement(RuleApp ruleApp) { + if (ruleApp != null) { + // Find inner most block + SourceElement firstStatement = NodeInfo.computeFirstStatement(ruleApp); + Deque blocks = new LinkedList(); + int methodFrameCount = 0; + if (firstStatement != null) { + if (firstStatement instanceof StatementBlock) { + blocks.addFirst((StatementBlock) firstStatement); + } + SourceElement lastStatement = null; + while (firstStatement instanceof ProgramPrefix && lastStatement != firstStatement) { + lastStatement = firstStatement; + firstStatement = firstStatement.getFirstElementIncludingBlocks(); + if (lastStatement instanceof MethodFrame) { + blocks.clear(); // Only block of inner most method frames are of interest. + methodFrameCount++; + } + if (firstStatement instanceof StatementBlock) { + blocks.addFirst((StatementBlock) firstStatement); + } + } } - } - // Compute second statement - StatementBlock block = null; - while (!blocks.isEmpty() && (block == null || block.getChildCount() < 2)) { - block = blocks.removeFirst(); - } - if (block != null && block.getChildCount() >= 2) { - return new Pair(methodFrameCount, block.getChildAt(1)); - } - else { - return new Pair(methodFrameCount, null); - } - } - else { - return null; - } - } - - /** - * Compares the given {@link SourceElement}s including their {@link PositionInfo}s. - * @param first The first {@link SourceElement}. - * @param second The second {@link SourceElement}. - * @return {@code true} both are equal and at the same {@link PositionInfo}, {@code false} otherwise. - */ - public static boolean equalsWithPosition(SourceElement first, SourceElement second) { - if (first != null && second != null) { - if (first instanceof While) { - if (second instanceof While) { - // Special treatment for while because its position info is lost during prove, but maintained in its guard. - return first.equals(second) && - equalsWithPosition(((While) first).getGuard(), ((While) second).getGuard()); + // Compute second statement + StatementBlock block = null; + while (!blocks.isEmpty() && (block == null || block.getChildCount() < 2)) { + block = blocks.removeFirst(); } - else { - return false; + if (block != null && block.getChildCount() >= 2) { + return new Pair(methodFrameCount, block.getChildAt(1)); + } else { + return new Pair(methodFrameCount, null); } - } - else { - // Compare all source elements including ints position info - return first.equals(second) && - ObjectUtil.equals(first.getPositionInfo(), second.getPositionInfo()); - } - } - else { - return first == null && second == null; - } - } - - /** - * Checks if the given {@link ProgramElement} contains the given {@link SourceElement}. - * @param toSearchIn The {@link ProgramElement} to search in. - * @param toSearch The {@link SourceElement} to search. - * @param services The {@link Services} to use. - * @return {@code true} contained, {@code false} not contained. - */ - public static boolean containsStatement(ProgramElement toSearchIn, SourceElement toSearch, Services services) { - if (toSearchIn != null) { - ContainsStatementVisitor visitor = new ContainsStatementVisitor(toSearchIn, toSearch, services); - visitor.start(); - return visitor.isContained(); - } - else { - return false; - } - } - - /** - * Creates recursive a term which can be used to determine the value - * of {@link #getProgramVariable()}. - * @param services The {@link Services} to use. - * @return The created term. - */ - public static Term createSelectTerm(IExecutionVariable variable) { - final Services services = variable.getServices(); - if (SymbolicExecutionUtil.isStaticVariable(variable.getProgramVariable())) { - // Static field access - Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)variable.getProgramVariable(), services); - return services.getTermBuilder().staticDot(variable.getProgramVariable().sort(), function); - } - else { - if (variable.getParentValue() == null) { - // Direct access to a variable, so return it as term - return services.getTermBuilder().var((ProgramVariable)variable.getProgramVariable()); - } - else { - Term parentTerm = variable.getParentValue().getVariable().createSelectTerm(); - if (variable.getProgramVariable() != null) { - if (services.getJavaInfo().getArrayLength() == variable.getProgramVariable()) { - // Special handling for length attribute of arrays - Function function = services.getTypeConverter().getHeapLDT().getLength(); - return services.getTermBuilder().func(function, parentTerm); - } - else { - // Field access on the parent variable - Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV((LocationVariable)variable.getProgramVariable(), services); - return services.getTermBuilder().dot(variable.getProgramVariable().sort(), parentTerm, function); - } + } else { + return null; + } + } + + /** + * Compares the given {@link SourceElement}s including their {@link PositionInfo}s. + * + * @param first The first {@link SourceElement}. + * @param second The second {@link SourceElement}. + * @return {@code true} both are equal and at the same {@link PositionInfo}, {@code false} + * otherwise. + */ + public static boolean equalsWithPosition(SourceElement first, SourceElement second) { + if (first != null && second != null) { + if (first instanceof While) { + if (second instanceof While) { + // Special treatment for while because its position info is lost during prove, + // but maintained in its guard. + return first.equals(second) && equalsWithPosition(((While) first).getGuard(), + ((While) second).getGuard()); + } else { + return false; + } + } else { + // Compare all source elements including ints position info + return first.equals(second) + && ObjectUtil.equals(first.getPositionInfo(), second.getPositionInfo()); } - else { - // Special handling for array indices. - return services.getTermBuilder().dotArr(parentTerm, variable.getArrayIndex()); + } else { + return first == null && second == null; + } + } + + /** + * Checks if the given {@link ProgramElement} contains the given {@link SourceElement}. + * + * @param toSearchIn The {@link ProgramElement} to search in. + * @param toSearch The {@link SourceElement} to search. + * @param services The {@link Services} to use. + * @return {@code true} contained, {@code false} not contained. + */ + public static boolean containsStatement(ProgramElement toSearchIn, SourceElement toSearch, + Services services) { + if (toSearchIn != null) { + ContainsStatementVisitor visitor = + new ContainsStatementVisitor(toSearchIn, toSearch, services); + visitor.start(); + return visitor.isContained(); + } else { + return false; + } + } + + /** + * Creates recursive a term which can be used to determine the value of + * {@link #getProgramVariable()}. + * + * @param services The {@link Services} to use. + * @return The created term. + */ + public static Term createSelectTerm(IExecutionVariable variable) { + final Services services = variable.getServices(); + if (SymbolicExecutionUtil.isStaticVariable(variable.getProgramVariable())) { + // Static field access + Function function = services.getTypeConverter().getHeapLDT().getFieldSymbolForPV( + (LocationVariable) variable.getProgramVariable(), services); + return services.getTermBuilder().staticDot(variable.getProgramVariable().sort(), + function); + } else { + if (variable.getParentValue() == null) { + // Direct access to a variable, so return it as term + return services.getTermBuilder() + .var((ProgramVariable) variable.getProgramVariable()); + } else { + Term parentTerm = variable.getParentValue().getVariable().createSelectTerm(); + if (variable.getProgramVariable() != null) { + if (services.getJavaInfo().getArrayLength() == variable.getProgramVariable()) { + // Special handling for length attribute of arrays + Function function = services.getTypeConverter().getHeapLDT().getLength(); + return services.getTermBuilder().func(function, parentTerm); + } else { + // Field access on the parent variable + Function function = + services.getTypeConverter().getHeapLDT().getFieldSymbolForPV( + (LocationVariable) variable.getProgramVariable(), services); + return services.getTermBuilder().dot(variable.getProgramVariable().sort(), + parentTerm, function); + } + } else { + // Special handling for array indices. + return services.getTermBuilder().dotArr(parentTerm, variable.getArrayIndex()); + } } - } - } - } - - /** - * Creates the {@link NotationInfo} for the given {@link IExecutionElement}. - * @param element The {@link IExecutionElement} to create its {@link NotationInfo}. - * @return The created {@link NotationInfo}. - */ - public static NotationInfo createNotationInfo(IExecutionElement element) { - Proof proof = element != null ? element.getProof() : null; - return createNotationInfo(proof); - } - - /** - * Creates the {@link NotationInfo} for the given {@link Node}. - * @param node The {@link Node} to create its {@link NotationInfo}. - * @return The created {@link NotationInfo}. - */ - public static NotationInfo createNotationInfo(Node node) { - Proof proof = node != null ? node.proof() : null; - return createNotationInfo(proof); - } - - /** - * Creates the {@link NotationInfo} for the given {@link Proof}. - * @param proof The {@link Proof} to create its {@link NotationInfo}. - * @return The created {@link NotationInfo}. - */ - public static NotationInfo createNotationInfo(Proof proof) { - NotationInfo notationInfo = new NotationInfo(); - if (proof != null && !proof.isDisposed()) { - notationInfo.setAbbrevMap(proof.abbreviations()); - } - return notationInfo; - } - - /** - * Checks if this branch would be closed without the uninterpreted predicate - * and thus be treated as valid/closed in a regular proof. - * @return {@code true} verified/closed, {@code false} not verified/still open - */ - public static boolean lazyComputeIsMainBranchVerified(Node node) { - if (!node.proof().isDisposed()) { - // Find uninterpreted predicate - Term predicate = AbstractOperationPO.getUninterpretedPredicate(node.proof()); - // Check if node can be treated as verified/closed - if (predicate != null) { - boolean verified = true; - Iterator leafsIter = node.leavesIterator(); - while (verified && leafsIter.hasNext()) { - Node leaf = leafsIter.next(); - if (!leaf.isClosed()) { - final Term toSearch = predicate; - SequentFormula topLevelPredicate = CollectionUtil.search(leaf.sequent().succedent(), new IFilter() { - @Override - public boolean select(SequentFormula element) { - return toSearch.op() == element.formula().op(); - } - }); - if (topLevelPredicate == null) { - verified = false; - } - } + } + } + + /** + * Creates the {@link NotationInfo} for the given {@link IExecutionElement}. + * + * @param element The {@link IExecutionElement} to create its {@link NotationInfo}. + * @return The created {@link NotationInfo}. + */ + public static NotationInfo createNotationInfo(IExecutionElement element) { + Proof proof = element != null ? element.getProof() : null; + return createNotationInfo(proof); + } + + /** + * Creates the {@link NotationInfo} for the given {@link Node}. + * + * @param node The {@link Node} to create its {@link NotationInfo}. + * @return The created {@link NotationInfo}. + */ + public static NotationInfo createNotationInfo(Node node) { + Proof proof = node != null ? node.proof() : null; + return createNotationInfo(proof); + } + + /** + * Creates the {@link NotationInfo} for the given {@link Proof}. + * + * @param proof The {@link Proof} to create its {@link NotationInfo}. + * @return The created {@link NotationInfo}. + */ + public static NotationInfo createNotationInfo(Proof proof) { + NotationInfo notationInfo = new NotationInfo(); + if (proof != null && !proof.isDisposed()) { + notationInfo.setAbbrevMap(proof.abbreviations()); + } + return notationInfo; + } + + /** + * Checks if this branch would be closed without the uninterpreted predicate and thus be treated + * as valid/closed in a regular proof. + * + * @return {@code true} verified/closed, {@code false} not verified/still open + */ + public static boolean lazyComputeIsMainBranchVerified(Node node) { + if (!node.proof().isDisposed()) { + // Find uninterpreted predicate + Term predicate = AbstractOperationPO.getUninterpretedPredicate(node.proof()); + // Check if node can be treated as verified/closed + if (predicate != null) { + boolean verified = true; + Iterator leafsIter = node.leavesIterator(); + while (verified && leafsIter.hasNext()) { + Node leaf = leafsIter.next(); + if (!leaf.isClosed()) { + final Term toSearch = predicate; + SequentFormula topLevelPredicate = CollectionUtil + .search(leaf.sequent().succedent(), new IFilter() { + @Override + public boolean select(SequentFormula element) { + return toSearch.op() == element.formula().op(); + } + }); + if (topLevelPredicate == null) { + verified = false; + } + } + } + return verified; + } else { + return node.isClosed(); } - return verified; - } - else { - return node.isClosed(); - } - } - else { - return false; - } - } - - /** - * Checks if this branch would be closed without the uninterpreted predicate - * and thus be treated as valid/closed in a regular proof. - * @return {@code true} verified/closed, {@code false} not verified/still open - */ - public static boolean lazyComputeIsAdditionalBranchVerified(Node node) { - if (!node.proof().isDisposed()) { - // Find uninterpreted predicate - Set additinalPredicates = AbstractOperationPO.getAdditionalUninterpretedPredicates(node.proof()); - // Check if node can be treated as verified/closed - if (!CollectionUtil.isEmpty(additinalPredicates)) { - boolean verified = true; - Iterator leafsIter = node.leavesIterator(); - while (verified && leafsIter.hasNext()) { - Node leaf = leafsIter.next(); - if (!leaf.isClosed()) { - final Set additinalOperatos = new HashSet(); - for (Term term : additinalPredicates) { - additinalOperatos.add(term.op()); - } - SequentFormula topLevelPredicate = CollectionUtil.search(leaf.sequent().succedent(), new IFilter() { - @Override - public boolean select(SequentFormula element) { - return additinalOperatos.contains(element.formula().op()); - } - }); - if (topLevelPredicate == null) { - verified = false; - } - } + } else { + return false; + } + } + + /** + * Checks if this branch would be closed without the uninterpreted predicate and thus be treated + * as valid/closed in a regular proof. + * + * @return {@code true} verified/closed, {@code false} not verified/still open + */ + public static boolean lazyComputeIsAdditionalBranchVerified(Node node) { + if (!node.proof().isDisposed()) { + // Find uninterpreted predicate + Set additinalPredicates = + AbstractOperationPO.getAdditionalUninterpretedPredicates(node.proof()); + // Check if node can be treated as verified/closed + if (!CollectionUtil.isEmpty(additinalPredicates)) { + boolean verified = true; + Iterator leafsIter = node.leavesIterator(); + while (verified && leafsIter.hasNext()) { + Node leaf = leafsIter.next(); + if (!leaf.isClosed()) { + final Set additinalOperatos = new HashSet(); + for (Term term : additinalPredicates) { + additinalOperatos.add(term.op()); + } + SequentFormula topLevelPredicate = CollectionUtil + .search(leaf.sequent().succedent(), new IFilter() { + @Override + public boolean select(SequentFormula element) { + return additinalOperatos.contains(element.formula().op()); + } + }); + if (topLevelPredicate == null) { + verified = false; + } + } + } + return verified; + } else { + return node.isClosed(); } - return verified; - } - else { - return node.isClosed(); - } - } - else { - return false; - } - } - - /** - * Checks if is an exceptional termination. - * @param node the node which is used for computation. - * @param exceptionVariable the exception variable which is used to check if the executed program in proof terminates normally. - * @return {@code true} exceptional termination, {@code false} normal termination. - */ - public static boolean lazyComputeIsExceptionalTermination(Node node, IProgramVariable exceptionVariable) { - Sort result = lazyComputeExceptionSort(node, exceptionVariable); - return result != null && !(result instanceof NullSort); - } - - /** - * Computes the exception {@link Sort} lazily when {@link #getExceptionSort()} - * is called the first time. - * @param node the node which is user for computation. - * @param exceptionVariable the exception variable which is used to check if the executed program in proof terminates normally. - * @return The exception {@link Sort}. - */ - public static Sort lazyComputeExceptionSort(Node node, IProgramVariable exceptionVariable) { - Sort result = null; - if (exceptionVariable != null) { - // Search final value of the exceptional variable which is used to check if the verified program terminates normally - ImmutableArray value = null; - for (SequentFormula f : node.sequent().succedent()) { - Pair,Term> updates = TermBuilder.goBelowUpdates2(f.formula()); - Iterator iter = updates.first.iterator(); - while (value == null && iter.hasNext()) { - value = extractValueFromUpdate(iter.next(), exceptionVariable); + } else { + return false; + } + } + + /** + * Checks if is an exceptional termination. + * + * @param node the node which is used for computation. + * @param exceptionVariable the exception variable which is used to check if the executed + * program in proof terminates normally. + * @return {@code true} exceptional termination, {@code false} normal termination. + */ + public static boolean lazyComputeIsExceptionalTermination(Node node, + IProgramVariable exceptionVariable) { + Sort result = lazyComputeExceptionSort(node, exceptionVariable); + return result != null && !(result instanceof NullSort); + } + + /** + * Computes the exception {@link Sort} lazily when {@link #getExceptionSort()} is called the + * first time. + * + * @param node the node which is user for computation. + * @param exceptionVariable the exception variable which is used to check if the executed + * program in proof terminates normally. + * @return The exception {@link Sort}. + */ + public static Sort lazyComputeExceptionSort(Node node, IProgramVariable exceptionVariable) { + Sort result = null; + if (exceptionVariable != null) { + // Search final value of the exceptional variable which is used to check if the verified + // program terminates normally + ImmutableArray value = null; + for (SequentFormula f : node.sequent().succedent()) { + Pair, Term> updates = TermBuilder.goBelowUpdates2(f.formula()); + Iterator iter = updates.first.iterator(); + while (value == null && iter.hasNext()) { + value = extractValueFromUpdate(iter.next(), exceptionVariable); + } } - } - // An exceptional termination is found if the exceptional variable is not null - if (value != null && value.size() == 1) { - result = value.get(0).sort(); - } - } - return result; - } - - /** - * Utility method to extract the value of the {@link IProgramVariable} - * from the given update term. - * @param term The given update term. - * @param variable The {@link IProgramVariable} for that the value is needed. - * @return The found value or {@code null} if it is not defined in the given update term. - */ - protected static ImmutableArray extractValueFromUpdate(Term term, IProgramVariable variable) { - ImmutableArray result = null; - if (term.op() instanceof ElementaryUpdate) { - ElementaryUpdate update = (ElementaryUpdate) term.op(); - if (ObjectUtil.equals(variable, update.lhs())) { - result = term.subs(); - } - } else if (term.op() instanceof UpdateJunctor) { - Iterator iter = term.subs().iterator(); - while (result == null && iter.hasNext()) { - result = extractValueFromUpdate(iter.next(), variable); - } - } - return result; - } - - /** - * Initializes the {@link Proof} of the given {@link SymbolicExecutionTreeBuilder} - * so that the correct {@link Strategy} is used. - * @param builder The {@link SymbolicExecutionTreeBuilder} to initialize. - */ - public static void initializeStrategy(SymbolicExecutionTreeBuilder builder) { - Proof proof = builder.getProof(); - StrategyProperties strategyProperties = proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - if (builder.isUninterpretedPredicateUsed()) { - proof.setActiveStrategy(new SymbolicExecutionStrategy.Factory().create(proof, strategyProperties)); - } - else { - proof.setActiveStrategy(new JavaCardDLStrategyFactory().create(proof, strategyProperties)); - } - } - - /** - * Checks if the modality at the applied rule represents the validity branch of an applied block contract. - * @param appliedRuleApp The {@link RuleApp} to check. - * @return {@code true} validitiy branch, {@code false} otherwise. - */ - public static boolean isBlockContractValidityBranch(RuleApp appliedRuleApp) { - return appliedRuleApp != null && isBlockContractValidityBranch(appliedRuleApp.posInOccurrence()); - } - - /** - * Checks if the modality at the given {@link PosInOccurrence} represents the validity branch of an applied block contract. - * @param pio The {@link PosInOccurrence} to check. - * @return validitiy branch, {@code false} otherwise. - */ - public static boolean isBlockContractValidityBranch(PosInOccurrence pio) { - if (pio != null) { - Term applicationTerm = TermBuilder.goBelowUpdates(pio.subTerm()); - return applicationTerm.getLabel(BlockContractValidityTermLabel.NAME) != null; - } - else { - return false; - } - } - - /** - * Checks if the {@link MergeRuleBuiltInRuleApp} is applied. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} is {@link MergeRuleBuiltInRuleApp}, {@code false} otherwise. - */ - public static boolean isJoin(RuleApp ruleApp) { - return ruleApp instanceof MergeRuleBuiltInRuleApp && - !((MergeRuleBuiltInRuleApp) ruleApp).getMergePartners().isEmpty(); - } - - /** - * Checks if the {@link CloseAfterMergeRuleBuiltInRuleApp} is applied. - * @param ruleApp The {@link RuleApp} to check. - * @return {@code true} is {@link CloseAfterMergeRuleBuiltInRuleApp}, {@code false} otherwise. - */ - public static boolean isCloseAfterJoin(RuleApp ruleApp) { - return ruleApp instanceof CloseAfterMergeRuleBuiltInRuleApp; - } - - /** - * Checks if the weakening goal is enabled or not. - * @param proof The {@link Proof} to check. - * @return {@code true} enabled, {@code false} disabled. - */ - public static boolean isWeakeningGoalEnabled(Proof proof) { - if (proof != null && !proof.isDisposed()) { - String value = proof.getSettings().getChoiceSettings().getDefaultChoices().get(CloseAfterMerge.MERGE_GENERATE_IS_WEAKENING_GOAL_CFG); - return CloseAfterMerge.MERGE_GENERATE_IS_WEAKENING_GOAL_CFG_ON.equals(value); - } - else { - return false; - } - } + // An exceptional termination is found if the exceptional variable is not null + if (value != null && value.size() == 1) { + result = value.get(0).sort(); + } + } + return result; + } + + /** + * Utility method to extract the value of the {@link IProgramVariable} from the given update + * term. + * + * @param term The given update term. + * @param variable The {@link IProgramVariable} for that the value is needed. + * @return The found value or {@code null} if it is not defined in the given update term. + */ + protected static ImmutableArray extractValueFromUpdate(Term term, + IProgramVariable variable) { + ImmutableArray result = null; + if (term.op() instanceof ElementaryUpdate) { + ElementaryUpdate update = (ElementaryUpdate) term.op(); + if (ObjectUtil.equals(variable, update.lhs())) { + result = term.subs(); + } + } else if (term.op() instanceof UpdateJunctor) { + Iterator iter = term.subs().iterator(); + while (result == null && iter.hasNext()) { + result = extractValueFromUpdate(iter.next(), variable); + } + } + return result; + } + + /** + * Initializes the {@link Proof} of the given {@link SymbolicExecutionTreeBuilder} so that the + * correct {@link Strategy} is used. + * + * @param builder The {@link SymbolicExecutionTreeBuilder} to initialize. + */ + public static void initializeStrategy(SymbolicExecutionTreeBuilder builder) { + Proof proof = builder.getProof(); + StrategyProperties strategyProperties = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + if (builder.isUninterpretedPredicateUsed()) { + proof.setActiveStrategy( + new SymbolicExecutionStrategy.Factory().create(proof, strategyProperties)); + } else { + proof.setActiveStrategy( + new JavaCardDLStrategyFactory().create(proof, strategyProperties)); + } + } + + /** + * Checks if the modality at the applied rule represents the validity branch of an applied block + * contract. + * + * @param appliedRuleApp The {@link RuleApp} to check. + * @return {@code true} validitiy branch, {@code false} otherwise. + */ + public static boolean isBlockContractValidityBranch(RuleApp appliedRuleApp) { + return appliedRuleApp != null + && isBlockContractValidityBranch(appliedRuleApp.posInOccurrence()); + } + + /** + * Checks if the modality at the given {@link PosInOccurrence} represents the validity branch of + * an applied block contract. + * + * @param pio The {@link PosInOccurrence} to check. + * @return validitiy branch, {@code false} otherwise. + */ + public static boolean isBlockContractValidityBranch(PosInOccurrence pio) { + if (pio != null) { + Term applicationTerm = TermBuilder.goBelowUpdates(pio.subTerm()); + return applicationTerm.getLabel(BlockContractValidityTermLabel.NAME) != null; + } else { + return false; + } + } + + /** + * Checks if the {@link MergeRuleBuiltInRuleApp} is applied. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} is {@link MergeRuleBuiltInRuleApp}, {@code false} otherwise. + */ + public static boolean isJoin(RuleApp ruleApp) { + return ruleApp instanceof MergeRuleBuiltInRuleApp + && !((MergeRuleBuiltInRuleApp) ruleApp).getMergePartners().isEmpty(); + } + + /** + * Checks if the {@link CloseAfterMergeRuleBuiltInRuleApp} is applied. + * + * @param ruleApp The {@link RuleApp} to check. + * @return {@code true} is {@link CloseAfterMergeRuleBuiltInRuleApp}, {@code false} otherwise. + */ + public static boolean isCloseAfterJoin(RuleApp ruleApp) { + return ruleApp instanceof CloseAfterMergeRuleBuiltInRuleApp; + } + + /** + * Checks if the weakening goal is enabled or not. + * + * @param proof The {@link Proof} to check. + * @return {@code true} enabled, {@code false} disabled. + */ + public static boolean isWeakeningGoalEnabled(Proof proof) { + if (proof != null && !proof.isDisposed()) { + String value = proof.getSettings().getChoiceSettings().getDefaultChoices() + .get(CloseAfterMerge.MERGE_GENERATE_IS_WEAKENING_GOAL_CFG); + return CloseAfterMerge.MERGE_GENERATE_IS_WEAKENING_GOAL_CFG_ON.equals(value); + } else { + return false; + } + } } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/ISideProofStoreListener.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/ISideProofStoreListener.java index 88ea04c205d..1dc0986c414 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/ISideProofStoreListener.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/ISideProofStoreListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util.event; import java.util.EventListener; @@ -7,18 +10,21 @@ /** * Observes changes on a {@link SideProofStore}. + * * @author Martin Hentschel */ public interface ISideProofStoreListener extends EventListener { - /** - * When new {@link Entry}s are added. - * @param e The {@link SideProofStoreEvent}. - */ - public void entriesAdded(SideProofStoreEvent e); - - /** - * When existing {@link Entry}s were removed. - * @param e The {@link SideProofStoreEvent}. - */ - public void entriesRemoved(SideProofStoreEvent e); + /** + * When new {@link Entry}s are added. + * + * @param e The {@link SideProofStoreEvent}. + */ + public void entriesAdded(SideProofStoreEvent e); + + /** + * When existing {@link Entry}s were removed. + * + * @param e The {@link SideProofStoreEvent}. + */ + public void entriesRemoved(SideProofStoreEvent e); } diff --git a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/SideProofStoreEvent.java b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/SideProofStoreEvent.java index e1b59487e0d..41bf114760d 100644 --- a/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/SideProofStoreEvent.java +++ b/key/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/event/SideProofStoreEvent.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.util.event; import java.util.EventObject; @@ -7,42 +10,45 @@ /** * An event thrown by a {@link SideProofStore} and observed via an {@link ISideProofStoreListener}. + * * @author Martin Hentschel */ public class SideProofStoreEvent extends EventObject { - /** - * Generated UID. - */ - private static final long serialVersionUID = 8046460017292232070L; + /** + * Generated UID. + */ + private static final long serialVersionUID = 8046460017292232070L; - /** - * The added or removed {@link Entry}s. - */ - private final Entry[] entries; - - /** - * Constructor. - * @param source The source. - * @param proof The added or removed {@link Entry}s. - */ - public SideProofStoreEvent(SideProofStore source, Entry[] entries) { - super(source); - this.entries = entries; - } + /** + * The added or removed {@link Entry}s. + */ + private final Entry[] entries; - /** - * Returns the added or removed {@link Entry}s. - * @return The added or removed {@link Entry}s. - */ - public Entry[] getEntries() { - return entries; - } + /** + * Constructor. + * + * @param source The source. + * @param proof The added or removed {@link Entry}s. + */ + public SideProofStoreEvent(SideProofStore source, Entry[] entries) { + super(source); + this.entries = entries; + } - /** - * {@inheritDoc} - */ - @Override - public SideProofStore getSource() { - return (SideProofStore)super.getSource(); - } + /** + * Returns the added or removed {@link Entry}s. + * + * @return The added or removed {@link Entry}s. + */ + public Entry[] getEntries() { + return entries; + } + + /** + * {@inheritDoc} + */ + @Override + public SideProofStore getSource() { + return (SideProofStore) super.getSource(); + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/AbstractSymbolicExecutionTestCase.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/AbstractSymbolicExecutionTestCase.java index 548eea47538..a22e1cbba77 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/AbstractSymbolicExecutionTestCase.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/AbstractSymbolicExecutionTestCase.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import java.io.File; @@ -76,2039 +79,2312 @@ import static org.junit.jupiter.api.Assertions.*; /** - * Provides the basic functionality of TestCases which tests - * the symbolic execution features. + * Provides the basic functionality of TestCases which tests the symbolic execution features. + * * @author Martin Hentschel */ public abstract class AbstractSymbolicExecutionTestCase { - /** - *

    - * If this constant is {@code true} a temporary directory is created with - * new oracle files. The developer has then to copy the new required files - * into the plug-in so that they are used during next test execution. - *

    - *

    - * Attention: It is strongly required that new test scenarios - * are verified with the SED application. If everything is fine a new test - * method can be added to this class and the first test execution can be - * used to generate the required oracle file. Existing oracle files should - * only be replaced if the functionality of the Symbolic Execution Debugger - * has changed so that they are outdated. - *

    - */ - public static final boolean CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY = false; - - /** - * If the fast mode is enabled the step wise creation of models is disabled. - */ - public static final boolean FAST_MODE = true; - - /** - * Number of executed SET nodes to execute all in one. - */ - public static final int ALL_IN_ONE_RUN = ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN; - - /** - * Number of executed SET nodes for only one SET node per auto mode run. - */ - public static final int SINGLE_SET_NODE_RUN = ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP; - - /** - * Default stop conditions of executed SET nodes. - */ - public static final int[] DEFAULT_MAXIMAL_SET_NODES_PER_RUN; - - /** - * The used temporary oracle directory. - */ - protected static final File tempNewOracleDirectory; - - /** - * The directory which contains the KeY repository. - */ - public static final File testCaseDirectory = FindResources.getTestCasesDirectory(); - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSymbolicExecutionTestCase.class); - - static { - assertNotNull(testCaseDirectory, "Could not find test case directory"); - } - - /** - * Creates the temporary oracle directory if required. - */ - static { - // Define fast mode - if (FAST_MODE) { - DEFAULT_MAXIMAL_SET_NODES_PER_RUN = new int[] {ALL_IN_ONE_RUN}; - } - else { - DEFAULT_MAXIMAL_SET_NODES_PER_RUN = new int[] {ALL_IN_ONE_RUN, SINGLE_SET_NODE_RUN}; - } - // Create temporary director for oracle files if required. - File directory = null; - try { - if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - directory = File.createTempFile("SYMBOLIC_EXECUTION", "ORACLE_DIRECTORY"); - directory.delete(); - directory.mkdirs(); - } - } - catch (IOException e) { - } - tempNewOracleDirectory = directory; - } - - /** - * Creates a new oracle file. - * @param node The node to save as oracle file. - * @param oraclePathInBaseDirFile The path in example directory. - * @param saveConstraints Save constraints? - * @param saveVariables Save variables? - * @param saveCallStack Save call stack? - * @param saveReturnValues Save method return values? - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - */ - protected static void createOracleFile(IExecutionNode node, - String oraclePathInBaseDirFile, - boolean saveConstraints, - boolean saveVariables, - boolean saveCallStack, - boolean saveReturnValues) throws IOException, ProofInputException { - if (tempNewOracleDirectory != null && tempNewOracleDirectory.isDirectory()) { - // Create sub folder structure - File oracleFile = new File(tempNewOracleDirectory, oraclePathInBaseDirFile); - oracleFile.getParentFile().mkdirs(); - // Create oracle file - ExecutionNodeWriter writer = new ExecutionNodeWriter(); - writer.write(node, ExecutionNodeWriter.DEFAULT_ENCODING, oracleFile, saveVariables, saveCallStack, saveReturnValues, saveConstraints); - // Print message to the user. - printOracleDirectory(); - } - } - - /** - * Prints {@link #tempNewOracleDirectory} to the user via {@link System#out}. - */ - protected static void printOracleDirectory() { - if (tempNewOracleDirectory != null) { - final String HEADER_LINE = "Oracle Directory is:"; - final String PREFIX = "### "; - final String SUFFIX = " ###"; - String path = tempNewOracleDirectory.toString(); - int length = Math.max(path.length(), HEADER_LINE.length()); - String borderLines = StringUtil.repeat("#", PREFIX.length() + length + SUFFIX.length()); - LOGGER.info(borderLines); - LOGGER.info(PREFIX + HEADER_LINE + StringUtil.repeat(" ", length - HEADER_LINE.length()) + SUFFIX); - LOGGER.info(PREFIX + path + StringUtil.repeat(" ", length - path.length()) + SUFFIX); - LOGGER.info(borderLines); - } - } - - /** - * Makes sure that the given nodes and their subtrees contains the same content. - * @param expected The expected {@link IExecutionNode}. - * @param current The current {@link IExecutionNode}. - * @param compareVariables Compare variables? - * @param compareCallStack Compare call stack? - * @param compareChildOrder Is the order of children relevant? - * @param compareReturnValues Compare return values? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - public static void assertExecutionNodes(IExecutionNode expected, - IExecutionNode current, - boolean compareVariables, - boolean compareCallStack, - boolean compareChildOrder, - boolean compareReturnValues, - boolean compareConstraints) throws ProofInputException { - if (compareChildOrder) { - // Order of children must be the same. - ExecutionNodePreorderIterator expectedIter = new ExecutionNodePreorderIterator(expected); - ExecutionNodePreorderIterator currentIter = new ExecutionNodePreorderIterator(current); - while (expectedIter.hasNext() && currentIter.hasNext()) { - IExecutionNode expectedNext = expectedIter.next(); - IExecutionNode currentNext = currentIter.next(); - assertExecutionNode(expectedNext, currentNext, true, compareVariables, compareCallStack, compareReturnValues, compareConstraints); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else { - // Order of children is not relevant. - ExecutionNodePreorderIterator expectedIter = new ExecutionNodePreorderIterator(expected); - Set> currentVisitedNodes = new LinkedHashSet>(); - while (expectedIter.hasNext()) { - IExecutionNode expectedNext = expectedIter.next(); - IExecutionNode currentNext = searchExecutionNode(current, expectedNext); - if (!currentVisitedNodes.add(currentNext)) { - fail("Node " + currentNext + " visited twice."); + /** + *

    + * If this constant is {@code true} a temporary directory is created with new oracle files. The + * developer has then to copy the new required files into the plug-in so that they are used + * during next test execution. + *

    + *

    + * Attention: It is strongly required that new test scenarios are verified with the SED + * application. If everything is fine a new test method can be added to this class and the first + * test execution can be used to generate the required oracle file. Existing oracle files should + * only be replaced if the functionality of the Symbolic Execution Debugger has changed so that + * they are outdated. + *

    + */ + public static final boolean CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY = false; + + /** + * If the fast mode is enabled the step wise creation of models is disabled. + */ + public static final boolean FAST_MODE = true; + + /** + * Number of executed SET nodes to execute all in one. + */ + public static final int ALL_IN_ONE_RUN = + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN; + + /** + * Number of executed SET nodes for only one SET node per auto mode run. + */ + public static final int SINGLE_SET_NODE_RUN = + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP; + + /** + * Default stop conditions of executed SET nodes. + */ + public static final int[] DEFAULT_MAXIMAL_SET_NODES_PER_RUN; + + /** + * The used temporary oracle directory. + */ + protected static final File tempNewOracleDirectory; + + /** + * The directory which contains the KeY repository. + */ + public static final File testCaseDirectory = FindResources.getTestCasesDirectory(); + private static final Logger LOGGER = + LoggerFactory.getLogger(AbstractSymbolicExecutionTestCase.class); + + static { + assertNotNull(testCaseDirectory, "Could not find test case directory"); + } + + /** + * Creates the temporary oracle directory if required. + */ + static { + // Define fast mode + if (FAST_MODE) { + DEFAULT_MAXIMAL_SET_NODES_PER_RUN = new int[] { ALL_IN_ONE_RUN }; + } else { + DEFAULT_MAXIMAL_SET_NODES_PER_RUN = new int[] { ALL_IN_ONE_RUN, SINGLE_SET_NODE_RUN }; + } + // Create temporary director for oracle files if required. + File directory = null; + try { + if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + directory = File.createTempFile("SYMBOLIC_EXECUTION", "ORACLE_DIRECTORY"); + directory.delete(); + directory.mkdirs(); } - assertExecutionNode(expectedNext, currentNext, true, compareVariables, compareCallStack, compareReturnValues, compareConstraints); - } - // Make sure that each current node was visited - ExecutionNodePreorderIterator currentIter = new ExecutionNodePreorderIterator(current); - while (currentIter.hasNext()) { - IExecutionNode currentNext = currentIter.next(); - if (!currentVisitedNodes.remove(currentNext)) { - fail("Node " + currentNext + " is not in expected model."); + } catch (IOException e) { + } + tempNewOracleDirectory = directory; + } + + /** + * Creates a new oracle file. + * + * @param node The node to save as oracle file. + * @param oraclePathInBaseDirFile The path in example directory. + * @param saveConstraints Save constraints? + * @param saveVariables Save variables? + * @param saveCallStack Save call stack? + * @param saveReturnValues Save method return values? + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + */ + protected static void createOracleFile(IExecutionNode node, String oraclePathInBaseDirFile, + boolean saveConstraints, boolean saveVariables, boolean saveCallStack, + boolean saveReturnValues) throws IOException, ProofInputException { + if (tempNewOracleDirectory != null && tempNewOracleDirectory.isDirectory()) { + // Create sub folder structure + File oracleFile = new File(tempNewOracleDirectory, oraclePathInBaseDirFile); + oracleFile.getParentFile().mkdirs(); + // Create oracle file + ExecutionNodeWriter writer = new ExecutionNodeWriter(); + writer.write(node, ExecutionNodeWriter.DEFAULT_ENCODING, oracleFile, saveVariables, + saveCallStack, saveReturnValues, saveConstraints); + // Print message to the user. + printOracleDirectory(); + } + } + + /** + * Prints {@link #tempNewOracleDirectory} to the user via {@link System#out}. + */ + protected static void printOracleDirectory() { + if (tempNewOracleDirectory != null) { + final String HEADER_LINE = "Oracle Directory is:"; + final String PREFIX = "### "; + final String SUFFIX = " ###"; + String path = tempNewOracleDirectory.toString(); + int length = Math.max(path.length(), HEADER_LINE.length()); + String borderLines = StringUtil.repeat("#", PREFIX.length() + length + SUFFIX.length()); + LOGGER.info(borderLines); + LOGGER.info(PREFIX + HEADER_LINE + StringUtil.repeat(" ", length - HEADER_LINE.length()) + + SUFFIX); + LOGGER.info(PREFIX + path + StringUtil.repeat(" ", length - path.length()) + SUFFIX); + LOGGER.info(borderLines); + } + } + + /** + * Makes sure that the given nodes and their subtrees contains the same content. + * + * @param expected The expected {@link IExecutionNode}. + * @param current The current {@link IExecutionNode}. + * @param compareVariables Compare variables? + * @param compareCallStack Compare call stack? + * @param compareChildOrder Is the order of children relevant? + * @param compareReturnValues Compare return values? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + public static void assertExecutionNodes(IExecutionNode expected, IExecutionNode current, + boolean compareVariables, boolean compareCallStack, boolean compareChildOrder, + boolean compareReturnValues, boolean compareConstraints) throws ProofInputException { + if (compareChildOrder) { + // Order of children must be the same. + ExecutionNodePreorderIterator expectedIter = + new ExecutionNodePreorderIterator(expected); + ExecutionNodePreorderIterator currentIter = new ExecutionNodePreorderIterator(current); + while (expectedIter.hasNext() && currentIter.hasNext()) { + IExecutionNode expectedNext = expectedIter.next(); + IExecutionNode currentNext = currentIter.next(); + assertExecutionNode(expectedNext, currentNext, true, compareVariables, + compareCallStack, compareReturnValues, compareConstraints); } - } - assertTrue(currentVisitedNodes.isEmpty()); - } - } - - /** - * Searches the direct or indirect child in subtree of the node to search in. - * @param toSearchIn The node to search in. - * @param childToSearch The node to search. - * @return The found node. - * @throws ProofInputException Occurred Exception. - */ - protected static IExecutionNode searchExecutionNode(IExecutionNode toSearchIn, IExecutionNode childToSearch) throws ProofInputException { - // Make sure that parameters are valid - assertNotNull(toSearchIn); - assertNotNull(childToSearch); - // Collect parents - Deque> parents = new LinkedList>(); - IExecutionNode parent = childToSearch; - while (parent != null) { - parents.addFirst(parent); - parent = parent.getParent(); - } - // Search children in parent order - boolean afterFirst = false; - for (IExecutionNode currentParent : parents) { - if (afterFirst) { - toSearchIn = searchDirectChildNode(toSearchIn, currentParent); - } - else { - afterFirst = true; - } - } - assertNotNull(toSearchIn, "Direct or indirect Child " + childToSearch + " is not contained in " + toSearchIn + "."); - return toSearchIn; - } - - /** - * Searches the direct child. Nodes are equal if the name and the element type is equal. - * @param parentToSearchIn The parent to search in its children. - * @param directChildToSearch The child to search. - * @return The found child. - * @throws ProofInputException Occurred Exception. - */ - protected static IExecutionNode searchDirectChildNode(IExecutionNode parentToSearchIn, IExecutionNode directChildToSearch) throws ProofInputException { - // Make sure that parameters are valid - assertNotNull(parentToSearchIn); - assertNotNull(directChildToSearch); - // Search child - IExecutionNode result = null; - int i = 0; - IExecutionNode[] children = parentToSearchIn.getChildren(); - while (result == null && i < children.length) { - if (children[i] instanceof IExecutionBranchCondition && directChildToSearch instanceof IExecutionBranchCondition) { - if (StringUtil.equalIgnoreWhiteSpace(children[i].getName(), directChildToSearch.getName()) && - StringUtil.equalIgnoreWhiteSpace(((IExecutionBranchCondition)children[i]).getAdditionalBranchLabel(), ((IExecutionBranchCondition)directChildToSearch).getAdditionalBranchLabel()) && - children[i].getElementType().equals(directChildToSearch.getElementType())) { - result = children[i]; - } - } - else{ - if (StringUtil.equalIgnoreWhiteSpace(children[i].getName(), directChildToSearch.getName()) && - children[i].getElementType().equals(directChildToSearch.getElementType())) { - result = children[i]; - } - } - i++; - } - assertNotNull(result, "Child " + directChildToSearch + " is not contained in " + parentToSearchIn + "."); - return result; - } - - /** - * Makes sure that the given nodes contains the same content. - * Children are not compared. - * @param expected The expected {@link IExecutionNode}. - * @param current The current {@link IExecutionNode}. - * @param compareParent Compare also the parent node? - * @param compareVariables Compare variables? - * @param compareCallStack Compare call stack? - * @param compareReturnValues Compare return values? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertExecutionNode(IExecutionNode expected, - IExecutionNode current, - boolean compareParent, - boolean compareVariables, - boolean compareCallStack, - boolean compareReturnValues, - boolean compareConstraints) throws ProofInputException { - // Compare nodes - assertNotNull(expected); - assertNotNull(current); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), - "Expected \"" + expected.getName() + "\" but is \"" + current.getName() + "\"."); - assertEquals(expected.isPathConditionChanged(), current.isPathConditionChanged()); - if (!StringUtil.equalIgnoreWhiteSpace(expected.getFormatedPathCondition(), current.getFormatedPathCondition())) { - assertEquals(expected.getFormatedPathCondition(), current.getFormatedPathCondition()); - } - if (compareParent) { - if (expected instanceof IExecutionBlockStartNode) { - assertTrue(current instanceof IExecutionBlockStartNode); - assertEquals(((IExecutionBlockStartNode)expected).isBlockOpened(), ((IExecutionBlockStartNode)current).isBlockOpened()); - assertBlockCompletions((IExecutionBlockStartNode)expected, (IExecutionBlockStartNode)current); - } - assertCompletedBlocks(expected, current); - assertOutgoingLinks(expected, current); - assertIncomingLinks(expected, current); - } - if (expected instanceof IExecutionBaseMethodReturn) { - assertTrue(current instanceof IExecutionBaseMethodReturn); - assertCallStateVariables((IExecutionBaseMethodReturn) expected, (IExecutionBaseMethodReturn) current, compareVariables, compareConstraints); - } - if (expected instanceof IExecutionBranchCondition) { - assertTrue(current instanceof IExecutionBranchCondition, "Expected IExecutionBranchCondition but is " + current.getClass() + "."); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionBranchCondition)expected).getFormatedBranchCondition(), ((IExecutionBranchCondition)current).getFormatedBranchCondition()), "Expected \"" + ((IExecutionBranchCondition)expected).getFormatedBranchCondition() + "\" but is \"" + ((IExecutionBranchCondition)current).getFormatedBranchCondition() + "\"."); - assertEquals(((IExecutionBranchCondition)expected).isMergedBranchCondition(), ((IExecutionBranchCondition)current).isMergedBranchCondition()); - assertEquals(((IExecutionBranchCondition)expected).isBranchConditionComputed(), ((IExecutionBranchCondition)current).isBranchConditionComputed()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionBranchCondition)expected).getAdditionalBranchLabel(), ((IExecutionBranchCondition)current).getAdditionalBranchLabel()), "Expected \"" + ((IExecutionBranchCondition)expected).getAdditionalBranchLabel() + "\" but is \"" + ((IExecutionBranchCondition)current).getAdditionalBranchLabel() + "\"."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionStart) { - assertTrue(current instanceof IExecutionStart, "Expected IExecutionStartNode but is " + (current != null ? current.getClass() : null) + "."); - assertTerminations((IExecutionStart)expected, (IExecutionStart)current); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionTermination) { - assertTrue(current instanceof IExecutionTermination, "Expected IExecutionTermination but is " + (current != null ? current.getClass() : null) + "."); - assertEquals(((IExecutionTermination)expected).getTerminationKind(), ((IExecutionTermination)current).getTerminationKind()); - assertEquals(((IExecutionTermination)expected).isBranchVerified(), ((IExecutionTermination)current).isBranchVerified()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionBranchStatement) { - assertTrue(current instanceof IExecutionBranchStatement, "Expected IExecutionBranchStatement but is " + (current != null ? current.getClass() : null) + "."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionLoopCondition) { - assertTrue(current instanceof IExecutionLoopCondition, "Expected IExecutionLoopCondition but is " + (current != null ? current.getClass() : null) + "."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionLoopStatement) { - assertTrue(current instanceof IExecutionLoopStatement, "Expected IExecutionLoopStatement but is " + (current != null ? current.getClass() : null) + "."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionMethodCall) { - assertTrue(current instanceof IExecutionMethodCall, "Expected IExecutionMethodCall but is " + (current != null ? current.getClass() : null) + "."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - assertMethodReturns((IExecutionMethodCall)expected, (IExecutionMethodCall)current); - } - else if (expected instanceof IExecutionMethodReturn) { - assertTrue(current instanceof IExecutionMethodReturn, "Expected IExecutionMethodReturn but is " + (current != null ? current.getClass() : null) + "."); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionMethodReturn)expected).getSignature(), ((IExecutionMethodReturn)current).getSignature()), ((IExecutionMethodReturn)expected).getSignature() + " does not match " + ((IExecutionMethodReturn)current).getSignature()); - if (compareReturnValues) { - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionMethodReturn)expected).getNameIncludingReturnValue(), ((IExecutionMethodReturn)current).getNameIncludingReturnValue()), ((IExecutionMethodReturn)expected).getNameIncludingReturnValue() + " does not match " + ((IExecutionMethodReturn)current).getNameIncludingReturnValue()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionMethodReturn)expected).getSignatureIncludingReturnValue(), ((IExecutionMethodReturn)current).getSignatureIncludingReturnValue()), ((IExecutionMethodReturn)expected).getSignatureIncludingReturnValue() + " does not match " + ((IExecutionMethodReturn)current).getSignatureIncludingReturnValue()); - assertEquals(((IExecutionMethodReturn)expected).isReturnValuesComputed(), ((IExecutionMethodReturn)current).isReturnValuesComputed()); - } - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionMethodReturn)expected).getFormatedMethodReturnCondition(), ((IExecutionMethodReturn)current).getFormatedMethodReturnCondition()), ((IExecutionMethodReturn)expected).getFormatedMethodReturnCondition() + " does not match " + ((IExecutionMethodReturn)current).getFormatedMethodReturnCondition()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - if (compareReturnValues) { - assertReturnValues(((IExecutionMethodReturn)expected).getReturnValues(), ((IExecutionMethodReturn)current).getReturnValues()); - } - } - else if (expected instanceof IExecutionExceptionalMethodReturn) { - assertTrue(current instanceof IExecutionExceptionalMethodReturn, "Expected IExecutionExceptionalMethodReturn but is " + (current != null ? current.getClass() : null) + "."); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionExceptionalMethodReturn)expected).getSignature(), ((IExecutionExceptionalMethodReturn)current).getSignature()), ((IExecutionExceptionalMethodReturn)expected).getSignature() + " does not match " + ((IExecutionExceptionalMethodReturn)current).getSignature()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(((IExecutionExceptionalMethodReturn)expected).getFormatedMethodReturnCondition(), ((IExecutionExceptionalMethodReturn)current).getFormatedMethodReturnCondition()), ((IExecutionExceptionalMethodReturn)expected).getFormatedMethodReturnCondition() + " does not match " + ((IExecutionExceptionalMethodReturn)current).getFormatedMethodReturnCondition()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionStatement) { - assertTrue(current instanceof IExecutionStatement, "Expected IExecutionStatement but is " + (current != null ? current.getClass() : null) + "."); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionOperationContract) { - assertTrue(current instanceof IExecutionOperationContract, "Expected IExecutionOperationContract but is " + (current != null ? current.getClass() : null) + "."); - assertEquals(((IExecutionOperationContract)expected).isPreconditionComplied(), ((IExecutionOperationContract)current).isPreconditionComplied()); - assertEquals(((IExecutionOperationContract)expected).hasNotNullCheck(), ((IExecutionOperationContract)current).hasNotNullCheck()); - assertEquals(((IExecutionOperationContract)expected).isNotNullCheckComplied(), ((IExecutionOperationContract)current).isNotNullCheckComplied()); - assertEquals(((IExecutionOperationContract)expected).getFormatedResultTerm(), ((IExecutionOperationContract)current).getFormatedResultTerm()); - assertEquals(((IExecutionOperationContract)expected).getFormatedExceptionTerm(), ((IExecutionOperationContract)current).getFormatedExceptionTerm()); - assertEquals(((IExecutionOperationContract)expected).getFormatedSelfTerm(), ((IExecutionOperationContract)current).getFormatedSelfTerm()); - assertEquals(((IExecutionOperationContract)expected).getFormatedContractParams(), ((IExecutionOperationContract)current).getFormatedContractParams()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionLoopInvariant) { - assertTrue(current instanceof IExecutionLoopInvariant, "Expected IExecutionLoopInvariant but is " + (current != null ? current.getClass() : null) + "."); - assertEquals(((IExecutionLoopInvariant)expected).isInitiallyValid(), ((IExecutionLoopInvariant)current).isInitiallyValid()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionAuxiliaryContract) { - assertTrue(current instanceof IExecutionAuxiliaryContract, "Expected IExecutionBlockContract but is " + (current != null ? current.getClass() : null) + "."); - assertEquals(((IExecutionAuxiliaryContract)expected).isPreconditionComplied(), ((IExecutionAuxiliaryContract)current).isPreconditionComplied()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else if (expected instanceof IExecutionJoin) { - assertTrue(current instanceof IExecutionJoin, "Expected IExecutionJoin but is " + (current != null ? current.getClass() : null) + "."); - assertEquals(((IExecutionJoin)expected).isWeakeningVerified(), ((IExecutionJoin)current).isWeakeningVerified()); - assertVariables(expected, current, compareVariables, compareConstraints); - assertConstraints(expected, current, compareConstraints); - } - else { - fail("Unknown execution node \"" + expected + "\"."); - } - // Optionally compare call stack - if (compareCallStack) { - IExecutionNode[] expectedStack = expected.getCallStack(); - IExecutionNode[] currentStack = current.getCallStack(); - if (expectedStack != null) { - assertNotNull(currentStack, "Call stack of \"" + current + "\" should not be null."); - assertEquals(expectedStack.length, currentStack.length, "Node: " + expected); - for (int i = 0; i < expectedStack.length; i++) { - assertExecutionNode(expectedStack[i], currentStack[i], false, false, false, false, false); + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + // Order of children is not relevant. + ExecutionNodePreorderIterator expectedIter = + new ExecutionNodePreorderIterator(expected); + Set> currentVisitedNodes = new LinkedHashSet>(); + while (expectedIter.hasNext()) { + IExecutionNode expectedNext = expectedIter.next(); + IExecutionNode currentNext = searchExecutionNode(current, expectedNext); + if (!currentVisitedNodes.add(currentNext)) { + fail("Node " + currentNext + " visited twice."); + } + assertExecutionNode(expectedNext, currentNext, true, compareVariables, + compareCallStack, compareReturnValues, compareConstraints); } - } - else{ - assertTrue(currentStack == null || currentStack.length == 0, - "Call stack of \"" + current + "\" is \"" + Arrays.toString(currentStack) + "\" but should be null or empty."); - } - } - // Optionally compare parent - if (compareParent) { - assertExecutionNode(expected, current, false, compareVariables, compareCallStack, compareReturnValues, compareConstraints); - } - } - - /** - * Compares the outgoing links. - * @param expected The expected {@link IExecutionNode}. - * @param current The current {@link IExecutionNode}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertOutgoingLinks(IExecutionNode expected, IExecutionNode current) throws ProofInputException { - ImmutableList expectedEntries = expected.getOutgoingLinks(); - ImmutableList currentEntries = current.getOutgoingLinks(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Outgoing links of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Outgoing links: " + expected); - Iterator expectedIter = expectedEntries.iterator(); - Iterator currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - IExecutionLink expectedNext = expectedIter.next(); - IExecutionLink currentNext = currentIter.next(); - assertExecutionNode(expectedNext.getSource(), currentNext.getSource(), false, false, false, false, false); - assertExecutionNode(expectedNext.getTarget(), currentNext.getTarget(), false, false, false, false, false); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), - "Outgoing links of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Compares the incoming links. - * @param expected The expected {@link IExecutionNode}. - * @param current The current {@link IExecutionNode}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertIncomingLinks(IExecutionNode expected, IExecutionNode current) throws ProofInputException { - ImmutableList expectedEntries = expected.getIncomingLinks(); - ImmutableList currentEntries = current.getIncomingLinks(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Incoming links of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Incoming links: " + expected); - Iterator expectedIter = expectedEntries.iterator(); - Iterator currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - IExecutionLink expectedNext = expectedIter.next(); - IExecutionLink currentNext = currentIter.next(); - assertExecutionNode(expectedNext.getSource(), currentNext.getSource(), false, false, false, false, false); - assertExecutionNode(expectedNext.getTarget(), currentNext.getTarget(), false, false, false, false, false); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), - "Incoming links of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Compares the completed blocks. - * @param expected The expected {@link IExecutionNode}. - * @param current The current {@link IExecutionNode}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertCompletedBlocks(IExecutionNode expected, IExecutionNode current) throws ProofInputException { - ImmutableList> expectedEntries = expected.getCompletedBlocks(); - ImmutableList> currentEntries = current.getCompletedBlocks(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Completed blocks of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); - Iterator> expectedIter = expectedEntries.iterator(); - Iterator> currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - IExecutionBlockStartNode expectedNext = expectedIter.next(); - IExecutionBlockStartNode currentNext = currentIter.next(); - assertExecutionNode(expectedNext, currentNext, false, false, false, false, false); - String expectedCondition = expected.getFormatedBlockCompletionCondition(expectedNext); - String currentCondition = current.getFormatedBlockCompletionCondition(currentNext); - if (!StringUtil.equalIgnoreWhiteSpace(expectedCondition, currentCondition)) { - assertEquals(expectedCondition, currentCondition); + // Make sure that each current node was visited + ExecutionNodePreorderIterator currentIter = new ExecutionNodePreorderIterator(current); + while (currentIter.hasNext()) { + IExecutionNode currentNext = currentIter.next(); + if (!currentVisitedNodes.remove(currentNext)) { + fail("Node " + currentNext + " is not in expected model."); + } } - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), - "Completed block entries of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Compares the block completions. - * @param expected The expected {@link IExecutionBlockStartNode}. - * @param current The current {@link IExecutionBlockStartNode}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertBlockCompletions(IExecutionBlockStartNode expected, IExecutionBlockStartNode current) throws ProofInputException { - ImmutableList> expectedEntries = expected.getBlockCompletions(); - ImmutableList> currentEntries = current.getBlockCompletions(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Block completions of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); - Iterator> expectedIter = expectedEntries.iterator(); - Iterator> currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, false, false); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), "Block completion entries of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Compares the method returns. - * @param expected The expected {@link IExecutionMethodCall}. - * @param current The current {@link IExecutionMethodCall}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertMethodReturns(IExecutionMethodCall expected, IExecutionMethodCall current) throws ProofInputException { - ImmutableList> expectedEntries = expected.getMethodReturns(); - ImmutableList> currentEntries = current.getMethodReturns(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Method return of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); - Iterator> expectedIter = expectedEntries.iterator(); - Iterator> currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, false, false); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), - "Method return entries of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Compares the terminations. - * @param expected The expected {@link IExecutionStart}. - * @param current The current {@link IExecutionStart}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertTerminations(IExecutionStart expected, IExecutionStart current) throws ProofInputException { - ImmutableList expectedEntries = expected.getTerminations(); - ImmutableList currentEntries = current.getTerminations(); - if (expectedEntries != null) { - assertNotNull(currentEntries, "Termination of \"" + current + "\" should not be null."); - assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); - Iterator expectedIter = expectedEntries.iterator(); - Iterator currentIter = currentEntries.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, false, false); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - else{ - assertTrue(currentEntries == null || currentEntries.isEmpty(), "Termination entries of \"" + current + "\" is \"" + currentEntries + "\" but should be null or empty."); - } - } - - /** - * Makes sure that the given nodes contains the same {@link IExecutionMethodReturnValue}s. - * @param expected The expected {@link IExecutionMethodReturnValue}s. - * @param current The current {@link IExecutionMethodReturnValue}s. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertReturnValues(IExecutionMethodReturnValue[] expected, IExecutionMethodReturnValue[] current) throws ProofInputException { - assertNotNull(expected); - assertNotNull(current); - assertEquals(expected.length, current.length); - for (int i = 0; i < expected.length; i++) { - assertReturnValue(expected[i], current[i]); - } - } - - /** - * Makes sure that the given {@link IExecutionMethodReturnValue}s are the same. - * @param expected The expected {@link IExecutionMethodReturnValue}. - * @param current The current {@link IExecutionMethodReturnValue}. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertReturnValue(IExecutionMethodReturnValue expected, IExecutionMethodReturnValue current) throws ProofInputException { - assertNotNull(expected); - assertNotNull(current); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), expected.getName() + " does not match " + current.getName()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getReturnValueString(), current.getReturnValueString()), expected.getReturnValueString() + " does not match " + current.getReturnValueString()); - assertEquals(expected.hasCondition(), current.hasCondition()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getConditionString(), current.getConditionString()), expected.getConditionString() + " does not match " + current.getConditionString()); - } - - /** - * Makes sure that the given nodes contains the same {@link IExecutionNode}s. - * @param expected The expected node. - * @param current The current node. - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertConstraints(IExecutionNode expected, IExecutionNode current, boolean compareConstraints) throws ProofInputException { - if (compareConstraints) { - assertNotNull(expected); - assertNotNull(current); - IExecutionConstraint[] expectedVariables = expected.getConstraints(); - IExecutionConstraint[] currentVariables = current.getConstraints(); - assertConstraints(expectedVariables, currentVariables); - } - } - - /** - * Makes sure that the given constraints are the same. - * @param expected The expected constraints. - * @param current The current constraints. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertConstraints(IExecutionConstraint[] expected, - IExecutionConstraint[] current) throws ProofInputException { - assertEquals(expected.length, current.length); - // Compare ignore order - List availableCurrentVariables = new LinkedList(); - CollectionUtil.addAll(availableCurrentVariables, current); - for (int i = 0; i < expected.length; i++) { - final IExecutionConstraint expectedVariable = expected[i]; - // Find current variable with same name - IExecutionConstraint currentVariable = CollectionUtil.searchAndRemove(availableCurrentVariables, new IFilter() { - @Override - public boolean select(IExecutionConstraint element) { - try { - return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), element.getName()); - } - catch (ProofInputException e) { - throw new RuntimeException(e); - } + assertTrue(currentVisitedNodes.isEmpty()); + } + } + + /** + * Searches the direct or indirect child in subtree of the node to search in. + * + * @param toSearchIn The node to search in. + * @param childToSearch The node to search. + * @return The found node. + * @throws ProofInputException Occurred Exception. + */ + protected static IExecutionNode searchExecutionNode(IExecutionNode toSearchIn, + IExecutionNode childToSearch) throws ProofInputException { + // Make sure that parameters are valid + assertNotNull(toSearchIn); + assertNotNull(childToSearch); + // Collect parents + Deque> parents = new LinkedList>(); + IExecutionNode parent = childToSearch; + while (parent != null) { + parents.addFirst(parent); + parent = parent.getParent(); + } + // Search children in parent order + boolean afterFirst = false; + for (IExecutionNode currentParent : parents) { + if (afterFirst) { + toSearchIn = searchDirectChildNode(toSearchIn, currentParent); + } else { + afterFirst = true; } - }); - assertNotNull(currentVariable); - // Compare variables - assertConstraint(expectedVariable, currentVariable); - } - assertTrue(availableCurrentVariables.isEmpty()); - } - - /** - * Makes sure that the given constraints are the same. - * @param expected The expected constraint. - * @param current The current constraint. - * @throws ProofInputException Occurred Exception. - */ - protected static void assertConstraint(IExecutionConstraint expected, - IExecutionConstraint current) throws ProofInputException { - if (expected != null) { - assertNotNull(current); - if (!StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName())) { + } + assertNotNull(toSearchIn, "Direct or indirect Child " + childToSearch + + " is not contained in " + toSearchIn + "."); + return toSearchIn; + } + + /** + * Searches the direct child. Nodes are equal if the name and the element type is equal. + * + * @param parentToSearchIn The parent to search in its children. + * @param directChildToSearch The child to search. + * @return The found child. + * @throws ProofInputException Occurred Exception. + */ + protected static IExecutionNode searchDirectChildNode(IExecutionNode parentToSearchIn, + IExecutionNode directChildToSearch) throws ProofInputException { + // Make sure that parameters are valid + assertNotNull(parentToSearchIn); + assertNotNull(directChildToSearch); + // Search child + IExecutionNode result = null; + int i = 0; + IExecutionNode[] children = parentToSearchIn.getChildren(); + while (result == null && i < children.length) { + if (children[i] instanceof IExecutionBranchCondition + && directChildToSearch instanceof IExecutionBranchCondition) { + if (StringUtil.equalIgnoreWhiteSpace(children[i].getName(), + directChildToSearch.getName()) + && StringUtil.equalIgnoreWhiteSpace( + ((IExecutionBranchCondition) children[i]) + .getAdditionalBranchLabel(), + ((IExecutionBranchCondition) directChildToSearch) + .getAdditionalBranchLabel()) + && children[i].getElementType() + .equals(directChildToSearch.getElementType())) { + result = children[i]; + } + } else { + if (StringUtil.equalIgnoreWhiteSpace(children[i].getName(), + directChildToSearch.getName()) + && children[i].getElementType() + .equals(directChildToSearch.getElementType())) { + result = children[i]; + } + } + i++; + } + assertNotNull(result, + "Child " + directChildToSearch + " is not contained in " + parentToSearchIn + "."); + return result; + } + + /** + * Makes sure that the given nodes contains the same content. Children are not compared. + * + * @param expected The expected {@link IExecutionNode}. + * @param current The current {@link IExecutionNode}. + * @param compareParent Compare also the parent node? + * @param compareVariables Compare variables? + * @param compareCallStack Compare call stack? + * @param compareReturnValues Compare return values? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertExecutionNode(IExecutionNode expected, IExecutionNode current, + boolean compareParent, boolean compareVariables, boolean compareCallStack, + boolean compareReturnValues, boolean compareConstraints) throws ProofInputException { + // Compare nodes + assertNotNull(expected); + assertNotNull(current); + assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), + "Expected \"" + expected.getName() + "\" but is \"" + current.getName() + "\"."); + assertEquals(expected.isPathConditionChanged(), current.isPathConditionChanged()); + if (!StringUtil.equalIgnoreWhiteSpace(expected.getFormatedPathCondition(), + current.getFormatedPathCondition())) { + assertEquals(expected.getFormatedPathCondition(), current.getFormatedPathCondition()); + } + if (compareParent) { + if (expected instanceof IExecutionBlockStartNode) { + assertTrue(current instanceof IExecutionBlockStartNode); + assertEquals(((IExecutionBlockStartNode) expected).isBlockOpened(), + ((IExecutionBlockStartNode) current).isBlockOpened()); + assertBlockCompletions((IExecutionBlockStartNode) expected, + (IExecutionBlockStartNode) current); + } + assertCompletedBlocks(expected, current); + assertOutgoingLinks(expected, current); + assertIncomingLinks(expected, current); + } + if (expected instanceof IExecutionBaseMethodReturn) { + assertTrue(current instanceof IExecutionBaseMethodReturn); + assertCallStateVariables((IExecutionBaseMethodReturn) expected, + (IExecutionBaseMethodReturn) current, compareVariables, compareConstraints); + } + if (expected instanceof IExecutionBranchCondition) { + assertTrue(current instanceof IExecutionBranchCondition, + "Expected IExecutionBranchCondition but is " + current.getClass() + "."); + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionBranchCondition) expected).getFormatedBranchCondition(), + ((IExecutionBranchCondition) current).getFormatedBranchCondition()), + "Expected \"" + + ((IExecutionBranchCondition) expected).getFormatedBranchCondition() + + "\" but is \"" + + ((IExecutionBranchCondition) current).getFormatedBranchCondition() + + "\"."); + assertEquals(((IExecutionBranchCondition) expected).isMergedBranchCondition(), + ((IExecutionBranchCondition) current).isMergedBranchCondition()); + assertEquals(((IExecutionBranchCondition) expected).isBranchConditionComputed(), + ((IExecutionBranchCondition) current).isBranchConditionComputed()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionBranchCondition) expected).getAdditionalBranchLabel(), + ((IExecutionBranchCondition) current).getAdditionalBranchLabel()), + "Expected \"" + + ((IExecutionBranchCondition) expected).getAdditionalBranchLabel() + + "\" but is \"" + + ((IExecutionBranchCondition) current).getAdditionalBranchLabel() + + "\"."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionStart) { + assertTrue(current instanceof IExecutionStart, "Expected IExecutionStartNode but is " + + (current != null ? current.getClass() : null) + "."); + assertTerminations((IExecutionStart) expected, (IExecutionStart) current); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionTermination) { + assertTrue(current instanceof IExecutionTermination, + "Expected IExecutionTermination but is " + + (current != null ? current.getClass() : null) + "."); + assertEquals(((IExecutionTermination) expected).getTerminationKind(), + ((IExecutionTermination) current).getTerminationKind()); + assertEquals(((IExecutionTermination) expected).isBranchVerified(), + ((IExecutionTermination) current).isBranchVerified()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionBranchStatement) { + assertTrue(current instanceof IExecutionBranchStatement, + "Expected IExecutionBranchStatement but is " + + (current != null ? current.getClass() : null) + "."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionLoopCondition) { + assertTrue(current instanceof IExecutionLoopCondition, + "Expected IExecutionLoopCondition but is " + + (current != null ? current.getClass() : null) + "."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionLoopStatement) { + assertTrue(current instanceof IExecutionLoopStatement, + "Expected IExecutionLoopStatement but is " + + (current != null ? current.getClass() : null) + "."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionMethodCall) { + assertTrue(current instanceof IExecutionMethodCall, + "Expected IExecutionMethodCall but is " + + (current != null ? current.getClass() : null) + "."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + assertMethodReturns((IExecutionMethodCall) expected, (IExecutionMethodCall) current); + } else if (expected instanceof IExecutionMethodReturn) { + assertTrue(current instanceof IExecutionMethodReturn, + "Expected IExecutionMethodReturn but is " + + (current != null ? current.getClass() : null) + "."); + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionMethodReturn) expected).getSignature(), + ((IExecutionMethodReturn) current).getSignature()), + ((IExecutionMethodReturn) expected).getSignature() + " does not match " + + ((IExecutionMethodReturn) current).getSignature()); + if (compareReturnValues) { + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionMethodReturn) expected).getNameIncludingReturnValue(), + ((IExecutionMethodReturn) current).getNameIncludingReturnValue()), + ((IExecutionMethodReturn) expected).getNameIncludingReturnValue() + + " does not match " + + ((IExecutionMethodReturn) current).getNameIncludingReturnValue()); + assertTrue(StringUtil.equalIgnoreWhiteSpace( + ((IExecutionMethodReturn) expected).getSignatureIncludingReturnValue(), + ((IExecutionMethodReturn) current).getSignatureIncludingReturnValue()), + ((IExecutionMethodReturn) expected).getSignatureIncludingReturnValue() + + " does not match " + ((IExecutionMethodReturn) current) + .getSignatureIncludingReturnValue()); + assertEquals(((IExecutionMethodReturn) expected).isReturnValuesComputed(), + ((IExecutionMethodReturn) current).isReturnValuesComputed()); + } + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionMethodReturn) expected).getFormatedMethodReturnCondition(), + ((IExecutionMethodReturn) current).getFormatedMethodReturnCondition()), + ((IExecutionMethodReturn) expected).getFormatedMethodReturnCondition() + + " does not match " + ((IExecutionMethodReturn) current) + .getFormatedMethodReturnCondition()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + if (compareReturnValues) { + assertReturnValues(((IExecutionMethodReturn) expected).getReturnValues(), + ((IExecutionMethodReturn) current).getReturnValues()); + } + } else if (expected instanceof IExecutionExceptionalMethodReturn) { + assertTrue(current instanceof IExecutionExceptionalMethodReturn, + "Expected IExecutionExceptionalMethodReturn but is " + + (current != null ? current.getClass() : null) + "."); + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionExceptionalMethodReturn) expected).getSignature(), + ((IExecutionExceptionalMethodReturn) current).getSignature()), + ((IExecutionExceptionalMethodReturn) expected).getSignature() + + " does not match " + + ((IExecutionExceptionalMethodReturn) current).getSignature()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace( + ((IExecutionExceptionalMethodReturn) expected) + .getFormatedMethodReturnCondition(), + ((IExecutionExceptionalMethodReturn) current) + .getFormatedMethodReturnCondition()), + ((IExecutionExceptionalMethodReturn) expected) + .getFormatedMethodReturnCondition() + " does not match " + + ((IExecutionExceptionalMethodReturn) current) + .getFormatedMethodReturnCondition()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionStatement) { + assertTrue(current instanceof IExecutionStatement, + "Expected IExecutionStatement but is " + + (current != null ? current.getClass() : null) + "."); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionOperationContract) { + assertTrue(current instanceof IExecutionOperationContract, + "Expected IExecutionOperationContract but is " + + (current != null ? current.getClass() : null) + "."); + assertEquals(((IExecutionOperationContract) expected).isPreconditionComplied(), + ((IExecutionOperationContract) current).isPreconditionComplied()); + assertEquals(((IExecutionOperationContract) expected).hasNotNullCheck(), + ((IExecutionOperationContract) current).hasNotNullCheck()); + assertEquals(((IExecutionOperationContract) expected).isNotNullCheckComplied(), + ((IExecutionOperationContract) current).isNotNullCheckComplied()); + assertEquals(((IExecutionOperationContract) expected).getFormatedResultTerm(), + ((IExecutionOperationContract) current).getFormatedResultTerm()); + assertEquals(((IExecutionOperationContract) expected).getFormatedExceptionTerm(), + ((IExecutionOperationContract) current).getFormatedExceptionTerm()); + assertEquals(((IExecutionOperationContract) expected).getFormatedSelfTerm(), + ((IExecutionOperationContract) current).getFormatedSelfTerm()); + assertEquals(((IExecutionOperationContract) expected).getFormatedContractParams(), + ((IExecutionOperationContract) current).getFormatedContractParams()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionLoopInvariant) { + assertTrue(current instanceof IExecutionLoopInvariant, + "Expected IExecutionLoopInvariant but is " + + (current != null ? current.getClass() : null) + "."); + assertEquals(((IExecutionLoopInvariant) expected).isInitiallyValid(), + ((IExecutionLoopInvariant) current).isInitiallyValid()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionAuxiliaryContract) { + assertTrue(current instanceof IExecutionAuxiliaryContract, + "Expected IExecutionBlockContract but is " + + (current != null ? current.getClass() : null) + "."); + assertEquals(((IExecutionAuxiliaryContract) expected).isPreconditionComplied(), + ((IExecutionAuxiliaryContract) current).isPreconditionComplied()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else if (expected instanceof IExecutionJoin) { + assertTrue(current instanceof IExecutionJoin, "Expected IExecutionJoin but is " + + (current != null ? current.getClass() : null) + "."); + assertEquals(((IExecutionJoin) expected).isWeakeningVerified(), + ((IExecutionJoin) current).isWeakeningVerified()); + assertVariables(expected, current, compareVariables, compareConstraints); + assertConstraints(expected, current, compareConstraints); + } else { + fail("Unknown execution node \"" + expected + "\"."); + } + // Optionally compare call stack + if (compareCallStack) { + IExecutionNode[] expectedStack = expected.getCallStack(); + IExecutionNode[] currentStack = current.getCallStack(); + if (expectedStack != null) { + assertNotNull(currentStack, + "Call stack of \"" + current + "\" should not be null."); + assertEquals(expectedStack.length, currentStack.length, "Node: " + expected); + for (int i = 0; i < expectedStack.length; i++) { + assertExecutionNode(expectedStack[i], currentStack[i], false, false, false, + false, false); + } + } else { + assertTrue(currentStack == null || currentStack.length == 0, + "Call stack of \"" + current + "\" is \"" + Arrays.toString(currentStack) + + "\" but should be null or empty."); + } + } + // Optionally compare parent + if (compareParent) { + assertExecutionNode(expected, current, false, compareVariables, compareCallStack, + compareReturnValues, compareConstraints); + } + } + + /** + * Compares the outgoing links. + * + * @param expected The expected {@link IExecutionNode}. + * @param current The current {@link IExecutionNode}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertOutgoingLinks(IExecutionNode expected, IExecutionNode current) + throws ProofInputException { + ImmutableList expectedEntries = expected.getOutgoingLinks(); + ImmutableList currentEntries = current.getOutgoingLinks(); + if (expectedEntries != null) { + assertNotNull(currentEntries, + "Outgoing links of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), + "Outgoing links: " + expected); + Iterator expectedIter = expectedEntries.iterator(); + Iterator currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + IExecutionLink expectedNext = expectedIter.next(); + IExecutionLink currentNext = currentIter.next(); + assertExecutionNode(expectedNext.getSource(), currentNext.getSource(), false, false, + false, false, false); + assertExecutionNode(expectedNext.getTarget(), currentNext.getTarget(), false, false, + false, false, false); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), "Outgoing links of \"" + + current + "\" is \"" + currentEntries + "\" but should be null or empty."); + } + } + + /** + * Compares the incoming links. + * + * @param expected The expected {@link IExecutionNode}. + * @param current The current {@link IExecutionNode}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertIncomingLinks(IExecutionNode expected, IExecutionNode current) + throws ProofInputException { + ImmutableList expectedEntries = expected.getIncomingLinks(); + ImmutableList currentEntries = current.getIncomingLinks(); + if (expectedEntries != null) { + assertNotNull(currentEntries, + "Incoming links of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), + "Incoming links: " + expected); + Iterator expectedIter = expectedEntries.iterator(); + Iterator currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + IExecutionLink expectedNext = expectedIter.next(); + IExecutionLink currentNext = currentIter.next(); + assertExecutionNode(expectedNext.getSource(), currentNext.getSource(), false, false, + false, false, false); + assertExecutionNode(expectedNext.getTarget(), currentNext.getTarget(), false, false, + false, false, false); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), "Incoming links of \"" + + current + "\" is \"" + currentEntries + "\" but should be null or empty."); + } + } + + /** + * Compares the completed blocks. + * + * @param expected The expected {@link IExecutionNode}. + * @param current The current {@link IExecutionNode}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertCompletedBlocks(IExecutionNode expected, + IExecutionNode current) throws ProofInputException { + ImmutableList> expectedEntries = expected.getCompletedBlocks(); + ImmutableList> currentEntries = current.getCompletedBlocks(); + if (expectedEntries != null) { + assertNotNull(currentEntries, + "Completed blocks of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); + Iterator> expectedIter = expectedEntries.iterator(); + Iterator> currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + IExecutionBlockStartNode expectedNext = expectedIter.next(); + IExecutionBlockStartNode currentNext = currentIter.next(); + assertExecutionNode(expectedNext, currentNext, false, false, false, false, false); + String expectedCondition = + expected.getFormatedBlockCompletionCondition(expectedNext); + String currentCondition = current.getFormatedBlockCompletionCondition(currentNext); + if (!StringUtil.equalIgnoreWhiteSpace(expectedCondition, currentCondition)) { + assertEquals(expectedCondition, currentCondition); + } + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), + "Completed block entries of \"" + current + "\" is \"" + currentEntries + + "\" but should be null or empty."); + } + } + + /** + * Compares the block completions. + * + * @param expected The expected {@link IExecutionBlockStartNode}. + * @param current The current {@link IExecutionBlockStartNode}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertBlockCompletions(IExecutionBlockStartNode expected, + IExecutionBlockStartNode current) throws ProofInputException { + ImmutableList> expectedEntries = expected.getBlockCompletions(); + ImmutableList> currentEntries = current.getBlockCompletions(); + if (expectedEntries != null) { + assertNotNull(currentEntries, + "Block completions of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); + Iterator> expectedIter = expectedEntries.iterator(); + Iterator> currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, + false, false); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), + "Block completion entries of \"" + current + "\" is \"" + currentEntries + + "\" but should be null or empty."); + } + } + + /** + * Compares the method returns. + * + * @param expected The expected {@link IExecutionMethodCall}. + * @param current The current {@link IExecutionMethodCall}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertMethodReturns(IExecutionMethodCall expected, + IExecutionMethodCall current) throws ProofInputException { + ImmutableList> expectedEntries = expected.getMethodReturns(); + ImmutableList> currentEntries = current.getMethodReturns(); + if (expectedEntries != null) { + assertNotNull(currentEntries, + "Method return of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); + Iterator> expectedIter = expectedEntries.iterator(); + Iterator> currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, + false, false); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), + "Method return entries of \"" + current + "\" is \"" + currentEntries + + "\" but should be null or empty."); + } + } + + /** + * Compares the terminations. + * + * @param expected The expected {@link IExecutionStart}. + * @param current The current {@link IExecutionStart}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertTerminations(IExecutionStart expected, IExecutionStart current) + throws ProofInputException { + ImmutableList expectedEntries = expected.getTerminations(); + ImmutableList currentEntries = current.getTerminations(); + if (expectedEntries != null) { + assertNotNull(currentEntries, "Termination of \"" + current + "\" should not be null."); + assertEquals(expectedEntries.size(), currentEntries.size(), "Node: " + expected); + Iterator expectedIter = expectedEntries.iterator(); + Iterator currentIter = currentEntries.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertExecutionNode(expectedIter.next(), currentIter.next(), false, false, false, + false, false); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } else { + assertTrue(currentEntries == null || currentEntries.isEmpty(), + "Termination entries of \"" + current + "\" is \"" + currentEntries + + "\" but should be null or empty."); + } + } + + /** + * Makes sure that the given nodes contains the same {@link IExecutionMethodReturnValue}s. + * + * @param expected The expected {@link IExecutionMethodReturnValue}s. + * @param current The current {@link IExecutionMethodReturnValue}s. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertReturnValues(IExecutionMethodReturnValue[] expected, + IExecutionMethodReturnValue[] current) throws ProofInputException { + assertNotNull(expected); + assertNotNull(current); + assertEquals(expected.length, current.length); + for (int i = 0; i < expected.length; i++) { + assertReturnValue(expected[i], current[i]); + } + } + + /** + * Makes sure that the given {@link IExecutionMethodReturnValue}s are the same. + * + * @param expected The expected {@link IExecutionMethodReturnValue}. + * @param current The current {@link IExecutionMethodReturnValue}. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertReturnValue(IExecutionMethodReturnValue expected, + IExecutionMethodReturnValue current) throws ProofInputException { + assertNotNull(expected); + assertNotNull(current); + assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), + expected.getName() + " does not match " + current.getName()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace(expected.getReturnValueString(), + current.getReturnValueString()), + expected.getReturnValueString() + " does not match " + + current.getReturnValueString()); + assertEquals(expected.hasCondition(), current.hasCondition()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace(expected.getConditionString(), + current.getConditionString()), + expected.getConditionString() + " does not match " + current.getConditionString()); + } + + /** + * Makes sure that the given nodes contains the same {@link IExecutionNode}s. + * + * @param expected The expected node. + * @param current The current node. + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertConstraints(IExecutionNode expected, IExecutionNode current, + boolean compareConstraints) throws ProofInputException { + if (compareConstraints) { + assertNotNull(expected); + assertNotNull(current); + IExecutionConstraint[] expectedVariables = expected.getConstraints(); + IExecutionConstraint[] currentVariables = current.getConstraints(); + assertConstraints(expectedVariables, currentVariables); + } + } + + /** + * Makes sure that the given constraints are the same. + * + * @param expected The expected constraints. + * @param current The current constraints. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertConstraints(IExecutionConstraint[] expected, + IExecutionConstraint[] current) throws ProofInputException { + assertEquals(expected.length, current.length); + // Compare ignore order + List availableCurrentVariables = + new LinkedList(); + CollectionUtil.addAll(availableCurrentVariables, current); + for (int i = 0; i < expected.length; i++) { + final IExecutionConstraint expectedVariable = expected[i]; + // Find current variable with same name + IExecutionConstraint currentVariable = CollectionUtil.searchAndRemove( + availableCurrentVariables, new IFilter() { + @Override + public boolean select(IExecutionConstraint element) { + try { + return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), + element.getName()); + } catch (ProofInputException e) { + throw new RuntimeException(e); + } + } + }); + assertNotNull(currentVariable); + // Compare variables + assertConstraint(expectedVariable, currentVariable); + } + assertTrue(availableCurrentVariables.isEmpty()); + } + + /** + * Makes sure that the given constraints are the same. + * + * @param expected The expected constraint. + * @param current The current constraint. + * @throws ProofInputException Occurred Exception. + */ + protected static void assertConstraint(IExecutionConstraint expected, + IExecutionConstraint current) throws ProofInputException { + if (expected != null) { + assertNotNull(current); + if (!StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName())) { + assertEquals(expected.getName(), current.getName()); + } + } else { + assertNull(current); + } + } + + /** + * Makes sure that the given nodes contains the same {@link IExecutionVariable}s of the call + * state. + * + * @param expected The expected node. + * @param current The current node. + * @param compareVariables Compare variables? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertCallStateVariables(IExecutionBaseMethodReturn expected, + IExecutionBaseMethodReturn current, boolean compareVariables, + boolean compareConstraints) throws ProofInputException { + if (compareVariables) { + assertNotNull(expected); + assertNotNull(current); + IExecutionVariable[] expectedVariables = expected.getCallStateVariables(); + IExecutionVariable[] currentVariables = current.getCallStateVariables(); + assertVariables(expectedVariables, currentVariables, true, true, compareConstraints); + } + } + + /** + * Makes sure that the given nodes contains the same {@link IExecutionVariable}s. + * + * @param expected The expected node. + * @param current The current node. + * @param compareVariables Compare variables? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertVariables(IExecutionNode expected, IExecutionNode current, + boolean compareVariables, boolean compareConstraints) throws ProofInputException { + if (compareVariables) { + assertNotNull(expected); + assertNotNull(current); + IExecutionVariable[] expectedVariables = expected.getVariables(); + IExecutionVariable[] currentVariables = current.getVariables(); + assertVariables(expectedVariables, currentVariables, true, true, compareConstraints); + } + } + + /** + * Makes sure that the given variables are the same. + * + * @param expected The expected variables. + * @param current The current variables. + * @param compareParent Compare parent? + * @param compareChildren Compare children? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertVariables(IExecutionVariable[] expected, + IExecutionVariable[] current, boolean compareParent, boolean compareChildren, + boolean compareConstraints) throws ProofInputException { + assertEquals(expected.length, current.length); + // Compare ignore order + List availableCurrentVariables = new LinkedList(); + CollectionUtil.addAll(availableCurrentVariables, current); + for (int i = 0; i < expected.length; i++) { + final IExecutionVariable expectedVariable = expected[i]; + // Find current variable with same name + IExecutionVariable currentVariable = CollectionUtil + .searchAndRemove(availableCurrentVariables, new IFilter() { + @Override + public boolean select(IExecutionVariable element) { + try { + return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), + element.getName()); + } catch (ProofInputException e) { + throw new RuntimeException(e); + } + } + }); + assertNotNull(currentVariable); + // Compare variables + assertVariable(expectedVariable, currentVariable, compareParent, compareChildren, + compareConstraints); + } + assertTrue(availableCurrentVariables.isEmpty()); + } + + /** + * Makes sure that the given variables are the same. + * + * @param expected The expected variable. + * @param current The current variable. + * @param compareParent Compare parent? + * @param compareChildren Compare children? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertVariable(IExecutionVariable expected, IExecutionVariable current, + boolean compareParent, boolean compareChildren, boolean compareConstraints) + throws ProofInputException { + if (expected != null) { + assertNotNull(current); + // Compare variable + assertEquals(expected.isArrayIndex(), current.isArrayIndex()); + assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); assertEquals(expected.getName(), current.getName()); - } - } - else { - assertNull(current); - } - } - - /** - * Makes sure that the given nodes contains the same {@link IExecutionVariable}s of the call state. - * @param expected The expected node. - * @param current The current node. - * @param compareVariables Compare variables? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertCallStateVariables(IExecutionBaseMethodReturn expected, IExecutionBaseMethodReturn current, boolean compareVariables, boolean compareConstraints) throws ProofInputException { - if (compareVariables) { - assertNotNull(expected); - assertNotNull(current); - IExecutionVariable[] expectedVariables = expected.getCallStateVariables(); - IExecutionVariable[] currentVariables = current.getCallStateVariables(); - assertVariables(expectedVariables, currentVariables, true, true, compareConstraints); - } - } - - /** - * Makes sure that the given nodes contains the same {@link IExecutionVariable}s. - * @param expected The expected node. - * @param current The current node. - * @param compareVariables Compare variables? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertVariables(IExecutionNode expected, IExecutionNode current, boolean compareVariables, boolean compareConstraints) throws ProofInputException { - if (compareVariables) { - assertNotNull(expected); - assertNotNull(current); - IExecutionVariable[] expectedVariables = expected.getVariables(); - IExecutionVariable[] currentVariables = current.getVariables(); - assertVariables(expectedVariables, currentVariables, true, true, compareConstraints); - } - } - - /** - * Makes sure that the given variables are the same. - * @param expected The expected variables. - * @param current The current variables. - * @param compareParent Compare parent? - * @param compareChildren Compare children? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertVariables(IExecutionVariable[] expected, - IExecutionVariable[] current, - boolean compareParent, - boolean compareChildren, - boolean compareConstraints) throws ProofInputException { - assertEquals(expected.length, current.length); - // Compare ignore order - List availableCurrentVariables = new LinkedList(); - CollectionUtil.addAll(availableCurrentVariables, current); - for (int i = 0; i < expected.length; i++) { - final IExecutionVariable expectedVariable = expected[i]; - // Find current variable with same name - IExecutionVariable currentVariable = CollectionUtil.searchAndRemove(availableCurrentVariables, new IFilter() { - @Override - public boolean select(IExecutionVariable element) { - try { - return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), element.getName()); - } - catch (ProofInputException e) { - throw new RuntimeException(e); - } + // Compare parent + if (compareParent) { + assertValue(expected.getParentValue(), current.getParentValue(), false, false, + false); + } + // Compare children + if (compareChildren) { + IExecutionValue[] expectedValues = expected.getValues(); + IExecutionValue[] currentValues = current.getValues(); + assertValues(expectedValues, currentValues, true, true, compareConstraints); + } + } else { + assertNull(current); + } + } + + /** + * Makes sure that the given values are the same. + * + * @param expected The expected values. + * @param current The current values. + * @param compareParent Compare parent? + * @param compareChildren Compare children? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertValues(IExecutionValue[] expected, IExecutionValue[] current, + boolean compareParent, boolean compareChildren, boolean compareConstraints) + throws ProofInputException { + assertEquals(expected.length, current.length); + // Compare ignore order + List availableCurrentVariables = new LinkedList(); + CollectionUtil.addAll(availableCurrentVariables, current); + for (int i = 0; i < expected.length; i++) { + final IExecutionValue expectedVariable = expected[i]; + // Find current variable with same name + IExecutionValue currentVariable = CollectionUtil + .searchAndRemove(availableCurrentVariables, new IFilter() { + @Override + public boolean select(IExecutionValue element) { + try { + return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), + element.getName()) + && StringUtil.equalIgnoreWhiteSpace( + expectedVariable.getConditionString(), + element.getConditionString()); + } catch (ProofInputException e) { + throw new RuntimeException(e); + } + } + }); + assertNotNull(currentVariable); + // Compare variables + assertValue(expectedVariable, currentVariable, compareParent, compareChildren, + compareConstraints); + } + assertTrue(availableCurrentVariables.isEmpty()); + } + + /** + * Makes sure that the given values are the same. + * + * @param expected The expected variable. + * @param current The current variable. + * @param compareParent Compare parent? + * @param compareChildren Compare children? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertValue(IExecutionValue expected, IExecutionValue current, + boolean compareParent, boolean compareChildren, boolean compareConstraints) + throws ProofInputException { + if (expected != null) { + assertNotNull(current); + // Compare variable + assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), + expected.getName() + " does not match " + current.getName()); + assertEquals(expected.getTypeString(), current.getTypeString()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace(expected.getValueString(), + current.getValueString()), + expected.getValueString() + " does not match " + current.getValueString()); + assertEquals(expected.isValueAnObject(), current.isValueAnObject()); + assertEquals(expected.isValueUnknown(), current.isValueUnknown()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace(expected.getConditionString(), + current.getConditionString()), + expected.getConditionString() + " does not match " + + current.getConditionString()); + // Compare parent + if (compareParent) { + assertVariable(expected.getVariable(), current.getVariable(), false, false, + compareConstraints); + } + // Compare children + if (compareChildren) { + IExecutionVariable[] expectedChildVariables = expected.getChildVariables(); + IExecutionVariable[] currentChildVariables = current.getChildVariables(); + assertVariables(expectedChildVariables, currentChildVariables, compareParent, + compareChildren, compareConstraints); + } + // Compare constraints + if (compareConstraints) { + IExecutionConstraint[] expectedConstraints = expected.getConstraints(); + IExecutionConstraint[] currentConstraints = current.getConstraints(); + assertConstraints(expectedConstraints, currentConstraints); + } + } else { + assertNull(current); + } + } + + /** + * Executes an "step return" global on all goals on the given + * {@link SymbolicExecutionTreeBuilder}. + * + * @param ui The {@link DefaultUserInterfaceControl} to use. + * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void stepReturn(DefaultUserInterfaceControl ui, + SymbolicExecutionTreeBuilder builder, String oraclePathInBaseDirFile, int oracleIndex, + String oracleFileExtension, File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + Proof proof = builder.getProof(); + CompoundStopCondition stopCondition = new CompoundStopCondition(); + stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition( + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); + stopCondition.addChildren(new StepReturnSymbolicExecutionTreeNodesStopCondition()); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Run proof + ui.getProofControl().startAndWaitForAutoMode(proof); + // Update symbolic execution tree + builder.analyse(); + // Test result + assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, + baseDir); + } + + + + /** + * Executes an "step return" global on all goals on the given + * {@link SymbolicExecutionTreeBuilder}. + * + * @param ui The {@link DefaultUserInterfaceControl} to use. + * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void stepReturnWithBreakpoints(DefaultUserInterfaceControl ui, + SymbolicExecutionTreeBuilder builder, String oraclePathInBaseDirFile, int oracleIndex, + String oracleFileExtension, File baseDir, CompoundStopCondition lineBreakpoints) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + Proof proof = builder.getProof(); + CompoundStopCondition stopCondition = new CompoundStopCondition(); + stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition( + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); + stopCondition.addChildren(new StepReturnSymbolicExecutionTreeNodesStopCondition()); + stopCondition.addChildren(lineBreakpoints); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Run proof + ui.getProofControl().startAndWaitForAutoMode(proof); + // Update symbolic execution tree + builder.analyse(); + // Test result + assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, + baseDir); + } + + /** + * Executes an "step over" global on all goals on the given + * {@link SymbolicExecutionTreeBuilder}. + * + * @param ui The {@link DefaultUserInterfaceControl} to use. + * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void stepOver(DefaultUserInterfaceControl ui, + SymbolicExecutionTreeBuilder builder, String oraclePathInBaseDirFile, int oracleIndex, + String oracleFileExtension, File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + Proof proof = builder.getProof(); + CompoundStopCondition stopCondition = new CompoundStopCondition(); + stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition( + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); + stopCondition.addChildren(new StepOverSymbolicExecutionTreeNodesStopCondition()); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Run proof + ui.getProofControl().startAndWaitForAutoMode(proof); + // Update symbolic execution tree + builder.analyse(); + // Test result + assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, + baseDir); + } + + /** + * Executes an "step into" global on all goals on the given + * {@link SymbolicExecutionTreeBuilder}. + * + * @param ui The {@link DefaultUserInterfaceControl} to use. + * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @return The found {@link SymbolicExecutionCompletions}. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static SymbolicExecutionCompletions stepInto(DefaultUserInterfaceControl ui, + SymbolicExecutionTreeBuilder builder, String oraclePathInBaseDirFile, int oracleIndex, + String oracleFileExtension, File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + Proof proof = builder.getProof(); + ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = + new ExecutedSymbolicExecutionTreeNodesStopCondition( + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Run proof + ui.getProofControl().startAndWaitForAutoMode(proof); + // Update symbolic execution tree + SymbolicExecutionCompletions completions = builder.analyse(); + // Test result + assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, + baseDir); + return completions; + } + + /** + * Executes an "step into" global on all goals on the given + * {@link SymbolicExecutionTreeBuilder}. + * + * @param ui The {@link DefaultUserInterfaceControl} to use. + * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void resume(DefaultUserInterfaceControl ui, + SymbolicExecutionTreeBuilder builder, String oraclePathInBaseDirFile, File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + Proof proof = builder.getProof(); + ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = + new ExecutedSymbolicExecutionTreeNodesStopCondition( + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN); + proof.getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + // Run proof + ui.getProofControl().startAndWaitForAutoMode(proof); + // Update symbolic execution tree + builder.analyse(); + // Test result + assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, baseDir); + } + + /** + * Makes sure that after a step the correct set tree is created. + * + * @param builder The {@link SymbolicExecutionTreeBuilder} to test. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void assertSetTreeAfterStep(SymbolicExecutionTreeBuilder builder, + String oraclePathInBaseDirFile, File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + createOracleFile(builder.getStartNode(), oraclePathInBaseDirFile, false, false, false, + false); + } else { + // Read oracle file + File oracleFile = new File(baseDir, oraclePathInBaseDirFile); + ExecutionNodeReader reader = new ExecutionNodeReader(); + IExecutionNode oracleRoot = reader.read(oracleFile); + assertNotNull(oracleRoot); + // Make sure that the created symbolic execution tree matches the expected one. + assertExecutionNodes(oracleRoot, builder.getStartNode(), false, false, false, false, + false); + } + } + + /** + * Makes sure that after a step the correct set tree is created. + * + * @param builder The {@link SymbolicExecutionTreeBuilder} to test. + * @param oraclePathInBaseDirFile The oracle path. + * @param oracleIndex The index of the current step. + * @param oracleFileExtension The oracle file extension + * @param baseDir The base directory for oracles. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + */ + protected static void assertSetTreeAfterStep(SymbolicExecutionTreeBuilder builder, + String oraclePathInBaseDirFile, int oracleIndex, String oracleFileExtension, + File baseDir) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + assertSetTreeAfterStep(builder, + oraclePathInBaseDirFile + "_" + oracleIndex + oracleFileExtension, baseDir); + } + + /** + * Searches a {@link IProgramMethod} in the given {@link Services}. + * + * @param services The {@link Services} to search in. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @return The first found {@link IProgramMethod} in the type. + */ + public static IProgramMethod searchProgramMethod(Services services, String containerTypeName, + final String methodFullName) { + return HelperClassForTests.searchProgramMethod(services, containerTypeName, methodFullName); + } + + /** + * Creates a {@link SymbolicExecutionEnvironment} which consists of loading a file to load, + * finding the method to proof, instantiation of proof and creation with configuration of + * {@link SymbolicExecutionTreeBuilder}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param baseContractName The name of the contract. + * @param methodFullName The method name to search. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvarints Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, + * {@code false} truth value evaluation is disabled. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The created {@link SymbolicExecutionEnvironment}. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment( + File baseDir, String javaPathInBaseDir, String baseContractName, + boolean mergeBranchConditions, boolean useOperationContracts, boolean useLoopInvarints, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean truthValueEvaluationEnabled, + boolean simplifyConditions) throws ProblemLoaderException, ProofInputException { + // Make sure that required files exists + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + // Load java file + KeYEnvironment environment = KeYEnvironment.load( + SymbolicExecutionJavaProfile.getDefaultInstance(truthValueEvaluationEnabled), + javaFile, null, null, null, true); + setupTacletOptions(environment); + // Start proof + final Contract contract = environment.getServices().getSpecificationRepository() + .getContractByName(baseContractName); + assertTrue(contract instanceof FunctionalOperationContract); + ProofOblInput input = new FunctionalOperationContractPO(environment.getInitConfig(), + (FunctionalOperationContract) contract, true, true); + Proof proof = environment.createProof(input); + assertNotNull(proof); + // Set strategy and goal chooser to use for auto mode + SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, + useOperationContracts, useLoopInvarints, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + // Create symbolic execution tree which contains only the start node at beginning + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, + usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); + SymbolicExecutionUtil.initializeStrategy(builder); + builder.analyse(); + assertNotNull(builder.getStartNode()); + return new SymbolicExecutionEnvironment(environment, builder); + } + + /** + * Creates a {@link SymbolicExecutionEnvironment} which consists of loading a file to load, + * finding the method to proof, instantiation of proof and creation with configuration of + * {@link SymbolicExecutionTreeBuilder}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param precondition An optional precondition to use. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvarints Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The created {@link SymbolicExecutionEnvironment}. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment( + File baseDir, String javaPathInBaseDir, String containerTypeName, String methodFullName, + String precondition, boolean mergeBranchConditions, boolean useOperationContracts, + boolean useLoopInvarints, boolean blockTreatmentContract, + boolean nonExecutionBranchHidingSideProofs, boolean aliasChecks, boolean useUnicode, + boolean usePrettyPrinting, boolean variablesAreOnlyComputedFromUpdates, + boolean simplifyConditions) throws ProblemLoaderException, ProofInputException { + // Make sure that required files exists + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + // Load java file + KeYEnvironment environment = + KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), javaFile, + null, null, null, true); + setupTacletOptions(environment); + // Search method to proof + IProgramMethod pm = + searchProgramMethod(environment.getServices(), containerTypeName, methodFullName); + // Start proof + ProofOblInput input = new ProgramMethodPO(environment.getInitConfig(), pm.getFullName(), pm, + precondition, true, true); + Proof proof = environment.createProof(input); + assertNotNull(proof); + // Set strategy and goal chooser to use for auto mode + SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, + useOperationContracts, useLoopInvarints, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + // Create symbolic execution tree which contains only the start node at beginning + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, + usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); + SymbolicExecutionUtil.initializeStrategy(builder); + builder.analyse(); + assertNotNull(builder.getStartNode()); + return new SymbolicExecutionEnvironment(environment, builder); + } + + private static void setupTacletOptions(KeYEnvironment env) { + // Set Taclet options + ImmutableSet choices = env.getInitConfig().getActivatedChoices(); + choices = choices.add(new Choice("methodExpansion", "noRestriction")); + + ProofSettings settings = env.getInitConfig().getSettings(); + if (settings == null) { + settings = ProofSettings.DEFAULT_SETTINGS; + } + settings.getChoiceSettings().updateWith(choices); + } + + /** + * Creates a {@link SymbolicExecutionEnvironment} which consists of loading a proof file to load + * and creation with configuration of {@link SymbolicExecutionTreeBuilder}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param proofPathInBaseDir The path to the proof file inside the base directory. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvarints Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, + * {@code false} truth value evaluation is disabled. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The created {@link SymbolicExecutionEnvironment}. + * @throws ProblemLoaderException Occurred Exception. + */ + protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment( + File baseDir, String proofPathInBaseDir, boolean mergeBranchConditions, + boolean useOperationContracts, boolean useLoopInvarints, boolean blockTreatmentContract, + boolean nonExecutionBranchHidingSideProofs, boolean aliasChecks, boolean useUnicode, + boolean usePrettyPrinting, boolean variablesAreOnlyComputedFromUpdates, + boolean truthValueEvaluationEnabled, boolean simplifyConditions) + throws ProblemLoaderException { + // Make sure that required files exists + File proofFile = new File(baseDir, proofPathInBaseDir); + assertTrue(proofFile.exists()); + // Load java file + KeYEnvironment environment = + KeYEnvironment.load( + SymbolicExecutionJavaProfile.getDefaultInstance( + truthValueEvaluationEnabled), + proofFile, null, null, null, + SymbolicExecutionTreeBuilder.createPoPropertiesToForce(), null, true); + setupTacletOptions(environment); + Proof proof = environment.getLoadedProof(); + assertNotNull(proof); + // Set strategy and goal chooser to use for auto mode + SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, + useOperationContracts, useLoopInvarints, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + // Create symbolic execution tree which contains only the start node at beginning + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, + usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); + SymbolicExecutionUtil.initializeStrategy(builder); + builder.analyse(); + assertNotNull(builder.getStartNode()); + return new SymbolicExecutionEnvironment(environment, builder); + } + + /** + * Creates a {@link SymbolicExecutionEnvironment} which consists of loading a file to load, + * finding the method to proof, instantiation of proof and creation with configuration of + * {@link SymbolicExecutionTreeBuilder}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The name of the type which contains the method. + * @param methodFullName The method name to search. + * @param precondition An optional precondition to use. + * @param startPosition The start position. + * @param endPosition The end position. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvarints Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The created {@link SymbolicExecutionEnvironment}. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment( + File baseDir, String javaPathInBaseDir, String containerTypeName, String methodFullName, + String precondition, Position startPosition, Position endPosition, + boolean mergeBranchConditions, boolean useOperationContracts, boolean useLoopInvarints, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean simplifyConditions) + throws ProblemLoaderException, ProofInputException { + // Make sure that required files exists + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + // Load java file + KeYEnvironment environment = + KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), javaFile, + null, null, null, true); + setupTacletOptions(environment); + // Search method to proof + IProgramMethod pm = + searchProgramMethod(environment.getServices(), containerTypeName, methodFullName); + // Start proof + ProofOblInput input = new ProgramMethodSubsetPO(environment.getInitConfig(), methodFullName, + pm, precondition, startPosition, endPosition, true, true); + Proof proof = environment.createProof(input); + assertNotNull(proof); + // Set strategy and goal chooser to use for auto mode + SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, + ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, + useOperationContracts, useLoopInvarints, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks); + // Create symbolic execution tree which contains only the start node at beginning + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, + usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); + SymbolicExecutionUtil.initializeStrategy(builder); + builder.analyse(); + assertNotNull(builder.getStartNode()); + return new SymbolicExecutionEnvironment(environment, builder); + } + + /** + * Extracts the content of the try block from the initial {@link Sequent}. + * + * @param proof The {@link Proof} which contains the initial {@link Sequent}: + * @return The try content. + */ + protected String getTryContent(Proof proof) { + assertNotNull(proof); + Node node = proof.root(); + Sequent sequent = node.sequent(); + assertEquals(1, sequent.succedent().size()); + Term succedent = sequent.succedent().get(0).formula(); + assertEquals(2, succedent.arity()); + Term updateApplication = succedent.subs().get(1); + assertEquals(2, updateApplication.arity()); + JavaProgramElement updateContent = updateApplication.subs().get(1).javaBlock().program(); + assertTrue(updateContent instanceof StatementBlock); + ImmutableArray updateContentBody = + ((StatementBlock) updateContent).getBody(); + assertEquals(2, updateContentBody.size()); + assertTrue(updateContentBody.get(1) instanceof Try); + Try tryStatement = (Try) updateContentBody.get(1); + assertEquals(1, tryStatement.getBranchCount()); + return ProofSaver.printAnything(tryStatement.getBody(), proof.getServices()); + } + + /** + * Makes sure that the save and loading process works. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param oraclePathInBaseDirFile The oracle path. + * @param env The already executed {@link SymbolicExecutionEnvironment} which contains the proof + * to save/load. + * @throws IOException Occurred Exception + * @throws ProofInputException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected void assertSaveAndReload(File baseDir, String javaPathInBaseDir, + String oraclePathInBaseDirFile, SymbolicExecutionEnvironment env) + throws IOException, ProofInputException, ParserConfigurationException, SAXException, + ProblemLoaderException { + File javaFile = new File(baseDir, javaPathInBaseDir); + assertTrue(javaFile.exists()); + File tempFile = File.createTempFile("TestProgramMethodSubsetPO", ".proof", + javaFile.getParentFile()); + KeYEnvironment reloadedEnv = null; + SymbolicExecutionTreeBuilder reloadedBuilder = null; + try { + ProofSaver saver = new ProofSaver(env.getProof(), tempFile.getAbsolutePath(), + KeYConstants.INTERNAL_VERSION); + assertNull(saver.save()); + // Load proof from saved *.proof file + reloadedEnv = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), + tempFile, null, null, null, true); + Proof reloadedProof = reloadedEnv.getLoadedProof(); + assertNotSame(env.getProof(), reloadedProof); + // Recreate symbolic execution tree + reloadedBuilder = new SymbolicExecutionTreeBuilder(reloadedProof, false, false, false, + false, true); + SymbolicExecutionUtil.initializeStrategy(reloadedBuilder); + reloadedBuilder.analyse(); + assertSetTreeAfterStep(reloadedBuilder, oraclePathInBaseDirFile, baseDir); + } finally { + if (reloadedBuilder != null) { + reloadedBuilder.dispose(); + } + if (reloadedEnv != null) { + reloadedEnv.dispose(); + } + if (tempFile != null) { + tempFile.delete(); + assertFalse(tempFile.exists()); + } + } + } + + /** + * Executes a test with the following steps: + *
      + *
    1. Load java file
    2. + *
    3. Instantiate proof for method in container type
    4. + *
    5. Try to close proof in auto mode
    6. + *
    7. Create symbolic execution tree
    8. + *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is + * defined
    10. + *
    11. Load oracle file
    12. + *
    13. Compare created symbolic execution tree with oracle model
    14. + *
    + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The java class to test. + * @param methodFullName The method to test. + * @param precondition An optional precondition. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param maximalNumberOfExecutedSetNodesPerRun The number of executed set nodes per auto mode + * run. The whole test is executed for each defined value. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected void doSETTest(File baseDir, String javaPathInBaseDir, String containerTypeName, + String methodFullName, String precondition, String oraclePathInBaseDirFile, + boolean includeConstraints, boolean includeVariables, boolean includeCallStack, + boolean includeReturnValues, int[] maximalNumberOfExecutedSetNodesPerRun, + boolean mergeBranchConditions, boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean simplifyConditions) + throws ProofInputException, IOException, ParserConfigurationException, SAXException, + ProblemLoaderException { + assertNotNull(maximalNumberOfExecutedSetNodesPerRun); + for (int i = 0; i < maximalNumberOfExecutedSetNodesPerRun.length; i++) { + SymbolicExecutionEnvironment env = doSETTest(baseDir, + javaPathInBaseDir, containerTypeName, methodFullName, precondition, + oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, + includeReturnValues, maximalNumberOfExecutedSetNodesPerRun[i], + mergeBranchConditions, useOperationContracts, useLoopInvariants, + blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, + useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, + simplifyConditions); + env.dispose(); + } + } + + /** + * Executes + * {@link #doSETTest(File, String, String, String, String, boolean, boolean, int, boolean, boolean, boolean)} + * and disposes the created {@link SymbolicExecutionEnvironment}. + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The java class to test. + * @param methodFullName The method to test. + * @param precondition An optional precondition. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The tested {@link SymbolicExecutionEnvironment}. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected void doSETTestAndDispose(File baseDir, String javaPathInBaseDir, + String containerTypeName, String methodFullName, String precondition, + String oraclePathInBaseDirFile, boolean includeConstraints, boolean includeVariables, + boolean includeCallStack, boolean includeReturnValues, + int maximalNumberOfExecutedSetNodes, boolean mergeBranchConditions, + boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean simplifyConditions) + throws ProofInputException, IOException, ParserConfigurationException, SAXException, + ProblemLoaderException { + SymbolicExecutionEnvironment env = doSETTest(baseDir, + javaPathInBaseDir, containerTypeName, methodFullName, precondition, + oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, + includeReturnValues, maximalNumberOfExecutedSetNodes, mergeBranchConditions, + useOperationContracts, useLoopInvariants, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, + variablesAreOnlyComputedFromUpdates, simplifyConditions); + env.dispose(); + } + + /** + * Executes a test with the following steps: + *
      + *
    1. Load java file
    2. + *
    3. Instantiate proof for method in container type
    4. + *
    5. Try to close proof in auto mode
    6. + *
    7. Create symbolic execution tree
    8. + *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is + * defined
    10. + *
    11. Load oracle file
    12. + *
    13. Compare created symbolic execution tree with oracle model
    14. + *
    + * + * @param baseDir The base directory which contains test and oracle file. + * @param proofFilePathInBaseDir The path to the proof file inside the base directory. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @return The tested {@link SymbolicExecutionEnvironment}. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected void doSETTestAndDispose(File baseDir, String proofFilePathInBaseDir, + String oraclePathInBaseDirFile, boolean includeConstraints, boolean includeVariables, + boolean includeCallStack, boolean includeReturnValues, boolean mergeBranchConditions, + boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates) throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = doSETTest(baseDir, + proofFilePathInBaseDir, oraclePathInBaseDirFile, includeConstraints, + includeVariables, includeCallStack, includeReturnValues, mergeBranchConditions, + useOperationContracts, useLoopInvariants, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, + variablesAreOnlyComputedFromUpdates, false, true); + if (env != null) { + env.dispose(); + } + } + + /** + * Executes a test with the following steps: + *
      + *
    1. Load java file
    2. + *
    3. Instantiate proof for method in container type
    4. + *
    5. Try to close proof in auto mode
    6. + *
    7. Create symbolic execution tree
    8. + *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is + * defined
    10. + *
    11. Load oracle file
    12. + *
    13. Compare created symbolic execution tree with oracle model
    14. + *
    + * + * @param baseDir The base directory which contains test and oracle file. + * @param proofFilePathInBaseDir The path to the proof file inside the base directory. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, + * {@code false} truth value evaluation is disabled. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The tested {@link SymbolicExecutionEnvironment}. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected SymbolicExecutionEnvironment doSETTest(File baseDir, + String proofFilePathInBaseDir, String oraclePathInBaseDirFile, + boolean includeConstraints, boolean includeVariables, boolean includeCallStack, + boolean includeReturnValues, boolean mergeBranchConditions, + boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean truthValueEvaluationEnabled, + boolean simplifyConditions) throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + SymbolicExecutionEnvironment env = null; + try { + // Make sure that parameter are valid. + assertNotNull(proofFilePathInBaseDir); + assertNotNull(oraclePathInBaseDirFile); + File oracleFile = new File(baseDir, oraclePathInBaseDirFile); + if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + assertTrue(oracleFile.exists(), + "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); + } + // Make sure that the correct taclet options are defined. + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(baseDir, proofFilePathInBaseDir, + mergeBranchConditions, useOperationContracts, useLoopInvariants, + blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, + useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, + truthValueEvaluationEnabled, simplifyConditions); + // Create new oracle file if required in a temporary directory + createOracleFile(env.getBuilder().getStartNode(), oraclePathInBaseDirFile, + includeConstraints, includeVariables, includeCallStack, includeReturnValues); + // Read oracle file + ExecutionNodeReader reader = new ExecutionNodeReader(); + IExecutionNode oracleRoot = reader.read(oracleFile); + assertNotNull(oracleRoot); + // Make sure that the created symbolic execution tree matches the expected one. + assertExecutionNodes(oracleRoot, env.getBuilder().getStartNode(), includeVariables, + includeCallStack, false, includeReturnValues, includeConstraints); + return env; + } finally { + // Restore original options + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + } + } + + /** + * Executes a test with the following steps: + *
      + *
    1. Load java file
    2. + *
    3. Instantiate proof for method in container type
    4. + *
    5. Try to close proof in auto mode
    6. + *
    7. Create symbolic execution tree
    8. + *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is + * defined
    10. + *
    11. Load oracle file
    12. + *
    13. Compare created symbolic execution tree with oracle model
    14. + *
    + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param containerTypeName The java class to test. + * @param methodFullName The method to test. + * @param precondition An optional precondition. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The tested {@link SymbolicExecutionEnvironment}. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected SymbolicExecutionEnvironment doSETTest(File baseDir, + String javaPathInBaseDir, String containerTypeName, final String methodFullName, + String precondition, String oraclePathInBaseDirFile, boolean includeConstraints, + boolean includeVariables, boolean includeCallStack, boolean includeReturnValues, + int maximalNumberOfExecutedSetNodes, boolean mergeBranchConditions, + boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean simplifyConditions) + throws ProofInputException, IOException, ParserConfigurationException, SAXException, + ProblemLoaderException { + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Make sure that parameter are valid. + assertNotNull(javaPathInBaseDir); + assertNotNull(containerTypeName); + assertNotNull(methodFullName); + assertNotNull(oraclePathInBaseDirFile); + File oracleFile = new File(baseDir, oraclePathInBaseDirFile); + if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + assertTrue(oracleFile.exists(), + "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); + } + assertTrue(maximalNumberOfExecutedSetNodes >= 1); + // Make sure that the correct taclet options are defined. + originalTacletOptions = setDefaultTacletOptions(baseDir, javaPathInBaseDir, + containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, + containerTypeName, methodFullName, precondition, mergeBranchConditions, + useOperationContracts, useLoopInvariants, blockTreatmentContract, + nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, + usePrettyPrinting, variablesAreOnlyComputedFromUpdates, + simplifyConditions); + internalDoSETTest(oracleFile, env, oraclePathInBaseDirFile, + maximalNumberOfExecutedSetNodes, includeConstraints, includeVariables, + includeCallStack, includeReturnValues); + return env; + } finally { + // Restore original options + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + } + } + + /** + * Executes a test with the following steps: + *
      + *
    1. Load java file
    2. + *
    3. Instantiate proof for method in container type
    4. + *
    5. Try to close proof in auto mode
    6. + *
    7. Create symbolic execution tree
    8. + *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is + * defined
    10. + *
    11. Load oracle file
    12. + *
    13. Compare created symbolic execution tree with oracle model
    14. + *
    + * + * @param baseDir The base directory which contains test and oracle file. + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param baseContractName The name of the contract. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param includeConstraints Include constraints? + * @param includeVariables Include variables? + * @param includeCallStack Include call stack? + * @param includeReturnValues Include method return values? + * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. + * @param mergeBranchConditions Merge branch conditions? + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by + * side proofs, {@code false} do not hide execution branch labels. + * @param aliasChecks Do alias checks? + * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode + * characters. + * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty + * printing. + * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only + * computed from updates, {@code false} {@link IExecutionVariable}s are computed + * according to the type structure of the visible memory. + * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, + * {@code false} truth value evaluation is disabled. + * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify + * conditions. + * @return The tested {@link SymbolicExecutionEnvironment}. + * @throws ProofInputException Occurred Exception + * @throws IOException Occurred Exception + * @throws ParserConfigurationException Occurred Exception + * @throws SAXException Occurred Exception + * @throws ProblemLoaderException Occurred Exception + */ + protected SymbolicExecutionEnvironment doSETTest(File baseDir, + String javaPathInBaseDir, String baseContractName, String oraclePathInBaseDirFile, + boolean includeConstraints, boolean includeVariables, boolean includeCallStack, + boolean includeReturnValues, int maximalNumberOfExecutedSetNodes, + boolean mergeBranchConditions, boolean useOperationContracts, boolean useLoopInvariants, + boolean blockTreatmentContract, boolean nonExecutionBranchHidingSideProofs, + boolean aliasChecks, boolean useUnicode, boolean usePrettyPrinting, + boolean variablesAreOnlyComputedFromUpdates, boolean truthValueEvaluationEnabled, + boolean simplifyConditions) throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + try { + // Make sure that parameter are valid. + assertNotNull(javaPathInBaseDir); + assertNotNull(baseContractName); + assertNotNull(oraclePathInBaseDirFile); + File oracleFile = new File(baseDir, oraclePathInBaseDirFile); + if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + assertTrue(oracleFile.exists(), + "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); + } + assertTrue(maximalNumberOfExecutedSetNodes >= 1); + // Make sure that the correct taclet options are defined. + originalTacletOptions = + setDefaultTacletOptions(baseDir, javaPathInBaseDir, baseContractName); + // Create proof environment for symbolic execution + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, baseContractName, + mergeBranchConditions, useOperationContracts, useLoopInvariants, + blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, + useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, + truthValueEvaluationEnabled, simplifyConditions); + internalDoSETTest(oracleFile, env, oraclePathInBaseDirFile, + maximalNumberOfExecutedSetNodes, includeConstraints, includeVariables, + includeCallStack, includeReturnValues); + return env; + } finally { + // Restore taclet options + restoreTacletOptions(originalTacletOptions); + } + } + + /** + * Internal test method called by + * {@link #doSETTest(File, String, String, String, boolean, boolean, boolean, int, boolean, boolean, boolean, boolean, boolean)} + * and + * {@link #doSETTest(File, String, String, String, String, String, boolean, boolean, boolean, int, boolean, boolean, boolean, boolean, boolean)}. + */ + private void internalDoSETTest(File oracleFile, + SymbolicExecutionEnvironment env, + String oraclePathInBaseDirFile, int maximalNumberOfExecutedSetNodes, + boolean includeConstraints, boolean includeVariables, boolean includeCallStack, + boolean includeReturnValues) + throws IOException, ProofInputException, ParserConfigurationException, SAXException { + // Set stop condition to stop after a number of detected symbolic execution tree nodes + // instead of applied rules + ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = + new ExecutedSymbolicExecutionTreeNodesStopCondition( + maximalNumberOfExecutedSetNodes); + env.getProof().getSettings().getStrategySettings() + .setCustomApplyStrategyStopCondition(stopCondition); + int nodeCount; + // Execute auto mode until no more symbolic execution tree nodes are found or no new rules + // are applied. + do { + // Store the number of nodes before start of the auto mode + nodeCount = env.getProof().countNodes(); + // Run proof + env.getProofControl().startAndWaitForAutoMode(env.getProof()); + // Update symbolic execution tree + env.getBuilder().analyse(); + // Make sure that not to many set nodes are executed + Map executedSetNodesPerGoal = stopCondition.getExectuedSetNodesPerGoal(); + for (Integer value : executedSetNodesPerGoal.values()) { + assertNotNull(value); + assertTrue(value.intValue() <= maximalNumberOfExecutedSetNodes, value.intValue() + + " is not less equal to " + maximalNumberOfExecutedSetNodes); } - }); - assertNotNull(currentVariable); - // Compare variables - assertVariable(expectedVariable, currentVariable, compareParent, compareChildren, compareConstraints); - } - assertTrue(availableCurrentVariables.isEmpty()); - } - - /** - * Makes sure that the given variables are the same. - * @param expected The expected variable. - * @param current The current variable. - * @param compareParent Compare parent? - * @param compareChildren Compare children? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertVariable(IExecutionVariable expected, - IExecutionVariable current, - boolean compareParent, - boolean compareChildren, - boolean compareConstraints) throws ProofInputException { - if (expected != null) { - assertNotNull(current); - // Compare variable - assertEquals(expected.isArrayIndex(), current.isArrayIndex()); - assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); - assertEquals(expected.getName(), current.getName()); - // Compare parent - if (compareParent) { - assertValue(expected.getParentValue(), current.getParentValue(), false, false, false); - } - // Compare children - if (compareChildren) { - IExecutionValue[] expectedValues = expected.getValues(); - IExecutionValue[] currentValues = current.getValues(); - assertValues(expectedValues, currentValues, true, true, compareConstraints); - } - } - else { - assertNull(current); - } - } - - /** - * Makes sure that the given values are the same. - * @param expected The expected values. - * @param current The current values. - * @param compareParent Compare parent? - * @param compareChildren Compare children? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertValues(IExecutionValue[] expected, - IExecutionValue[] current, - boolean compareParent, - boolean compareChildren, - boolean compareConstraints) throws ProofInputException { - assertEquals(expected.length, current.length); - // Compare ignore order - List availableCurrentVariables = new LinkedList(); - CollectionUtil.addAll(availableCurrentVariables, current); - for (int i = 0; i < expected.length; i++) { - final IExecutionValue expectedVariable = expected[i]; - // Find current variable with same name - IExecutionValue currentVariable = CollectionUtil.searchAndRemove(availableCurrentVariables, new IFilter() { - @Override - public boolean select(IExecutionValue element) { - try { - return StringUtil.equalIgnoreWhiteSpace(expectedVariable.getName(), element.getName()) && - StringUtil.equalIgnoreWhiteSpace(expectedVariable.getConditionString(), element.getConditionString()); - } - catch (ProofInputException e) { - throw new RuntimeException(e); - } + } while (stopCondition.wasSetNodeExecuted() && nodeCount != env.getProof().countNodes()); + // Create new oracle file if required in a temporary directory + createOracleFile(env.getBuilder().getStartNode(), oraclePathInBaseDirFile, + includeConstraints, includeVariables, includeCallStack, includeReturnValues); + // Read oracle file + ExecutionNodeReader reader = new ExecutionNodeReader(); + IExecutionNode oracleRoot = reader.read(oracleFile); + assertNotNull(oracleRoot); + // Make sure that the created symbolic execution tree matches the expected one. + assertExecutionNodes(oracleRoot, env.getBuilder().getStartNode(), includeVariables, + includeCallStack, false, includeReturnValues, includeConstraints); + } + + /** + * Ensures that the default taclet options are defined. + * + * @param baseDir The base directory which contains the java file. + * @param javaPathInBaseDir The path in the base directory to the java file. + * @param baseContractName The name of the contract to prove. + * @return The original settings which are overwritten. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + public static HashMap setDefaultTacletOptions(File baseDir, + String javaPathInBaseDir, String baseContractName) + throws ProblemLoaderException, ProofInputException { + if (!SymbolicExecutionUtil.isChoiceSettingInitialised()) { + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInBaseDir, + baseContractName, false, false, false, false, false, false, false, + false, false, false, false); + env.dispose(); + } + return setDefaultTacletOptions(); + } + + /** + * Ensures that the default taclet options are defined. + * + * @param baseDir The base directory which contains the java file. + * @param javaPathInBaseDir The path in the base directory to the java file. + * @param containerTypeName The type nach which provides the method. + * @param methodFullName The method to prove. + * @return The original settings which are overwritten. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + public static HashMap setDefaultTacletOptions(File baseDir, + String javaPathInBaseDir, String containerTypeName, String methodFullName) + throws ProblemLoaderException, ProofInputException { + if (!SymbolicExecutionUtil.isChoiceSettingInitialised()) { + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, + containerTypeName, methodFullName, null, false, false, false, false, + false, false, false, false, false, false); + env.dispose(); + } + return setDefaultTacletOptions(); + } + + /** + * Ensures that the default taclet options are defined. + * + * @param javaFile The java file to load. + * @param containerTypeName The type name which provides the target. + * @param targetName The target to proof. + * @return The original settings which are overwritten. + * @throws ProblemLoaderException Occurred Exception. + * @throws ProofInputException Occurred Exception. + */ + public static HashMap setDefaultTacletOptionsForTarget(File javaFile, + String containerTypeName, final String targetName) + throws ProblemLoaderException, ProofInputException { + return HelperClassForTests.setDefaultTacletOptionsForTarget(javaFile, containerTypeName, + targetName); + } + + /** + * Ensures that the default taclet options are defined. + * + * @return The original settings which are overwritten. + */ + public static HashMap setDefaultTacletOptions() { + HashMap original = HelperClassForTests.setDefaultTacletOptions(); + ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); + ImmutableSet cs = DefaultImmutableSet.nil(); + cs = cs.add(new Choice("noRestriction", "methodExpansion")); + choiceSettings.updateWith(cs); + return original; + } + + /** + * Restores the given taclet options. + * + * @param options The taclet options to restore. + */ + public static void restoreTacletOptions(HashMap options) { + HelperClassForTests.restoreTacletOptions(options); + } + + /** + * creates a new factory that should be used by others afterwards + * + * @return + */ + protected ITermProgramVariableCollectorFactory createNewProgramVariableCollectorFactory( + final SymbolicExecutionBreakpointStopCondition breakpointParentStopCondition) { + ITermProgramVariableCollectorFactory programVariableCollectorFactory = + new ITermProgramVariableCollectorFactory() { + @Override + public TermProgramVariableCollector create(Services services) { + return new TermProgramVariableCollectorKeepUpdatesForBreakpointconditions( + services, breakpointParentStopCondition); + } + }; + return programVariableCollectorFactory; + } + + /** + * Makes sure that two {@link Term}s are equal. + * + * @param expected The expected {@link Term}. + * @param actual The actual {@link Term}. + */ + protected void assertTerm(Term expected, Term actual) { + if (expected != null) { + assertEquals(expected.op(), actual.op()); + assertEquals(expected.javaBlock(), actual.javaBlock()); + assertEquals(expected.getLabels(), actual.getLabels()); + assertEquals(expected.arity(), actual.arity()); + for (int i = 0; i < expected.arity(); i++) { + assertTerm(expected.sub(i), actual.sub(i)); } - }); - assertNotNull(currentVariable); - // Compare variables - assertValue(expectedVariable, currentVariable, compareParent, compareChildren, compareConstraints); - } - assertTrue(availableCurrentVariables.isEmpty()); - } - - /** - * Makes sure that the given values are the same. - * @param expected The expected variable. - * @param current The current variable. - * @param compareParent Compare parent? - * @param compareChildren Compare children? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertValue(IExecutionValue expected, - IExecutionValue current, - boolean compareParent, - boolean compareChildren, - boolean compareConstraints) throws ProofInputException { - if (expected != null) { - assertNotNull(current); - // Compare variable - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getName(), current.getName()), expected.getName() + " does not match " + current.getName()); - assertEquals(expected.getTypeString(), current.getTypeString()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getValueString(), current.getValueString()), expected.getValueString() + " does not match " + current.getValueString()); - assertEquals(expected.isValueAnObject(), current.isValueAnObject()); - assertEquals(expected.isValueUnknown(), current.isValueUnknown()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getConditionString(), current.getConditionString()), expected.getConditionString() + " does not match " + current.getConditionString()); - // Compare parent - if (compareParent) { - assertVariable(expected.getVariable(), current.getVariable(), false, false, compareConstraints); - } - // Compare children - if (compareChildren) { - IExecutionVariable[] expectedChildVariables = expected.getChildVariables(); - IExecutionVariable[] currentChildVariables = current.getChildVariables(); - assertVariables(expectedChildVariables, currentChildVariables, compareParent, compareChildren, compareConstraints); - } - // Compare constraints - if (compareConstraints) { - IExecutionConstraint[] expectedConstraints = expected.getConstraints(); - IExecutionConstraint[] currentConstraints = current.getConstraints(); - assertConstraints(expectedConstraints, currentConstraints); - } - } - else { - assertNull(current); - } - } - - /** - * Executes an "step return" global on all goals on the given {@link SymbolicExecutionTreeBuilder}. - * @param ui The {@link DefaultUserInterfaceControl} to use. - * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void stepReturn(DefaultUserInterfaceControl ui, - SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - int oracleIndex, - String oracleFileExtension, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - Proof proof = builder.getProof(); - CompoundStopCondition stopCondition = new CompoundStopCondition(); - stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition(ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); - stopCondition.addChildren(new StepReturnSymbolicExecutionTreeNodesStopCondition()); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Run proof - ui.getProofControl().startAndWaitForAutoMode(proof); - // Update symbolic execution tree - builder.analyse(); - // Test result - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, baseDir); - } - - - - /** - * Executes an "step return" global on all goals on the given {@link SymbolicExecutionTreeBuilder}. - * @param ui The {@link DefaultUserInterfaceControl} to use. - * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void stepReturnWithBreakpoints(DefaultUserInterfaceControl ui, - SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - int oracleIndex, - String oracleFileExtension, - File baseDir, - CompoundStopCondition lineBreakpoints) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - Proof proof = builder.getProof(); - CompoundStopCondition stopCondition = new CompoundStopCondition(); - stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition(ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); - stopCondition.addChildren(new StepReturnSymbolicExecutionTreeNodesStopCondition()); - stopCondition.addChildren(lineBreakpoints); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Run proof - ui.getProofControl().startAndWaitForAutoMode(proof); - // Update symbolic execution tree - builder.analyse(); - // Test result - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, baseDir); - } - - /** - * Executes an "step over" global on all goals on the given {@link SymbolicExecutionTreeBuilder}. - * @param ui The {@link DefaultUserInterfaceControl} to use. - * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void stepOver(DefaultUserInterfaceControl ui, - SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - int oracleIndex, - String oracleFileExtension, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - Proof proof = builder.getProof(); - CompoundStopCondition stopCondition = new CompoundStopCondition(); - stopCondition.addChildren(new ExecutedSymbolicExecutionTreeNodesStopCondition(ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN)); - stopCondition.addChildren(new StepOverSymbolicExecutionTreeNodesStopCondition()); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Run proof - ui.getProofControl().startAndWaitForAutoMode(proof); - // Update symbolic execution tree - builder.analyse(); - // Test result - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, baseDir); - } - - /** - * Executes an "step into" global on all goals on the given {@link SymbolicExecutionTreeBuilder}. - * @param ui The {@link DefaultUserInterfaceControl} to use. - * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @return The found {@link SymbolicExecutionCompletions}. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static SymbolicExecutionCompletions stepInto(DefaultUserInterfaceControl ui, - SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - int oracleIndex, - String oracleFileExtension, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - Proof proof = builder.getProof(); - ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = new ExecutedSymbolicExecutionTreeNodesStopCondition(ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_FOR_ONE_STEP); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Run proof - ui.getProofControl().startAndWaitForAutoMode(proof); - // Update symbolic execution tree - SymbolicExecutionCompletions completions = builder.analyse(); - // Test result - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, oracleIndex, oracleFileExtension, baseDir); - return completions; - } - - /** - * Executes an "step into" global on all goals on the given {@link SymbolicExecutionTreeBuilder}. - * @param ui The {@link DefaultUserInterfaceControl} to use. - * @param builder The {@link SymbolicExecutionGoalChooser} to do step on. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void resume(DefaultUserInterfaceControl ui, - SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - Proof proof = builder.getProof(); - ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = new ExecutedSymbolicExecutionTreeNodesStopCondition(ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN); - proof.getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - // Run proof - ui.getProofControl().startAndWaitForAutoMode(proof); - // Update symbolic execution tree - builder.analyse(); - // Test result - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile, baseDir); - } - - /** - * Makes sure that after a step the correct set tree is created. - * @param builder The {@link SymbolicExecutionTreeBuilder} to test. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void assertSetTreeAfterStep(SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - createOracleFile(builder.getStartNode(), oraclePathInBaseDirFile, false, false, false, false); - } - else { - // Read oracle file - File oracleFile = new File(baseDir, oraclePathInBaseDirFile); - ExecutionNodeReader reader = new ExecutionNodeReader(); - IExecutionNode oracleRoot = reader.read(oracleFile); - assertNotNull(oracleRoot); - // Make sure that the created symbolic execution tree matches the expected one. - assertExecutionNodes(oracleRoot, builder.getStartNode(), false, false, false, false, false); - } - } - - /** - * Makes sure that after a step the correct set tree is created. - * @param builder The {@link SymbolicExecutionTreeBuilder} to test. - * @param oraclePathInBaseDirFile The oracle path. - * @param oracleIndex The index of the current step. - * @param oracleFileExtension The oracle file extension - * @param baseDir The base directory for oracles. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - */ - protected static void assertSetTreeAfterStep(SymbolicExecutionTreeBuilder builder, - String oraclePathInBaseDirFile, - int oracleIndex, - String oracleFileExtension, - File baseDir) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - assertSetTreeAfterStep(builder, oraclePathInBaseDirFile + "_" + oracleIndex + oracleFileExtension, baseDir); - } - - /** - * Searches a {@link IProgramMethod} in the given {@link Services}. - * @param services The {@link Services} to search in. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @return The first found {@link IProgramMethod} in the type. - */ - public static IProgramMethod searchProgramMethod(Services services, - String containerTypeName, - final String methodFullName) { - return HelperClassForTests.searchProgramMethod(services, containerTypeName, methodFullName); - } - - /** - * Creates a {@link SymbolicExecutionEnvironment} which consists - * of loading a file to load, finding the method to proof, instantiation - * of proof and creation with configuration of {@link SymbolicExecutionTreeBuilder}. - * @param baseDir The base directory which contains test and oracle file. - * @param baseContractName The name of the contract. - * @param methodFullName The method name to search. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvarints Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The created {@link SymbolicExecutionEnvironment}. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment(File baseDir, - String javaPathInBaseDir, - String baseContractName, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvarints, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean truthValueEvaluationEnabled, - boolean simplifyConditions) throws ProblemLoaderException, ProofInputException { - // Make sure that required files exists - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - // Load java file - KeYEnvironment environment = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(truthValueEvaluationEnabled), javaFile, null, null, null, true); - setupTacletOptions(environment); - // Start proof - final Contract contract = environment.getServices().getSpecificationRepository().getContractByName(baseContractName); - assertTrue(contract instanceof FunctionalOperationContract); - ProofOblInput input = new FunctionalOperationContractPO(environment.getInitConfig(), (FunctionalOperationContract)contract, true, true); - Proof proof = environment.createProof(input); - assertNotNull(proof); - // Set strategy and goal chooser to use for auto mode - SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, useOperationContracts, useLoopInvarints, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - // Create symbolic execution tree which contains only the start node at beginning - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - SymbolicExecutionUtil.initializeStrategy(builder); - builder.analyse(); - assertNotNull(builder.getStartNode()); - return new SymbolicExecutionEnvironment(environment, builder); - } - - /** - * Creates a {@link SymbolicExecutionEnvironment} which consists - * of loading a file to load, finding the method to proof, instantiation - * of proof and creation with configuration of {@link SymbolicExecutionTreeBuilder}. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param precondition An optional precondition to use. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvarints Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The created {@link SymbolicExecutionEnvironment}. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - String precondition, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvarints, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) throws ProblemLoaderException, ProofInputException { - // Make sure that required files exists - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - // Load java file - KeYEnvironment environment = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), javaFile, null, null, null, true); - setupTacletOptions(environment); - // Search method to proof - IProgramMethod pm = searchProgramMethod(environment.getServices(), containerTypeName, methodFullName); - // Start proof - ProofOblInput input = new ProgramMethodPO(environment.getInitConfig(), pm.getFullName(), pm, precondition, true, true); - Proof proof = environment.createProof(input); - assertNotNull(proof); - // Set strategy and goal chooser to use for auto mode - SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, useOperationContracts, useLoopInvarints, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - // Create symbolic execution tree which contains only the start node at beginning - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - SymbolicExecutionUtil.initializeStrategy(builder); - builder.analyse(); - assertNotNull(builder.getStartNode()); - return new SymbolicExecutionEnvironment(environment, builder); - } - - private static void setupTacletOptions(KeYEnvironment env) { - // Set Taclet options - ImmutableSet choices = env.getInitConfig().getActivatedChoices(); - choices = choices.add(new Choice("methodExpansion", "noRestriction")); - - ProofSettings settings = env.getInitConfig().getSettings(); - if (settings==null) { - settings = ProofSettings.DEFAULT_SETTINGS; - } - settings.getChoiceSettings().updateWith(choices); - } - - /** - * Creates a {@link SymbolicExecutionEnvironment} which consists - * of loading a proof file to load and creation with configuration of {@link SymbolicExecutionTreeBuilder}. - * @param baseDir The base directory which contains test and oracle file. - * @param proofPathInBaseDir The path to the proof file inside the base directory. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvarints Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The created {@link SymbolicExecutionEnvironment}. - * @throws ProblemLoaderException Occurred Exception. - */ - protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment(File baseDir, - String proofPathInBaseDir, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvarints, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean truthValueEvaluationEnabled, - boolean simplifyConditions) throws ProblemLoaderException { - // Make sure that required files exists - File proofFile = new File(baseDir, proofPathInBaseDir); - assertTrue(proofFile.exists()); - // Load java file - KeYEnvironment environment = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(truthValueEvaluationEnabled), proofFile, null, null, null, SymbolicExecutionTreeBuilder.createPoPropertiesToForce(), null, true); - setupTacletOptions(environment); - Proof proof = environment.getLoadedProof(); - assertNotNull(proof); - // Set strategy and goal chooser to use for auto mode - SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, useOperationContracts, useLoopInvarints, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - // Create symbolic execution tree which contains only the start node at beginning - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - SymbolicExecutionUtil.initializeStrategy(builder); - builder.analyse(); - assertNotNull(builder.getStartNode()); - return new SymbolicExecutionEnvironment(environment, builder); - } - - /** - * Creates a {@link SymbolicExecutionEnvironment} which consists - * of loading a file to load, finding the method to proof, instantiation - * of proof and creation with configuration of {@link SymbolicExecutionTreeBuilder}. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The name of the type which contains the method. - * @param methodFullName The method name to search. - * @param precondition An optional precondition to use. - * @param startPosition The start position. - * @param endPosition The end position. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvarints Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The created {@link SymbolicExecutionEnvironment}. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - protected static SymbolicExecutionEnvironment createSymbolicExecutionEnvironment(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - String precondition, - Position startPosition, - Position endPosition, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvarints, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) throws ProblemLoaderException, ProofInputException { - // Make sure that required files exists - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - // Load java file - KeYEnvironment environment = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), javaFile, null, null, null, true); - setupTacletOptions(environment); - // Search method to proof - IProgramMethod pm = searchProgramMethod(environment.getServices(), containerTypeName, methodFullName); - // Start proof - ProofOblInput input = new ProgramMethodSubsetPO(environment.getInitConfig(), methodFullName, pm, precondition, startPosition, endPosition, true, true); - Proof proof = environment.createProof(input); - assertNotNull(proof); - // Set strategy and goal chooser to use for auto mode - SymbolicExecutionEnvironment.configureProofForSymbolicExecution(proof, ExecutedSymbolicExecutionTreeNodesStopCondition.MAXIMAL_NUMBER_OF_SET_NODES_TO_EXECUTE_PER_GOAL_IN_COMPLETE_RUN, useOperationContracts, useLoopInvarints, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks); - // Create symbolic execution tree which contains only the start node at beginning - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, mergeBranchConditions, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - SymbolicExecutionUtil.initializeStrategy(builder); - builder.analyse(); - assertNotNull(builder.getStartNode()); - return new SymbolicExecutionEnvironment(environment, builder); - } - - /** - * Extracts the content of the try block from the initial {@link Sequent}. - * @param proof The {@link Proof} which contains the initial {@link Sequent}: - * @return The try content. - */ - protected String getTryContent(Proof proof) { - assertNotNull(proof); - Node node = proof.root(); - Sequent sequent = node.sequent(); - assertEquals(1, sequent.succedent().size()); - Term succedent = sequent.succedent().get(0).formula(); - assertEquals(2, succedent.arity()); - Term updateApplication = succedent.subs().get(1); - assertEquals(2, updateApplication.arity()); - JavaProgramElement updateContent = updateApplication.subs().get(1).javaBlock().program(); - assertTrue(updateContent instanceof StatementBlock); - ImmutableArray updateContentBody = ((StatementBlock)updateContent).getBody(); - assertEquals(2, updateContentBody.size()); - assertTrue(updateContentBody.get(1) instanceof Try); - Try tryStatement = (Try)updateContentBody.get(1); - assertEquals(1, tryStatement.getBranchCount()); - return ProofSaver.printAnything(tryStatement.getBody(), proof.getServices()); - } - - /** - * Makes sure that the save and loading process works. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param oraclePathInBaseDirFile The oracle path. - * @param env The already executed {@link SymbolicExecutionEnvironment} which contains the proof to save/load. - * @throws IOException Occurred Exception - * @throws ProofInputException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected void assertSaveAndReload(File baseDir, - String javaPathInBaseDir, - String oraclePathInBaseDirFile, - SymbolicExecutionEnvironment env) throws IOException, ProofInputException, ParserConfigurationException, SAXException, ProblemLoaderException { - File javaFile = new File(baseDir, javaPathInBaseDir); - assertTrue(javaFile.exists()); - File tempFile = File.createTempFile("TestProgramMethodSubsetPO", ".proof", javaFile.getParentFile()); - KeYEnvironment reloadedEnv = null; - SymbolicExecutionTreeBuilder reloadedBuilder = null; - try { - ProofSaver saver = new ProofSaver(env.getProof(), tempFile.getAbsolutePath(), KeYConstants.INTERNAL_VERSION); - assertNull(saver.save()); - // Load proof from saved *.proof file - reloadedEnv = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), tempFile, null, null, null, true); - Proof reloadedProof = reloadedEnv.getLoadedProof(); - assertNotSame(env.getProof(), reloadedProof); - // Recreate symbolic execution tree - reloadedBuilder = new SymbolicExecutionTreeBuilder(reloadedProof, false, false, false, false, true); - SymbolicExecutionUtil.initializeStrategy(reloadedBuilder); - reloadedBuilder.analyse(); - assertSetTreeAfterStep(reloadedBuilder, oraclePathInBaseDirFile, baseDir); - } - finally { - if (reloadedBuilder != null) { - reloadedBuilder.dispose(); - } - if (reloadedEnv != null) { - reloadedEnv.dispose(); - } - if (tempFile != null) { - tempFile.delete(); - assertFalse(tempFile.exists()); - } - } - } - - /** - * Executes a test with the following steps: - *
      - *
    1. Load java file
    2. - *
    3. Instantiate proof for method in container type
    4. - *
    5. Try to close proof in auto mode
    6. - *
    7. Create symbolic execution tree
    8. - *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is defined
    10. - *
    11. Load oracle file
    12. - *
    13. Compare created symbolic execution tree with oracle model
    14. - *
    - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The java class to test. - * @param methodFullName The method to test. - * @param precondition An optional precondition. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param maximalNumberOfExecutedSetNodesPerRun The number of executed set nodes per auto mode run. The whole test is executed for each defined value. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected void doSETTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - String precondition, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - int[] maximalNumberOfExecutedSetNodesPerRun, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - assertNotNull(maximalNumberOfExecutedSetNodesPerRun); - for (int i = 0; i < maximalNumberOfExecutedSetNodesPerRun.length; i++) { - SymbolicExecutionEnvironment env = doSETTest(baseDir, - javaPathInBaseDir, - containerTypeName, - methodFullName, - precondition, - oraclePathInBaseDirFile, - includeConstraints, - includeVariables, - includeCallStack, - includeReturnValues, - maximalNumberOfExecutedSetNodesPerRun[i], - mergeBranchConditions, - useOperationContracts, - useLoopInvariants, - blockTreatmentContract, - nonExecutionBranchHidingSideProofs, - aliasChecks, - useUnicode, - usePrettyPrinting, - variablesAreOnlyComputedFromUpdates, - simplifyConditions); - env.dispose(); - } - } - - /** - * Executes {@link #doSETTest(File, String, String, String, String, boolean, boolean, int, boolean, boolean, boolean)} and disposes the created {@link SymbolicExecutionEnvironment}. - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The java class to test. - * @param methodFullName The method to test. - * @param precondition An optional precondition. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The tested {@link SymbolicExecutionEnvironment}. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected void doSETTestAndDispose(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName, - String precondition, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - int maximalNumberOfExecutedSetNodes, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env = doSETTest(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, precondition, oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, includeReturnValues, maximalNumberOfExecutedSetNodes, mergeBranchConditions, useOperationContracts, useLoopInvariants, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - env.dispose(); - } - - /** - * Executes a test with the following steps: - *
      - *
    1. Load java file
    2. - *
    3. Instantiate proof for method in container type
    4. - *
    5. Try to close proof in auto mode
    6. - *
    7. Create symbolic execution tree
    8. - *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is defined
    10. - *
    11. Load oracle file
    12. - *
    13. Compare created symbolic execution tree with oracle model
    14. - *
    - * @param baseDir The base directory which contains test and oracle file. - * @param proofFilePathInBaseDir The path to the proof file inside the base directory. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @return The tested {@link SymbolicExecutionEnvironment}. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected void doSETTestAndDispose(File baseDir, - String proofFilePathInBaseDir, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env = doSETTest(baseDir, proofFilePathInBaseDir, oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, includeReturnValues, mergeBranchConditions, useOperationContracts, useLoopInvariants, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, false, true); - if (env != null) { - env.dispose(); - } - } - - /** - * Executes a test with the following steps: - *
      - *
    1. Load java file
    2. - *
    3. Instantiate proof for method in container type
    4. - *
    5. Try to close proof in auto mode
    6. - *
    7. Create symbolic execution tree
    8. - *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is defined
    10. - *
    11. Load oracle file
    12. - *
    13. Compare created symbolic execution tree with oracle model
    14. - *
    - * @param baseDir The base directory which contains test and oracle file. - * @param proofFilePathInBaseDir The path to the proof file inside the base directory. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The tested {@link SymbolicExecutionEnvironment}. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected SymbolicExecutionEnvironment doSETTest(File baseDir, - String proofFilePathInBaseDir, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean truthValueEvaluationEnabled, - boolean simplifyConditions) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - SymbolicExecutionEnvironment env = null; - try { - // Make sure that parameter are valid. - assertNotNull(proofFilePathInBaseDir); - assertNotNull(oraclePathInBaseDirFile); - File oracleFile = new File(baseDir, oraclePathInBaseDirFile); - if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - assertTrue(oracleFile.exists(), "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); - } - // Make sure that the correct taclet options are defined. - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(baseDir, proofFilePathInBaseDir, mergeBranchConditions, useOperationContracts, useLoopInvariants, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, truthValueEvaluationEnabled, simplifyConditions); - // Create new oracle file if required in a temporary directory - createOracleFile(env.getBuilder().getStartNode(), oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, includeReturnValues); - // Read oracle file - ExecutionNodeReader reader = new ExecutionNodeReader(); - IExecutionNode oracleRoot = reader.read(oracleFile); - assertNotNull(oracleRoot); - // Make sure that the created symbolic execution tree matches the expected one. - assertExecutionNodes(oracleRoot, env.getBuilder().getStartNode(), includeVariables, includeCallStack, false, includeReturnValues, includeConstraints); - return env; - } - finally { - // Restore original options - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - } - } - - /** - * Executes a test with the following steps: - *
      - *
    1. Load java file
    2. - *
    3. Instantiate proof for method in container type
    4. - *
    5. Try to close proof in auto mode
    6. - *
    7. Create symbolic execution tree
    8. - *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is defined
    10. - *
    11. Load oracle file
    12. - *
    13. Compare created symbolic execution tree with oracle model
    14. - *
    - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param containerTypeName The java class to test. - * @param methodFullName The method to test. - * @param precondition An optional precondition. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The tested {@link SymbolicExecutionEnvironment}. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected SymbolicExecutionEnvironment doSETTest(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - final String methodFullName, - String precondition, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - int maximalNumberOfExecutedSetNodes, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean simplifyConditions) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try { - // Make sure that parameter are valid. - assertNotNull(javaPathInBaseDir); - assertNotNull(containerTypeName); - assertNotNull(methodFullName); - assertNotNull(oraclePathInBaseDirFile); - File oracleFile = new File(baseDir, oraclePathInBaseDirFile); - if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - assertTrue(oracleFile.exists(), "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); - } - assertTrue(maximalNumberOfExecutedSetNodes >= 1); - // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(baseDir, javaPathInBaseDir, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, precondition, mergeBranchConditions, useOperationContracts, useLoopInvariants, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, simplifyConditions); - internalDoSETTest(oracleFile, env, oraclePathInBaseDirFile, maximalNumberOfExecutedSetNodes, includeConstraints, includeVariables, includeCallStack, includeReturnValues); - return env; - } - finally { - // Restore original options - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - } - } - - /** - * Executes a test with the following steps: - *
      - *
    1. Load java file
    2. - *
    3. Instantiate proof for method in container type
    4. - *
    5. Try to close proof in auto mode
    6. - *
    7. Create symbolic execution tree
    8. - *
    9. Create new oracle file in temporary directory {@link #tempNewOracleDirectory} if it is defined
    10. - *
    11. Load oracle file
    12. - *
    13. Compare created symbolic execution tree with oracle model
    14. - *
    - * @param baseDir The base directory which contains test and oracle file. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param baseContractName The name of the contract. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param includeConstraints Include constraints? - * @param includeVariables Include variables? - * @param includeCallStack Include call stack? - * @param includeReturnValues Include method return values? - * @param maximalNumberOfExecutedSetNodes The number of executed set nodes per auto mode run. - * @param mergeBranchConditions Merge branch conditions? - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param nonExecutionBranchHidingSideProofs {@code true} hide non execution branch labels by side proofs, {@code false} do not hide execution branch labels. - * @param aliasChecks Do alias checks? - * @param useUnicode {@code true} use unicode characters, {@code false} do not use unicode characters. - * @param usePrettyPrinting {@code true} use pretty printing, {@code false} do not use pretty printing. - * @param variablesAreOnlyComputedFromUpdates {@code true} {@link IExecutionVariable} are only computed from updates, {@code false} {@link IExecutionVariable}s are computed according to the type structure of the visible memory. - * @param truthValueEvaluationEnabled {@code true} truth value evaluation is enabled, {@code false} truth value evaluation is disabled. - * @param simplifyConditions {@code true} simplify conditions, {@code false} do not simplify conditions. - * @return The tested {@link SymbolicExecutionEnvironment}. - * @throws ProofInputException Occurred Exception - * @throws IOException Occurred Exception - * @throws ParserConfigurationException Occurred Exception - * @throws SAXException Occurred Exception - * @throws ProblemLoaderException Occurred Exception - */ - protected SymbolicExecutionEnvironment doSETTest(File baseDir, - String javaPathInBaseDir, - String baseContractName, - String oraclePathInBaseDirFile, - boolean includeConstraints, - boolean includeVariables, - boolean includeCallStack, - boolean includeReturnValues, - int maximalNumberOfExecutedSetNodes, - boolean mergeBranchConditions, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - boolean nonExecutionBranchHidingSideProofs, - boolean aliasChecks, - boolean useUnicode, - boolean usePrettyPrinting, - boolean variablesAreOnlyComputedFromUpdates, - boolean truthValueEvaluationEnabled, - boolean simplifyConditions) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - try { - // Make sure that parameter are valid. - assertNotNull(javaPathInBaseDir); - assertNotNull(baseContractName); - assertNotNull(oraclePathInBaseDirFile); - File oracleFile = new File(baseDir, oraclePathInBaseDirFile); - if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - assertTrue(oracleFile.exists(), "Oracle file does not exist. Set \"CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY\" to true to create an oracle file."); - } - assertTrue(maximalNumberOfExecutedSetNodes >= 1); - // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(baseDir, javaPathInBaseDir, baseContractName); - // Create proof environment for symbolic execution - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, baseContractName, mergeBranchConditions, useOperationContracts, useLoopInvariants, blockTreatmentContract, nonExecutionBranchHidingSideProofs, aliasChecks, useUnicode, usePrettyPrinting, variablesAreOnlyComputedFromUpdates, truthValueEvaluationEnabled, simplifyConditions); - internalDoSETTest(oracleFile, env, oraclePathInBaseDirFile, maximalNumberOfExecutedSetNodes, includeConstraints, includeVariables, includeCallStack, includeReturnValues); - return env; - } - finally { - // Restore taclet options - restoreTacletOptions(originalTacletOptions); - } - } - - /** - * Internal test method called by - * {@link #doSETTest(File, String, String, String, boolean, boolean, boolean, int, boolean, boolean, boolean, boolean, boolean)} and - * {@link #doSETTest(File, String, String, String, String, String, boolean, boolean, boolean, int, boolean, boolean, boolean, boolean, boolean)}. - */ - private void internalDoSETTest(File oracleFile, SymbolicExecutionEnvironment env, String oraclePathInBaseDirFile, int maximalNumberOfExecutedSetNodes, boolean includeConstraints, boolean includeVariables, boolean includeCallStack, boolean includeReturnValues) throws IOException, ProofInputException, ParserConfigurationException, SAXException { - // Set stop condition to stop after a number of detected symbolic execution tree nodes instead of applied rules - ExecutedSymbolicExecutionTreeNodesStopCondition stopCondition = new ExecutedSymbolicExecutionTreeNodesStopCondition(maximalNumberOfExecutedSetNodes); - env.getProof().getSettings().getStrategySettings().setCustomApplyStrategyStopCondition(stopCondition); - int nodeCount; - // Execute auto mode until no more symbolic execution tree nodes are found or no new rules are applied. - do { - // Store the number of nodes before start of the auto mode - nodeCount = env.getProof().countNodes(); - // Run proof - env.getProofControl().startAndWaitForAutoMode(env.getProof()); - // Update symbolic execution tree - env.getBuilder().analyse(); - // Make sure that not to many set nodes are executed - Map executedSetNodesPerGoal = stopCondition.getExectuedSetNodesPerGoal(); - for (Integer value : executedSetNodesPerGoal.values()) { - assertNotNull(value); - assertTrue(value.intValue() <= maximalNumberOfExecutedSetNodes, value.intValue() + " is not less equal to " + maximalNumberOfExecutedSetNodes); - } - } while(stopCondition.wasSetNodeExecuted() && nodeCount != env.getProof().countNodes()); - // Create new oracle file if required in a temporary directory - createOracleFile(env.getBuilder().getStartNode(), oraclePathInBaseDirFile, includeConstraints, includeVariables, includeCallStack, includeReturnValues); - // Read oracle file - ExecutionNodeReader reader = new ExecutionNodeReader(); - IExecutionNode oracleRoot = reader.read(oracleFile); - assertNotNull(oracleRoot); - // Make sure that the created symbolic execution tree matches the expected one. - assertExecutionNodes(oracleRoot, env.getBuilder().getStartNode(), includeVariables, includeCallStack, false, includeReturnValues, includeConstraints); - } - - /** - * Ensures that the default taclet options are defined. - * @param baseDir The base directory which contains the java file. - * @param javaPathInBaseDir The path in the base directory to the java file. - * @param baseContractName The name of the contract to prove. - * @return The original settings which are overwritten. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - public static HashMap setDefaultTacletOptions(File baseDir, - String javaPathInBaseDir, - String baseContractName) throws ProblemLoaderException, ProofInputException { - if (!SymbolicExecutionUtil.isChoiceSettingInitialised()) { - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInBaseDir, baseContractName, false, false, false, false, false, false, false, false, false, false, false); - env.dispose(); - } - return setDefaultTacletOptions(); - } - - /** - * Ensures that the default taclet options are defined. - * @param baseDir The base directory which contains the java file. - * @param javaPathInBaseDir The path in the base directory to the java file. - * @param containerTypeName The type nach which provides the method. - * @param methodFullName The method to prove. - * @return The original settings which are overwritten. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - public static HashMap setDefaultTacletOptions(File baseDir, - String javaPathInBaseDir, - String containerTypeName, - String methodFullName) throws ProblemLoaderException, ProofInputException { - if (!SymbolicExecutionUtil.isChoiceSettingInitialised()) { - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(baseDir, javaPathInBaseDir, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - env.dispose(); - } - return setDefaultTacletOptions(); - } - - /** - * Ensures that the default taclet options are defined. - * @param javaFile The java file to load. - * @param containerTypeName The type name which provides the target. - * @param targetName The target to proof. - * @return The original settings which are overwritten. - * @throws ProblemLoaderException Occurred Exception. - * @throws ProofInputException Occurred Exception. - */ - public static HashMap setDefaultTacletOptionsForTarget(File javaFile, - String containerTypeName, - final String targetName) throws ProblemLoaderException, ProofInputException { - return HelperClassForTests.setDefaultTacletOptionsForTarget(javaFile, containerTypeName, targetName); - } - - /** - * Ensures that the default taclet options are defined. - * @return The original settings which are overwritten. - */ - public static HashMap setDefaultTacletOptions() { - HashMap original = HelperClassForTests.setDefaultTacletOptions(); - ChoiceSettings choiceSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings(); - ImmutableSet cs = DefaultImmutableSet.nil(); - cs = cs.add(new Choice("noRestriction", "methodExpansion")); - choiceSettings.updateWith(cs); - return original; - } - - /** - * Restores the given taclet options. - * @param options The taclet options to restore. - */ - public static void restoreTacletOptions(HashMap options) { - HelperClassForTests.restoreTacletOptions(options); - } - - /** - * creates a new factory that should be used by others afterwards - * @return - */ - protected ITermProgramVariableCollectorFactory createNewProgramVariableCollectorFactory(final SymbolicExecutionBreakpointStopCondition breakpointParentStopCondition) { - ITermProgramVariableCollectorFactory programVariableCollectorFactory = new ITermProgramVariableCollectorFactory() { - @Override - public TermProgramVariableCollector create(Services services) { - return new TermProgramVariableCollectorKeepUpdatesForBreakpointconditions(services, breakpointParentStopCondition); - } - }; - return programVariableCollectorFactory; - } - - /** - * Makes sure that two {@link Term}s are equal. - * @param expected The expected {@link Term}. - * @param actual The actual {@link Term}. - */ - protected void assertTerm(Term expected, Term actual) { - if (expected != null) { - assertEquals(expected.op(), actual.op()); - assertEquals(expected.javaBlock(), actual.javaBlock()); - assertEquals(expected.getLabels(), actual.getLabels()); - assertEquals(expected.arity(), actual.arity()); - for (int i = 0; i < expected.arity(); i++) { - assertTerm(expected.sub(i), actual.sub(i)); - } - } - else { - assertNull(actual); - } - } - - /** - * Checks if one step simplification is enabled in the given {@link Proof}. - * @param proof The {@link Proof} to read from or {@code null} to return the general settings value. - * @return {@code true} one step simplification is enabled, {@code false} if disabled. - */ - public static boolean isOneStepSimplificationEnabled(Proof proof) { - return HelperClassForTests.isOneStepSimplificationEnabled(proof); - } - - /** - * Defines if one step simplification is enabled in general and within the {@link Proof}. - * @param proof The optional {@link Proof}. - * @param enabled {@code true} use one step simplification, {@code false} do not use one step simplification. - */ - public static void setOneStepSimplificationEnabled(Proof proof, boolean enabled) { - HelperClassForTests.setOneStepSimplificationEnabled(proof, enabled); - } + } else { + assertNull(actual); + } + } + + /** + * Checks if one step simplification is enabled in the given {@link Proof}. + * + * @param proof The {@link Proof} to read from or {@code null} to return the general settings + * value. + * @return {@code true} one step simplification is enabled, {@code false} if disabled. + */ + public static boolean isOneStepSimplificationEnabled(Proof proof) { + return HelperClassForTests.isOneStepSimplificationEnabled(proof); + } + + /** + * Defines if one step simplification is enabled in general and within the {@link Proof}. + * + * @param proof The optional {@link Proof}. + * @param enabled {@code true} use one step simplification, {@code false} do not use one step + * simplification. + */ + public static void setOneStepSimplificationEnabled(Proof proof, boolean enabled) { + HelperClassForTests.setOneStepSimplificationEnabled(proof, enabled); + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestConditionalVariables.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestConditionalVariables.java index 109e959acf2..90979d8b014 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestConditionalVariables.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestConditionalVariables.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -13,156 +16,169 @@ import org.junit.jupiter.api.Test; /** - * Tests the conditional values provided by {@link IExecutionNode#getVariables(de.uka.ilkd.key.logic.Term)}. + * Tests the conditional values provided by + * {@link IExecutionNode#getVariables(de.uka.ilkd.key.logic.Term)}. + * * @author Martin Hentschel */ public class TestConditionalVariables extends AbstractSymbolicExecutionTestCase { - /** - * Compares the conditional values on the {@code Number} example. - * @throws Exception Occurred Exception. - */ - @Test - public void testVariablesUnderMethodReturnCondition() throws Exception { - SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, - "/set/conditionalVariables/test/Number.java", - "Number", - "equals", - null, - "/set/conditionalVariables/oracle/Number.xml", - false, - false, - false, - false, - 1000, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - try { - // Find nodes in tree - IExecutionStart start = env.getBuilder().getStartNode(); - IExecutionNode call = start.getChildren()[0]; - IExecutionNode ifStatement = call.getChildren()[0]; - IExecutionNode notNullCondition = ifStatement.getChildren()[0]; - IExecutionNode equalCondition = notNullCondition.getChildren()[0]; - IExecutionNode returnTrueStatement = equalCondition.getChildren()[0]; - IExecutionBaseMethodReturn returnTrue = (IExecutionBaseMethodReturn)returnTrueStatement.getChildren()[0]; - IExecutionNode notEqualCondition = notNullCondition.getChildren()[1]; - IExecutionNode returnFalseStatement = notEqualCondition.getChildren()[0]; - IExecutionBaseMethodReturn returnFalse = (IExecutionBaseMethodReturn)returnFalseStatement.getChildren()[0]; - IExecutionNode nullCondition = ifStatement.getChildren()[1]; - IExecutionBaseMethodReturn exceptionalReturn = (IExecutionBaseMethodReturn)nullCondition.getChildren()[0]; - // Test conditional values on if statement (call node provides only exc) under method return condition - assertConditionalVariables(createExpectedEqualCaseVariables(), ifStatement, returnTrue.getMethodReturnCondition(), true, true, false); - assertConditionalVariables(createExpectedNotEqualCaseVariables(), ifStatement, returnFalse.getMethodReturnCondition(), true, true, false); - assertConditionalVariables(createExpectedNullCaseVariables(), ifStatement, exceptionalReturn.getMethodReturnCondition(), true, true, false); - } - finally { - env.dispose(); - } - } - - /** - * Ensures that the result of {@link IExecutionNode#getVariables(Term)} is correct. - * @param expected The expected {@link IExecutionVariable}s. - * @param node The current {@link IExecutionNode} to call {@link IExecutionNode#getVariables(Term)} on. - * @param condition The condition to use. - * @param compareParent Compare parents? - * @param compareChildren Compare children? - * @param compareConstraints Compare constraints? - * @throws ProofInputException Occurred Exception. - */ - protected static void assertConditionalVariables(IExecutionVariable[] expected, - IExecutionNode node, - Term condition, - boolean compareParent, - boolean compareChildren, - boolean compareConstraints) throws ProofInputException { - IExecutionVariable[] current = node.getVariables(condition); - assertVariables(expected, current, true, true, false); - IExecutionVariable[] currentAgain = node.getVariables(condition); - Assertions.assertSame(current, currentAgain); - assertVariables(expected, currentAgain, true, true, false); - } + /** + * Compares the conditional values on the {@code Number} example. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testVariablesUnderMethodReturnCondition() throws Exception { + SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, + "/set/conditionalVariables/test/Number.java", "Number", "equals", null, + "/set/conditionalVariables/oracle/Number.xml", false, false, false, false, 1000, + false, false, false, false, false, false, false, false, false, true); + try { + // Find nodes in tree + IExecutionStart start = env.getBuilder().getStartNode(); + IExecutionNode call = start.getChildren()[0]; + IExecutionNode ifStatement = call.getChildren()[0]; + IExecutionNode notNullCondition = ifStatement.getChildren()[0]; + IExecutionNode equalCondition = notNullCondition.getChildren()[0]; + IExecutionNode returnTrueStatement = equalCondition.getChildren()[0]; + IExecutionBaseMethodReturn returnTrue = + (IExecutionBaseMethodReturn) returnTrueStatement.getChildren()[0]; + IExecutionNode notEqualCondition = notNullCondition.getChildren()[1]; + IExecutionNode returnFalseStatement = notEqualCondition.getChildren()[0]; + IExecutionBaseMethodReturn returnFalse = + (IExecutionBaseMethodReturn) returnFalseStatement.getChildren()[0]; + IExecutionNode nullCondition = ifStatement.getChildren()[1]; + IExecutionBaseMethodReturn exceptionalReturn = + (IExecutionBaseMethodReturn) nullCondition.getChildren()[0]; + // Test conditional values on if statement (call node provides only exc) under method + // return condition + assertConditionalVariables(createExpectedEqualCaseVariables(), ifStatement, + returnTrue.getMethodReturnCondition(), true, true, false); + assertConditionalVariables(createExpectedNotEqualCaseVariables(), ifStatement, + returnFalse.getMethodReturnCondition(), true, true, false); + assertConditionalVariables(createExpectedNullCaseVariables(), ifStatement, + exceptionalReturn.getMethodReturnCondition(), true, true, false); + } finally { + env.dispose(); + } + } - /** - * Creates the expected variables in case that {@code n.content == self.content}. - * @return The expected {@link IExecutionVariable}s. - */ - protected IExecutionVariable[] createExpectedEqualCaseVariables() { - ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; - // self - result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); - ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], "Number", "self", "self {true}", false, true, "true"); - result[0].addValue(selfValue); - ExecutionNodeReader.KeYlessVariable selfContentVar = new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); - selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); - selfValue.addChildVariable(selfContentVar); - // n - result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); - ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], "Number", "n", "n {true}", false, true, "true"); - result[1].addValue(nValue); - ExecutionNodeReader.KeYlessVariable nContentVar = new ExecutionNodeReader.KeYlessVariable(nValue, false, null, "content"); - nContentVar.addValue(new ExecutionNodeReader.KeYlessValue(nContentVar, "int", "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); - nValue.addChildVariable(nContentVar); - // exc - result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); - result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", "exc {true}", false, false, "true")); - return result; - } + /** + * Ensures that the result of {@link IExecutionNode#getVariables(Term)} is correct. + * + * @param expected The expected {@link IExecutionVariable}s. + * @param node The current {@link IExecutionNode} to call + * {@link IExecutionNode#getVariables(Term)} on. + * @param condition The condition to use. + * @param compareParent Compare parents? + * @param compareChildren Compare children? + * @param compareConstraints Compare constraints? + * @throws ProofInputException Occurred Exception. + */ + protected static void assertConditionalVariables(IExecutionVariable[] expected, + IExecutionNode node, Term condition, boolean compareParent, boolean compareChildren, + boolean compareConstraints) throws ProofInputException { + IExecutionVariable[] current = node.getVariables(condition); + assertVariables(expected, current, true, true, false); + IExecutionVariable[] currentAgain = node.getVariables(condition); + Assertions.assertSame(current, currentAgain); + assertVariables(expected, currentAgain, true, true, false); + } - /** - * Creates the expected variables in case that {@code n.content != self.content}. - * @return The expected {@link IExecutionVariable}s. - */ - protected IExecutionVariable[] createExpectedNotEqualCaseVariables() { - ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; - // self - result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); - ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], "Number", "self", "self {true}", false, true, "true"); - result[0].addValue(selfValue); - ExecutionNodeReader.KeYlessVariable selfContentVar = new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); - selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", "int::select(heap,self,Number::$content)", "content {true}", false, false, "true")); - selfValue.addChildVariable(selfContentVar); - // n - result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); - ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], "Number", "n", "n {true}", false, true, "true"); - result[1].addValue(nValue); - ExecutionNodeReader.KeYlessVariable nContentVar = new ExecutionNodeReader.KeYlessVariable(nValue, false, null, "content"); - nContentVar.addValue(new ExecutionNodeReader.KeYlessValue(nContentVar, "int", "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); - nValue.addChildVariable(nContentVar); - // exc - result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); - result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", "exc {true}", false, false, "true")); - return result; - } + /** + * Creates the expected variables in case that {@code n.content == self.content}. + * + * @return The expected {@link IExecutionVariable}s. + */ + protected IExecutionVariable[] createExpectedEqualCaseVariables() { + ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; + // self + result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); + ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], + "Number", "self", "self {true}", false, true, "true"); + result[0].addValue(selfValue); + ExecutionNodeReader.KeYlessVariable selfContentVar = + new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); + selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", + "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); + selfValue.addChildVariable(selfContentVar); + // n + result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); + ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], + "Number", "n", "n {true}", false, true, "true"); + result[1].addValue(nValue); + ExecutionNodeReader.KeYlessVariable nContentVar = + new ExecutionNodeReader.KeYlessVariable(nValue, false, null, "content"); + nContentVar.addValue(new ExecutionNodeReader.KeYlessValue(nContentVar, "int", + "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); + nValue.addChildVariable(nContentVar); + // exc + result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); + result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", + "exc {true}", false, false, "true")); + return result; + } - /** - * Creates the expected variables in case that {@code n} is {@code null}. - * @return The expected {@link IExecutionVariable}s. - */ - protected IExecutionVariable[] createExpectedNullCaseVariables() { - ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; - // self - result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); - ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], "Number", "self", "self {true}", false, true, "true"); - result[0].addValue(selfValue); - ExecutionNodeReader.KeYlessVariable selfContentVar = new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); - selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", "int::select(heap,self,Number::$content)", "content {true}", false, false, "true")); - selfValue.addChildVariable(selfContentVar); - // n - result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); - ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], "Null", "null", "n {true}", false, false, "true"); - result[1].addValue(nValue); - // exc - result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); - result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", "exc {true}", false, false, "true")); - return result; - } + /** + * Creates the expected variables in case that {@code n.content != self.content}. + * + * @return The expected {@link IExecutionVariable}s. + */ + protected IExecutionVariable[] createExpectedNotEqualCaseVariables() { + ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; + // self + result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); + ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], + "Number", "self", "self {true}", false, true, "true"); + result[0].addValue(selfValue); + ExecutionNodeReader.KeYlessVariable selfContentVar = + new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); + selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", + "int::select(heap,self,Number::$content)", "content {true}", false, false, "true")); + selfValue.addChildVariable(selfContentVar); + // n + result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); + ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], + "Number", "n", "n {true}", false, true, "true"); + result[1].addValue(nValue); + ExecutionNodeReader.KeYlessVariable nContentVar = + new ExecutionNodeReader.KeYlessVariable(nValue, false, null, "content"); + nContentVar.addValue(new ExecutionNodeReader.KeYlessValue(nContentVar, "int", + "int::select(heap,n,Number::$content)", "content {true}", false, false, "true")); + nValue.addChildVariable(nContentVar); + // exc + result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); + result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", + "exc {true}", false, false, "true")); + return result; + } + + /** + * Creates the expected variables in case that {@code n} is {@code null}. + * + * @return The expected {@link IExecutionVariable}s. + */ + protected IExecutionVariable[] createExpectedNullCaseVariables() { + ExecutionNodeReader.KeYlessVariable[] result = new ExecutionNodeReader.KeYlessVariable[3]; + // self + result[0] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "self"); + ExecutionNodeReader.KeYlessValue selfValue = new ExecutionNodeReader.KeYlessValue(result[0], + "Number", "self", "self {true}", false, true, "true"); + result[0].addValue(selfValue); + ExecutionNodeReader.KeYlessVariable selfContentVar = + new ExecutionNodeReader.KeYlessVariable(selfValue, false, null, "content"); + selfContentVar.addValue(new ExecutionNodeReader.KeYlessValue(selfContentVar, "int", + "int::select(heap,self,Number::$content)", "content {true}", false, false, "true")); + selfValue.addChildVariable(selfContentVar); + // n + result[1] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "n"); + ExecutionNodeReader.KeYlessValue nValue = new ExecutionNodeReader.KeYlessValue(result[1], + "Null", "null", "n {true}", false, false, "true"); + result[1].addValue(nValue); + // exc + result[2] = new ExecutionNodeReader.KeYlessVariable(null, false, null, "exc"); + result[2].addValue(new ExecutionNodeReader.KeYlessValue(result[2], "Null", "null", + "exc {true}", false, false, "true")); + return result; + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodePreorderIterator.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodePreorderIterator.java index ff26b1a34cd..6258332946b 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodePreorderIterator.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodePreorderIterator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.java.Services; @@ -22,279 +25,304 @@ /** * Tests for {@link ExecutionNodePreorderIterator}. + * * @author Martin Hentschel */ public class TestExecutionNodePreorderIterator { - /** - * Tests a tree of {@link IExecutionNode}s with three levels after root. - */ - @Test - public void testNodesThreeLevel() throws ProofInputException { - // Create tree to test - Proof proof = new Proof("target", new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); - Node root = appendRoot(proof); - Node l1 = appendNode(proof, root); - Node l11 = appendNode(proof, l1); - Node l111 = appendNode(proof, l11); - Node l12 = appendNode(proof, l1); - Node l2 = appendNode(proof, root); - Node l21 = appendNode(proof, l2); - Node l22 = appendNode(proof, l2); - Node l221 = appendNode(proof, l22); - Node l222 = appendNode(proof, l22); - Node l23 = appendNode(proof, l2); - Node l3 = appendNode(proof, root); - Node l4 = appendNode(proof, root); - Node l41 = appendNode(proof, l4); - // Create execution test model - KeYlessStart executionRoot = new KeYlessStart("", null, false); - KeYlessStatement el1 = createStatement(executionRoot, l1); - KeYlessStatement el11 = createStatement(el1, l11); - createStatement(el11, l111); - createStatement(el1, l12); - KeYlessStatement el2 = createStatement(executionRoot, l2); - createStatement(el2, l21); - KeYlessStatement el22 = createStatement(el2, l22); - createStatement(el22, l221); - createStatement(el22, l222); - createStatement(el2, l23); - createStatement(executionRoot, l3); - KeYlessStatement el4 = createStatement(executionRoot, l4); - createStatement(el4, l41); - // Test tree - ExpectedNode[] level111 = createExpectedNodes("3"); - ExpectedNode[] level11 = createExpectedNodes(new String[] {"2", "4"}, level111, null); - ExpectedNode[] level122 = createExpectedNodes("8", "9"); - ExpectedNode[] level12 = createExpectedNodes(new String[] {"6", "7", "10"}, null, level122, null); - ExpectedNode[] level14 = createExpectedNodes("13"); - ExpectedNode[] level1 = createExpectedNodes(new String[] {"1", "5", "11", "12"}, level11, level12, null, level14); - assertRoot(executionRoot, createExpectedNodes(new String[] {""}, level1)); - } - - /** - * Tests a tree of {@link IExecutionNode}s with two levels after root. - */ - @Test public void testNodesTwoLevel() throws ProofInputException { - // Create tree to test - Proof proof = new Proof("target", new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); - Node root = appendRoot(proof); - Node l1 = appendNode(proof, root); - Node l11 = appendNode(proof, l1); - Node l12 = appendNode(proof, l1); - Node l2 = appendNode(proof, root); - Node l21 = appendNode(proof, l2); - Node l22 = appendNode(proof, l2); - Node l23 = appendNode(proof, l2); - Node l3 = appendNode(proof, root); - Node l4 = appendNode(proof, root); - Node l41 = appendNode(proof, l4); - // Create execution test model - KeYlessStart executionRoot = new KeYlessStart("", null, false); - KeYlessStatement el1 = createStatement(executionRoot, l1); - createStatement(el1, l11); - createStatement(el1, l12); - KeYlessStatement el2 = createStatement(executionRoot, l2); - createStatement(el2, l21); - createStatement(el2, l22); - createStatement(el2, l23); - createStatement(executionRoot, l3); - KeYlessStatement el4 = createStatement(executionRoot, l4); - createStatement(el4, l41); - // Test tree - ExpectedNode[] level11 = createExpectedNodes("2", "3"); - ExpectedNode[] level12 = createExpectedNodes("5", "6", "7"); - ExpectedNode[] level14 = createExpectedNodes("10"); - ExpectedNode[] level1 = createExpectedNodes(new String[] {"1", "4", "8", "9"}, level11, level12, null, level14); - assertRoot(executionRoot, createExpectedNodes(new String[] {""}, level1)); - } - - /** - * Tests a tree of {@link IExecutionNode}s with one level after root. - */ - @Test public void testNodesOneLevel() throws ProofInputException { - // Create tree to test - Proof proof = new Proof("target", new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); - Node root = appendRoot(proof); - Node child1 = appendNode(proof, root); - Node child2 = appendNode(proof, root); - Node child3 = appendNode(proof, root); - Node child4 = appendNode(proof, root); - // Create execution test model - KeYlessStart executionRoot = new KeYlessStart("", null, false); - createStatement(executionRoot, child1); - createStatement(executionRoot, child2); - createStatement(executionRoot, child3); - createStatement(executionRoot, child4); - // Test tree - ExpectedNode[] level1 = createExpectedNodes("1", "2", "3", "4"); - assertRoot(executionRoot, createExpectedNodes(new String[] {""}, level1)); - } - - /** - * Creates a new {@link KeYlessStatement} which represents the given {@link Node} in KeY's proof tree. - * @param parent The parent {@link AbstractKeYlessExecutionNode}. - * @param proofNode The {@link Node} in KeY's proof tree to represent. - * @return The created {@link KeYlessStatement}. - */ - protected KeYlessStatement createStatement(AbstractKeYlessExecutionNode parent, Node proofNode) { - KeYlessStatement statement = new KeYlessStatement(parent, proofNode.serialNr() + "", null, false); - parent.addChild(statement); - return statement; - } + /** + * Tests a tree of {@link IExecutionNode}s with three levels after root. + */ + @Test + public void testNodesThreeLevel() throws ProofInputException { + // Create tree to test + Proof proof = new Proof("target", + new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); + Node root = appendRoot(proof); + Node l1 = appendNode(proof, root); + Node l11 = appendNode(proof, l1); + Node l111 = appendNode(proof, l11); + Node l12 = appendNode(proof, l1); + Node l2 = appendNode(proof, root); + Node l21 = appendNode(proof, l2); + Node l22 = appendNode(proof, l2); + Node l221 = appendNode(proof, l22); + Node l222 = appendNode(proof, l22); + Node l23 = appendNode(proof, l2); + Node l3 = appendNode(proof, root); + Node l4 = appendNode(proof, root); + Node l41 = appendNode(proof, l4); + // Create execution test model + KeYlessStart executionRoot = new KeYlessStart("", null, false); + KeYlessStatement el1 = createStatement(executionRoot, l1); + KeYlessStatement el11 = createStatement(el1, l11); + createStatement(el11, l111); + createStatement(el1, l12); + KeYlessStatement el2 = createStatement(executionRoot, l2); + createStatement(el2, l21); + KeYlessStatement el22 = createStatement(el2, l22); + createStatement(el22, l221); + createStatement(el22, l222); + createStatement(el2, l23); + createStatement(executionRoot, l3); + KeYlessStatement el4 = createStatement(executionRoot, l4); + createStatement(el4, l41); + // Test tree + ExpectedNode[] level111 = createExpectedNodes("3"); + ExpectedNode[] level11 = createExpectedNodes(new String[] { "2", "4" }, level111, null); + ExpectedNode[] level122 = createExpectedNodes("8", "9"); + ExpectedNode[] level12 = + createExpectedNodes(new String[] { "6", "7", "10" }, null, level122, null); + ExpectedNode[] level14 = createExpectedNodes("13"); + ExpectedNode[] level1 = createExpectedNodes(new String[] { "1", "5", "11", "12" }, level11, + level12, null, level14); + assertRoot(executionRoot, createExpectedNodes(new String[] { "" }, level1)); + } - /** - * Tests only a root {@link IExecutionNode}. - */ - @Test public void testEmptyRoot() throws ProofInputException { - // Create tree to test - Proof proof = new Proof("target", new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); - Node root = appendRoot(proof); - // Create execution test model - TreeSettings settings = new TreeSettings(false, false, false, false, false); - ExecutionStart executionRoot = new ExecutionStart(settings, root); - // Test tree - assertRoot(executionRoot, createExpectedNodes("")); - } - - /** - * Makes sure that a {@link ExecutionNodePreorderIterator} which iterates over the given - * {@link IExecutionNode} returns nodes in preorder iteration over the - * expected trees. - * @param element The {@link IExecutionNode} to iterate over. - * @param expectedRoots The expected values. - * @throws ProofInputException Occurred Exception. - */ - protected void assertRoot(IExecutionNode element, - ExpectedNode[] expectedRoots) throws ProofInputException { - ExecutionNodePreorderIterator iter = new ExecutionNodePreorderIterator(element); - assertExpectedNodes(iter, expectedRoots, false); - assertFalse(iter.hasNext()); - } - - /** - * Makes sure that the nodes returned by the given {@link ExecutionNodePreorderIterator} - * are equal to the defined model. - * @param iter The {@link ExecutionNodePreorderIterator} to test. - * @param expectedRoots The expected model. - * @param iterateOverSubtree Start new sub tree iteration at the current node? - * @throws ProofInputException Occurred Exception. - */ - protected void assertExpectedNodes(ExecutionNodePreorderIterator iter, - ExpectedNode[] expectedRoots, - boolean iterateOverSubtree) throws ProofInputException { - if (expectedRoots != null) { - assertNotNull(iter); - for (ExpectedNode node : expectedRoots) { - assertTrue(iter.hasNext()); - IExecutionNode next = iter.next(); - assertNotNull(next); - assertEquals(node.getExpectedName(), next.getName()); - if (iterateOverSubtree) { - assertRoot(next, new ExpectedNode[] {node}); + /** + * Tests a tree of {@link IExecutionNode}s with two levels after root. + */ + @Test + public void testNodesTwoLevel() throws ProofInputException { + // Create tree to test + Proof proof = new Proof("target", + new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); + Node root = appendRoot(proof); + Node l1 = appendNode(proof, root); + Node l11 = appendNode(proof, l1); + Node l12 = appendNode(proof, l1); + Node l2 = appendNode(proof, root); + Node l21 = appendNode(proof, l2); + Node l22 = appendNode(proof, l2); + Node l23 = appendNode(proof, l2); + Node l3 = appendNode(proof, root); + Node l4 = appendNode(proof, root); + Node l41 = appendNode(proof, l4); + // Create execution test model + KeYlessStart executionRoot = new KeYlessStart("", null, false); + KeYlessStatement el1 = createStatement(executionRoot, l1); + createStatement(el1, l11); + createStatement(el1, l12); + KeYlessStatement el2 = createStatement(executionRoot, l2); + createStatement(el2, l21); + createStatement(el2, l22); + createStatement(el2, l23); + createStatement(executionRoot, l3); + KeYlessStatement el4 = createStatement(executionRoot, l4); + createStatement(el4, l41); + // Test tree + ExpectedNode[] level11 = createExpectedNodes("2", "3"); + ExpectedNode[] level12 = createExpectedNodes("5", "6", "7"); + ExpectedNode[] level14 = createExpectedNodes("10"); + ExpectedNode[] level1 = createExpectedNodes(new String[] { "1", "4", "8", "9" }, level11, + level12, null, level14); + assertRoot(executionRoot, createExpectedNodes(new String[] { "" }, level1)); + } + + /** + * Tests a tree of {@link IExecutionNode}s with one level after root. + */ + @Test + public void testNodesOneLevel() throws ProofInputException { + // Create tree to test + Proof proof = new Proof("target", + new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); + Node root = appendRoot(proof); + Node child1 = appendNode(proof, root); + Node child2 = appendNode(proof, root); + Node child3 = appendNode(proof, root); + Node child4 = appendNode(proof, root); + // Create execution test model + KeYlessStart executionRoot = new KeYlessStart("", null, false); + createStatement(executionRoot, child1); + createStatement(executionRoot, child2); + createStatement(executionRoot, child3); + createStatement(executionRoot, child4); + // Test tree + ExpectedNode[] level1 = createExpectedNodes("1", "2", "3", "4"); + assertRoot(executionRoot, createExpectedNodes(new String[] { "" }, level1)); + } + + /** + * Creates a new {@link KeYlessStatement} which represents the given {@link Node} in KeY's proof + * tree. + * + * @param parent The parent {@link AbstractKeYlessExecutionNode}. + * @param proofNode The {@link Node} in KeY's proof tree to represent. + * @return The created {@link KeYlessStatement}. + */ + protected KeYlessStatement createStatement(AbstractKeYlessExecutionNode parent, + Node proofNode) { + KeYlessStatement statement = + new KeYlessStatement(parent, proofNode.serialNr() + "", null, false); + parent.addChild(statement); + return statement; + } + + /** + * Tests only a root {@link IExecutionNode}. + */ + @Test + public void testEmptyRoot() throws ProofInputException { + // Create tree to test + Proof proof = new Proof("target", + new InitConfig(new Services(AbstractProfile.getDefaultProfile()))); + Node root = appendRoot(proof); + // Create execution test model + TreeSettings settings = new TreeSettings(false, false, false, false, false); + ExecutionStart executionRoot = new ExecutionStart(settings, root); + // Test tree + assertRoot(executionRoot, createExpectedNodes("")); + } + + /** + * Makes sure that a {@link ExecutionNodePreorderIterator} which iterates over the given + * {@link IExecutionNode} returns nodes in preorder iteration over the expected trees. + * + * @param element The {@link IExecutionNode} to iterate over. + * @param expectedRoots The expected values. + * @throws ProofInputException Occurred Exception. + */ + protected void assertRoot(IExecutionNode element, ExpectedNode[] expectedRoots) + throws ProofInputException { + ExecutionNodePreorderIterator iter = new ExecutionNodePreorderIterator(element); + assertExpectedNodes(iter, expectedRoots, false); + assertFalse(iter.hasNext()); + } + + /** + * Makes sure that the nodes returned by the given {@link ExecutionNodePreorderIterator} are + * equal to the defined model. + * + * @param iter The {@link ExecutionNodePreorderIterator} to test. + * @param expectedRoots The expected model. + * @param iterateOverSubtree Start new sub tree iteration at the current node? + * @throws ProofInputException Occurred Exception. + */ + protected void assertExpectedNodes(ExecutionNodePreorderIterator iter, + ExpectedNode[] expectedRoots, boolean iterateOverSubtree) throws ProofInputException { + if (expectedRoots != null) { + assertNotNull(iter); + for (ExpectedNode node : expectedRoots) { + assertTrue(iter.hasNext()); + IExecutionNode next = iter.next(); + assertNotNull(next); + assertEquals(node.getExpectedName(), next.getName()); + if (iterateOverSubtree) { + assertRoot(next, new ExpectedNode[] { node }); + } + assertExpectedNodes(iter, node.getExpectedChildren(), true); } - assertExpectedNodes(iter, node.getExpectedChildren(), true); - } - } - } - - /** - * Forms the expected tree. - * @author Martin Hentschel - */ - protected static class ExpectedNode { - /** - * The expected name. - */ - private final String expectedName; - - /** - * The expected children. - */ - private ExpectedNode[] expectedChildren; + } + } + + /** + * Forms the expected tree. + * + * @author Martin Hentschel + */ + protected static class ExpectedNode { + /** + * The expected name. + */ + private final String expectedName; + + /** + * The expected children. + */ + private ExpectedNode[] expectedChildren; + + /** + * Constructor. + * + * @param expectedName The expected name. + */ + public ExpectedNode(String expectedName) { + this.expectedName = expectedName; + } + + /** + * Constructor. + * + * @param expectedName The expected name. + * @param expectedChildren The expected children. + */ + public ExpectedNode(String expectedName, ExpectedNode[] expectedChildren) { + this.expectedName = expectedName; + this.expectedChildren = expectedChildren; + } + + /** + * Returns the expected name. + * + * @return The expected name. + */ + public String getExpectedName() { + return expectedName; + } + + /** + * Returns the expected children. + * + * @return The expected children. + */ + public ExpectedNode[] getExpectedChildren() { + return expectedChildren; + } + } - /** - * Constructor. - * @param expectedName The expected name. - */ - public ExpectedNode(String expectedName) { - this.expectedName = expectedName; - } + /** + * Creates new {@link ExpectedNode}s with the given names and children. + * + * @param expectedNames The given names. + * @param children The given children. + * @return The created {@link ExpectedNode}s. + */ + protected ExpectedNode[] createExpectedNodes(String[] expectedNames, + ExpectedNode[]... children) { + assertEquals(expectedNames.length, children.length); + List result = new LinkedList<>(); + for (int i = 0; i < expectedNames.length; i++) { + result.add(new ExpectedNode(expectedNames[i], children[i])); + } + return result.toArray(new ExpectedNode[0]); + } - /** - * Constructor. - * @param expectedName The expected name. - * @param expectedChildren The expected children. - */ - public ExpectedNode(String expectedName, ExpectedNode[] expectedChildren) { - this.expectedName = expectedName; - this.expectedChildren = expectedChildren; - } - - /** - * Returns the expected name. - * @return The expected name. - */ - public String getExpectedName() { - return expectedName; - } + /** + * Creates new {@link ExpectedNode}s with the given names. + * + * @param expectedNames The given names. + * @return The created {@link ExpectedNode}s. + */ + protected ExpectedNode[] createExpectedNodes(String... expectedNames) { + List result = new LinkedList<>(); + for (String name : expectedNames) { + result.add(new ExpectedNode(name)); + } + return result.toArray(new ExpectedNode[0]); + } - /** - * Returns the expected children. - * @return The expected children. - */ - public ExpectedNode[] getExpectedChildren() { - return expectedChildren; - } - } + /** + * Appends a new node to the given parent {@link Node}. + * + * @param proof The {@link Proof} which forms the test model. + * @param parent The parent {@link Node} to add to. + * @return The new created child {@link Node}. + */ + protected Node appendNode(Proof proof, Node parent) { + Node newChild = new Node(proof); + parent.add(newChild); + return newChild; + } - /** - * Creates new {@link ExpectedNode}s with the given names and children. - * @param expectedNames The given names. - * @param children The given children. - * @return The created {@link ExpectedNode}s. - */ - protected ExpectedNode[] createExpectedNodes(String[] expectedNames, ExpectedNode[]... children) { - assertEquals(expectedNames.length, children.length); - List result = new LinkedList<>(); - for (int i = 0; i < expectedNames.length; i++) { - result.add(new ExpectedNode(expectedNames[i], children[i])); - } - return result.toArray(new ExpectedNode[0]); - } - - /** - * Creates new {@link ExpectedNode}s with the given names. - * @param expectedNames The given names. - * @return The created {@link ExpectedNode}s. - */ - protected ExpectedNode[] createExpectedNodes(String... expectedNames) { - List result = new LinkedList<>(); - for (String name : expectedNames) { - result.add(new ExpectedNode(name)); - } - return result.toArray(new ExpectedNode[0]); - } - - /** - * Appends a new node to the given parent {@link Node}. - * @param proof The {@link Proof} which forms the test model. - * @param parent The parent {@link Node} to add to. - * @return The new created child {@link Node}. - */ - protected Node appendNode(Proof proof, Node parent) { - Node newChild = new Node(proof); - parent.add(newChild); - return newChild; - } - - /** - * Sets a new root {@link Node} on the proof. - * @param proof The {@link Proof} to set root on. - * @return The created root {@link Node}. - */ - protected Node appendRoot(Proof proof) { - Node root = new Node(proof); - proof.setRoot(root); - return root; - } -} \ No newline at end of file + /** + * Sets a new root {@link Node} on the proof. + * + * @param proof The {@link Proof} to set root on. + * @return The created root {@link Node}. + */ + protected Node appendRoot(Proof proof) { + Node root = new Node(proof); + proof.setRoot(root); + return root; + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodeWriterAndReader.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodeWriterAndReader.java index ec9657cc201..912df7c7f8a 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodeWriterAndReader.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionNodeWriterAndReader.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.proof.init.ProofInputException; @@ -21,212 +24,257 @@ /** * Tests {@link ExecutionNodeWriter} and {@link ExecutionNodeReader} + * * @author Martin Hentschel */ public class TestExecutionNodeWriterAndReader { - /** - * Tests the reading and writing process without variables and without call stack. - */ - @Test - public void testWritingAndReading_withoutVariables_and_withoutCallStack_withReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(false, false, true, true); - } - - /** - * Tests the reading and writing process without call stack. - */ - @Test public void testWritingAndReading_withoutCallStack_withReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(true, false, true, true); - } - - /** - * Tests the reading and writing process without variables. - */ - @Test public void testWritingAndReading_withoutVariables_withReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(false, true, true, true); - } - - /** - * Tests the reading and writing process. - */ - @Test public void testWritingAndReading_withReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(true, true, true, true); - } - - /** - * Tests the reading and writing process without variables and without call stack. - */ - @Test public void testWritingAndReading_withoutVariables_and_withoutCallStack_noReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(false, false, false, true); - } - - /** - * Tests the reading and writing process without call stack. - */ - @Test public void testWritingAndReading_withoutCallStack_noReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(true, false, false, false); - } - - /** - * Tests the reading and writing process without variables. - */ - @Test public void testWritingAndReading_withoutVariables_noReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(false, true, false, true); - } - - /** - * Tests the reading and writing process. - */ - @Test public void testWritingAndReading_noReturnValues() throws ProofInputException, ParserConfigurationException, SAXException, IOException { - doTestWritingAndReading(true, true, false, false); - } - - /** - * @param saveVariabes Save variables? - * @param saveCallStack Save call stack? - * @param saveReturnValues Save method return values? - * @param saveConstraints Save constraints? - */ - protected void doTestWritingAndReading(boolean saveVariabes, - boolean saveCallStack, - boolean saveReturnValues, - boolean saveConstraints) throws ProofInputException, ParserConfigurationException, SAXException, IOException { - // Create model - IExecutionNode expectedNode = createModel(); - // Serialize model to XML string - ExecutionNodeWriter writer = new ExecutionNodeWriter(); - String xml = writer.toXML(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, saveVariabes, saveCallStack, saveReturnValues, saveConstraints); - // Read from XML string - ExecutionNodeReader reader = new ExecutionNodeReader(); - IExecutionNode currentNode = reader.read(new ByteArrayInputStream(xml.getBytes(Charset.forName(ExecutionNodeWriter.DEFAULT_ENCODING)))); - TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); - // Serialize model to output stream - ByteArrayOutputStream out = new ByteArrayOutputStream(); - writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, out, saveVariabes, saveCallStack, saveReturnValues, saveConstraints); - // Read from input stream - currentNode = reader.read(new ByteArrayInputStream(out.toByteArray())); - TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); - // Serialize model to temporary file - File tempFile = File.createTempFile("TestExecutionNodeWriterAndReader", "testWritingAndReading"); - try { - tempFile.delete(); - writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, tempFile, saveVariabes, saveCallStack, saveReturnValues, saveConstraints); - assertTrue(tempFile.isFile()); - // Read from temporary file - currentNode = reader.read(tempFile); - TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); - } - finally { - tempFile.delete(); - } - } - - /** - * Creates an example symbolic execution tree. - * @return The root of the example symbolic execution tree. - */ - protected IExecutionNode createModel() { - KeYlessStart root = new KeYlessStart("start", "pc1", true); - root.addCallStackEntry(root); - KeYlessBranchCondition bc = new KeYlessBranchCondition(root, "bc", "pc2", false, "condition of bc", true, true, "myCustomBC"); - bc.addCallStackEntry(root); - bc.addCallStackEntry(bc); - root.addChild(bc); - KeYlessTermination tNormal = new KeYlessTermination(root, "t normal", "pc3", true, TerminationKind.NORMAL, true); - root.addChild(tNormal); - root.addTermination(tNormal); - KeYlessTermination tExceptional = new KeYlessTermination(root, "t exceptional", "pc4", false, TerminationKind.EXCEPTIONAL, false); - root.addChild(tExceptional); - root.addTermination(tExceptional); - KeYlessTermination tloop = new KeYlessTermination(root, "t loop", "pcLoopTermination", false, TerminationKind.LOOP_BODY, true); - root.addChild(tloop); - root.addTermination(tloop); - KeYlessBranchStatement bn = new KeYlessBranchStatement(root, "bn", "pc5", true, true); - bn.addCallStackEntry(root); - bn.addCallStackEntry(bc); - root.addChild(bn); - IExecutionConstraint constraint = new KeYlessConstraint("myConstraint"); - bn.addConstraint(constraint); - KeYlessVariable bnVar1 = new KeYlessVariable(null, true, "2", "bnVar1"); - bn.addVariable(bnVar1); - KeYlessValue bnVar1Value1 = new KeYlessValue(bnVar1, "myType1", "myValue1", "value of bnVar1", true, false, "c1"); - bnVar1.addValue(bnVar1Value1); - bnVar1Value1.addConstraint(new KeYlessConstraint("constraint of bnVar1")); - KeYlessValue bnVar1Value2 = new KeYlessValue(bnVar1, "myType2", "myValue2", "value of bnVar1", false, true, "c2"); - bnVar1.addValue(bnVar1Value2); - KeYlessVariable bnVar2 = new KeYlessVariable(null, false, null, "bnVar2"); - bn.addVariable(bnVar2); - KeYlessValue bnVar2Value = new KeYlessValue(bnVar2, "myTypeAgain", "myValueAgain", "value of bnVar2", false, true, "c3"); - bnVar2.addValue(bnVar2Value); - KeYlessLoopStatement ln = new KeYlessLoopStatement(root, "ln", "pc6", true, false); - root.addChild(ln); - ln.addCompletedBlock(bn, "My Block Completion Condition!"); - bn.addBlockCompletion(ln); - KeYlessLoopCondition lc = new KeYlessLoopCondition(ln, "lc", "pc7", false, true); - ln.addChild(lc); - KeYlessMethodCall mc = new KeYlessMethodCall(ln, "mc", "pc8", false); - mc.addCallStackEntry(mc); - ln.addChild(mc); - KeYlessMethodReturn mr = new KeYlessMethodReturn(mc, "mr", "pc9", true, "mc with return value", "mc(arg)", "mc(arg) with return value", true, "myMethodReturnCondition"); - mr.addReturnValue(new KeYlessMethodReturnValue("rv1", "rv1String", false, null)); - mr.addReturnValue(new KeYlessMethodReturnValue("rv2", "rv2String", true, "c2String")); - mr.addCallStackEntry(mc); - mc.addChild(mr); - mc.addMethodReturn(mr); - KeYlessBlockContract blockContract = new KeYlessBlockContract(mr, "blockContract", "formatedPathCondition", true, true); - mr.addChild(blockContract); - KeYlessJoin join = new KeYlessJoin(mr, "join", "formatedPathConditionOfJoin", false, true); - mr.addChild(join); - - KeYlessVariable mrVar1 = new KeYlessVariable(null, true, "2", "mrVar1"); - mr.addCallStateVariable(mrVar1); - KeYlessValue mrVar1Value1 = new KeYlessValue(mrVar1, "myType1", "myValue1", "value of mrVar1", true, false, "c1"); - mrVar1.addValue(mrVar1Value1); - KeYlessVariable mrVar1child1 = new KeYlessVariable(mrVar1Value1, true, "2", "mrVar1child1"); - mrVar1Value1.addChildVariable(mrVar1child1); - KeYlessValue mrVar1child1Value1 = new KeYlessValue(mrVar1child1, "myType2", "myValue1child1", "value of mrVar1child1", true, false, "c2"); - mrVar1child1.addValue(mrVar1child1Value1); - - KeYlessExceptionalMethodReturn emr = new KeYlessExceptionalMethodReturn(mc, "emr", "pcExceptional", true, "mc(arg)", "myExceptionalMethodReturnCondition"); - emr.addCallStackEntry(mc); - mc.addChild(emr); - mc.addMethodReturn(emr); - KeYlessOperationContract contract = new KeYlessOperationContract(root, "useOperationContract", "pcUse", true, false, true, false, "ResultTerm", "ExceptionTerm", "SelfTerm", "ParamA, ParamB"); - root.addChild(contract); - KeYlessLoopInvariant invariant = new KeYlessLoopInvariant(root, "useLoppInvariant", "pcUseLoopInvariant", false, true); - root.addChild(invariant); - KeYlessStatement s = new KeYlessStatement(root, "s", "pc10", true); - root.addChild(s); - KeYlessVariable sVar1 = new KeYlessVariable(null, true, "2", "sVar1"); - s.addVariable(sVar1); - KeYlessValue sVar1Value = new KeYlessValue(sVar1, "myType", "myValue", "value of sVar1", false, false, "c4"); - sVar1.addValue(sVar1Value); - KeYlessVariable sVar1_1 = new KeYlessVariable(sVar1Value, true, "2", "sVar1_1"); - sVar1Value.addChildVariable(sVar1_1); - KeYlessValue sVar1_1Value = new KeYlessValue(sVar1_1, "myType", "myValue", "value of sVar1_1", true, true, "c5"); - sVar1_1.addValue(sVar1_1Value); - KeYlessVariable sVar1_1_1 = new KeYlessVariable(sVar1_1Value, true, "1", "sVar1_1_1"); - sVar1_1Value.addChildVariable(sVar1_1_1); - KeYlessValue sVar1_1_1Value = new KeYlessValue(sVar1_1_1, "myType", "myValue", "value of sVar1_1_1", true, false, "c6"); - sVar1_1_1.addValue(sVar1_1_1Value); - KeYlessVariable sVar1_2 = new KeYlessVariable(sVar1Value, true, "2", "sVar1_2"); - sVar1Value.addChildVariable(sVar1_2); - KeYlessValue sVar1_2Value = new KeYlessValue(sVar1_2, "myType", "myValue", "value of sVar1_2", false, true, "c7"); - sVar1_2.addValue(sVar1_2Value); - KeYlessVariable sVar1_2_1 = new KeYlessVariable(sVar1_2Value, true, "2", "sVar1_2_1"); - sVar1_2Value.addChildVariable(sVar1_2_1); - KeYlessValue sVar1_2_1Value = new KeYlessValue(sVar1_2_1, "myType", "myValue", "value of sVar1_2_1", false, false, "c8"); - sVar1_2_1.addValue(sVar1_2_1Value); - KeYlessVariable sVar1_2_2 = new KeYlessVariable(sVar1_2Value, true, "2", "sVar1_2_2"); - sVar1_2Value.addChildVariable(sVar1_2_2); - KeYlessValue sVar1_2_2Value = new KeYlessValue(sVar1_2_2, "myType", "myValue", "value of sVar1_2_2", true, true, "c9"); - sVar1_2_2.addValue(sVar1_2_2Value); - - KeYLessLink link = new KeYLessLink(); - link.setSource(emr); - emr.addOutgoingLink(link); - link.setTarget(blockContract); - blockContract.addIncomingLink(link); - return root; - } -} \ No newline at end of file + /** + * Tests the reading and writing process without variables and without call stack. + */ + @Test + public void testWritingAndReading_withoutVariables_and_withoutCallStack_withReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(false, false, true, true); + } + + /** + * Tests the reading and writing process without call stack. + */ + @Test + public void testWritingAndReading_withoutCallStack_withReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(true, false, true, true); + } + + /** + * Tests the reading and writing process without variables. + */ + @Test + public void testWritingAndReading_withoutVariables_withReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(false, true, true, true); + } + + /** + * Tests the reading and writing process. + */ + @Test + public void testWritingAndReading_withReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(true, true, true, true); + } + + /** + * Tests the reading and writing process without variables and without call stack. + */ + @Test + public void testWritingAndReading_withoutVariables_and_withoutCallStack_noReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(false, false, false, true); + } + + /** + * Tests the reading and writing process without call stack. + */ + @Test + public void testWritingAndReading_withoutCallStack_noReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(true, false, false, false); + } + + /** + * Tests the reading and writing process without variables. + */ + @Test + public void testWritingAndReading_withoutVariables_noReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(false, true, false, true); + } + + /** + * Tests the reading and writing process. + */ + @Test + public void testWritingAndReading_noReturnValues() + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + doTestWritingAndReading(true, true, false, false); + } + + /** + * @param saveVariabes Save variables? + * @param saveCallStack Save call stack? + * @param saveReturnValues Save method return values? + * @param saveConstraints Save constraints? + */ + protected void doTestWritingAndReading(boolean saveVariabes, boolean saveCallStack, + boolean saveReturnValues, boolean saveConstraints) + throws ProofInputException, ParserConfigurationException, SAXException, IOException { + // Create model + IExecutionNode expectedNode = createModel(); + // Serialize model to XML string + ExecutionNodeWriter writer = new ExecutionNodeWriter(); + String xml = writer.toXML(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, saveVariabes, + saveCallStack, saveReturnValues, saveConstraints); + // Read from XML string + ExecutionNodeReader reader = new ExecutionNodeReader(); + IExecutionNode currentNode = reader.read(new ByteArrayInputStream( + xml.getBytes(Charset.forName(ExecutionNodeWriter.DEFAULT_ENCODING)))); + TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, + saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); + // Serialize model to output stream + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, out, saveVariabes, + saveCallStack, saveReturnValues, saveConstraints); + // Read from input stream + currentNode = reader.read(new ByteArrayInputStream(out.toByteArray())); + TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, + saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); + // Serialize model to temporary file + File tempFile = + File.createTempFile("TestExecutionNodeWriterAndReader", "testWritingAndReading"); + try { + tempFile.delete(); + writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, tempFile, saveVariabes, + saveCallStack, saveReturnValues, saveConstraints); + assertTrue(tempFile.isFile()); + // Read from temporary file + currentNode = reader.read(tempFile); + TestSymbolicExecutionTreeBuilder.assertExecutionNodes(expectedNode, currentNode, + saveVariabes, saveCallStack, true, saveReturnValues, saveConstraints); + } finally { + tempFile.delete(); + } + } + + /** + * Creates an example symbolic execution tree. + * + * @return The root of the example symbolic execution tree. + */ + protected IExecutionNode createModel() { + KeYlessStart root = new KeYlessStart("start", "pc1", true); + root.addCallStackEntry(root); + KeYlessBranchCondition bc = new KeYlessBranchCondition(root, "bc", "pc2", false, + "condition of bc", true, true, "myCustomBC"); + bc.addCallStackEntry(root); + bc.addCallStackEntry(bc); + root.addChild(bc); + KeYlessTermination tNormal = + new KeYlessTermination(root, "t normal", "pc3", true, TerminationKind.NORMAL, true); + root.addChild(tNormal); + root.addTermination(tNormal); + KeYlessTermination tExceptional = new KeYlessTermination(root, "t exceptional", "pc4", + false, TerminationKind.EXCEPTIONAL, false); + root.addChild(tExceptional); + root.addTermination(tExceptional); + KeYlessTermination tloop = new KeYlessTermination(root, "t loop", "pcLoopTermination", + false, TerminationKind.LOOP_BODY, true); + root.addChild(tloop); + root.addTermination(tloop); + KeYlessBranchStatement bn = new KeYlessBranchStatement(root, "bn", "pc5", true, true); + bn.addCallStackEntry(root); + bn.addCallStackEntry(bc); + root.addChild(bn); + IExecutionConstraint constraint = new KeYlessConstraint("myConstraint"); + bn.addConstraint(constraint); + KeYlessVariable bnVar1 = new KeYlessVariable(null, true, "2", "bnVar1"); + bn.addVariable(bnVar1); + KeYlessValue bnVar1Value1 = new KeYlessValue(bnVar1, "myType1", "myValue1", + "value of bnVar1", true, false, "c1"); + bnVar1.addValue(bnVar1Value1); + bnVar1Value1.addConstraint(new KeYlessConstraint("constraint of bnVar1")); + KeYlessValue bnVar1Value2 = new KeYlessValue(bnVar1, "myType2", "myValue2", + "value of bnVar1", false, true, "c2"); + bnVar1.addValue(bnVar1Value2); + KeYlessVariable bnVar2 = new KeYlessVariable(null, false, null, "bnVar2"); + bn.addVariable(bnVar2); + KeYlessValue bnVar2Value = new KeYlessValue(bnVar2, "myTypeAgain", "myValueAgain", + "value of bnVar2", false, true, "c3"); + bnVar2.addValue(bnVar2Value); + KeYlessLoopStatement ln = new KeYlessLoopStatement(root, "ln", "pc6", true, false); + root.addChild(ln); + ln.addCompletedBlock(bn, "My Block Completion Condition!"); + bn.addBlockCompletion(ln); + KeYlessLoopCondition lc = new KeYlessLoopCondition(ln, "lc", "pc7", false, true); + ln.addChild(lc); + KeYlessMethodCall mc = new KeYlessMethodCall(ln, "mc", "pc8", false); + mc.addCallStackEntry(mc); + ln.addChild(mc); + KeYlessMethodReturn mr = + new KeYlessMethodReturn(mc, "mr", "pc9", true, "mc with return value", "mc(arg)", + "mc(arg) with return value", true, "myMethodReturnCondition"); + mr.addReturnValue(new KeYlessMethodReturnValue("rv1", "rv1String", false, null)); + mr.addReturnValue(new KeYlessMethodReturnValue("rv2", "rv2String", true, "c2String")); + mr.addCallStackEntry(mc); + mc.addChild(mr); + mc.addMethodReturn(mr); + KeYlessBlockContract blockContract = + new KeYlessBlockContract(mr, "blockContract", "formatedPathCondition", true, true); + mr.addChild(blockContract); + KeYlessJoin join = new KeYlessJoin(mr, "join", "formatedPathConditionOfJoin", false, true); + mr.addChild(join); + + KeYlessVariable mrVar1 = new KeYlessVariable(null, true, "2", "mrVar1"); + mr.addCallStateVariable(mrVar1); + KeYlessValue mrVar1Value1 = new KeYlessValue(mrVar1, "myType1", "myValue1", + "value of mrVar1", true, false, "c1"); + mrVar1.addValue(mrVar1Value1); + KeYlessVariable mrVar1child1 = new KeYlessVariable(mrVar1Value1, true, "2", "mrVar1child1"); + mrVar1Value1.addChildVariable(mrVar1child1); + KeYlessValue mrVar1child1Value1 = new KeYlessValue(mrVar1child1, "myType2", + "myValue1child1", "value of mrVar1child1", true, false, "c2"); + mrVar1child1.addValue(mrVar1child1Value1); + + KeYlessExceptionalMethodReturn emr = new KeYlessExceptionalMethodReturn(mc, "emr", + "pcExceptional", true, "mc(arg)", "myExceptionalMethodReturnCondition"); + emr.addCallStackEntry(mc); + mc.addChild(emr); + mc.addMethodReturn(emr); + KeYlessOperationContract contract = + new KeYlessOperationContract(root, "useOperationContract", "pcUse", true, false, + true, false, "ResultTerm", "ExceptionTerm", "SelfTerm", "ParamA, ParamB"); + root.addChild(contract); + KeYlessLoopInvariant invariant = new KeYlessLoopInvariant(root, "useLoppInvariant", + "pcUseLoopInvariant", false, true); + root.addChild(invariant); + KeYlessStatement s = new KeYlessStatement(root, "s", "pc10", true); + root.addChild(s); + KeYlessVariable sVar1 = new KeYlessVariable(null, true, "2", "sVar1"); + s.addVariable(sVar1); + KeYlessValue sVar1Value = + new KeYlessValue(sVar1, "myType", "myValue", "value of sVar1", false, false, "c4"); + sVar1.addValue(sVar1Value); + KeYlessVariable sVar1_1 = new KeYlessVariable(sVar1Value, true, "2", "sVar1_1"); + sVar1Value.addChildVariable(sVar1_1); + KeYlessValue sVar1_1Value = new KeYlessValue(sVar1_1, "myType", "myValue", + "value of sVar1_1", true, true, "c5"); + sVar1_1.addValue(sVar1_1Value); + KeYlessVariable sVar1_1_1 = new KeYlessVariable(sVar1_1Value, true, "1", "sVar1_1_1"); + sVar1_1Value.addChildVariable(sVar1_1_1); + KeYlessValue sVar1_1_1Value = new KeYlessValue(sVar1_1_1, "myType", "myValue", + "value of sVar1_1_1", true, false, "c6"); + sVar1_1_1.addValue(sVar1_1_1Value); + KeYlessVariable sVar1_2 = new KeYlessVariable(sVar1Value, true, "2", "sVar1_2"); + sVar1Value.addChildVariable(sVar1_2); + KeYlessValue sVar1_2Value = new KeYlessValue(sVar1_2, "myType", "myValue", + "value of sVar1_2", false, true, "c7"); + sVar1_2.addValue(sVar1_2Value); + KeYlessVariable sVar1_2_1 = new KeYlessVariable(sVar1_2Value, true, "2", "sVar1_2_1"); + sVar1_2Value.addChildVariable(sVar1_2_1); + KeYlessValue sVar1_2_1Value = new KeYlessValue(sVar1_2_1, "myType", "myValue", + "value of sVar1_2_1", false, false, "c8"); + sVar1_2_1.addValue(sVar1_2_1Value); + KeYlessVariable sVar1_2_2 = new KeYlessVariable(sVar1_2Value, true, "2", "sVar1_2_2"); + sVar1_2Value.addChildVariable(sVar1_2_2); + KeYlessValue sVar1_2_2Value = new KeYlessValue(sVar1_2_2, "myType", "myValue", + "value of sVar1_2_2", true, true, "c9"); + sVar1_2_2.addValue(sVar1_2_2Value); + + KeYLessLink link = new KeYLessLink(); + link.setSource(emr); + emr.addOutgoingLink(link); + link.setTarget(blockContract); + blockContract.addIncomingLink(link); + return root; + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionVariableExtractor.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionVariableExtractor.java index b5d4102797d..93a6720d3c8 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionVariableExtractor.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestExecutionVariableExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.symbolic_execution.ExecutionVariableExtractor; @@ -7,440 +10,215 @@ /** * Tests for {@link ExecutionVariableExtractor}. + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) public class TestExecutionVariableExtractor extends AbstractSymbolicExecutionTestCase { - /** - * Tests example: /set/variablesEmptyArrayCreationTest - */ - @Test - public void testVariablesEmptyArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", - "EmptyArrayCreationTest", - "main", - "obj != null & n == 0", - "/set/variablesEmptyArrayCreationTest/oracle/EmptyArrayCreationTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variablesNonSimpleArrayCreationTest - */ - @Test public void testVariablesNonSimpleArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesNonSimpleArrayCreationTest/test/NonSimpleArrayCreationTest.java", - "NonSimpleArrayCreationTest", - "main", - "n >= 4 & instance != null & instance.value == 100", - "/set/variablesNonSimpleArrayCreationTest/oracle/NonSimpleArrayCreationTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variablesNonSimpleArrayAssignmentTest - */ - @Test public void testVariablesNonSimpleArrayAssignmentTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesNonSimpleArrayAssignmentTest/test/NonSimpleArrayAssignmentTest.java", - "NonSimpleArrayAssignmentTest", - "main", - "array != null & array.length >= 4", - "/set/variablesNonSimpleArrayAssignmentTest/oracle/NonSimpleArrayAssignmentTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variablesArrayCreationInstanceTest - */ - @Test public void testVariablesArrayCreationInstanceTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayCreationInstanceTest/test/ArrayCreationInstanceTest.java", - "ArrayCreationInstanceTest", - "main", - "obj != null & n >= 4", - "/set/variablesArrayCreationInstanceTest/oracle/ArrayCreationInstanceTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variablesArrayAssignmentTest - */ - @Test public void testVariablesArrayAssignmentTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayAssignmentTest/test/ArrayAssignmentTest.java", - "ArrayAssignmentTest", - "main", - "array != null & array.length >= 4", - "/set/variablesArrayAssignmentTest/oracle/ArrayAssignmentTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variablesArrayCreationTest - */ - @Test public void testVariablesArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayCreationTest/test/ArrayCreationTest.java", - "ArrayCreationTest", - "main", - "n >= 4", - "/set/variablesArrayCreationTest/oracle/ArrayCreationTest_Sequent.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false); - } - - /** - * Tests example: /set/variableVariableMethodContractTest - */ - @Test public void testVariableMethodContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/variableVariableMethodContractTest/test/VariableMethodContractTest.java", - "VariableMethodContractTest", - "findMax", - null, + /** + * Tests example: /set/variablesEmptyArrayCreationTest + */ + @Test + public void testVariablesEmptyArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", + "EmptyArrayCreationTest", "main", "obj != null & n == 0", + "/set/variablesEmptyArrayCreationTest/oracle/EmptyArrayCreationTest_Sequent.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, true, false); + } + + /** + * Tests example: /set/variablesNonSimpleArrayCreationTest + */ + @Test + public void testVariablesNonSimpleArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesNonSimpleArrayCreationTest/test/NonSimpleArrayCreationTest.java", + "NonSimpleArrayCreationTest", "main", + "n >= 4 & instance != null & instance.value == 100", + "/set/variablesNonSimpleArrayCreationTest/oracle/NonSimpleArrayCreationTest_Sequent.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, true, false); + } + + /** + * Tests example: /set/variablesNonSimpleArrayAssignmentTest + */ + @Test + public void testVariablesNonSimpleArrayAssignmentTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesNonSimpleArrayAssignmentTest/test/NonSimpleArrayAssignmentTest.java", + "NonSimpleArrayAssignmentTest", "main", "array != null & array.length >= 4", + "/set/variablesNonSimpleArrayAssignmentTest/oracle/NonSimpleArrayAssignmentTest_Sequent.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, true, false); + } + + /** + * Tests example: /set/variablesArrayCreationInstanceTest + */ + @Test + public void testVariablesArrayCreationInstanceTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayCreationInstanceTest/test/ArrayCreationInstanceTest.java", + "ArrayCreationInstanceTest", "main", "obj != null & n >= 4", + "/set/variablesArrayCreationInstanceTest/oracle/ArrayCreationInstanceTest_Sequent.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, true, false); + } + + /** + * Tests example: /set/variablesArrayAssignmentTest + */ + @Test + public void testVariablesArrayAssignmentTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayAssignmentTest/test/ArrayAssignmentTest.java", + "ArrayAssignmentTest", "main", "array != null & array.length >= 4", + "/set/variablesArrayAssignmentTest/oracle/ArrayAssignmentTest_Sequent.xml", false, + true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, true, false); + } + + /** + * Tests example: /set/variablesArrayCreationTest + */ + @Test + public void testVariablesArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayCreationTest/test/ArrayCreationTest.java", "ArrayCreationTest", + "main", "n >= 4", + "/set/variablesArrayCreationTest/oracle/ArrayCreationTest_Sequent.xml", false, true, + false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, true, false); + } + + /** + * Tests example: /set/variableVariableMethodContractTest + */ + @Test + public void testVariableMethodContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/variableVariableMethodContractTest/test/VariableMethodContractTest.java", + "VariableMethodContractTest", "findMax", null, "/set/variableVariableMethodContractTest/oracle/VariableMethodContractTest.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesConditionalCycle - */ - @Test public void testVariablesConditionalCycle() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesConditionalCycle/test/VariablesConditionalCycle.java", - "VariablesConditionalCycle", - "main", - null, - "/set/variablesConditionalCycle/oracle/VariablesConditionalCycle.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesSimpleCycle - */ - @Test public void testVariablesSimpleCycle() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesSimpleCycle/test/VariablesSimpleCycle.java", - "VariablesSimpleCycle", - "main", - "something != null", - "/set/variablesSimpleCycle/oracle/VariablesSimpleCycle.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesWithQuantifier - */ - @Test public void testVariablesWithQuantifier() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesWithQuantifier/test/EnoughInfoReturn.java", - "EnoughInfoReturn", - "passwordChecker", - "passwords != null", - "/set/variablesWithQuantifier/oracle/EnoughInfoReturn.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesVariableArrayIndex - */ - @Test public void testVariableArrayIndex() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesVariableArrayIndex/test/VariableArrayIndex.java", - "VariableArrayIndex", - "magic", + false, true, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, true, true); + } + + /** + * Tests example: /set/variablesConditionalCycle + */ + @Test + public void testVariablesConditionalCycle() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesConditionalCycle/test/VariablesConditionalCycle.java", + "VariablesConditionalCycle", "main", null, + "/set/variablesConditionalCycle/oracle/VariablesConditionalCycle.xml", false, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, true, true); + } + + /** + * Tests example: /set/variablesSimpleCycle + */ + @Test + public void testVariablesSimpleCycle() throws Exception { + doSETTest(testCaseDirectory, "/set/variablesSimpleCycle/test/VariablesSimpleCycle.java", + "VariablesSimpleCycle", "main", "something != null", + "/set/variablesSimpleCycle/oracle/VariablesSimpleCycle.xml", false, true, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, true, true); + } + + /** + * Tests example: /set/variablesWithQuantifier + */ + @Test + public void testVariablesWithQuantifier() throws Exception { + doSETTest(testCaseDirectory, "/set/variablesWithQuantifier/test/EnoughInfoReturn.java", + "EnoughInfoReturn", "passwordChecker", "passwords != null", + "/set/variablesWithQuantifier/oracle/EnoughInfoReturn.xml", false, true, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, false, + false, false, true, true); + } + + /** + * Tests example: /set/variablesVariableArrayIndex + */ + @Test + public void testVariableArrayIndex() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesVariableArrayIndex/test/VariableArrayIndex.java", + "VariableArrayIndex", "magic", "array != null && array.length >= 1 && index >= 0 && index < array.length", - "/set/variablesVariableArrayIndex/oracle/VariableArrayIndex.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } + "/set/variablesVariableArrayIndex/oracle/VariableArrayIndex.xml", false, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, true, true); + } + + /** + * Tests example: /set/variablesConditionalValuesTest + */ + @Test + public void testVariablesConditionalValuesTest_next() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesConditionalValuesTest/test/ConditionalValuesTest.java", + "ConditionalValuesTest", "mainNext", null, + "/set/variablesConditionalValuesTest/oracle/ConditionalValuesTest_next.xml", false, + true, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, true, true); + } + + /** + * Tests example: /set/variablesConditionalValuesTest + */ + @Test + public void testVariablesConditionalValuesTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesConditionalValuesTest/test/ConditionalValuesTest.java", + "ConditionalValuesTest", "main", null, + "/set/variablesConditionalValuesTest/oracle/ConditionalValuesTest.xml", false, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, true, true); + } + + /** + * Tests example: /set/variableVariablesArrayTest + */ + @Test + public void testVariableVariablesArrayTest() throws Exception { + doSETTest(testCaseDirectory, "/set/variableVariablesArrayTest/test/VariablesArrayTest.java", + "VariablesArrayTest", "arrayTest", null, + "/set/variableVariablesArrayTest/oracle/VariablesArrayTest.xml", false, true, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, true, true); + } + + /** + * Tests example: /set/variablesLocalVariablesTest + */ + @Test + public void testVariablesLocalVariablesTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesLocalVariablesTest/test/LocalVariablesTest.java", + "LocalVariablesTest", "main", null, + "/set/variablesLocalVariablesTest/oracle/LocalVariablesTest.xml", false, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, true, true); + } - /** - * Tests example: /set/variablesConditionalValuesTest - */ - @Test public void testVariablesConditionalValuesTest_next() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesConditionalValuesTest/test/ConditionalValuesTest.java", - "ConditionalValuesTest", - "mainNext", - null, - "/set/variablesConditionalValuesTest/oracle/ConditionalValuesTest_next.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesConditionalValuesTest - */ - @Test public void testVariablesConditionalValuesTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesConditionalValuesTest/test/ConditionalValuesTest.java", - "ConditionalValuesTest", - "main", - null, - "/set/variablesConditionalValuesTest/oracle/ConditionalValuesTest.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variableVariablesArrayTest - */ - @Test public void testVariableVariablesArrayTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/variableVariablesArrayTest/test/VariablesArrayTest.java", - "VariablesArrayTest", - "arrayTest", - null, - "/set/variableVariablesArrayTest/oracle/VariablesArrayTest.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesLocalVariablesTest - */ - @Test public void testVariablesLocalVariablesTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesLocalVariablesTest/test/LocalVariablesTest.java", - "LocalVariablesTest", - "main", - null, - "/set/variablesLocalVariablesTest/oracle/LocalVariablesTest.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } - - /** - * Tests example: /set/variablesUpdateVariablesTest - */ - @Test public void testUpdateVariablesTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesUpdateVariablesTest/test/UpdateVariablesTest.java", - "UpdateVariablesTest", - "main", - null, - "/set/variablesUpdateVariablesTest/oracle/UpdateVariablesTest.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - true, - true); - } + /** + * Tests example: /set/variablesUpdateVariablesTest + */ + @Test + public void testUpdateVariablesTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesUpdateVariablesTest/test/UpdateVariablesTest.java", + "UpdateVariablesTest", "main", null, + "/set/variablesUpdateVariablesTest/oracle/UpdateVariablesTest.xml", false, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, true, true); + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestParallelSiteProofs.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestParallelSiteProofs.java index 55069f5f2e4..76dc4c63994 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestParallelSiteProofs.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestParallelSiteProofs.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -21,230 +24,246 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** - * This test class makes sure that parallel site proofs are working. It is only - * verified that no exception is thrown and not that correct results are computed. + * This test class makes sure that parallel site proofs are working. It is only verified that no + * exception is thrown and not that correct results are computed. + * * @author Martin Hentschel */ public class TestParallelSiteProofs extends AbstractSymbolicExecutionTestCase { - private static final int NUMBER_OF_THREADS = 21; - - /** - * Tests parallel site proofs on a new instantiate proof after applying "resume" on it. - */ - @Test - @Disabled("Commented out for the moment as Hudson throws an OOM Exception") - public void xxxtestNewProof() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException, InterruptedException { - // Define test settings - String javaPathInkeyRepDirectory = "/set/magic42/test/Magic42.java"; - String containerTypeName = "Magic42"; - final String methodFullName = "compute"; - String oraclePathInBaseDirFile = "/set/magic42/oracle/Magic42.xml"; - // Create proof environment for symbolic execution - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - try { - // Resume - resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); - // Do test steps - doParallelSiteProofTest(env); - } - finally { - env.dispose(); - } - } - - /** - * Tests parallel site proofs on a proof reconstructed from a *.proof file. - */ - @Test public void testProofFile() throws ProblemLoaderException, InterruptedException { - // Define test settings - String javaPathInkeyRepDirectory = "/set/magic42/test/Magic42.proof"; - // Create proof environment for symbolic execution - SymbolicExecutionEnvironment env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, false, false, false, false, false, false, false, false, false, false, false); - try { - // Do test steps - doParallelSiteProofTest(env); - } - finally { - env.dispose(); - } - } - - /** - * Executes the test steps to make sure that parallel tests are working - * without thrown {@link Exception}s. - * @param env The {@link SymbolicExecutionEnvironment} to use. - */ - protected void doParallelSiteProofTest(SymbolicExecutionEnvironment env) throws InterruptedException { - // Create threads - List> threads = new LinkedList<>(); - ExecutionNodePreorderIterator iter = new ExecutionNodePreorderIterator(env.getBuilder().getStartNode()); - while (iter.hasNext() && threads.size() < NUMBER_OF_THREADS) { - IExecutionNode next = iter.next(); - if (next != null) { - threads.add(new ExecutionVariableSiteProofThread(next)); - } - if (next instanceof IExecutionMethodReturn) { - threads.add(new ExecutionReturnValueSiteProofThread((IExecutionMethodReturn)next)); - } - } - // Make sure that the correct number of threads are available - assertEquals(NUMBER_OF_THREADS, threads.size()); - // Start threads - for (SiteProofThread thread : threads) { - thread.start(); - } - // Wait for threads - waitForThreads(threads, 20 * 1000); - // Check result - for (SiteProofThread thread : threads) { - // Make sure that no exception is thrown. - if (thread.getException() != null) { - thread.getException().printStackTrace(); - Assertions.fail(thread.getException().getMessage()); - } - // Make sure that something was computed in site proofs. - Assertions.assertNotNull(thread.getResult()); - } - } - - /** - * Waits until the given {@link Thread}s have terminated. - * @param threads The {@link Thread}s to wait for. - */ - public static void waitForThreads(List> threads, long timeout) throws InterruptedException { - long start = System.currentTimeMillis(); - if (threads != null) { - for (SiteProofThread thread : threads) { - thread.join(timeout); - if (System.currentTimeMillis() > start + timeout) { - Assertions.fail("Timeout during wait for parallel site proofs."); + private static final int NUMBER_OF_THREADS = 21; + + /** + * Tests parallel site proofs on a new instantiate proof after applying "resume" on it. + */ + @Test + @Disabled("Commented out for the moment as Hudson throws an OOM Exception") + public void xxxtestNewProof() + throws ProofInputException, IOException, ParserConfigurationException, SAXException, + ProblemLoaderException, InterruptedException { + // Define test settings + String javaPathInkeyRepDirectory = "/set/magic42/test/Magic42.java"; + String containerTypeName = "Magic42"; + final String methodFullName = "compute"; + String oraclePathInBaseDirFile = "/set/magic42/oracle/Magic42.xml"; + // Create proof environment for symbolic execution + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, false); + try { + // Resume + resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); + // Do test steps + doParallelSiteProofTest(env); + } finally { + env.dispose(); + } + } + + /** + * Tests parallel site proofs on a proof reconstructed from a *.proof file. + */ + @Test + public void testProofFile() throws ProblemLoaderException, InterruptedException { + // Define test settings + String javaPathInkeyRepDirectory = "/set/magic42/test/Magic42.proof"; + // Create proof environment for symbolic execution + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + false, false, false, false, false, false, false, false, false, false, + false); + try { + // Do test steps + doParallelSiteProofTest(env); + } finally { + env.dispose(); + } + } + + /** + * Executes the test steps to make sure that parallel tests are working without thrown + * {@link Exception}s. + * + * @param env The {@link SymbolicExecutionEnvironment} to use. + */ + protected void doParallelSiteProofTest( + SymbolicExecutionEnvironment env) + throws InterruptedException { + // Create threads + List> threads = new LinkedList<>(); + ExecutionNodePreorderIterator iter = + new ExecutionNodePreorderIterator(env.getBuilder().getStartNode()); + while (iter.hasNext() && threads.size() < NUMBER_OF_THREADS) { + IExecutionNode next = iter.next(); + if (next != null) { + threads.add(new ExecutionVariableSiteProofThread(next)); + } + if (next instanceof IExecutionMethodReturn) { + threads.add(new ExecutionReturnValueSiteProofThread((IExecutionMethodReturn) next)); + } + } + // Make sure that the correct number of threads are available + assertEquals(NUMBER_OF_THREADS, threads.size()); + // Start threads + for (SiteProofThread thread : threads) { + thread.start(); + } + // Wait for threads + waitForThreads(threads, 20 * 1000); + // Check result + for (SiteProofThread thread : threads) { + // Make sure that no exception is thrown. + if (thread.getException() != null) { + thread.getException().printStackTrace(); + Assertions.fail(thread.getException().getMessage()); + } + // Make sure that something was computed in site proofs. + Assertions.assertNotNull(thread.getResult()); + } + } + + /** + * Waits until the given {@link Thread}s have terminated. + * + * @param threads The {@link Thread}s to wait for. + */ + public static void waitForThreads(List> threads, long timeout) + throws InterruptedException { + long start = System.currentTimeMillis(); + if (threads != null) { + for (SiteProofThread thread : threads) { + thread.join(timeout); + if (System.currentTimeMillis() > start + timeout) { + Assertions.fail("Timeout during wait for parallel site proofs."); + } + /* + * while (thread.isAlive()) { if (System.currentTimeMillis() > start + timeout) { + * Assertions.fail("Timeout during wait for parallel site proofs."); } try { + * Thread.sleep(100); } catch (InterruptedException e) { // Nothing to do. } } + */ + } + } + } + + /** + * Utility {@link Thread} to execute a parallel site proof. + * + * @author Martin Hentschel + */ + private static abstract class SiteProofThread extends Thread { + /** + * A possibly caught exception. + */ + private Exception exception; + + /** + * The result of the executed site proof. + */ + private T result; + + /** + * Returns the caught exception. + * + * @return The caught exception. + */ + public Exception getException() { + return exception; + } + + /** + * Sets the caught exception. + * + * @param exception The caught exception. + */ + protected void setException(Exception exception) { + this.exception = exception; + } + + /** + * Returns the result of the site proof. + * + * @return The site proof result. + */ + public T getResult() { + return result; + } + + /** + * Sets the result of the site proof. + * + * @param result The site proof result. + */ + protected void setResult(T result) { + this.result = result; + } + } + + /** + * A {@link Thread} which computes the variables of a given {@link IExecutionNode} via site + * proofs. + * + * @author Martin Hentschel + */ + private static class ExecutionVariableSiteProofThread + extends SiteProofThread { + /** + * The {@link IExecutionNode} to read variables from. + */ + private final IExecutionNode node; + + /** + * Constructor. + * + * @param node The {@link IExecutionNode} to read variables from. + */ + public ExecutionVariableSiteProofThread(IExecutionNode node) { + this.node = node; + } + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + setResult(node.getVariables()); + } catch (Exception e) { + setException(e); + } + } + } + + /** + * A {@link Thread} which computes the method return value of a given + * {@link IExecutionMethodReturn} via a site proof. + * + * @author Martin Hentschel + */ + private static class ExecutionReturnValueSiteProofThread extends SiteProofThread { + /** + * The {@link IExecutionMethodReturn} to read method return value from. + */ + private final IExecutionMethodReturn returnNode; + + /** + * Constructor + * + * @param returnNode The {@link IExecutionMethodReturn} to read method return value from. + */ + public ExecutionReturnValueSiteProofThread(IExecutionMethodReturn returnNode) { + this.returnNode = returnNode; + } + + /** + * {@inheritDoc} + */ + @Override + public void run() { + try { + setResult(returnNode.getNameIncludingReturnValue()); + } catch (Exception e) { + setException(e); } - /*while (thread.isAlive()) { - if (System.currentTimeMillis() > start + timeout) { - Assertions.fail("Timeout during wait for parallel site proofs."); - } - try { - Thread.sleep(100); - } - catch (InterruptedException e) { - // Nothing to do. - } - }*/ - } - } - } - - /** - * Utility {@link Thread} to execute a parallel site proof. - * @author Martin Hentschel - */ - private static abstract class SiteProofThread extends Thread { - /** - * A possibly caught exception. - */ - private Exception exception; - - /** - * The result of the executed site proof. - */ - private T result; - - /** - * Returns the caught exception. - * @return The caught exception. - */ - public Exception getException() { - return exception; - } - - /** - * Sets the caught exception. - * @param exception The caught exception. - */ - protected void setException(Exception exception) { - this.exception = exception; - } - - /** - * Returns the result of the site proof. - * @return The site proof result. - */ - public T getResult() { - return result; - } - - /** - * Sets the result of the site proof. - * @param result The site proof result. - */ - protected void setResult(T result) { - this.result = result; - } - } - - /** - * A {@link Thread} which computes the variables of a given {@link IExecutionNode} - * via site proofs. - * @author Martin Hentschel - */ - private static class ExecutionVariableSiteProofThread extends SiteProofThread { - /** - * The {@link IExecutionNode} to read variables from. - */ - private final IExecutionNode node; - - /** - * Constructor. - * @param node The {@link IExecutionNode} to read variables from. - */ - public ExecutionVariableSiteProofThread(IExecutionNode node) { - this.node = node; - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - setResult(node.getVariables()); - } - catch (Exception e) { - setException(e); - } - } - } - - /** - * A {@link Thread} which computes the method return value of a given - * {@link IExecutionMethodReturn} via a site proof. - * @author Martin Hentschel - */ - private static class ExecutionReturnValueSiteProofThread extends SiteProofThread { - /** - * The {@link IExecutionMethodReturn} to read method return value from. - */ - private final IExecutionMethodReturn returnNode; - - /** - * Constructor - * @param returnNode The {@link IExecutionMethodReturn} to read method return value from. - */ - public ExecutionReturnValueSiteProofThread(IExecutionMethodReturn returnNode) { - this.returnNode = returnNode; - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - setResult(returnNode.getNameIncludingReturnValue()); - } - catch (Exception e) { - setException(e); - } - } - } -} \ No newline at end of file + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicExecutionTreeBuilder.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicExecutionTreeBuilder.java index f4b5023c989..92e98fdc8f9 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicExecutionTreeBuilder.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicExecutionTreeBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -21,5297 +24,2616 @@ /** * Tests for {@link SymbolicExecutionTreeBuilder}, - * {@link ExecutedSymbolicExecutionTreeNodesStopCondition} and - * {@link SymbolicExecutionGoalChooser}. + * {@link ExecutedSymbolicExecutionTreeNodesStopCondition} and {@link SymbolicExecutionGoalChooser}. + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) @Tag("slow") public class TestSymbolicExecutionTreeBuilder extends AbstractSymbolicExecutionTestCase { - /** - * Tests example: /set/joinTest - */ - @Test - public void testJoinTestAfterBranchConditionWithWeakeningGoalNotVerified() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoalNotVerified.proof", - "/set/joinTest/oracle/JoinTestAfterBranchConditionWithWeakeningGoalNotVerified.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/joinTest - */ - @Test - public void testJoinTestAfterBranchConditionWithWeakeningGoalAndSubgoals() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoalAndSubgoals.proof", - "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and without weakening! - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/joinTest - */ - @Test - public void testJoinTestAfterBranchConditionWithWeakeningGoal() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoal.proof", - "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and without weakening! - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/joinTest - */ - @Test - public void testJoinTestAfterBranchCondition() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/joinTest/test/JoinTestAfterBranchCondition.proof", - "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and without weakening! - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/joinTest - */ - @Test - public void testJoinTestAfterAssignment() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/joinTest/test/JoinTestAfterAssignment.proof", - "/set/joinTest/oracle/JoinTestAfterAssignment.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesEmptyArrayCreationTest - */ - @Test - public void testVariablesEmptyArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", - "EmptyArrayCreationTest", - "main", - "obj != null & n == 0", - "/set/variablesEmptyArrayCreationTest/oracle/EmptyArrayCreationTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesNonSimpleArrayCreationTest - */ - @Test - public void testVariablesNonSimpleArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesNonSimpleArrayCreationTest/test/NonSimpleArrayCreationTest.java", - "NonSimpleArrayCreationTest", - "main", - "n >= 4 & instance != null & instance.value == 100", - "/set/variablesNonSimpleArrayCreationTest/oracle/NonSimpleArrayCreationTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesNonSimpleArrayAssignmentTest - */ - @Test - public void testVariablesNonSimpleArrayAssignmentTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesNonSimpleArrayAssignmentTest/test/NonSimpleArrayAssignmentTest.java", - "NonSimpleArrayAssignmentTest", - "main", - "array != null & array.length >= 4", - "/set/variablesNonSimpleArrayAssignmentTest/oracle/NonSimpleArrayAssignmentTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesArrayCreationInstanceTest - */ - @Test - public void testVariablesArrayCreationInstanceTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayCreationInstanceTest/test/ArrayCreationInstanceTest.java", - "ArrayCreationInstanceTest", - "main", - "obj != null & n >= 4", - "/set/variablesArrayCreationInstanceTest/oracle/ArrayCreationInstanceTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesArrayAssignmentTest - */ - @Test - public void testVariablesArrayAssignmentTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayAssignmentTest/test/ArrayAssignmentTest.java", - "ArrayAssignmentTest", - "main", - "array != null & array.length >= 4", - "/set/variablesArrayAssignmentTest/oracle/ArrayAssignmentTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/variablesArrayCreationTest - */ - @Test - public void testVariablesArrayCreationTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayCreationTest/test/ArrayCreationTest.java", - "ArrayCreationTest", - "main", - "n >= 4", - "/set/variablesArrayCreationTest/oracle/ArrayCreationTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/useOperationContractLightweightOperationContractTest - */ - @Test - public void testUseOperationContractLightweightOperationContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractLightweightOperationContractTest/test/LightweightOperationContractTest.java", - "LightweightOperationContractTest", - "main", - null, + /** + * Tests example: /set/joinTest + */ + @Test + public void testJoinTestAfterBranchConditionWithWeakeningGoalNotVerified() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoalNotVerified.proof", + "/set/joinTest/oracle/JoinTestAfterBranchConditionWithWeakeningGoalNotVerified.xml", + false, false, false, false, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/joinTest + */ + @Test + public void testJoinTestAfterBranchConditionWithWeakeningGoalAndSubgoals() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoalAndSubgoals.proof", + "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and + // without weakening! + false, false, false, false, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/joinTest + */ + @Test + public void testJoinTestAfterBranchConditionWithWeakeningGoal() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/joinTest/test/JoinTestAfterBranchConditionWithWeakeningGoal.proof", + "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and + // without weakening! + false, false, false, false, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/joinTest + */ + @Test + public void testJoinTestAfterBranchCondition() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/joinTest/test/JoinTestAfterBranchCondition.proof", + "/set/joinTest/oracle/JoinTestAfterBranchCondition.xml", // Same result: with and + // without weakening! + false, false, false, false, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/joinTest + */ + @Test + public void testJoinTestAfterAssignment() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/joinTest/test/JoinTestAfterAssignment.proof", + "/set/joinTest/oracle/JoinTestAfterAssignment.xml", false, false, false, false, + false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/variablesEmptyArrayCreationTest + */ + @Test + public void testVariablesEmptyArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", + "EmptyArrayCreationTest", "main", "obj != null & n == 0", + "/set/variablesEmptyArrayCreationTest/oracle/EmptyArrayCreationTest.xml", false, + true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, false); + } + + /** + * Tests example: /set/variablesNonSimpleArrayCreationTest + */ + @Test + public void testVariablesNonSimpleArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesNonSimpleArrayCreationTest/test/NonSimpleArrayCreationTest.java", + "NonSimpleArrayCreationTest", "main", + "n >= 4 & instance != null & instance.value == 100", + "/set/variablesNonSimpleArrayCreationTest/oracle/NonSimpleArrayCreationTest.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, false); + } + + /** + * Tests example: /set/variablesNonSimpleArrayAssignmentTest + */ + @Test + public void testVariablesNonSimpleArrayAssignmentTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesNonSimpleArrayAssignmentTest/test/NonSimpleArrayAssignmentTest.java", + "NonSimpleArrayAssignmentTest", "main", "array != null & array.length >= 4", + "/set/variablesNonSimpleArrayAssignmentTest/oracle/NonSimpleArrayAssignmentTest.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, false); + } + + /** + * Tests example: /set/variablesArrayCreationInstanceTest + */ + @Test + public void testVariablesArrayCreationInstanceTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayCreationInstanceTest/test/ArrayCreationInstanceTest.java", + "ArrayCreationInstanceTest", "main", "obj != null & n >= 4", + "/set/variablesArrayCreationInstanceTest/oracle/ArrayCreationInstanceTest.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, false); + } + + /** + * Tests example: /set/variablesArrayAssignmentTest + */ + @Test + public void testVariablesArrayAssignmentTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayAssignmentTest/test/ArrayAssignmentTest.java", + "ArrayAssignmentTest", "main", "array != null & array.length >= 4", + "/set/variablesArrayAssignmentTest/oracle/ArrayAssignmentTest.xml", false, true, + false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, false); + } + + /** + * Tests example: /set/variablesArrayCreationTest + */ + @Test + public void testVariablesArrayCreationTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayCreationTest/test/ArrayCreationTest.java", "ArrayCreationTest", + "main", "n >= 4", "/set/variablesArrayCreationTest/oracle/ArrayCreationTest.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, false); + } + + /** + * Tests example: /set/useOperationContractLightweightOperationContractTest + */ + @Test + public void testUseOperationContractLightweightOperationContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractLightweightOperationContractTest/test/LightweightOperationContractTest.java", + "LightweightOperationContractTest", "main", null, "/set/useOperationContractLightweightOperationContractTest/oracle/LightweightOperationContractTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractAssignableEverything + */ + @Test + public void testBlockContractAssignableEverything() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractAssignableEverything/test/BlockContractAssignableEverything.proof", + "/set/blockContractAssignableEverything/oracle/BlockContractAssignableEverything.xml", + false, false, true, true, false, false, false, false, false, false, false, false, false); - } - - /** - * Tests example: /set/blockContractAssignableEverything - */ - @Test - public void testBlockContractAssignableEverything() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractAssignableEverything/test/BlockContractAssignableEverything.proof", - "/set/blockContractAssignableEverything/oracle/BlockContractAssignableEverything.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractAssignableLocationNotRequested - */ - @Test - public void testBlockContractAssignableLocationNotRequested() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractAssignableLocationNotRequested/test/BlockContractAssignableLocationNotRequested.proof", - "/set/blockContractAssignableLocationNotRequested/oracle/BlockContractAssignableLocationNotRequested.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractAssignableRequestedLocation - */ - @Test - public void testBlockContractAssignableRequestedLocation() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractAssignableRequestedLocation/test/BlockContractAssignableRequestedLocation.proof", - "/set/blockContractAssignableRequestedLocation/oracle/BlockContractAssignableRequestedLocation.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractParamRemaned - */ - @Test - public void testBlockContractParamRemaned() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractParamRemaned/test/BlockContractParamRemaned.proof", - "/set/blockContractParamRemaned/oracle/BlockContractParamRemaned.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractPreconditionNotVerified - */ - @Test - public void testBlockContractPreconditionNotVerified() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractPreconditionNotVerified/test/BlockContractPreconditionNotVerified.proof", - "/set/blockContractPreconditionNotVerified/oracle/BlockContractPreconditionNotVerified.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractThisTest - */ - @Test - public void testBlockContractThisTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractThisTest/test/BlockContractThisTest.proof", - "/set/blockContractThisTest/oracle/BlockContractThisTest.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractVarRenamedLater - */ - @Test - public void testBlockContractVarRenamedLater() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractVarRenamedLater/test/BlockContractVarRenamedLater.proof", - "/set/blockContractVarRenamedLater/oracle/BlockContractVarRenamedLater.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithException - */ - @Test - public void testBlockContractWithException() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithException/test/BlockContractWithException.proof", - "/set/blockContractWithException/oracle/BlockContractWithException.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithExceptionPostconditionNotVerified - */ - @Test - public void testBlockContractWithExceptionPostconditionNotVerified() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithExceptionPostconditionNotVerified/test/BlockContractWithExceptionPostconditionNotVerified.proof", - "/set/blockContractWithExceptionPostconditionNotVerified/oracle/BlockContractWithExceptionPostconditionNotVerified.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithReturn - */ - @Test - public void testBlockContractWithReturn() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithReturn/test/BlockContractWithReturn.proof", - "/set/blockContractWithReturn/oracle/BlockContractWithReturn.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithReturnPostconditionNotVerified - */ - @Test - public void testBlockContractWithReturnPostconditionNotVerified() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithReturnPostconditionNotVerified/test/BlockContractWithReturnPostconditionNotVerified.proof", - "/set/blockContractWithReturnPostconditionNotVerified/oracle/BlockContractWithReturnPostconditionNotVerified.xml", - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/useLoopInvariantWithoutDecreasing - */ - @Test - public void testUseLoopInvariantWithoutDecreasing() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/useLoopInvariantWithoutDecreasing/test/LoopInvArrayExample.proof", - "/set/useLoopInvariantWithoutDecreasing/oracle/LoopInvArrayExample.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/simpleIf - */ - @Test - public void testSimpleIfNoConditionSimplification() throws Exception { - doSETTest(testCaseDirectory, - "/set/simpleIf/test/SimpleIf.java", - "SimpleIf", - "min", - null, - "/set/simpleIf/oracle/SimpleIf_NoConditionSimplification.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, + } + + /** + * Tests example: /set/blockContractAssignableLocationNotRequested + */ + @Test + public void testBlockContractAssignableLocationNotRequested() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractAssignableLocationNotRequested/test/BlockContractAssignableLocationNotRequested.proof", + "/set/blockContractAssignableLocationNotRequested/oracle/BlockContractAssignableLocationNotRequested.xml", + false, false, true, true, false, false, false, false, false, false, false, false, false); - } - - /** - * Tests example: /set/simpleStaticContractTest in the Symbolic Execution Profile - * and ensures that no rules are applied forever. - */ - @Test - public void testSimpleStaticContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/simpleStaticContractTest/test/SimpleStaticContractTest.java", - "SimpleStaticContractTest", - "main", - null, - "/set/simpleStaticContractTest/oracle/SimpleStaticContractTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/anotherStaticContractTest in the Symbolic Execution Profile - * and ensures that no rules are applied forever. - */ - @Test - public void testAnotherStaticContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/anotherStaticContractTest/test/AnotherStaticContractTest.java", - "AnotherStaticContractTest", - "main", - null, - "/set/anotherStaticContractTest/oracle/AnotherStaticContractTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticDefaultContractTest in the Symbolic Execution Profile - * and ensures that no rules are applied forever. - */ - @Test - public void testStaticDefaultContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticDefaultContractTest/test/StaticDefaultContractTest.java", - "StaticDefaultContractTest", - "main", - null, - "/set/staticDefaultContractTest/oracle/StaticDefaultContractTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/anotherInstanceContractTest in the Symbolic Execution Profile - * and ensures that no rules are applied forever. - */ - @Test - public void testAnotherInstanceContractTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/anotherInstanceContractTest/test/AnotherInstanceContractTest.java", - "AnotherInstanceContractTest", - "main", - null, - "/set/anotherInstanceContractTest/oracle/AnotherInstanceContractTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceOfNotInEndlessLoop in the Symbolic Execution Profile - * and ensures that no rules are applied forever. - */ - @Test public void testInstanceOfNotInEndlessLoop() throws Exception { - SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, - "/set/instanceOfNotInEndlessLoop/test/Number.java", - "Number", - "equals", - null, - "/set/instanceOfNotInEndlessLoop/oracle/Number.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - try { - int nodesCount = env.getProof().countNodes(); - assertTrue(nodesCount >= 100); // Currently 105 nodes are needed, +-5 are acceptable - assertTrue(nodesCount < 110); // Currently 105 nodes are needed, +-5 are acceptable - } - finally { - if (env != null) { - env.dispose(); - } - } - } - - /** - * Tests example: /set/assumesUserInputTest in the Symbolic Execution Profile - */ - @Test public void testAssumesUserInputTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/assumesUserInputTest/test/AssumesUserInputTest.proof", - "/set/assumesUserInputTest/oracle/AssumesUserInputTest.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, + } + + /** + * Tests example: /set/blockContractAssignableRequestedLocation + */ + @Test + public void testBlockContractAssignableRequestedLocation() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractAssignableRequestedLocation/test/BlockContractAssignableRequestedLocation.proof", + "/set/blockContractAssignableRequestedLocation/oracle/BlockContractAssignableRequestedLocation.xml", + false, false, true, true, false, false, false, false, false, false, false, false, false); - } - - /** - * Tests simple pruning on the example /set/complexIf. - * @throws Exception - * @author Anna Filighera - */ - @Test public void testSimplePruning() throws Exception { - SymbolicExecutionEnvironment env = null; - try { - env = doSETTest(testCaseDirectory, - "/set/complexIf/test/ComplexIf.java", - "ComplexIf", - "min", - null, - "/set/complexIf/oracle/ComplexIf.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - env.getBuilder().prune(env.getProof().root().child(0).child(0)); - assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/PrunedIf.xml", testCaseDirectory); - } finally { - if (env.getProof() != null) { - env.getProof().dispose(); - } - if (env != null) { - env.dispose(); - } - } - } - - /** - * Tests pruning on a branch of the first split in the example /set/complexIf. - * @throws Exception - * @author Anna Filighera - */ - @Test public void testBranchPruning() throws Exception { - SymbolicExecutionEnvironment env = null; - try { - env = doSETTest(testCaseDirectory, - "/set/complexIf/test/ComplexIf.java", - "ComplexIf", - "min", - null, - "/set/complexIf/oracle/ComplexIf.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - - Iterator iter = env.getProof().root().subtreeIterator(); - Node node = null; - while (iter.hasNext()) { - node = iter.next(); - if (node.childrenCount() == 2) { - break; + } + + /** + * Tests example: /set/blockContractParamRemaned + */ + @Test + public void testBlockContractParamRemaned() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractParamRemaned/test/BlockContractParamRemaned.proof", + "/set/blockContractParamRemaned/oracle/BlockContractParamRemaned.xml", false, false, + true, true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractPreconditionNotVerified + */ + @Test + public void testBlockContractPreconditionNotVerified() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractPreconditionNotVerified/test/BlockContractPreconditionNotVerified.proof", + "/set/blockContractPreconditionNotVerified/oracle/BlockContractPreconditionNotVerified.xml", + false, false, true, true, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/blockContractThisTest + */ + @Test + public void testBlockContractThisTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractThisTest/test/BlockContractThisTest.proof", + "/set/blockContractThisTest/oracle/BlockContractThisTest.xml", false, false, true, + true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractVarRenamedLater + */ + @Test + public void testBlockContractVarRenamedLater() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractVarRenamedLater/test/BlockContractVarRenamedLater.proof", + "/set/blockContractVarRenamedLater/oracle/BlockContractVarRenamedLater.xml", false, + false, true, true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractWithException + */ + @Test + public void testBlockContractWithException() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithException/test/BlockContractWithException.proof", + "/set/blockContractWithException/oracle/BlockContractWithException.xml", false, + false, true, true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractWithExceptionPostconditionNotVerified + */ + @Test + public void testBlockContractWithExceptionPostconditionNotVerified() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithExceptionPostconditionNotVerified/test/BlockContractWithExceptionPostconditionNotVerified.proof", + "/set/blockContractWithExceptionPostconditionNotVerified/oracle/BlockContractWithExceptionPostconditionNotVerified.xml", + false, false, true, true, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/blockContractWithReturn + */ + @Test + public void testBlockContractWithReturn() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithReturn/test/BlockContractWithReturn.proof", + "/set/blockContractWithReturn/oracle/BlockContractWithReturn.xml", false, false, + true, true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/blockContractWithReturnPostconditionNotVerified + */ + @Test + public void testBlockContractWithReturnPostconditionNotVerified() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithReturnPostconditionNotVerified/test/BlockContractWithReturnPostconditionNotVerified.proof", + "/set/blockContractWithReturnPostconditionNotVerified/oracle/BlockContractWithReturnPostconditionNotVerified.xml", + false, false, true, true, false, false, false, false, false, false, false, false, + false); + } + + /** + * Tests example: /set/useLoopInvariantWithoutDecreasing + */ + @Test + public void testUseLoopInvariantWithoutDecreasing() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/useLoopInvariantWithoutDecreasing/test/LoopInvArrayExample.proof", + "/set/useLoopInvariantWithoutDecreasing/oracle/LoopInvArrayExample.xml", false, + false, false, false, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/simpleIf + */ + @Test + public void testSimpleIfNoConditionSimplification() throws Exception { + doSETTest(testCaseDirectory, "/set/simpleIf/test/SimpleIf.java", "SimpleIf", "min", null, + "/set/simpleIf/oracle/SimpleIf_NoConditionSimplification.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, false); + } + + /** + * Tests example: /set/simpleStaticContractTest in the Symbolic Execution Profile and ensures + * that no rules are applied forever. + */ + @Test + public void testSimpleStaticContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/simpleStaticContractTest/test/SimpleStaticContractTest.java", + "SimpleStaticContractTest", "main", null, + "/set/simpleStaticContractTest/oracle/SimpleStaticContractTest.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/anotherStaticContractTest in the Symbolic Execution Profile and ensures + * that no rules are applied forever. + */ + @Test + public void testAnotherStaticContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/anotherStaticContractTest/test/AnotherStaticContractTest.java", + "AnotherStaticContractTest", "main", null, + "/set/anotherStaticContractTest/oracle/AnotherStaticContractTest.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/staticDefaultContractTest in the Symbolic Execution Profile and ensures + * that no rules are applied forever. + */ + @Test + public void testStaticDefaultContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/staticDefaultContractTest/test/StaticDefaultContractTest.java", + "StaticDefaultContractTest", "main", null, + "/set/staticDefaultContractTest/oracle/StaticDefaultContractTest.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/anotherInstanceContractTest in the Symbolic Execution Profile and ensures + * that no rules are applied forever. + */ + @Test + public void testAnotherInstanceContractTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/anotherInstanceContractTest/test/AnotherInstanceContractTest.java", + "AnotherInstanceContractTest", "main", null, + "/set/anotherInstanceContractTest/oracle/AnotherInstanceContractTest.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceOfNotInEndlessLoop in the Symbolic Execution Profile and ensures + * that no rules are applied forever. + */ + @Test + public void testInstanceOfNotInEndlessLoop() throws Exception { + SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, + "/set/instanceOfNotInEndlessLoop/test/Number.java", "Number", "equals", null, + "/set/instanceOfNotInEndlessLoop/oracle/Number.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + try { + int nodesCount = env.getProof().countNodes(); + assertTrue(nodesCount >= 100); // Currently 105 nodes are needed, +-5 are acceptable + assertTrue(nodesCount < 110); // Currently 105 nodes are needed, +-5 are acceptable + } finally { + if (env != null) { + env.dispose(); } - } - assertEquals(2, node.childrenCount(), "They prooftree does not contain nodes it should."); - env.getBuilder().prune(node.child(0)); - assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/BranchPrunedIf.xml", testCaseDirectory); - } finally { - if (env.getProof() != null) { - env.getProof().dispose(); - } - if (env != null) { - env.dispose(); - } - } - } - - - /** - * Tests pruning on both branches of a split in a branch of the first split in the example /set/complexIf. - * @throws Exception - * @author Anna Filighera - */ - @Test public void testComplexPruning() throws Exception { - SymbolicExecutionEnvironment env = null; - try { - env = doSETTest(testCaseDirectory, - "/set/complexIf/test/ComplexIf.java", - "ComplexIf", - "min", - null, - "/set/complexIf/oracle/ComplexIf.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - - Iterator iter = env.getProof().root().subtreeIterator(); - Node node = null; - int branchesCount = 0; - while (iter.hasNext()) { - node = iter.next(); - if (node.childrenCount() == 2) { - branchesCount++; + } + } + + /** + * Tests example: /set/assumesUserInputTest in the Symbolic Execution Profile + */ + @Test + public void testAssumesUserInputTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/assumesUserInputTest/test/AssumesUserInputTest.proof", + "/set/assumesUserInputTest/oracle/AssumesUserInputTest.xml", false, false, false, + false, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests simple pruning on the example /set/complexIf. + * + * @throws Exception + * @author Anna Filighera + */ + @Test + public void testSimplePruning() throws Exception { + SymbolicExecutionEnvironment env = null; + try { + env = doSETTest(testCaseDirectory, "/set/complexIf/test/ComplexIf.java", "ComplexIf", + "min", null, "/set/complexIf/oracle/ComplexIf.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + env.getBuilder().prune(env.getProof().root().child(0).child(0)); + assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/PrunedIf.xml", + testCaseDirectory); + } finally { + if (env.getProof() != null) { + env.getProof().dispose(); } - if (branchesCount == 2) { - break; + if (env != null) { + env.dispose(); } - } - assertEquals(2, node.childrenCount(), "They prooftree does not contain nodes it should."); - env.getBuilder().prune(node.child(0)); - assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/Branch0InBranchPrunedIf.xml", testCaseDirectory); - env.getBuilder().prune(node.child(1)); - assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/Branch1InBranchPrunedIf.xml", testCaseDirectory); - } finally { - if (env.getProof() != null) { - env.getProof().dispose(); - } - if (env != null) { - env.dispose(); - } - } - } - - /** - * Tests example: /set/symbolicExecutionCompletionsTest - */ - @Test public void testSymbolicExecutionCompletionsTest() throws Exception { - SymbolicExecutionEnvironment env = null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try { - String javaPathInBaseDir = "/set/symbolicExecutionCompletionsTest/test/SymbolicExecutionCompletionsTest.java"; - String containerTypeName = "SymbolicExecutionCompletionsTest"; - String methodFullName = "magic"; - // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInBaseDir, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInBaseDir, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - IExecutionStart start = env.getBuilder().getStartNode(); - // Perform step into - SymbolicExecutionCompletions completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 1, ".xml", testCaseDirectory); - assertNotNull(completions); - IExecutionNode call = start.getChildren()[0]; - assertEquals(0, completions.getBlockCompletions().length); - assertEquals(0, completions.getMethodReturns().length); - // Perform step into - completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 2, ".xml", testCaseDirectory); - assertNotNull(completions); - IExecutionNode ifStatement = call.getChildren()[0]; - assertEquals(0, completions.getBlockCompletions().length); - assertEquals(0, completions.getMethodReturns().length); - // Perform step into - completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 3, ".xml", testCaseDirectory); - assertNotNull(completions); - IExecutionNode leftBC = ifStatement.getChildren()[0]; - IExecutionNode rightBC = ifStatement.getChildren()[1]; - IExecutionNode leftReturnStatement = leftBC.getChildren()[0]; - IExecutionNode rightIncrement = rightBC.getChildren()[0]; - assertEquals(1, completions.getBlockCompletions().length); - assertSame(leftReturnStatement, completions.getBlockCompletions()[0]); - assertEquals(0, completions.getMethodReturns().length); - // Perform step into - completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 4, ".xml", testCaseDirectory); - assertNotNull(completions); - IExecutionNode leftReturn = leftReturnStatement.getChildren()[0]; - IExecutionNode rightReturnStatement = rightIncrement.getChildren()[0]; - assertEquals(1, completions.getBlockCompletions().length); - assertSame(rightReturnStatement, completions.getBlockCompletions()[0]); - assertEquals(1, completions.getMethodReturns().length); - assertSame(leftReturn, completions.getMethodReturns()[0]); - // Perform step into - completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 5, ".xml", testCaseDirectory); - assertNotNull(completions); - IExecutionNode rightReturn = rightReturnStatement.getChildren()[0]; - assertEquals(0, completions.getBlockCompletions().length); - assertEquals(1, completions.getMethodReturns().length); - assertSame(rightReturn, completions.getMethodReturns()[0]); - // Perform step into - completions = stepInto(env.getUi(), env.getBuilder(), "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", 6, ".xml", testCaseDirectory); - assertNotNull(completions); - assertEquals(0, completions.getBlockCompletions().length); - assertEquals(0, completions.getMethodReturns().length); - } - finally { - // Restore original options - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } - - /** - * Tests example: /set/allNodeTypesTest in the Java Profile - */ - @Test public void testAllNodeTypesTest_JavaProfile_NoOneStepSimplification() throws Exception { - doJavaProfileTest("/set/allNodeTypesTest/test/AllNodeTypesTest_VerificationProfile_NoOneStepSimplification.proof", - "/set/allNodeTypesTest/oracle/AllNodeTypesTest_VerificationProfile_NoOneStepSimplification.xml"); - } - - /** - * Tests example: /set/allNodeTypesTest in the Java Profile - */ - @Test public void testAllNodeTypesTest_JavaProfile() throws Exception { - doJavaProfileTest("/set/allNodeTypesTest/test/AllNodeTypesTest_VerificationProfile.proof", - "/set/allNodeTypesTest/oracle/AllNodeTypesTest_VerificationProfile.xml"); - } - - /** - * Loads an existing proof file performed in the {@link JavaProfile}. - * @param proofFilePathInBaseDir The path to the proof file inside the base directory. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @throws Exception Occurred Exception. - */ - protected void doJavaProfileTest(String proofFilePathInBaseDir, - String oraclePathInBaseDirFile) throws Exception { - // Ensure that JavaProfile was used before - KeYEnvironment env = KeYEnvironment.load(JavaProfile.getDefaultInstance(), new File(testCaseDirectory, proofFilePathInBaseDir), null, null, null, true); - env.dispose(); - // Test symbolic execution - doSETTestAndDispose(testCaseDirectory, - proofFilePathInBaseDir, - oraclePathInBaseDirFile, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - // Test symbolic execution again when symbolic execution profile was used before. - doSETTestAndDispose(testCaseDirectory, - proofFilePathInBaseDir, - oraclePathInBaseDirFile, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, + } + } + + /** + * Tests pruning on a branch of the first split in the example /set/complexIf. + * + * @throws Exception + * @author Anna Filighera + */ + @Test + public void testBranchPruning() throws Exception { + SymbolicExecutionEnvironment env = null; + try { + env = doSETTest(testCaseDirectory, "/set/complexIf/test/ComplexIf.java", "ComplexIf", + "min", null, "/set/complexIf/oracle/ComplexIf.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + + Iterator iter = env.getProof().root().subtreeIterator(); + Node node = null; + while (iter.hasNext()) { + node = iter.next(); + if (node.childrenCount() == 2) { + break; + } + } + assertEquals(2, node.childrenCount(), + "They prooftree does not contain nodes it should."); + env.getBuilder().prune(node.child(0)); + assertSetTreeAfterStep(env.getBuilder(), "/set/complexIf/oracle/BranchPrunedIf.xml", + testCaseDirectory); + } finally { + if (env.getProof() != null) { + env.getProof().dispose(); + } + if (env != null) { + env.dispose(); + } + } + } + + + /** + * Tests pruning on both branches of a split in a branch of the first split in the example + * /set/complexIf. + * + * @throws Exception + * @author Anna Filighera + */ + @Test + public void testComplexPruning() throws Exception { + SymbolicExecutionEnvironment env = null; + try { + env = doSETTest(testCaseDirectory, "/set/complexIf/test/ComplexIf.java", "ComplexIf", + "min", null, "/set/complexIf/oracle/ComplexIf.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + + Iterator iter = env.getProof().root().subtreeIterator(); + Node node = null; + int branchesCount = 0; + while (iter.hasNext()) { + node = iter.next(); + if (node.childrenCount() == 2) { + branchesCount++; + } + if (branchesCount == 2) { + break; + } + } + assertEquals(2, node.childrenCount(), + "They prooftree does not contain nodes it should."); + env.getBuilder().prune(node.child(0)); + assertSetTreeAfterStep(env.getBuilder(), + "/set/complexIf/oracle/Branch0InBranchPrunedIf.xml", testCaseDirectory); + env.getBuilder().prune(node.child(1)); + assertSetTreeAfterStep(env.getBuilder(), + "/set/complexIf/oracle/Branch1InBranchPrunedIf.xml", testCaseDirectory); + } finally { + if (env.getProof() != null) { + env.getProof().dispose(); + } + if (env != null) { + env.dispose(); + } + } + } + + /** + * Tests example: /set/symbolicExecutionCompletionsTest + */ + @Test + public void testSymbolicExecutionCompletionsTest() throws Exception { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + String javaPathInBaseDir = + "/set/symbolicExecutionCompletionsTest/test/SymbolicExecutionCompletionsTest.java"; + String containerTypeName = "SymbolicExecutionCompletionsTest"; + String methodFullName = "magic"; + // Make sure that the correct taclet options are defined. + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInBaseDir, + containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInBaseDir, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + IExecutionStart start = env.getBuilder().getStartNode(); + // Perform step into + SymbolicExecutionCompletions completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 1, ".xml", testCaseDirectory); + assertNotNull(completions); + IExecutionNode call = start.getChildren()[0]; + assertEquals(0, completions.getBlockCompletions().length); + assertEquals(0, completions.getMethodReturns().length); + // Perform step into + completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 2, ".xml", testCaseDirectory); + assertNotNull(completions); + IExecutionNode ifStatement = call.getChildren()[0]; + assertEquals(0, completions.getBlockCompletions().length); + assertEquals(0, completions.getMethodReturns().length); + // Perform step into + completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 3, ".xml", testCaseDirectory); + assertNotNull(completions); + IExecutionNode leftBC = ifStatement.getChildren()[0]; + IExecutionNode rightBC = ifStatement.getChildren()[1]; + IExecutionNode leftReturnStatement = leftBC.getChildren()[0]; + IExecutionNode rightIncrement = rightBC.getChildren()[0]; + assertEquals(1, completions.getBlockCompletions().length); + assertSame(leftReturnStatement, completions.getBlockCompletions()[0]); + assertEquals(0, completions.getMethodReturns().length); + // Perform step into + completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 4, ".xml", testCaseDirectory); + assertNotNull(completions); + IExecutionNode leftReturn = leftReturnStatement.getChildren()[0]; + IExecutionNode rightReturnStatement = rightIncrement.getChildren()[0]; + assertEquals(1, completions.getBlockCompletions().length); + assertSame(rightReturnStatement, completions.getBlockCompletions()[0]); + assertEquals(1, completions.getMethodReturns().length); + assertSame(leftReturn, completions.getMethodReturns()[0]); + // Perform step into + completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 5, ".xml", testCaseDirectory); + assertNotNull(completions); + IExecutionNode rightReturn = rightReturnStatement.getChildren()[0]; + assertEquals(0, completions.getBlockCompletions().length); + assertEquals(1, completions.getMethodReturns().length); + assertSame(rightReturn, completions.getMethodReturns()[0]); + // Perform step into + completions = stepInto(env.getUi(), env.getBuilder(), + "/set/symbolicExecutionCompletionsTest/oracle/SymbolicExecutionCompletionsTest", + 6, ".xml", testCaseDirectory); + assertNotNull(completions); + assertEquals(0, completions.getBlockCompletions().length); + assertEquals(0, completions.getMethodReturns().length); + } finally { + // Restore original options + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } + + /** + * Tests example: /set/allNodeTypesTest in the Java Profile + */ + @Test + public void testAllNodeTypesTest_JavaProfile_NoOneStepSimplification() throws Exception { + doJavaProfileTest( + "/set/allNodeTypesTest/test/AllNodeTypesTest_VerificationProfile_NoOneStepSimplification.proof", + "/set/allNodeTypesTest/oracle/AllNodeTypesTest_VerificationProfile_NoOneStepSimplification.xml"); + } + + /** + * Tests example: /set/allNodeTypesTest in the Java Profile + */ + @Test + public void testAllNodeTypesTest_JavaProfile() throws Exception { + doJavaProfileTest("/set/allNodeTypesTest/test/AllNodeTypesTest_VerificationProfile.proof", + "/set/allNodeTypesTest/oracle/AllNodeTypesTest_VerificationProfile.xml"); + } + + /** + * Loads an existing proof file performed in the {@link JavaProfile}. + * + * @param proofFilePathInBaseDir The path to the proof file inside the base directory. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @throws Exception Occurred Exception. + */ + protected void doJavaProfileTest(String proofFilePathInBaseDir, String oraclePathInBaseDirFile) + throws Exception { + // Ensure that JavaProfile was used before + KeYEnvironment env = KeYEnvironment.load(JavaProfile.getDefaultInstance(), + new File(testCaseDirectory, proofFilePathInBaseDir), null, null, null, true); + env.dispose(); + // Test symbolic execution + doSETTestAndDispose(testCaseDirectory, proofFilePathInBaseDir, oraclePathInBaseDirFile, + false, false, false, false, false, false, false, false, false, false, false, false, false); - } - - /** - * Tests example: /set/allNodeTypesTest in the Symbolic Execution Profile - */ - @Test public void testAllNodeTypesTest_SymbolicExecutionProfile() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/allNodeTypesTest/test/AllNodeTypesTest.proof", - "/set/allNodeTypesTest/oracle/AllNodeTypesTest.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, + // Test symbolic execution again when symbolic execution profile was used before. + doSETTestAndDispose(testCaseDirectory, proofFilePathInBaseDir, oraclePathInBaseDirFile, + false, false, false, false, false, false, false, false, false, false, false, false, false); - } - - /** - * Tests example: /set/loopStatementBlockTest - */ - @Test public void testLoopStatementBlockTest_nestedLoop() throws Exception { - doSETTest(testCaseDirectory, - "/set/loopStatementBlockTest/test/LoopStatementBlockTest.java", - "LoopStatementBlockTest", - "nestedLoop", - null, - "/set/loopStatementBlockTest/oracle/LoopStatementBlockTest_nestedLoop.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/loopStatementBlockTest - */ - @Test public void testLoopStatementBlockTest_simpleLoop() throws Exception { - doSETTest(testCaseDirectory, - "/set/loopStatementBlockTest/test/LoopStatementBlockTest.java", - "LoopStatementBlockTest", - "simpleLoop", - null, - "/set/loopStatementBlockTest/oracle/LoopStatementBlockTest_simpleLoop.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_min() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "min", - null, - "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_min.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_nestedIf() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "nestedIf", - null, - "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_nestedIf.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_simpleBlock() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "simpleBlock", - null, + } + + /** + * Tests example: /set/allNodeTypesTest in the Symbolic Execution Profile + */ + @Test + public void testAllNodeTypesTest_SymbolicExecutionProfile() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/allNodeTypesTest/test/AllNodeTypesTest.proof", + "/set/allNodeTypesTest/oracle/AllNodeTypesTest.xml", false, false, false, false, + false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/loopStatementBlockTest + */ + @Test + public void testLoopStatementBlockTest_nestedLoop() throws Exception { + doSETTest(testCaseDirectory, "/set/loopStatementBlockTest/test/LoopStatementBlockTest.java", + "LoopStatementBlockTest", "nestedLoop", null, + "/set/loopStatementBlockTest/oracle/LoopStatementBlockTest_nestedLoop.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/loopStatementBlockTest + */ + @Test + public void testLoopStatementBlockTest_simpleLoop() throws Exception { + doSETTest(testCaseDirectory, "/set/loopStatementBlockTest/test/LoopStatementBlockTest.java", + "LoopStatementBlockTest", "simpleLoop", null, + "/set/loopStatementBlockTest/oracle/LoopStatementBlockTest_simpleLoop.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_min() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "min", null, + "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_min.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_nestedIf() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "nestedIf", null, + "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_nestedIf.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_simpleBlock() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "simpleBlock", null, "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_simpleBlock.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_ifNoBlock() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "ifNoBlock", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_ifNoBlock() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "ifNoBlock", null, "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_ifNoBlock.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_onlyThen() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "onlyThen", - null, - "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_onlyThen.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_onlyElse() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "onlyElse", - null, - "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_onlyElse.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_switchTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "switchTest", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_onlyThen() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "onlyThen", null, + "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_onlyThen.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_onlyElse() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "onlyElse", null, + "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_onlyElse.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_switchTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "switchTest", null, "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_switchTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_onlyEmptyThen() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "onlyEmptyThen", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_onlyEmptyThen() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "onlyEmptyThen", null, "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_onlyEmptyThen.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/branchStatementBlockTest - */ - @Test public void testBranchStatementBlockTest_recursive() throws Exception { - doSETTest(testCaseDirectory, - "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", - "BranchStatementBlockTest", - "recursiveMain", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/branchStatementBlockTest + */ + @Test + public void testBranchStatementBlockTest_recursive() throws Exception { + doSETTest(testCaseDirectory, + "/set/branchStatementBlockTest/test/BranchStatementBlockTest.java", + "BranchStatementBlockTest", "recursiveMain", null, "/set/branchStatementBlockTest/oracle/BranchStatementBlockTest_recursive.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/constraintsAfterUsedLoopInvariant - */ - @Test public void testConstraintsAfterUsedLoopInvariant() throws Exception { - doSETTest(testCaseDirectory, - "/set/constraintsAfterUsedLoopInvariant/test/E_Loop.java", - "E_Loop", - "calculate", - null, - "/set/constraintsAfterUsedLoopInvariant/oracle/E_Loop.xml", - true, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/constraintsOfAppliedMethodContract - */ - @Test public void testConstraintsOfAppliedMethodContract() throws Exception { - doSETTest(testCaseDirectory, - "/set/constraintsOfAppliedMethodContract/test/MethodContract.java", - "MethodContract", - "magic", - null, - "/set/constraintsOfAppliedMethodContract/oracle/MethodContract.xml", - true, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/exceptionalMethodReturnTest - */ - @Test public void testExceptionalMethodReturnTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/exceptionalMethodReturnTest/test/ExceptionalMethodReturnTest.java", - "ExceptionalMethodReturnTest", - "main", - null, - "/set/exceptionalMethodReturnTest/oracle/ExceptionalMethodReturnTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/exceptionalMethodReturnTestWithLoop - */ - @Test public void testExceptionalMethodReturnTestWithLoop() throws Exception { - doSETTest(testCaseDirectory, - "/set/exceptionalMethodReturnTestWithLoop/test/Loop.java", - "Loop", - "magic", - null, - "/set/exceptionalMethodReturnTestWithLoop/oracle/Loop.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticInstanceFieldChanged - */ - @Test public void testStaticInstanceFieldChanged() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticInstanceFieldChanged/test/StaticInstanceFieldChanged.java", - "StaticInstanceFieldChanged", - "magic", - null, - "/set/staticInstanceFieldChanged/oracle/StaticInstanceFieldChanged.xml", - false, - true, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractVariableNestedOperationContractUse - */ - @Test public void testUseOperationContractVariableNestedOperationContractUse() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractVariableNestedOperationContractUse/test/VariableNestedOperationContractUse.java", - "VariableNestedOperationContractUse", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/constraintsAfterUsedLoopInvariant + */ + @Test + public void testConstraintsAfterUsedLoopInvariant() throws Exception { + doSETTest(testCaseDirectory, "/set/constraintsAfterUsedLoopInvariant/test/E_Loop.java", + "E_Loop", "calculate", null, + "/set/constraintsAfterUsedLoopInvariant/oracle/E_Loop.xml", true, true, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/constraintsOfAppliedMethodContract + */ + @Test + public void testConstraintsOfAppliedMethodContract() throws Exception { + doSETTest(testCaseDirectory, + "/set/constraintsOfAppliedMethodContract/test/MethodContract.java", + "MethodContract", "magic", null, + "/set/constraintsOfAppliedMethodContract/oracle/MethodContract.xml", true, true, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/exceptionalMethodReturnTest + */ + @Test + public void testExceptionalMethodReturnTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/exceptionalMethodReturnTest/test/ExceptionalMethodReturnTest.java", + "ExceptionalMethodReturnTest", "main", null, + "/set/exceptionalMethodReturnTest/oracle/ExceptionalMethodReturnTest.xml", false, + false, true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/exceptionalMethodReturnTestWithLoop + */ + @Test + public void testExceptionalMethodReturnTestWithLoop() throws Exception { + doSETTest(testCaseDirectory, "/set/exceptionalMethodReturnTestWithLoop/test/Loop.java", + "Loop", "magic", null, "/set/exceptionalMethodReturnTestWithLoop/oracle/Loop.xml", + false, false, true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticInstanceFieldChanged + */ + @Test + public void testStaticInstanceFieldChanged() throws Exception { + doSETTest(testCaseDirectory, + "/set/staticInstanceFieldChanged/test/StaticInstanceFieldChanged.java", + "StaticInstanceFieldChanged", "magic", null, + "/set/staticInstanceFieldChanged/oracle/StaticInstanceFieldChanged.xml", false, + true, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractVariableNestedOperationContractUse + */ + @Test + public void testUseOperationContractVariableNestedOperationContractUse() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractVariableNestedOperationContractUse/test/VariableNestedOperationContractUse.java", + "VariableNestedOperationContractUse", "main", null, "/set/useOperationContractVariableNestedOperationContractUse/oracle/VariableNestedOperationContractUse.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractApplyContractTwice - */ - @Test public void testUseOperationContractApplyContractTwice() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractApplyContractTwice/test/OperationContractAppliedTwiceTest.java", - "OperationContractAppliedTwiceTest", - "doubleMagic", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractApplyContractTwice + */ + @Test + public void testUseOperationContractApplyContractTwice() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractApplyContractTwice/test/OperationContractAppliedTwiceTest.java", + "OperationContractAppliedTwiceTest", "doubleMagic", null, "/set/useOperationContractApplyContractTwice/oracle/OperationContractAppliedTwiceTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verificationProofFile_VerifyNumber - */ - @Test public void testVerifyNumberNormal() throws Exception { - doSETTestAndDispose(testCaseDirectory, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/verificationProofFile_VerifyNumber + */ + @Test + public void testVerifyNumberNormal() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/verificationProofFile_VerifyNumber/test/VerifyNumberNormal.proof", - "/set/verificationProofFile_VerifyNumber/oracle/VerifyNumberNormal.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/verificationProofFile_VerifyMin - */ - @Test public void testVerifyMinTrueBranch() throws Exception { - doSETTestAndDispose(testCaseDirectory, + "/set/verificationProofFile_VerifyNumber/oracle/VerifyNumberNormal.xml", false, + false, false, false, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/verificationProofFile_VerifyMin + */ + @Test + public void testVerifyMinTrueBranch() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/verificationProofFile_VerifyMin/test/VerifyMinTrueBranch.proof", - "/set/verificationProofFile_VerifyMin/oracle/VerifyMinTrueBranch.xml", - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/verificationProofFile_VerifyMin - */ - @Test public void testVerifyMin() throws Exception { - doSETTestAndDispose(testCaseDirectory, + "/set/verificationProofFile_VerifyMin/oracle/VerifyMinTrueBranch.xml", false, false, + false, false, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/verificationProofFile_VerifyMin + */ + @Test + public void testVerifyMin() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/verificationProofFile_VerifyMin/test/VerifyMin.proof", - "/set/verificationProofFile_VerifyMin/oracle/VerifyMin.xml", - false, - true, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/simpleMethodCallStackTest - */ - @Test public void testSimpleMethodCallStack() throws Exception { - doSETTest(testCaseDirectory, + "/set/verificationProofFile_VerifyMin/oracle/VerifyMin.xml", false, true, true, + true, false, false, false, false, false, false, false, false, false); + } + + /** + * Tests example: /set/simpleMethodCallStackTest + */ + @Test + public void testSimpleMethodCallStack() throws Exception { + doSETTest(testCaseDirectory, "/set/simpleMethodCallStackTest/test/SimpleMethodCallStackTest.java", - "SimpleMethodCallStackTest", - "magic", - null, - "/set/simpleMethodCallStackTest/oracle/SimpleMethodCallStackTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodCallStackTest - */ - @Test public void testMethodCallStack() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodCallStackTest/test/MethodCallStackTest.java", - "MethodCallStackTest", - "magic", - null, - "/set/methodCallStackTest/oracle/MethodCallStackTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/unicodeTest - */ - @Test public void testUnicode_Disabled() throws Exception { - doSETTest(testCaseDirectory, - "/set/unicodeTest/test/UnicodeTest.java", - "UnicodeTest", - "magic", - null, - "/set/unicodeTest/oracle/UnicodeTest_Disabled.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - true, - false, - true); - } - - /** - * Tests example: /set/unicodeTest - */ - @Test public void testUnicode_Enabled() throws Exception { - doSETTest(testCaseDirectory, - "/set/unicodeTest/test/UnicodeTest.java", - "UnicodeTest", - "magic", - null, - "/set/unicodeTest/oracle/UnicodeTest_Enabled.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - true, - true, - false, - true); - } - - /** - * Tests example: /set/prettyPrint - */ - @Test public void testPrettyPrinting_Disabled() throws Exception { - doSETTest(testCaseDirectory, - "/set/prettyPrint/test/PrettyPrintTest.java", - "PrettyPrintTest", - "main", - null, - "/set/prettyPrint/oracle/PrettyPrintTest_Disabled.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/prettyPrint - */ - @Test public void testPrettyPrinting_Enabled() throws Exception { - doSETTest(testCaseDirectory, - "/set/prettyPrint/test/PrettyPrintTest.java", - "PrettyPrintTest", - "main", - null, - "/set/prettyPrint/oracle/PrettyPrintTest_Enabled.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - true, - false, - true); - } - - /** - * Tests example: /set/useLoopInvariantAndOperationContractStrictlyPure - */ - @Test public void testLoopInvariantAndOperationContractStrictlyPure() throws Exception { - doSETTest(testCaseDirectory, + "SimpleMethodCallStackTest", "magic", null, + "/set/simpleMethodCallStackTest/oracle/SimpleMethodCallStackTest.xml", false, false, + true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/methodCallStackTest + */ + @Test + public void testMethodCallStack() throws Exception { + doSETTest(testCaseDirectory, "/set/methodCallStackTest/test/MethodCallStackTest.java", + "MethodCallStackTest", "magic", null, + "/set/methodCallStackTest/oracle/MethodCallStackTest.xml", false, false, true, true, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/unicodeTest + */ + @Test + public void testUnicode_Disabled() throws Exception { + doSETTest(testCaseDirectory, "/set/unicodeTest/test/UnicodeTest.java", "UnicodeTest", + "magic", null, "/set/unicodeTest/oracle/UnicodeTest_Disabled.xml", false, true, + true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, + false, false, true, false, true); + } + + /** + * Tests example: /set/unicodeTest + */ + @Test + public void testUnicode_Enabled() throws Exception { + doSETTest(testCaseDirectory, "/set/unicodeTest/test/UnicodeTest.java", "UnicodeTest", + "magic", null, "/set/unicodeTest/oracle/UnicodeTest_Enabled.xml", false, true, true, + true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, false, + true, true, false, true); + } + + /** + * Tests example: /set/prettyPrint + */ + @Test + public void testPrettyPrinting_Disabled() throws Exception { + doSETTest(testCaseDirectory, "/set/prettyPrint/test/PrettyPrintTest.java", + "PrettyPrintTest", "main", null, + "/set/prettyPrint/oracle/PrettyPrintTest_Disabled.xml", false, true, true, true, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/prettyPrint + */ + @Test + public void testPrettyPrinting_Enabled() throws Exception { + doSETTest(testCaseDirectory, "/set/prettyPrint/test/PrettyPrintTest.java", + "PrettyPrintTest", "main", null, + "/set/prettyPrint/oracle/PrettyPrintTest_Enabled.xml", false, true, true, true, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, false, false, + true, false, true); + } + + /** + * Tests example: /set/useLoopInvariantAndOperationContractStrictlyPure + */ + @Test + public void testLoopInvariantAndOperationContractStrictlyPure() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantAndOperationContractStrictlyPure/test/IndexOf.java", - "IndexOf", - "indexOf", - null, - "/set/useLoopInvariantAndOperationContractStrictlyPure/oracle/IndexOf.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainVoidMethod() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainVoidMethod", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainVoidMethod.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainNoArgs() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainNoArgs", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainNoArgs.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainResult() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainResult", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainResult.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainResultNotSpecified() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainResultNotSpecified", - null, + "IndexOf", "indexOf", null, + "/set/useLoopInvariantAndOperationContractStrictlyPure/oracle/IndexOf.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainVoidMethod() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainVoidMethod", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainVoidMethod.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainNoArgs() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainNoArgs", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainNoArgs.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainResult() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainResult", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainResult.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainResultNotSpecified() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainResultNotSpecified", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainResultNotSpecified.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainExceptinalVoid() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainExceptinalVoid", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainExceptinalVoid() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainExceptinalVoid", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainExceptinalVoid.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainExceptinalUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainExceptinalUnused", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainExceptinalUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainExceptinalUnused", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainExceptinalUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainExceptinal() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainExceptinal", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainExceptinal.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainBooleanResultUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainBooleanResultUnused", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainExceptinal() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainExceptinal", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainExceptinal.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainBooleanResultUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainBooleanResultUnused", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainBooleanResultUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainBooleanResultUnspecifiedUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainBooleanResultUnspecifiedUnused", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainBooleanResultUnspecifiedUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainBooleanResultUnspecifiedUnused", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainBooleanResultUnspecifiedUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainExceptionalConstructor() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainExceptionalConstructor", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainExceptionalConstructor() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainExceptionalConstructor", null, "/set/instanceContractTest/oracle/InstanceContractTest_mainExceptionalConstructor.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainConstructor() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainConstructor", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainConstructor.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/instanceContractTest - */ - @Test public void testInstanceContractTest_mainOnObject() throws Exception { - doSETTest(testCaseDirectory, - "/set/instanceContractTest/test/InstanceContractTest.java", - "InstanceContractTest", - "mainOnObject", - null, - "/set/instanceContractTest/oracle/InstanceContractTest_mainOnObject.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainVoidMethod() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainVoidMethod", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainVoidMethod.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainNoArgs() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainNoArgs", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainNoArgs.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainResult() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainResult", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainResult.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainResultNotSpecified() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainResultNotSpecified", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainConstructor() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainConstructor", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainConstructor.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/instanceContractTest + */ + @Test + public void testInstanceContractTest_mainOnObject() throws Exception { + doSETTest(testCaseDirectory, "/set/instanceContractTest/test/InstanceContractTest.java", + "InstanceContractTest", "mainOnObject", null, + "/set/instanceContractTest/oracle/InstanceContractTest_mainOnObject.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainVoidMethod() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainVoidMethod", null, + "/set/staticContractTest/oracle/StaticContractTest_mainVoidMethod.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainNoArgs() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainNoArgs", null, + "/set/staticContractTest/oracle/StaticContractTest_mainNoArgs.xml", false, false, + false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainResult() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainResult", null, + "/set/staticContractTest/oracle/StaticContractTest_mainResult.xml", false, false, + false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainResultNotSpecified() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainResultNotSpecified", null, "/set/staticContractTest/oracle/StaticContractTest_mainResultNotSpecified.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainExceptinalVoid() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainExceptinalVoid", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainExceptinalVoid.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainExceptinalUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainExceptinalUnused", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainExceptinalUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainExceptinal() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainExceptinal", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainExceptinal.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainBooleanResultUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainBooleanResultUnused", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainExceptinalVoid() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainExceptinalVoid", null, + "/set/staticContractTest/oracle/StaticContractTest_mainExceptinalVoid.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainExceptinalUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainExceptinalUnused", null, + "/set/staticContractTest/oracle/StaticContractTest_mainExceptinalUnused.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainExceptinal() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainExceptinal", null, + "/set/staticContractTest/oracle/StaticContractTest_mainExceptinal.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainBooleanResultUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainBooleanResultUnused", null, "/set/staticContractTest/oracle/StaticContractTest_mainBooleanResultUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainBooleanResultUnspecifiedUnused() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainBooleanResultUnspecifiedUnused", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainBooleanResultUnspecifiedUnused() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainBooleanResultUnspecifiedUnused", null, "/set/staticContractTest/oracle/StaticContractTest_mainBooleanResultUnspecifiedUnused.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainExceptionalConstructor() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainExceptionalConstructor", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainExceptionalConstructor() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainExceptionalConstructor", null, "/set/staticContractTest/oracle/StaticContractTest_mainExceptionalConstructor.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainConstructor() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainConstructor", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainConstructor.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticContractTest - */ - @Test public void testStaticContractTest_mainOnObject() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticContractTest/test/StaticContractTest.java", - "StaticContractTest", - "mainOnObject", - null, - "/set/staticContractTest/oracle/StaticContractTest_mainOnObject.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_notLoop() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::notLoop(int)].JML operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_notLoop.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_loop() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::loop(int)].JML operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_loop.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_notMagic() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::notMagic()].JML operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_notMagic.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_magic() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::magic()].JML operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_magic.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_notMagicException() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::notMagicException()].JML exceptional_behavior operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_notMagicException.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/verifiedTest - */ - @Test public void testVerifiedTest_magicException() throws Exception { - doSETTest(testCaseDirectory, - "/set/verifiedTest/test/VerifiedTest.java", - "VerifiedTest[VerifiedTest::magicException()].JML exceptional_behavior operation contract.0", - "/set/verifiedTest/oracle/VerifiedTest_magicException.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodCallReturnTests - */ - @Test public void testMethodCallReturnTests() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodCallReturnTests/test/MethodCallReturnTests.java", - "MethodCallReturnTests", - "main", - null, - "/set/methodCallReturnTests/oracle/MethodCallReturnTests.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useLoopInvariantArrayAverage - */ - @Test public void testUseLoopInvariantArrayAverage() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArrayAverage/test/ArrayAverage.java", - "ArrayAverage", - "average", - null, - "/set/useLoopInvariantArrayAverage/oracle/ArrayAverage.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractStatementsInImpliciteConstructor - */ - @Test public void testUseOperationContractStatementsInImpliciteConstructor() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractStatementsInImpliciteConstructor/test/UseOperationContractStatementsInImpliciteConstructor.java", - "UseOperationContractStatementsInImpliciteConstructor", - "average", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainConstructor() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainConstructor", null, + "/set/staticContractTest/oracle/StaticContractTest_mainConstructor.xml", false, + false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/staticContractTest + */ + @Test + public void testStaticContractTest_mainOnObject() throws Exception { + doSETTest(testCaseDirectory, "/set/staticContractTest/test/StaticContractTest.java", + "StaticContractTest", "mainOnObject", null, + "/set/staticContractTest/oracle/StaticContractTest_mainOnObject.xml", false, false, + false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_notLoop() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::notLoop(int)].JML operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_notLoop.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, true, false, false, false, false, false, false, false, + true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_loop() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::loop(int)].JML operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_loop.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, true, false, false, false, false, false, false, false, + true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_notMagic() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::notMagic()].JML operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_notMagic.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + false, true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_magic() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::magic()].JML operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_magic.xml", false, false, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + false, true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_notMagicException() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::notMagicException()].JML exceptional_behavior operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_notMagicException.xml", false, false, false, + false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/verifiedTest + */ + @Test + public void testVerifiedTest_magicException() throws Exception { + doSETTest(testCaseDirectory, "/set/verifiedTest/test/VerifiedTest.java", + "VerifiedTest[VerifiedTest::magicException()].JML exceptional_behavior operation contract.0", + "/set/verifiedTest/oracle/VerifiedTest_magicException.xml", false, false, false, + false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/methodCallReturnTests + */ + @Test + public void testMethodCallReturnTests() throws Exception { + doSETTest(testCaseDirectory, "/set/methodCallReturnTests/test/MethodCallReturnTests.java", + "MethodCallReturnTests", "main", null, + "/set/methodCallReturnTests/oracle/MethodCallReturnTests.xml", false, true, true, + true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/useLoopInvariantArrayAverage + */ + @Test + public void testUseLoopInvariantArrayAverage() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantArrayAverage/test/ArrayAverage.java", + "ArrayAverage", "average", null, + "/set/useLoopInvariantArrayAverage/oracle/ArrayAverage.xml", false, false, true, + true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractStatementsInImpliciteConstructor + */ + @Test + public void testUseOperationContractStatementsInImpliciteConstructor() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractStatementsInImpliciteConstructor/test/UseOperationContractStatementsInImpliciteConstructor.java", + "UseOperationContractStatementsInImpliciteConstructor", "average", null, "/set/useOperationContractStatementsInImpliciteConstructor/oracle/UseOperationContractStatementsInImpliciteConstructor.xml", - false, - true, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantLoopSplittingCondition - *

    - *

    - * Tests the handling of method returns in different modalities. - *

    - */ - @Test public void testUseLoopInvariantLoopSplittingCondition() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantLoopSplittingCondition/test/LoopSplittingCondition.java", - "LoopSplittingCondition", - "main", - null, + false, true, true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantLoopSplittingCondition + *

    + *

    + * Tests the handling of method returns in different modalities. + *

    + */ + @Test + public void testUseLoopInvariantLoopSplittingCondition() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantLoopSplittingCondition/test/LoopSplittingCondition.java", + "LoopSplittingCondition", "main", null, "/set/useLoopInvariantLoopSplittingCondition/oracle/LoopSplittingCondition.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantTwoLoops - *

    - *

    - * Tests the handling of method returns in different modalities. - *

    - */ - @Test public void testUseLoopInvariantTwoLoops() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantTwoLoops/test/TwoLoops.java", - "TwoLoops", - "main", - null, - "/set/useLoopInvariantTwoLoops/oracle/TwoLoops.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsConditionFullImplemented - *

    - *

    - * Tests the handling of method returns in different modalities. - *

    - */ - @Test public void testLoopInvariantMethodReturnInDifferentModalities() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsConditionFullImplemented/test/WhileWithMethodCallAsConditionFullImplemented.java", - "WhileWithMethodCallAsConditionFullImplemented", - "size", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantTwoLoops + *

    + *

    + * Tests the handling of method returns in different modalities. + *

    + */ + @Test + public void testUseLoopInvariantTwoLoops() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantTwoLoops/test/TwoLoops.java", "TwoLoops", + "main", null, "/set/useLoopInvariantTwoLoops/oracle/TwoLoops.xml", false, false, + false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, false, false, + false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsConditionFullImplemented + *

    + *

    + * Tests the handling of method returns in different modalities. + *

    + */ + @Test + public void testLoopInvariantMethodReturnInDifferentModalities() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsConditionFullImplemented/test/WhileWithMethodCallAsConditionFullImplemented.java", + "WhileWithMethodCallAsConditionFullImplemented", "size", null, "/set/useLoopInvariantWhileWithMethodCallAsConditionFullImplemented/oracle/WhileWithMethodCallAsConditionFullImplemented.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantLoopBodyBranchClosed - *

    - *

    - * Tests the handling of {@code continue} when a loop is expanded. - *

    - */ - @Test public void testLoopBodyBranchClosed() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantLoopBodyBranchClosed/test/LoopBodyBranchClosed.java", - "LoopBodyBranchClosed", - "deadBody", - null, - "/set/useLoopInvariantLoopBodyBranchClosed/oracle/LoopBodyBranchClosed.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantLoopUsageBranchClosed - *

    - *

    - * Tests the handling of {@code continue} when a loop is expanded. - *

    - */ - @Test public void testLoopUsageBranchClosed() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantLoopUsageBranchClosed/test/LoopUsageBranchClosed.java", - "LoopUsageBranchClosed", - "deadCodeAfterLoop", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantLoopBodyBranchClosed + *

    + *

    + * Tests the handling of {@code continue} when a loop is expanded. + *

    + */ + @Test + public void testLoopBodyBranchClosed() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantLoopBodyBranchClosed/test/LoopBodyBranchClosed.java", + "LoopBodyBranchClosed", "deadBody", null, + "/set/useLoopInvariantLoopBodyBranchClosed/oracle/LoopBodyBranchClosed.xml", false, + false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, + false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantLoopUsageBranchClosed + *

    + *

    + * Tests the handling of {@code continue} when a loop is expanded. + *

    + */ + @Test + public void testLoopUsageBranchClosed() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantLoopUsageBranchClosed/test/LoopUsageBranchClosed.java", + "LoopUsageBranchClosed", "deadCodeAfterLoop", null, "/set/useLoopInvariantLoopUsageBranchClosed/oracle/LoopUsageBranchClosed.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/nestedLoopsWithContinue - *

    - *

    - * Tests the handling of {@code continue} when a loop is expanded. - *

    - */ - @Test public void testNestedLoopsWithContinue() throws Exception { - doSETTest(testCaseDirectory, - "/set/nestedLoopsWithContinue/test/NestedLoopsWithContinue.java", - "NestedLoopsWithContinue", - "main", - null, - "/set/nestedLoopsWithContinue/oracle/NestedLoopsWithContinue.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhileWithContinue - *

    - *

    - * Tests the handling of {@code continue} when a loop invariant is applied. - *

    - */ - @Test public void testArraySumWhileWithContinue() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhileWithContinue/test/ArraySumWhileWithContinue.java", - "ArraySumWhileWithContinue", - "sum", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/nestedLoopsWithContinue + *

    + *

    + * Tests the handling of {@code continue} when a loop is expanded. + *

    + */ + @Test + public void testNestedLoopsWithContinue() throws Exception { + doSETTest(testCaseDirectory, + "/set/nestedLoopsWithContinue/test/NestedLoopsWithContinue.java", + "NestedLoopsWithContinue", "main", null, + "/set/nestedLoopsWithContinue/oracle/NestedLoopsWithContinue.xml", false, false, + true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhileWithContinue + *

    + *

    + * Tests the handling of {@code continue} when a loop invariant is applied. + *

    + */ + @Test + public void testArraySumWhileWithContinue() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumWhileWithContinue/test/ArraySumWhileWithContinue.java", + "ArraySumWhileWithContinue", "sum", null, "/set/useLoopInvariantArraySumWhileWithContinue/oracle/ArraySumWhileWithContinue.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantVoidWhileWithReturn - *

    - *

    - * Tests the handling of {@code return} when a loop invariant is applied. - *

    - */ - @Test public void testVoidWhileWithReturn() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantVoidWhileWithReturn/test/VoidWhileWithReturn.java", - "VoidWhileWithReturn", - "sum", - null, - "/set/useLoopInvariantVoidWhileWithReturn/oracle/VoidWhileWithReturn.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhileWithReturn - *

    - *

    - * Tests the handling of {@code return} when a loop invariant is applied. - *

    - */ - @Test public void testArraySumWhileWithReturn() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhileWithReturn/test/ArraySumWhileWithReturn.java", - "ArraySumWhileWithReturn", - "sum", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantVoidWhileWithReturn + *

    + *

    + * Tests the handling of {@code return} when a loop invariant is applied. + *

    + */ + @Test + public void testVoidWhileWithReturn() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantVoidWhileWithReturn/test/VoidWhileWithReturn.java", + "VoidWhileWithReturn", "sum", null, + "/set/useLoopInvariantVoidWhileWithReturn/oracle/VoidWhileWithReturn.xml", false, + false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, + false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhileWithReturn + *

    + *

    + * Tests the handling of {@code return} when a loop invariant is applied. + *

    + */ + @Test + public void testArraySumWhileWithReturn() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumWhileWithReturn/test/ArraySumWhileWithReturn.java", + "ArraySumWhileWithReturn", "sum", null, "/set/useLoopInvariantArraySumWhileWithReturn/oracle/ArraySumWhileWithReturn.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhileWithBreak - *

    - *

    - * Tests the handling of {@code break} when a loop invariant is applied. - *

    - */ - @Test public void testArraySumWhileWithBreak() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhileWithBreak/test/ArraySumWhileWithBreak.java", - "ArraySumWhileWithBreak", - "sum", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhileWithBreak + *

    + *

    + * Tests the handling of {@code break} when a loop invariant is applied. + *

    + */ + @Test + public void testArraySumWhileWithBreak() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumWhileWithBreak/test/ArraySumWhileWithBreak.java", + "ArraySumWhileWithBreak", "sum", null, "/set/useLoopInvariantArraySumWhileWithBreak/oracle/ArraySumWhileWithBreak.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhileWithException - *

    - *

    - * Tests the handling of thrown exceptions when a loop invariant is applied. - *

    - */ - @Test public void testArraySumWhileWithException() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhileWithException/test/ArraySumWhileWithException.java", - "ArraySumWhileWithException", - "sum", - "array != null", + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhileWithException + *

    + *

    + * Tests the handling of thrown exceptions when a loop invariant is applied. + *

    + */ + @Test + public void testArraySumWhileWithException() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumWhileWithException/test/ArraySumWhileWithException.java", + "ArraySumWhileWithException", "sum", "array != null", "/set/useLoopInvariantArraySumWhileWithException/oracle/ArraySumWhileWithException.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithMethodCallAsCondition_preMethodContract() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", - "WhileWithMethodCallAsCondition", - "size", - "array != null", + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithMethodCallAsCondition_preMethodContract() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", + "WhileWithMethodCallAsCondition", "size", "array != null", "/set/useLoopInvariantWhileWithMethodCallAsCondition/oracle/WhileWithMethodCallAsCondition_preMethodContract.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithMethodCallAsCondition_preExpandMethods() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", - "WhileWithMethodCallAsCondition", - "size", - "array != null", + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithMethodCallAsCondition_preExpandMethods() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", + "WhileWithMethodCallAsCondition", "size", "array != null", "/set/useLoopInvariantWhileWithMethodCallAsCondition/oracle/WhileWithMethodCallAsCondition_preExpandMethods.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithMethodCallAsCondition_NoPreMethodContract() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", - "WhileWithMethodCallAsCondition", - "size", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithMethodCallAsCondition_NoPreMethodContract() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", + "WhileWithMethodCallAsCondition", "size", null, "/set/useLoopInvariantWhileWithMethodCallAsCondition/oracle/WhileWithMethodCallAsCondition_NoPreMethodContract.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithLoopInvariantInCondition - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithLoopInvariantInCondition() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithLoopInvariantInCondition/test/WhileWithLoopInvariantInCondition.java", - "WhileWithLoopInvariantInCondition", - "size", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithLoopInvariantInCondition + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithLoopInvariantInCondition() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithLoopInvariantInCondition/test/WhileWithLoopInvariantInCondition.java", + "WhileWithLoopInvariantInCondition", "size", null, "/set/useLoopInvariantWhileWithLoopInvariantInCondition/oracle/WhileWithLoopInvariantInCondition.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsConditionOnObject - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithMethodCallAsConditionOnObject() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsConditionOnObject/test/WhileWithMethodCallAsConditionOnObject.java", - "WhileWithMethodCallAsConditionOnObject", - "size", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsConditionOnObject + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithMethodCallAsConditionOnObject() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsConditionOnObject/test/WhileWithMethodCallAsConditionOnObject.java", + "WhileWithMethodCallAsConditionOnObject", "size", null, "/set/useLoopInvariantWhileWithMethodCallAsConditionOnObject/oracle/WhileWithMethodCallAsConditionOnObject.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testWhileWithMethodCallAsCondition_NoPreExpandMethods() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", - "WhileWithMethodCallAsCondition", - "size", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantWhileWithMethodCallAsCondition + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testWhileWithMethodCallAsCondition_NoPreExpandMethods() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantWhileWithMethodCallAsCondition/test/WhileWithMethodCallAsCondition.java", + "WhileWithMethodCallAsCondition", "size", null, "/set/useLoopInvariantWhileWithMethodCallAsCondition/oracle/WhileWithMethodCallAsCondition_NoPreExpandMethods.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySizeDoWhile - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySizeDoWhile() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySizeDoWhile/test/ArraySizeDoWhile.java", - "ArraySizeDoWhile", - "size", - "array != null", - "/set/useLoopInvariantArraySizeDoWhile/oracle/ArraySizeDoWhile.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySizeWhile - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySizeWhile() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySizeWhile/test/ArraySizeWhile.java", - "ArraySizeWhile", - "size", - "array != null", - "/set/useLoopInvariantArraySizeWhile/oracle/ArraySizeWhile.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumFor - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySumFor() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumFor/test/ArraySumFor.java", - "ArraySumFor", - "sum", - "array != null", - "/set/useLoopInvariantArraySumFor/oracle/ArraySumFor.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumForEach - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySumForEach() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumForEach/test/ArraySumForEach.java", - "ArraySumForEach", - "sum", - "array != null", - "/set/useLoopInvariantArraySumForEach/oracle/ArraySumForEach.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhile - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySumWhile() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhile/test/ArraySumWhile.java", - "ArraySumWhile", - "sum", - "array != null", - "/set/useLoopInvariantArraySumWhile/oracle/ArraySumWhile.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/useLoopInvariantArraySumWhileInitiallyInvalid - *

    - *

    - * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! - *

    - */ - @Test public void testUseLoopInvariantArraySumWhileInitiallyInvalid() throws Exception { - doSETTest(testCaseDirectory, - "/set/useLoopInvariantArraySumWhileInitiallyInvalid/test/ArraySumWhileInitiallyInvalid.java", - "ArraySumWhileInitiallyInvalid", - "sum", - "array != null", + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySizeDoWhile + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySizeDoWhile() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySizeDoWhile/test/ArraySizeDoWhile.java", + "ArraySizeDoWhile", "size", "array != null", + "/set/useLoopInvariantArraySizeDoWhile/oracle/ArraySizeDoWhile.xml", false, false, + true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, + false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySizeWhile + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySizeWhile() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantArraySizeWhile/test/ArraySizeWhile.java", + "ArraySizeWhile", "size", "array != null", + "/set/useLoopInvariantArraySizeWhile/oracle/ArraySizeWhile.xml", false, false, true, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, false, + false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumFor + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySumFor() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantArraySumFor/test/ArraySumFor.java", + "ArraySumFor", "sum", "array != null", + "/set/useLoopInvariantArraySumFor/oracle/ArraySumFor.xml", false, false, true, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, false, + false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumForEach + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySumForEach() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumForEach/test/ArraySumForEach.java", "ArraySumForEach", + "sum", "array != null", + "/set/useLoopInvariantArraySumForEach/oracle/ArraySumForEach.xml", false, false, + true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, + false, false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhile + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySumWhile() throws Exception { + doSETTest(testCaseDirectory, "/set/useLoopInvariantArraySumWhile/test/ArraySumWhile.java", + "ArraySumWhile", "sum", "array != null", + "/set/useLoopInvariantArraySumWhile/oracle/ArraySumWhile.xml", false, false, true, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, false, false, false, + false, false, false, true); + } + + /** + *

    + * Tests example: /set/useLoopInvariantArraySumWhileInitiallyInvalid + *

    + *

    + * The preserves loop body branch is fulfilled and not contained in the symbolic execution tree! + *

    + */ + @Test + public void testUseLoopInvariantArraySumWhileInitiallyInvalid() throws Exception { + doSETTest(testCaseDirectory, + "/set/useLoopInvariantArraySumWhileInitiallyInvalid/test/ArraySumWhileInitiallyInvalid.java", + "ArraySumWhileInitiallyInvalid", "sum", "array != null", "/set/useLoopInvariantArraySumWhileInitiallyInvalid/oracle/ArraySumWhileInitiallyInvalid.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractQueryTest - */ - @Test public void testUseOperationContractQueryTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractQueryTest/test/UseOperationContractQueryTest.java", - "UseOperationContractQueryTest", - "main", - "value == magicNumber()", + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, true, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractQueryTest + */ + @Test + public void testUseOperationContractQueryTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractQueryTest/test/UseOperationContractQueryTest.java", + "UseOperationContractQueryTest", "main", "value == magicNumber()", "/set/useOperationContractQueryTest/oracle/UseOperationContractQueryTest.xml", - false, - false, - true, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractAllBranchesOpenTest - */ - @Test public void testUseOperationContractAllBranchesOpenTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractAllBranchesOpenTest/test/UseOperationContractAllBranchesOpenTest.java", - "UseOperationContractAllBranchesOpenTest", - "main", - null, + false, false, true, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractAllBranchesOpenTest + */ + @Test + public void testUseOperationContractAllBranchesOpenTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractAllBranchesOpenTest/test/UseOperationContractAllBranchesOpenTest.java", + "UseOperationContractAllBranchesOpenTest", "main", null, "/set/useOperationContractAllBranchesOpenTest/oracle/UseOperationContractAllBranchesOpenTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/identicalTermsDuringProof - */ - @Test public void testIdenticalTermsDuringProof() throws Exception { - // Make sure that correct symbolic execution tree is created. - SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, - "/set/identicalTermsDuringProof/test/IdenticalTermsDuringProof.java", - "IdenticalTermsDuringProof", - "mid", - null, - "/set/identicalTermsDuringProof/oracle/IdenticalTermsDuringProof.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - try { - // Find both statements "mid = y;". - IExecutionStart startNode = env.getBuilder().getStartNode(); - IExecutionMethodCall methodCall = (IExecutionMethodCall)startNode.getChildren()[0]; - IExecutionStatement intMidZ = (IExecutionStatement)methodCall.getChildren()[0]; - IExecutionBranchStatement ifYZ = (IExecutionBranchStatement)intMidZ.getChildren()[0]; - IExecutionBranchCondition notXY = (IExecutionBranchCondition)ifYZ.getChildren()[0]; - IExecutionBranchStatement ifXZ = (IExecutionBranchStatement)notXY.getChildren()[0]; - IExecutionBranchCondition not1X = (IExecutionBranchCondition)ifXZ.getChildren()[0]; - IExecutionStatement midThenBranch = (IExecutionStatement)not1X.getChildren()[0]; - IExecutionBranchCondition not1Y = (IExecutionBranchCondition)ifYZ.getChildren()[1]; - IExecutionStatement midElseBranch = (IExecutionStatement)not1Y.getChildren()[0]; - // Make sure that both statements "mid = y;" have the correct position info. - assertNotSame(midThenBranch, midElseBranch); - assertNotSame(midThenBranch.getActiveStatement(), midElseBranch.getActiveStatement()); - PositionInfo thenPosition = midThenBranch.getActivePositionInfo(); - PositionInfo elsePosition = midElseBranch.getActivePositionInfo(); - assertNotSame(thenPosition, elsePosition); - assertNotSame(PositionInfo.UNDEFINED, thenPosition); - assertNotSame(PositionInfo.UNDEFINED, elsePosition); - assertEquals(6, thenPosition.getStartPosition().getLine()); - assertEquals(21, thenPosition.getStartPosition().getColumn()); - assertEquals(6, thenPosition.getEndPosition().getLine()); - assertEquals(24, thenPosition.getEndPosition().getColumn()); - assertEquals(9, elsePosition.getStartPosition().getLine()); - assertEquals(17, elsePosition.getStartPosition().getColumn()); - assertEquals(9, elsePosition.getEndPosition().getLine()); - assertEquals(20, elsePosition.getEndPosition().getColumn()); - } - finally { - env.dispose(); - } - } - - /** - * Tests example: /set/labelTest - */ - @Test - public void testLabelTest_doubled() throws Exception { - doSETTest(testCaseDirectory, - "/set/labelTest/test/LabelTest.java", - "LabelTest", - "doubled", - null, - "/set/labelTest/oracle/LabelTest_doubled.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/labelTest - */ - @Test - public void testLabelTest_lost() throws Exception { - doSETTest(testCaseDirectory, - "/set/labelTest/test/LabelTest.java", - "LabelTest", - "lost", - null, - "/set/labelTest/oracle/LabelTest_lost.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/emptyBlockTest - */ - @Test public void testEmptyBlockTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/emptyBlockTest/test/EmptyBlockTest.java", - "EmptyBlockTest", - "emptyBlocks", - null, - "/set/emptyBlockTest/oracle/EmptyBlockTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractExceptionalNoPreconditionWithNullCheckTest - */ - @Test - public void testUseOperationContractExceptionalNoPreconditionWithNullCheckTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractExceptionalNoPreconditionWithNullCheckTest/test/UseOperationContractExceptionalNoPreconditionWithNullCheckTest.java", - "UseOperationContractExceptionalNoPreconditionWithNullCheckTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/identicalTermsDuringProof + */ + @Test + public void testIdenticalTermsDuringProof() throws Exception { + // Make sure that correct symbolic execution tree is created. + SymbolicExecutionEnvironment env = doSETTest(testCaseDirectory, + "/set/identicalTermsDuringProof/test/IdenticalTermsDuringProof.java", + "IdenticalTermsDuringProof", "mid", null, + "/set/identicalTermsDuringProof/oracle/IdenticalTermsDuringProof.xml", false, false, + false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, true); + try { + // Find both statements "mid = y;". + IExecutionStart startNode = env.getBuilder().getStartNode(); + IExecutionMethodCall methodCall = (IExecutionMethodCall) startNode.getChildren()[0]; + IExecutionStatement intMidZ = (IExecutionStatement) methodCall.getChildren()[0]; + IExecutionBranchStatement ifYZ = (IExecutionBranchStatement) intMidZ.getChildren()[0]; + IExecutionBranchCondition notXY = (IExecutionBranchCondition) ifYZ.getChildren()[0]; + IExecutionBranchStatement ifXZ = (IExecutionBranchStatement) notXY.getChildren()[0]; + IExecutionBranchCondition not1X = (IExecutionBranchCondition) ifXZ.getChildren()[0]; + IExecutionStatement midThenBranch = (IExecutionStatement) not1X.getChildren()[0]; + IExecutionBranchCondition not1Y = (IExecutionBranchCondition) ifYZ.getChildren()[1]; + IExecutionStatement midElseBranch = (IExecutionStatement) not1Y.getChildren()[0]; + // Make sure that both statements "mid = y;" have the correct position info. + assertNotSame(midThenBranch, midElseBranch); + assertNotSame(midThenBranch.getActiveStatement(), midElseBranch.getActiveStatement()); + PositionInfo thenPosition = midThenBranch.getActivePositionInfo(); + PositionInfo elsePosition = midElseBranch.getActivePositionInfo(); + assertNotSame(thenPosition, elsePosition); + assertNotSame(PositionInfo.UNDEFINED, thenPosition); + assertNotSame(PositionInfo.UNDEFINED, elsePosition); + assertEquals(6, thenPosition.getStartPosition().getLine()); + assertEquals(21, thenPosition.getStartPosition().getColumn()); + assertEquals(6, thenPosition.getEndPosition().getLine()); + assertEquals(24, thenPosition.getEndPosition().getColumn()); + assertEquals(9, elsePosition.getStartPosition().getLine()); + assertEquals(17, elsePosition.getStartPosition().getColumn()); + assertEquals(9, elsePosition.getEndPosition().getLine()); + assertEquals(20, elsePosition.getEndPosition().getColumn()); + } finally { + env.dispose(); + } + } + + /** + * Tests example: /set/labelTest + */ + @Test + public void testLabelTest_doubled() throws Exception { + doSETTest(testCaseDirectory, "/set/labelTest/test/LabelTest.java", "LabelTest", "doubled", + null, "/set/labelTest/oracle/LabelTest_doubled.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/labelTest + */ + @Test + public void testLabelTest_lost() throws Exception { + doSETTest(testCaseDirectory, "/set/labelTest/test/LabelTest.java", "LabelTest", "lost", + null, "/set/labelTest/oracle/LabelTest_lost.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/emptyBlockTest + */ + @Test + public void testEmptyBlockTest() throws Exception { + doSETTest(testCaseDirectory, "/set/emptyBlockTest/test/EmptyBlockTest.java", + "EmptyBlockTest", "emptyBlocks", null, + "/set/emptyBlockTest/oracle/EmptyBlockTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/useOperationContractExceptionalNoPreconditionWithNullCheckTest + */ + @Test + public void testUseOperationContractExceptionalNoPreconditionWithNullCheckTest() + throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractExceptionalNoPreconditionWithNullCheckTest/test/UseOperationContractExceptionalNoPreconditionWithNullCheckTest.java", + "UseOperationContractExceptionalNoPreconditionWithNullCheckTest", "main", null, "/set/useOperationContractExceptionalNoPreconditionWithNullCheckTest/oracle/UseOperationContractExceptionalNoPreconditionWithNullCheckTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractFalsePreconditionTest - */ - @Test - public void testUseOperationContractFalsePreconditionTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractFalsePreconditionTest/test/UseOperationContractFalsePreconditionTest.java", - "UseOperationContractFalsePreconditionTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractFalsePreconditionTest + */ + @Test + public void testUseOperationContractFalsePreconditionTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractFalsePreconditionTest/test/UseOperationContractFalsePreconditionTest.java", + "UseOperationContractFalsePreconditionTest", "main", null, "/set/useOperationContractFalsePreconditionTest/oracle/UseOperationContractFalsePreconditionTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractFixedNormalPostTest - */ - @Test - public void testUseOperationContractFixedNormalPostTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractFixedNormalPostTest/test/UseOperationContractFixedNormalPostTest.java", - "UseOperationContractFixedNormalPostTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractFixedNormalPostTest + */ + @Test + public void testUseOperationContractFixedNormalPostTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractFixedNormalPostTest/test/UseOperationContractFixedNormalPostTest.java", + "UseOperationContractFixedNormalPostTest", "main", null, "/set/useOperationContractFixedNormalPostTest/oracle/UseOperationContractFixedNormalPostTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractInvalidPreconditionOnObjectTest - */ - @Test - public void testUseOperationContractInvalidPreconditionOnObjectTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractInvalidPreconditionOnObjectTest/test/UseOperationContractInvalidPreconditionOnObjectTest.java", - "UseOperationContractInvalidPreconditionOnObjectTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractInvalidPreconditionOnObjectTest + */ + @Test + public void testUseOperationContractInvalidPreconditionOnObjectTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractInvalidPreconditionOnObjectTest/test/UseOperationContractInvalidPreconditionOnObjectTest.java", + "UseOperationContractInvalidPreconditionOnObjectTest", "main", null, "/set/useOperationContractInvalidPreconditionOnObjectTest/oracle/UseOperationContractInvalidPreconditionOnObjectTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractInvalidPreconditionTest - */ - @Test - public void testUseOperationContractInvalidPreconditionTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractInvalidPreconditionTest/test/UseOperationContractInvalidPreconditionTest.java", - "UseOperationContractInvalidPreconditionTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractInvalidPreconditionTest + */ + @Test + public void testUseOperationContractInvalidPreconditionTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractInvalidPreconditionTest/test/UseOperationContractInvalidPreconditionTest.java", + "UseOperationContractInvalidPreconditionTest", "main", null, "/set/useOperationContractInvalidPreconditionTest/oracle/UseOperationContractInvalidPreconditionTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractNoExceptionTest - */ - @Test - public void testUseOperationContractNoExceptionTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractNoExceptionTest/test/UseOperationContractNoExceptionTest.java", - "UseOperationContractNoExceptionTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractNoExceptionTest + */ + @Test + public void testUseOperationContractNoExceptionTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractNoExceptionTest/test/UseOperationContractNoExceptionTest.java", + "UseOperationContractNoExceptionTest", "main", null, "/set/useOperationContractNoExceptionTest/oracle/UseOperationContractNoExceptionTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractNoPreconditionTest - */ - @Test - public void testUseOperationContractNoPreconditionTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractNoPreconditionTest/test/UseOperationContractNoPreconditionTest.java", - "UseOperationContractNoPreconditionTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractNoPreconditionTest + */ + @Test + public void testUseOperationContractNoPreconditionTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractNoPreconditionTest/test/UseOperationContractNoPreconditionTest.java", + "UseOperationContractNoPreconditionTest", "main", null, "/set/useOperationContractNoPreconditionTest/oracle/UseOperationContractNoPreconditionTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractNoPreconditionWithNullCheckTest - */ - @Test - public void testUseOperationContractNoPreconditionWithNullCheckTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractNoPreconditionWithNullCheckTest/test/UseOperationContractNoPreconditionWithNullCheckTest.java", - "UseOperationContractNoPreconditionWithNullCheckTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractNoPreconditionWithNullCheckTest + */ + @Test + public void testUseOperationContractNoPreconditionWithNullCheckTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractNoPreconditionWithNullCheckTest/test/UseOperationContractNoPreconditionWithNullCheckTest.java", + "UseOperationContractNoPreconditionWithNullCheckTest", "main", null, "/set/useOperationContractNoPreconditionWithNullCheckTest/oracle/UseOperationContractNoPreconditionWithNullCheckTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractNormalAndExceptionalBranchTest - */ - @Test - public void testUseOperationContractNormalAndExceptionalBranchTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractNormalAndExceptionalBranchTest/test/UseOperationContractNormalAndExceptionalBranchTest.java", - "UseOperationContractNormalAndExceptionalBranchTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractNormalAndExceptionalBranchTest + */ + @Test + public void testUseOperationContractNormalAndExceptionalBranchTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractNormalAndExceptionalBranchTest/test/UseOperationContractNormalAndExceptionalBranchTest.java", + "UseOperationContractNormalAndExceptionalBranchTest", "main", null, "/set/useOperationContractNormalAndExceptionalBranchTest/oracle/UseOperationContractNormalAndExceptionalBranchTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/useOperationContractNormalAndExceptionalTogetherTest - */ - @Test - public void testUseOperationContractNormalAndExceptionalTogetherTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/useOperationContractNormalAndExceptionalTogetherTest/test/UseOperationContractNormalAndExceptionalTogetherTest.java", - "UseOperationContractNormalAndExceptionalTogetherTest", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/useOperationContractNormalAndExceptionalTogetherTest + */ + @Test + public void testUseOperationContractNormalAndExceptionalTogetherTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/useOperationContractNormalAndExceptionalTogetherTest/test/UseOperationContractNormalAndExceptionalTogetherTest.java", + "UseOperationContractNormalAndExceptionalTogetherTest", "main", null, "/set/useOperationContractNormalAndExceptionalTogetherTest/oracle/UseOperationContractNormalAndExceptionalTogetherTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/complexConstructorTest - */ - @Disabled - @Test - public void testComplexConstructorTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/complexConstructorTest/test/ComplexConstructorTest.java", - "ComplexConstructorTest", - "main", - null, - "/set/complexConstructorTest/oracle/ComplexConstructorTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/simpleConstructorTest - */ - @Test - public void testSimpleConstructorTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/simpleConstructorTest/test/SimpleConstructorTest.java", - "SimpleConstructorTest", - "main", - null, - "/set/simpleConstructorTest/oracle/SimpleConstructorTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesUnknownTest - */ - @Test - public void testVariablesUnknownTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesUnknownTest/test/UnknownTest.java", - "endless.UnknownTest", - "main", - null, - "/set/variablesUnknownTest/oracle/UnknownTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesParameterAttributesChange - */ - @Test - public void testElseIfTest_variablesParameterAttributesChange() throws Exception { - doSETTest(testCaseDirectory, - "/set/variablesParameterAttributesChange/test/VariablesParameterAttributesChange.java", - "VariablesParameterAttributesChange", - "main", - null, + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, true, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/complexConstructorTest + */ + @Disabled + @Test + public void testComplexConstructorTest() throws Exception { + doSETTest(testCaseDirectory, "/set/complexConstructorTest/test/ComplexConstructorTest.java", + "ComplexConstructorTest", "main", null, + "/set/complexConstructorTest/oracle/ComplexConstructorTest.xml", false, false, true, + true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/simpleConstructorTest + */ + @Test + public void testSimpleConstructorTest() throws Exception { + doSETTest(testCaseDirectory, "/set/simpleConstructorTest/test/SimpleConstructorTest.java", + "SimpleConstructorTest", "main", null, + "/set/simpleConstructorTest/oracle/SimpleConstructorTest.xml", false, false, true, + true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/variablesUnknownTest + */ + @Test + public void testVariablesUnknownTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/variablesUnknownTest/test/UnknownTest.java", + "endless.UnknownTest", "main", null, + "/set/variablesUnknownTest/oracle/UnknownTest.xml", false, true, false, false, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + } + + /** + * Tests example: /set/variablesParameterAttributesChange + */ + @Test + public void testElseIfTest_variablesParameterAttributesChange() throws Exception { + doSETTest(testCaseDirectory, + "/set/variablesParameterAttributesChange/test/VariablesParameterAttributesChange.java", + "VariablesParameterAttributesChange", "main", null, "/set/variablesParameterAttributesChange/oracle/VariablesParameterAttributesChange.xml", - false, - true, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/elseIfTest - */ - @Test - public void testElseIfTest_mergedBranchConditions() throws Exception { - doSETTest(testCaseDirectory, - "/set/elseIfTest/test/ElseIfTest.java", - "ElseIfTest", - "elseIf", - null, - "/set/elseIfTest/oracle/ElseIfTestMergedBranchConditions.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - true, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/switchCaseTest - */ - @Test - public void testSwitchCaseTest_mergedBranchConditions() throws Exception { - doSETTest(testCaseDirectory, - "/set/switchCaseTest/test/SwitchCaseTest.java", - "SwitchCaseTest", - "switchCase", - null, - "/set/switchCaseTest/oracle/SwitchCaseTestMergedBranchConditions.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - true, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/loopIterationTest - */ - @Test - public void testLoopIteration_LoopWithMethod() throws Exception { - doSETTest(testCaseDirectory, - "/set/loopIterationTest/test/LoopIterationTest.java", - "LoopIterationTest", - "loopMultipleTimes", - null, - "/set/loopIterationTest/oracle/LoopIterationTest_loopMultipleTimes.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/loopIterationTest - */ - @Test - public void testLoopIteration_LoopStatementCopied() throws Exception { - doSETTest(testCaseDirectory, - "/set/loopIterationTest/test/LoopIterationTest.java", - "LoopIterationTest", - "mainWorks", - null, - "/set/loopIterationTest/oracle/LoopIterationTest_mainWorks.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/loopIterationTest - */ - @Test - public void testLoopIteration_LoopStatementReused() throws Exception { - doSETTest(testCaseDirectory, - "/set/loopIterationTest/test/LoopIterationTest.java", - "LoopIterationTest", - "main", - null, - "/set/loopIterationTest/oracle/LoopIterationTest_main.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesArrayTest - */ - @Test - public void testVariablesArrayTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesArrayTest/test/VariablesArrayTest.java", - "VariablesArrayTest", - "main", - null, - "/set/variablesArrayTest/oracle/VariablesArrayTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesInstanceVariableTest - */ - @Test - public void testVariablesInstanceVariableTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesInstanceVariableTest/test/VariablesInstanceVariableTest.java", - "VariablesInstanceVariableTest", - "main", - null, - "/set/variablesInstanceVariableTest/oracle/VariablesInstanceVariableTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesLocalTest - */ - @Test - public void testVariablesLocalTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesLocalTest/test/VariablesLocalTest.java", - "VariablesLocalTest", - "main", - null, - "/set/variablesLocalTest/oracle/VariablesLocalTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/variablesStaticTest - */ - @Test - public void testVariablesStaticTest() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/variablesStaticTest/test/VariablesStaticTest.java", - "VariablesStaticTest", - "main", - null, - "/set/variablesStaticTest/oracle/VariablesStaticTest.xml", - false, - true, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/complexFlatSteps - */ - @Test - public void testComplexFlatSteps() throws Exception { - doSETTest(testCaseDirectory, - "/set/complexFlatSteps/test/ComplexFlatSteps.java", - "ComplexFlatSteps", - "doSomething", - null, - "/set/complexFlatSteps/oracle/ComplexFlatSteps.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/complexIf - */ - @Test - public void testComplexIf() throws Exception { - doSETTest(testCaseDirectory, - "/set/complexIf/test/ComplexIf.java", - "ComplexIf", - "min", - null, - "/set/complexIf/oracle/ComplexIf.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/doWhileFalseTest - */ - @Test - public void testDoWhileFlaseTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/doWhileFalseTest/test/DoWhileFalseTest.java", - "DoWhileFalseTest", - "main", - null, - "/set/doWhileFalseTest/oracle/DoWhileFalseTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/doWhileTest - */ - @Test - public void testDoWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/doWhileTest/test/DoWhileTest.java", - "DoWhileTest", - "main", - null, - "/set/doWhileTest/oracle/DoWhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/elseIfDifferentVariables - */ - @Test - public void testElseIfDifferentVariables() throws Exception { - doSETTest(testCaseDirectory, - "/set/elseIfDifferentVariables/test/ElseIfDifferentVariables.java", - "ElseIfDifferentVariables", - "main", - null, - "/set/elseIfDifferentVariables/oracle/ElseIfDifferentVariables.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/elseIfTest - */ - @Test - public void testElseIfTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/elseIfTest/test/ElseIfTest.java", - "ElseIfTest", - "elseIf", - null, - "/set/elseIfTest/oracle/ElseIfTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/fixedRecursiveMethodCallTest - */ - @Test - public void testFixedRecursiveMethodCallTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/fixedRecursiveMethodCallTest/test/FixedRecursiveMethodCallTest.java", - "FixedRecursiveMethodCallTest", - "decreaseValue", - null, - "/set/fixedRecursiveMethodCallTest/oracle/FixedRecursiveMethodCallTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/forEachTest - */ - @Test - public void testForEachTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/forEachTest/test/ForEachTest.java", - "ForEachTest", - "main", - null, - "/set/forEachTest/oracle/ForEachTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/forFalseTest - */ - @Test - public void testForFalseTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/forFalseTest/test/ForFalseTest.java", - "ForFalseTest", - "main", - null, - "/set/forFalseTest/oracle/ForFalseTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/forTest - */ - @Test - public void testForTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/forTest/test/ForTest.java", - "ForTest", - "main", - null, - "/set/forTest/oracle/ForTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/functionalDoWhileTest - */ - @Test - public void testFunctionalDoWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/functionalDoWhileTest/test/FunctionalDoWhileTest.java", - "FunctionalDoWhileTest", - "main", - null, - "/set/functionalDoWhileTest/oracle/FunctionalDoWhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/functionalForTest - */ - @Test - public void testFunctionalForTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/functionalForTest/test/FunctionalForTest.java", - "FunctionalForTest", - "main", - null, - "/set/functionalForTest/oracle/FunctionalForTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/functionalIf - */ - @Test - public void testFunctionalIf() throws Exception { - doSETTest(testCaseDirectory, - "/set/functionalIf/test/FunctionalIf.java", - "FunctionalIf", - "min", - null, - "/set/functionalIf/oracle/FunctionalIf.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/functionalWhileTest - */ - @Test - public void testFunctionalWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/functionalWhileTest/test/FunctionalWhileTest.java", - "FunctionalWhileTest", - "main", - null, - "/set/functionalWhileTest/oracle/FunctionalWhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodCallOnObject - */ - @Test - public void testMethodCallOnObject() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodCallOnObject/test/MethodCallOnObject.java", - "MethodCallOnObject", - "main", - null, - "/set/methodCallOnObject/oracle/MethodCallOnObject.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodCallOnObjectWithException - */ - @Test - public void testMethodCallOnObjectWithException() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodCallOnObjectWithException/test/MethodCallOnObjectWithException.java", - "MethodCallOnObjectWithException", - "main", - null, + false, true, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/elseIfTest + */ + @Test + public void testElseIfTest_mergedBranchConditions() throws Exception { + doSETTest(testCaseDirectory, "/set/elseIfTest/test/ElseIfTest.java", "ElseIfTest", "elseIf", + null, "/set/elseIfTest/oracle/ElseIfTestMergedBranchConditions.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, true, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/switchCaseTest + */ + @Test + public void testSwitchCaseTest_mergedBranchConditions() throws Exception { + doSETTest(testCaseDirectory, "/set/switchCaseTest/test/SwitchCaseTest.java", + "SwitchCaseTest", "switchCase", null, + "/set/switchCaseTest/oracle/SwitchCaseTestMergedBranchConditions.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, true, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/loopIterationTest + */ + @Test + public void testLoopIteration_LoopWithMethod() throws Exception { + doSETTest(testCaseDirectory, "/set/loopIterationTest/test/LoopIterationTest.java", + "LoopIterationTest", "loopMultipleTimes", null, + "/set/loopIterationTest/oracle/LoopIterationTest_loopMultipleTimes.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/loopIterationTest + */ + @Test + public void testLoopIteration_LoopStatementCopied() throws Exception { + doSETTest(testCaseDirectory, "/set/loopIterationTest/test/LoopIterationTest.java", + "LoopIterationTest", "mainWorks", null, + "/set/loopIterationTest/oracle/LoopIterationTest_mainWorks.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/loopIterationTest + */ + @Test + public void testLoopIteration_LoopStatementReused() throws Exception { + doSETTest(testCaseDirectory, "/set/loopIterationTest/test/LoopIterationTest.java", + "LoopIterationTest", "main", null, + "/set/loopIterationTest/oracle/LoopIterationTest_main.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/variablesArrayTest + */ + @Test + public void testVariablesArrayTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesArrayTest/test/VariablesArrayTest.java", "VariablesArrayTest", + "main", null, "/set/variablesArrayTest/oracle/VariablesArrayTest.xml", false, true, + false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/variablesInstanceVariableTest + */ + @Test + public void testVariablesInstanceVariableTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesInstanceVariableTest/test/VariablesInstanceVariableTest.java", + "VariablesInstanceVariableTest", "main", null, + "/set/variablesInstanceVariableTest/oracle/VariablesInstanceVariableTest.xml", + false, true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/variablesLocalTest + */ + @Test + public void testVariablesLocalTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesLocalTest/test/VariablesLocalTest.java", "VariablesLocalTest", + "main", null, "/set/variablesLocalTest/oracle/VariablesLocalTest.xml", false, true, + false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/variablesStaticTest + */ + @Test + public void testVariablesStaticTest() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/variablesStaticTest/test/VariablesStaticTest.java", "VariablesStaticTest", + "main", null, "/set/variablesStaticTest/oracle/VariablesStaticTest.xml", false, + true, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/complexFlatSteps + */ + @Test + public void testComplexFlatSteps() throws Exception { + doSETTest(testCaseDirectory, "/set/complexFlatSteps/test/ComplexFlatSteps.java", + "ComplexFlatSteps", "doSomething", null, + "/set/complexFlatSteps/oracle/ComplexFlatSteps.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/complexIf + */ + @Test + public void testComplexIf() throws Exception { + doSETTest(testCaseDirectory, "/set/complexIf/test/ComplexIf.java", "ComplexIf", "min", null, + "/set/complexIf/oracle/ComplexIf.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/doWhileFalseTest + */ + @Test + public void testDoWhileFlaseTest() throws Exception { + doSETTest(testCaseDirectory, "/set/doWhileFalseTest/test/DoWhileFalseTest.java", + "DoWhileFalseTest", "main", null, + "/set/doWhileFalseTest/oracle/DoWhileFalseTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/doWhileTest + */ + @Test + public void testDoWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/doWhileTest/test/DoWhileTest.java", "DoWhileTest", + "main", null, "/set/doWhileTest/oracle/DoWhileTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/elseIfDifferentVariables + */ + @Test + public void testElseIfDifferentVariables() throws Exception { + doSETTest(testCaseDirectory, + "/set/elseIfDifferentVariables/test/ElseIfDifferentVariables.java", + "ElseIfDifferentVariables", "main", null, + "/set/elseIfDifferentVariables/oracle/ElseIfDifferentVariables.xml", false, false, + false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/elseIfTest + */ + @Test + public void testElseIfTest() throws Exception { + doSETTest(testCaseDirectory, "/set/elseIfTest/test/ElseIfTest.java", "ElseIfTest", "elseIf", + null, "/set/elseIfTest/oracle/ElseIfTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/fixedRecursiveMethodCallTest + */ + @Test + public void testFixedRecursiveMethodCallTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/fixedRecursiveMethodCallTest/test/FixedRecursiveMethodCallTest.java", + "FixedRecursiveMethodCallTest", "decreaseValue", null, + "/set/fixedRecursiveMethodCallTest/oracle/FixedRecursiveMethodCallTest.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/forEachTest + */ + @Test + public void testForEachTest() throws Exception { + doSETTest(testCaseDirectory, "/set/forEachTest/test/ForEachTest.java", "ForEachTest", + "main", null, "/set/forEachTest/oracle/ForEachTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/forFalseTest + */ + @Test + public void testForFalseTest() throws Exception { + doSETTest(testCaseDirectory, "/set/forFalseTest/test/ForFalseTest.java", "ForFalseTest", + "main", null, "/set/forFalseTest/oracle/ForFalseTest.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/forTest + */ + @Test + public void testForTest() throws Exception { + doSETTest(testCaseDirectory, "/set/forTest/test/ForTest.java", "ForTest", "main", null, + "/set/forTest/oracle/ForTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/functionalDoWhileTest + */ + @Test + public void testFunctionalDoWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/functionalDoWhileTest/test/FunctionalDoWhileTest.java", + "FunctionalDoWhileTest", "main", null, + "/set/functionalDoWhileTest/oracle/FunctionalDoWhileTest.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/functionalForTest + */ + @Test + public void testFunctionalForTest() throws Exception { + doSETTest(testCaseDirectory, "/set/functionalForTest/test/FunctionalForTest.java", + "FunctionalForTest", "main", null, + "/set/functionalForTest/oracle/FunctionalForTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/functionalIf + */ + @Test + public void testFunctionalIf() throws Exception { + doSETTest(testCaseDirectory, "/set/functionalIf/test/FunctionalIf.java", "FunctionalIf", + "min", null, "/set/functionalIf/oracle/FunctionalIf.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/functionalWhileTest + */ + @Test + public void testFunctionalWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/functionalWhileTest/test/FunctionalWhileTest.java", + "FunctionalWhileTest", "main", null, + "/set/functionalWhileTest/oracle/FunctionalWhileTest.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/methodCallOnObject + */ + @Test + public void testMethodCallOnObject() throws Exception { + doSETTest(testCaseDirectory, "/set/methodCallOnObject/test/MethodCallOnObject.java", + "MethodCallOnObject", "main", null, + "/set/methodCallOnObject/oracle/MethodCallOnObject.xml", false, false, false, true, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/methodCallOnObjectWithException + */ + @Test + public void testMethodCallOnObjectWithException() throws Exception { + doSETTest(testCaseDirectory, + "/set/methodCallOnObjectWithException/test/MethodCallOnObjectWithException.java", + "MethodCallOnObjectWithException", "main", null, "/set/methodCallOnObjectWithException/oracle/MethodCallOnObjectWithException.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodCallParallelTest - */ - @Test - public void testMethodCallParallelTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodCallParallelTest/test/MethodCallParallelTest.java", - "MethodCallParallelTest", - "main", - null, - "/set/methodCallParallelTest/oracle/MethodCallParallelTest.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodFormatTest - */ - @Test - public void testMethodFormatTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodFormatTest/test/MethodFormatTest.java", - "MethodFormatTest", - "main", - null, - "/set/methodFormatTest/oracle/MethodFormatTest.xml", - false, - false, - false, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodHierarchyCallTest - */ - @Test - public void testMethodHierarchyCallTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodHierarchyCallTest/test/MethodHierarchyCallTest.java", - "MethodHierarchyCallTest", - "main", - null, - "/set/methodHierarchyCallTest/oracle/MethodHierarchyCallTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/methodHierarchyCallWithExceptionTest - */ - @Test - public void testMethodHierarchyCallWithExceptionTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/methodHierarchyCallWithExceptionTest/test/MethodHierarchyCallWithExceptionTest.java", - "MethodHierarchyCallWithExceptionTest", - "main", - null, + false, false, false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/methodCallParallelTest + */ + @Test + public void testMethodCallParallelTest() throws Exception { + doSETTest(testCaseDirectory, "/set/methodCallParallelTest/test/MethodCallParallelTest.java", + "MethodCallParallelTest", "main", null, + "/set/methodCallParallelTest/oracle/MethodCallParallelTest.xml", false, false, + false, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/methodFormatTest + */ + @Test + public void testMethodFormatTest() throws Exception { + doSETTest(testCaseDirectory, "/set/methodFormatTest/test/MethodFormatTest.java", + "MethodFormatTest", "main", null, + "/set/methodFormatTest/oracle/MethodFormatTest.xml", false, false, false, true, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/methodHierarchyCallTest + */ + @Test + public void testMethodHierarchyCallTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/methodHierarchyCallTest/test/MethodHierarchyCallTest.java", + "MethodHierarchyCallTest", "main", null, + "/set/methodHierarchyCallTest/oracle/MethodHierarchyCallTest.xml", false, false, + true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, + false, false, false, false, true); + } + + /** + * Tests example: /set/methodHierarchyCallWithExceptionTest + */ + @Test + public void testMethodHierarchyCallWithExceptionTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/methodHierarchyCallWithExceptionTest/test/MethodHierarchyCallWithExceptionTest.java", + "MethodHierarchyCallWithExceptionTest", "main", null, "/set/methodHierarchyCallWithExceptionTest/oracle/MethodHierarchyCallWithExceptionTest.xml", - false, - false, - true, - true, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nestedDoWhileTest - */ - @Test - public void testNestedDoWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/nestedDoWhileTest/test/NestedDoWhileTest.java", - "NestedDoWhileTest", - "main", - null, - "/set/nestedDoWhileTest/oracle/NestedDoWhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nestedForTest - */ - @Test - public void testNestedForTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/nestedForTest/test/NestedForTest.java", - "NestedForTest", - "main", - null, - "/set/nestedForTest/oracle/NestedForTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nestedWhileTest - */ - @Test - public void testNestedWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/nestedWhileTest/test/NestedWhileTest.java", - "NestedWhileTest", - "mainNested", - null, - "/set/nestedWhileTest/oracle/NestedWhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - *

    - * Tests example: /set/recursiveFibonacci - *

    - *

    - * This test produces a deep symbolic execution tree to make sure - * that no {@link StackOverflowError}s are thrown. - *

    - */ - @Test - public void testRecursiveFibonacci_LONG_RUNNING_TEST() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/recursiveFibonacci/test/RecursiveFibonacci.java", - "RecursiveFibonacci", - "fibonacci10", - null, - "/set/recursiveFibonacci/oracle/RecursiveFibonacci.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/simpleIf - */ - @Test - public void testSimpleIf() throws Exception { - doSETTest(testCaseDirectory, - "/set/simpleIf/test/SimpleIf.java", - "SimpleIf", - "min", - null, - "/set/simpleIf/oracle/SimpleIf.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/simpleNullPointerSplitTest - */ - @Test - public void testSimpleNullPointerSplitTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/simpleNullPointerSplitTest/test/SimpleNullPointerSplitTest.java", - "SimpleNullPointerSplitTest", - "main", - null, - "/set/simpleNullPointerSplitTest/oracle/SimpleNullPointerSplitTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/statementKindTest - */ - @Test - public void testStatementKindTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/statementKindTest/test/StatementKindTest.java", - "StatementKindTest", - "main", - null, - "/set/statementKindTest/oracle/StatementKindTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/statements - */ - @Test - public void testStatements() throws Exception { - doSETTest(testCaseDirectory, - "/set/statements/test/FlatSteps.java", - "FlatSteps", - "doSomething", - null, - "/set/statements/oracle/FlatSteps.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/staticMethodCall - */ - @Test - public void testStaticMethodCall() throws Exception { - doSETTest(testCaseDirectory, - "/set/staticMethodCall/test/StaticMethodCall.java", - "StaticMethodCall", - "main", - null, - "/set/staticMethodCall/oracle/StaticMethodCall.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/switchCaseTest - */ - @Test - public void testSwitchCaseTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/switchCaseTest/test/SwitchCaseTest.java", - "SwitchCaseTest", - "switchCase", - null, - "/set/switchCaseTest/oracle/SwitchCaseTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/throwTest - */ - @Test - public void testThrowTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/throwTest/test/ThrowTest.java", - "ThrowTest", - "main", - null, - "/set/throwTest/oracle/ThrowTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/throwVariableTest - */ - @Test - public void testThrowVariableTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/throwVariableTest/test/ThrowVariableTest.java", - "ThrowVariableTest", - "main", - null, - "/set/throwVariableTest/oracle/ThrowVariableTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/tryCatchFinally - */ - @Test - public void testTryCatchFinally() throws Exception { - doSETTest(testCaseDirectory, - "/set/tryCatchFinally/test/TryCatchFinally.java", - "TryCatchFinally", - "tryCatchFinally", - null, - "/set/tryCatchFinally/oracle/TryCatchFinally.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/whileFalseTest - */ - @Test - public void testWhileFalseTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/whileFalseTest/test/WhileFalseTest.java", - "WhileFalseTest", - "main", - null, - "/set/whileFalseTest/oracle/WhileFalseTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/whileTest - */ - @Test - public void testWhileTest() throws Exception { - doSETTest(testCaseDirectory, - "/set/whileTest/test/WhileTest.java", - "WhileTest", - "main", - null, - "/set/whileTest/oracle/WhileTest.xml", - false, - false, - false, - false, - DEFAULT_MAXIMAL_SET_NODES_PER_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } + false, false, true, true, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/nestedDoWhileTest + */ + @Test + public void testNestedDoWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/nestedDoWhileTest/test/NestedDoWhileTest.java", + "NestedDoWhileTest", "main", null, + "/set/nestedDoWhileTest/oracle/NestedDoWhileTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/nestedForTest + */ + @Test + public void testNestedForTest() throws Exception { + doSETTest(testCaseDirectory, "/set/nestedForTest/test/NestedForTest.java", "NestedForTest", + "main", null, "/set/nestedForTest/oracle/NestedForTest.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/nestedWhileTest + */ + @Test + public void testNestedWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/nestedWhileTest/test/NestedWhileTest.java", + "NestedWhileTest", "mainNested", null, + "/set/nestedWhileTest/oracle/NestedWhileTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + *

    + * Tests example: /set/recursiveFibonacci + *

    + *

    + * This test produces a deep symbolic execution tree to make sure that no + * {@link StackOverflowError}s are thrown. + *

    + */ + @Test + public void testRecursiveFibonacci_LONG_RUNNING_TEST() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/recursiveFibonacci/test/RecursiveFibonacci.java", "RecursiveFibonacci", + "fibonacci10", null, "/set/recursiveFibonacci/oracle/RecursiveFibonacci.xml", false, + false, false, false, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/simpleIf + */ + @Test + public void testSimpleIf() throws Exception { + doSETTest(testCaseDirectory, "/set/simpleIf/test/SimpleIf.java", "SimpleIf", "min", null, + "/set/simpleIf/oracle/SimpleIf.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/simpleNullPointerSplitTest + */ + @Test + public void testSimpleNullPointerSplitTest() throws Exception { + doSETTest(testCaseDirectory, + "/set/simpleNullPointerSplitTest/test/SimpleNullPointerSplitTest.java", + "SimpleNullPointerSplitTest", "main", null, + "/set/simpleNullPointerSplitTest/oracle/SimpleNullPointerSplitTest.xml", false, + false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, + false, false, false, false, false, true); + } + + /** + * Tests example: /set/statementKindTest + */ + @Test + public void testStatementKindTest() throws Exception { + doSETTest(testCaseDirectory, "/set/statementKindTest/test/StatementKindTest.java", + "StatementKindTest", "main", null, + "/set/statementKindTest/oracle/StatementKindTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/statements + */ + @Test + public void testStatements() throws Exception { + doSETTest(testCaseDirectory, "/set/statements/test/FlatSteps.java", "FlatSteps", + "doSomething", null, "/set/statements/oracle/FlatSteps.xml", false, false, false, + false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/staticMethodCall + */ + @Test + public void testStaticMethodCall() throws Exception { + doSETTest(testCaseDirectory, "/set/staticMethodCall/test/StaticMethodCall.java", + "StaticMethodCall", "main", null, + "/set/staticMethodCall/oracle/StaticMethodCall.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/switchCaseTest + */ + @Test + public void testSwitchCaseTest() throws Exception { + doSETTest(testCaseDirectory, "/set/switchCaseTest/test/SwitchCaseTest.java", + "SwitchCaseTest", "switchCase", null, + "/set/switchCaseTest/oracle/SwitchCaseTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/throwTest + */ + @Test + public void testThrowTest() throws Exception { + doSETTest(testCaseDirectory, "/set/throwTest/test/ThrowTest.java", "ThrowTest", "main", + null, "/set/throwTest/oracle/ThrowTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/throwVariableTest + */ + @Test + public void testThrowVariableTest() throws Exception { + doSETTest(testCaseDirectory, "/set/throwVariableTest/test/ThrowVariableTest.java", + "ThrowVariableTest", "main", null, + "/set/throwVariableTest/oracle/ThrowVariableTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/tryCatchFinally + */ + @Test + public void testTryCatchFinally() throws Exception { + doSETTest(testCaseDirectory, "/set/tryCatchFinally/test/TryCatchFinally.java", + "TryCatchFinally", "tryCatchFinally", null, + "/set/tryCatchFinally/oracle/TryCatchFinally.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } + + /** + * Tests example: /set/whileFalseTest + */ + @Test + public void testWhileFalseTest() throws Exception { + doSETTest(testCaseDirectory, "/set/whileFalseTest/test/WhileFalseTest.java", + "WhileFalseTest", "main", null, "/set/whileFalseTest/oracle/WhileFalseTest.xml", + false, false, false, false, DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, + false, false, false, false, false, false, true); + } + + /** + * Tests example: /set/whileTest + */ + @Test + public void testWhileTest() throws Exception { + doSETTest(testCaseDirectory, "/set/whileTest/test/WhileTest.java", "WhileTest", "main", + null, "/set/whileTest/oracle/WhileTest.xml", false, false, false, false, + DEFAULT_MAXIMAL_SET_NODES_PER_RUN, false, false, false, false, false, false, false, + false, false, true); + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutExtractor.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutExtractor.java index 847c784a6ac..4aa79dab1e1 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutExtractor.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutExtractor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -24,1051 +27,885 @@ /** * Tests {@link SymbolicLayoutExtractor}. + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) @Tag("slow") @Disabled public class TestSymbolicLayoutExtractor extends AbstractSymbolicExecutionTestCase { - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test - public void testEmptyArrayCreationTest() throws Exception { - doTest("/set/configurationExtractorEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", - "EmptyArrayCreationTest", - "/set/configurationExtractorEmptyArrayCreationTest/oracle/", - "EmptyArrayCreationTest.xml", - "testEmptyArrayCreationTest_initial", - ".xml", - "testEmptyArrayCreationTest_current", - ".xml", - "n == 0", - 1, - 1, - false, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayCreationTest() throws Exception { - doTest("/set/configurationExtractorArrayCreationTest/test/ArrayCreationTest.java", - "ArrayCreationTest", - "/set/configurationExtractorArrayCreationTest/oracle/", - "ArrayCreationTest.xml", - "testArrayCreationTest_initial", - ".xml", - "testArrayCreationTest_current", - ".xml", - "n >= 4", - 1, - 1, - false, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testMyInteger() throws Exception { - doTest("/set/configurationExtractorMyInteger/test/MyInteger.java", - "MyInteger", - "/set/configurationExtractorMyInteger/oracle/", - "StaticMember.xml", - "testMyInteger_initial", - ".xml", - "testMyInteger_current", - ".xml", - null, - 1, - 2, - false, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testVariableArrayIndex() throws Exception { - doTest("/set/configurationExtractorVariableArrayIndex/test/VariableArrayIndex.java", - "VariableArrayIndex", - "/set/configurationExtractorVariableArrayIndex/oracle/", - "StaticMember.xml", - "testVariableArrayIndex_initial", - ".xml", - "testVariableArrayIndex_current", - ".xml", - null, - 1, - 1, - false, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testStaticMember_OnReturnNode() throws Exception { - doTest("/set/configurationExtractorStaticMember/test/StaticMember.java", - "StaticMember", - "/set/configurationExtractorStaticMember/oracle/", - "StaticMember.xml", - "testInstanceCreationTest_staticMember_initial", - ".xml", - "testInstanceCreationTest_staticMember_current", - ".xml", - null, - 1, - 2, - false, - false); - } - - /** - * Tests "configurationExtractorExistsQuantifierTest". - * @throws Exception Occurred Exception. - */ - @Test public void testExistsQuantifierTest() throws Exception { - doTest("/set/configurationExtractorExistsQuantifierTest/test/ExistsQuantifierTest.proof", - "/set/configurationExtractorExistsQuantifierTest/oracle/", - "ExistsQuantifierTest.xml", - "testExistsQuantifierTest_initial", - ".xml", - "testExistsQuantifierTest_current", - ".xml", - null, - 1, - 2, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testInstanceCreationTest_OnReturnNode() throws Exception { - doTest("/set/configurationExtractorInstanceCreationTest/test/InstanceCreationTest.java", - "InstanceCreationTest", - "/set/configurationExtractorInstanceCreationTest/oracle/", - "InstanceCreationTest.xml", - "testInstanceCreationTest_onReturnNode_initial", - ".xml", - "testInstanceCreationTest_onReturnNode_current", - ".xml", - null, - 5, - 2, - false, - false); - } - - /** - * Tests "configurationExtractorWithOperationContractsTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testWithOperationContracts() throws Exception { - doTest("/set/configurationExtractorWithOperationContractsTest/test/ConfigurationExtractorWithOperationContractsTest.java", - "ConfigurationExtractorWithOperationContractsTest", - "/set/configurationExtractorWithOperationContractsTest/oracle/", - "ConfigurationExtractorWithOperationContractsTest.xml", - "testWithOperationContracts_initial", - ".xml", - "testWithOperationContracts_current", - ".xml", - null, - 1, - 2, - true); - } - - /** - * Tests "configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass() throws Exception { - doTest("/set/configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass/test/AssociationSourceIsNotRepresentativeTermOfEquivalenceClass.java", - "algorithm.AssociationSourceIsNotRepresentativeTermOfEquivalenceClass", - "/set/configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass/oracle/", - "AssociationSourceIsNotRepresentativeTermOfEquivalenceClass.xml", - "testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass_initial", - ".xml", - "testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass_current", - ".xml", - null, - 1, - 3, - false); - } - - /** - * Tests "configurationExtractorArrayInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayInstanceCreationTest() throws Exception { - doTest("/set/configurationExtractorArrayInstanceCreationTest/test/ArrayInstanceCreationTest.java", - "ArrayInstanceCreationTest", - "/set/configurationExtractorArrayInstanceCreationTest/oracle/", - "ArrayInstanceCreationTest.xml", - "testArrayInstanceCreationTest_initial", - ".xml", - "testArrayInstanceCreationTest_current", - ".xml", - null, - 1, - 2, - false); - } - - /** - * Tests "configurationExtractorInstanceCreationTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testInstanceCreationTest() throws Exception { - doTest("/set/configurationExtractorInstanceCreationTest/test/InstanceCreationTest.java", - "InstanceCreationTest", - "/set/configurationExtractorInstanceCreationTest/oracle/", - "InstanceCreationTest.xml", - "testInstanceCreationTest_initial", - ".xml", - "testInstanceCreationTest_current", - ".xml", - null, - 5, - 2, - false); - } - - /** - * Tests "configurationExtractorSimpleArrayCreation" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleArrayCreation() throws Exception { - doTest("/set/configurationExtractorSimpleArrayCreation/test/SimpleArrayCreation.java", - "SimpleArrayCreation", - "/set/configurationExtractorSimpleArrayCreation/oracle/", - "SimpleArrayCreation.xml", - "testSimpleArrayCreation_initial", - ".xml", - "testSimpleArrayCreation_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorMultiArrayIndexReadWriteAccess" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testMultiArrayIndexReadWriteAccess() throws Exception { - doTest("/set/configurationExtractorMultiArrayIndexReadWriteAccess/test/MultiArrayIndexReadWriteAccess.java", - "MultiArrayIndexReadWriteAccess", - "/set/configurationExtractorMultiArrayIndexReadWriteAccess/oracle/", - "MultiArrayIndexReadWriteAccess.xml", - "testMultiArrayIndexReadWriteAccess_initial", - ".xml", - "testMultiArrayIndexReadWriteAccess_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedArrays" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedArrays() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedArrays/test/SimpleLinkedArrays.java", - "SimpleLinkedArrays", - "/set/configurationExtractorSimpleLinkedArrays/oracle/", - "SimpleLinkedArrays.xml", - "testSimpleLinkedArrays_initial", - ".xml", - "testSimpleLinkedArrays_current", - ".xml", - null, - 1, - 5, - false); - } - - /** - * Tests "configurationExtractorObjectArrayIndexWriteAccess" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testObjectArrayIndexWriteAccess() throws Exception { - doTest("/set/configurationExtractorObjectArrayIndexWriteAccess/test/ObjectArrayIndexWriteAccess.java", - "ObjectArrayIndexWriteAccess", - "/set/configurationExtractorObjectArrayIndexWriteAccess/oracle/", - "ObjectArrayIndexWriteAccess.xml", - "testObjectArrayIndexWriteAccess_initial", - ".xml", - "testObjectArrayIndexWriteAccess_current", - ".xml", - null, - 2, - 1, - false); - } - - /** - * Tests "configurationExtractorArrayIndexWriteAccess" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexWriteAccess() throws Exception { - doTest("/set/configurationExtractorArrayIndexWriteAccess/test/ArrayIndexWriteAccess.java", - "ArrayIndexWriteAccess", - "/set/configurationExtractorArrayIndexWriteAccess/oracle/", - "ArrayIndexWriteAccess.xml", - "testArrayIndexWriteAccess_initial", - ".xml", - "testArrayIndexWriteAccess_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorObjectArrayIndexReadAccess" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testObjectArrayIndexReadAccess() throws Exception { - doTest("/set/configurationExtractorObjectArrayIndexReadAccess/test/ObjectArrayIndexReadAccess.java", - "ObjectArrayIndexReadAccess", - "/set/configurationExtractorObjectArrayIndexReadAccess/oracle/", - "ObjectArrayIndexReadAccess.xml", - "testObjectArrayIndexReadAccess_initial", - ".xml", - "testObjectArrayIndexReadAccess_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorOneAssignmentTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexReadAccess() throws Exception { - doTest("/set/configurationExtractorArrayIndexReadAccess/test/ArrayIndexReadAccess.java", - "ArrayIndexReadAccess", - "/set/configurationExtractorArrayIndexReadAccess/oracle/", - "ArrayIndexReadAccess.xml", - "testArrayIndexReadAccess_initial", - ".xml", - "testArrayIndexReadAccess_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorOneAssignmentTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testOneAssignmentTest() throws Exception { - doTest("/set/configurationExtractorOneAssignmentTest/test/OneAssignmentTest.java", - "OneAssignmentTest", - "/set/configurationExtractorOneAssignmentTest/oracle/", - "OneAssignmentTest.xml", - "testOneAssignmentTest_initial", - ".xml", - "testOneAssignmentTest_current", - ".xml", - null, - 1, - 5, - false); - } - - /** - * Tests "configurationExtractorEmptyPathConditionAndNoUpdates" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testEmptyPathConditionAndNoUpdates() throws Exception { - doTest("/set/configurationExtractorEmptyPathConditionAndNoUpdates/test/EmptyPathConditionAndNoUpdates.java", - "EmptyPathConditionAndNoUpdates", - "/set/configurationExtractorEmptyPathConditionAndNoUpdates/oracle/", - "EmptyPathConditionAndNoUpdates.xml", - "testEmptyPathConditionAndNoUpdates_initial", - ".xml", - "testEmptyPathConditionAndNoUpdates_current", - ".xml", - null, - 1, - 2, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedOjbectsInsertion" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbectsInsertion() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbectsInsertion/test/SimpleLinkedOjbectsInsertion.java", - "SimpleLinkedOjbectsInsertion", - "/set/configurationExtractorSimpleLinkedOjbectsInsertion/oracle/", - "SimpleLinkedOjbectsInsertion.xml", - "testSimpleLinkedOjbectsInsertion_initial", - ".xml", - "testSimpleLinkedOjbectsInsertion_current", - ".xml", - null, - 2, - 4, - false); - } - - /** - * Tests "configurationExtractorIntegerConditionTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testObjectConditionTest() throws Exception { - doTest("/set/configurationExtractorObjectConditionTest/test/ObjectConditionTest.java", - "ObjectConditionTest", - "/set/configurationExtractorObjectConditionTest/oracle/", - "ObjectConditionTest.xml", - "testObjectConditionTestt_initial", - ".xml", - "testObjectConditionTest_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorIntegerConditionTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testIntegerConditionTest() throws Exception { - doTest("/set/configurationExtractorIntegerConditionTest/test/IntegerConditionTest.java", - "IntegerConditionTest", - "/set/configurationExtractorIntegerConditionTest/oracle/", - "IsInstanceTest.xml", - "testIntegerConditionTest_initial", - ".xml", - "testIntegerConditionTest_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorIsInstanceTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testIsInstanceTest() throws Exception { - doTest("/set/configurationExtractorIsInstanceTest/test/IsInstanceTest.java", - "IsInstanceTest", - "/set/configurationExtractorIsInstanceTest/oracle/", - "IsInstanceTest.xml", - "testIsInstanceTest_initial", - ".xml", - "testIsInstanceTest_current", - ".xml", - null, - 1, - 2, - false); - } - - /** - * Tests "configurationExtractorIsNullTest" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testIsNullTest() throws Exception { - doTest("/set/configurationExtractorIsNullTest/test/IsNullTest.java", - "IsNullTest", - "/set/configurationExtractorIsNullTest/oracle/", - "NullInEquivalenceClass.xml", - "testIsNullTest_initial", - ".xml", - "testIsNullTest_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedOjbects" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbectsInstanceVariable() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbectsInstanceVariable/test/SimpleLinkedOjbectsInstanceVariable.java", - "SimpleLinkedOjbectsInstanceVariable", - "/set/configurationExtractorSimpleLinkedOjbectsInstanceVariable/oracle/", - "SimpleLinkedOjbectsInstanceVariable.xml", - "testSimpleLinkedOjbectsInstanceVariable_initial", - ".xml", - "testSimpleLinkedOjbectsInstanceVariable_current", - ".xml", - null, - 1, - 4, - false); - } - - /** - * Tests "configurationExtractorSimpleStaticAttributes" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleStaticAttributes() throws Exception { - doTest("/set/configurationExtractorSimpleStaticAttributes/test/SimpleStaticAttributes.java", - "SimpleStaticAttributes", - "/set/configurationExtractorSimpleStaticAttributes/oracle/", - "SimpleStaticAttributes.xml", - "testSimpleStaticAttributes_initial", - ".xml", - "testSimpleStaticAttributes_current", - ".xml", - null, - 1, - 2, - false); - } - - /** - * Tests "configurationExtractorSimpleArrayLength" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleArrayLength() throws Exception { - doTest("/set/configurationExtractorSimpleArrayLength/test/SimpleArrayLength.java", - "SimpleArrayLength", - "/set/configurationExtractorSimpleArrayLength/oracle/", - "SimpleArrayLength.xml", - "testSimpleArrayLength_initial", - ".xml", - "testSimpleArrayLength_current", - ".xml", - null, - 1, - 1, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedOjbectsDeletion" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbectsDeletion() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbectsDeletion/test/SimpleLinkedOjbectsDeletion.java", - "SimpleLinkedOjbectsDeletion", - "/set/configurationExtractorSimpleLinkedOjbectsDeletion/oracle/", - "SimpleLinkedOjbectsDeletion.xml", - "testSimpleLinkedOjbectsDeletion_initial", - ".xml", - "testSimpleLinkedOjbectsDeletion_current", - ".xml", - null, - 1, - 4, - false); - } - - - /** - * Tests "configurationExtractorSimpleLinkedOjbectsDeletion" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbectsDeletionPreCondition() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbectsDeletion/test/SimpleLinkedOjbectsDeletion.java", - "SimpleLinkedOjbectsDeletion", - "/set/configurationExtractorSimpleLinkedOjbectsDeletion/oracle/", - "SimpleLinkedOjbectsDeletionPreCondition.xml", - "testSimpleLinkedOjbectsDeletionPreCondition_initial", - ".xml", - "testSimpleLinkedOjbectsDeletionPreCondition_current", - ".xml", - "x != null & x.next != null & x.next.next != null", - 1, - 4, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedOjbects" without precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbects() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbects/test/SimpleLinkedOjbects.java", - "SimpleLinkedOjbects", - "/set/configurationExtractorSimpleLinkedOjbects/oracle/", - "SimpleLinkedOjbects.xml", - "testSimpleLinkedOjbects_initial", - ".xml", - "testSimpleLinkedOjbects_current", - ".xml", - null, - 1, - 4, - false); - } - - /** - * Tests "configurationExtractorSimpleLinkedOjbects" with precondition. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLinkedOjbectsPreCondition() throws Exception { - doTest("/set/configurationExtractorSimpleLinkedOjbects/test/SimpleLinkedOjbects.java", - "SimpleLinkedOjbects", - "/set/configurationExtractorSimpleLinkedOjbects/oracle/", - "SimpleLinkedOjbectsPreCondition.xml", - "testSimpleLinkedOjbectsPreCondition_initial", - ".xml", - "testSimpleLinkedOjbectsPreCondition_current", - ".xml", - "x != null & x.next != null & x.next.next != null", - 1, - 4, - false); - } - - /** - * Executes the test steps. - * @param javaPathInkeyRepDirectory The path to the Java file. - * @param containerTypeName The class name. - * @param oraclePathInBaseDir The path to the oracle directory. - * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. - * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. - * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. - * @param currentStatesOraclePrefix Prefix for current memory layout oracles. - * @param currentStatesOracleFileExtension Current memory layout oracle file extension. - * @param precondition An optional precondition. - * @param useOperationContracts Use operation contracts? - * @throws Exception Occurred Exception. - */ - protected void doTest(String javaPathInkeyRepDirectory, - String containerTypeName, - String oraclePathInBaseDir, - String symbolicExecutionOracleFileName, - String initialStatesOraclePrefix, - String initialStatesOracleFileExtension, - String currentStatesOraclePrefix, - String currentStatesOracleFileExtension, - String precondition, - int numberOfReturnNodeInMostLeftBranch, - int expectedNumberOfLayouts, - boolean useOperationContracts) throws Exception { - doTest(javaPathInkeyRepDirectory, - containerTypeName, - oraclePathInBaseDir, - symbolicExecutionOracleFileName, - initialStatesOraclePrefix, - initialStatesOracleFileExtension, - currentStatesOraclePrefix, - currentStatesOracleFileExtension, - precondition, - numberOfReturnNodeInMostLeftBranch, - expectedNumberOfLayouts, - useOperationContracts, - true); - } - - /** - * Executes the test steps. - * @param javaPathInkeyRepDirectory The path to the Java file. - * @param containerTypeName The class name. - * @param oraclePathInBaseDir The path to the oracle directory. - * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. - * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. - * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. - * @param currentStatesOraclePrefix Prefix for current memory layout oracles. - * @param currentStatesOracleFileExtension Current memory layout oracle file extension. - * @param precondition An optional precondition. - * @param useOperationContracts Use operation contracts? - * @throws Exception Occurred Exception. - */ - protected void doTest(String javaPathInkeyRepDirectory, - String containerTypeName, - String oraclePathInBaseDir, - String symbolicExecutionOracleFileName, - String initialStatesOraclePrefix, - String initialStatesOracleFileExtension, - String currentStatesOraclePrefix, - String currentStatesOracleFileExtension, - String precondition, - int numberOfReturnNodeInMostLeftBranch, - int expectedNumberOfLayouts, - boolean useOperationContracts, - boolean onReturnStatementNode) throws Exception { - HashMap originalTacletOptions = null; - SymbolicExecutionEnvironment env = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try { - // Define test settings - final String methodFullName = "compute"; - // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, precondition, false, useOperationContracts, false, false, false, false, false, false, false, true); - setOneStepSimplificationEnabled(null, true); - // Resume - resume(env.getUi(), env.getBuilder(), oraclePathInBaseDir + symbolicExecutionOracleFileName, testCaseDirectory); - // Perform test steps - doTestSteps(env, oraclePathInBaseDir, symbolicExecutionOracleFileName, initialStatesOraclePrefix, initialStatesOracleFileExtension, currentStatesOraclePrefix, currentStatesOracleFileExtension, precondition, numberOfReturnNodeInMostLeftBranch, expectedNumberOfLayouts, onReturnStatementNode); - } - finally { - // Restore original options - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } - - /** - * Executes the test steps. - * @param proofFilePathInkeyRepDirectory The path to the Proof file. - * @param oraclePathInBaseDir The path to the oracle directory. - * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. - * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. - * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. - * @param currentStatesOraclePrefix Prefix for current memory layout oracles. - * @param currentStatesOracleFileExtension Current memory layout oracle file extension. - * @param precondition An optional precondition. - * @throws Exception Occurred Exception. - */ - protected void doTest(String proofFilePathInkeyRepDirectory, - String oraclePathInBaseDir, - String symbolicExecutionOracleFileName, - String initialStatesOraclePrefix, - String initialStatesOracleFileExtension, - String currentStatesOraclePrefix, - String currentStatesOracleFileExtension, - String precondition, - int numberOfReturnNodeInMostLeftBranch, - int expectedNumberOfLayouts, - boolean onReturnStatementNode) throws Exception { - SymbolicExecutionEnvironment env = null; - try { - // Load proof file - env = createSymbolicExecutionEnvironment(testCaseDirectory, proofFilePathInkeyRepDirectory, false, false, false, false, false, false, false, false, false, false, true); - // Perform test steps - doTestSteps(env, oraclePathInBaseDir, symbolicExecutionOracleFileName, initialStatesOraclePrefix, initialStatesOracleFileExtension, currentStatesOraclePrefix, currentStatesOracleFileExtension, precondition, numberOfReturnNodeInMostLeftBranch, expectedNumberOfLayouts, onReturnStatementNode); - } - finally { - if (env != null) { - env.dispose(); - } - } - } - - protected void doTestSteps(SymbolicExecutionEnvironment env, - String oraclePathInBaseDir, - String symbolicExecutionOracleFileName, - String initialStatesOraclePrefix, - String initialStatesOracleFileExtension, - String currentStatesOraclePrefix, - String currentStatesOracleFileExtension, - String precondition, - int numberOfReturnNodeInMostLeftBranch, - int expectedNumberOfLayouts, - boolean onReturnStatementNode) throws Exception { - // Find most left method return node - IExecutionNode returnNode = env.getBuilder().getStartNode(); - int foundReturnStatement = 0; - while (foundReturnStatement < numberOfReturnNodeInMostLeftBranch && returnNode.getChildren().length >= 1) { - returnNode = returnNode.getChildren()[0]; - if (returnNode instanceof IExecutionMethodReturn) { - foundReturnStatement++; - } - } - assertTrue(returnNode instanceof IExecutionMethodReturn); - IExecutionNode nodeToTest; - if (onReturnStatementNode) { - // Get the return statement which is returned in returnNode - IExecutionNode returnStatement = returnNode.getParent(); - while (!(returnStatement instanceof IExecutionStatement)) { - if (returnStatement instanceof IExecutionStatement) { - foundReturnStatement++; + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEmptyArrayCreationTest() throws Exception { + doTest("/set/configurationExtractorEmptyArrayCreationTest/test/EmptyArrayCreationTest.java", + "EmptyArrayCreationTest", + "/set/configurationExtractorEmptyArrayCreationTest/oracle/", + "EmptyArrayCreationTest.xml", "testEmptyArrayCreationTest_initial", ".xml", + "testEmptyArrayCreationTest_current", ".xml", "n == 0", 1, 1, false, false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayCreationTest() throws Exception { + doTest("/set/configurationExtractorArrayCreationTest/test/ArrayCreationTest.java", + "ArrayCreationTest", "/set/configurationExtractorArrayCreationTest/oracle/", + "ArrayCreationTest.xml", "testArrayCreationTest_initial", ".xml", + "testArrayCreationTest_current", ".xml", "n >= 4", 1, 1, false, false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMyInteger() throws Exception { + doTest("/set/configurationExtractorMyInteger/test/MyInteger.java", "MyInteger", + "/set/configurationExtractorMyInteger/oracle/", "StaticMember.xml", + "testMyInteger_initial", ".xml", "testMyInteger_current", ".xml", null, 1, 2, false, + false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testVariableArrayIndex() throws Exception { + doTest("/set/configurationExtractorVariableArrayIndex/test/VariableArrayIndex.java", + "VariableArrayIndex", "/set/configurationExtractorVariableArrayIndex/oracle/", + "StaticMember.xml", "testVariableArrayIndex_initial", ".xml", + "testVariableArrayIndex_current", ".xml", null, 1, 1, false, false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testStaticMember_OnReturnNode() throws Exception { + doTest("/set/configurationExtractorStaticMember/test/StaticMember.java", "StaticMember", + "/set/configurationExtractorStaticMember/oracle/", "StaticMember.xml", + "testInstanceCreationTest_staticMember_initial", ".xml", + "testInstanceCreationTest_staticMember_current", ".xml", null, 1, 2, false, false); + } + + /** + * Tests "configurationExtractorExistsQuantifierTest". + * + * @throws Exception Occurred Exception. + */ + @Test + public void testExistsQuantifierTest() throws Exception { + doTest("/set/configurationExtractorExistsQuantifierTest/test/ExistsQuantifierTest.proof", + "/set/configurationExtractorExistsQuantifierTest/oracle/", + "ExistsQuantifierTest.xml", "testExistsQuantifierTest_initial", ".xml", + "testExistsQuantifierTest_current", ".xml", null, 1, 2, false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testInstanceCreationTest_OnReturnNode() throws Exception { + doTest("/set/configurationExtractorInstanceCreationTest/test/InstanceCreationTest.java", + "InstanceCreationTest", "/set/configurationExtractorInstanceCreationTest/oracle/", + "InstanceCreationTest.xml", "testInstanceCreationTest_onReturnNode_initial", ".xml", + "testInstanceCreationTest_onReturnNode_current", ".xml", null, 5, 2, false, false); + } + + /** + * Tests "configurationExtractorWithOperationContractsTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testWithOperationContracts() throws Exception { + doTest("/set/configurationExtractorWithOperationContractsTest/test/ConfigurationExtractorWithOperationContractsTest.java", + "ConfigurationExtractorWithOperationContractsTest", + "/set/configurationExtractorWithOperationContractsTest/oracle/", + "ConfigurationExtractorWithOperationContractsTest.xml", + "testWithOperationContracts_initial", ".xml", "testWithOperationContracts_current", + ".xml", null, 1, 2, true); + } + + /** + * Tests "configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass" + * without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass() throws Exception { + doTest("/set/configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass/test/AssociationSourceIsNotRepresentativeTermOfEquivalenceClass.java", + "algorithm.AssociationSourceIsNotRepresentativeTermOfEquivalenceClass", + "/set/configurationExtractorAssociationSourceIsNotRepresentativeTermOfEquivalenceClass/oracle/", + "AssociationSourceIsNotRepresentativeTermOfEquivalenceClass.xml", + "testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass_initial", ".xml", + "testAssociationSourceIsNotRepresentativeTermOfEquivalenceClass_current", ".xml", + null, 1, 3, false); + } + + /** + * Tests "configurationExtractorArrayInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayInstanceCreationTest() throws Exception { + doTest("/set/configurationExtractorArrayInstanceCreationTest/test/ArrayInstanceCreationTest.java", + "ArrayInstanceCreationTest", + "/set/configurationExtractorArrayInstanceCreationTest/oracle/", + "ArrayInstanceCreationTest.xml", "testArrayInstanceCreationTest_initial", ".xml", + "testArrayInstanceCreationTest_current", ".xml", null, 1, 2, false); + } + + /** + * Tests "configurationExtractorInstanceCreationTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testInstanceCreationTest() throws Exception { + doTest("/set/configurationExtractorInstanceCreationTest/test/InstanceCreationTest.java", + "InstanceCreationTest", "/set/configurationExtractorInstanceCreationTest/oracle/", + "InstanceCreationTest.xml", "testInstanceCreationTest_initial", ".xml", + "testInstanceCreationTest_current", ".xml", null, 5, 2, false); + } + + /** + * Tests "configurationExtractorSimpleArrayCreation" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleArrayCreation() throws Exception { + doTest("/set/configurationExtractorSimpleArrayCreation/test/SimpleArrayCreation.java", + "SimpleArrayCreation", "/set/configurationExtractorSimpleArrayCreation/oracle/", + "SimpleArrayCreation.xml", "testSimpleArrayCreation_initial", ".xml", + "testSimpleArrayCreation_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorMultiArrayIndexReadWriteAccess" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMultiArrayIndexReadWriteAccess() throws Exception { + doTest("/set/configurationExtractorMultiArrayIndexReadWriteAccess/test/MultiArrayIndexReadWriteAccess.java", + "MultiArrayIndexReadWriteAccess", + "/set/configurationExtractorMultiArrayIndexReadWriteAccess/oracle/", + "MultiArrayIndexReadWriteAccess.xml", "testMultiArrayIndexReadWriteAccess_initial", + ".xml", "testMultiArrayIndexReadWriteAccess_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorSimpleLinkedArrays" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedArrays() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedArrays/test/SimpleLinkedArrays.java", + "SimpleLinkedArrays", "/set/configurationExtractorSimpleLinkedArrays/oracle/", + "SimpleLinkedArrays.xml", "testSimpleLinkedArrays_initial", ".xml", + "testSimpleLinkedArrays_current", ".xml", null, 1, 5, false); + } + + /** + * Tests "configurationExtractorObjectArrayIndexWriteAccess" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testObjectArrayIndexWriteAccess() throws Exception { + doTest("/set/configurationExtractorObjectArrayIndexWriteAccess/test/ObjectArrayIndexWriteAccess.java", + "ObjectArrayIndexWriteAccess", + "/set/configurationExtractorObjectArrayIndexWriteAccess/oracle/", + "ObjectArrayIndexWriteAccess.xml", "testObjectArrayIndexWriteAccess_initial", + ".xml", "testObjectArrayIndexWriteAccess_current", ".xml", null, 2, 1, false); + } + + /** + * Tests "configurationExtractorArrayIndexWriteAccess" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexWriteAccess() throws Exception { + doTest("/set/configurationExtractorArrayIndexWriteAccess/test/ArrayIndexWriteAccess.java", + "ArrayIndexWriteAccess", "/set/configurationExtractorArrayIndexWriteAccess/oracle/", + "ArrayIndexWriteAccess.xml", "testArrayIndexWriteAccess_initial", ".xml", + "testArrayIndexWriteAccess_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorObjectArrayIndexReadAccess" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testObjectArrayIndexReadAccess() throws Exception { + doTest("/set/configurationExtractorObjectArrayIndexReadAccess/test/ObjectArrayIndexReadAccess.java", + "ObjectArrayIndexReadAccess", + "/set/configurationExtractorObjectArrayIndexReadAccess/oracle/", + "ObjectArrayIndexReadAccess.xml", "testObjectArrayIndexReadAccess_initial", ".xml", + "testObjectArrayIndexReadAccess_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorOneAssignmentTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexReadAccess() throws Exception { + doTest("/set/configurationExtractorArrayIndexReadAccess/test/ArrayIndexReadAccess.java", + "ArrayIndexReadAccess", "/set/configurationExtractorArrayIndexReadAccess/oracle/", + "ArrayIndexReadAccess.xml", "testArrayIndexReadAccess_initial", ".xml", + "testArrayIndexReadAccess_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorOneAssignmentTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testOneAssignmentTest() throws Exception { + doTest("/set/configurationExtractorOneAssignmentTest/test/OneAssignmentTest.java", + "OneAssignmentTest", "/set/configurationExtractorOneAssignmentTest/oracle/", + "OneAssignmentTest.xml", "testOneAssignmentTest_initial", ".xml", + "testOneAssignmentTest_current", ".xml", null, 1, 5, false); + } + + /** + * Tests "configurationExtractorEmptyPathConditionAndNoUpdates" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEmptyPathConditionAndNoUpdates() throws Exception { + doTest("/set/configurationExtractorEmptyPathConditionAndNoUpdates/test/EmptyPathConditionAndNoUpdates.java", + "EmptyPathConditionAndNoUpdates", + "/set/configurationExtractorEmptyPathConditionAndNoUpdates/oracle/", + "EmptyPathConditionAndNoUpdates.xml", "testEmptyPathConditionAndNoUpdates_initial", + ".xml", "testEmptyPathConditionAndNoUpdates_current", ".xml", null, 1, 2, false); + } + + /** + * Tests "configurationExtractorSimpleLinkedOjbectsInsertion" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbectsInsertion() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbectsInsertion/test/SimpleLinkedOjbectsInsertion.java", + "SimpleLinkedOjbectsInsertion", + "/set/configurationExtractorSimpleLinkedOjbectsInsertion/oracle/", + "SimpleLinkedOjbectsInsertion.xml", "testSimpleLinkedOjbectsInsertion_initial", + ".xml", "testSimpleLinkedOjbectsInsertion_current", ".xml", null, 2, 4, false); + } + + /** + * Tests "configurationExtractorIntegerConditionTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testObjectConditionTest() throws Exception { + doTest("/set/configurationExtractorObjectConditionTest/test/ObjectConditionTest.java", + "ObjectConditionTest", "/set/configurationExtractorObjectConditionTest/oracle/", + "ObjectConditionTest.xml", "testObjectConditionTestt_initial", ".xml", + "testObjectConditionTest_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorIntegerConditionTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testIntegerConditionTest() throws Exception { + doTest("/set/configurationExtractorIntegerConditionTest/test/IntegerConditionTest.java", + "IntegerConditionTest", "/set/configurationExtractorIntegerConditionTest/oracle/", + "IsInstanceTest.xml", "testIntegerConditionTest_initial", ".xml", + "testIntegerConditionTest_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorIsInstanceTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testIsInstanceTest() throws Exception { + doTest("/set/configurationExtractorIsInstanceTest/test/IsInstanceTest.java", + "IsInstanceTest", "/set/configurationExtractorIsInstanceTest/oracle/", + "IsInstanceTest.xml", "testIsInstanceTest_initial", ".xml", + "testIsInstanceTest_current", ".xml", null, 1, 2, false); + } + + /** + * Tests "configurationExtractorIsNullTest" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testIsNullTest() throws Exception { + doTest("/set/configurationExtractorIsNullTest/test/IsNullTest.java", "IsNullTest", + "/set/configurationExtractorIsNullTest/oracle/", "NullInEquivalenceClass.xml", + "testIsNullTest_initial", ".xml", "testIsNullTest_current", ".xml", null, 1, 1, + false); + } + + /** + * Tests "configurationExtractorSimpleLinkedOjbects" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbectsInstanceVariable() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbectsInstanceVariable/test/SimpleLinkedOjbectsInstanceVariable.java", + "SimpleLinkedOjbectsInstanceVariable", + "/set/configurationExtractorSimpleLinkedOjbectsInstanceVariable/oracle/", + "SimpleLinkedOjbectsInstanceVariable.xml", + "testSimpleLinkedOjbectsInstanceVariable_initial", ".xml", + "testSimpleLinkedOjbectsInstanceVariable_current", ".xml", null, 1, 4, false); + } + + /** + * Tests "configurationExtractorSimpleStaticAttributes" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleStaticAttributes() throws Exception { + doTest("/set/configurationExtractorSimpleStaticAttributes/test/SimpleStaticAttributes.java", + "SimpleStaticAttributes", + "/set/configurationExtractorSimpleStaticAttributes/oracle/", + "SimpleStaticAttributes.xml", "testSimpleStaticAttributes_initial", ".xml", + "testSimpleStaticAttributes_current", ".xml", null, 1, 2, false); + } + + /** + * Tests "configurationExtractorSimpleArrayLength" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleArrayLength() throws Exception { + doTest("/set/configurationExtractorSimpleArrayLength/test/SimpleArrayLength.java", + "SimpleArrayLength", "/set/configurationExtractorSimpleArrayLength/oracle/", + "SimpleArrayLength.xml", "testSimpleArrayLength_initial", ".xml", + "testSimpleArrayLength_current", ".xml", null, 1, 1, false); + } + + /** + * Tests "configurationExtractorSimpleLinkedOjbectsDeletion" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbectsDeletion() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbectsDeletion/test/SimpleLinkedOjbectsDeletion.java", + "SimpleLinkedOjbectsDeletion", + "/set/configurationExtractorSimpleLinkedOjbectsDeletion/oracle/", + "SimpleLinkedOjbectsDeletion.xml", "testSimpleLinkedOjbectsDeletion_initial", + ".xml", "testSimpleLinkedOjbectsDeletion_current", ".xml", null, 1, 4, false); + } + + + /** + * Tests "configurationExtractorSimpleLinkedOjbectsDeletion" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbectsDeletionPreCondition() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbectsDeletion/test/SimpleLinkedOjbectsDeletion.java", + "SimpleLinkedOjbectsDeletion", + "/set/configurationExtractorSimpleLinkedOjbectsDeletion/oracle/", + "SimpleLinkedOjbectsDeletionPreCondition.xml", + "testSimpleLinkedOjbectsDeletionPreCondition_initial", ".xml", + "testSimpleLinkedOjbectsDeletionPreCondition_current", ".xml", + "x != null & x.next != null & x.next.next != null", 1, 4, false); + } + + /** + * Tests "configurationExtractorSimpleLinkedOjbects" without precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbects() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbects/test/SimpleLinkedOjbects.java", + "SimpleLinkedOjbects", "/set/configurationExtractorSimpleLinkedOjbects/oracle/", + "SimpleLinkedOjbects.xml", "testSimpleLinkedOjbects_initial", ".xml", + "testSimpleLinkedOjbects_current", ".xml", null, 1, 4, false); + } + + /** + * Tests "configurationExtractorSimpleLinkedOjbects" with precondition. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLinkedOjbectsPreCondition() throws Exception { + doTest("/set/configurationExtractorSimpleLinkedOjbects/test/SimpleLinkedOjbects.java", + "SimpleLinkedOjbects", "/set/configurationExtractorSimpleLinkedOjbects/oracle/", + "SimpleLinkedOjbectsPreCondition.xml", + "testSimpleLinkedOjbectsPreCondition_initial", ".xml", + "testSimpleLinkedOjbectsPreCondition_current", ".xml", + "x != null & x.next != null & x.next.next != null", 1, 4, false); + } + + /** + * Executes the test steps. + * + * @param javaPathInkeyRepDirectory The path to the Java file. + * @param containerTypeName The class name. + * @param oraclePathInBaseDir The path to the oracle directory. + * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. + * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. + * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. + * @param currentStatesOraclePrefix Prefix for current memory layout oracles. + * @param currentStatesOracleFileExtension Current memory layout oracle file extension. + * @param precondition An optional precondition. + * @param useOperationContracts Use operation contracts? + * @throws Exception Occurred Exception. + */ + protected void doTest(String javaPathInkeyRepDirectory, String containerTypeName, + String oraclePathInBaseDir, String symbolicExecutionOracleFileName, + String initialStatesOraclePrefix, String initialStatesOracleFileExtension, + String currentStatesOraclePrefix, String currentStatesOracleFileExtension, + String precondition, int numberOfReturnNodeInMostLeftBranch, + int expectedNumberOfLayouts, boolean useOperationContracts) throws Exception { + doTest(javaPathInkeyRepDirectory, containerTypeName, oraclePathInBaseDir, + symbolicExecutionOracleFileName, initialStatesOraclePrefix, + initialStatesOracleFileExtension, currentStatesOraclePrefix, + currentStatesOracleFileExtension, precondition, numberOfReturnNodeInMostLeftBranch, + expectedNumberOfLayouts, useOperationContracts, true); + } + + /** + * Executes the test steps. + * + * @param javaPathInkeyRepDirectory The path to the Java file. + * @param containerTypeName The class name. + * @param oraclePathInBaseDir The path to the oracle directory. + * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. + * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. + * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. + * @param currentStatesOraclePrefix Prefix for current memory layout oracles. + * @param currentStatesOracleFileExtension Current memory layout oracle file extension. + * @param precondition An optional precondition. + * @param useOperationContracts Use operation contracts? + * @throws Exception Occurred Exception. + */ + protected void doTest(String javaPathInkeyRepDirectory, String containerTypeName, + String oraclePathInBaseDir, String symbolicExecutionOracleFileName, + String initialStatesOraclePrefix, String initialStatesOracleFileExtension, + String currentStatesOraclePrefix, String currentStatesOracleFileExtension, + String precondition, int numberOfReturnNodeInMostLeftBranch, + int expectedNumberOfLayouts, boolean useOperationContracts, + boolean onReturnStatementNode) throws Exception { + HashMap originalTacletOptions = null; + SymbolicExecutionEnvironment env = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + final String methodFullName = "compute"; + // Make sure that the correct taclet options are defined. + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, precondition, false, useOperationContracts, + false, false, false, false, false, false, false, true); + setOneStepSimplificationEnabled(null, true); + // Resume + resume(env.getUi(), env.getBuilder(), + oraclePathInBaseDir + symbolicExecutionOracleFileName, testCaseDirectory); + // Perform test steps + doTestSteps(env, oraclePathInBaseDir, symbolicExecutionOracleFileName, + initialStatesOraclePrefix, initialStatesOracleFileExtension, + currentStatesOraclePrefix, currentStatesOracleFileExtension, precondition, + numberOfReturnNodeInMostLeftBranch, expectedNumberOfLayouts, + onReturnStatementNode); + } finally { + // Restore original options + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); } - returnStatement = returnStatement.getParent(); - } - assertNotNull(returnStatement); - assertTrue(returnStatement.getName().startsWith("return")); - nodeToTest = returnStatement; - } - else { - nodeToTest = returnNode; - } - // Extract possible heaps - SymbolicLayoutExtractor extractor = new SymbolicLayoutExtractor(nodeToTest.getProofNode(), nodeToTest.getModalityPIO(), false, false, true); - extractor.analyse(); - // Test the initial memory layouts (first time with lazy computation) - List initialLayoutsFirstTime = new ArrayList(extractor.getLayoutsCount()); - assertEquals(expectedNumberOfLayouts, extractor.getLayoutsCount()); - for (int i = 0; i < extractor.getLayoutsCount(); i++) { - ISymbolicLayout current = extractor.getInitialLayout(i); - initialLayoutsFirstTime.add(current); - String oracleFile = oraclePathInBaseDir + initialStatesOraclePrefix + i + initialStatesOracleFileExtension; - createOracleFile(current, oracleFile); - if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - SymbolicLayoutReader reader = new SymbolicLayoutReader(); - ISymbolicLayout expected = reader.read(new File(testCaseDirectory, oracleFile)); - assertNotNull(expected); - assertModel(expected, current); - } - } - // Test the initial memory layouts (second time with same memory layouts) - for (int i = 0; i < extractor.getLayoutsCount(); i++) { - ISymbolicLayout current = extractor.getInitialLayout(i); - assertSame(initialLayoutsFirstTime.get(i), current); - } - // Test the current memory layouts (first time with lazy computation) - List currentLayoutsFirstTime = new ArrayList(extractor.getLayoutsCount()); - for (int i = 0; i < extractor.getLayoutsCount(); i++) { - ISymbolicLayout current = extractor.getCurrentLayout(i); - currentLayoutsFirstTime.add(current); - String oracleFile = oraclePathInBaseDir + currentStatesOraclePrefix + i + currentStatesOracleFileExtension; - createOracleFile(current, oracleFile); - if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - SymbolicLayoutReader reader = new SymbolicLayoutReader(); - ISymbolicLayout expected = reader.read(new File(testCaseDirectory, oracleFile)); - assertNotNull(expected); - assertModel(expected, current); - } - } - // Test the current memory layouts (second time with same memory layouts) - for (int i = 0; i < extractor.getLayoutsCount(); i++) { - ISymbolicLayout current = extractor.getCurrentLayout(i); - assertSame(currentLayoutsFirstTime.get(i), current); - } - } - - protected static void createOracleFile(ISymbolicLayout model, - String oraclePathInBaseDirFile) throws IOException { - if (tempNewOracleDirectory != null && tempNewOracleDirectory.isDirectory()) { - // Create sub folder structure - File oracleFile = new File(tempNewOracleDirectory, oraclePathInBaseDirFile); - oracleFile.getParentFile().mkdirs(); - // Create oracle file - SymbolicLayoutWriter writer = new SymbolicLayoutWriter(); - writer.write(model, SymbolicLayoutWriter.DEFAULT_ENCODING, oracleFile); - // Print message to the user. - printOracleDirectory(); - } - } - - public static void assertModel(ISymbolicLayout expected, ISymbolicLayout current) { - if (expected != null) { - assertNotNull(current); - assertState(expected.getState(), current.getState()); - assertObjects(expected.getObjects(), current.getObjects()); - assertEquivalenceClasses(expected.getEquivalenceClasses(), current.getEquivalenceClasses()); - } - else { - assertNull(current); - } - } - - /** - * Compares the given {@link ISymbolicState}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertState(ISymbolicState expected, ISymbolicState current) { - if (expected != null) { - assertNotNull(current); - assertEquals(expected.getName(), current.getName()); - assertValues(expected.getValues(), current.getValues()); - assertAssociations(expected.getAssociations(), current.getAssociations()); - } - else { - assertNull(current); - } - } - - /** - * Compares the given {@link ISymbolicObject}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertObjects(ImmutableList expected, ImmutableList current) { - assertNotNull(expected); - assertNotNull(current); - assertEquals(expected.size(), current.size()); - Iterator expectedIter = expected.iterator(); - Iterator currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertObject(expectedIter.next(), currentIter.next(), true); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - - /** - * Compares the given {@link ISymbolicObject}s. - * @param expected The expected instance. - * @param current The current instance. - * @param compareAssociations Compare contained associations? - */ - public static void assertObject(ISymbolicObject expected, ISymbolicObject current, boolean compareAssociations) { - if (expected != null) { - assertNotNull(current); - assertEquals(expected.getNameString(), current.getNameString()); - assertEquals(expected.getTypeString(), current.getTypeString()); - assertValues(expected.getValues(), current.getValues()); - if (compareAssociations) { + } + } + + /** + * Executes the test steps. + * + * @param proofFilePathInkeyRepDirectory The path to the Proof file. + * @param oraclePathInBaseDir The path to the oracle directory. + * @param symbolicExecutionOracleFileName File name of the symbolic execution oracle file. + * @param initialStatesOraclePrefix Prefix for initial memory layout oracles. + * @param initialStatesOracleFileExtension Initial memory layout oracle file extension. + * @param currentStatesOraclePrefix Prefix for current memory layout oracles. + * @param currentStatesOracleFileExtension Current memory layout oracle file extension. + * @param precondition An optional precondition. + * @throws Exception Occurred Exception. + */ + protected void doTest(String proofFilePathInkeyRepDirectory, String oraclePathInBaseDir, + String symbolicExecutionOracleFileName, String initialStatesOraclePrefix, + String initialStatesOracleFileExtension, String currentStatesOraclePrefix, + String currentStatesOracleFileExtension, String precondition, + int numberOfReturnNodeInMostLeftBranch, int expectedNumberOfLayouts, + boolean onReturnStatementNode) throws Exception { + SymbolicExecutionEnvironment env = null; + try { + // Load proof file + env = createSymbolicExecutionEnvironment(testCaseDirectory, + proofFilePathInkeyRepDirectory, false, false, false, false, false, false, false, + false, false, false, true); + // Perform test steps + doTestSteps(env, oraclePathInBaseDir, symbolicExecutionOracleFileName, + initialStatesOraclePrefix, initialStatesOracleFileExtension, + currentStatesOraclePrefix, currentStatesOracleFileExtension, precondition, + numberOfReturnNodeInMostLeftBranch, expectedNumberOfLayouts, + onReturnStatementNode); + } finally { + if (env != null) { + env.dispose(); + } + } + } + + protected void doTestSteps(SymbolicExecutionEnvironment env, + String oraclePathInBaseDir, String symbolicExecutionOracleFileName, + String initialStatesOraclePrefix, String initialStatesOracleFileExtension, + String currentStatesOraclePrefix, String currentStatesOracleFileExtension, + String precondition, int numberOfReturnNodeInMostLeftBranch, + int expectedNumberOfLayouts, boolean onReturnStatementNode) throws Exception { + // Find most left method return node + IExecutionNode returnNode = env.getBuilder().getStartNode(); + int foundReturnStatement = 0; + while (foundReturnStatement < numberOfReturnNodeInMostLeftBranch + && returnNode.getChildren().length >= 1) { + returnNode = returnNode.getChildren()[0]; + if (returnNode instanceof IExecutionMethodReturn) { + foundReturnStatement++; + } + } + assertTrue(returnNode instanceof IExecutionMethodReturn); + IExecutionNode nodeToTest; + if (onReturnStatementNode) { + // Get the return statement which is returned in returnNode + IExecutionNode returnStatement = returnNode.getParent(); + while (!(returnStatement instanceof IExecutionStatement)) { + if (returnStatement instanceof IExecutionStatement) { + foundReturnStatement++; + } + returnStatement = returnStatement.getParent(); + } + assertNotNull(returnStatement); + assertTrue(returnStatement.getName().startsWith("return")); + nodeToTest = returnStatement; + } else { + nodeToTest = returnNode; + } + // Extract possible heaps + SymbolicLayoutExtractor extractor = new SymbolicLayoutExtractor(nodeToTest.getProofNode(), + nodeToTest.getModalityPIO(), false, false, true); + extractor.analyse(); + // Test the initial memory layouts (first time with lazy computation) + List initialLayoutsFirstTime = + new ArrayList(extractor.getLayoutsCount()); + assertEquals(expectedNumberOfLayouts, extractor.getLayoutsCount()); + for (int i = 0; i < extractor.getLayoutsCount(); i++) { + ISymbolicLayout current = extractor.getInitialLayout(i); + initialLayoutsFirstTime.add(current); + String oracleFile = oraclePathInBaseDir + initialStatesOraclePrefix + i + + initialStatesOracleFileExtension; + createOracleFile(current, oracleFile); + if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + SymbolicLayoutReader reader = new SymbolicLayoutReader(); + ISymbolicLayout expected = reader.read(new File(testCaseDirectory, oracleFile)); + assertNotNull(expected); + assertModel(expected, current); + } + } + // Test the initial memory layouts (second time with same memory layouts) + for (int i = 0; i < extractor.getLayoutsCount(); i++) { + ISymbolicLayout current = extractor.getInitialLayout(i); + assertSame(initialLayoutsFirstTime.get(i), current); + } + // Test the current memory layouts (first time with lazy computation) + List currentLayoutsFirstTime = + new ArrayList(extractor.getLayoutsCount()); + for (int i = 0; i < extractor.getLayoutsCount(); i++) { + ISymbolicLayout current = extractor.getCurrentLayout(i); + currentLayoutsFirstTime.add(current); + String oracleFile = oraclePathInBaseDir + currentStatesOraclePrefix + i + + currentStatesOracleFileExtension; + createOracleFile(current, oracleFile); + if (!CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + SymbolicLayoutReader reader = new SymbolicLayoutReader(); + ISymbolicLayout expected = reader.read(new File(testCaseDirectory, oracleFile)); + assertNotNull(expected); + assertModel(expected, current); + } + } + // Test the current memory layouts (second time with same memory layouts) + for (int i = 0; i < extractor.getLayoutsCount(); i++) { + ISymbolicLayout current = extractor.getCurrentLayout(i); + assertSame(currentLayoutsFirstTime.get(i), current); + } + } + + protected static void createOracleFile(ISymbolicLayout model, String oraclePathInBaseDirFile) + throws IOException { + if (tempNewOracleDirectory != null && tempNewOracleDirectory.isDirectory()) { + // Create sub folder structure + File oracleFile = new File(tempNewOracleDirectory, oraclePathInBaseDirFile); + oracleFile.getParentFile().mkdirs(); + // Create oracle file + SymbolicLayoutWriter writer = new SymbolicLayoutWriter(); + writer.write(model, SymbolicLayoutWriter.DEFAULT_ENCODING, oracleFile); + // Print message to the user. + printOracleDirectory(); + } + } + + public static void assertModel(ISymbolicLayout expected, ISymbolicLayout current) { + if (expected != null) { + assertNotNull(current); + assertState(expected.getState(), current.getState()); + assertObjects(expected.getObjects(), current.getObjects()); + assertEquivalenceClasses(expected.getEquivalenceClasses(), + current.getEquivalenceClasses()); + } else { + assertNull(current); + } + } + + /** + * Compares the given {@link ISymbolicState}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertState(ISymbolicState expected, ISymbolicState current) { + if (expected != null) { + assertNotNull(current); + assertEquals(expected.getName(), current.getName()); + assertValues(expected.getValues(), current.getValues()); assertAssociations(expected.getAssociations(), current.getAssociations()); - } - } - else { - assertNull(current); - } - } - - /** - * Compares the given {@link ISymbolicEquivalenceClass}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertEquivalenceClasses(ImmutableList expected, ImmutableList current) { - assertNotNull(expected); - assertNotNull(current); - assertEquals(expected.size(), current.size()); - Iterator expectedIter = expected.iterator(); - Iterator currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertEquivalenceClass(expectedIter.next(), currentIter.next()); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - - /** - * Compares the given {@link ISymbolicEquivalenceClass}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertEquivalenceClass(ISymbolicEquivalenceClass expected, ISymbolicEquivalenceClass current) { - if (expected != null) { - assertNotNull(current); - assertStringListEqualsIgnoreWhiteSpace(expected.getTermStrings(), current.getTermStrings()); - assertEquals(expected.getRepresentativeString(), current.getRepresentativeString()); - } - else { - assertNull(current); - } - } - - /** - * Compares the given {@link ImmutableList}s ignoring white space. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertStringListEqualsIgnoreWhiteSpace(ImmutableList expected, ImmutableList current) { - assertNotNull(expected); - assertNotNull(current); - assertEquals(expected.size(), current.size()); - Iterator expectedIter = expected.iterator(); - Iterator currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - String nextExpected = expectedIter.next(); - String nextCurrent = currentIter.next(); - assertTrue(StringUtil.equalIgnoreWhiteSpace(nextExpected, nextCurrent), "\"" + nextExpected + "\" does not match \"" + nextCurrent + "\""); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - - /** - * Compares the given {@link ISymbolicValue}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertValues(ImmutableList expected, ImmutableList current) { - assertNotNull(expected); - assertNotNull(current); - - assertEquals(expected.size(), current.size()); - Iterator expectedIter = expected.iterator(); - Iterator currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertValue(expectedIter.next(), currentIter.next()); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - - /** - * Compares the given {@link ISymbolicValue}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertValue(ISymbolicValue expected, ISymbolicValue current) { - if (expected != null) { - assertNotNull(current); - assertEquals(expected.getName(), current.getName()); - assertEquals(expected.getProgramVariableString(), current.getProgramVariableString()); - assertEquals(expected.isArrayIndex(), current.isArrayIndex()); - assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expected.getValueString(), current.getValueString()), "\"" + expected.getValueString() + "\" does not match \"" + current.getValueString() + "\""); - assertEquals(expected.getTypeString(), current.getTypeString()); - assertEquals(expected.getConditionString(), current.getConditionString()); - } - else { - assertNull(current); - } - } - - /** - * Compares the given {@link ISymbolicAssociation}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertAssociations(ImmutableList expected, ImmutableList current) { - assertNotNull(expected); - assertNotNull(current); - assertEquals(expected.size(), current.size()); - Iterator expectedIter = expected.iterator(); - Iterator currentIter = current.iterator(); - while (expectedIter.hasNext() && currentIter.hasNext()) { - assertAssociation(expectedIter.next(), currentIter.next()); - } - assertFalse(expectedIter.hasNext()); - assertFalse(currentIter.hasNext()); - } - - /** - * Compares the given {@link ISymbolicAssociation}s. - * @param expected The expected instance. - * @param current The current instance. - */ - public static void assertAssociation(ISymbolicAssociation expected, ISymbolicAssociation current) { - if (expected != null) { - assertNotNull(current); - assertEquals(expected.getName(), current.getName()); - assertEquals(expected.getProgramVariableString(), current.getProgramVariableString()); - assertEquals(expected.isArrayIndex(), current.isArrayIndex()); - assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); - assertObject(expected.getTarget(), current.getTarget(), false); - assertEquals(expected.getConditionString(), current.getConditionString()); - } - else { - assertNull(current); - } - } -} \ No newline at end of file + } else { + assertNull(current); + } + } + + /** + * Compares the given {@link ISymbolicObject}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertObjects(ImmutableList expected, + ImmutableList current) { + assertNotNull(expected); + assertNotNull(current); + assertEquals(expected.size(), current.size()); + Iterator expectedIter = expected.iterator(); + Iterator currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertObject(expectedIter.next(), currentIter.next(), true); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } + + /** + * Compares the given {@link ISymbolicObject}s. + * + * @param expected The expected instance. + * @param current The current instance. + * @param compareAssociations Compare contained associations? + */ + public static void assertObject(ISymbolicObject expected, ISymbolicObject current, + boolean compareAssociations) { + if (expected != null) { + assertNotNull(current); + assertEquals(expected.getNameString(), current.getNameString()); + assertEquals(expected.getTypeString(), current.getTypeString()); + assertValues(expected.getValues(), current.getValues()); + if (compareAssociations) { + assertAssociations(expected.getAssociations(), current.getAssociations()); + } + } else { + assertNull(current); + } + } + + /** + * Compares the given {@link ISymbolicEquivalenceClass}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertEquivalenceClasses(ImmutableList expected, + ImmutableList current) { + assertNotNull(expected); + assertNotNull(current); + assertEquals(expected.size(), current.size()); + Iterator expectedIter = expected.iterator(); + Iterator currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertEquivalenceClass(expectedIter.next(), currentIter.next()); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } + + /** + * Compares the given {@link ISymbolicEquivalenceClass}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertEquivalenceClass(ISymbolicEquivalenceClass expected, + ISymbolicEquivalenceClass current) { + if (expected != null) { + assertNotNull(current); + assertStringListEqualsIgnoreWhiteSpace(expected.getTermStrings(), + current.getTermStrings()); + assertEquals(expected.getRepresentativeString(), current.getRepresentativeString()); + } else { + assertNull(current); + } + } + + /** + * Compares the given {@link ImmutableList}s ignoring white space. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertStringListEqualsIgnoreWhiteSpace(ImmutableList expected, + ImmutableList current) { + assertNotNull(expected); + assertNotNull(current); + assertEquals(expected.size(), current.size()); + Iterator expectedIter = expected.iterator(); + Iterator currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + String nextExpected = expectedIter.next(); + String nextCurrent = currentIter.next(); + assertTrue(StringUtil.equalIgnoreWhiteSpace(nextExpected, nextCurrent), + "\"" + nextExpected + "\" does not match \"" + nextCurrent + "\""); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } + + /** + * Compares the given {@link ISymbolicValue}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertValues(ImmutableList expected, + ImmutableList current) { + assertNotNull(expected); + assertNotNull(current); + + assertEquals(expected.size(), current.size()); + Iterator expectedIter = expected.iterator(); + Iterator currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertValue(expectedIter.next(), currentIter.next()); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } + + /** + * Compares the given {@link ISymbolicValue}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertValue(ISymbolicValue expected, ISymbolicValue current) { + if (expected != null) { + assertNotNull(current); + assertEquals(expected.getName(), current.getName()); + assertEquals(expected.getProgramVariableString(), current.getProgramVariableString()); + assertEquals(expected.isArrayIndex(), current.isArrayIndex()); + assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); + assertTrue( + StringUtil.equalIgnoreWhiteSpace(expected.getValueString(), + current.getValueString()), + "\"" + expected.getValueString() + "\" does not match \"" + + current.getValueString() + "\""); + assertEquals(expected.getTypeString(), current.getTypeString()); + assertEquals(expected.getConditionString(), current.getConditionString()); + } else { + assertNull(current); + } + } + + /** + * Compares the given {@link ISymbolicAssociation}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertAssociations(ImmutableList expected, + ImmutableList current) { + assertNotNull(expected); + assertNotNull(current); + assertEquals(expected.size(), current.size()); + Iterator expectedIter = expected.iterator(); + Iterator currentIter = current.iterator(); + while (expectedIter.hasNext() && currentIter.hasNext()) { + assertAssociation(expectedIter.next(), currentIter.next()); + } + assertFalse(expectedIter.hasNext()); + assertFalse(currentIter.hasNext()); + } + + /** + * Compares the given {@link ISymbolicAssociation}s. + * + * @param expected The expected instance. + * @param current The current instance. + */ + public static void assertAssociation(ISymbolicAssociation expected, + ISymbolicAssociation current) { + if (expected != null) { + assertNotNull(current); + assertEquals(expected.getName(), current.getName()); + assertEquals(expected.getProgramVariableString(), current.getProgramVariableString()); + assertEquals(expected.isArrayIndex(), current.isArrayIndex()); + assertEquals(expected.getArrayIndexString(), current.getArrayIndexString()); + assertObject(expected.getTarget(), current.getTarget(), false); + assertEquals(expected.getConditionString(), current.getConditionString()); + } else { + assertNull(current); + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutWriterAndReader.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutWriterAndReader.java index c625e669517..9572fc33701 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutWriterAndReader.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestSymbolicLayoutWriterAndReader.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.symbolic_execution.ExecutionNodeWriter; @@ -19,76 +22,82 @@ /** * Tests {@link SymbolicLayoutWriter} and {@link SymbolicLayoutReader} + * * @author Martin Hentschel */ -public class TestSymbolicLayoutWriterAndReader { - /** - * Tests the writing and reading of an {@link ISymbolicLayout}. - */ - @Test - public void testWritingAndReading() throws ParserConfigurationException, SAXException, IOException { - // Create model - ISymbolicLayout expectedNode = createModel(); - // Serialize model to XML string - SymbolicLayoutWriter writer = new SymbolicLayoutWriter(); - String xml = writer.toXML(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING); - // Read from XML string - SymbolicLayoutReader reader = new SymbolicLayoutReader(); - ISymbolicLayout currentNode = reader.read(new ByteArrayInputStream(xml.getBytes(Charset.forName(ExecutionNodeWriter.DEFAULT_ENCODING)))); - TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); - // Serialize model to output stream - ByteArrayOutputStream out = new ByteArrayOutputStream(); - writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, out); - // Read from input stream - currentNode = reader.read(new ByteArrayInputStream(out.toByteArray())); - TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); - // Serialize model to temporary file - File tempFile = File.createTempFile("TestExecutionNodeWriterAndReader", "testWritingAndReading"); - try { - tempFile.delete(); - writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, tempFile); - Assertions.assertTrue(tempFile.isFile()); - // Read from temporary file - currentNode = reader.read(tempFile); - TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); - } - finally { - tempFile.delete(); - } - } +public class TestSymbolicLayoutWriterAndReader { + /** + * Tests the writing and reading of an {@link ISymbolicLayout}. + */ + @Test + public void testWritingAndReading() + throws ParserConfigurationException, SAXException, IOException { + // Create model + ISymbolicLayout expectedNode = createModel(); + // Serialize model to XML string + SymbolicLayoutWriter writer = new SymbolicLayoutWriter(); + String xml = writer.toXML(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING); + // Read from XML string + SymbolicLayoutReader reader = new SymbolicLayoutReader(); + ISymbolicLayout currentNode = reader.read(new ByteArrayInputStream( + xml.getBytes(Charset.forName(ExecutionNodeWriter.DEFAULT_ENCODING)))); + TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); + // Serialize model to output stream + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, out); + // Read from input stream + currentNode = reader.read(new ByteArrayInputStream(out.toByteArray())); + TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); + // Serialize model to temporary file + File tempFile = + File.createTempFile("TestExecutionNodeWriterAndReader", "testWritingAndReading"); + try { + tempFile.delete(); + writer.write(expectedNode, ExecutionNodeWriter.DEFAULT_ENCODING, tempFile); + Assertions.assertTrue(tempFile.isFile()); + // Read from temporary file + currentNode = reader.read(tempFile); + TestSymbolicLayoutExtractor.assertModel(expectedNode, currentNode); + } finally { + tempFile.delete(); + } + } - /** - * Creates an example model. - * @return The root of the example model. - */ - protected ISymbolicLayout createModel() { - KeYlessLayout model = new KeYlessLayout(); - model.addEquivalenceClass(new KeYlessEquivalenceClass(ImmutableSLList.nil().append("A", "B", "C"), "A")); - model.addEquivalenceClass(new KeYlessEquivalenceClass(ImmutableSLList.nil().append("1", "2", "3"), "63")); - // state - KeYlessState state = new KeYlessState("exampleState"); - state.addValue(new KeYlessValue("v1", "v1", false, "-1", "v1Value", "t1", null)); - state.addValue(new KeYlessValue("v2", "v2", false, "-1", "v2Value", "t2", "c1")); - model.setState(state); - // o1 - KeYlessObject o1 = new KeYlessObject("o1", "t1"); - o1.addValue(new KeYlessValue("o1", "o1", false, "-1", "o1Value", "t1", "c2")); - model.addObject(o1); - // o2 - KeYlessObject o2 = new KeYlessObject("o2", "t2"); - model.addObject(o2); - // o3 - KeYlessObject o3 = new KeYlessObject("o3", "t3"); - o3.addValue(new KeYlessValue("o1", "o1", false, "-1", "o1Value", "t1", null)); - o3.addValue(new KeYlessValue("o2", "o2", true, "52", "o2Value", "t2", "c3")); - o3.addValue(new KeYlessValue("o3", "o3", false, "-1", "o3Value", "t3", null)); - model.addObject(o3); - // associations - state.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o2, null)); - o1.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o1, "c4")); - o1.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o2, "c5")); - o2.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o3, null)); - o3.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o1, "c6")); - return model; - } -} \ No newline at end of file + /** + * Creates an example model. + * + * @return The root of the example model. + */ + protected ISymbolicLayout createModel() { + KeYlessLayout model = new KeYlessLayout(); + model.addEquivalenceClass(new KeYlessEquivalenceClass( + ImmutableSLList.nil().append("A", "B", "C"), "A")); + model.addEquivalenceClass(new KeYlessEquivalenceClass( + ImmutableSLList.nil().append("1", "2", "3"), "63")); + // state + KeYlessState state = new KeYlessState("exampleState"); + state.addValue(new KeYlessValue("v1", "v1", false, "-1", "v1Value", "t1", null)); + state.addValue(new KeYlessValue("v2", "v2", false, "-1", "v2Value", "t2", "c1")); + model.setState(state); + // o1 + KeYlessObject o1 = new KeYlessObject("o1", "t1"); + o1.addValue(new KeYlessValue("o1", "o1", false, "-1", "o1Value", "t1", "c2")); + model.addObject(o1); + // o2 + KeYlessObject o2 = new KeYlessObject("o2", "t2"); + model.addObject(o2); + // o3 + KeYlessObject o3 = new KeYlessObject("o3", "t3"); + o3.addValue(new KeYlessValue("o1", "o1", false, "-1", "o1Value", "t1", null)); + o3.addValue(new KeYlessValue("o2", "o2", true, "52", "o2Value", "t2", "c3")); + o3.addValue(new KeYlessValue("o3", "o3", false, "-1", "o3Value", "t3", null)); + model.addObject(o3); + // associations + state.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o2, null)); + o1.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o1, "c4")); + o1.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o2, "c5")); + o2.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o3, null)); + o3.addAssociation(new KeYlessAssociation("a1", "a1", false, "-1", o1, "c6")); + return model; + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueEvaluationUtil.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueEvaluationUtil.java index 1be64388251..8448f950cdb 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueEvaluationUtil.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueEvaluationUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -22,1204 +25,1388 @@ /** * Tests for {@link TruthValueTracingUtil}. + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) public class TestTruthValueEvaluationUtil extends AbstractSymbolicExecutionTestCase { - private static final Logger LOGGER = LoggerFactory.getLogger(TestTruthValueEvaluationUtil.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(TestTruthValueEvaluationUtil.class); - /** - * Tests example: /set/truthValueWeakeningTest - */ - @Test + /** + * Tests example: /set/truthValueWeakeningTest + */ + @Test public void testJoinTestAfterBranchConditionWithWeakeningGoal() throws Exception { - // Create expected results - ExpectedBranchResult seGoal = new ExpectedBranchResult(); - ExpectedBranchResult weakeningGoal = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE), - new ExpectedTruthValueResult("10.0", TruthValue.FALSE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.FALSE), - new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("17.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult seResult = new ExpectedTruthValueEvaluationResult(seGoal); - ExpectedTruthValueEvaluationResult weakeningResult = new ExpectedTruthValueEvaluationResult(weakeningGoal); - // Perform test - doTruthValueEvaluationTest("/set/truthValueWeakeningTest/test/JoinTestAfterBranchConditionWithWeakeningGoal.proof", - "/set/truthValueWeakeningTest/oracle/JoinTestAfterBranchCondition.xml", - false, - false, - false, - seResult, - weakeningResult); - } - - /** - * Tests example: /set/truthValueLabelBelowUpdatesDifferentToApplicationTerm - */ - @Test public void testTruthValueLabelBelowUpdatesDifferentToApplicationTerm() throws Exception { - // Create expected results - ExpectedBranchResult goal15 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); - ExpectedBranchResult goal17 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal15, goal17); - // Perform test - doTruthValueEvaluationTest("/set/truthValueLabelBelowUpdatesDifferentToApplicationTerm/test/TwoBranch.proof", - "/set/truthValueLabelBelowUpdatesDifferentToApplicationTerm/oracle/TwoBranch.xml", - false, - false, - false, - result); - } - - /** - * Tests example: /set/truthValueExceptinalAssignableNothingTest - */ - @Test public void testExceptinalAssignableNothingTest_OSS() throws Exception { - // Create expected results - ExpectedBranchResult goal374 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal407 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal444 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal475 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal476 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult exceptionResult = new ExpectedTruthValueEvaluationResult(goal374, goal407, goal444, goal475, goal476); - // Perform test - doTruthValueEvaluationTest("/set/truthValueExceptinalAssignableNothingTest/test/ExceptinalAssignableNothingTest_OSS.proof", - "/set/truthValueExceptinalAssignableNothingTest/oracle/ExceptinalAssignableNothingTest.xml", - false, - false, - false, - exceptionResult); - } - - /** - * Tests example: /set/truthValueExceptinalAssignableNothingTest - */ - @Test public void testExceptinalAssignableNothingTest() throws Exception { - // Create expected results - ExpectedBranchResult goal374 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal407 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal444 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal475 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedBranchResult goal476 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult exceptionResult = new ExpectedTruthValueEvaluationResult(goal374, goal407, goal444, goal475, goal476); - // Perform test - doTruthValueEvaluationTest("/set/truthValueExceptinalAssignableNothingTest/test/ExceptinalAssignableNothingTest.proof", - "/set/truthValueExceptinalAssignableNothingTest/oracle/ExceptinalAssignableNothingTest.xml", - false, - false, - false, - exceptionResult); - } - - /** - * Tests example: /set/truthValueBlockContractMagic42 - */ - @Test - @Disabled - public void IGNORE_testBlockContractMagic42() throws Exception { - // Create expected results - ExpectedBranchResult goal66 = new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult preconditionResult = new ExpectedTruthValueEvaluationResult(goal66); - ExpectedBranchResult goal62 = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("19.0", TruthValue.TRUE), - new ExpectedTruthValueResult("20.0", TruthValue.TRUE), - new ExpectedTruthValueResult("21.0", TruthValue.TRUE)); - ExpectedBranchResult goal64 = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("21.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult validitiyResult = new ExpectedTruthValueEvaluationResult(goal62, goal64); - ExpectedBranchResult goal152 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal154 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult usageResult = new ExpectedTruthValueEvaluationResult(goal152, goal154); - // Perform test - doTruthValueEvaluationTest("/set/truthValueBlockContractMagic42/test/BlockContractMagic42.proof", - "/set/truthValueBlockContractMagic42/oracle/BlockContractMagic42.xml", - false, - false, - true, - preconditionResult, - validitiyResult, - usageResult); - } - - /** - * Tests example: /set/truthValueRejectedFormula - */ - @Test public void testValueRejectedFormula() throws Exception { - // Create expected results - ExpectedBranchResult goal31 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal33 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal31, goal33); - // Perform test - doTruthValueEvaluationTest("/set/truthValueRejectedFormula/test/LabelLostVerification.proof", - "/set/truthValueRejectedFormula/oracle/LabelLostVerification.xml", - false, - false, - false, - result); - } - - /** - * Tests example: /set/truthValueAddingOfLabeledSubtree - */ - @Test@Disabled - public void IGNORE_testAddingOfLabeledSubtree() throws Exception { - // Create expected results - ExpectedBranchResult goal53 = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.FALSE), - new ExpectedTruthValueResult("16.0", TruthValue.UNKNOWN), - new ExpectedTruthValueResult("17.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult resultInvInitial = new ExpectedTruthValueEvaluationResult(goal53); - ExpectedBranchResult goal141 = new ExpectedBranchResult(); - ExpectedTruthValueEvaluationResult resultInvTermination = new ExpectedTruthValueEvaluationResult(goal141); - ExpectedBranchResult goal214 = new ExpectedBranchResult(); - ExpectedBranchResult goal229 = new ExpectedBranchResult(); - ExpectedBranchResult goal233 = new ExpectedBranchResult(); - ExpectedBranchResult goal231 = new ExpectedBranchResult(); - ExpectedBranchResult goal216 = new ExpectedBranchResult(); - ExpectedTruthValueEvaluationResult resultNormalTermination = new ExpectedTruthValueEvaluationResult(goal214, goal229, goal233, goal231, goal216); - // Perform test - doTruthValueEvaluationTest("/set/truthValueAddingOfLabeledSubtree/test/ImmutableList.proof", - "/set/truthValueAddingOfLabeledSubtree/oracle/ImmutableList.xml", - false, - false, - false, - resultInvInitial, - resultInvTermination, - resultNormalTermination); - } - - /** - * Tests example: /set/truthValueAssignableAndLoop - */ - @Test@Disabled - public void IGNORE_testAssignableAndLoop() throws Exception { - // Create expected results - ExpectedBranchResult goal430 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.FALSE), - new ExpectedTruthValueResult("4.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult resultExceptionBranch = new ExpectedTruthValueEvaluationResult(goal430); - ExpectedBranchResult goal478 = new ExpectedBranchResult(new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult resultInvInitial = new ExpectedTruthValueEvaluationResult(goal478); - ExpectedBranchResult goal922 = new ExpectedBranchResult(new ExpectedTruthValueResult("19.0", TruthValue.TRUE), - new ExpectedTruthValueResult("20.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult resultPrecondition = new ExpectedTruthValueEvaluationResult(goal922); - ExpectedBranchResult goal886 = new ExpectedBranchResult(); - ExpectedBranchResult goal869 = new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE), - new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); - ExpectedBranchResult goal868 = new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE), - new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult resultLoopEnd = new ExpectedTruthValueEvaluationResult(goal868, goal869, goal886); - ExpectedBranchResult goal1113 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.UNKNOWN), - new ExpectedTruthValueResult("6.0", TruthValue.UNKNOWN)); - ExpectedBranchResult goal1134 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); - ExpectedBranchResult goal1137 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result5 = new ExpectedTruthValueEvaluationResult(goal1113, goal1134, goal1137); - // Perform test - doTruthValueEvaluationTest("/set/truthValueAssignableAndLoop/test/MagicProofNoOSS.proof", - "/set/truthValueAssignableAndLoop/oracle/MagicProofNoOSS.xml", - true, - true, - false, - resultExceptionBranch, - resultInvInitial, - resultPrecondition, - resultLoopEnd, - result5); - } - - /** - * Tests example: /set/truthValueAnd - */ - @Test public void testAnd3_replaceKnown() throws Exception { - // Create expected results - ExpectedBranchResult goal13 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE), - new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE)); - ExpectedBranchResult goal15 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("2.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE), - new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal13, goal15); - // Perform test - doTruthValueEvaluationTest("/set/truthValueAnd/test/And3_replaceKnown.proof", - "/set/truthValueAnd/oracle/And3_replaceKnown.xml", - false, - false, - false, - result1); - } - - /** - * Tests example: /set/truthValueUnderstandingProofsMyInteger - */ - @Test public void testUnderstandingProofs_MyInteger() throws Exception { - // Create expected results - ExpectedBranchResult goal131 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); - ExpectedBranchResult goal133 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.FALSE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); - ExpectedBranchResult goal150 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal131, goal133, goal150); - // Perform test - doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsMyInteger/test/MyInteger.proof", - "/set/truthValueUnderstandingProofsMyInteger/oracle/MyInteger.xml", - false, - false, - false, - result1); - } - - /** - * Tests example: /set/truthValueUnderstandingProofsArrayUtil - */ - @Test public void testUnderstandingProofs_ArrayUtil() throws Exception { - // Create expected results - ExpectedBranchResult goal87 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE), - new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal87); - ExpectedBranchResult goal175 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.FALSE), - new ExpectedTruthValueResult("2.0", TruthValue.FALSE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result2 = new ExpectedTruthValueEvaluationResult(goal175); - ExpectedBranchResult goal249 = new ExpectedBranchResult(new ExpectedTruthValueResult("16.0", TruthValue.TRUE), - new ExpectedTruthValueResult("17.0", TruthValue.TRUE), - new ExpectedTruthValueResult("18.0", TruthValue.TRUE), - new ExpectedTruthValueResult("19.0", TruthValue.TRUE), - new ExpectedTruthValueResult("24.0", TruthValue.TRUE), - new ExpectedTruthValueResult("25.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result3 = new ExpectedTruthValueEvaluationResult(goal249); - ExpectedBranchResult goal698 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedBranchResult goal747 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("34.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedBranchResult goal812 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("34.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedBranchResult goal821 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("38.0", TruthValue.TRUE), - new ExpectedTruthValueResult("39.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result4 = new ExpectedTruthValueEvaluationResult(goal698, goal747, goal812, goal821); - ExpectedBranchResult goal1012 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("34.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedBranchResult goal1021 = new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), - new ExpectedTruthValueResult("27.0", TruthValue.TRUE), - new ExpectedTruthValueResult("28.0", TruthValue.TRUE), - new ExpectedTruthValueResult("29.0", TruthValue.TRUE), - new ExpectedTruthValueResult("38.0", TruthValue.TRUE), - new ExpectedTruthValueResult("39.0", TruthValue.TRUE), - new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result5 = new ExpectedTruthValueEvaluationResult(goal1012, goal1021); - ExpectedBranchResult goal1251 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), - new ExpectedTruthValueResult("1.0", TruthValue.FALSE), - new ExpectedTruthValueResult("2.0", TruthValue.FALSE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE), - new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result6 = new ExpectedTruthValueEvaluationResult(goal1251); - ExpectedBranchResult goal1272 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE), - new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result7 = new ExpectedTruthValueEvaluationResult(goal1272); - // Perform test - doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsArrayUtil/test/ArrayUtil.proof", - "/set/truthValueUnderstandingProofsArrayUtil/oracle/ArrayUtil.xml", - false, - false, - false, - result1, - result2, - result3, - result4, - result5, - result6, - result7); - } - - /** - * Tests example: /set/truthValueUnderstandingProofsAccount - */ - @Test public void testUnderstandingProofs_Account() throws Exception { - // Create expected results - ExpectedBranchResult goal246 = new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("10.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE)); - ExpectedBranchResult goal248 = new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), - new ExpectedTruthValueResult("11.0", TruthValue.TRUE), - new ExpectedTruthValueResult("12.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal246, goal248); - ExpectedBranchResult goal195 = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("14.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE), - new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); - ExpectedBranchResult goal197 = new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), - new ExpectedTruthValueResult("15.0", TruthValue.TRUE), - new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result2 = new ExpectedTruthValueEvaluationResult(goal195, goal197); - ExpectedBranchResult goal165 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal166 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal168 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result3 = new ExpectedTruthValueEvaluationResult(goal165, goal166, goal168); - ExpectedBranchResult goal224 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE), - new ExpectedTruthValueResult("3.0", TruthValue.FALSE), - new ExpectedTruthValueResult("4.0", TruthValue.FALSE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult result4 = new ExpectedTruthValueEvaluationResult(goal224); - // Perform test - doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsAccount/test/Account.proof", - "/set/truthValueUnderstandingProofsAccount/oracle/Account.xml", - false, - false, - false, - result1, - result2, - result3, - result4); - } - - /** - * Tests example: /set/truthValueUnderstandingProofsCalendar - */ - @Test public void testUnderstandingProofs_Calendar() throws Exception { - // Create expected results - ExpectedBranchResult goal369 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.TRUE), - new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("4.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal392 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("7.0", TruthValue.TRUE), - new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); - ExpectedBranchResult goal423 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("2.0", TruthValue.FALSE), - new ExpectedTruthValueResult("3.0", TruthValue.FALSE), - new ExpectedTruthValueResult("4.0", TruthValue.FALSE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); - ExpectedBranchResult goal425 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), - new ExpectedTruthValueResult("1.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal369, goal392, goal423, goal425); - ExpectedBranchResult goal611 = new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.FALSE), - new ExpectedTruthValueResult("6.0", TruthValue.FALSE), - new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); - ExpectedTruthValueEvaluationResult result2 = new ExpectedTruthValueEvaluationResult(goal611); - // Perform test - doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsCalendar/test/Calendar.proof", - "/set/truthValueUnderstandingProofsCalendar/oracle/Calendar.xml", - false, - false, - false, - result1, - result2); - } - - /** - * Tests example: /set/truthValueMyInteger - */ - @Test public void testMyInteger() throws Exception { - // Create expected results - ExpectedBranchResult goal131 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); - ExpectedBranchResult goal133 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.FALSE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.FALSE), new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); - ExpectedBranchResult goal150 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal131, goal133, goal150); - // Perform test - doTruthValueEvaluationTest("/set/truthValueMyInteger/test/MyInteger.proof", - "/set/truthValueMyInteger/oracle/MyInteger.xml", - false, - false, - false, - result); - } - - /** - * Tests example: /set/truthValueEquivExample - */ - @Test public void testEquivExample_NoOneStepSimplification() throws Exception { - // Create expected results - ExpectedBranchResult goal79 = new ExpectedBranchResult(new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); - ExpectedBranchResult goal91 = new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); - ExpectedBranchResult goal95 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE)); - ExpectedBranchResult goal97 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.FALSE)); // SETAccumulate is false - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal79, goal91, goal95, goal97); - // Perform test - doTruthValueEvaluationTest("/set/truthValueEquivExample/test/EquivExampleNoOneStepSimplification.proof", - "/set/truthValueEquivExample/oracle/EquivExample.xml", - false, - true, - false, - result); - } - - /** - * Tests example: /set/truthValueEquivExample - */ - @Test public void testEquivExample() throws Exception { - // Create expected results - ExpectedBranchResult goal39 = new ExpectedBranchResult(new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); - ExpectedBranchResult goal50 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), - new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); - ExpectedBranchResult goal53 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); - ExpectedBranchResult goal55 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.FALSE)); // SETAccumulate is false - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal39, goal50, goal53, goal55); - // Perform test - doTruthValueEvaluationTest("/set/truthValueEquivExample/test/EquivExample.proof", - "/set/truthValueEquivExample/oracle/EquivExample.xml", - false, - false, - false, - result); - } - - /** - * Tests example: /set/truthValueIfThenElseIntegerTest - */ - @Test public void testIfThenElseInteger() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueIfThenElseIntegerTest/test/IfThenElseIntegerTest.java", - "IfThenElseIntegerTest[IfThenElseIntegerTest::magic(int,int)].JML normal_behavior operation contract.0", - "/set/truthValueIfThenElseIntegerTest/oracle/IfThenElseIntegerTest.xml", - false, - false, - false, - thenResult, - elseResult); - } - - /** - * Tests example: /set/truthValueIfThenElseNotFormulaTest - */ - @Test public void testIfThenElseNotFormula() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueIfThenElseNotFormulaTest/test/IfThenElseNotFormulaTest.java", - "IfThenElseNotFormulaTest[IfThenElseNotFormulaTest::magic(int,int)].JML normal_behavior operation contract.0", - "/set/truthValueIfThenElseNotFormulaTest/oracle/IfThenElseNotFormulaTest.xml", - false, - false, - false, - thenResult, - elseResult); - } - - /** - * Tests example: /set/truthValueIfThenElseFormulaTest - */ - @Test public void testIfThenElseFormula() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.FALSE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueIfThenElseFormulaTest/test/IfThenElseFormulaTest.java", - "IfThenElseFormulaTest[IfThenElseFormulaTest::magic(int,int)].JML normal_behavior operation contract.0", - "/set/truthValueIfThenElseFormulaTest/oracle/IfThenElseFormulaTest.xml", - false, - false, - false, - thenResult, - elseResult); - } - - /** - * Tests example: /set/truthValueNotLastEvaluationGivesTruthValue - */ - @Test public void testNotLastEvaluationGivesTruthValue() throws Exception { - // Create expected results - ExpectedBranchResult goal53 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("6.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.12", TruthValue.FALSE), new ExpectedTruthValueResult("1.13", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE)); - ExpectedBranchResult goal41 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.TRUE)); - ExpectedBranchResult goal39 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.TRUE)); - ExpectedBranchResult goal55 = new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.11", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult result = new ExpectedTruthValueEvaluationResult(goal53, goal41, goal39, goal55); - // Perform test - doTruthValueEvaluationTest("/set/truthValueNotLastEvaluationGivesTruthValue/test/NotLastEvaluationGivesTruthValue.proof", - "/set/truthValueNotLastEvaluationGivesTruthValue/oracle/NotLastEvaluationGivesTruthValue.xml", - false, - true, - false, - result); - } - - /** - * Tests example: /set/truthValueArraySumWhile - */ - @Test public void testArraySumWhile_NoOneStepSimplification() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult initialResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("14.0", TruthValue.TRUE), new ExpectedTruthValueResult("15.0", TruthValue.TRUE), new ExpectedTruthValueResult("16.0", TruthValue.TRUE), new ExpectedTruthValueResult("17.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult preservesResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("18.0", TruthValue.TRUE), new ExpectedTruthValueResult("19.0", TruthValue.TRUE), new ExpectedTruthValueResult("20.0", TruthValue.TRUE), new ExpectedTruthValueResult("21.0", TruthValue.TRUE), new ExpectedTruthValueResult("22.0", TruthValue.TRUE), new ExpectedTruthValueResult("23.0", TruthValue.TRUE), new ExpectedTruthValueResult("24.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.FALSE), new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueArraySumWhile/test/ArraySumWhileNoOneStepSimplification.proof", - "/set/truthValueArraySumWhile/oracle/ArraySumWhile.xml", - false, - true, - false, - initialResult, - preservesResult, - terminationResult); - } - - /** - * Tests example: /set/truthValueArraySumWhile - */ - @Test public void testArraySumWhile() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult initialResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("14.0", TruthValue.TRUE), new ExpectedTruthValueResult("15.0", TruthValue.TRUE), new ExpectedTruthValueResult("16.0", TruthValue.TRUE), new ExpectedTruthValueResult("17.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult preservesResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("18.0", TruthValue.TRUE), new ExpectedTruthValueResult("19.0", TruthValue.TRUE), new ExpectedTruthValueResult("20.0", TruthValue.TRUE), new ExpectedTruthValueResult("21.0", TruthValue.TRUE), new ExpectedTruthValueResult("22.0", TruthValue.TRUE), new ExpectedTruthValueResult("23.0", TruthValue.TRUE), new ExpectedTruthValueResult("24.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE), new ExpectedTruthValueResult("4.0", TruthValue.FALSE), new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueArraySumWhile/test/ArraySumWhile.proof", - "/set/truthValueArraySumWhile/oracle/ArraySumWhile.xml", - false, - true, - false, - initialResult, - preservesResult, - terminationResult); - } - - /** - * Tests example: /set/truthValueArrayUtil - */ - @Test@Disabled - public void IGNORE_testArrayUtil_NoOneStepSimplification() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult goal97 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("6.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal826 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("17.0", TruthValue.TRUE), new ExpectedTruthValueResult("18.0", TruthValue.TRUE), new ExpectedTruthValueResult("20.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal630 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("13.0", TruthValue.FALSE))); - ExpectedTruthValueEvaluationResult goal792 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("12.0", TruthValue.TRUE), new ExpectedTruthValueResult("13.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal1024 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal1161 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueArrayUtil/test/ArrayUtilNoOneStepSimplification.proof", - "/set/truthValueArrayUtil/oracle/ArrayUtil.xml", - true, - true, - false, - goal97, - goal826, - goal630, - goal792, - goal1024, - goal1161); - } - - /** - * Tests example: /set/truthValueArrayUtil - */ - @Test@Disabled - public void IGNORE_testArrayUtil() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult goal97 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("6.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal826 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("17.0", TruthValue.TRUE), new ExpectedTruthValueResult("18.0", TruthValue.TRUE), new ExpectedTruthValueResult("20.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal630 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("13.0", TruthValue.FALSE))); - ExpectedTruthValueEvaluationResult goal792 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("12.0", TruthValue.TRUE), new ExpectedTruthValueResult("13.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal1024 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult goal1161 = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueArrayUtil/test/ArrayUtil.proof", - "/set/truthValueArrayUtil/oracle/ArrayUtil.xml", - true, - true, - false, - goal97, - goal826, - goal630, - goal792, - goal1024, - goal1161); - } - - /** - * Tests example: /set/truthValueSimpleInstanceMethodContractApplication - */ - @Test public void testSimpleInstanceMethodContractApplication_NoOneStepSimplification() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("12.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueSimpleInstanceMethodContractApplication/test/SimpleInstanceMethodContractApplication_NoOneStepSimplification.proof", - "/set/truthValueSimpleInstanceMethodContractApplication/oracle/SimpleInstanceMethodContractApplication.xml", - true, - false, - false, - preResult, - terminationResult); - } - - /** - * Tests example: /set/truthValueSimpleInstanceMethodContractApplication - */ - @Test public void testSimpleInstanceMethodContractApplication() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("12.0", TruthValue.TRUE), new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueSimpleInstanceMethodContractApplication/test/SimpleInstanceMethodContractApplication.proof", - "/set/truthValueSimpleInstanceMethodContractApplication/oracle/SimpleInstanceMethodContractApplication.xml", - true, - false, - false, - preResult, - terminationResult); - } + // Create expected results + ExpectedBranchResult seGoal = new ExpectedBranchResult(); + ExpectedBranchResult weakeningGoal = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.FALSE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.FALSE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("17.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult seResult = + new ExpectedTruthValueEvaluationResult(seGoal); + ExpectedTruthValueEvaluationResult weakeningResult = + new ExpectedTruthValueEvaluationResult(weakeningGoal); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueWeakeningTest/test/JoinTestAfterBranchConditionWithWeakeningGoal.proof", + "/set/truthValueWeakeningTest/oracle/JoinTestAfterBranchCondition.xml", false, + false, false, seResult, weakeningResult); + } - /** - * Tests example: /set/truthValueSimpleMethodContractApplication - */ - @Test public void testSimpleMethodContractApplication_NoOneStepSimplification() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueSimpleMethodContractApplication/test/SimpleMethodContractApplication_NoOneStepSimplification.proof", - "/set/truthValueSimpleMethodContractApplication/oracle/SimpleMethodContractApplication.xml", - true, - false, - false, - preResult, - terminationResult); - } - - /** - * Tests example: /set/truthValueSimpleMethodContractApplication - */ - @Test public void testSimpleMethodContractApplication() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("10.0", TruthValue.TRUE), new ExpectedTruthValueResult("9.0", TruthValue.TRUE), new ExpectedTruthValueResult("11.0", TruthValue.TRUE), new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult terminationResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE), new ExpectedTruthValueResult("5.0", TruthValue.TRUE), new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueSimpleMethodContractApplication/test/SimpleMethodContractApplication.proof", - "/set/truthValueSimpleMethodContractApplication/oracle/SimpleMethodContractApplication.xml", - true, - false, - false, - preResult, - terminationResult); - } - - /** - * Tests example: /set/truthValueDifferentBranchesTest - */ - @Test public void testDifferentBranchesTest() throws Exception { - // Create expected results - ExpectedTruthValueEvaluationResult firstResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult secondResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); - ExpectedTruthValueEvaluationResult thirdResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE))); - ExpectedTruthValueEvaluationResult fourthResult = new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE))); - // Perform test - doTruthValueEvaluationTest("/set/truthValueDifferentBranchesTest/test/DifferentBranchesTest.proof", - "/set/truthValueDifferentBranchesTest/oracle/DifferentBranchesTest.xml", - false, - false, - false, - firstResult, - secondResult, - thirdResult, - fourthResult); - } - - /** - * Tests example: /set/truthValueMultiplePredicateResults - */ - @Test public void testMultiplePredicateResultsTest() throws Exception { - // Create expected results - ExpectedBranchResult goal102 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE)); - ExpectedBranchResult goal95 = new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), new ExpectedTruthValueResult("1.0", TruthValue.TRUE)); - ExpectedTruthValueEvaluationResult expectedResult = new ExpectedTruthValueEvaluationResult(goal102, goal95); - // Perform test - doTruthValueEvaluationTest("/set/truthValueMultiplePredicateResults/test/MultiplePredicateResultsTest.java", - "MultiplePredicateResultsTest[MultiplePredicateResultsTest::main(MultiplePredicateResultsTest,MultiplePredicateResultsTest)].JML normal_behavior operation contract.0", - "/set/truthValueMultiplePredicateResults/oracle/MultiplePredicateResultsTest.xml", - false, - false, - false, - expectedResult); - } - - /** - * Performs an {@link TruthValueTracingUtil} test. - * @param proofFilePathInBaseDir The path to the java file inside the base directory. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param expectedResults The expected results. - * @throws Exception Occurred Exception. - */ - protected void doTruthValueEvaluationTest(String proofFilePathInBaseDir, - String oraclePathInBaseDirFile, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { - SymbolicExecutionEnvironment env = null; - try { - // Perform symbolic execution - env = doSETTest(testCaseDirectory, - proofFilePathInBaseDir, - oraclePathInBaseDirFile, - false, - false, - false, - false, - false, - useOperationContracts, - useLoopInvariants, - blockTreatmentContract, - false, - false, - false, - false, - false, - true, - true); - assertNotNull(env); - // Evaluate truth values - doTruthValueEvaluationTest(env, expectedResults); - } - finally { - if (env != null) { - env.dispose(); - } - } - } - - /** - * Performs an {@link TruthValueTracingUtil} test. - * @param javaPathInBaseDir The path to the java file inside the base directory. - * @param baseContractName The name of the contract. - * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. - * @param useOperationContracts Use operation contracts? - * @param useLoopInvariants Use loop invariants? - * @param blockTreatmentContract Block contracts or expand otherwise? - * @param expectedResults The expected results. - * @throws Exception Occurred Exception. - */ - protected void doTruthValueEvaluationTest(String javaPathInBaseDir, - String baseContractName, - String oraclePathInBaseDirFile, - boolean useOperationContracts, - boolean useLoopInvariants, - boolean blockTreatmentContract, - ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { - SymbolicExecutionEnvironment env = null; - try { - // Perform symbolic execution - env = doSETTest(testCaseDirectory, - javaPathInBaseDir, - baseContractName, - oraclePathInBaseDirFile, - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - useOperationContracts, - useLoopInvariants, - blockTreatmentContract, - false, - false, - false, - false, - false, - true, - true); - // Evaluate truth values - doTruthValueEvaluationTest(env, expectedResults); - } - finally { - if (env != null) { - env.dispose(); - } - } - } - - /** - * Performs an {@link TruthValueTracingUtil} test. - * @param env The {@link SymbolicExecutionEnvironment} to use. - * @param expectedResults The expected results. - * @throws Exception Occurred Exception. - */ - protected void doTruthValueEvaluationTest(SymbolicExecutionEnvironment env, - ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { - // Compute current results - List currentResults = new LinkedList<>(); - ExecutionNodePreorderIterator iter = new ExecutionNodePreorderIterator(env.getBuilder().getStartNode()); - while (iter.hasNext()) { - IExecutionNode next = iter.next(); - Node nodeToEvaluate; - if (next instanceof IExecutionTermination) { - nodeToEvaluate = next.getProofNode(); - } - else if (next instanceof IExecutionOperationContract) { - nodeToEvaluate = next.getProofNode().child(2); // Precondition branch - } - else if (next instanceof IExecutionLoopInvariant) { - nodeToEvaluate = next.getProofNode().child(0); // Initial - } - else if (next instanceof IExecutionAuxiliaryContract) { - nodeToEvaluate = next.getProofNode().child(1); // Precondition branch - } - else if (next instanceof IExecutionJoin) { - nodeToEvaluate = next.getProofNode().child(0); // Weakening branch - } - else { - nodeToEvaluate = null; - } - if (nodeToEvaluate != null) { - TruthValueTracingResult result = TruthValueTracingUtil.evaluate(nodeToEvaluate, FormulaTermLabel.NAME, false, false); - currentResults.add(result); - if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { - LOGGER.info("Found Result: {}", result); + /** + * Tests example: /set/truthValueLabelBelowUpdatesDifferentToApplicationTerm + */ + @Test + public void testTruthValueLabelBelowUpdatesDifferentToApplicationTerm() throws Exception { + // Create expected results + ExpectedBranchResult goal15 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); + ExpectedBranchResult goal17 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal15, goal17); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueLabelBelowUpdatesDifferentToApplicationTerm/test/TwoBranch.proof", + "/set/truthValueLabelBelowUpdatesDifferentToApplicationTerm/oracle/TwoBranch.xml", + false, false, false, result); + } + + /** + * Tests example: /set/truthValueExceptinalAssignableNothingTest + */ + @Test + public void testExceptinalAssignableNothingTest_OSS() throws Exception { + // Create expected results + ExpectedBranchResult goal374 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal407 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal444 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal475 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal476 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult exceptionResult = + new ExpectedTruthValueEvaluationResult(goal374, goal407, goal444, goal475, goal476); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueExceptinalAssignableNothingTest/test/ExceptinalAssignableNothingTest_OSS.proof", + "/set/truthValueExceptinalAssignableNothingTest/oracle/ExceptinalAssignableNothingTest.xml", + false, false, false, exceptionResult); + } + + /** + * Tests example: /set/truthValueExceptinalAssignableNothingTest + */ + @Test + public void testExceptinalAssignableNothingTest() throws Exception { + // Create expected results + ExpectedBranchResult goal374 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal407 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal444 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal475 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedBranchResult goal476 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult exceptionResult = + new ExpectedTruthValueEvaluationResult(goal374, goal407, goal444, goal475, goal476); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueExceptinalAssignableNothingTest/test/ExceptinalAssignableNothingTest.proof", + "/set/truthValueExceptinalAssignableNothingTest/oracle/ExceptinalAssignableNothingTest.xml", + false, false, false, exceptionResult); + } + + /** + * Tests example: /set/truthValueBlockContractMagic42 + */ + @Test + @Disabled + public void IGNORE_testBlockContractMagic42() throws Exception { + // Create expected results + ExpectedBranchResult goal66 = + new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult preconditionResult = + new ExpectedTruthValueEvaluationResult(goal66); + ExpectedBranchResult goal62 = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("19.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE), + new ExpectedTruthValueResult("21.0", TruthValue.TRUE)); + ExpectedBranchResult goal64 = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("21.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult validitiyResult = + new ExpectedTruthValueEvaluationResult(goal62, goal64); + ExpectedBranchResult goal152 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal154 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult usageResult = + new ExpectedTruthValueEvaluationResult(goal152, goal154); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueBlockContractMagic42/test/BlockContractMagic42.proof", + "/set/truthValueBlockContractMagic42/oracle/BlockContractMagic42.xml", false, false, + true, preconditionResult, validitiyResult, usageResult); + } + + /** + * Tests example: /set/truthValueRejectedFormula + */ + @Test + public void testValueRejectedFormula() throws Exception { + // Create expected results + ExpectedBranchResult goal31 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal33 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal31, goal33); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueRejectedFormula/test/LabelLostVerification.proof", + "/set/truthValueRejectedFormula/oracle/LabelLostVerification.xml", false, false, + false, result); + } + + /** + * Tests example: /set/truthValueAddingOfLabeledSubtree + */ + @Test + @Disabled + public void IGNORE_testAddingOfLabeledSubtree() throws Exception { + // Create expected results + ExpectedBranchResult goal53 = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.FALSE), + new ExpectedTruthValueResult("16.0", TruthValue.UNKNOWN), + new ExpectedTruthValueResult("17.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult resultInvInitial = + new ExpectedTruthValueEvaluationResult(goal53); + ExpectedBranchResult goal141 = new ExpectedBranchResult(); + ExpectedTruthValueEvaluationResult resultInvTermination = + new ExpectedTruthValueEvaluationResult(goal141); + ExpectedBranchResult goal214 = new ExpectedBranchResult(); + ExpectedBranchResult goal229 = new ExpectedBranchResult(); + ExpectedBranchResult goal233 = new ExpectedBranchResult(); + ExpectedBranchResult goal231 = new ExpectedBranchResult(); + ExpectedBranchResult goal216 = new ExpectedBranchResult(); + ExpectedTruthValueEvaluationResult resultNormalTermination = + new ExpectedTruthValueEvaluationResult(goal214, goal229, goal233, goal231, goal216); + // Perform test + doTruthValueEvaluationTest("/set/truthValueAddingOfLabeledSubtree/test/ImmutableList.proof", + "/set/truthValueAddingOfLabeledSubtree/oracle/ImmutableList.xml", false, false, + false, resultInvInitial, resultInvTermination, resultNormalTermination); + } + + /** + * Tests example: /set/truthValueAssignableAndLoop + */ + @Test + @Disabled + public void IGNORE_testAssignableAndLoop() throws Exception { + // Create expected results + ExpectedBranchResult goal430 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.FALSE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult resultExceptionBranch = + new ExpectedTruthValueEvaluationResult(goal430); + ExpectedBranchResult goal478 = + new ExpectedBranchResult(new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult resultInvInitial = + new ExpectedTruthValueEvaluationResult(goal478); + ExpectedBranchResult goal922 = + new ExpectedBranchResult(new ExpectedTruthValueResult("19.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult resultPrecondition = + new ExpectedTruthValueEvaluationResult(goal922); + ExpectedBranchResult goal886 = new ExpectedBranchResult(); + ExpectedBranchResult goal869 = + new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); + ExpectedBranchResult goal868 = + new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult resultLoopEnd = + new ExpectedTruthValueEvaluationResult(goal868, goal869, goal886); + ExpectedBranchResult goal1113 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.UNKNOWN), + new ExpectedTruthValueResult("6.0", TruthValue.UNKNOWN)); + ExpectedBranchResult goal1134 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); + ExpectedBranchResult goal1137 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result5 = + new ExpectedTruthValueEvaluationResult(goal1113, goal1134, goal1137); + // Perform test + doTruthValueEvaluationTest("/set/truthValueAssignableAndLoop/test/MagicProofNoOSS.proof", + "/set/truthValueAssignableAndLoop/oracle/MagicProofNoOSS.xml", true, true, false, + resultExceptionBranch, resultInvInitial, resultPrecondition, resultLoopEnd, + result5); + } + + /** + * Tests example: /set/truthValueAnd + */ + @Test + public void testAnd3_replaceKnown() throws Exception { + // Create expected results + ExpectedBranchResult goal13 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE)); + ExpectedBranchResult goal15 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result1 = + new ExpectedTruthValueEvaluationResult(goal13, goal15); + // Perform test + doTruthValueEvaluationTest("/set/truthValueAnd/test/And3_replaceKnown.proof", + "/set/truthValueAnd/oracle/And3_replaceKnown.xml", false, false, false, result1); + } + + /** + * Tests example: /set/truthValueUnderstandingProofsMyInteger + */ + @Test + public void testUnderstandingProofs_MyInteger() throws Exception { + // Create expected results + ExpectedBranchResult goal131 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); + ExpectedBranchResult goal133 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); + ExpectedBranchResult goal150 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result1 = + new ExpectedTruthValueEvaluationResult(goal131, goal133, goal150); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueUnderstandingProofsMyInteger/test/MyInteger.proof", + "/set/truthValueUnderstandingProofsMyInteger/oracle/MyInteger.xml", false, false, + false, result1); + } + + /** + * Tests example: /set/truthValueUnderstandingProofsArrayUtil + */ + @Test + public void testUnderstandingProofs_ArrayUtil() throws Exception { + // Create expected results + ExpectedBranchResult goal87 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result1 = new ExpectedTruthValueEvaluationResult(goal87); + ExpectedBranchResult goal175 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.FALSE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result2 = + new ExpectedTruthValueEvaluationResult(goal175); + ExpectedBranchResult goal249 = + new ExpectedBranchResult(new ExpectedTruthValueResult("16.0", TruthValue.TRUE), + new ExpectedTruthValueResult("17.0", TruthValue.TRUE), + new ExpectedTruthValueResult("18.0", TruthValue.TRUE), + new ExpectedTruthValueResult("19.0", TruthValue.TRUE), + new ExpectedTruthValueResult("24.0", TruthValue.TRUE), + new ExpectedTruthValueResult("25.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result3 = + new ExpectedTruthValueEvaluationResult(goal249); + ExpectedBranchResult goal698 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedBranchResult goal747 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("34.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedBranchResult goal812 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("34.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedBranchResult goal821 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("38.0", TruthValue.TRUE), + new ExpectedTruthValueResult("39.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result4 = + new ExpectedTruthValueEvaluationResult(goal698, goal747, goal812, goal821); + ExpectedBranchResult goal1012 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("34.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedBranchResult goal1021 = + new ExpectedBranchResult(new ExpectedTruthValueResult("26.0", TruthValue.TRUE), + new ExpectedTruthValueResult("27.0", TruthValue.TRUE), + new ExpectedTruthValueResult("28.0", TruthValue.TRUE), + new ExpectedTruthValueResult("29.0", TruthValue.TRUE), + new ExpectedTruthValueResult("38.0", TruthValue.TRUE), + new ExpectedTruthValueResult("39.0", TruthValue.TRUE), + new ExpectedTruthValueResult("40.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result5 = + new ExpectedTruthValueEvaluationResult(goal1012, goal1021); + ExpectedBranchResult goal1251 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.FALSE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result6 = + new ExpectedTruthValueEvaluationResult(goal1251); + ExpectedBranchResult goal1272 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result7 = + new ExpectedTruthValueEvaluationResult(goal1272); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueUnderstandingProofsArrayUtil/test/ArrayUtil.proof", + "/set/truthValueUnderstandingProofsArrayUtil/oracle/ArrayUtil.xml", false, false, + false, result1, result2, result3, result4, result5, result6, result7); + } + + /** + * Tests example: /set/truthValueUnderstandingProofsAccount + */ + @Test + public void testUnderstandingProofs_Account() throws Exception { + // Create expected results + ExpectedBranchResult goal246 = + new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE)); + ExpectedBranchResult goal248 = + new ExpectedBranchResult(new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result1 = + new ExpectedTruthValueEvaluationResult(goal246, goal248); + ExpectedBranchResult goal195 = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); + ExpectedBranchResult goal197 = + new ExpectedBranchResult(new ExpectedTruthValueResult("13.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result2 = + new ExpectedTruthValueEvaluationResult(goal195, goal197); + ExpectedBranchResult goal165 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal166 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal168 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result3 = + new ExpectedTruthValueEvaluationResult(goal165, goal166, goal168); + ExpectedBranchResult goal224 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE), + new ExpectedTruthValueResult("3.0", TruthValue.FALSE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult result4 = + new ExpectedTruthValueEvaluationResult(goal224); + // Perform test + doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsAccount/test/Account.proof", + "/set/truthValueUnderstandingProofsAccount/oracle/Account.xml", false, false, false, + result1, result2, result3, result4); + } + + /** + * Tests example: /set/truthValueUnderstandingProofsCalendar + */ + @Test + public void testUnderstandingProofs_Calendar() throws Exception { + // Create expected results + ExpectedBranchResult goal369 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal392 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE)); + ExpectedBranchResult goal423 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("3.0", TruthValue.FALSE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); + ExpectedBranchResult goal425 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result1 = + new ExpectedTruthValueEvaluationResult(goal369, goal392, goal423, goal425); + ExpectedBranchResult goal611 = + new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.FALSE)); + ExpectedTruthValueEvaluationResult result2 = + new ExpectedTruthValueEvaluationResult(goal611); + // Perform test + doTruthValueEvaluationTest("/set/truthValueUnderstandingProofsCalendar/test/Calendar.proof", + "/set/truthValueUnderstandingProofsCalendar/oracle/Calendar.xml", false, false, + false, result1, result2); + } + + /** + * Tests example: /set/truthValueMyInteger + */ + @Test + public void testMyInteger() throws Exception { + // Create expected results + ExpectedBranchResult goal131 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); + ExpectedBranchResult goal133 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.FALSE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("6.0", TruthValue.FALSE)); + ExpectedBranchResult goal150 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal131, goal133, goal150); + // Perform test + doTruthValueEvaluationTest("/set/truthValueMyInteger/test/MyInteger.proof", + "/set/truthValueMyInteger/oracle/MyInteger.xml", false, false, false, result); + } + + /** + * Tests example: /set/truthValueEquivExample + */ + @Test + public void testEquivExample_NoOneStepSimplification() throws Exception { + // Create expected results + ExpectedBranchResult goal79 = + new ExpectedBranchResult(new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); + ExpectedBranchResult goal91 = + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); + ExpectedBranchResult goal95 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE)); + ExpectedBranchResult goal97 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE)); // SETAccumulate is + // false + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal79, goal91, goal95, goal97); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueEquivExample/test/EquivExampleNoOneStepSimplification.proof", + "/set/truthValueEquivExample/oracle/EquivExample.xml", false, true, false, result); + } + + /** + * Tests example: /set/truthValueEquivExample + */ + @Test + public void testEquivExample() throws Exception { + // Create expected results + ExpectedBranchResult goal39 = + new ExpectedBranchResult(new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE)); + ExpectedBranchResult goal50 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); + ExpectedBranchResult goal53 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE)); + ExpectedBranchResult goal55 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.FALSE)); // SETAccumulate is + // false + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal39, goal50, goal53, goal55); + // Perform test + doTruthValueEvaluationTest("/set/truthValueEquivExample/test/EquivExample.proof", + "/set/truthValueEquivExample/oracle/EquivExample.xml", false, false, false, result); + } + + /** + * Tests example: /set/truthValueIfThenElseIntegerTest + */ + @Test + public void testIfThenElseInteger() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueIfThenElseIntegerTest/test/IfThenElseIntegerTest.java", + "IfThenElseIntegerTest[IfThenElseIntegerTest::magic(int,int)].JML normal_behavior operation contract.0", + "/set/truthValueIfThenElseIntegerTest/oracle/IfThenElseIntegerTest.xml", false, + false, false, thenResult, elseResult); + } + + /** + * Tests example: /set/truthValueIfThenElseNotFormulaTest + */ + @Test + public void testIfThenElseNotFormula() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueIfThenElseNotFormulaTest/test/IfThenElseNotFormulaTest.java", + "IfThenElseNotFormulaTest[IfThenElseNotFormulaTest::magic(int,int)].JML normal_behavior operation contract.0", + "/set/truthValueIfThenElseNotFormulaTest/oracle/IfThenElseNotFormulaTest.xml", + false, false, false, thenResult, elseResult); + } + + /** + * Tests example: /set/truthValueIfThenElseFormulaTest + */ + @Test + public void testIfThenElseFormula() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult thenResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult elseResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueIfThenElseFormulaTest/test/IfThenElseFormulaTest.java", + "IfThenElseFormulaTest[IfThenElseFormulaTest::magic(int,int)].JML normal_behavior operation contract.0", + "/set/truthValueIfThenElseFormulaTest/oracle/IfThenElseFormulaTest.xml", false, + false, false, thenResult, elseResult); + } + + /** + * Tests example: /set/truthValueNotLastEvaluationGivesTruthValue + */ + @Test + public void testNotLastEvaluationGivesTruthValue() throws Exception { + // Create expected results + ExpectedBranchResult goal53 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.12", TruthValue.FALSE), + new ExpectedTruthValueResult("1.13", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE)); + ExpectedBranchResult goal41 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.TRUE)); + ExpectedBranchResult goal39 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.TRUE)); + ExpectedBranchResult goal55 = + new ExpectedBranchResult(new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.11", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult result = + new ExpectedTruthValueEvaluationResult(goal53, goal41, goal39, goal55); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueNotLastEvaluationGivesTruthValue/test/NotLastEvaluationGivesTruthValue.proof", + "/set/truthValueNotLastEvaluationGivesTruthValue/oracle/NotLastEvaluationGivesTruthValue.xml", + false, true, false, result); + } + + /** + * Tests example: /set/truthValueArraySumWhile + */ + @Test + public void testArraySumWhile_NoOneStepSimplification() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult initialResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE), + new ExpectedTruthValueResult("17.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult preservesResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("18.0", TruthValue.TRUE), + new ExpectedTruthValueResult("19.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE), + new ExpectedTruthValueResult("21.0", TruthValue.TRUE), + new ExpectedTruthValueResult("22.0", TruthValue.TRUE), + new ExpectedTruthValueResult("23.0", TruthValue.TRUE), + new ExpectedTruthValueResult("24.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueArraySumWhile/test/ArraySumWhileNoOneStepSimplification.proof", + "/set/truthValueArraySumWhile/oracle/ArraySumWhile.xml", false, true, false, + initialResult, preservesResult, terminationResult); + } + + /** + * Tests example: /set/truthValueArraySumWhile + */ + @Test + public void testArraySumWhile() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult initialResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("14.0", TruthValue.TRUE), + new ExpectedTruthValueResult("15.0", TruthValue.TRUE), + new ExpectedTruthValueResult("16.0", TruthValue.TRUE), + new ExpectedTruthValueResult("17.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult preservesResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("18.0", TruthValue.TRUE), + new ExpectedTruthValueResult("19.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE), + new ExpectedTruthValueResult("21.0", TruthValue.TRUE), + new ExpectedTruthValueResult("22.0", TruthValue.TRUE), + new ExpectedTruthValueResult("23.0", TruthValue.TRUE), + new ExpectedTruthValueResult("24.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE), + new ExpectedTruthValueResult("4.0", TruthValue.FALSE), + new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest("/set/truthValueArraySumWhile/test/ArraySumWhile.proof", + "/set/truthValueArraySumWhile/oracle/ArraySumWhile.xml", false, true, false, + initialResult, preservesResult, terminationResult); + } + + /** + * Tests example: /set/truthValueArrayUtil + */ + @Test + @Disabled + public void IGNORE_testArrayUtil_NoOneStepSimplification() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult goal97 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal826 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("17.0", TruthValue.TRUE), + new ExpectedTruthValueResult("18.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal630 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.FALSE))); + ExpectedTruthValueEvaluationResult goal792 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal1024 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal1161 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueArrayUtil/test/ArrayUtilNoOneStepSimplification.proof", + "/set/truthValueArrayUtil/oracle/ArrayUtil.xml", true, true, false, goal97, goal826, + goal630, goal792, goal1024, goal1161); + } + + /** + * Tests example: /set/truthValueArrayUtil + */ + @Test + @Disabled + public void IGNORE_testArrayUtil() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult goal97 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("6.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal826 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("17.0", TruthValue.TRUE), + new ExpectedTruthValueResult("18.0", TruthValue.TRUE), + new ExpectedTruthValueResult("20.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal630 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.FALSE))); + ExpectedTruthValueEvaluationResult goal792 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("8.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("13.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal1024 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult goal1161 = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("3.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest("/set/truthValueArrayUtil/test/ArrayUtil.proof", + "/set/truthValueArrayUtil/oracle/ArrayUtil.xml", true, true, false, goal97, goal826, + goal630, goal792, goal1024, goal1161); + } + + /** + * Tests example: /set/truthValueSimpleInstanceMethodContractApplication + */ + @Test + public void testSimpleInstanceMethodContractApplication_NoOneStepSimplification() + throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueSimpleInstanceMethodContractApplication/test/SimpleInstanceMethodContractApplication_NoOneStepSimplification.proof", + "/set/truthValueSimpleInstanceMethodContractApplication/oracle/SimpleInstanceMethodContractApplication.xml", + true, false, false, preResult, terminationResult); + } + + /** + * Tests example: /set/truthValueSimpleInstanceMethodContractApplication + */ + @Test + public void testSimpleInstanceMethodContractApplication() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("12.0", TruthValue.TRUE), + new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueSimpleInstanceMethodContractApplication/test/SimpleInstanceMethodContractApplication.proof", + "/set/truthValueSimpleInstanceMethodContractApplication/oracle/SimpleInstanceMethodContractApplication.xml", + true, false, false, preResult, terminationResult); + } + + /** + * Tests example: /set/truthValueSimpleMethodContractApplication + */ + @Test + public void testSimpleMethodContractApplication_NoOneStepSimplification() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueSimpleMethodContractApplication/test/SimpleMethodContractApplication_NoOneStepSimplification.proof", + "/set/truthValueSimpleMethodContractApplication/oracle/SimpleMethodContractApplication.xml", + true, false, false, preResult, terminationResult); + } + + /** + * Tests example: /set/truthValueSimpleMethodContractApplication + */ + @Test + public void testSimpleMethodContractApplication() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult preResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("10.0", TruthValue.TRUE), + new ExpectedTruthValueResult("9.0", TruthValue.TRUE), + new ExpectedTruthValueResult("11.0", TruthValue.TRUE), + new ExpectedTruthValueResult("7.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult terminationResult = + new ExpectedTruthValueEvaluationResult(new ExpectedBranchResult( + new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE), + new ExpectedTruthValueResult("5.0", TruthValue.TRUE), + new ExpectedTruthValueResult("2.0", TruthValue.TRUE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueSimpleMethodContractApplication/test/SimpleMethodContractApplication.proof", + "/set/truthValueSimpleMethodContractApplication/oracle/SimpleMethodContractApplication.xml", + true, false, false, preResult, terminationResult); + } + + /** + * Tests example: /set/truthValueDifferentBranchesTest + */ + @Test + public void testDifferentBranchesTest() throws Exception { + // Create expected results + ExpectedTruthValueEvaluationResult firstResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult secondResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE))); + ExpectedTruthValueEvaluationResult thirdResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE))); + ExpectedTruthValueEvaluationResult fourthResult = new ExpectedTruthValueEvaluationResult( + new ExpectedBranchResult(new ExpectedTruthValueResult("1.0", TruthValue.FALSE))); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueDifferentBranchesTest/test/DifferentBranchesTest.proof", + "/set/truthValueDifferentBranchesTest/oracle/DifferentBranchesTest.xml", false, + false, false, firstResult, secondResult, thirdResult, fourthResult); + } + + /** + * Tests example: /set/truthValueMultiplePredicateResults + */ + @Test + public void testMultiplePredicateResultsTest() throws Exception { + // Create expected results + ExpectedBranchResult goal102 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.FALSE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE)); + ExpectedBranchResult goal95 = + new ExpectedBranchResult(new ExpectedTruthValueResult("0.0", TruthValue.TRUE), + new ExpectedTruthValueResult("1.0", TruthValue.TRUE)); + ExpectedTruthValueEvaluationResult expectedResult = + new ExpectedTruthValueEvaluationResult(goal102, goal95); + // Perform test + doTruthValueEvaluationTest( + "/set/truthValueMultiplePredicateResults/test/MultiplePredicateResultsTest.java", + "MultiplePredicateResultsTest[MultiplePredicateResultsTest::main(MultiplePredicateResultsTest,MultiplePredicateResultsTest)].JML normal_behavior operation contract.0", + "/set/truthValueMultiplePredicateResults/oracle/MultiplePredicateResultsTest.xml", + false, false, false, expectedResult); + } + + /** + * Performs an {@link TruthValueTracingUtil} test. + * + * @param proofFilePathInBaseDir The path to the java file inside the base directory. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param expectedResults The expected results. + * @throws Exception Occurred Exception. + */ + protected void doTruthValueEvaluationTest(String proofFilePathInBaseDir, + String oraclePathInBaseDirFile, boolean useOperationContracts, + boolean useLoopInvariants, boolean blockTreatmentContract, + ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { + SymbolicExecutionEnvironment env = null; + try { + // Perform symbolic execution + env = doSETTest(testCaseDirectory, proofFilePathInBaseDir, oraclePathInBaseDirFile, + false, false, false, false, false, useOperationContracts, useLoopInvariants, + blockTreatmentContract, false, false, false, false, false, true, true); + assertNotNull(env); + // Evaluate truth values + doTruthValueEvaluationTest(env, expectedResults); + } finally { + if (env != null) { + env.dispose(); + } + } + } + + /** + * Performs an {@link TruthValueTracingUtil} test. + * + * @param javaPathInBaseDir The path to the java file inside the base directory. + * @param baseContractName The name of the contract. + * @param oraclePathInBaseDirFile The path to the oracle file inside the base directory. + * @param useOperationContracts Use operation contracts? + * @param useLoopInvariants Use loop invariants? + * @param blockTreatmentContract Block contracts or expand otherwise? + * @param expectedResults The expected results. + * @throws Exception Occurred Exception. + */ + protected void doTruthValueEvaluationTest(String javaPathInBaseDir, String baseContractName, + String oraclePathInBaseDirFile, boolean useOperationContracts, + boolean useLoopInvariants, boolean blockTreatmentContract, + ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { + SymbolicExecutionEnvironment env = null; + try { + // Perform symbolic execution + env = doSETTest(testCaseDirectory, javaPathInBaseDir, baseContractName, + oraclePathInBaseDirFile, false, false, false, false, ALL_IN_ONE_RUN, false, + useOperationContracts, useLoopInvariants, blockTreatmentContract, false, false, + false, false, false, true, true); + // Evaluate truth values + doTruthValueEvaluationTest(env, expectedResults); + } finally { + if (env != null) { + env.dispose(); } - } - } - // Compare results - assertResults(expectedResults, currentResults); - } + } + } - /** - * Asserts the results. - * @param expected The expected results. - * @param current The current results. - */ - protected void assertResults(ExpectedTruthValueEvaluationResult[] expected, List current) { - Assertions.assertEquals(expected.length, current.size()); - int i = 0; - Iterator currentIter = current.iterator(); - while (i < expected.length && currentIter.hasNext()) { - assertTruthValueResults(expected[i], currentIter.next()); - i++; - } - Assertions.assertEquals(expected.length, i); - Assertions.assertFalse(currentIter.hasNext()); - } - - /** - * Asserts the truth value results. - * @param expected The expected results. - * @param current The current results. - */ - protected void assertTruthValueResults(ExpectedTruthValueEvaluationResult expected, TruthValueTracingResult current) { - BranchResult[] currentResults = current.getBranchResults(); - Assertions.assertEquals(expected.branchResults.length, currentResults.length); - for (int i = 0; i < currentResults.length; i++) { - assertBranchResult(expected.branchResults[i], currentResults[i]); - } - } + /** + * Performs an {@link TruthValueTracingUtil} test. + * + * @param env The {@link SymbolicExecutionEnvironment} to use. + * @param expectedResults The expected results. + * @throws Exception Occurred Exception. + */ + protected void doTruthValueEvaluationTest( + SymbolicExecutionEnvironment env, + ExpectedTruthValueEvaluationResult... expectedResults) throws Exception { + // Compute current results + List currentResults = new LinkedList<>(); + ExecutionNodePreorderIterator iter = + new ExecutionNodePreorderIterator(env.getBuilder().getStartNode()); + while (iter.hasNext()) { + IExecutionNode next = iter.next(); + Node nodeToEvaluate; + if (next instanceof IExecutionTermination) { + nodeToEvaluate = next.getProofNode(); + } else if (next instanceof IExecutionOperationContract) { + nodeToEvaluate = next.getProofNode().child(2); // Precondition branch + } else if (next instanceof IExecutionLoopInvariant) { + nodeToEvaluate = next.getProofNode().child(0); // Initial + } else if (next instanceof IExecutionAuxiliaryContract) { + nodeToEvaluate = next.getProofNode().child(1); // Precondition branch + } else if (next instanceof IExecutionJoin) { + nodeToEvaluate = next.getProofNode().child(0); // Weakening branch + } else { + nodeToEvaluate = null; + } + if (nodeToEvaluate != null) { + TruthValueTracingResult result = TruthValueTracingUtil.evaluate(nodeToEvaluate, + FormulaTermLabel.NAME, false, false); + currentResults.add(result); + if (CREATE_NEW_ORACLE_FILES_IN_TEMP_DIRECTORY) { + LOGGER.info("Found Result: {}", result); + } + } + } + // Compare results + assertResults(expectedResults, currentResults); + } + + /** + * Asserts the results. + * + * @param expected The expected results. + * @param current The current results. + */ + protected void assertResults(ExpectedTruthValueEvaluationResult[] expected, + List current) { + Assertions.assertEquals(expected.length, current.size()); + int i = 0; + Iterator currentIter = current.iterator(); + while (i < expected.length && currentIter.hasNext()) { + assertTruthValueResults(expected[i], currentIter.next()); + i++; + } + Assertions.assertEquals(expected.length, i); + Assertions.assertFalse(currentIter.hasNext()); + } + + /** + * Asserts the truth value results. + * + * @param expected The expected results. + * @param current The current results. + */ + protected void assertTruthValueResults(ExpectedTruthValueEvaluationResult expected, + TruthValueTracingResult current) { + BranchResult[] currentResults = current.getBranchResults(); + Assertions.assertEquals(expected.branchResults.length, currentResults.length); + for (int i = 0; i < currentResults.length; i++) { + assertBranchResult(expected.branchResults[i], currentResults[i]); + } + } + + /** + * Asserts the branch results. + * + * @param expected The expected results. + * @param current The current results. + */ + protected void assertBranchResult(ExpectedBranchResult expected, BranchResult current) { + Map currentResults = current.getResults(); + Assertions.assertTrue(expected.labelResults.size() <= currentResults.size(), + "To many expected results at goal " + current.getLeafNode().serialNr()); + for (Entry expectedEntry : expected.labelResults.entrySet()) { + MultiEvaluationResult currentInstruction = currentResults.get(expectedEntry.getKey()); + assertNotNull(currentInstruction, "Current result of " + expectedEntry.getKey() + + " is missing at goal " + current.getLeafNode().serialNr() + "."); + TruthValue currentResult = + currentInstruction.evaluate(current.getTermLabelName(), currentResults); + TruthValue expectedValue = expectedEntry.getValue(); + if (expectedValue == null) { + Assertions.assertNull(currentResult); + } else { + assertNotNull(currentResult, "Current result of " + expectedEntry.getKey() + + " at goal " + current.getLeafNode().serialNr() + " is not available."); + Assertions.assertEquals(expectedValue, currentResult, + "Wrong truth value of " + expectedEntry.getKey() + " at goal " + + current.getLeafNode().serialNr() + "."); + } + } + } + + /** + * Represents an expected evaluation result. + * + * @author Martin Hentschel + */ + protected static class ExpectedTruthValueEvaluationResult { + /** + * The expected branches. + */ + private final ExpectedBranchResult[] branchResults; + + /** + * Constructor. + * + * @param branchResults The expected branches. + */ + public ExpectedTruthValueEvaluationResult(ExpectedBranchResult... branchResults) { + this.branchResults = branchResults; + } + } - /** - * Asserts the branch results. - * @param expected The expected results. - * @param current The current results. - */ - protected void assertBranchResult(ExpectedBranchResult expected, BranchResult current) { - Map currentResults = current.getResults(); - Assertions.assertTrue(expected.labelResults.size() <= currentResults.size(), "To many expected results at goal " + current.getLeafNode().serialNr()); - for (Entry expectedEntry : expected.labelResults.entrySet()) { - MultiEvaluationResult currentInstruction = currentResults.get(expectedEntry.getKey()); - assertNotNull(currentInstruction, "Current result of " + expectedEntry.getKey() + " is missing at goal " + current.getLeafNode().serialNr() + "."); - TruthValue currentResult = currentInstruction.evaluate(current.getTermLabelName(), currentResults); - TruthValue expectedValue = expectedEntry.getValue(); - if (expectedValue == null) { - Assertions.assertNull(currentResult); - } - else { - assertNotNull(currentResult, "Current result of " + expectedEntry.getKey() + " at goal " + current.getLeafNode().serialNr() + " is not available."); - Assertions.assertEquals(expectedValue, currentResult, "Wrong truth value of " + expectedEntry.getKey() + " at goal " + current.getLeafNode().serialNr() + "."); - } - } - } + /** + * Represents an expected branch result. + * + * @author Martin Hentschel + */ + protected static class ExpectedBranchResult { + /** + * The truth values of all labels. + */ + private final Map labelResults = new HashMap<>(); + + /** + * Constructor. + * + * @param labelResults The truth values of all labels. + */ + public ExpectedBranchResult(ExpectedTruthValueResult... labelResults) { + for (ExpectedTruthValueResult result : labelResults) { + this.labelResults.put(result.labelId, result.value); + } + } + } - /** - * Represents an expected evaluation result. - * @author Martin Hentschel - */ - protected static class ExpectedTruthValueEvaluationResult { - /** - * The expected branches. - */ - private final ExpectedBranchResult[] branchResults; + /** + * Represents an expected truth value result of a particular label ID. + * + * @author Martin Hentschel + */ + protected static class ExpectedTruthValueResult { + /** + * The label ID. + */ + private final String labelId; - /** - * Constructor. - * @param branchResults The expected branches. - */ - public ExpectedTruthValueEvaluationResult(ExpectedBranchResult... branchResults) { - this.branchResults = branchResults; - } - } - - /** - * Represents an expected branch result. - * @author Martin Hentschel - */ - protected static class ExpectedBranchResult { - /** - * The truth values of all labels. - */ - private final Map labelResults = new HashMap<>(); + /** + * The truth value. + */ + private final TruthValue value; - /** - * Constructor. - * @param labelResults The truth values of all labels. - */ - public ExpectedBranchResult(ExpectedTruthValueResult... labelResults) { - for (ExpectedTruthValueResult result : labelResults) { - this.labelResults.put(result.labelId, result.value); - } - } - } - - /** - * Represents an expected truth value result of a particular label ID. - * @author Martin Hentschel - */ - protected static class ExpectedTruthValueResult { - /** - * The label ID. - */ - private final String labelId; - - /** - * The truth value. - */ - private final TruthValue value; - - /** - * Constructor. - * @param labelId The label ID. - * @param value The truth value. - */ - public ExpectedTruthValueResult(String labelId, TruthValue value) { - this.labelId = labelId; - this.value = value; - } - } + /** + * Constructor. + * + * @param labelId The label ID. + * @param value The truth value. + */ + public ExpectedTruthValueResult(String labelId, TruthValue value) { + this.labelId = labelId; + this.value = value; + } + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueValue.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueValue.java index a26e7b5d2ef..95e3f827dca 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueValue.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/TestTruthValueValue.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase; import de.uka.ilkd.key.symbolic_execution.TruthValueTracingUtil.TruthValue; @@ -9,195 +12,249 @@ /** * Tests for {@link TruthValue}. + * * @author Martin Hentschel */ -public class TestTruthValueValue { - /** - * Tests {@link TruthValue#ifThenElse(TruthValue, TruthValue, TruthValue)}. - */ - @Test - public void testIfThenElse() { - // true - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, null)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, null)); - assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.TRUE)); - assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.FALSE)); - assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.UNKNOWN)); - assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, null)); - // false - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.UNKNOWN)); - assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, null)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.UNKNOWN)); - assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, null)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, null)); - assertEquals(TruthValue.TRUE, TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.UNKNOWN)); - assertNull(TruthValue.ifThenElse(TruthValue.FALSE, null, null)); - // unknown - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, null, null)); - // null - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.TRUE, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.FALSE, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.UNKNOWN, null)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, null)); - } - - /** - * Tests {@link TruthValue#eqv(TruthValue, TruthValue)}. - */ - @Test public void testEqv() { - // true - assertEquals(TruthValue.TRUE, TruthValue.eqv(TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.eqv(TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.TRUE, null)); - // false - assertEquals(TruthValue.FALSE, TruthValue.eqv(TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.TRUE, TruthValue.eqv(TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.FALSE, null)); - // unknown - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, null)); - // null - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, null)); - } - - /** - * Tests {@link TruthValue#and(TruthValue, TruthValue)}. - */ - @Test public void testAnd() { - // true - assertEquals(TruthValue.TRUE, TruthValue.and(TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.TRUE, null)); - // false - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, null)); - // unknown - assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, null)); - // null - assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.and(null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, null)); - } - - /** - * Tests {@link TruthValue#or(TruthValue, TruthValue)}. - */ - @Test public void testOr() { - // true - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, null)); - // false - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.or(TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.FALSE, null)); - // unknown - assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, null)); - // null - assertEquals(TruthValue.TRUE, TruthValue.or(null, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, null)); - } - - /** - * Tests {@link TruthValue#imp(TruthValue, TruthValue)}. - */ - @Test public void testImp() { - // true - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.TRUE, TruthValue.TRUE)); - assertEquals(TruthValue.FALSE, TruthValue.imp(TruthValue.TRUE, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.TRUE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.TRUE, null)); - // false - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.TRUE)); - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.FALSE)); - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.UNKNOWN)); - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, null)); - // unknown - assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, null)); - // null - assertEquals(TruthValue.TRUE, TruthValue.imp(null, TruthValue.TRUE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, null)); - } - - /** - * Tests {@link TruthValue#not(TruthValue)}. - */ - @Test public void testNot() { - assertEquals(TruthValue.FALSE, TruthValue.not(TruthValue.TRUE)); - assertEquals(TruthValue.TRUE, TruthValue.not(TruthValue.FALSE)); - assertEquals(TruthValue.UNKNOWN, TruthValue.not(TruthValue.UNKNOWN)); - assertEquals(TruthValue.UNKNOWN, TruthValue.not(null)); - } +public class TestTruthValueValue { + /** + * Tests {@link TruthValue#ifThenElse(TruthValue, TruthValue, TruthValue)}. + */ + @Test + public void testIfThenElse() { + // true + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.TRUE, null)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.FALSE, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.TRUE, TruthValue.UNKNOWN, null)); + assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.TRUE)); + assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.FALSE)); + assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, TruthValue.UNKNOWN)); + assertNull(TruthValue.ifThenElse(TruthValue.TRUE, null, null)); + // false + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, TruthValue.UNKNOWN)); + assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.TRUE, null)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, TruthValue.UNKNOWN)); + assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.FALSE, null)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertNull(TruthValue.ifThenElse(TruthValue.FALSE, TruthValue.UNKNOWN, null)); + assertEquals(TruthValue.TRUE, + TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, + TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.FALSE, null, TruthValue.UNKNOWN)); + assertNull(TruthValue.ifThenElse(TruthValue.FALSE, null, null)); + // unknown + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.TRUE, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.FALSE, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, TruthValue.UNKNOWN, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(TruthValue.UNKNOWN, null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(TruthValue.UNKNOWN, null, null)); + // null + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.TRUE, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.FALSE, null)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, + TruthValue.ifThenElse(null, TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, TruthValue.UNKNOWN, null)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.ifThenElse(null, null, null)); + } + + /** + * Tests {@link TruthValue#eqv(TruthValue, TruthValue)}. + */ + @Test + public void testEqv() { + // true + assertEquals(TruthValue.TRUE, TruthValue.eqv(TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.eqv(TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.TRUE, null)); + // false + assertEquals(TruthValue.FALSE, TruthValue.eqv(TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.TRUE, TruthValue.eqv(TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.FALSE, null)); + // unknown + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(TruthValue.UNKNOWN, null)); + // null + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.eqv(null, null)); + } + + /** + * Tests {@link TruthValue#and(TruthValue, TruthValue)}. + */ + @Test + public void testAnd() { + // true + assertEquals(TruthValue.TRUE, TruthValue.and(TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.TRUE, null)); + // false + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.FALSE, null)); + // unknown + assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.and(TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(TruthValue.UNKNOWN, null)); + // null + assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.and(null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.and(null, null)); + } + + /** + * Tests {@link TruthValue#or(TruthValue, TruthValue)}. + */ + @Test + public void testOr() { + // true + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.TRUE, null)); + // false + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.or(TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.FALSE, null)); + // unknown + assertEquals(TruthValue.TRUE, TruthValue.or(TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(TruthValue.UNKNOWN, null)); + // null + assertEquals(TruthValue.TRUE, TruthValue.or(null, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.or(null, null)); + } + + /** + * Tests {@link TruthValue#imp(TruthValue, TruthValue)}. + */ + @Test + public void testImp() { + // true + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.TRUE, TruthValue.TRUE)); + assertEquals(TruthValue.FALSE, TruthValue.imp(TruthValue.TRUE, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.TRUE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.TRUE, null)); + // false + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.TRUE)); + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.FALSE)); + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, TruthValue.UNKNOWN)); + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.FALSE, null)); + // unknown + assertEquals(TruthValue.TRUE, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(TruthValue.UNKNOWN, null)); + // null + assertEquals(TruthValue.TRUE, TruthValue.imp(null, TruthValue.TRUE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.imp(null, null)); + } + + /** + * Tests {@link TruthValue#not(TruthValue)}. + */ + @Test + public void testNot() { + assertEquals(TruthValue.FALSE, TruthValue.not(TruthValue.TRUE)); + assertEquals(TruthValue.TRUE, TruthValue.not(TruthValue.FALSE)); + assertEquals(TruthValue.UNKNOWN, TruthValue.not(TruthValue.UNKNOWN)); + assertEquals(TruthValue.UNKNOWN, TruthValue.not(null)); + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestFunctionalOperationContractPO.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestFunctionalOperationContractPO.java index 952cc32c551..dceaafc63ca 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestFunctionalOperationContractPO.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestFunctionalOperationContractPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.po; import java.io.IOException; @@ -19,50 +22,53 @@ /** * Tests the {@link FunctionalOperationContractPO} used for symbolic execution. + * * @author Martin Hentschel */ public class TestFunctionalOperationContractPO extends AbstractSymbolicExecutionTestCase { - /** - * Tests the contract of method {@code doubleValue}. - */ - @Test - public void testDoubleValue() throws Exception { - doTest("/set/existingContractTest/test/ExistingContractTest.java", - "ExistingContractTest[ExistingContractTest::doubleValue(int)].JML operation contract.0", - "/set/existingContractTest/oracle/ExistingContractTest.xml", - "{result_doubleValue=self.doubleValue(_value)@ExistingContractTest; }"); - } - - /** - * Executes the test steps of all contained test methods. - */ - protected void doTest(String javaPathInkeyRepDirectory, - String baseContractName, - String oraclePathInBaseDirFile, - String expectedTryContent) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - SymbolicExecutionEnvironment env = null; - try { - // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, baseContractName); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, baseContractName, false, false, false, false, false, false, false, false, false, false, false); - // Extract and test try content - String tryContent = getTryContent(env.getProof()); - if (!StringUtil.equalIgnoreWhiteSpace(expectedTryContent, tryContent)) { - Assertions.assertEquals(expectedTryContent, tryContent); - } - // Resume - resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); - // Test save and reload of the proof - assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, oraclePathInBaseDirFile, env); - } - finally { - // Restore taclet options - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file + /** + * Tests the contract of method {@code doubleValue}. + */ + @Test + public void testDoubleValue() throws Exception { + doTest("/set/existingContractTest/test/ExistingContractTest.java", + "ExistingContractTest[ExistingContractTest::doubleValue(int)].JML operation contract.0", + "/set/existingContractTest/oracle/ExistingContractTest.xml", + "{result_doubleValue=self.doubleValue(_value)@ExistingContractTest; }"); + } + + /** + * Executes the test steps of all contained test methods. + */ + protected void doTest(String javaPathInkeyRepDirectory, String baseContractName, + String oraclePathInBaseDirFile, String expectedTryContent) throws ProofInputException, + IOException, ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + SymbolicExecutionEnvironment env = null; + try { + // Make sure that the correct taclet options are defined. + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, baseContractName); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + baseContractName, false, false, false, false, false, false, false, false, false, + false, false); + // Extract and test try content + String tryContent = getTryContent(env.getProof()); + if (!StringUtil.equalIgnoreWhiteSpace(expectedTryContent, tryContent)) { + Assertions.assertEquals(expectedTryContent, tryContent); + } + // Resume + resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); + // Test save and reload of the proof + assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, + oraclePathInBaseDirFile, env); + } finally { + // Restore taclet options + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodPO.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodPO.java index 6f0d8b90c9b..eb6a64861bc 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodPO.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.po; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -28,8 +31,7 @@ public class TestProgramMethodPO extends AbstractSymbolicExecutionTestCase { @Test public void testComplicatedInnerMethod() throws Exception { doTest("/set/fullqualifiedTypeNamesTest/test/my/packageName/TheClass.java", - "my.packageName.TheClass.TheInnerClass", - "complicatedInnerMethod", + "my.packageName.TheClass.TheInnerClass", "complicatedInnerMethod", "/set/fullqualifiedTypeNamesTest/oracle/TheInnerClass_complicatedInnerMethod.xml", null, "{result_complicatedInnerMethod=self.complicatedInnerMethod(z,a,b,x,o,ac)@my.packageName.TheClass.TheInnerClass; }"); @@ -41,8 +43,7 @@ public void testComplicatedInnerMethod() throws Exception { @Test public void testComplicatedMethod_Precondition() throws Exception { doTest("/set/fullqualifiedTypeNamesTest/test/my/packageName/TheClass.java", - "my.packageName.TheClass", - "complicatedMethod", + "my.packageName.TheClass", "complicatedMethod", "/set/fullqualifiedTypeNamesTest/oracle/TheClass_complicatedMethod.xml", "a == 2 && b && x != null && \"Hello\" == x", "{result_complicatedMethod=self.complicatedMethod(i,a,b,x,o,ac,acArray)@my.packageName.TheClass; }"); @@ -52,13 +53,11 @@ public void testComplicatedMethod_Precondition() throws Exception { * Tests {@code complicatedMethod} without precondition. */ @Test - public void testComplicatedMethod() throws IOException, ProofInputException, ParserConfigurationException, - SAXException, ProblemLoaderException { + public void testComplicatedMethod() throws IOException, ProofInputException, + ParserConfigurationException, SAXException, ProblemLoaderException { doTest("/set/fullqualifiedTypeNamesTest/test/my/packageName/TheClass.java", - "my.packageName.TheClass", - "complicatedMethod", - "/set/fullqualifiedTypeNamesTest/oracle/TheClass_complicatedMethod.xml", - null, + "my.packageName.TheClass", "complicatedMethod", + "/set/fullqualifiedTypeNamesTest/oracle/TheClass_complicatedMethod.xml", null, "{result_complicatedMethod=self.complicatedMethod(i,a,b,x,o,ac,acArray)@my.packageName.TheClass; }"); } @@ -66,11 +65,9 @@ public void testComplicatedMethod() throws IOException, ProofInputException, Par * Tests {@code returnMethod} with precondition. */ @Test - public void testReturnMethod_Precondition() throws IOException, ProofInputException, ParserConfigurationException, - SAXException, ProblemLoaderException { - doTest("/set/methodPOTest/test/MethodPOTest.java", - "MethodPOTest", - "returnMethod", + public void testReturnMethod_Precondition() throws IOException, ProofInputException, + ParserConfigurationException, SAXException, ProblemLoaderException { + doTest("/set/methodPOTest/test/MethodPOTest.java", "MethodPOTest", "returnMethod", "/set/methodPOTest/oracle/MethodPOTest_returnMethod_ParamNotNull.xml", "param != null", "{result_returnMethod=MethodPOTest.returnMethod(param)@MethodPOTest; }"); @@ -80,13 +77,10 @@ public void testReturnMethod_Precondition() throws IOException, ProofInputExcept * Tests {@code returnMethod} without precondition. */ @Test - public void testReturnMethod() throws IOException, ProofInputException, ParserConfigurationException, - SAXException, ProblemLoaderException { - doTest("/set/methodPOTest/test/MethodPOTest.java", - "MethodPOTest", - "returnMethod", - "/set/methodPOTest/oracle/MethodPOTest_returnMethod.xml", - null, + public void testReturnMethod() throws IOException, ProofInputException, + ParserConfigurationException, SAXException, ProblemLoaderException { + doTest("/set/methodPOTest/test/MethodPOTest.java", "MethodPOTest", "returnMethod", + "/set/methodPOTest/oracle/MethodPOTest_returnMethod.xml", null, "{result_returnMethod=MethodPOTest.returnMethod(param)@MethodPOTest; }"); } @@ -95,12 +89,9 @@ public void testReturnMethod() throws IOException, ProofInputException, ParserCo */ @Test public void testVoidMethod_Precondition() throws Exception { - doTest("/set/methodPOTest/test/MethodPOTest.java", - "MethodPOTest", - "voidMethod", + doTest("/set/methodPOTest/test/MethodPOTest.java", "MethodPOTest", "voidMethod", "/set/methodPOTest/oracle/MethodPOTest_voidMethod_ParamNotNull.xml", - "param != null", - "{MethodPOTest.voidMethod(param)@MethodPOTest; }"); + "param != null", "{MethodPOTest.voidMethod(param)@MethodPOTest; }"); } /** @@ -108,39 +99,39 @@ public void testVoidMethod_Precondition() throws Exception { */ @Test public void testVoidMethod() throws Exception { - doTest("/set/methodPOTest/test/MethodPOTest.java", - "MethodPOTest", - "voidMethod", - "/set/methodPOTest/oracle/MethodPOTest_voidMethod.xml", - null, + doTest("/set/methodPOTest/test/MethodPOTest.java", "MethodPOTest", "voidMethod", + "/set/methodPOTest/oracle/MethodPOTest_voidMethod.xml", null, "{MethodPOTest.voidMethod(param)@MethodPOTest; }"); } /** * Executes the test steps of all contained test methods. */ - protected void doTest(String javaPathInkeyRepDirectory, - String containerTypeName, - String methodFullName, - String oraclePathInBaseDirFile, - String precondition, - String expectedTryContent) throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { + protected void doTest(String javaPathInkeyRepDirectory, String containerTypeName, + String methodFullName, String oraclePathInBaseDirFile, String precondition, + String expectedTryContent) throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { HashMap originalTacletOptions = null; SymbolicExecutionEnvironment env = null; boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); try { // Make sure that the correct taclet options are defined. - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); setOneStepSimplificationEnabled(null, true); // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, precondition, false, false, false, false, false, false, false, false, false, true); + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, precondition, false, false, false, false, + false, false, false, false, false, true); // Extract and test try content String tryContent = getTryContent(env.getProof()); - assertTrue(StringUtil.equalIgnoreWhiteSpace(expectedTryContent, tryContent), "Expected \"" + expectedTryContent + "\" but is \"" + tryContent + "\"."); + assertTrue(StringUtil.equalIgnoreWhiteSpace(expectedTryContent, tryContent), + "Expected \"" + expectedTryContent + "\" but is \"" + tryContent + "\"."); // Resume resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); // Test save and reload of the proof - assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, oraclePathInBaseDirFile, env); + assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, + oraclePathInBaseDirFile, env); } finally { // Restore original options setOneStepSimplificationEnabled(null, originalOneStepSimplification); @@ -150,4 +141,4 @@ protected void doTest(String javaPathInkeyRepDirectory, } } } -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodSubsetPO.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodSubsetPO.java index 47265b01178..412ed89b275 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodSubsetPO.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/po/TestProgramMethodSubsetPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.po; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -21,13 +24,10 @@ public class TestProgramMethodSubsetPO extends AbstractSymbolicExecutionTestCase */ @Test public void testDoSomethingElseBranch() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", - "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_elsebranch.xml", - null, - new Position(24, 27), - new Position(25, 33), + "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_elsebranch.xml", null, + new Position(24, 27), new Position(25, 33), "{method-frame(result->result_doSomething, source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x-=42;return x; } }"); } @@ -36,118 +36,96 @@ public void testDoSomethingElseBranch() throws Exception { */ @Test public void testDoSomethingIfBranch() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", - "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_ifbranch.xml", - null, - new Position(20, 27), - new Position(21, 31), + "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_ifbranch.xml", null, + new Position(20, 27), new Position(21, 31), "{method-frame(source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x=x*-1; x+=2; } }"); } /** - * Tests {@code {method-frame(source=doSomething(int, String, boolean)@MethodPartPOTest,this=self): {if (asdf<0) { - * x=x*-1; - * x+=2; - * }else { - * x-=42;return x; - * } - * } - * }} of {@code doSomething} with precondition. + * Tests + * {@code {method-frame(source=doSomething(int, String, boolean)@MethodPartPOTest,this=self): {if (asdf<0) + * { x=x*-1; x+=2; }else { x-=42;return x; } } }} of {@code doSomething} with precondition. */ @Test public void testDoSomethingIf() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", - "doSomething", - "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_if.xml", - null, - new Position(19, 17), - new Position(26, 17), + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", + "doSomething", "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_if.xml", + null, new Position(19, 17), new Position(26, 17), "{method-frame(source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): {if (asdf<0) { x=x*-1; x+=2; }else { x-=42;return x; } } }"); } /** - * Tests {@code {method-frame(source=doSomething(int, String, boolean)@MethodPartPOTest,this=self): {int x = 0;if (asdf<0) { - * x=x*-1; - * x+=2; - * }else { - * x-=42;return x; - * } - * x=1*asdf; - * } - * }} of {@code doSomething} with precondition. + * Tests + * {@code {method-frame(source=doSomething(int, String, boolean)@MethodPartPOTest,this=self): {int x = 0;if (asdf<0) + * { x=x*-1; x+=2; }else { x-=42;return x; } x=1*asdf; } }} of {@code doSomething} with + * precondition. */ @Test public void testDoSomethingIfWithSurroundingStatements() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_if_surroundingStatements.xml", - null, - new Position(17, 63), - new Position(27, 29), + null, new Position(17, 63), new Position(27, 29), "{method-frame(source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): {int x = 0;if (asdf<0) { x=x*-1; x+=2; }else { x-=42;return x; } x=1*asdf; } }"); } /** - * Tests {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; return z;} of {@code doSomething} with precondition. + * Tests + * {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; return z;} + * of {@code doSomething} with precondition. */ @Test public void testDoSomethingWithReturn_Precondition() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_withReturn_precondition.xml", - "x == 1 && asdf == 2 && this.field == 3", - new Position(27, 19), + "x == 1 && asdf == 2 && this.field == 3", new Position(27, 19), new Position(31, 25), "{method-frame(result->result_doSomething, source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x=1*asdf;int y = 2+MethodPartPOTest.CONSTANT+this.field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;return z; } }"); } /** - * Tests {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; return z;} of {@code doSomething} without precondition. + * Tests + * {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; return z;} + * of {@code doSomething} without precondition. */ @Test public void testDoSomethingWithReturn() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", - "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_withReturn.xml", - null, - new Position(27, 19), - new Position(31, 25), + "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_withReturn.xml", null, + new Position(27, 19), new Position(31, 25), "{method-frame(result->result_doSomething, source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x=1*asdf;int y = 2+MethodPartPOTest.CONSTANT+this.field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;return z; } }"); } /** - * Tests {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;} of {@code doSomething} with precondition. + * Tests + * {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;} + * of {@code doSomething} with precondition. */ @Test public void testDoSomethingNoReturn_Precondition() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_noReturn_precondition.xml", - "x == 1 && asdf == 2 && this.field == 3", - new Position(27, 19), + "x == 1 && asdf == 2 && this.field == 3", new Position(27, 19), new Position(30, 44), "{method-frame(source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x=1*asdf;int y = 2+MethodPartPOTest.CONSTANT+this.field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; } }"); } /** - * Tests {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;} of {@code doSomething} without precondition. + * Tests + * {@code x=1*asdf;int y = 2+CONSTANT+field;int doubleValue = doubleValue(x);int z = x+y+doubleValue;} + * of {@code doSomething} without precondition. */ @Test public void testDoSomethingNoReturn() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "doSomething", - "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_noReturn.xml", - null, - new Position(27, 19), - new Position(30, 44), + "/set/methodPartPOTest/oracle/MethodPartPOTest_doSomething_noReturn.xml", null, + new Position(27, 19), new Position(30, 44), "{method-frame(source=doSomething(int, java.lang.String, boolean)@MethodPartPOTest,this=self): { x=1*asdf;int y = 2+MethodPartPOTest.CONSTANT+this.field;int doubleValue = doubleValue(x);int z = x+y+doubleValue; } }"); } @@ -156,13 +134,9 @@ public void testDoSomethingNoReturn() throws Exception { */ @Test public void testVoidMethodWithReturn_Precondition() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", - "voidMethod", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "voidMethod", "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_withReturn_precondition.xml", - "y == -2", - new Position(11, 22), - new Position(13, 31), + "y == -2", new Position(11, 22), new Position(13, 31), "{method-frame(source=voidMethod(boolean, int)@MethodPartPOTest,this=self): {int b = 3*y;return ; } }"); } @@ -171,13 +145,9 @@ public void testVoidMethodWithReturn_Precondition() throws Exception { */ @Test public void testVoidMethodWithReturn() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", - "voidMethod", - "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_withReturn.xml", - null, - new Position(11, 22), - new Position(13, 31), + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "voidMethod", + "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_withReturn.xml", null, + new Position(11, 22), new Position(13, 31), "{method-frame(source=voidMethod(boolean, int)@MethodPartPOTest,this=self): {int b = 3*y;return ; } }"); } @@ -186,13 +156,9 @@ public void testVoidMethodWithReturn() throws Exception { */ @Test public void testVoidMethodNoReturn_Precondition() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", - "voidMethod", + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "voidMethod", "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_noReturn_precondition.xml", - "y == 2", - new Position(8, 24), - new Position(9, 38), + "y == 2", new Position(8, 24), new Position(9, 38), "{method-frame(source=voidMethod(boolean, int)@MethodPartPOTest,this=self): {int a = 2*y; } }"); } @@ -201,34 +167,24 @@ public void testVoidMethodNoReturn_Precondition() throws Exception { */ @Test public void testVoidMethodNoReturn() throws Exception { - doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", - "MethodPartPOTest", - "voidMethod", - "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_noReturn.xml", - null, - new Position(8, 24), - new Position(9, 38), + doTest("/set/methodPartPOTest/test/MethodPartPOTest.java", "MethodPartPOTest", "voidMethod", + "/set/methodPartPOTest/oracle/MethodPartPOTest_voidMethod_noReturn.xml", null, + new Position(8, 24), new Position(9, 38), "{method-frame(source=voidMethod(boolean, int)@MethodPartPOTest,this=self): {int a = 2*y; } }"); } /** * Executes the test steps of all contained test methods. */ - protected void doTest(String javaPathInkeyRepDirectory, - String containerTypeName, - String methodFullName, - String oraclePathInBaseDirFile, - String precondition, - Position startPosition, - Position endPosition, - String expectedTryContent) throws Exception { + protected void doTest(String javaPathInkeyRepDirectory, String containerTypeName, + String methodFullName, String oraclePathInBaseDirFile, String precondition, + Position startPosition, Position endPosition, String expectedTryContent) + throws Exception { // Create proof environment for symbolic execution - SymbolicExecutionEnvironment env - = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, - methodFullName, precondition, startPosition, endPosition, false, - false, false, false, - false, false, false, - false, false, true); + SymbolicExecutionEnvironment env = + createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, precondition, startPosition, endPosition, + false, false, false, false, false, false, false, false, false, true); try { // Extract and test try content String tryContent = getTryContent(env.getProof()); @@ -237,9 +193,10 @@ protected void doTest(String javaPathInkeyRepDirectory, // Resume resume(env.getUi(), env.getBuilder(), oraclePathInBaseDirFile, testCaseDirectory); // Test save and reload of the proof - assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, oraclePathInBaseDirFile, env); + assertSaveAndReload(testCaseDirectory, javaPathInkeyRepDirectory, + oraclePathInBaseDirFile, env); } finally { env.dispose(); } } -} \ No newline at end of file +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/slicing/TestThinBackwardSlicer.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/slicing/TestThinBackwardSlicer.java index 790bd527e1e..f64075797c8 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/slicing/TestThinBackwardSlicer.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/slicing/TestThinBackwardSlicer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.slicing; import de.uka.ilkd.key.control.KeYEnvironment; @@ -34,863 +37,893 @@ /** * Tests for {@link ThinBackwardSlicer}. + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) public class TestThinBackwardSlicer extends AbstractSymbolicExecutionTestCase { - /** - * Flag to print found slices in the console. - */ - public static final boolean PRINT_SLICE = false; - private static final Logger LOGGER = LoggerFactory.getLogger(TestThinBackwardSlicer.class); - - /** - * Tests slicing on the example {@code blockContractAssignableLocationNotRequested}. - * @throws Exception Occurred Exception. - */ - @Test - public void testBlockContractAssignableLocationNotRequested() throws Exception { - doSlicingTest("/slicing/blockContractAssignableLocationNotRequested/BlockContractAssignableLocationNotRequested.proof", - new ReturnSelector(122), - true, - 109, - 14, - 12); - } - - /** - * Tests slicing on the example {@code blockContractAssignableRequestedLocation}. - * @throws Exception Occurred Exception. - */ - @Test public void testBlockContractAssignableRequestedLocation() throws Exception { - doSlicingTest("/slicing/blockContractAssignableRequestedLocation/BlockContractAssignableRequestedLocation.proof", - new ReturnSelector(111), - true, - 23); - } - - /** - * Tests slicing on the example {@code blockContractAssignableEverything}. - * @throws Exception Occurred Exception. - */ - @Test public void testBlockContractAssignableEverything() throws Exception { - doSlicingTest("/slicing/blockContractAssignableEverything/BlockContractAssignableEverything.proof", - new ReturnSelector(97), - true, - 23); - } - - /** - * Tests slicing on the example {@code methodContractAssignableLocationNotRequested}. - * @throws Exception Occurred Exception. - */ - @Test public void testMethodContractAssignableLocationNotRequested() throws Exception { - doSlicingTest("/slicing/methodContractAssignableLocationNotRequested/MethodContractAssignableLocationNotRequested.proof", - new ReturnSelector(29), - true, - 14, - 12); - } - - /** - * Tests slicing on the example {@code methodContractAssignableRequestedLocation}. - * @throws Exception Occurred Exception. - */ - @Test public void testMethodContractAssignableRequestedLocation() throws Exception { - doSlicingTest("/slicing/methodContractAssignableRequestedLocation/MethodContractAssignableRequestedLocation.proof", - new ReturnSelector(29), - true, - 23); - } - - /** - * Tests slicing on the example {@code methodContractAssignableEverything}. - * @throws Exception Occurred Exception. - */ - @Test public void testMethodContractAssignableEverything() throws Exception { - doSlicingTest("/slicing/methodContractAssignableEverything/MethodContractAssignableExample.proof", - new ReturnSelector(29), - true, - 23); - } - - /** - * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index {@code 0}. - * @throws Exception Occurred Exception. - */ - @Test public void testEquivalenceClasses_Index_1_no_OSS() throws Exception { - doSlicingTest("/slicing/equivalenceClassesTest/Example_NoOSS.proof", - new ReturnSelector(55), - new EquivalenceClassByIndexSelector(1), // [Equivalence Class [a,b]] - true, - 38); - } - - /** - * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index {@code 0}. - * @throws Exception Occurred Exception. - */ - @Test public void testEquivalenceClasses_Index_0_no_OSS() throws Exception { - doSlicingTest("/slicing/equivalenceClassesTest/Example_NoOSS.proof", - new ReturnSelector(55 ), - new EquivalenceClassByIndexSelector(0), // [] - true, - 24); - } - - /** - * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index {@code 0}. - * @throws Exception Occurred Exception. - */ - @Test public void testEquivalenceClasses_Index_1() throws Exception { - doSlicingTest("/slicing/equivalenceClassesTest/Example.proof", - new ReturnSelector(27), - new EquivalenceClassByIndexSelector(1), // [Equivalence Class [a,b]] - true, - 22); - } - - /** - * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index {@code 0}. - * @throws Exception Occurred Exception. - */ - @Test public void testEquivalenceClasses_Index_0() throws Exception { - doSlicingTest("/slicing/equivalenceClassesTest/Example.proof", - new ReturnSelector(27), - new EquivalenceClassByIndexSelector(0), // [] - true, - 17); - } - - /** - * Tests slicing on the example {@code aliasedByExecutionTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testAliasedByExecutionTest() throws Exception { - doSlicingTest("/slicing/aliasedByExecutionTest/AliasedByExecution.proof", - new ReturnSelector(41), - true, - 31); - } - - /** - * Tests slicing on the example {@code aliasedByExecutionTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testNotAliasedByExecutionTest() throws Exception { - doSlicingTest("/slicing/aliasedByExecutionTest/AliasedByExecution.proof", - new ReturnSelector(72), - true, - 17); - } - - /** - * Tests slicing on the example {@code loopInvariantNestedListFieldsTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testLoopInvariantNestedListFieldsTest() throws Exception { - doSlicingTest("/slicing/loopInvariantNestedListFieldsTest/LoopInvariantNestedListFieldsTest.proof", - new ReturnSelector(424), - true, - 67); - } - - /** - * Tests slicing on the example {@code loopInvariantNotInListFieldsTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testLoopInvariantNotInListFieldsTest() throws Exception { - doSlicingTest("/slicing/loopInvariantNotInListFieldsTest/LoopInvariantNotInListFieldsTest.proof", - new ReturnSelector(278), - true, - 13); - } - - /** - * Tests slicing on the example {@code loopInvariantInListFieldsTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testLoopInvariantInListFieldsTest() throws Exception { - doSlicingTest("/slicing/loopInvariantInListFieldsTest/LoopInvariantInListFieldsTest.proof", - new ReturnSelector(278), - true, - 15); - } - - /** - * Tests slicing on the example {@code loopInvariantStarFieldsTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testLoopInvariantStarFieldsTest() throws Exception { - doSlicingTest("/slicing/loopInvariantStarFieldsTest/LoopInvariantStarFieldsTest.proof", - new ReturnSelector(229), - true, - 13); - } - - /** - * Tests slicing on the example {@code simpleStaticLoopInvariantTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleStaticLoopInvariantTest() throws Exception { - doSlicingTest("/slicing/simpleStaticLoopInvariantTest/SimpleStatiLoopInvariantTest.proof", - new ReturnSelector(224), - true, - 12); - } - - /** - * Tests slicing on the example {@code simpleLoopInvariantTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLoopInvariantTest() throws Exception { - doSlicingTest("/slicing/simpleLoopInvariantTest/SimpleLoopInvariantTest.proof", - new ReturnSelector(125), - true, - 9); - } - - /** - * Tests slicing on the example {@code arrayIndexAsVariableFieldTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexAsVariableFieldTest() throws Exception { - doSlicingTest("/slicing/arrayIndexAsVariableFieldTest/ArrayIndexAsVariableFieldTest.proof", - new ReturnSelector(412), - true, - 408, 397, 315, 256, 148); - } - - /** - * Tests slicing on the example {@code arrayIndexVariableTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexVariableTest() throws Exception { - doSlicingTest("/slicing/arrayIndexVariableTest/ArrayIndexVariableTest.proof", - new ReturnSelector(347), - true, - 343, 332, 258, 211, 118); - } - - /** - * Tests slicing on the example {@code arrayIndexSideeffectsBevore}. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexSideeffectsBevore() throws Exception { - doSlicingTest("/slicing/arrayIndexSideeffectsBevore/ArrayIndexSideeffectsBevore.proof", - new ReturnSelector(211), - true, - 148, 55); - } - - /** - * Tests slicing on the example {@code arrayIndexSideeffectsAfter}. - * @throws Exception Occurred Exception. - */ - @Test public void testArrayIndexSideeffectsAfter() throws Exception { - doSlicingTest("/slicing/arrayIndexSideeffectsAfter/ArrayIndexSideeffectsAfter.proof", - new ReturnSelector(216), - true, - 163, 59); - } - - /** - * Tests slicing on the example {@code simpleMultidimensionArrayTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleMultidimensionArrayTest() throws Exception { - doSlicingTest("/slicing/simpleMultidimensionArrayTest/SimpleMultidimensionArrayTest.proof", - new ReturnSelector(456), - true, - 440, 436, 411, 348, 172, 133); - } - - /** - * Tests slicing on the example {@code simpleArrayTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleArrayTest() throws Exception { - doSlicingTest("/slicing/simpleArrayTest/SimpleArrayTest.proof", - new ReturnSelector(163), - false, - 143, 36, 21); - } - - /** - * Tests slicing on the example {@code figure2Param}. - * @throws Exception Occurred Exception. - */ - @Test public void testFigure2Param_right() throws Exception { - doSlicingTest("/slicing/figure2Param/Figure2Param.proof", - new RightAssignmentSelector(165), - true, - 151, 85); - } - - /** - * Tests slicing on the example {@code figure2Local}. - * @throws Exception Occurred Exception. - */ - @Test public void testFigure2Local_right() throws Exception { - doSlicingTest("/slicing/figure2Local/Figure2Local.proof", - new RightVariableDeclarationSelector(168), - true, - 154, 86); - } - - /** - * Tests slicing on the example {@code figure2Instance}. - * @throws Exception Occurred Exception. - */ - @Test public void testFigure2Instance_right() throws Exception { - doSlicingTest("/slicing/figure2Instance/Figure2Instance.proof", - new RightAssignmentSelector(267), - true, - 229, 182, 180, 165, 161, 144, 99); - } - - /** - * Tests slicing on the example {@code valueChange}. - * @throws Exception Occurred Exception. - */ - @Test public void testValueChange() throws Exception { - doSlicingTest("/slicing/valueChange/ValueChange.proof", - new ReturnSelector(88), - true, - 84, 72, 56, 52,26); - } - - /** - * Tests slicing on the example {@code readWriteTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testReadWriteTest() throws Exception { - doSlicingTest("/slicing/readWriteTest/ReadWriteTest.proof", - new ReturnSelector(40), - true, - 36, 29, 21, 11); - } - - /** - * Tests slicing on the example {@code aliasChanged}. - * @throws Exception Occurred Exception. - */ - @Test public void testAliasChanged() throws Exception { - doSlicingTest("/slicing/aliasChanged/AliasChanged.proof", - new ReturnSelector(203), - false, - 198, 194, 86, 57); - } - - /** - * Tests slicing on the example {@code aliasNotAvailable}. - * @throws Exception Occurred Exception. - */ - @Test public void testAliasNotAvailable() throws Exception { - doSlicingTest("/slicing/aliasNotAvailable/AliasNotAvailable.proof", - new ReturnSelector(178), - false, - 173, 169, 98, 77); - } - - /** - * Tests slicing on the example {@code intEndTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testIntEndTest() throws Exception { - doSlicingTest("/slicing/intEndTest/IntEndTest.proof", - new ReturnSelector(17), - false, - 13, 11); - } - - /** - * Tests slicing on the example {@code simpleAliasChanged}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleAliasChanged() throws Exception { - doSlicingTest("/slicing/simpleAliasChanged/SimpleAliasChanged.proof", - new ReturnSelector(36), - false, - 24); - } - - /** - * Tests slicing on the example {@code instanceFieldsAliased}. - * @throws Exception Occurred Exception. - */ - @Test public void testInstanceFieldsAliased() throws Exception { - doSlicingTest("/slicing/instanceFieldsAliased/InstanceFieldsAliased.proof", - new ReturnSelector(185), - false, - 180, 176, 68); - } - - /** - * Tests slicing on the example {@code nestedInstanceFields}. - * @throws Exception Occurred Exception. - */ - @Test public void testNestedInstanceFields() throws Exception { - doSlicingTest("/slicing/nestedInstanceFields/NestedInstanceFields.proof", - new ReturnSelector(142), - false, - 137, 133, 41, 27); - } - - /** - * Tests slicing on the example {@code methodCallTest}. - * @throws Exception Occurred Exception. - */ - @Test public void testMethodCallTest() throws Exception { - doSlicingTest("/slicing/methodCallTest/MethodCallTest.proof", - new ReturnSelector(138), - false, - 98, 39, 15); - } - - /** - * Tests slicing on the example {@code aliasing}. - * @throws Exception Occurred Exception. - */ - @Test public void testAliasing() throws Exception { - doSlicingTest("/slicing/aliasing/Aliasing.proof", - new ReturnSelector(62), - false, - 58, 20, 15); - } - - /** - * Tests slicing on the example {@code nestedInstanceAccess}. - * @throws Exception Occurred Exception. - */ - @Test public void testNestedInstanceAccess_subResult() throws Exception { - doSlicingTest("/slicing/nestedInstanceAccess/NestedInstanceAccess.proof", - new ReturnSelector(138), - false, - 136, 132, 127, 113, 86, 54, 39); - } - - /** - * Tests slicing on the example {@code figure2}. - * @throws Exception Occurred Exception. - */ - @Test public void testFigure2_right() throws Exception { - doSlicingTest("/slicing/figure2/Figure2.proof", - new RightAssignmentSelector(269), - false, - 229, 179); - } - - /** - * Tests slicing on the example {@code figure2}. - * @throws Exception Occurred Exception. - */ - @Test public void testFigure2_left() throws Exception { - doSlicingTest("/slicing/figure2/Figure2.proof", - new LeftAssignmentSelector(269), - false, - 269, 229, 179); - } - - /** - * Tests slicing on the example {@code simpleInstanceFields}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleInstanceFields() throws Exception { - doSlicingTest("/slicing/simpleInstanceFields/SimpleInstanceFields.proof", - new ReturnSelector(74), - false, - 69, 65, 18, 13); - } - - /** - * Tests slicing on the example {@code simpleThisInstanceFields}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleThisInstanceFields() throws Exception { - doSlicingTest("/slicing/simpleThisInstanceFields/SimpleThisInstanceFields.proof", - new ReturnSelector(48), - false, - 46, 42, 11, 9); - } - - /** - * Tests slicing on the example {@code simpleStaticFields}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleStaticFields() throws Exception { - doSlicingTest("/slicing/simpleStaticFields/SimpleStaticFields.proof", - new ReturnSelector(73), - false, - 59, 17, 10); - } - - /** - * Tests slicing on the example {@code simpleLocalVariables}. - * @throws Exception Occurred Exception. - */ - @Test public void testSimpleLocalVariables() throws Exception { - doSlicingTest("/slicing/simpleLocalVariables/SimpleLocalVariables.proof", - new ReturnSelector(23), - true, - 19, 11, 7); - } - - /** - * Performs a slicing test. - * @param proofFileInRepository The path to the proof file. - * @param selector The {@link ISeedLocationSelector} to use. - * @param fullSlize {@code true} if the he full slice is given as expected slice and {@code false} if only a part of the slice is given as expected slice. - * @param expectedSlice The serial IDs of the expected slices. - * @throws Exception Occurred Exception - */ - protected void doSlicingTest(String proofFileInRepository, - ISeedLocationSelector selector, - boolean fullSlize, - int... expectedSlice) throws Exception { - doSlicingTest(proofFileInRepository, - selector, - new NoEquivalenceClassSelector(), - fullSlize, - expectedSlice); - } - - /** - * Performs a slicing test. - * @param proofFileInRepository The path to the proof file. - * @param selector The {@link ISeedLocationSelector} to use. - * @param fullSlize {@code true} if the he full slice is given as expected slice and {@code false} if only a part of the slice is given as expected slice. - * @param expectedSlice The serial IDs of the expected slices. - * @throws Exception Occurred Exception - */ - protected void doSlicingTest(String proofFileInRepository, - ISeedLocationSelector selector, - IEquivalenceClassSelector eqSelector, - boolean fullSlize, - int... expectedSlice) throws Exception { - // Load proof - File proofFile = new File(testCaseDirectory, proofFileInRepository); - Assertions.assertTrue(proofFile.exists()); - KeYEnvironment environment = KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), proofFile, null, null, null, true); - try { - // Get loaded proof - Proof proof = environment.getLoadedProof(); - Assertions.assertNotNull(proof); - // Find seed - Pair seed = selector.findSeed(proof); - // Select equivalence class - Assertions.assertNotNull(eqSelector); - ImmutableList sec = eqSelector.selectEquivalenceClass(environment, proof, seed); - if (PRINT_SLICE) { - LOGGER.info("Equivalence Class: {}", sec); - } - // Perform slicing - ThinBackwardSlicer slicer = new ThinBackwardSlicer(); - ImmutableArray slices = slicer.slice(seed.first, seed.second, sec); - // Print slice if requested - if (PRINT_SLICE) { - LOGGER.info("Found Slices: {}", slices.size()); - for (Node slice : slices) { - LOGGER.info("SerialNr {}", slice.serialNr()); + /** + * Flag to print found slices in the console. + */ + public static final boolean PRINT_SLICE = false; + private static final Logger LOGGER = LoggerFactory.getLogger(TestThinBackwardSlicer.class); + + /** + * Tests slicing on the example {@code blockContractAssignableLocationNotRequested}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testBlockContractAssignableLocationNotRequested() throws Exception { + doSlicingTest( + "/slicing/blockContractAssignableLocationNotRequested/BlockContractAssignableLocationNotRequested.proof", + new ReturnSelector(122), true, 109, 14, 12); + } + + /** + * Tests slicing on the example {@code blockContractAssignableRequestedLocation}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testBlockContractAssignableRequestedLocation() throws Exception { + doSlicingTest( + "/slicing/blockContractAssignableRequestedLocation/BlockContractAssignableRequestedLocation.proof", + new ReturnSelector(111), true, 23); + } + + /** + * Tests slicing on the example {@code blockContractAssignableEverything}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testBlockContractAssignableEverything() throws Exception { + doSlicingTest( + "/slicing/blockContractAssignableEverything/BlockContractAssignableEverything.proof", + new ReturnSelector(97), true, 23); + } + + /** + * Tests slicing on the example {@code methodContractAssignableLocationNotRequested}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMethodContractAssignableLocationNotRequested() throws Exception { + doSlicingTest( + "/slicing/methodContractAssignableLocationNotRequested/MethodContractAssignableLocationNotRequested.proof", + new ReturnSelector(29), true, 14, 12); + } + + /** + * Tests slicing on the example {@code methodContractAssignableRequestedLocation}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMethodContractAssignableRequestedLocation() throws Exception { + doSlicingTest( + "/slicing/methodContractAssignableRequestedLocation/MethodContractAssignableRequestedLocation.proof", + new ReturnSelector(29), true, 23); + } + + /** + * Tests slicing on the example {@code methodContractAssignableEverything}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMethodContractAssignableEverything() throws Exception { + doSlicingTest( + "/slicing/methodContractAssignableEverything/MethodContractAssignableExample.proof", + new ReturnSelector(29), true, 23); + } + + /** + * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index + * {@code 0}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEquivalenceClasses_Index_1_no_OSS() throws Exception { + doSlicingTest("/slicing/equivalenceClassesTest/Example_NoOSS.proof", new ReturnSelector(55), + new EquivalenceClassByIndexSelector(1), // [Equivalence Class [a,b]] + true, 38); + } + + /** + * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index + * {@code 0}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEquivalenceClasses_Index_0_no_OSS() throws Exception { + doSlicingTest("/slicing/equivalenceClassesTest/Example_NoOSS.proof", new ReturnSelector(55), + new EquivalenceClassByIndexSelector(0), // [] + true, 24); + } + + /** + * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index + * {@code 0}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEquivalenceClasses_Index_1() throws Exception { + doSlicingTest("/slicing/equivalenceClassesTest/Example.proof", new ReturnSelector(27), + new EquivalenceClassByIndexSelector(1), // [Equivalence Class [a,b]] + true, 22); + } + + /** + * Tests slicing on the example {@code equivalenceClassesTest} with equivalence classes at index + * {@code 0}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testEquivalenceClasses_Index_0() throws Exception { + doSlicingTest("/slicing/equivalenceClassesTest/Example.proof", new ReturnSelector(27), + new EquivalenceClassByIndexSelector(0), // [] + true, 17); + } + + /** + * Tests slicing on the example {@code aliasedByExecutionTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testAliasedByExecutionTest() throws Exception { + doSlicingTest("/slicing/aliasedByExecutionTest/AliasedByExecution.proof", + new ReturnSelector(41), true, 31); + } + + /** + * Tests slicing on the example {@code aliasedByExecutionTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testNotAliasedByExecutionTest() throws Exception { + doSlicingTest("/slicing/aliasedByExecutionTest/AliasedByExecution.proof", + new ReturnSelector(72), true, 17); + } + + /** + * Tests slicing on the example {@code loopInvariantNestedListFieldsTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testLoopInvariantNestedListFieldsTest() throws Exception { + doSlicingTest( + "/slicing/loopInvariantNestedListFieldsTest/LoopInvariantNestedListFieldsTest.proof", + new ReturnSelector(424), true, 67); + } + + /** + * Tests slicing on the example {@code loopInvariantNotInListFieldsTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testLoopInvariantNotInListFieldsTest() throws Exception { + doSlicingTest( + "/slicing/loopInvariantNotInListFieldsTest/LoopInvariantNotInListFieldsTest.proof", + new ReturnSelector(278), true, 13); + } + + /** + * Tests slicing on the example {@code loopInvariantInListFieldsTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testLoopInvariantInListFieldsTest() throws Exception { + doSlicingTest("/slicing/loopInvariantInListFieldsTest/LoopInvariantInListFieldsTest.proof", + new ReturnSelector(278), true, 15); + } + + /** + * Tests slicing on the example {@code loopInvariantStarFieldsTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testLoopInvariantStarFieldsTest() throws Exception { + doSlicingTest("/slicing/loopInvariantStarFieldsTest/LoopInvariantStarFieldsTest.proof", + new ReturnSelector(229), true, 13); + } + + /** + * Tests slicing on the example {@code simpleStaticLoopInvariantTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleStaticLoopInvariantTest() throws Exception { + doSlicingTest("/slicing/simpleStaticLoopInvariantTest/SimpleStatiLoopInvariantTest.proof", + new ReturnSelector(224), true, 12); + } + + /** + * Tests slicing on the example {@code simpleLoopInvariantTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLoopInvariantTest() throws Exception { + doSlicingTest("/slicing/simpleLoopInvariantTest/SimpleLoopInvariantTest.proof", + new ReturnSelector(125), true, 9); + } + + /** + * Tests slicing on the example {@code arrayIndexAsVariableFieldTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexAsVariableFieldTest() throws Exception { + doSlicingTest("/slicing/arrayIndexAsVariableFieldTest/ArrayIndexAsVariableFieldTest.proof", + new ReturnSelector(412), true, 408, 397, 315, 256, 148); + } + + /** + * Tests slicing on the example {@code arrayIndexVariableTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexVariableTest() throws Exception { + doSlicingTest("/slicing/arrayIndexVariableTest/ArrayIndexVariableTest.proof", + new ReturnSelector(347), true, 343, 332, 258, 211, 118); + } + + /** + * Tests slicing on the example {@code arrayIndexSideeffectsBevore}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexSideeffectsBevore() throws Exception { + doSlicingTest("/slicing/arrayIndexSideeffectsBevore/ArrayIndexSideeffectsBevore.proof", + new ReturnSelector(211), true, 148, 55); + } + + /** + * Tests slicing on the example {@code arrayIndexSideeffectsAfter}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testArrayIndexSideeffectsAfter() throws Exception { + doSlicingTest("/slicing/arrayIndexSideeffectsAfter/ArrayIndexSideeffectsAfter.proof", + new ReturnSelector(216), true, 163, 59); + } + + /** + * Tests slicing on the example {@code simpleMultidimensionArrayTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleMultidimensionArrayTest() throws Exception { + doSlicingTest("/slicing/simpleMultidimensionArrayTest/SimpleMultidimensionArrayTest.proof", + new ReturnSelector(456), true, 440, 436, 411, 348, 172, 133); + } + + /** + * Tests slicing on the example {@code simpleArrayTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleArrayTest() throws Exception { + doSlicingTest("/slicing/simpleArrayTest/SimpleArrayTest.proof", new ReturnSelector(163), + false, 143, 36, 21); + } + + /** + * Tests slicing on the example {@code figure2Param}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testFigure2Param_right() throws Exception { + doSlicingTest("/slicing/figure2Param/Figure2Param.proof", new RightAssignmentSelector(165), + true, 151, 85); + } + + /** + * Tests slicing on the example {@code figure2Local}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testFigure2Local_right() throws Exception { + doSlicingTest("/slicing/figure2Local/Figure2Local.proof", + new RightVariableDeclarationSelector(168), true, 154, 86); + } + + /** + * Tests slicing on the example {@code figure2Instance}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testFigure2Instance_right() throws Exception { + doSlicingTest("/slicing/figure2Instance/Figure2Instance.proof", + new RightAssignmentSelector(267), true, 229, 182, 180, 165, 161, 144, 99); + } + + /** + * Tests slicing on the example {@code valueChange}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testValueChange() throws Exception { + doSlicingTest("/slicing/valueChange/ValueChange.proof", new ReturnSelector(88), true, 84, + 72, 56, 52, 26); + } + + /** + * Tests slicing on the example {@code readWriteTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testReadWriteTest() throws Exception { + doSlicingTest("/slicing/readWriteTest/ReadWriteTest.proof", new ReturnSelector(40), true, + 36, 29, 21, 11); + } + + /** + * Tests slicing on the example {@code aliasChanged}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testAliasChanged() throws Exception { + doSlicingTest("/slicing/aliasChanged/AliasChanged.proof", new ReturnSelector(203), false, + 198, 194, 86, 57); + } + + /** + * Tests slicing on the example {@code aliasNotAvailable}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testAliasNotAvailable() throws Exception { + doSlicingTest("/slicing/aliasNotAvailable/AliasNotAvailable.proof", new ReturnSelector(178), + false, 173, 169, 98, 77); + } + + /** + * Tests slicing on the example {@code intEndTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testIntEndTest() throws Exception { + doSlicingTest("/slicing/intEndTest/IntEndTest.proof", new ReturnSelector(17), false, 13, + 11); + } + + /** + * Tests slicing on the example {@code simpleAliasChanged}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleAliasChanged() throws Exception { + doSlicingTest("/slicing/simpleAliasChanged/SimpleAliasChanged.proof", + new ReturnSelector(36), false, 24); + } + + /** + * Tests slicing on the example {@code instanceFieldsAliased}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testInstanceFieldsAliased() throws Exception { + doSlicingTest("/slicing/instanceFieldsAliased/InstanceFieldsAliased.proof", + new ReturnSelector(185), false, 180, 176, 68); + } + + /** + * Tests slicing on the example {@code nestedInstanceFields}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testNestedInstanceFields() throws Exception { + doSlicingTest("/slicing/nestedInstanceFields/NestedInstanceFields.proof", + new ReturnSelector(142), false, 137, 133, 41, 27); + } + + /** + * Tests slicing on the example {@code methodCallTest}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testMethodCallTest() throws Exception { + doSlicingTest("/slicing/methodCallTest/MethodCallTest.proof", new ReturnSelector(138), + false, 98, 39, 15); + } + + /** + * Tests slicing on the example {@code aliasing}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testAliasing() throws Exception { + doSlicingTest("/slicing/aliasing/Aliasing.proof", new ReturnSelector(62), false, 58, 20, + 15); + } + + /** + * Tests slicing on the example {@code nestedInstanceAccess}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testNestedInstanceAccess_subResult() throws Exception { + doSlicingTest("/slicing/nestedInstanceAccess/NestedInstanceAccess.proof", + new ReturnSelector(138), false, 136, 132, 127, 113, 86, 54, 39); + } + + /** + * Tests slicing on the example {@code figure2}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testFigure2_right() throws Exception { + doSlicingTest("/slicing/figure2/Figure2.proof", new RightAssignmentSelector(269), false, + 229, 179); + } + + /** + * Tests slicing on the example {@code figure2}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testFigure2_left() throws Exception { + doSlicingTest("/slicing/figure2/Figure2.proof", new LeftAssignmentSelector(269), false, 269, + 229, 179); + } + + /** + * Tests slicing on the example {@code simpleInstanceFields}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleInstanceFields() throws Exception { + doSlicingTest("/slicing/simpleInstanceFields/SimpleInstanceFields.proof", + new ReturnSelector(74), false, 69, 65, 18, 13); + } + + /** + * Tests slicing on the example {@code simpleThisInstanceFields}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleThisInstanceFields() throws Exception { + doSlicingTest("/slicing/simpleThisInstanceFields/SimpleThisInstanceFields.proof", + new ReturnSelector(48), false, 46, 42, 11, 9); + } + + /** + * Tests slicing on the example {@code simpleStaticFields}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleStaticFields() throws Exception { + doSlicingTest("/slicing/simpleStaticFields/SimpleStaticFields.proof", + new ReturnSelector(73), false, 59, 17, 10); + } + + /** + * Tests slicing on the example {@code simpleLocalVariables}. + * + * @throws Exception Occurred Exception. + */ + @Test + public void testSimpleLocalVariables() throws Exception { + doSlicingTest("/slicing/simpleLocalVariables/SimpleLocalVariables.proof", + new ReturnSelector(23), true, 19, 11, 7); + } + + /** + * Performs a slicing test. + * + * @param proofFileInRepository The path to the proof file. + * @param selector The {@link ISeedLocationSelector} to use. + * @param fullSlize {@code true} if the he full slice is given as expected slice and + * {@code false} if only a part of the slice is given as expected slice. + * @param expectedSlice The serial IDs of the expected slices. + * @throws Exception Occurred Exception + */ + protected void doSlicingTest(String proofFileInRepository, ISeedLocationSelector selector, + boolean fullSlize, int... expectedSlice) throws Exception { + doSlicingTest(proofFileInRepository, selector, new NoEquivalenceClassSelector(), fullSlize, + expectedSlice); + } + + /** + * Performs a slicing test. + * + * @param proofFileInRepository The path to the proof file. + * @param selector The {@link ISeedLocationSelector} to use. + * @param fullSlize {@code true} if the he full slice is given as expected slice and + * {@code false} if only a part of the slice is given as expected slice. + * @param expectedSlice The serial IDs of the expected slices. + * @throws Exception Occurred Exception + */ + protected void doSlicingTest(String proofFileInRepository, ISeedLocationSelector selector, + IEquivalenceClassSelector eqSelector, boolean fullSlize, int... expectedSlice) + throws Exception { + // Load proof + File proofFile = new File(testCaseDirectory, proofFileInRepository); + Assertions.assertTrue(proofFile.exists()); + KeYEnvironment environment = + KeYEnvironment.load(SymbolicExecutionJavaProfile.getDefaultInstance(), proofFile, + null, null, null, true); + try { + // Get loaded proof + Proof proof = environment.getLoadedProof(); + Assertions.assertNotNull(proof); + // Find seed + Pair seed = selector.findSeed(proof); + // Select equivalence class + Assertions.assertNotNull(eqSelector); + ImmutableList sec = + eqSelector.selectEquivalenceClass(environment, proof, seed); + if (PRINT_SLICE) { + LOGGER.info("Equivalence Class: {}", sec); } - } - if (fullSlize) { - // Compare all Nodes in the slice - Assertions.assertEquals(expectedSlice.length, slices.size()); - for (int i = 0; i < expectedSlice.length; i++) { - Node slice = slices.get(i); - Assertions.assertNotNull(slice); - Assertions.assertEquals(expectedSlice[i], slice.serialNr()); + // Perform slicing + ThinBackwardSlicer slicer = new ThinBackwardSlicer(); + ImmutableArray slices = slicer.slice(seed.first, seed.second, sec); + // Print slice if requested + if (PRINT_SLICE) { + LOGGER.info("Found Slices: {}", slices.size()); + for (Node slice : slices) { + LOGGER.info("SerialNr {}", slice.serialNr()); + } } - } - else { - // Ensure that only given Nodes exist in the slice maintaining the order - int currentIndex = 0; - for (int expected : expectedSlice) { - Node slice = null; - while (slice == null && currentIndex < slices.size()) { - Node toCheck = slices.get(currentIndex); - Assertions.assertNotNull(toCheck); - if (toCheck.serialNr() == expected) { - slice = toCheck; - } - currentIndex++; - } - Assertions.assertNotNull(slice); + if (fullSlize) { + // Compare all Nodes in the slice + Assertions.assertEquals(expectedSlice.length, slices.size()); + for (int i = 0; i < expectedSlice.length; i++) { + Node slice = slices.get(i); + Assertions.assertNotNull(slice); + Assertions.assertEquals(expectedSlice[i], slice.serialNr()); + } + } else { + // Ensure that only given Nodes exist in the slice maintaining the order + int currentIndex = 0; + for (int expected : expectedSlice) { + Node slice = null; + while (slice == null && currentIndex < slices.size()) { + Node toCheck = slices.get(currentIndex); + Assertions.assertNotNull(toCheck); + if (toCheck.serialNr() == expected) { + slice = toCheck; + } + currentIndex++; + } + Assertions.assertNotNull(slice); + } } - } - } - finally { - environment.dispose(); - } - } - - /** - * Implementations are used to select an {@link ISymbolicEquivalenceClass}. - * @author Martin Hentschel - */ - protected interface IEquivalenceClassSelector { - /** - * Selects the {@link ISymbolicEquivalenceClass}. - * @param environment The current {@link KeYEnvironment}. - * @param proof The current {@link Proof}. - * @param seed The current seed. - * @return The {@link ISymbolicEquivalenceClass}es or {@code null} to select. - */ - ImmutableList selectEquivalenceClass(KeYEnvironment environment, - Proof proof, - Pair seed) throws Exception; - } - - /** - * An {@link IEquivalenceClassSelector} which selects no {@link ISymbolicEquivalenceClass}. - * @author Martin Hentschel - */ - protected static class NoEquivalenceClassSelector implements IEquivalenceClassSelector { - /** - * {@inheritDoc} - */ - @Override - public ImmutableList selectEquivalenceClass(KeYEnvironment environment, Proof proof, Pair seed) { - return null; - } - } - - /** - * An {@link IEquivalenceClassSelector} which selects an {@link ISymbolicEquivalenceClass} by index. - * @author Martin Hentschel - */ - protected static class EquivalenceClassByIndexSelector implements IEquivalenceClassSelector { - /** - * The index of the {@link ISymbolicEquivalenceClass}es. - */ - private final int index; - - /** - * Constructor. - * @param index The index of the {@link ISymbolicEquivalenceClass}es. - */ - public EquivalenceClassByIndexSelector(int index) { - this.index = index; - } - - /** - * {@inheritDoc} - */ - @Override - public ImmutableList selectEquivalenceClass(KeYEnvironment environment, - Proof proof, - Pair seed) throws Exception { - SymbolicExecutionTreeBuilder builder = new SymbolicExecutionTreeBuilder(proof, false, false, false, false, false); - SymbolicExecutionUtil.initializeStrategy(builder); - builder.analyse(); - IExecutionNode node = builder.getExecutionNode(seed.first); - assert node instanceof AbstractExecutionNode; - ExecutionNodeSymbolicLayoutExtractor extractor = ((AbstractExecutionNode) node).getLayoutExtractor(); - return extractor.getEquivalenceClasses(index); - } - } - - /** - * {@link ISeedLocationSelector} which searches the right side of a variable declaration. - * @author Martin Hentschel - */ - protected static class RightVariableDeclarationSelector implements ISeedLocationSelector { - /** - * The serial ID of the seed node. - */ - private final int seedNodeId; - - /** - * Constructor. - * @param seedNodeId The serial ID of the seed node. - */ - public RightVariableDeclarationSelector(int seedNodeId) { - this.seedNodeId = seedNodeId; - } - - /** - * {@inheritDoc} - */ - @Override - public Pair findSeed(Proof proof) { - // Find seed - Node seedNode = findNode(proof, seedNodeId); - Assertions.assertNotNull(seedNode); - // Get seed location - SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); - Assertions.assertTrue(activeStatemt instanceof VariableDeclaration); - VariableDeclaration variableDeclaration = (VariableDeclaration) activeStatemt; - SourceElement seedLocation = variableDeclaration.getChildAt(1); - Assertions.assertTrue(seedLocation instanceof VariableSpecification); - return new Pair<>(seedNode, (ReferencePrefix) ((VariableSpecification) seedLocation).getInitializer()); - } - } - - /** - * {@link ISeedLocationSelector} which searches the right side of an assignment. - * @author Martin Hentschel - */ - protected static class RightAssignmentSelector implements ISeedLocationSelector { - /** - * The serial ID of the seed node. - */ - private final int seedNodeId; - - /** - * Constructor. - * @param seedNodeId The serial ID of the seed node. - */ - public RightAssignmentSelector(int seedNodeId) { - this.seedNodeId = seedNodeId; - } - - /** - * {@inheritDoc} - */ - @Override - public Pair findSeed(Proof proof) { - // Find seed - Node seedNode = findNode(proof, seedNodeId); - Assertions.assertNotNull(seedNode); - // Get seed location - SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); - Assertions.assertTrue(activeStatemt instanceof CopyAssignment); - CopyAssignment assignment = (CopyAssignment) activeStatemt; - SourceElement seedLocation = assignment.getChildAt(1); - return new Pair<>(seedNode, (ReferencePrefix) seedLocation); - } - } - - /** - * {@link ISeedLocationSelector} which searches the left side of an assignment. - * @author Martin Hentschel - */ - protected static class LeftAssignmentSelector implements ISeedLocationSelector { - /** - * The serial ID of the seed node. - */ - private final int seedNodeId; - - /** - * Constructor. - * @param seedNodeId The serial ID of the seed node. - */ - public LeftAssignmentSelector(int seedNodeId) { - this.seedNodeId = seedNodeId; - } - - /** - * {@inheritDoc} - */ - @Override - public Pair findSeed(Proof proof) { - // Find seed - Node seedNode = findNode(proof, seedNodeId); - Assertions.assertNotNull(seedNode); - // Get seed location - SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); - Assertions.assertTrue(activeStatemt instanceof CopyAssignment); - CopyAssignment assignment = (CopyAssignment) activeStatemt; - SourceElement seedLocation = assignment.getChildAt(0); - return new Pair<>(seedNode, (ReferencePrefix) seedLocation); - } - } - - /** - * {@link ISeedLocationSelector} which searches a return expression as seed. - * @author Martin Hentschel - */ - protected static class ReturnSelector implements ISeedLocationSelector { - /** - * The serial ID of the seed node. - */ - private final int seedNodeId; - - /** - * Constructor. - * @param seedNodeId The serial ID of the seed node. - */ - public ReturnSelector(int seedNodeId) { - this.seedNodeId = seedNodeId; - } - - /** - * {@inheritDoc} - */ - @Override - public Pair findSeed(Proof proof) { - // Find seed - Node seedNode = findNode(proof, seedNodeId); - Assertions.assertNotNull(seedNode); - // Get seed location - SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); - Assertions.assertTrue(activeStatemt instanceof Return); - Return returnStatement = (Return) activeStatemt; - SourceElement seedLocation = returnStatement.getExpression(); - return new Pair<>(seedNode, (ReferencePrefix) seedLocation); - } - } - - /** - * Implementations of this interface are used to find the seed. - * @author Martin Hentschel - */ - protected interface ISeedLocationSelector { - Pair findSeed(Proof proof); - } - - /** - * Searches a {@link Node} with the given serial ID. - * @param proof The {@link Proof} to search in. - * @param nodeId The ID of the {@link Node} to search. - * @return The found {@link Node} or {@code null} if not available. - */ - protected static Node findNode(Proof proof, int nodeId) { - FindNodeProofVisitor visitor = new FindNodeProofVisitor(nodeId); - proof.breadthFirstSearch(proof.root(), visitor); - return visitor.getNode(); - } - - /** - * Utility class used by {@link TestThinBackwardSlicer#findNode(Proof, int)}. - * @author Martin Hentschel - */ - private static class FindNodeProofVisitor implements ProofVisitor { - /** - * The ID of the node to search. - */ - private final int nodeId; - - /** - * The found node. - */ - private Node node; - - /** - * Constructor. - * @param nodeId The ID of the node to search. - */ - public FindNodeProofVisitor(int nodeId) { - this.nodeId = nodeId; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(Proof proof, Node visitedNode) { - if (visitedNode.serialNr() == nodeId) { - node = visitedNode; - } - } - - /** - * Returns the found {@link Node}. - * @return The found {@link Node} or {@code null} if not available. - */ - public Node getNode() { - return node; - } - } + } finally { + environment.dispose(); + } + } + + /** + * Implementations are used to select an {@link ISymbolicEquivalenceClass}. + * + * @author Martin Hentschel + */ + protected interface IEquivalenceClassSelector { + /** + * Selects the {@link ISymbolicEquivalenceClass}. + * + * @param environment The current {@link KeYEnvironment}. + * @param proof The current {@link Proof}. + * @param seed The current seed. + * @return The {@link ISymbolicEquivalenceClass}es or {@code null} to select. + */ + ImmutableList selectEquivalenceClass( + KeYEnvironment environment, Proof proof, Pair seed) + throws Exception; + } + + /** + * An {@link IEquivalenceClassSelector} which selects no {@link ISymbolicEquivalenceClass}. + * + * @author Martin Hentschel + */ + protected static class NoEquivalenceClassSelector implements IEquivalenceClassSelector { + /** + * {@inheritDoc} + */ + @Override + public ImmutableList selectEquivalenceClass( + KeYEnvironment environment, Proof proof, Pair seed) { + return null; + } + } + + /** + * An {@link IEquivalenceClassSelector} which selects an {@link ISymbolicEquivalenceClass} by + * index. + * + * @author Martin Hentschel + */ + protected static class EquivalenceClassByIndexSelector implements IEquivalenceClassSelector { + /** + * The index of the {@link ISymbolicEquivalenceClass}es. + */ + private final int index; + + /** + * Constructor. + * + * @param index The index of the {@link ISymbolicEquivalenceClass}es. + */ + public EquivalenceClassByIndexSelector(int index) { + this.index = index; + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableList selectEquivalenceClass( + KeYEnvironment environment, Proof proof, Pair seed) + throws Exception { + SymbolicExecutionTreeBuilder builder = + new SymbolicExecutionTreeBuilder(proof, false, false, false, false, false); + SymbolicExecutionUtil.initializeStrategy(builder); + builder.analyse(); + IExecutionNode node = builder.getExecutionNode(seed.first); + assert node instanceof AbstractExecutionNode; + ExecutionNodeSymbolicLayoutExtractor extractor = + ((AbstractExecutionNode) node).getLayoutExtractor(); + return extractor.getEquivalenceClasses(index); + } + } + + /** + * {@link ISeedLocationSelector} which searches the right side of a variable declaration. + * + * @author Martin Hentschel + */ + protected static class RightVariableDeclarationSelector implements ISeedLocationSelector { + /** + * The serial ID of the seed node. + */ + private final int seedNodeId; + + /** + * Constructor. + * + * @param seedNodeId The serial ID of the seed node. + */ + public RightVariableDeclarationSelector(int seedNodeId) { + this.seedNodeId = seedNodeId; + } + + /** + * {@inheritDoc} + */ + @Override + public Pair findSeed(Proof proof) { + // Find seed + Node seedNode = findNode(proof, seedNodeId); + Assertions.assertNotNull(seedNode); + // Get seed location + SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); + Assertions.assertTrue(activeStatemt instanceof VariableDeclaration); + VariableDeclaration variableDeclaration = (VariableDeclaration) activeStatemt; + SourceElement seedLocation = variableDeclaration.getChildAt(1); + Assertions.assertTrue(seedLocation instanceof VariableSpecification); + return new Pair<>(seedNode, + (ReferencePrefix) ((VariableSpecification) seedLocation).getInitializer()); + } + } + + /** + * {@link ISeedLocationSelector} which searches the right side of an assignment. + * + * @author Martin Hentschel + */ + protected static class RightAssignmentSelector implements ISeedLocationSelector { + /** + * The serial ID of the seed node. + */ + private final int seedNodeId; + + /** + * Constructor. + * + * @param seedNodeId The serial ID of the seed node. + */ + public RightAssignmentSelector(int seedNodeId) { + this.seedNodeId = seedNodeId; + } + + /** + * {@inheritDoc} + */ + @Override + public Pair findSeed(Proof proof) { + // Find seed + Node seedNode = findNode(proof, seedNodeId); + Assertions.assertNotNull(seedNode); + // Get seed location + SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); + Assertions.assertTrue(activeStatemt instanceof CopyAssignment); + CopyAssignment assignment = (CopyAssignment) activeStatemt; + SourceElement seedLocation = assignment.getChildAt(1); + return new Pair<>(seedNode, (ReferencePrefix) seedLocation); + } + } + + /** + * {@link ISeedLocationSelector} which searches the left side of an assignment. + * + * @author Martin Hentschel + */ + protected static class LeftAssignmentSelector implements ISeedLocationSelector { + /** + * The serial ID of the seed node. + */ + private final int seedNodeId; + + /** + * Constructor. + * + * @param seedNodeId The serial ID of the seed node. + */ + public LeftAssignmentSelector(int seedNodeId) { + this.seedNodeId = seedNodeId; + } + + /** + * {@inheritDoc} + */ + @Override + public Pair findSeed(Proof proof) { + // Find seed + Node seedNode = findNode(proof, seedNodeId); + Assertions.assertNotNull(seedNode); + // Get seed location + SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); + Assertions.assertTrue(activeStatemt instanceof CopyAssignment); + CopyAssignment assignment = (CopyAssignment) activeStatemt; + SourceElement seedLocation = assignment.getChildAt(0); + return new Pair<>(seedNode, (ReferencePrefix) seedLocation); + } + } + + /** + * {@link ISeedLocationSelector} which searches a return expression as seed. + * + * @author Martin Hentschel + */ + protected static class ReturnSelector implements ISeedLocationSelector { + /** + * The serial ID of the seed node. + */ + private final int seedNodeId; + + /** + * Constructor. + * + * @param seedNodeId The serial ID of the seed node. + */ + public ReturnSelector(int seedNodeId) { + this.seedNodeId = seedNodeId; + } + + /** + * {@inheritDoc} + */ + @Override + public Pair findSeed(Proof proof) { + // Find seed + Node seedNode = findNode(proof, seedNodeId); + Assertions.assertNotNull(seedNode); + // Get seed location + SourceElement activeStatemt = seedNode.getNodeInfo().getActiveStatement(); + Assertions.assertTrue(activeStatemt instanceof Return); + Return returnStatement = (Return) activeStatemt; + SourceElement seedLocation = returnStatement.getExpression(); + return new Pair<>(seedNode, (ReferencePrefix) seedLocation); + } + } + + /** + * Implementations of this interface are used to find the seed. + * + * @author Martin Hentschel + */ + protected interface ISeedLocationSelector { + Pair findSeed(Proof proof); + } + + /** + * Searches a {@link Node} with the given serial ID. + * + * @param proof The {@link Proof} to search in. + * @param nodeId The ID of the {@link Node} to search. + * @return The found {@link Node} or {@code null} if not available. + */ + protected static Node findNode(Proof proof, int nodeId) { + FindNodeProofVisitor visitor = new FindNodeProofVisitor(nodeId); + proof.breadthFirstSearch(proof.root(), visitor); + return visitor.getNode(); + } + + /** + * Utility class used by {@link TestThinBackwardSlicer#findNode(Proof, int)}. + * + * @author Martin Hentschel + */ + private static class FindNodeProofVisitor implements ProofVisitor { + /** + * The ID of the node to search. + */ + private final int nodeId; + + /** + * The found node. + */ + private Node node; + + /** + * Constructor. + * + * @param nodeId The ID of the node to search. + */ + public FindNodeProofVisitor(int nodeId) { + this.nodeId = nodeId; + } + + /** + * {@inheritDoc} + */ + @Override + public void visit(Proof proof, Node visitedNode) { + if (visitedNode.serialNr() == nodeId) { + node = visitedNode; + } + } + + /** + * Returns the found {@link Node}. + * + * @return The found {@link Node} or {@code null} if not available. + */ + public Node getNode() { + return node; + } + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionCaughtOrUncaught.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionCaughtOrUncaught.java index ad0891aa370..daa4c4979e9 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionCaughtOrUncaught.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionCaughtOrUncaught.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -21,54 +24,73 @@ /** * Tests whether caught and uncaught ExceptionBreakpoints are handled correctly - * + * * @author Marco Drebing */ -public class TestExceptionBreakpointStopConditionCaughtOrUncaught extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env = null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try { - // Define test settings - String javaPathInkeyRepDirectory = "/set/exceptionBreakpointsCaughtOrUncaught/test/ClassCastAndNullpointerExceptions.java"; - String containerTypeName = "ClassCastAndNullpointerExceptions"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/exceptionBreakpointsCaughtOrUncaught/oracle/ClassCastAndNullpointerExceptions"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - - Proof proof = env.getBuilder().getProof(); - StrategyProperties props = proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); - props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); +public class TestExceptionBreakpointStopConditionCaughtOrUncaught + extends AbstractSymbolicExecutionTestCase { + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/exceptionBreakpointsCaughtOrUncaught/test/ClassCastAndNullpointerExceptions.java"; + String containerTypeName = "ClassCastAndNullpointerExceptions"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/exceptionBreakpointsCaughtOrUncaught/oracle/ClassCastAndNullpointerExceptions"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - SymbolicExecutionExceptionBreakpoint firstBreakpoint = new SymbolicExecutionExceptionBreakpoint(proof, "java.lang.NullPointerException", true, false, false, true, -1); - SymbolicExecutionExceptionBreakpoint secondBreakpoint = new SymbolicExecutionExceptionBreakpoint(proof, "java.lang.ClassCastException", false, true, false, true, -1); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(firstBreakpoint, secondBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file + Proof proof = env.getBuilder().getProof(); + StrategyProperties props = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); + props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); + + SymbolicExecutionExceptionBreakpoint firstBreakpoint = + new SymbolicExecutionExceptionBreakpoint(proof, + "java.lang.NullPointerException", true, false, false, true, -1); + SymbolicExecutionExceptionBreakpoint secondBreakpoint = + new SymbolicExecutionExceptionBreakpoint(proof, "java.lang.ClassCastException", + false, true, false, true, -1); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(firstBreakpoint, secondBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithHitCount.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithHitCount.java index 658b1467a4d..2ec18655893 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithHitCount.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithHitCount.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -17,50 +20,67 @@ import java.io.IOException; import java.util.HashMap; -public class TestExceptionBreakpointStopConditionWithHitCount extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - SymbolicExecutionEnvironment env = null; - try { - // Define test settings - String javaPathInkeyRepDirectory = "/set/exceptionBreakpointsWithHitCountTest/test/ClassCastAndNullpointerExceptions.java"; - String containerTypeName = "ClassCastAndNullpointerExceptions"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/exceptionBreakpointsWithHitCountTest/oracle/ClassCastAndNullpointerExceptions"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - - Proof proof = env.getBuilder().getProof(); - StrategyProperties props = proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); - props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); - - SymbolicExecutionExceptionBreakpoint firstBreakpoint = new SymbolicExecutionExceptionBreakpoint(proof,"java.lang.NullPointerException", true, true, false, true, 2); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(firstBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestExceptionBreakpointStopConditionWithHitCount + extends AbstractSymbolicExecutionTestCase { + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + SymbolicExecutionEnvironment env = null; + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/exceptionBreakpointsWithHitCountTest/test/ClassCastAndNullpointerExceptions.java"; + String containerTypeName = "ClassCastAndNullpointerExceptions"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/exceptionBreakpointsWithHitCountTest/oracle/ClassCastAndNullpointerExceptions"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + + Proof proof = env.getBuilder().getProof(); + StrategyProperties props = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); + props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); + + SymbolicExecutionExceptionBreakpoint firstBreakpoint = + new SymbolicExecutionExceptionBreakpoint(proof, + "java.lang.NullPointerException", true, true, false, true, 2); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(firstBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithSubclasses.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithSubclasses.java index 0b4283faa3b..c74f9e38c37 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithSubclasses.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestExceptionBreakpointStopConditionWithSubclasses.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -17,54 +20,77 @@ import java.io.IOException; import java.util.HashMap; -public class TestExceptionBreakpointStopConditionWithSubclasses extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - SymbolicExecutionEnvironment env = null; - try { - // Define test settings - String javaPathInkeyRepDirectory = "/set/exceptionBreakpointsWithSubclassesTest/test/ClassCastAndNullpointerExceptions.java"; - String containerTypeName = "ClassCastAndNullpointerExceptions"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/exceptionBreakpointsWithSubclassesTest/oracle/ClassCastAndNullpointerExceptions"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - - Proof proof = env.getBuilder().getProof(); - StrategyProperties props = proof.getSettings().getStrategySettings().getActiveStrategyProperties(); - props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); - props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); - proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); - - SymbolicExecutionExceptionBreakpoint firstBreakpoint = new SymbolicExecutionExceptionBreakpoint(proof,"java.lang.Exception", true, true, true, true, -1); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(firstBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - // Restore runtime option - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestExceptionBreakpointStopConditionWithSubclasses + extends AbstractSymbolicExecutionTestCase { + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + SymbolicExecutionEnvironment env = null; + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/exceptionBreakpointsWithSubclassesTest/test/ClassCastAndNullpointerExceptions.java"; + String containerTypeName = "ClassCastAndNullpointerExceptions"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/exceptionBreakpointsWithSubclassesTest/oracle/ClassCastAndNullpointerExceptions"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + + Proof proof = env.getBuilder().getProof(); + StrategyProperties props = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + props.put(StrategyProperties.METHOD_OPTIONS_KEY, StrategyProperties.METHOD_EXPAND); + props.put(StrategyProperties.LOOP_OPTIONS_KEY, StrategyProperties.LOOP_EXPAND); + proof.getSettings().getStrategySettings().setActiveStrategyProperties(props); + + SymbolicExecutionExceptionBreakpoint firstBreakpoint = + new SymbolicExecutionExceptionBreakpoint(proof, "java.lang.Exception", true, + true, true, true, -1); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(firstBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + // Restore runtime option + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestJavaWatchpointStopConditionWithHitCount.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestJavaWatchpointStopConditionWithHitCount.java index 79956720be1..f1457c61c51 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestJavaWatchpointStopConditionWithHitCount.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestJavaWatchpointStopConditionWithHitCount.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -20,59 +23,92 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; public class TestJavaWatchpointStopConditionWithHitCount extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/javaWatchpointsWithHitCountTest/test/GlobalAccessesAndModifications.java"; - String containerTypeName = "GlobalAccessesAndModifications"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/javaWatchpointsWithHitCountTest/oracle/GlobalAccessesAndModifications"; - String oracleFileExtension = ".xml"; - // Set settings - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - KeYJavaType containerType = null; - for ( KeYJavaType kjt : env.getProof().getJavaInfo().getAllKeYJavaTypes()){ - if(kjt.getSort().toString().equals("GlobalAccessesAndModifications")){ - containerType = kjt; + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/javaWatchpointsWithHitCountTest/test/GlobalAccessesAndModifications.java"; + String containerTypeName = "GlobalAccessesAndModifications"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/javaWatchpointsWithHitCountTest/oracle/GlobalAccessesAndModifications"; + String oracleFileExtension = ".xml"; + // Set settings + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + KeYJavaType containerType = null; + for (KeYJavaType kjt : env.getProof().getJavaInfo().getAllKeYJavaTypes()) { + if (kjt.getSort().toString().equals("GlobalAccessesAndModifications")) { + containerType = kjt; + } } - } - - FieldWatchpoint firstBreakpoint = new FieldWatchpoint(true, 2, "access", true,false, containerType, env.getBuilder().getProof()); - FieldWatchpoint secondBreakpoint = new FieldWatchpoint(true, -1, "modification", false,true, containerType, env.getBuilder().getProof()); - FieldWatchpoint thirdBreakpoint = new FieldWatchpoint(true, 2, "accessAndModification", true,true, containerType, env.getBuilder().getProof()); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(firstBreakpoint,secondBreakpoint,thirdBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file + + FieldWatchpoint firstBreakpoint = new FieldWatchpoint(true, 2, "access", true, false, + containerType, env.getBuilder().getProof()); + FieldWatchpoint secondBreakpoint = new FieldWatchpoint(true, -1, "modification", false, + true, containerType, env.getBuilder().getProof()); + FieldWatchpoint thirdBreakpoint = new FieldWatchpoint(true, 2, "accessAndModification", + true, true, containerType, env.getBuilder().getProof()); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(firstBreakpoint, secondBreakpoint, + thirdBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnSatisfiable.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnSatisfiable.java index 547ba6f3213..ad2b2d312fb 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnSatisfiable.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnSatisfiable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -17,50 +20,71 @@ import java.io.IOException; import java.util.HashMap; -public class TestKeYWatchpointGlobalVariablesOnSatisfiable extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/keyWatchpointGlobalVariablesOnSatisfiable/test/GlobalVariablesOnSatisfiable.java"; - String containerTypeName = "GlobalVariablesOnSatisfiable"; - final String methodFullName = "doSomething"; - String oraclePathInkeyRepDirectoryFile = "/set/keyWatchpointGlobalVariablesOnSatisfiable/oracle/GlobalVariablesOnSatisfiable"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - JavaInfo javaInfo = env.getServices().getJavaInfo(); - KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); - - KeYWatchpoint globalVariableCondition = new KeYWatchpoint(-1, env.getBuilder().getProof(),"x_global==17", true, true, containerType, false); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestKeYWatchpointGlobalVariablesOnSatisfiable + extends AbstractSymbolicExecutionTestCase { + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/keyWatchpointGlobalVariablesOnSatisfiable/test/GlobalVariablesOnSatisfiable.java"; + String containerTypeName = "GlobalVariablesOnSatisfiable"; + final String methodFullName = "doSomething"; + String oraclePathInkeyRepDirectoryFile = + "/set/keyWatchpointGlobalVariablesOnSatisfiable/oracle/GlobalVariablesOnSatisfiable"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + JavaInfo javaInfo = env.getServices().getJavaInfo(); + KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); + + KeYWatchpoint globalVariableCondition = new KeYWatchpoint(-1, + env.getBuilder().getProof(), "x_global==17", true, true, containerType, false); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnTrueWithHitCount.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnTrueWithHitCount.java index 789754c23e0..869610c9951 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnTrueWithHitCount.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointGlobalVariablesOnTrueWithHitCount.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,47 +22,62 @@ import de.uka.ilkd.key.symbolic_execution.testcase.AbstractSymbolicExecutionTestCase; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; -public class TestKeYWatchpointGlobalVariablesOnTrueWithHitCount extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/keyWatchpointGlobalVariablesOnTrueWithHitCount/test/GlobalVariablesOnTrue.java"; - String containerTypeName = "GlobalVariablesOnTrue"; - final String methodFullName = "doSomething"; - String oraclePathInkeyRepDirectoryFile = "/set/keyWatchpointGlobalVariablesOnTrueWithHitCount/oracle/GlobalVariablesOnTrue"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - JavaInfo javaInfo = env.getServices().getJavaInfo(); - KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); - - KeYWatchpoint globalVariableCondition = new KeYWatchpoint(2, env.getBuilder().getProof(),"x_global==17", true, true, containerType, true); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestKeYWatchpointGlobalVariablesOnTrueWithHitCount + extends AbstractSymbolicExecutionTestCase { + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/keyWatchpointGlobalVariablesOnTrueWithHitCount/test/GlobalVariablesOnTrue.java"; + String containerTypeName = "GlobalVariablesOnTrue"; + final String methodFullName = "doSomething"; + String oraclePathInkeyRepDirectoryFile = + "/set/keyWatchpointGlobalVariablesOnTrueWithHitCount/oracle/GlobalVariablesOnTrue"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + JavaInfo javaInfo = env.getServices().getJavaInfo(); + KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); + + KeYWatchpoint globalVariableCondition = new KeYWatchpoint(2, + env.getBuilder().getProof(), "x_global==17", true, true, containerType, true); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointMethodsOnSatisfiable.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointMethodsOnSatisfiable.java index afdbae6f25e..1b2fef0b817 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointMethodsOnSatisfiable.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestKeYWatchpointMethodsOnSatisfiable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -20,49 +23,70 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; public class TestKeYWatchpointMethodsOnSatisfiable extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/keyWatchpointMethodsOnSatisfiable/test/MethodsOnSatisfiable.java"; - String containerTypeName = "MethodsOnSatisfiable"; - final String methodFullName = "doSomething"; - String oraclePathInkeyRepDirectoryFile = "/set/keyWatchpointMethodsOnSatisfiable/oracle/MethodsOnSatisfiable"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - JavaInfo javaInfo = env.getServices().getJavaInfo(); - KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); - - KeYWatchpoint globalVariableCondition = new KeYWatchpoint(-1, env.getBuilder().getProof(),"main(x_global)==42", true, true, containerType, false); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/keyWatchpointMethodsOnSatisfiable/test/MethodsOnSatisfiable.java"; + String containerTypeName = "MethodsOnSatisfiable"; + final String methodFullName = "doSomething"; + String oraclePathInkeyRepDirectoryFile = + "/set/keyWatchpointMethodsOnSatisfiable/oracle/MethodsOnSatisfiable"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + JavaInfo javaInfo = env.getServices().getJavaInfo(); + KeYJavaType containerType = javaInfo.getTypeByClassName(containerTypeName); + + KeYWatchpoint globalVariableCondition = + new KeYWatchpoint(-1, env.getBuilder().getProof(), "main(x_global)==42", true, + true, containerType, false); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(globalVariableCondition); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithConditions.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithConditions.java index dae666984ad..647a97ab815 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithConditions.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithConditions.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -18,86 +21,140 @@ import de.uka.ilkd.key.symbolic_execution.testcase.AbstractSymbolicExecutionTestCase; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; -public class TestLineBreakpointStopConditionSimpleWithConditions extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment envMain=null; - SymbolicExecutionEnvironment envSomethingMain=null; - SymbolicExecutionEnvironment envSomethingLocalMain=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/lineBreakpointsWithConditionsTest/test/SimpleConditionExample.java"; - String containerTypeName = "SimpleConditionExample"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/lineBreakpointsWithConditionsTest/oracle/BreakpointStopConditionWithCondition"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - envMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - IProgramMethod main = searchProgramMethod(envMain.getServices(), containerTypeName, "main"); - // Test method main() - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - LineBreakpoint mainBreakpoint = new LineBreakpoint(main.getPositionInfo().getFileName(), 9, -1, main, envMain.getBuilder().getProof(), "z==1", true, true,6,11); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); - allBreakpoints.addChildren(bc); - envMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - - - //Test method somethingMain() - envSomethingMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, "somethingMain", null, false, false, false, false, false, false, false, false, false, false); - IProgramMethod something = searchProgramMethod(envSomethingMain.getServices(), containerTypeName, "something"); - IProgramMethod somethingMain = searchProgramMethod(envSomethingMain.getServices(), containerTypeName, "somethingMain"); - allBreakpoints = new CompoundStopCondition(); - LineBreakpoint somethingMainBreakpoint = new LineBreakpoint(somethingMain.getPositionInfo().getFileName(), 15, -1, somethingMain, envSomethingMain.getBuilder().getProof(),"a==2", true, true,13,17); - LineBreakpoint somethingBreakpoint = new LineBreakpoint(something.getPositionInfo().getFileName(), 20, -1, something, envSomethingMain.getBuilder().getProof(),"b==3", true, true,19,21); - bc = new SymbolicExecutionBreakpointStopCondition(somethingBreakpoint, somethingMainBreakpoint); - allBreakpoints.addChildren(bc); - envSomethingMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - assertSetTreeAfterStep(envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - - //Test method somethingLocalMain() - envSomethingLocalMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, "somethingLocalMain", null, false, false, false, false, false, false, false, false, false, false); - IProgramMethod somethingLocal = searchProgramMethod(envSomethingLocalMain.getServices(), containerTypeName, "somethingLocal"); - IProgramMethod somethingLocalMain = searchProgramMethod(envSomethingLocalMain.getServices(), containerTypeName, "somethingLocalMain"); - allBreakpoints = new CompoundStopCondition(); - LineBreakpoint somethingLocalBreakpoint = new LineBreakpoint(somethingLocal.getPositionInfo().getFileName(), 31, -1, somethingLocal, envSomethingLocalMain.getBuilder().getProof(),"y==42*42&&x==42", true, true,29,32); - LineBreakpoint somethingLocalMainBreakpoint = new LineBreakpoint(somethingLocalMain.getPositionInfo().getFileName(), 26, -1, somethingLocalMain, envSomethingLocalMain.getBuilder().getProof(),"x==42*42&&y==42", true, true,23,27); - bc = new SymbolicExecutionBreakpointStopCondition(somethingLocalBreakpoint, somethingLocalMainBreakpoint); - allBreakpoints.addChildren(bc); - envSomethingLocalMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - - assertSetTreeAfterStep(envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(envMain!=null){ - envMain.dispose(); - } - if(envSomethingMain!=null){ - envSomethingMain.dispose(); - } - if(envSomethingLocalMain!=null){ - envSomethingLocalMain.dispose(); - } - } - } -} \ No newline at end of file +public class TestLineBreakpointStopConditionSimpleWithConditions + extends AbstractSymbolicExecutionTestCase { + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment envMain = null; + SymbolicExecutionEnvironment envSomethingMain = null; + SymbolicExecutionEnvironment envSomethingLocalMain = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/lineBreakpointsWithConditionsTest/test/SimpleConditionExample.java"; + String containerTypeName = "SimpleConditionExample"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/lineBreakpointsWithConditionsTest/oracle/BreakpointStopConditionWithCondition"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + envMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, + false, false, false, false, false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); + IProgramMethod main = + searchProgramMethod(envMain.getServices(), containerTypeName, "main"); + // Test method main() + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + LineBreakpoint mainBreakpoint = new LineBreakpoint(main.getPositionInfo().getFileName(), + 9, -1, main, envMain.getBuilder().getProof(), "z==1", true, true, 6, 11); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); + allBreakpoints.addChildren(bc); + envMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + + + // Test method somethingMain() + envSomethingMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, "somethingMain", null, false, + false, false, false, false, false, false, false, false, false); + IProgramMethod something = searchProgramMethod(envSomethingMain.getServices(), + containerTypeName, "something"); + IProgramMethod somethingMain = searchProgramMethod(envSomethingMain.getServices(), + containerTypeName, "somethingMain"); + allBreakpoints = new CompoundStopCondition(); + LineBreakpoint somethingMainBreakpoint = new LineBreakpoint( + somethingMain.getPositionInfo().getFileName(), 15, -1, somethingMain, + envSomethingMain.getBuilder().getProof(), "a==2", true, true, 13, 17); + LineBreakpoint somethingBreakpoint = + new LineBreakpoint(something.getPositionInfo().getFileName(), 20, -1, something, + envSomethingMain.getBuilder().getProof(), "b==3", true, true, 19, 21); + bc = new SymbolicExecutionBreakpointStopCondition(somethingBreakpoint, + somethingMainBreakpoint); + allBreakpoints.addChildren(bc); + envSomethingMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + assertSetTreeAfterStep(envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + + // Test method somethingLocalMain() + envSomethingLocalMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, "somethingLocalMain", null, false, + false, false, false, false, false, false, false, false, false); + IProgramMethod somethingLocal = searchProgramMethod(envSomethingLocalMain.getServices(), + containerTypeName, "somethingLocal"); + IProgramMethod somethingLocalMain = searchProgramMethod( + envSomethingLocalMain.getServices(), containerTypeName, "somethingLocalMain"); + allBreakpoints = new CompoundStopCondition(); + LineBreakpoint somethingLocalBreakpoint = + new LineBreakpoint(somethingLocal.getPositionInfo().getFileName(), 31, -1, + somethingLocal, envSomethingLocalMain.getBuilder().getProof(), + "y==42*42&&x==42", true, true, 29, 32); + LineBreakpoint somethingLocalMainBreakpoint = + new LineBreakpoint(somethingLocalMain.getPositionInfo().getFileName(), 26, -1, + somethingLocalMain, envSomethingLocalMain.getBuilder().getProof(), + "x==42*42&&y==42", true, true, 23, 27); + bc = new SymbolicExecutionBreakpointStopCondition(somethingLocalBreakpoint, + somethingLocalMainBreakpoint); + allBreakpoints.addChildren(bc); + envSomethingLocalMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + + assertSetTreeAfterStep(envSomethingLocalMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (envMain != null) { + envMain.dispose(); + } + if (envSomethingMain != null) { + envSomethingMain.dispose(); + } + if (envSomethingLocalMain != null) { + envSomethingLocalMain.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithHitCount.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithHitCount.java index 0afb7ecc2ae..adf56b9048b 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithHitCount.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithHitCount.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,56 +22,89 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; /** - * Tests for {@link LineBreakpoint}. Tests if execution stops at {@link JavaLineBreakpoint} correctly. - * + * Tests for {@link LineBreakpoint}. Tests if execution stops at {@link JavaLineBreakpoint} + * correctly. + * * @author Marco Drebing */ -public class TestLineBreakpointStopConditionSimpleWithHitCount extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - SymbolicExecutionEnvironment env=null; - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/lineBreakpointsWithHitcountTest/test/BreakpointStopCallerAndLoop.java"; - String containerTypeName = "BreakpointStopCallerAndLoop"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/lineBreakpointsWithHitcountTest/oracle/BreakpointStop"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - IProgramMethod callerMain = searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "main"); - IProgramMethod calleeMain = searchProgramMethod(env.getServices(), "BreakpointStopCallee", "main"); - IProgramMethod callerLoop = searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "loop"); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - LineBreakpoint firstBreakpoint = new LineBreakpoint(callerMain.getPositionInfo().getFileName(), 16, -1, callerMain, env.getBuilder().getProof(),null, true, false, 15, 21); - LineBreakpoint secondBreakpoint = new LineBreakpoint(callerLoop.getPositionInfo().getFileName(), 10, 2, callerLoop, env.getBuilder().getProof(),null, true, false, 8, 13); - LineBreakpoint thirdBreakpoint = new LineBreakpoint(calleeMain.getPositionInfo().getFileName(), 7, -1, calleeMain, env.getBuilder().getProof(),null, true, false, 6, 9); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(firstBreakpoint, secondBreakpoint, thirdBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestLineBreakpointStopConditionSimpleWithHitCount + extends AbstractSymbolicExecutionTestCase { + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + SymbolicExecutionEnvironment env = null; + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/lineBreakpointsWithHitcountTest/test/BreakpointStopCallerAndLoop.java"; + String containerTypeName = "BreakpointStopCallerAndLoop"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/lineBreakpointsWithHitcountTest/oracle/BreakpointStop"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + IProgramMethod callerMain = + searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "main"); + IProgramMethod calleeMain = + searchProgramMethod(env.getServices(), "BreakpointStopCallee", "main"); + IProgramMethod callerLoop = + searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "loop"); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + LineBreakpoint firstBreakpoint = + new LineBreakpoint(callerMain.getPositionInfo().getFileName(), 16, -1, + callerMain, env.getBuilder().getProof(), null, true, false, 15, 21); + LineBreakpoint secondBreakpoint = + new LineBreakpoint(callerLoop.getPositionInfo().getFileName(), 10, 2, + callerLoop, env.getBuilder().getProof(), null, true, false, 8, 13); + LineBreakpoint thirdBreakpoint = + new LineBreakpoint(calleeMain.getPositionInfo().getFileName(), 7, -1, + calleeMain, env.getBuilder().getProof(), null, true, false, 6, 9); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(firstBreakpoint, secondBreakpoint, + thirdBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithLoopInvariant.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithLoopInvariant.java index f3b5cab7094..0a9db8282c1 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithLoopInvariant.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestLineBreakpointStopConditionSimpleWithLoopInvariant.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -17,56 +20,72 @@ import java.util.HashMap; -public class TestLineBreakpointStopConditionSimpleWithLoopInvariant extends AbstractSymbolicExecutionTestCase { - @Test - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment envMain=null; - SymbolicExecutionEnvironment envSomethingMain=null; - SymbolicExecutionEnvironment envSomethingLocalMain=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/lineBreakpointsWithLoopInvariantTest/test/ArrayUtil.java"; - String containerTypeName = "ArrayUtil"; - final String methodFullName = "indexOf"; - String oraclePathInkeyRepDirectoryFile = "/set/lineBreakpointsWithLoopInvariantTest/oracle/ArrayUtil"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - envMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, true, true, true, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - IProgramMethod indexOfMethod = searchProgramMethod(envMain.getServices(), containerTypeName, "indexOf"); - // Test method main() - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - LineBreakpoint mainBreakpoint = new LineBreakpoint(indexOfMethod.getPositionInfo().getFileName(), 21, -1, indexOfMethod, envMain.getBuilder().getProof(), null, true, true, 13, 26); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); - allBreakpoints.addChildren(bc); - envMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - - // Suspend at breakpoint - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - - // Finish symbolic execution - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(envMain!=null){ - envMain.dispose(); - } - if(envSomethingMain!=null){ - envSomethingMain.dispose(); - } - if(envSomethingLocalMain!=null){ - envSomethingLocalMain.dispose(); - } - } - } -} \ No newline at end of file +public class TestLineBreakpointStopConditionSimpleWithLoopInvariant + extends AbstractSymbolicExecutionTestCase { + @Test + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment envMain = null; + SymbolicExecutionEnvironment envSomethingMain = null; + SymbolicExecutionEnvironment envSomethingLocalMain = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/lineBreakpointsWithLoopInvariantTest/test/ArrayUtil.java"; + String containerTypeName = "ArrayUtil"; + final String methodFullName = "indexOf"; + String oraclePathInkeyRepDirectoryFile = + "/set/lineBreakpointsWithLoopInvariantTest/oracle/ArrayUtil"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + envMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, true, + true, true, false, false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); + IProgramMethod indexOfMethod = + searchProgramMethod(envMain.getServices(), containerTypeName, "indexOf"); + // Test method main() + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + LineBreakpoint mainBreakpoint = new LineBreakpoint( + indexOfMethod.getPositionInfo().getFileName(), 21, -1, indexOfMethod, + envMain.getBuilder().getProof(), null, true, true, 13, 26); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); + allBreakpoints.addChildren(bc); + envMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + + // Suspend at breakpoint + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + + // Finish symbolic execution + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (envMain != null) { + envMain.dispose(); + } + if (envSomethingMain != null) { + envSomethingMain.dispose(); + } + if (envSomethingLocalMain != null) { + envSomethingLocalMain.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithConditions.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithConditions.java index f0f2155d9b0..6d8a62689e0 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithConditions.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithConditions.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,86 +22,147 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; public class TestMethodBreakpointWithConditions extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment envMain=null; - SymbolicExecutionEnvironment envSomethingMain=null; - SymbolicExecutionEnvironment envSomethingLocalMain=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/methodBreakpointsWithConditionsTest/test/SimpleConditionExample.java"; - String containerTypeName = "SimpleConditionExample"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/methodBreakpointsWithConditionsTest/oracle/BreakpointStopConditionWithCondition"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - envMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - IProgramMethod main = searchProgramMethod(envMain.getServices(), "SimpleConditionExample", "main"); - // Test method main() - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - MethodBreakpoint mainBreakpoint = new MethodBreakpoint(main.getPositionInfo().getFileName(), 6, -1, main, envMain.getBuilder().getProof(), "z==-1", true, true,6,11,true,true); - - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); - allBreakpoints.addChildren(bc); - envMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - - - //Test method somethingMain() - envSomethingMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, "somethingMain", null, false, false, false, false, false, false, false, false, false, false); - IProgramMethod something = searchProgramMethod(envSomethingMain.getServices(), "SimpleConditionExample", "something"); - IProgramMethod somethingMain = searchProgramMethod(envSomethingMain.getServices(), "SimpleConditionExample", "somethingMain"); - allBreakpoints = new CompoundStopCondition(); - MethodBreakpoint somethingMainBreakpoint = new MethodBreakpoint(somethingMain.getPositionInfo().getFileName(), 13, -1, somethingMain, envSomethingMain.getBuilder().getProof(),"a==2", true, true,13,17,true, true); - MethodBreakpoint somethingBreakpoint = new MethodBreakpoint(something.getPositionInfo().getFileName(), 19, -1, something, envSomethingMain.getBuilder().getProof(),"b==3", true, true,19,21,true,true); - bc = new SymbolicExecutionBreakpointStopCondition(somethingBreakpoint, somethingMainBreakpoint); - allBreakpoints.addChildren(bc); - envSomethingMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - assertSetTreeAfterStep(envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - - //Test method somethingLocalMain() - envSomethingLocalMain = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, "somethingLocalMain", null, false, false, false, false, false, false, false, false, false, false); - IProgramMethod somethingLocal = searchProgramMethod(envSomethingLocalMain.getServices(), "SimpleConditionExample", "somethingLocal"); - IProgramMethod somethingLocalMain = searchProgramMethod(envSomethingLocalMain.getServices(), "SimpleConditionExample", "somethingLocalMain"); - allBreakpoints = new CompoundStopCondition(); - MethodBreakpoint somethingLocalBreakpoint = new MethodBreakpoint(somethingLocal.getPositionInfo().getFileName(), 30, -1, somethingLocal, envSomethingLocalMain.getBuilder().getProof(),"y==42*42||x==42", true, true,30,34,true,true); - MethodBreakpoint somethingLocalMainBreakpoint = new MethodBreakpoint(somethingLocalMain.getPositionInfo().getFileName(), 23, -1, somethingLocalMain, envSomethingLocalMain.getBuilder().getProof(),"x==42*42", true, true,23,28,true,true); - bc = new SymbolicExecutionBreakpointStopCondition(somethingLocalBreakpoint, somethingLocalMainBreakpoint); - allBreakpoints.addChildren(bc); - envSomethingLocalMain.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - assertSetTreeAfterStep(envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(envMain!=null){ - envMain.dispose(); - } - if(envSomethingMain!=null){ - envSomethingMain.dispose(); - } - if(envSomethingLocalMain!=null){ - envSomethingLocalMain.dispose(); - } - } - } -} \ No newline at end of file + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment envMain = null; + SymbolicExecutionEnvironment envSomethingMain = null; + SymbolicExecutionEnvironment envSomethingLocalMain = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/methodBreakpointsWithConditionsTest/test/SimpleConditionExample.java"; + String containerTypeName = "SimpleConditionExample"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/methodBreakpointsWithConditionsTest/oracle/BreakpointStopConditionWithCondition"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + envMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, + false, false, false, false, false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(envMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); + IProgramMethod main = + searchProgramMethod(envMain.getServices(), "SimpleConditionExample", "main"); + // Test method main() + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + MethodBreakpoint mainBreakpoint = new MethodBreakpoint( + main.getPositionInfo().getFileName(), 6, -1, main, + envMain.getBuilder().getProof(), "z==-1", true, true, 6, 11, true, true); + + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(mainBreakpoint); + allBreakpoints.addChildren(bc); + envMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envMain.getUi(), envMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + + + // Test method somethingMain() + envSomethingMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, "somethingMain", null, false, + false, false, false, false, false, false, false, false, false); + IProgramMethod something = searchProgramMethod(envSomethingMain.getServices(), + "SimpleConditionExample", "something"); + IProgramMethod somethingMain = searchProgramMethod(envSomethingMain.getServices(), + "SimpleConditionExample", "somethingMain"); + allBreakpoints = new CompoundStopCondition(); + MethodBreakpoint somethingMainBreakpoint = + new MethodBreakpoint(somethingMain.getPositionInfo().getFileName(), 13, -1, + somethingMain, envSomethingMain.getBuilder().getProof(), "a==2", true, + true, 13, 17, true, true); + MethodBreakpoint somethingBreakpoint = + new MethodBreakpoint(something.getPositionInfo().getFileName(), 19, -1, + something, envSomethingMain.getBuilder().getProof(), "b==3", true, true, + 19, 21, true, true); + bc = new SymbolicExecutionBreakpointStopCondition(somethingBreakpoint, + somethingMainBreakpoint); + allBreakpoints.addChildren(bc); + envSomethingMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + assertSetTreeAfterStep(envSomethingMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingMain.getUi(), envSomethingMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + + // Test method somethingLocalMain() + envSomethingLocalMain = createSymbolicExecutionEnvironment(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, "somethingLocalMain", null, false, + false, false, false, false, false, false, false, false, false); + IProgramMethod somethingLocal = searchProgramMethod(envSomethingLocalMain.getServices(), + "SimpleConditionExample", "somethingLocal"); + IProgramMethod somethingLocalMain = + searchProgramMethod(envSomethingLocalMain.getServices(), + "SimpleConditionExample", "somethingLocalMain"); + allBreakpoints = new CompoundStopCondition(); + MethodBreakpoint somethingLocalBreakpoint = + new MethodBreakpoint(somethingLocal.getPositionInfo().getFileName(), 30, -1, + somethingLocal, envSomethingLocalMain.getBuilder().getProof(), + "y==42*42||x==42", true, true, 30, 34, true, true); + MethodBreakpoint somethingLocalMainBreakpoint = + new MethodBreakpoint(somethingLocalMain.getPositionInfo().getFileName(), 23, -1, + somethingLocalMain, envSomethingLocalMain.getBuilder().getProof(), + "x==42*42", true, true, 23, 28, true, true); + bc = new SymbolicExecutionBreakpointStopCondition(somethingLocalBreakpoint, + somethingLocalMainBreakpoint); + allBreakpoints.addChildren(bc); + envSomethingLocalMain.getProof().getServices() + .setFactory(createNewProgramVariableCollectorFactory(bc)); + assertSetTreeAfterStep(envSomethingLocalMain.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(envSomethingLocalMain.getUi(), + envSomethingLocalMain.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (envMain != null) { + envMain.dispose(); + } + if (envSomethingMain != null) { + envSomethingMain.dispose(); + } + if (envSomethingLocalMain != null) { + envSomethingLocalMain.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithHitCount.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithHitCount.java index 7f1810f7e53..ddb71c6e7e2 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithHitCount.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestMethodBreakpointWithHitCount.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,54 +22,83 @@ import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionEnvironment; public class TestMethodBreakpointWithHitCount extends AbstractSymbolicExecutionTestCase { - @Test//weigl not prev. activated - public void testBreakpointStopCondition() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - SymbolicExecutionEnvironment env=null; - HashMap originalTacletOptions = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - try{ - // Define test settings - String javaPathInkeyRepDirectory = "/set/methodBreakpointsWithHitcountTest/test/BreakpointStopCallerAndLoop.java"; - String containerTypeName = "BreakpointStopCallerAndLoop"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/methodBreakpointsWithHitcountTest/oracle/MethodBreakpointStop"; - String oracleFileExtension = ".xml"; - // Store original settings of KeY - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - IProgramMethod callerMain = searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "main"); - IProgramMethod calleeMain = searchProgramMethod(env.getServices(), "BreakpointStopCallee", "main"); - IProgramMethod callerLoop = searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "loop"); - CompoundStopCondition allBreakpoints = new CompoundStopCondition(); - //on method call and return - MethodBreakpoint inAndOutBreakpoint = new MethodBreakpoint(callerMain.getPositionInfo().getFileName(), 15, -1, callerMain, env.getBuilder().getProof(),null, true, false, 15, 24,true,true); - //on method call with hitcount - MethodBreakpoint hitCountBreakpoint = new MethodBreakpoint(callerLoop.getPositionInfo().getFileName(), 8, 2, callerLoop, env.getBuilder().getProof(),null, true, false, 8, 13, true, false); - //on method return with hitcount - MethodBreakpoint thirdBreakpoint = new MethodBreakpoint(calleeMain.getPositionInfo().getFileName(), 6, 2, calleeMain, env.getBuilder().getProof(),null, true, false, 6, 9, false, true); - SymbolicExecutionBreakpointStopCondition bc = new SymbolicExecutionBreakpointStopCondition(inAndOutBreakpoint,hitCountBreakpoint,thirdBreakpoint); - allBreakpoints.addChildren(bc); - env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); - // Do steps - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); - stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory, allBreakpoints); + @Test // weigl not prev. activated + public void testBreakpointStopCondition() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + SymbolicExecutionEnvironment env = null; + HashMap originalTacletOptions = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + try { + // Define test settings + String javaPathInkeyRepDirectory = + "/set/methodBreakpointsWithHitcountTest/test/BreakpointStopCallerAndLoop.java"; + String containerTypeName = "BreakpointStopCallerAndLoop"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/methodBreakpointsWithHitcountTest/oracle/MethodBreakpointStop"; + String oracleFileExtension = ".xml"; + // Store original settings of KeY + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + IProgramMethod callerMain = + searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "main"); + IProgramMethod calleeMain = + searchProgramMethod(env.getServices(), "BreakpointStopCallee", "main"); + IProgramMethod callerLoop = + searchProgramMethod(env.getServices(), "BreakpointStopCallerAndLoop", "loop"); + CompoundStopCondition allBreakpoints = new CompoundStopCondition(); + // on method call and return + MethodBreakpoint inAndOutBreakpoint = new MethodBreakpoint( + callerMain.getPositionInfo().getFileName(), 15, -1, callerMain, + env.getBuilder().getProof(), null, true, false, 15, 24, true, true); + // on method call with hitcount + MethodBreakpoint hitCountBreakpoint = new MethodBreakpoint( + callerLoop.getPositionInfo().getFileName(), 8, 2, callerLoop, + env.getBuilder().getProof(), null, true, false, 8, 13, true, false); + // on method return with hitcount + MethodBreakpoint thirdBreakpoint = new MethodBreakpoint( + calleeMain.getPositionInfo().getFileName(), 6, 2, calleeMain, + env.getBuilder().getProof(), null, true, false, 6, 9, false, true); + SymbolicExecutionBreakpointStopCondition bc = + new SymbolicExecutionBreakpointStopCondition(inAndOutBreakpoint, + hitCountBreakpoint, thirdBreakpoint); + allBreakpoints.addChildren(bc); + env.getProof().getServices().setFactory(createNewProgramVariableCollectorFactory(bc)); + // Do steps + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); + stepReturnWithBreakpoints(env.getUi(), env.getBuilder(), + oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, + testCaseDirectory, allBreakpoints); - } - finally{ - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if(env!=null){ - env.dispose(); - } - } - } -} \ No newline at end of file + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepOverSymbolicExecutionTreeNodesStopCondition.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepOverSymbolicExecutionTreeNodesStopCondition.java index 8fe7033e890..a2331ab1f30 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepOverSymbolicExecutionTreeNodesStopCondition.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepOverSymbolicExecutionTreeNodesStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,55 +22,74 @@ /** * Tests for {@link StepOverSymbolicExecutionTreeNodesStopCondition} and - * {@link SymbolicExecutionGoalChooser}. To do a step over the - * {@link CompoundStopCondition} is also tested. + * {@link SymbolicExecutionGoalChooser}. To do a step over the {@link CompoundStopCondition} is also + * tested. + * * @author Martin Hentschel */ -public class TestStepOverSymbolicExecutionTreeNodesStopCondition extends AbstractSymbolicExecutionTestCase { - /** - * Does some step over tests on two branches with different number - * of symbolic execution tree nodes to make sure that the - * stop conditions works correctly in combination with the goal chooser. - */ - @Test//weigl not prev. activated - public void testStepOverOnTwoBranches() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - SymbolicExecutionEnvironment env = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - // Define test settings - String javaPathInkeyRepDirectory = "/set/stepOverOnTwoBranches/test/StepOverOnTwoBranches.java"; - String containerTypeName = "StepOverOnTwoBranches"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/stepOverOnTwoBranches/oracle/StepOverOnTwoBranches"; - String oracleFileExtension = ".xml"; - // Create proof environment for symbolic execution - try { - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, true); - // Create proof environment for symbolic execution - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - // Do steps - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // main method - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // if - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // i = 2 - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // j = 3 - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // x = valueLonger(i) - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // y = value(j) - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // z - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // zz - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // return statement - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // method return -2 - stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // end - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestStepOverSymbolicExecutionTreeNodesStopCondition + extends AbstractSymbolicExecutionTestCase { + /** + * Does some step over tests on two branches with different number of symbolic execution tree + * nodes to make sure that the stop conditions works correctly in combination with the goal + * chooser. + */ + @Test // weigl not prev. activated + public void testStepOverOnTwoBranches() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + SymbolicExecutionEnvironment env = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + // Define test settings + String javaPathInkeyRepDirectory = + "/set/stepOverOnTwoBranches/test/StepOverOnTwoBranches.java"; + String containerTypeName = "StepOverOnTwoBranches"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = + "/set/stepOverOnTwoBranches/oracle/StepOverOnTwoBranches"; + String oracleFileExtension = ".xml"; + // Create proof environment for symbolic execution + try { + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, true); + // Create proof environment for symbolic execution + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + // Do steps + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // main method + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // if + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // i = 2 + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // j = 3 + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // x = valueLonger(i) + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // y = value(j) + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // z + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // zz + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // return statement + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // method return -2 + stepOver(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // end + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepReturnSymbolicExecutionTreeNodesStopCondition.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepReturnSymbolicExecutionTreeNodesStopCondition.java index c566d720f4e..bf47d4afb1d 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepReturnSymbolicExecutionTreeNodesStopCondition.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestStepReturnSymbolicExecutionTreeNodesStopCondition.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; import java.io.IOException; @@ -19,54 +22,73 @@ /** * Tests for {@link StepReturnSymbolicExecutionTreeNodesStopCondition} and - * {@link SymbolicExecutionGoalChooser}. To do a step over the - * {@link CompoundStopCondition} is also tested. + * {@link SymbolicExecutionGoalChooser}. To do a step over the {@link CompoundStopCondition} is also + * tested. + * * @author Martin Hentschel */ -public class TestStepReturnSymbolicExecutionTreeNodesStopCondition extends AbstractSymbolicExecutionTestCase { - /** - * Does some step return tests on one branch. - */ - @Test//weigl was not prev. activated - public void testStepReturn() throws ProofInputException, IOException, ParserConfigurationException, SAXException, ProblemLoaderException { - HashMap originalTacletOptions = null; - SymbolicExecutionEnvironment env = null; - boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); - // Define test settings - String javaPathInkeyRepDirectory = "/set/stepReturnTest/test/StepReturnTest.java"; - String containerTypeName = "StepReturnTest"; - final String methodFullName = "main"; - String oraclePathInkeyRepDirectoryFile = "/set/stepReturnTest/oracle/StepReturnTest"; - String oracleFileExtension = ".xml"; - try { - originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName); - setOneStepSimplificationEnabled(null, true); - // Create proof environment for symbolic execution - env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, containerTypeName, methodFullName, null, false, false, false, false, false, false, false, false, false, false); - // Make sure that initial tree is valid - int oracleIndex = 0; - assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); - // Do steps - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // call main - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // first level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // call first level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // second level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // call second level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // third level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // call third level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // fourth level - stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // call fourth level - stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // a = a * 2 - stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // second level - stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // first level - stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, oracleFileExtension, testCaseDirectory); // end - } - finally { - setOneStepSimplificationEnabled(null, originalOneStepSimplification); - restoreTacletOptions(originalTacletOptions); - if (env != null) { - env.dispose(); - } - } - } -} \ No newline at end of file +public class TestStepReturnSymbolicExecutionTreeNodesStopCondition + extends AbstractSymbolicExecutionTestCase { + /** + * Does some step return tests on one branch. + */ + @Test // weigl was not prev. activated + public void testStepReturn() throws ProofInputException, IOException, + ParserConfigurationException, SAXException, ProblemLoaderException { + HashMap originalTacletOptions = null; + SymbolicExecutionEnvironment env = null; + boolean originalOneStepSimplification = isOneStepSimplificationEnabled(null); + // Define test settings + String javaPathInkeyRepDirectory = "/set/stepReturnTest/test/StepReturnTest.java"; + String containerTypeName = "StepReturnTest"; + final String methodFullName = "main"; + String oraclePathInkeyRepDirectoryFile = "/set/stepReturnTest/oracle/StepReturnTest"; + String oracleFileExtension = ".xml"; + try { + originalTacletOptions = setDefaultTacletOptions(testCaseDirectory, + javaPathInkeyRepDirectory, containerTypeName, methodFullName); + setOneStepSimplificationEnabled(null, true); + // Create proof environment for symbolic execution + env = createSymbolicExecutionEnvironment(testCaseDirectory, javaPathInkeyRepDirectory, + containerTypeName, methodFullName, null, false, false, false, false, false, + false, false, false, false, false); + // Make sure that initial tree is valid + int oracleIndex = 0; + assertSetTreeAfterStep(env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); + // Do steps + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // call main + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // first level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // call first level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // second level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // call second level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // third level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // call third level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // fourth level + stepInto(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, ++oracleIndex, + oracleFileExtension, testCaseDirectory); // call fourth level + stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); // a = a * 2 + stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); // second level + stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); // first level + stepReturn(env.getUi(), env.getBuilder(), oraclePathInkeyRepDirectoryFile, + ++oracleIndex, oracleFileExtension, testCaseDirectory); // end + } finally { + setOneStepSimplificationEnabled(null, originalOneStepSimplification); + restoreTacletOptions(originalTacletOptions); + if (env != null) { + env.dispose(); + } + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestSymbolicExecutionStrategy.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestSymbolicExecutionStrategy.java index 28758f1c2bb..ef82553d18a 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestSymbolicExecutionStrategy.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/strategy/TestSymbolicExecutionStrategy.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.strategy; @@ -9,790 +12,391 @@ /** * Tests for {@link SymbolicExecutionStrategy} + * * @author Martin Hentschel */ @TestMethodOrder(MethodOrderer.MethodName.class) public class TestSymbolicExecutionStrategy extends AbstractSymbolicExecutionTestCase { - /** - * Tests example: /set/blockContractPreconditionNotVerified - */ - @Test - public void testBlockContractPreconditionNotVerified_SymbolicExecution() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractPreconditionNotVerified/test/BlockContractPreconditionNotVerified.java", - "BlockContractPreconditionNotVerified", - "main", - null, - "/set/blockContractPreconditionNotVerified/oracle/BlockContractPreconditionNotVerified_symbolicExecution.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithExceptionPostconditionNotVerified - */ - @Test public void testBlockContractWithExceptionPostconditionNotVerified_SymbolicExecution() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithExceptionPostconditionNotVerified/test/BlockContractWithExceptionPostconditionNotVerified.java", - "BlockContractWithExceptionPostconditionNotVerified", - "main", - null, - "/set/blockContractWithExceptionPostconditionNotVerified/oracle/BlockContractWithExceptionPostconditionNotVerified_symbolicExecution.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithException - */ - @Test public void testBlockContractWithException_SymbolicExecution() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithException/test/BlockContractWithException.java", - "BlockContractWithException", - "main", - null, - "/set/blockContractWithException/oracle/BlockContractWithException_symbolicExecution.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithReturnPostconditionNotVerified - */ - @Test public void testBlockContractWithReturnPostconditionNotVerified_SymbolicExecution() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithReturnPostconditionNotVerified/test/BlockContractWithReturnPostconditionNotVerified.java", - "BlockContractWithReturnPostconditionNotVerified", - "main", - null, - "/set/blockContractWithReturnPostconditionNotVerified/oracle/BlockContractWithReturnPostconditionNotVerified_symbolicExecution.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false); - } - - /** - * Tests example: /set/blockContractWithReturn - */ - @Test public void testBlockContractWithReturn_SymbolicExecution() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/blockContractWithReturn/test/BlockContractWithReturn.java", - "BlockContractWithReturn", - "main", - null, - "/set/blockContractWithReturn/oracle/BlockContractWithReturn_symbolicExecution.xml", - false, - false, - false, - false, - ALL_IN_ONE_RUN, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false); - } + /** + * Tests example: /set/blockContractPreconditionNotVerified + */ + @Test + public void testBlockContractPreconditionNotVerified_SymbolicExecution() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractPreconditionNotVerified/test/BlockContractPreconditionNotVerified.java", + "BlockContractPreconditionNotVerified", "main", null, + "/set/blockContractPreconditionNotVerified/oracle/BlockContractPreconditionNotVerified_symbolicExecution.xml", + false, false, false, false, ALL_IN_ONE_RUN, false, false, false, true, false, false, + false, false, false, false); + } - /** - * Tests example: /set/nonExecutionBranchHidingArraysIndexOf - */ - @Test public void testNonExecutionBranchHidingArraysIndexOf_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingArraysIndexOf/test/Arrays.java", - "Arrays", - "indexOf", - "array != null && filter != null && \\invariant_for(filter)", - "/set/nonExecutionBranchHidingArraysIndexOf/oracle/Arrays_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } - /** - * Tests example: /set/nonExecutionBranchHidingArraysIndexOf - */ - @Test public void testNonExecutionBranchHidingArraysIndexOf_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingArraysIndexOf/test/Arrays.java", - "Arrays", - "indexOf", - "array != null && filter != null && \\invariant_for(filter)", - "/set/nonExecutionBranchHidingArraysIndexOf/oracle/Arrays_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery - */ - @Test public void testNonExecutionBranchHidingLoopInvariantWithSplittingQuery_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/test/LoopInvariantWithSplittingQuery.java", - "LoopInvariantWithSplittingQuery", - "main", - null, - "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/oracle/LoopInvariantWithSplittingQuery_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery - */ - @Test public void testNonExecutionBranchHidingLoopInvariantWithSplittingQuery_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/test/LoopInvariantWithSplittingQuery.java", - "LoopInvariantWithSplittingQuery", - "main", - null, - "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/oracle/LoopInvariantWithSplittingQuery_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } - - /** - * Tests example: /set/nonExecutionBranchHidingQueryInPrecondition - */ - @Test public void testNonExecutionBranchHidingQueryInPrecondition_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryInPrecondition/test/QueryInPrecondition.java", - "QueryInPrecondition", - "main", - null, - "/set/nonExecutionBranchHidingQueryInPrecondition/oracle/QueryInPrecondition_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/blockContractWithExceptionPostconditionNotVerified + */ + @Test + public void testBlockContractWithExceptionPostconditionNotVerified_SymbolicExecution() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithExceptionPostconditionNotVerified/test/BlockContractWithExceptionPostconditionNotVerified.java", + "BlockContractWithExceptionPostconditionNotVerified", "main", null, + "/set/blockContractWithExceptionPostconditionNotVerified/oracle/BlockContractWithExceptionPostconditionNotVerified_symbolicExecution.xml", + false, false, false, false, ALL_IN_ONE_RUN, false, false, false, true, false, false, + false, false, false, false); + } - /** - * Tests example: /set/nonExecutionBranchHidingQueryInPrecondition - */ - @Test public void testNonExecutionBranchHidingQueryInPrecondition_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryInPrecondition/test/QueryInPrecondition.java", - "QueryInPrecondition", - "main", - null, - "/set/nonExecutionBranchHidingQueryInPrecondition/oracle/QueryInPrecondition_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/blockContractWithException + */ + @Test + public void testBlockContractWithException_SymbolicExecution() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithException/test/BlockContractWithException.java", + "BlockContractWithException", "main", null, + "/set/blockContractWithException/oracle/BlockContractWithException_symbolicExecution.xml", + false, false, false, false, ALL_IN_ONE_RUN, false, false, false, true, false, false, + false, false, false, false); + } - /** - * Tests example: /set/nonExecutionBranchHidingComplexPrecondition - */ - @Test public void testNonExecutionBranchHidingComplexPrecondition_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingComplexPrecondition/test/ComplexPrecondition.java", - "ComplexPrecondition", - "main", - null, - "/set/nonExecutionBranchHidingComplexPrecondition/oracle/ComplexPrecondition_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/blockContractWithReturnPostconditionNotVerified + */ + @Test + public void testBlockContractWithReturnPostconditionNotVerified_SymbolicExecution() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithReturnPostconditionNotVerified/test/BlockContractWithReturnPostconditionNotVerified.java", + "BlockContractWithReturnPostconditionNotVerified", "main", null, + "/set/blockContractWithReturnPostconditionNotVerified/oracle/BlockContractWithReturnPostconditionNotVerified_symbolicExecution.xml", + false, false, false, false, ALL_IN_ONE_RUN, false, false, false, true, false, false, + false, false, false, false); + } - /** - * Tests example: /set/nonExecutionBranchHidingComplexPrecondition - */ - @Test public void testNonExecutionBranchHidingComplexPrecondition_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingComplexPrecondition/test/ComplexPrecondition.java", - "ComplexPrecondition", - "main", - null, - "/set/nonExecutionBranchHidingComplexPrecondition/oracle/ComplexPrecondition_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/blockContractWithReturn + */ + @Test + public void testBlockContractWithReturn_SymbolicExecution() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/blockContractWithReturn/test/BlockContractWithReturn.java", + "BlockContractWithReturn", "main", null, + "/set/blockContractWithReturn/oracle/BlockContractWithReturn_symbolicExecution.xml", + false, false, false, false, ALL_IN_ONE_RUN, false, false, false, true, false, false, + false, false, false, false); + } - /** - * Tests example: /set/nonExecutionBranchHidingQueryWithSideEffects - */ - @Test public void testNonExecutionBranchHidingQueryWithSideEffects_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryWithSideEffects/test/QueryWithSideEffects.java", - "QueryWithSideEffects", - "main", - null, - "/set/nonExecutionBranchHidingQueryWithSideEffects/oracle/QueryWithSideEffects_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingArraysIndexOf + */ + @Test + public void testNonExecutionBranchHidingArraysIndexOf_hiding_side_proof() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingArraysIndexOf/test/Arrays.java", "Arrays", "indexOf", + "array != null && filter != null && \\invariant_for(filter)", + "/set/nonExecutionBranchHidingArraysIndexOf/oracle/Arrays_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingQueryWithSideEffects - */ - @Test public void testNonExecutionBranchHidingQueryWithSideEffects_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryWithSideEffects/test/QueryWithSideEffects.java", - "QueryWithSideEffects", - "main", - null, - "/set/nonExecutionBranchHidingQueryWithSideEffects/oracle/QueryWithSideEffects_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingArraysIndexOf + */ + @Test + public void testNonExecutionBranchHidingArraysIndexOf_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingArraysIndexOf/test/Arrays.java", "Arrays", "indexOf", + "array != null && filter != null && \\invariant_for(filter)", + "/set/nonExecutionBranchHidingArraysIndexOf/oracle/Arrays_hiding_off.xml", false, + false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, false, + false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingQueryWithFields - */ - @Test public void testNonExecutionBranchHidingQueryWithFields_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryWithFields/test/QueryWithFields.java", - "QueryWithFields", - "main", - null, - "/set/nonExecutionBranchHidingQueryWithFields/oracle/QueryWithFields_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery + */ + @Test + public void testNonExecutionBranchHidingLoopInvariantWithSplittingQuery_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/test/LoopInvariantWithSplittingQuery.java", + "LoopInvariantWithSplittingQuery", "main", null, + "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/oracle/LoopInvariantWithSplittingQuery_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingQueryWithFields - */ - @Test public void testNonExecutionBranchHidingQueryWithFields_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingQueryWithFields/test/QueryWithFields.java", - "QueryWithFields", - "main", - null, - "/set/nonExecutionBranchHidingQueryWithFields/oracle/QueryWithFields_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery + */ + @Test + public void testNonExecutionBranchHidingLoopInvariantWithSplittingQuery_hiding_off() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/test/LoopInvariantWithSplittingQuery.java", + "LoopInvariantWithSplittingQuery", "main", null, + "/set/nonExecutionBranchHidingLoopInvariantWithSplittingQuery/oracle/LoopInvariantWithSplittingQuery_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleObjectQuery - */ - @Test public void testNonExecutionBranchHidingSimpleObjectQuery_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleObjectQuery/test/SimpleObjectQuery.java", - "SimpleObjectQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleObjectQuery/oracle/SimpleObjectQuery_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryInPrecondition + */ + @Test + public void testNonExecutionBranchHidingQueryInPrecondition_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryInPrecondition/test/QueryInPrecondition.java", + "QueryInPrecondition", "main", null, + "/set/nonExecutionBranchHidingQueryInPrecondition/oracle/QueryInPrecondition_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleObjectQuery - */ - @Test public void testNonExecutionBranchHidingSimpleObjectQuery_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleObjectQuery/test/SimpleObjectQuery.java", - "SimpleObjectQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleObjectQuery/oracle/SimpleObjectQuery_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryInPrecondition + */ + @Test + public void testNonExecutionBranchHidingQueryInPrecondition_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryInPrecondition/test/QueryInPrecondition.java", + "QueryInPrecondition", "main", null, + "/set/nonExecutionBranchHidingQueryInPrecondition/oracle/QueryInPrecondition_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleBooleanQuery - */ - @Test public void testNonExecutionBranchHidingSimpleBooleanQuery_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleBooleanQuery/test/SimpleBooleanQuery.java", - "SimpleBooleanQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleBooleanQuery/oracle/SimpleBooleanQuery_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingComplexPrecondition + */ + @Test + public void testNonExecutionBranchHidingComplexPrecondition_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingComplexPrecondition/test/ComplexPrecondition.java", + "ComplexPrecondition", "main", null, + "/set/nonExecutionBranchHidingComplexPrecondition/oracle/ComplexPrecondition_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleBooleanQuery - */ - @Test public void testNonExecutionBranchHidingSimpleBooleanQuery_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleBooleanQuery/test/SimpleBooleanQuery.java", - "SimpleBooleanQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleBooleanQuery/oracle/SimpleBooleanQuery_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingComplexPrecondition + */ + @Test + public void testNonExecutionBranchHidingComplexPrecondition_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingComplexPrecondition/test/ComplexPrecondition.java", + "ComplexPrecondition", "main", null, + "/set/nonExecutionBranchHidingComplexPrecondition/oracle/ComplexPrecondition_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery - */ - @Test public void testNonExecutionBranchHidingSimpleIntQuery_mainWithSymbolicUpdates_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", - "SimpleIntQuery", - "mainWithSymbolicUpdates", - null, - "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_mainWithSymbolicUpdates_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryWithSideEffects + */ + @Test + public void testNonExecutionBranchHidingQueryWithSideEffects_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryWithSideEffects/test/QueryWithSideEffects.java", + "QueryWithSideEffects", "main", null, + "/set/nonExecutionBranchHidingQueryWithSideEffects/oracle/QueryWithSideEffects_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery - */ - @Test public void testNonExecutionBranchHidingSimpleIntQuery_mainWithUpdates_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", - "SimpleIntQuery", - "mainWithUpdates", - null, - "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_mainWithUpdates_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryWithSideEffects + */ + @Test + public void testNonExecutionBranchHidingQueryWithSideEffects_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryWithSideEffects/test/QueryWithSideEffects.java", + "QueryWithSideEffects", "main", null, + "/set/nonExecutionBranchHidingQueryWithSideEffects/oracle/QueryWithSideEffects_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery - */ - @Test public void testNonExecutionBranchHidingSimpleIntQuery_main_hiding_side_proof() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", - "SimpleIntQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_main_hiding_side_proof.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - true, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryWithFields + */ + @Test + public void testNonExecutionBranchHidingQueryWithFields_hiding_side_proof() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryWithFields/test/QueryWithFields.java", + "QueryWithFields", "main", null, + "/set/nonExecutionBranchHidingQueryWithFields/oracle/QueryWithFields_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery - */ - @Test public void testNonExecutionBranchHidingSimpleIntQuery_main_hiding_off() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", - "SimpleIntQuery", - "main", - null, - "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_main_hiding_off.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - true, - true, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingQueryWithFields + */ + @Test + public void testNonExecutionBranchHidingQueryWithFields_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingQueryWithFields/test/QueryWithFields.java", + "QueryWithFields", "main", null, + "/set/nonExecutionBranchHidingQueryWithFields/oracle/QueryWithFields_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/aliasTest - */ - @Test public void testAliasTest_Array_AliasChecksNever() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/aliasTest/test/AliasTest.java", - "AliasTest", - "array", - "w != null && array != null && array.length == 2 && array[0] != null && array[1] != null", - "/set/aliasTest/oracle/AliasTest_array_never.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingSimpleObjectQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleObjectQuery_hiding_side_proof() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleObjectQuery/test/SimpleObjectQuery.java", + "SimpleObjectQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleObjectQuery/oracle/SimpleObjectQuery_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/aliasTest - */ - @Test public void testAliasTest_Array_AliasChecksImmediately() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/aliasTest/test/AliasTest.java", - "AliasTest", - "array", - "w != null && array != null && array.length == 2 && array[0] != null && array[1] != null", - "/set/aliasTest/oracle/AliasTest_array_immediately.xml", - false, - false, - false, - true, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - true, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingSimpleObjectQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleObjectQuery_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleObjectQuery/test/SimpleObjectQuery.java", + "SimpleObjectQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleObjectQuery/oracle/SimpleObjectQuery_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } - /** - * Tests example: /set/aliasTest - */ - @Test public void testAliasTest_Objects_AliasChecksNever() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/aliasTest/test/AliasTest.java", - "AliasTest", - "main", - "a != null && b != null", - "/set/aliasTest/oracle/AliasTest_main_never.xml", - false, - true, - false, - true, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true); - } + /** + * Tests example: /set/nonExecutionBranchHidingSimpleBooleanQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleBooleanQuery_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleBooleanQuery/test/SimpleBooleanQuery.java", + "SimpleBooleanQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleBooleanQuery/oracle/SimpleBooleanQuery_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } - /** - * Tests example: /set/aliasTest - */ - @Test public void testAliasTest_Objects_AliasChecksImmediately() throws Exception { - doSETTestAndDispose(testCaseDirectory, - "/set/aliasTest/test/AliasTest.java", - "AliasTest", - "main", - "a != null && b != null", - "/set/aliasTest/oracle/AliasTest_main_immediately.xml", - false, - true, - false, - true, - ALL_IN_ONE_RUN, - false, - false, - false, - false, - false, - true, - false, - false, - false, - true); - } -} \ No newline at end of file + /** + * Tests example: /set/nonExecutionBranchHidingSimpleBooleanQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleBooleanQuery_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleBooleanQuery/test/SimpleBooleanQuery.java", + "SimpleBooleanQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleBooleanQuery/oracle/SimpleBooleanQuery_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleIntQuery_mainWithSymbolicUpdates_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", + "SimpleIntQuery", "mainWithSymbolicUpdates", null, + "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_mainWithSymbolicUpdates_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } + + /** + * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleIntQuery_mainWithUpdates_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", + "SimpleIntQuery", "mainWithUpdates", null, + "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_mainWithUpdates_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } + + /** + * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleIntQuery_main_hiding_side_proof() + throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", + "SimpleIntQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_main_hiding_side_proof.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, true, false, + false, false, false, true); + } + + /** + * Tests example: /set/nonExecutionBranchHidingSimpleIntQuery + */ + @Test + public void testNonExecutionBranchHidingSimpleIntQuery_main_hiding_off() throws Exception { + doSETTestAndDispose(testCaseDirectory, + "/set/nonExecutionBranchHidingSimpleIntQuery/test/SimpleIntQuery.java", + "SimpleIntQuery", "main", null, + "/set/nonExecutionBranchHidingSimpleIntQuery/oracle/SimpleIntQuery_main_hiding_off.xml", + false, false, false, true, ALL_IN_ONE_RUN, false, true, true, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/aliasTest + */ + @Test + public void testAliasTest_Array_AliasChecksNever() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/aliasTest/test/AliasTest.java", "AliasTest", + "array", + "w != null && array != null && array.length == 2 && array[0] != null && array[1] != null", + "/set/aliasTest/oracle/AliasTest_array_never.xml", false, false, false, true, + ALL_IN_ONE_RUN, false, false, false, false, false, false, false, false, false, + true); + } + + /** + * Tests example: /set/aliasTest + */ + @Test + public void testAliasTest_Array_AliasChecksImmediately() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/aliasTest/test/AliasTest.java", "AliasTest", + "array", + "w != null && array != null && array.length == 2 && array[0] != null && array[1] != null", + "/set/aliasTest/oracle/AliasTest_array_immediately.xml", false, false, false, true, + ALL_IN_ONE_RUN, false, false, false, false, false, true, false, false, false, true); + } + + /** + * Tests example: /set/aliasTest + */ + @Test + public void testAliasTest_Objects_AliasChecksNever() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/aliasTest/test/AliasTest.java", "AliasTest", + "main", "a != null && b != null", "/set/aliasTest/oracle/AliasTest_main_never.xml", + false, true, false, true, ALL_IN_ONE_RUN, false, false, false, false, false, false, + false, false, false, true); + } + + /** + * Tests example: /set/aliasTest + */ + @Test + public void testAliasTest_Objects_AliasChecksImmediately() throws Exception { + doSETTestAndDispose(testCaseDirectory, "/set/aliasTest/test/AliasTest.java", "AliasTest", + "main", "a != null && b != null", + "/set/aliasTest/oracle/AliasTest_main_immediately.xml", false, true, false, true, + ALL_IN_ONE_RUN, false, false, false, false, false, true, false, false, false, true); + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestDefaultEntry.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestDefaultEntry.java index f4c08097755..cd1ec1d26da 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestDefaultEntry.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestDefaultEntry.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.util; import de.uka.ilkd.key.symbolic_execution.util.DefaultEntry; @@ -10,20 +13,21 @@ /** * Tests for {@link DefaultEntry}. + * * @author Martin Hentschel */ public class TestDefaultEntry { - /** - * Tests {@link DefaultEntry#getKey()}, {@link DefaultEntry#getValue()} and - * {@link DefaultEntry#setValue(Object)}. - */ - @Test - public void testGetterAndSetter() { - Entry entry = new DefaultEntry<>("A", "B"); - assertEquals("A", entry.getKey()); - assertEquals("B", entry.getValue()); - entry.setValue("C"); - assertEquals("A", entry.getKey()); - assertEquals("C", entry.getValue()); - } -} \ No newline at end of file + /** + * Tests {@link DefaultEntry#getKey()}, {@link DefaultEntry#getValue()} and + * {@link DefaultEntry#setValue(Object)}. + */ + @Test + public void testGetterAndSetter() { + Entry entry = new DefaultEntry<>("A", "B"); + assertEquals("A", entry.getKey()); + assertEquals("B", entry.getValue()); + entry.setValue("C"); + assertEquals("A", entry.getKey()); + assertEquals("C", entry.getValue()); + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestEqualsHashCodeResetter.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestEqualsHashCodeResetter.java index 4706a1da4d7..05908a2568a 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestEqualsHashCodeResetter.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestEqualsHashCodeResetter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.util; import java.util.HashMap; @@ -13,256 +16,260 @@ /** * Tests for {@link EqualsHashCodeResetter} + * * @author Martin Hentschel */ public class TestEqualsHashCodeResetter { - /** - * Tests {@link EqualsHashCodeResetter#getWrappedElement()}. - */ - @Test - public void testGetWrappedElement() { - // Create model - String a1 = "a"; - String a2 = "a"; - String b = "b"; - MyBean a1b = new MyBean(a1); - MyBean a2b = new MyBean(a2); - MyBean bb = new MyBean(b); - EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); - EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); - EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r - EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); - EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); - // Test wrapped elements - assertSame(a1b, a1r.getWrappedElement()); - assertSame(a2b, a2r.getWrappedElement()); - assertSame(a1b, a1ar.getWrappedElement()); - assertSame(bb, br.getWrappedElement()); - Assertions.assertNull(nullr.getWrappedElement()); - } - - /** - * Tests {@link EqualsHashCodeResetter#equals(Object)} by direct comparison - * and used in a {@link LinkedHashSet}. - */ - @Test public void testEquals() { - // Create model - String a1 = "a"; - String a2 = "a"; - String b = "b"; - MyBean a1b = new MyBean(a1); - MyBean a2b = new MyBean(a2); - MyBean bb = new MyBean(b); - EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); - EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); - EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r - EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); - EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); - // Test equals on bean - assertEquals(a1b, a1b); - assertEquals(a1b, a2b); // Equals is overwritten - assertNotEquals(a1b, bb); - assertEquals(a2b, a2b); - assertNotEquals(a2b, bb); - assertEquals(bb, bb); - // Test equals on bean with resetter - assertNotEquals(a1b, a1r); - assertNotEquals(a1b, a2r); - assertNotEquals(a1b, a1ar); - assertNotEquals(a1b, br); - assertNotEquals(a1b, nullr); - assertNotEquals(a2b, a1r); - assertNotEquals(a2b, a2r); - assertNotEquals(a2b, a1ar); - assertNotEquals(a2b, br); - assertNotEquals(a2b, nullr); - assertNotEquals(bb, a1r); - assertNotEquals(bb, a2r); - assertNotEquals(bb, a1ar); - assertNotEquals(bb, br); - assertNotEquals(bb, nullr); - // Test equals on resetter - assertEquals(a1r, a1r); - assertNotEquals(a1r, a2r); // Equals is no longer overwritten - assertEquals(a1r, a1ar); - assertNotEquals(a1r, br); - assertNotEquals(a1r, nullr); - assertEquals(a2r, a2r); - assertNotEquals(a2r, a1ar); - assertNotEquals(a2r, br); - assertNotEquals(a2r, nullr); - assertEquals(a1ar, a1ar); - assertNotEquals(a1ar, br); - assertNotEquals(a1ar, nullr); - assertEquals(br, br); - assertNotEquals(br, nullr); - assertEquals(nullr, nullr); - // Test equals on resetter with bean - assertNotEquals(a1r, a1b); - assertNotEquals(a1r, a2b); - assertNotEquals(a1r, bb); - assertNotEquals(a2r, a1b); - assertNotEquals(a2r, a2b); - assertNotEquals(a2r, bb); - assertNotEquals(a1ar, a1b); - assertNotEquals(a1ar, a2b); - assertNotEquals(a1ar, bb); - assertNotEquals(br, a1b); - assertNotEquals(br, a2b); - assertNotEquals(br, bb); - assertNotEquals(nullr, a1b); - assertNotEquals(nullr, a2b); - assertNotEquals(nullr, bb); - // Test bean in LinkedHashSet - Set beanSet = new LinkedHashSet<>(); - beanSet.add(a1b); - beanSet.add(a2b); // Replaces existing element a1b - beanSet.add(bb); - assertEquals(2, beanSet.size()); - Assertions.assertTrue(beanSet.contains(a1b)); - Assertions.assertTrue(beanSet.contains(a2b)); - Assertions.assertTrue(beanSet.contains(bb)); - // Test resetter in LinkedHashSet - Set> set = new LinkedHashSet<>(); - set.add(a1r); - set.add(a2r); - set.add(br); - assertEquals(3, set.size()); - Assertions.assertTrue(set.contains(a1r)); - Assertions.assertTrue(set.contains(a2r)); - Assertions.assertTrue(set.contains(a1ar)); - Assertions.assertTrue(set.contains(br)); - } - - /** - * Tests {@link EqualsHashCodeResetter#hashCode()} by direct comparison - * and used in a {@link HashMap}. - */ - @Test public void testHashCode() { - // Create model - String a1 = "a"; - String a2 = "a"; - String b = "b"; - MyBean a1b = new MyBean(a1); - MyBean a2b = new MyBean(a2); - MyBean bb = new MyBean(b); - EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); - EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); - EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r - EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); - EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); - // Compare hashcodes on bean - assertEquals(a1b.hashCode(), a1b.hashCode()); - assertEquals(a1b.hashCode(), a2b.hashCode()); // Hashcode is overwritten - assertNotEquals(a1b.hashCode(), bb.hashCode()); - assertEquals(a2b.hashCode(), a2b.hashCode()); - assertNotEquals(a2b.hashCode(), bb.hashCode()); - assertEquals(bb.hashCode(), bb.hashCode()); - // Compare hashcodes on bean with resetter - assertNotEquals(a1b.hashCode(), a1r.hashCode()); - assertNotEquals(a1b.hashCode(), a2r.hashCode()); - assertNotEquals(a1b.hashCode(), a1ar.hashCode()); - assertNotEquals(a1b.hashCode(), br.hashCode()); - assertNotEquals(a1b.hashCode(), nullr.hashCode()); - assertNotEquals(a2b.hashCode(), a1r.hashCode()); - assertNotEquals(a2b.hashCode(), a2r.hashCode()); - assertNotEquals(a2b.hashCode(), a1ar.hashCode()); - assertNotEquals(a2b.hashCode(), br.hashCode()); - assertNotEquals(a2b.hashCode(), nullr.hashCode()); - assertNotEquals(bb.hashCode(), a1r.hashCode()); - assertNotEquals(bb.hashCode(), a2r.hashCode()); - assertNotEquals(bb.hashCode(), a1ar.hashCode()); - assertNotEquals(bb.hashCode(), br.hashCode()); - assertNotEquals(bb.hashCode(), nullr.hashCode()); - // Compare hashcodes on resetter - assertEquals(a1r.hashCode(), a1r.hashCode()); - assertNotEquals(a1r.hashCode(), a2r.hashCode()); // Hashcode is no longer overwritten - assertEquals(a1r.hashCode(), a1ar.hashCode()); - assertNotEquals(a1r.hashCode(), br.hashCode()); - assertNotEquals(a1r.hashCode(), nullr.hashCode()); - assertEquals(a2r.hashCode(), a2r.hashCode()); - assertNotEquals(a2r.hashCode(), a1ar.hashCode()); - assertNotEquals(a2r.hashCode(), br.hashCode()); - assertNotEquals(a2r.hashCode(), nullr.hashCode()); - assertEquals(a1ar.hashCode(), a1ar.hashCode()); - assertNotEquals(a1ar.hashCode(), br.hashCode()); - assertNotEquals(a1ar.hashCode(), nullr.hashCode()); - assertEquals(br.hashCode(), br.hashCode()); - assertNotEquals(br.hashCode(), nullr.hashCode()); - assertEquals(nullr.hashCode(), nullr.hashCode()); - // Compare hashcodes on resetter with bean - assertNotEquals(a1r.hashCode(), a1b.hashCode()); - assertNotEquals(a1r.hashCode(), a2b.hashCode()); - assertNotEquals(a1r.hashCode(), bb.hashCode()); - assertNotEquals(a2r.hashCode(), a1b.hashCode()); - assertNotEquals(a2r.hashCode(), a2b.hashCode()); - assertNotEquals(a2r.hashCode(), bb.hashCode()); - assertNotEquals(a1ar.hashCode(), a1b.hashCode()); - assertNotEquals(a1ar.hashCode(), a2b.hashCode()); - assertNotEquals(a1ar.hashCode(), bb.hashCode()); - assertNotEquals(br.hashCode(), a1b.hashCode()); - assertNotEquals(br.hashCode(), a2b.hashCode()); - assertNotEquals(br.hashCode(), bb.hashCode()); - assertNotEquals(nullr.hashCode(), a1b.hashCode()); - assertNotEquals(nullr.hashCode(), a2b.hashCode()); - assertNotEquals(nullr.hashCode(), bb.hashCode()); - // Test bean in HashMap - Map beanMap = new HashMap<>(); - beanMap.put(a1b, "a1rValue"); - beanMap.put(a2b, "a2rValue"); // Overwrites existing value "a1rValue" - beanMap.put(bb, "brValue"); - assertEquals("a2rValue", beanMap.get(a1b)); - assertEquals("a2rValue", beanMap.get(a2b)); - assertEquals("brValue", beanMap.get(bb)); - // Test resetter in HashMap - Map, String> map = new HashMap<>(); - map.put(a1r, "a1rValue"); - map.put(a2r, "a2rValue"); - map.put(br, "brValue"); - assertEquals("a1rValue", map.get(a1r)); - assertEquals("a2rValue", map.get(a2r)); - assertEquals("a1rValue", map.get(a1ar)); - assertEquals("brValue", map.get(br)); - } - - /** - * Utility class used in tests. - * @author Martin Hentschel - */ - private static class MyBean { - /** - * A value. - */ - private final String value; + /** + * Tests {@link EqualsHashCodeResetter#getWrappedElement()}. + */ + @Test + public void testGetWrappedElement() { + // Create model + String a1 = "a"; + String a2 = "a"; + String b = "b"; + MyBean a1b = new MyBean(a1); + MyBean a2b = new MyBean(a2); + MyBean bb = new MyBean(b); + EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); + EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); + EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r + EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); + EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); + // Test wrapped elements + assertSame(a1b, a1r.getWrappedElement()); + assertSame(a2b, a2r.getWrappedElement()); + assertSame(a1b, a1ar.getWrappedElement()); + assertSame(bb, br.getWrappedElement()); + Assertions.assertNull(nullr.getWrappedElement()); + } - /** - * Constructor. - * @param value A value. - */ - public MyBean(String value) { - assertNotNull(value); - this.value = value; - } + /** + * Tests {@link EqualsHashCodeResetter#equals(Object)} by direct comparison and used in a + * {@link LinkedHashSet}. + */ + @Test + public void testEquals() { + // Create model + String a1 = "a"; + String a2 = "a"; + String b = "b"; + MyBean a1b = new MyBean(a1); + MyBean a2b = new MyBean(a2); + MyBean bb = new MyBean(b); + EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); + EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); + EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r + EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); + EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); + // Test equals on bean + assertEquals(a1b, a1b); + assertEquals(a1b, a2b); // Equals is overwritten + assertNotEquals(a1b, bb); + assertEquals(a2b, a2b); + assertNotEquals(a2b, bb); + assertEquals(bb, bb); + // Test equals on bean with resetter + assertNotEquals(a1b, a1r); + assertNotEquals(a1b, a2r); + assertNotEquals(a1b, a1ar); + assertNotEquals(a1b, br); + assertNotEquals(a1b, nullr); + assertNotEquals(a2b, a1r); + assertNotEquals(a2b, a2r); + assertNotEquals(a2b, a1ar); + assertNotEquals(a2b, br); + assertNotEquals(a2b, nullr); + assertNotEquals(bb, a1r); + assertNotEquals(bb, a2r); + assertNotEquals(bb, a1ar); + assertNotEquals(bb, br); + assertNotEquals(bb, nullr); + // Test equals on resetter + assertEquals(a1r, a1r); + assertNotEquals(a1r, a2r); // Equals is no longer overwritten + assertEquals(a1r, a1ar); + assertNotEquals(a1r, br); + assertNotEquals(a1r, nullr); + assertEquals(a2r, a2r); + assertNotEquals(a2r, a1ar); + assertNotEquals(a2r, br); + assertNotEquals(a2r, nullr); + assertEquals(a1ar, a1ar); + assertNotEquals(a1ar, br); + assertNotEquals(a1ar, nullr); + assertEquals(br, br); + assertNotEquals(br, nullr); + assertEquals(nullr, nullr); + // Test equals on resetter with bean + assertNotEquals(a1r, a1b); + assertNotEquals(a1r, a2b); + assertNotEquals(a1r, bb); + assertNotEquals(a2r, a1b); + assertNotEquals(a2r, a2b); + assertNotEquals(a2r, bb); + assertNotEquals(a1ar, a1b); + assertNotEquals(a1ar, a2b); + assertNotEquals(a1ar, bb); + assertNotEquals(br, a1b); + assertNotEquals(br, a2b); + assertNotEquals(br, bb); + assertNotEquals(nullr, a1b); + assertNotEquals(nullr, a2b); + assertNotEquals(nullr, bb); + // Test bean in LinkedHashSet + Set beanSet = new LinkedHashSet<>(); + beanSet.add(a1b); + beanSet.add(a2b); // Replaces existing element a1b + beanSet.add(bb); + assertEquals(2, beanSet.size()); + Assertions.assertTrue(beanSet.contains(a1b)); + Assertions.assertTrue(beanSet.contains(a2b)); + Assertions.assertTrue(beanSet.contains(bb)); + // Test resetter in LinkedHashSet + Set> set = new LinkedHashSet<>(); + set.add(a1r); + set.add(a2r); + set.add(br); + assertEquals(3, set.size()); + Assertions.assertTrue(set.contains(a1r)); + Assertions.assertTrue(set.contains(a2r)); + Assertions.assertTrue(set.contains(a1ar)); + Assertions.assertTrue(set.contains(br)); + } - /** - * Overwritten to make {@link MyBean}s equal if they have the same value. - */ - @Override - public boolean equals(Object obj) { - if (obj instanceof MyBean) { - return value.equals(((MyBean)obj).value); - } - else { - return false; - } - } + /** + * Tests {@link EqualsHashCodeResetter#hashCode()} by direct comparison and used in a + * {@link HashMap}. + */ + @Test + public void testHashCode() { + // Create model + String a1 = "a"; + String a2 = "a"; + String b = "b"; + MyBean a1b = new MyBean(a1); + MyBean a2b = new MyBean(a2); + MyBean bb = new MyBean(b); + EqualsHashCodeResetter a1r = new EqualsHashCodeResetter<>(a1b); + EqualsHashCodeResetter a2r = new EqualsHashCodeResetter<>(a2b); + EqualsHashCodeResetter a1ar = new EqualsHashCodeResetter<>(a1b); // Alias of a1r + EqualsHashCodeResetter br = new EqualsHashCodeResetter<>(bb); + EqualsHashCodeResetter nullr = new EqualsHashCodeResetter<>(null); + // Compare hashcodes on bean + assertEquals(a1b.hashCode(), a1b.hashCode()); + assertEquals(a1b.hashCode(), a2b.hashCode()); // Hashcode is overwritten + assertNotEquals(a1b.hashCode(), bb.hashCode()); + assertEquals(a2b.hashCode(), a2b.hashCode()); + assertNotEquals(a2b.hashCode(), bb.hashCode()); + assertEquals(bb.hashCode(), bb.hashCode()); + // Compare hashcodes on bean with resetter + assertNotEquals(a1b.hashCode(), a1r.hashCode()); + assertNotEquals(a1b.hashCode(), a2r.hashCode()); + assertNotEquals(a1b.hashCode(), a1ar.hashCode()); + assertNotEquals(a1b.hashCode(), br.hashCode()); + assertNotEquals(a1b.hashCode(), nullr.hashCode()); + assertNotEquals(a2b.hashCode(), a1r.hashCode()); + assertNotEquals(a2b.hashCode(), a2r.hashCode()); + assertNotEquals(a2b.hashCode(), a1ar.hashCode()); + assertNotEquals(a2b.hashCode(), br.hashCode()); + assertNotEquals(a2b.hashCode(), nullr.hashCode()); + assertNotEquals(bb.hashCode(), a1r.hashCode()); + assertNotEquals(bb.hashCode(), a2r.hashCode()); + assertNotEquals(bb.hashCode(), a1ar.hashCode()); + assertNotEquals(bb.hashCode(), br.hashCode()); + assertNotEquals(bb.hashCode(), nullr.hashCode()); + // Compare hashcodes on resetter + assertEquals(a1r.hashCode(), a1r.hashCode()); + assertNotEquals(a1r.hashCode(), a2r.hashCode()); // Hashcode is no longer overwritten + assertEquals(a1r.hashCode(), a1ar.hashCode()); + assertNotEquals(a1r.hashCode(), br.hashCode()); + assertNotEquals(a1r.hashCode(), nullr.hashCode()); + assertEquals(a2r.hashCode(), a2r.hashCode()); + assertNotEquals(a2r.hashCode(), a1ar.hashCode()); + assertNotEquals(a2r.hashCode(), br.hashCode()); + assertNotEquals(a2r.hashCode(), nullr.hashCode()); + assertEquals(a1ar.hashCode(), a1ar.hashCode()); + assertNotEquals(a1ar.hashCode(), br.hashCode()); + assertNotEquals(a1ar.hashCode(), nullr.hashCode()); + assertEquals(br.hashCode(), br.hashCode()); + assertNotEquals(br.hashCode(), nullr.hashCode()); + assertEquals(nullr.hashCode(), nullr.hashCode()); + // Compare hashcodes on resetter with bean + assertNotEquals(a1r.hashCode(), a1b.hashCode()); + assertNotEquals(a1r.hashCode(), a2b.hashCode()); + assertNotEquals(a1r.hashCode(), bb.hashCode()); + assertNotEquals(a2r.hashCode(), a1b.hashCode()); + assertNotEquals(a2r.hashCode(), a2b.hashCode()); + assertNotEquals(a2r.hashCode(), bb.hashCode()); + assertNotEquals(a1ar.hashCode(), a1b.hashCode()); + assertNotEquals(a1ar.hashCode(), a2b.hashCode()); + assertNotEquals(a1ar.hashCode(), bb.hashCode()); + assertNotEquals(br.hashCode(), a1b.hashCode()); + assertNotEquals(br.hashCode(), a2b.hashCode()); + assertNotEquals(br.hashCode(), bb.hashCode()); + assertNotEquals(nullr.hashCode(), a1b.hashCode()); + assertNotEquals(nullr.hashCode(), a2b.hashCode()); + assertNotEquals(nullr.hashCode(), bb.hashCode()); + // Test bean in HashMap + Map beanMap = new HashMap<>(); + beanMap.put(a1b, "a1rValue"); + beanMap.put(a2b, "a2rValue"); // Overwrites existing value "a1rValue" + beanMap.put(bb, "brValue"); + assertEquals("a2rValue", beanMap.get(a1b)); + assertEquals("a2rValue", beanMap.get(a2b)); + assertEquals("brValue", beanMap.get(bb)); + // Test resetter in HashMap + Map, String> map = new HashMap<>(); + map.put(a1r, "a1rValue"); + map.put(a2r, "a2rValue"); + map.put(br, "brValue"); + assertEquals("a1rValue", map.get(a1r)); + assertEquals("a2rValue", map.get(a2r)); + assertEquals("a1rValue", map.get(a1ar)); + assertEquals("brValue", map.get(br)); + } - /** - * Overwritten to make {@link MyBean}s equal if they have the same value. - */ - @Override - public int hashCode() { - return value.hashCode(); - } - } -} \ No newline at end of file + /** + * Utility class used in tests. + * + * @author Martin Hentschel + */ + private static class MyBean { + /** + * A value. + */ + private final String value; + + /** + * Constructor. + * + * @param value A value. + */ + public MyBean(String value) { + assertNotNull(value); + this.value = value; + } + + /** + * Overwritten to make {@link MyBean}s equal if they have the same value. + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof MyBean) { + return value.equals(((MyBean) obj).value); + } else { + return false; + } + } + + /** + * Overwritten to make {@link MyBean}s equal if they have the same value. + */ + @Override + public int hashCode() { + return value.hashCode(); + } + } +} diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSideProofStore.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSideProofStore.java index 9393a21f0da..f513cb80d29 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSideProofStore.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSideProofStore.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.util; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -27,256 +30,269 @@ /** * Tests for {@link SideProofStore} + * * @author Martin Hentschel */ public class TestSideProofStore { - /** - * Tests the proof management and thrown events: - *
      - *
    • {@link SideProofStore#containsEntry(Proof)}
    • - *
    • {@link SideProofStore#containsEntry(Entry)}
    • - *
    • {@link SideProofStore#getEntry(Proof)}
    • - *
    • {@link SideProofStore#countEntries()}
    • - *
    • {@link SideProofStore#getEntries()}
    • - *
    • {@link SideProofStore#getEntryAt(int)}
    • - *
    • {@link SideProofStore#addProof(String, Proof)}
    • - *
    • {@link SideProofStore#removeEntries(java.util.Collection)}
    • - *
    - */ - @SuppressWarnings("unchecked") - @Test - public void testProofManagement() { - LoggingProofStoreListener listener = new LoggingProofStoreListener(); - try { - SideProofStore.DEFAULT_INSTANCE.addProofStoreListener(listener); - // Create proofs - Services services = new Services(AbstractProfile.getDefaultProfile()); - InitConfig ic = new InitConfig(services); - ProofEnvironment pe = new ProofEnvironment(ic); - Proof p1 = new Proof("TestSideProofStore 1", ic.deepCopy()); - p1.setEnv(pe); - Proof p2 = new Proof("TestSideProofStore 2", ic.deepCopy()); - p2.setEnv(pe); - Proof p3 = new Proof("TestSideProofStore 3", ic.deepCopy()); - p3.setEnv(pe); - Proof[] allProofs = new Proof[] {p1, p2, p3}; - // Test initial state - assertEntries(allProofs, new Proof[0]); - // Add proof p1 - SideProofStore.DEFAULT_INSTANCE.addProof("P1", p1); - assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1)); - listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, - new Entry[] {SideProofStore.DEFAULT_INSTANCE.getEntry(p1)})); - listener.assertRemovedLog(); - // Add proof p2 - SideProofStore.DEFAULT_INSTANCE.addProof("P2", p2); - assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1), new Pair<>("P2", p2)); - listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, - new Entry[] {SideProofStore.DEFAULT_INSTANCE.getEntry(p2)})); - listener.assertRemovedLog(); - // Add proof p3 - SideProofStore.DEFAULT_INSTANCE.addProof("P3", p3); - assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1), new Pair<>("P2", p2), new Pair<>("P3", p3)); - listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, - new Entry[] {SideProofStore.DEFAULT_INSTANCE.getEntry(p3)})); - listener.assertRemovedLog(); - // Remove p1 and p3 - List toRemove = new LinkedList<>(); - toRemove.add(SideProofStore.DEFAULT_INSTANCE.getEntry(p1)); - toRemove.add(SideProofStore.DEFAULT_INSTANCE.getEntry(p3)); - SideProofStore.DEFAULT_INSTANCE.removeEntries(toRemove); - assertEntries(allProofs, new Proof[] {p1, p3}, new Pair<>("P2", p2)); - listener.assertAddedLog(); - listener.assertRemovedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, - toRemove.toArray(new Entry[0]))); - // Remove p2 - toRemove = Collections.singletonList(SideProofStore.DEFAULT_INSTANCE.getEntry(p2)); - SideProofStore.DEFAULT_INSTANCE.removeEntries(toRemove); - assertEntries(allProofs, new Proof[] {p1, p2, p3}); - listener.assertAddedLog(); - listener.assertRemovedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, - toRemove.toArray(new Entry[0]))); - } - finally { - SideProofStore.DEFAULT_INSTANCE.removeProofStoreListener(listener); - } - } - - /** - * Ensures the {@link Entry} is {@link SideProofStore#DEFAULT_INSTANCE}. - * @param allProofs All available {@link Proof}s. - * @param disposedProofs The expected disposed {@link Proof}s. - * @param expectedEntries The expected entries in {@link SideProofStore#DEFAULT_INSTANCE}. - */ - @SuppressWarnings("unchecked") - private void assertEntries(Proof[] allProofs, Proof[] disposedProofs, Pair... expectedEntries) { - // Test entries - List containedProofs = new LinkedList<>(); - assertEquals(expectedEntries.length, SideProofStore.DEFAULT_INSTANCE.countEntries()); - Entry[] entries = SideProofStore.DEFAULT_INSTANCE.getEntries(); - assertEquals(expectedEntries.length, entries.length); - for (int i = 0; i < expectedEntries.length; i++) { - assertEquals(entries[i].getDescription(), expectedEntries[i].first); - Assertions.assertSame(entries[i].getProof(), expectedEntries[i].second); - Assertions.assertSame(entries[i], SideProofStore.DEFAULT_INSTANCE.getEntryAt(i)); - KeYEnvironment ui = entries[i].getEnvironment(); - Assertions.assertNotNull(ui); - KeYEnvironment uiAgain = entries[i].getEnvironment(); - Assertions.assertSame(ui, uiAgain); - containedProofs.add(expectedEntries[i].second); - Assertions.assertFalse(entries[i].getProof().isDisposed()); - Object[] user = ProofUserManager.getInstance().getUsers(entries[i].getProof()); - assertEquals(1, user.length); - Assertions.assertSame(SideProofStore.DEFAULT_INSTANCE, user[0]); - } - // Test proofs - for (Proof proof : allProofs) { - Entry entry = SideProofStore.DEFAULT_INSTANCE.getEntry(proof); - assertEquals(containedProofs.contains(proof), entry != null); - assertEquals(containedProofs.contains(proof), SideProofStore.DEFAULT_INSTANCE.containsEntry(proof)); - assertEquals(containedProofs.contains(proof), SideProofStore.DEFAULT_INSTANCE.containsEntry(entry)); - assertEquals(ArrayUtil.contains(disposedProofs, proof), proof.isDisposed()); - } - } + /** + * Tests the proof management and thrown events: + *
      + *
    • {@link SideProofStore#containsEntry(Proof)}
    • + *
    • {@link SideProofStore#containsEntry(Entry)}
    • + *
    • {@link SideProofStore#getEntry(Proof)}
    • + *
    • {@link SideProofStore#countEntries()}
    • + *
    • {@link SideProofStore#getEntries()}
    • + *
    • {@link SideProofStore#getEntryAt(int)}
    • + *
    • {@link SideProofStore#addProof(String, Proof)}
    • + *
    • {@link SideProofStore#removeEntries(java.util.Collection)}
    • + *
    + */ + @SuppressWarnings("unchecked") + @Test + public void testProofManagement() { + LoggingProofStoreListener listener = new LoggingProofStoreListener(); + try { + SideProofStore.DEFAULT_INSTANCE.addProofStoreListener(listener); + // Create proofs + Services services = new Services(AbstractProfile.getDefaultProfile()); + InitConfig ic = new InitConfig(services); + ProofEnvironment pe = new ProofEnvironment(ic); + Proof p1 = new Proof("TestSideProofStore 1", ic.deepCopy()); + p1.setEnv(pe); + Proof p2 = new Proof("TestSideProofStore 2", ic.deepCopy()); + p2.setEnv(pe); + Proof p3 = new Proof("TestSideProofStore 3", ic.deepCopy()); + p3.setEnv(pe); + Proof[] allProofs = new Proof[] { p1, p2, p3 }; + // Test initial state + assertEntries(allProofs, new Proof[0]); + // Add proof p1 + SideProofStore.DEFAULT_INSTANCE.addProof("P1", p1); + assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1)); + listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, + new Entry[] { SideProofStore.DEFAULT_INSTANCE.getEntry(p1) })); + listener.assertRemovedLog(); + // Add proof p2 + SideProofStore.DEFAULT_INSTANCE.addProof("P2", p2); + assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1), new Pair<>("P2", p2)); + listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, + new Entry[] { SideProofStore.DEFAULT_INSTANCE.getEntry(p2) })); + listener.assertRemovedLog(); + // Add proof p3 + SideProofStore.DEFAULT_INSTANCE.addProof("P3", p3); + assertEntries(allProofs, new Proof[0], new Pair<>("P1", p1), new Pair<>("P2", p2), + new Pair<>("P3", p3)); + listener.assertAddedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, + new Entry[] { SideProofStore.DEFAULT_INSTANCE.getEntry(p3) })); + listener.assertRemovedLog(); + // Remove p1 and p3 + List toRemove = new LinkedList<>(); + toRemove.add(SideProofStore.DEFAULT_INSTANCE.getEntry(p1)); + toRemove.add(SideProofStore.DEFAULT_INSTANCE.getEntry(p3)); + SideProofStore.DEFAULT_INSTANCE.removeEntries(toRemove); + assertEntries(allProofs, new Proof[] { p1, p3 }, new Pair<>("P2", p2)); + listener.assertAddedLog(); + listener.assertRemovedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, + toRemove.toArray(new Entry[0]))); + // Remove p2 + toRemove = Collections.singletonList(SideProofStore.DEFAULT_INSTANCE.getEntry(p2)); + SideProofStore.DEFAULT_INSTANCE.removeEntries(toRemove); + assertEntries(allProofs, new Proof[] { p1, p2, p3 }); + listener.assertAddedLog(); + listener.assertRemovedLog(new SideProofStoreEvent(SideProofStore.DEFAULT_INSTANCE, + toRemove.toArray(new Entry[0]))); + } finally { + SideProofStore.DEFAULT_INSTANCE.removeProofStoreListener(listener); + } + } - /** - * A logging {@link ISideProofStoreListener}. - * @author Martin Hentschel - */ - private static class LoggingProofStoreListener implements ISideProofStoreListener { - /** - * The log with added entries. - */ - private final List addedLog = new LinkedList<>(); - - /** - * The log with removed entries. - */ - private final List removedLog = new LinkedList<>(); + /** + * Ensures the {@link Entry} is {@link SideProofStore#DEFAULT_INSTANCE}. + * + * @param allProofs All available {@link Proof}s. + * @param disposedProofs The expected disposed {@link Proof}s. + * @param expectedEntries The expected entries in {@link SideProofStore#DEFAULT_INSTANCE}. + */ + @SuppressWarnings("unchecked") + private void assertEntries(Proof[] allProofs, Proof[] disposedProofs, + Pair... expectedEntries) { + // Test entries + List containedProofs = new LinkedList<>(); + assertEquals(expectedEntries.length, SideProofStore.DEFAULT_INSTANCE.countEntries()); + Entry[] entries = SideProofStore.DEFAULT_INSTANCE.getEntries(); + assertEquals(expectedEntries.length, entries.length); + for (int i = 0; i < expectedEntries.length; i++) { + assertEquals(entries[i].getDescription(), expectedEntries[i].first); + Assertions.assertSame(entries[i].getProof(), expectedEntries[i].second); + Assertions.assertSame(entries[i], SideProofStore.DEFAULT_INSTANCE.getEntryAt(i)); + KeYEnvironment ui = entries[i].getEnvironment(); + Assertions.assertNotNull(ui); + KeYEnvironment uiAgain = entries[i].getEnvironment(); + Assertions.assertSame(ui, uiAgain); + containedProofs.add(expectedEntries[i].second); + Assertions.assertFalse(entries[i].getProof().isDisposed()); + Object[] user = ProofUserManager.getInstance().getUsers(entries[i].getProof()); + assertEquals(1, user.length); + Assertions.assertSame(SideProofStore.DEFAULT_INSTANCE, user[0]); + } + // Test proofs + for (Proof proof : allProofs) { + Entry entry = SideProofStore.DEFAULT_INSTANCE.getEntry(proof); + assertEquals(containedProofs.contains(proof), entry != null); + assertEquals(containedProofs.contains(proof), + SideProofStore.DEFAULT_INSTANCE.containsEntry(proof)); + assertEquals(containedProofs.contains(proof), + SideProofStore.DEFAULT_INSTANCE.containsEntry(entry)); + assertEquals(ArrayUtil.contains(disposedProofs, proof), proof.isDisposed()); + } + } - /** - * {@inheritDoc} - */ - @Override - public void entriesAdded(SideProofStoreEvent e) { - addedLog.add(e); - } + /** + * A logging {@link ISideProofStoreListener}. + * + * @author Martin Hentschel + */ + private static class LoggingProofStoreListener implements ISideProofStoreListener { + /** + * The log with added entries. + */ + private final List addedLog = new LinkedList<>(); - /** - * {@inheritDoc} - */ - @Override - public void entriesRemoved(SideProofStoreEvent e) { - removedLog.add(e); - } - - /** - * Compares the log with the given events and clears the log. - * @param expectedEvents The expected {@link SideProofStoreEvent}s. - */ - public void assertAddedLog(SideProofStoreEvent... expectedEvents) { - assertLog(addedLog, expectedEvents); - } - - /** - * Compares the log with the given events and clears the log. - * @param expectedEvents The expected {@link SideProofStoreEvent}s. - */ - public void assertRemovedLog(SideProofStoreEvent... expectedEvents) { - assertLog(removedLog, expectedEvents); - } - - /** - * Compares the log with the given events and clears the log. - * @param log The logged events. - * @param expectedEvents The expected {@link SideProofStoreEvent}s. - */ - protected void assertLog(List log, SideProofStoreEvent... expectedEvents) { - assertEquals(expectedEvents.length, log.size()); - for (int i = 0; i < log.size(); i++) { - SideProofStoreEvent currentLog = log.get(i); - assertEquals(expectedEvents[i].getSource(), currentLog.getSource()); - assertEquals(expectedEvents[i].getEntries().length, currentLog.getEntries().length); - for (int j = 0; j < expectedEvents[i].getEntries().length; j++) { - assertEquals(expectedEvents[i].getEntries()[j], currentLog.getEntries()[j]); + /** + * The log with removed entries. + */ + private final List removedLog = new LinkedList<>(); + + /** + * {@inheritDoc} + */ + @Override + public void entriesAdded(SideProofStoreEvent e) { + addedLog.add(e); + } + + /** + * {@inheritDoc} + */ + @Override + public void entriesRemoved(SideProofStoreEvent e) { + removedLog.add(e); + } + + /** + * Compares the log with the given events and clears the log. + * + * @param expectedEvents The expected {@link SideProofStoreEvent}s. + */ + public void assertAddedLog(SideProofStoreEvent... expectedEvents) { + assertLog(addedLog, expectedEvents); + } + + /** + * Compares the log with the given events and clears the log. + * + * @param expectedEvents The expected {@link SideProofStoreEvent}s. + */ + public void assertRemovedLog(SideProofStoreEvent... expectedEvents) { + assertLog(removedLog, expectedEvents); + } + + /** + * Compares the log with the given events and clears the log. + * + * @param log The logged events. + * @param expectedEvents The expected {@link SideProofStoreEvent}s. + */ + protected void assertLog(List log, + SideProofStoreEvent... expectedEvents) { + assertEquals(expectedEvents.length, log.size()); + for (int i = 0; i < log.size(); i++) { + SideProofStoreEvent currentLog = log.get(i); + assertEquals(expectedEvents[i].getSource(), currentLog.getSource()); + assertEquals(expectedEvents[i].getEntries().length, currentLog.getEntries().length); + for (int j = 0; j < expectedEvents[i].getEntries().length; j++) { + assertEquals(expectedEvents[i].getEntries()[j], currentLog.getEntries()[j]); + } } - } - log.clear(); - } - } - - /** - * Tests {@link SideProofStore#isEnabled()} and - * {@link SideProofStore#setEnabled(boolean)} together with the thrown events - * and the event management. - */ - @Test public void testEnabledState() { - LoggingPropertyChangeListener listener = new LoggingPropertyChangeListener(); - boolean originalEnabled = SideProofStore.DEFAULT_INSTANCE.isEnabled(); - try { - // Setup initial disabled state - SideProofStore.DEFAULT_INSTANCE.setEnabled(false); - SideProofStore.DEFAULT_INSTANCE.addPropertyChangeListener(SideProofStore.PROP_ENABLED, listener); - // Test initial disabled state - Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); - listener.assertLog(); - // Set disabled again - SideProofStore.DEFAULT_INSTANCE.setEnabled(false); - Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); - listener.assertLog(); - // Change to enabled - SideProofStore.DEFAULT_INSTANCE.setEnabled(true); - Assertions.assertTrue(SideProofStore.DEFAULT_INSTANCE.isEnabled()); - listener.assertLog(new PropertyChangeEvent(SideProofStore.DEFAULT_INSTANCE, SideProofStore.PROP_ENABLED, - false, true)); - // Set enabled again - SideProofStore.DEFAULT_INSTANCE.setEnabled(true); - Assertions.assertTrue(SideProofStore.DEFAULT_INSTANCE.isEnabled()); - listener.assertLog(); - // Change to dissabled - SideProofStore.DEFAULT_INSTANCE.setEnabled(false); - Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); - listener.assertLog(new PropertyChangeEvent(SideProofStore.DEFAULT_INSTANCE, SideProofStore.PROP_ENABLED, - true, false)); - } - finally { - SideProofStore.DEFAULT_INSTANCE.removePropertyChangeListener(SideProofStore.PROP_ENABLED, listener); - SideProofStore.DEFAULT_INSTANCE.setEnabled(originalEnabled); - } - } - - /** - * A logging {@link PropertyChangeListener}. - * @author Martin Hentschel - */ - private static class LoggingPropertyChangeListener implements PropertyChangeListener { - /** - * The log. - */ - private final List log = new LinkedList<>(); + log.clear(); + } + } + + /** + * Tests {@link SideProofStore#isEnabled()} and {@link SideProofStore#setEnabled(boolean)} + * together with the thrown events and the event management. + */ + @Test + public void testEnabledState() { + LoggingPropertyChangeListener listener = new LoggingPropertyChangeListener(); + boolean originalEnabled = SideProofStore.DEFAULT_INSTANCE.isEnabled(); + try { + // Setup initial disabled state + SideProofStore.DEFAULT_INSTANCE.setEnabled(false); + SideProofStore.DEFAULT_INSTANCE.addPropertyChangeListener(SideProofStore.PROP_ENABLED, + listener); + // Test initial disabled state + Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); + listener.assertLog(); + // Set disabled again + SideProofStore.DEFAULT_INSTANCE.setEnabled(false); + Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); + listener.assertLog(); + // Change to enabled + SideProofStore.DEFAULT_INSTANCE.setEnabled(true); + Assertions.assertTrue(SideProofStore.DEFAULT_INSTANCE.isEnabled()); + listener.assertLog(new PropertyChangeEvent(SideProofStore.DEFAULT_INSTANCE, + SideProofStore.PROP_ENABLED, false, true)); + // Set enabled again + SideProofStore.DEFAULT_INSTANCE.setEnabled(true); + Assertions.assertTrue(SideProofStore.DEFAULT_INSTANCE.isEnabled()); + listener.assertLog(); + // Change to dissabled + SideProofStore.DEFAULT_INSTANCE.setEnabled(false); + Assertions.assertFalse(SideProofStore.DEFAULT_INSTANCE.isEnabled()); + listener.assertLog(new PropertyChangeEvent(SideProofStore.DEFAULT_INSTANCE, + SideProofStore.PROP_ENABLED, true, false)); + } finally { + SideProofStore.DEFAULT_INSTANCE + .removePropertyChangeListener(SideProofStore.PROP_ENABLED, listener); + SideProofStore.DEFAULT_INSTANCE.setEnabled(originalEnabled); + } + } - /** - * {@inheritDoc} - */ - @Override - public void propertyChange(PropertyChangeEvent evt) { - log.add(evt); - } + /** + * A logging {@link PropertyChangeListener}. + * + * @author Martin Hentschel + */ + private static class LoggingPropertyChangeListener implements PropertyChangeListener { + /** + * The log. + */ + private final List log = new LinkedList<>(); - /** - * Compares the log with the given events and clears the log. - * @param expectedEvents The expected {@link PropertyChangeEvent}s. - */ - public void assertLog(PropertyChangeEvent... expectedEvents) { - assertEquals(expectedEvents.length, log.size()); - for (int i = 0; i < log.size(); i++) { - PropertyChangeEvent currentLog = log.get(i); - assertEquals(expectedEvents[i].getSource(), currentLog.getSource()); - assertEquals(expectedEvents[i].getPropertyName(), currentLog.getPropertyName()); - assertEquals(expectedEvents[i].getOldValue(), currentLog.getOldValue()); - assertEquals(expectedEvents[i].getNewValue(), currentLog.getNewValue()); - } - log.clear(); - } - } + /** + * {@inheritDoc} + */ + @Override + public void propertyChange(PropertyChangeEvent evt) { + log.add(evt); + } + + /** + * Compares the log with the given events and clears the log. + * + * @param expectedEvents The expected {@link PropertyChangeEvent}s. + */ + public void assertLog(PropertyChangeEvent... expectedEvents) { + assertEquals(expectedEvents.length, log.size()); + for (int i = 0; i < log.size(); i++) { + PropertyChangeEvent currentLog = log.get(i); + assertEquals(expectedEvents[i].getSource(), currentLog.getSource()); + assertEquals(expectedEvents[i].getPropertyName(), currentLog.getPropertyName()); + assertEquals(expectedEvents[i].getOldValue(), currentLog.getOldValue()); + assertEquals(expectedEvents[i].getNewValue(), currentLog.getNewValue()); + } + log.clear(); + } + } } diff --git a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSymbolicExecutionUtil.java b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSymbolicExecutionUtil.java index cba8d341e2c..7d023dc4610 100644 --- a/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSymbolicExecutionUtil.java +++ b/key/key.core.symbolic_execution/src/test/java/de/uka/ilkd/key/symbolic_execution/testcase/util/TestSymbolicExecutionUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.symbolic_execution.testcase.util; import de.uka.ilkd.key.control.KeYEnvironment; @@ -37,7 +40,7 @@ public class TestSymbolicExecutionUtil extends AbstractSymbolicExecutionTestCase public void test1ImproveReadability() throws ProblemLoaderException { File location = new File(testCaseDirectory, "/readability/InnerAndAnonymousTypeTest/InnerAndAnonymousTypeTest.java") - .getAbsoluteFile(); + .getAbsoluteFile(); assertTrue(location.exists(), "Could not find required resource: " + location); KeYEnvironment environment = KeYEnvironment.load(location, null, null, null); @@ -62,7 +65,8 @@ public void test1ImproveReadability() throws ProblemLoaderException { Term altBPlusOne = TB.lt(a, bPlusOne); Term ageqOnePlusB = TB.geq(a, onePlusB); Term ageqBPlusOne = TB.geq(a, bPlusOne); - Term minusOne = services.getTypeConverter().getIntegerLDT().translateLiteral(new IntLiteral(-1), services); + Term minusOne = services.getTypeConverter().getIntegerLDT() + .translateLiteral(new IntLiteral(-1), services); Term minusOnePlusB = TB.add(minusOne, b); Term bPlusMinusOne = TB.add(b, minusOne); Term bMinusOne = TB.func(integerLDT.getSub(), b, TB.one()); @@ -97,13 +101,12 @@ public void test1ImproveReadability() throws ProblemLoaderException { // Test combined assertTerm(agtb, SymbolicExecutionUtil.improveReadability(TB.not(altOnePlusB), services)); assertTerm(aleqb, SymbolicExecutionUtil.improveReadability(TB.not(ageqOnePlusB), services)); - assertTerm(ageqb, SymbolicExecutionUtil.improveReadability(TB.not(aleqBPlusMinusOne), services)); + assertTerm(ageqb, + SymbolicExecutionUtil.improveReadability(TB.not(aleqBPlusMinusOne), services)); assertTerm(altb, SymbolicExecutionUtil.improveReadability(TB.not(agtBMinusOne), services)); // Test complex term - Term complex = TB.and(altOnePlusB, - TB.or(ageqBPlusOne, agtMinusOnePlusB)); - Term expectedComplex = TB.and(aleqb, - TB.or(agtb, ageqb)); + Term complex = TB.and(altOnePlusB, TB.or(ageqBPlusOne, agtMinusOnePlusB)); + Term expectedComplex = TB.and(aleqb, TB.or(agtb, ageqb)); assertTerm(expectedComplex, SymbolicExecutionUtil.improveReadability(complex, services)); environment.dispose(); } @@ -113,30 +116,43 @@ public void test1ImproveReadability() throws ProblemLoaderException { * {@link SymbolicExecutionUtil#setChoiceSetting(String, String)} and * {@link SymbolicExecutionUtil#isChoiceSettingInitialised()}. */ - @Test public void test2GetAndSetChoiceSetting() { + @Test + public void test2GetAndSetChoiceSetting() { String originalValue = null; try { - //weigl: disable, no clue why the choice settings should be initialised + // weigl: disable, no clue why the choice settings should be initialised // assertTrue(SymbolicExecutionUtil.isChoiceSettingInitialised()); // Store default choice settings - HashMap defaultSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); - //weigl: disable, no clue why the choice settings should be initialised - //assertFalse(defaultSettings.isEmpty()); + HashMap defaultSettings = + ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); + // weigl: disable, no clue why the choice settings should be initialised + // assertFalse(defaultSettings.isEmpty()); // Test initial value - originalValue = SymbolicExecutionUtil.getChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS); - assertTrue(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW.equals(originalValue) || SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN.equals(originalValue)); + originalValue = SymbolicExecutionUtil + .getChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS); + assertTrue(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW + .equals(originalValue) + || SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN + .equals(originalValue)); // Change value and make sure that it has changed - String newValue = SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW.equals(originalValue) ? SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN : SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW; - SymbolicExecutionUtil.setChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS, newValue); - Assertions.assertEquals(newValue, SymbolicExecutionUtil.getChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS)); + String newValue = SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW + .equals(originalValue) + ? SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_BAN + : SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS_VALUE_ALLOW; + SymbolicExecutionUtil.setChoiceSetting( + SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS, newValue); + Assertions.assertEquals(newValue, SymbolicExecutionUtil + .getChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS)); // Make sure that all other settings are unchanged. - HashMap changedSettings = ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); + HashMap changedSettings = + ProofSettings.DEFAULT_SETTINGS.getChoiceSettings().getDefaultChoices(); defaultSettings.put(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS, newValue); Assertions.assertEquals(defaultSettings, changedSettings); } finally { if (originalValue != null) { - SymbolicExecutionUtil.setChoiceSetting(SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS, originalValue); + SymbolicExecutionUtil.setChoiceSetting( + SymbolicExecutionUtil.CHOICE_SETTING_RUNTIME_EXCEPTIONS, originalValue); } } } -} \ No newline at end of file +} diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/SemanticsBlastingMacro.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/SemanticsBlastingMacro.java index f0a6b47dbe7..1c64cccef72 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/SemanticsBlastingMacro.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/SemanticsBlastingMacro.java @@ -1,6 +1,6 @@ -/** - * - */ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.HashSet; @@ -16,161 +16,162 @@ public final class SemanticsBlastingMacro extends AbstractBlastingMacro { - private final SemanticsRuleFilter semanticsFilter; - private final EqualityRuleFilter equalityRuleFilter; - private final HashSet allowedPullOut; - public SemanticsBlastingMacro() { - super(); - semanticsFilter = new SemanticsRuleFilter(); - equalityRuleFilter = new EqualityRuleFilter(); - allowedPullOut = new HashSet(20); - - allowedPullOut.add("store"); - allowedPullOut.add("create"); - allowedPullOut.add("anon"); - allowedPullOut.add("memset"); - allowedPullOut.add("empty"); - allowedPullOut.add("allLocs"); - allowedPullOut.add("singleton"); - allowedPullOut.add("union"); - allowedPullOut.add("intersect"); - allowedPullOut.add("setMinus"); - allowedPullOut.add("allFields"); - allowedPullOut.add("allObjects"); - allowedPullOut.add("arrayRange"); - allowedPullOut.add("freshLocs"); - allowedPullOut.add("seqDef"); - allowedPullOut.add("seqReverse"); - allowedPullOut.add("seqSub"); - allowedPullOut.add("seqConcat"); - allowedPullOut.add("seqSingleton"); - allowedPullOut.add("infiniteUnion"); - } - - @Override - protected RuleFilter getSemanticsRuleFilter () { - return semanticsFilter; - } - - @Override - protected RuleFilter getEqualityRuleFilter () { - return equalityRuleFilter; - } - - @Override - protected Set getAllowedPullOut () { - return allowedPullOut; - } - - @Override - public String getName() { - return "Semantics Blasting"; - } - - @Override - public String getCategory() { - return null; - } - - @Override - public String getDescription() { - // TODO Auto-generated method stub - return "Semantics Blasting"; - } - - - - private class SemanticsRuleFilter implements RuleFilter{ - protected HashSet allowedRulesNames; - { - allowedRulesNames = new HashSet(100); - allowedRulesNames.add("selectOfStore"); - allowedRulesNames.add("selectOfCreate"); - allowedRulesNames.add("selectOfAnon"); - allowedRulesNames.add("selectOfMemset"); - - allowedRulesNames.add("elementOfEmpty"); - allowedRulesNames.add("elementOfAllLocs"); - allowedRulesNames.add("elementOfSingleton"); - allowedRulesNames.add("elementOfUnion"); - allowedRulesNames.add("elementOfIntersect"); - allowedRulesNames.add("elementOfSetMinus"); - allowedRulesNames.add("elementOfAllFields"); - allowedRulesNames.add("elementOfAllObjects"); - allowedRulesNames.add("elementOfArrayRange"); - allowedRulesNames.add("elementOfFreshLocs"); - allowedRulesNames.add("elementOfInfiniteUnion"); - allowedRulesNames.add("subsetToElementOf"); - allowedRulesNames.add("disjointToElementOf"); - allowedRulesNames.add("createdInHeapToElementOf"); - - - - allowedRulesNames.add("getOfSeqDef"); - allowedRulesNames.add("getOfSeqSingleton"); - allowedRulesNames.add("getOfSeqConcat"); - allowedRulesNames.add("getOfSeqSub"); - allowedRulesNames.add("getOfSeqReverse"); - allowedRulesNames.add("lenOfSeqDef"); - allowedRulesNames.add("lenOfSeqSingleton"); - allowedRulesNames.add("lenOfSeqConcat"); - allowedRulesNames.add("lenOfSeqSub"); - allowedRulesNames.add("lenOfSeqReverse"); - - //some int rules - allowedRulesNames.add("inByte"); - allowedRulesNames.add("inChar"); - allowedRulesNames.add("inShort"); - allowedRulesNames.add("inInt"); - allowedRulesNames.add("inLong"); - allowedRulesNames.add("translateJavaUnaryMinusInt"); - allowedRulesNames.add("translateJavaUnaryMinusLong"); - allowedRulesNames.add("translateJavaAddInt"); - allowedRulesNames.add("translateJavaAddLong"); - allowedRulesNames.add("translateJavaSubInt"); - allowedRulesNames.add("translateJavaSubLong"); - allowedRulesNames.add("translateJavaMulInt"); - allowedRulesNames.add("translateJavaMulLong"); - allowedRulesNames.add("translateJavaMod"); - allowedRulesNames.add("translateJavaDivInt"); - allowedRulesNames.add("translateJavaDivLong"); - allowedRulesNames.add("translateJavaCastByte"); - allowedRulesNames.add("translateJavaCastShort"); - allowedRulesNames.add("translateJavaCastInt"); - allowedRulesNames.add("translateJavaCastLong"); - allowedRulesNames.add("translateJavaCastChar"); - allowedRulesNames.add("jdiv_axiom_inline"); - - //other rules - allowedRulesNames.add("array_store_known_dynamic_array_type"); - //non null - allowedRulesNames.add("nonNull"); - allowedRulesNames.add("nonNullZero"); - allowedRulesNames.add("sub_literals"); - allowedRulesNames.add("equal_literals"); - //allowedRulesNames.add("applyEq"); - } - @Override - public boolean filter(Rule rule) { - return allowedRulesNames.contains(rule.name().toString()); - } - } - - private class EqualityRuleFilter implements RuleFilter{ - private HashSet allowedRulesNames; - { - allowedRulesNames = new HashSet(); - allowedRulesNames.add("equalityToElementOf"); - allowedRulesNames.add("equalityToSelect"); - allowedRulesNames.add("equalityToSeqGetAndSeqLen"); - } - @Override - public boolean filter(Rule rule) { - return allowedRulesNames.contains(rule.name().toString()); - } - } - - + private final SemanticsRuleFilter semanticsFilter; + private final EqualityRuleFilter equalityRuleFilter; + private final HashSet allowedPullOut; + + public SemanticsBlastingMacro() { + super(); + semanticsFilter = new SemanticsRuleFilter(); + equalityRuleFilter = new EqualityRuleFilter(); + allowedPullOut = new HashSet(20); + + allowedPullOut.add("store"); + allowedPullOut.add("create"); + allowedPullOut.add("anon"); + allowedPullOut.add("memset"); + allowedPullOut.add("empty"); + allowedPullOut.add("allLocs"); + allowedPullOut.add("singleton"); + allowedPullOut.add("union"); + allowedPullOut.add("intersect"); + allowedPullOut.add("setMinus"); + allowedPullOut.add("allFields"); + allowedPullOut.add("allObjects"); + allowedPullOut.add("arrayRange"); + allowedPullOut.add("freshLocs"); + allowedPullOut.add("seqDef"); + allowedPullOut.add("seqReverse"); + allowedPullOut.add("seqSub"); + allowedPullOut.add("seqConcat"); + allowedPullOut.add("seqSingleton"); + allowedPullOut.add("infiniteUnion"); + } + + @Override + protected RuleFilter getSemanticsRuleFilter() { + return semanticsFilter; + } + + @Override + protected RuleFilter getEqualityRuleFilter() { + return equalityRuleFilter; + } + + @Override + protected Set getAllowedPullOut() { + return allowedPullOut; + } + + @Override + public String getName() { + return "Semantics Blasting"; + } + + @Override + public String getCategory() { + return null; + } + + @Override + public String getDescription() { + // TODO Auto-generated method stub + return "Semantics Blasting"; + } + + + + private class SemanticsRuleFilter implements RuleFilter { + protected HashSet allowedRulesNames; + { + allowedRulesNames = new HashSet(100); + allowedRulesNames.add("selectOfStore"); + allowedRulesNames.add("selectOfCreate"); + allowedRulesNames.add("selectOfAnon"); + allowedRulesNames.add("selectOfMemset"); + + allowedRulesNames.add("elementOfEmpty"); + allowedRulesNames.add("elementOfAllLocs"); + allowedRulesNames.add("elementOfSingleton"); + allowedRulesNames.add("elementOfUnion"); + allowedRulesNames.add("elementOfIntersect"); + allowedRulesNames.add("elementOfSetMinus"); + allowedRulesNames.add("elementOfAllFields"); + allowedRulesNames.add("elementOfAllObjects"); + allowedRulesNames.add("elementOfArrayRange"); + allowedRulesNames.add("elementOfFreshLocs"); + allowedRulesNames.add("elementOfInfiniteUnion"); + allowedRulesNames.add("subsetToElementOf"); + allowedRulesNames.add("disjointToElementOf"); + allowedRulesNames.add("createdInHeapToElementOf"); + + + + allowedRulesNames.add("getOfSeqDef"); + allowedRulesNames.add("getOfSeqSingleton"); + allowedRulesNames.add("getOfSeqConcat"); + allowedRulesNames.add("getOfSeqSub"); + allowedRulesNames.add("getOfSeqReverse"); + allowedRulesNames.add("lenOfSeqDef"); + allowedRulesNames.add("lenOfSeqSingleton"); + allowedRulesNames.add("lenOfSeqConcat"); + allowedRulesNames.add("lenOfSeqSub"); + allowedRulesNames.add("lenOfSeqReverse"); + + // some int rules + allowedRulesNames.add("inByte"); + allowedRulesNames.add("inChar"); + allowedRulesNames.add("inShort"); + allowedRulesNames.add("inInt"); + allowedRulesNames.add("inLong"); + allowedRulesNames.add("translateJavaUnaryMinusInt"); + allowedRulesNames.add("translateJavaUnaryMinusLong"); + allowedRulesNames.add("translateJavaAddInt"); + allowedRulesNames.add("translateJavaAddLong"); + allowedRulesNames.add("translateJavaSubInt"); + allowedRulesNames.add("translateJavaSubLong"); + allowedRulesNames.add("translateJavaMulInt"); + allowedRulesNames.add("translateJavaMulLong"); + allowedRulesNames.add("translateJavaMod"); + allowedRulesNames.add("translateJavaDivInt"); + allowedRulesNames.add("translateJavaDivLong"); + allowedRulesNames.add("translateJavaCastByte"); + allowedRulesNames.add("translateJavaCastShort"); + allowedRulesNames.add("translateJavaCastInt"); + allowedRulesNames.add("translateJavaCastLong"); + allowedRulesNames.add("translateJavaCastChar"); + allowedRulesNames.add("jdiv_axiom_inline"); + + // other rules + allowedRulesNames.add("array_store_known_dynamic_array_type"); + // non null + allowedRulesNames.add("nonNull"); + allowedRulesNames.add("nonNullZero"); + allowedRulesNames.add("sub_literals"); + allowedRulesNames.add("equal_literals"); + // allowedRulesNames.add("applyEq"); + } + + @Override + public boolean filter(Rule rule) { + return allowedRulesNames.contains(rule.name().toString()); + } + } + + private class EqualityRuleFilter implements RuleFilter { + private HashSet allowedRulesNames; + { + allowedRulesNames = new HashSet(); + allowedRulesNames.add("equalityToElementOf"); + allowedRulesNames.add("equalityToSelect"); + allowedRulesNames.add("equalityToSeqGetAndSeqLen"); + } + + @Override + public boolean filter(Rule rule) { + return allowedRulesNames.contains(rule.name().toString()); + } + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/TestGenMacro.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/TestGenMacro.java index 83ccbdb5980..0eeb882f681 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/TestGenMacro.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/macros/TestGenMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.HashSet; @@ -20,138 +23,135 @@ import de.uka.ilkd.key.strategy.Strategy; public class TestGenMacro extends StrategyProofMacro { - @Override - protected Strategy createStrategy(Proof proof, - PosInOccurrence posInOcc) { - return new TestGenStrategy(proof - .getActiveStrategy()); - } + @Override + protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { + return new TestGenStrategy(proof.getActiveStrategy()); + } - @Override - public String getDescription() { - return "Finish symbolic execution but restrict loop unwinding."; - } + @Override + public String getDescription() { + return "Finish symbolic execution but restrict loop unwinding."; + } - @Override - public String getName() { - return "TestGen (finite loop unwinding)"; - } + @Override + public String getName() { + return "TestGen (finite loop unwinding)"; + } - @Override - public String getCategory() { - return null; - } + @Override + public String getCategory() { + return null; + } } + /** - * The Class FilterAppManager is a special strategy assigning to any rule - * infinite costs if the goal has no modality + * The Class FilterAppManager is a special strategy assigning to any rule infinite costs if the goal + * has no modality */ class TestGenStrategy extends FilterStrategy { - private static final Name NAME = new Name( - TestGenStrategy.class.getSimpleName()); - private static final Set unwindRules; - private static final int UNWIND_COST = 1000; - private final int limit; - static { - unwindRules = new HashSet<>(); - TestGenStrategy.unwindRules.add("loopUnwind"); - TestGenStrategy.unwindRules.add("doWhileUnwind"); - TestGenStrategy.unwindRules.add("methodCall"); - TestGenStrategy.unwindRules.add("methodCallWithAssignment"); - TestGenStrategy.unwindRules.add("staticMethodCall"); - TestGenStrategy.unwindRules.add("staticMethodCallWithAssignment"); - } - - /* - * recursively descent into the term to detect a modality. - */ - private static boolean hasModality(Term term) { - if (term.op() instanceof Modality) { - return true; - } - for (final Term sub : term.subs()) { - if (hasModality(sub)) { - return true; - } - } - return false; - } - - - /* - * find a modality term in a node - */ - private static boolean hasModality(Node node) { - final Sequent sequent = node.sequent(); - for (final SequentFormula sequentFormula : sequent) { - if (hasModality(sequentFormula.formula())) { - return true; - } - } - return false; - } - - - private static boolean isUnwindRule(Rule rule) { - if (rule == null) { - return false; - } - final String name = rule.name().toString(); - return TestGenStrategy.unwindRules.contains(name); - } - - public TestGenStrategy(Strategy delegate) { - super(delegate); - limit = TestGenerationSettings.getInstance().getMaximalUnwinds(); - } - - @Override - public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, - Goal goal) { - if (TestGenStrategy.isUnwindRule(app.rule())) { - return NumberRuleAppCost.create(TestGenStrategy.UNWIND_COST); - } - return super.computeCost(app, pio, goal); - } - - private int computeUnwindRules(Goal goal) { - int totalUnwinds = 0; - Node node = goal.node(); - while (!node.root()) { - final RuleApp app = node.getAppliedRuleApp(); - if (app != null) { - final Rule rule = app.rule(); - if (TestGenStrategy.isUnwindRule(rule)) { - ++totalUnwinds; - } - } - node = node.parent(); - } - return totalUnwinds; - } - - @Override - public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { - if (!hasModality(goal.node())) { - return false; - } - if (TestGenStrategy.isUnwindRule(app.rule())) { - final int noUnwindRules = computeUnwindRules(goal); - return noUnwindRules < limit; - } - return super.isApprovedApp(app, pio, goal); - } - - @Override - public Name name() { - return TestGenStrategy.NAME; - } - - @Override - public boolean isStopAtFirstNonCloseableGoal() { - return false; - } + private static final Name NAME = new Name(TestGenStrategy.class.getSimpleName()); + private static final Set unwindRules; + private static final int UNWIND_COST = 1000; + private final int limit; + static { + unwindRules = new HashSet<>(); + TestGenStrategy.unwindRules.add("loopUnwind"); + TestGenStrategy.unwindRules.add("doWhileUnwind"); + TestGenStrategy.unwindRules.add("methodCall"); + TestGenStrategy.unwindRules.add("methodCallWithAssignment"); + TestGenStrategy.unwindRules.add("staticMethodCall"); + TestGenStrategy.unwindRules.add("staticMethodCallWithAssignment"); + } + + /* + * recursively descent into the term to detect a modality. + */ + private static boolean hasModality(Term term) { + if (term.op() instanceof Modality) { + return true; + } + for (final Term sub : term.subs()) { + if (hasModality(sub)) { + return true; + } + } + return false; + } + + + /* + * find a modality term in a node + */ + private static boolean hasModality(Node node) { + final Sequent sequent = node.sequent(); + for (final SequentFormula sequentFormula : sequent) { + if (hasModality(sequentFormula.formula())) { + return true; + } + } + return false; + } + + + private static boolean isUnwindRule(Rule rule) { + if (rule == null) { + return false; + } + final String name = rule.name().toString(); + return TestGenStrategy.unwindRules.contains(name); + } + + public TestGenStrategy(Strategy delegate) { + super(delegate); + limit = TestGenerationSettings.getInstance().getMaximalUnwinds(); + } + + @Override + public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, Goal goal) { + if (TestGenStrategy.isUnwindRule(app.rule())) { + return NumberRuleAppCost.create(TestGenStrategy.UNWIND_COST); + } + return super.computeCost(app, pio, goal); + } + + private int computeUnwindRules(Goal goal) { + int totalUnwinds = 0; + Node node = goal.node(); + while (!node.root()) { + final RuleApp app = node.getAppliedRuleApp(); + if (app != null) { + final Rule rule = app.rule(); + if (TestGenStrategy.isUnwindRule(rule)) { + ++totalUnwinds; + } + } + node = node.parent(); + } + return totalUnwinds; + } + + @Override + public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { + if (!hasModality(goal.node())) { + return false; + } + if (TestGenStrategy.isUnwindRule(app.rule())) { + final int noUnwindRules = computeUnwindRules(goal); + return noUnwindRules < limit; + } + return super.isApprovedApp(app, pio, goal); + } + + @Override + public Name name() { + return TestGenStrategy.NAME; + } + + @Override + public boolean isStopAtFirstNonCloseableGoal() { + return false; + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/settings/TestGenerationSettings.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/settings/TestGenerationSettings.java index f0ce1f818f4..5278b9a8f05 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/settings/TestGenerationSettings.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/settings/TestGenerationSettings.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.settings; import javax.annotation.Nonnull; @@ -10,11 +13,12 @@ import java.util.Properties; public class TestGenerationSettings implements Settings, Cloneable { - //region Default Values for option fields + // region Default Values for option fields private static final boolean DEFAULT_APPLYSYMBOLICEX = false; private static final int DEFAULT_MAXUNWINDS = 3; private static final int DEFAULT_CONCURRENTPROCESSES = 1; - private static final String DEFAULT_OUTPUTPATH = System.getProperty("user.home") + File.separator + "testFiles"; + private static final String DEFAULT_OUTPUTPATH = + System.getProperty("user.home") + File.separator + "testFiles"; private static final boolean DEFAULT_REMOVEDUPLICATES = true; private static final boolean DEFAULT_USERFL = false; private static final boolean DEFAULT_USEJUNIT = false; @@ -22,10 +26,11 @@ public class TestGenerationSettings implements Settings, Cloneable { private static final String DEFAULT_OPENJMLPATH = "."; private static final String DEFAULT_OBJENESISPATH = "."; private static final boolean DEFAULT_INCLUDEPOSTCONDITION = false; - //endregion + // endregion // region property names - private static final String PROP_APPLY_SYMBOLIC_EXECUTION = "[TestGenSettings]applySymbolicExecution"; + private static final String PROP_APPLY_SYMBOLIC_EXECUTION = + "[TestGenSettings]applySymbolicExecution"; private static final String PROP_MAX_UWINDS = "[TestGenSettings]maxUnwinds"; private static final String PROP_OUTPUT_PATH = "[TestGenSettings]OutputPath"; private static final String PROP_REMOVE_DUPLICATES = "[TestGenSettings]RemoveDuplicates"; @@ -35,8 +40,9 @@ public class TestGenerationSettings implements Settings, Cloneable { private static final String PROP_INVARIANT_FOR_ALL = "[TestGenSettings]InvariantForAll"; private static final String PROP_OPENJML_PATH = "[TestGenSettings]OpenJMLPath"; private static final String PROP_OBJENESIS_PATH = "[TestGenSettings]ObjenesisPath"; - private static final String PROP_INCLUDE_POST_CONDITION = "[TestGenSettings]IncludePostCondition"; - //endregion + private static final String PROP_INCLUDE_POST_CONDITION = + "[TestGenSettings]IncludePostCondition"; + // endregion private final Collection listeners; // Option fields @@ -95,7 +101,7 @@ public void removeSettingsListener(SettingsListener l) { listeners.remove(l); } - //FIXME weigl: This method seems broken. I would expect: clone() = new TGS(this) + // FIXME weigl: This method seems broken. I would expect: clone() = new TGS(this) public TestGenerationSettings clone(TestGenerationSettings data) { return new TestGenerationSettings(data); } @@ -136,41 +142,35 @@ public boolean includePostCondition() { @Override public void readSettings(Properties props) { - applySymbolicExecution = SettingsConverter.read(props, - TestGenerationSettings.PROP_APPLY_SYMBOLIC_EXECUTION, - TestGenerationSettings.DEFAULT_APPLYSYMBOLICEX); - maxUnwinds = SettingsConverter.read(props, - TestGenerationSettings.PROP_MAX_UWINDS, + applySymbolicExecution = + SettingsConverter.read(props, TestGenerationSettings.PROP_APPLY_SYMBOLIC_EXECUTION, + TestGenerationSettings.DEFAULT_APPLYSYMBOLICEX); + maxUnwinds = SettingsConverter.read(props, TestGenerationSettings.PROP_MAX_UWINDS, TestGenerationSettings.DEFAULT_MAXUNWINDS); - outputPath = SettingsConverter.read(props, - TestGenerationSettings.PROP_OUTPUT_PATH, + outputPath = SettingsConverter.read(props, TestGenerationSettings.PROP_OUTPUT_PATH, TestGenerationSettings.DEFAULT_OUTPUTPATH); - removeDuplicates = SettingsConverter.read(props, - TestGenerationSettings.PROP_REMOVE_DUPLICATES, - TestGenerationSettings.DEFAULT_REMOVEDUPLICATES); - useRFL = SettingsConverter.read(props, - TestGenerationSettings.PROP_USE_RFL, + removeDuplicates = + SettingsConverter.read(props, TestGenerationSettings.PROP_REMOVE_DUPLICATES, + TestGenerationSettings.DEFAULT_REMOVEDUPLICATES); + useRFL = SettingsConverter.read(props, TestGenerationSettings.PROP_USE_RFL, TestGenerationSettings.DEFAULT_USERFL); - useJunit = SettingsConverter.read(props, - TestGenerationSettings.PROP_USE_JUNIT, + useJunit = SettingsConverter.read(props, TestGenerationSettings.PROP_USE_JUNIT, TestGenerationSettings.DEFAULT_USEJUNIT); - concurrentProcesses = SettingsConverter.read(props, - TestGenerationSettings.PROP_CONCURRENT_PROCESSES, - TestGenerationSettings.DEFAULT_CONCURRENTPROCESSES); - invariantForAll = SettingsConverter.read(props, - TestGenerationSettings.PROP_INVARIANT_FOR_ALL, - TestGenerationSettings.DEFAULT_INVARIANTFORALL); - openjmlPath = SettingsConverter.read(props, - TestGenerationSettings.PROP_OPENJML_PATH, + concurrentProcesses = + SettingsConverter.read(props, TestGenerationSettings.PROP_CONCURRENT_PROCESSES, + TestGenerationSettings.DEFAULT_CONCURRENTPROCESSES); + invariantForAll = + SettingsConverter.read(props, TestGenerationSettings.PROP_INVARIANT_FOR_ALL, + TestGenerationSettings.DEFAULT_INVARIANTFORALL); + openjmlPath = SettingsConverter.read(props, TestGenerationSettings.PROP_OPENJML_PATH, TestGenerationSettings.DEFAULT_OPENJMLPATH); - objenesisPath = SettingsConverter.read(props, - TestGenerationSettings.PROP_OBJENESIS_PATH, + objenesisPath = SettingsConverter.read(props, TestGenerationSettings.PROP_OBJENESIS_PATH, TestGenerationSettings.DEFAULT_OBJENESISPATH); - includePostCondition = SettingsConverter.read(props, - TestGenerationSettings.PROP_INCLUDE_POST_CONDITION, - TestGenerationSettings.DEFAULT_INCLUDEPOSTCONDITION); + includePostCondition = + SettingsConverter.read(props, TestGenerationSettings.PROP_INCLUDE_POST_CONDITION, + TestGenerationSettings.DEFAULT_INCLUDEPOSTCONDITION); } public boolean removeDuplicates() { @@ -236,31 +236,20 @@ public boolean useJunit() { @Override public void writeSettings(Properties props) { - SettingsConverter.store(props, - TestGenerationSettings.PROP_APPLY_SYMBOLIC_EXECUTION, + SettingsConverter.store(props, TestGenerationSettings.PROP_APPLY_SYMBOLIC_EXECUTION, applySymbolicExecution); - SettingsConverter.store(props, - TestGenerationSettings.PROP_CONCURRENT_PROCESSES, + SettingsConverter.store(props, TestGenerationSettings.PROP_CONCURRENT_PROCESSES, concurrentProcesses); - SettingsConverter.store(props, - TestGenerationSettings.PROP_INVARIANT_FOR_ALL, + SettingsConverter.store(props, TestGenerationSettings.PROP_INVARIANT_FOR_ALL, invariantForAll); - SettingsConverter.store(props, TestGenerationSettings.PROP_MAX_UWINDS, - maxUnwinds); - SettingsConverter.store(props, TestGenerationSettings.PROP_OUTPUT_PATH, - outputPath); - SettingsConverter.store(props, - TestGenerationSettings.PROP_REMOVE_DUPLICATES, + SettingsConverter.store(props, TestGenerationSettings.PROP_MAX_UWINDS, maxUnwinds); + SettingsConverter.store(props, TestGenerationSettings.PROP_OUTPUT_PATH, outputPath); + SettingsConverter.store(props, TestGenerationSettings.PROP_REMOVE_DUPLICATES, removeDuplicates); - SettingsConverter.store(props, - TestGenerationSettings.PROP_USE_RFL, - useRFL); - SettingsConverter.store(props, TestGenerationSettings.PROP_USE_JUNIT, - useJunit); - SettingsConverter.store(props, TestGenerationSettings.PROP_OPENJML_PATH, - openjmlPath); - SettingsConverter.store(props, TestGenerationSettings.PROP_OBJENESIS_PATH, - objenesisPath); + SettingsConverter.store(props, TestGenerationSettings.PROP_USE_RFL, useRFL); + SettingsConverter.store(props, TestGenerationSettings.PROP_USE_JUNIT, useJunit); + SettingsConverter.store(props, TestGenerationSettings.PROP_OPENJML_PATH, openjmlPath); + SettingsConverter.store(props, TestGenerationSettings.PROP_OBJENESIS_PATH, objenesisPath); SettingsConverter.store(props, TestGenerationSettings.PROP_INCLUDE_POST_CONDITION, includePostCondition); } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractCounterExampleGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractCounterExampleGenerator.java index d74853ca538..0fb3ebf44c9 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractCounterExampleGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractCounterExampleGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.counterexample; import java.util.LinkedList; @@ -22,116 +25,121 @@ import org.slf4j.LoggerFactory; /** - * Implementations of this class are used find a counter example for a given - * {@link Sequent} using the SMT solver {@link SolverPropertiesHandler#Z3_CE_SOLVER}. + * Implementations of this class are used find a counter example for a given {@link Sequent} using + * the SMT solver {@link SolverPropertiesHandler#Z3_CE_SOLVER}. *

    - * This class provides the full logic independent from the a user interface. - * Subclasses are used to realize the user interface specific functionality. + * This class provides the full logic independent from the a user interface. Subclasses are + * used to realize the user interface specific functionality. *

    - * When {@link #searchCounterExample(KeYMediator, Proof, Sequent)} is called - * a new {@link Proof} is instantiated by {@link #createProof(KeYMediator, Proof, Sequent)}. - * Next the macro {@link SemanticsBlastingMacro} is performed on the new {@link Proof} - * and when done the SMT solver is started. The progress of the SMT solver and - * the final result can be observed by a {@link SolverLauncherListener} instantiated. - * by {@link #createSolverListener(DefaultSMTSettings)}. + * When {@link #searchCounterExample(KeYMediator, Proof, Sequent)} is called a new {@link Proof} is + * instantiated by {@link #createProof(KeYMediator, Proof, Sequent)}. Next the macro + * {@link SemanticsBlastingMacro} is performed on the new {@link Proof} and when done the SMT solver + * is started. The progress of the SMT solver and the final result can be observed by a + * {@link SolverLauncherListener} instantiated. by + * {@link #createSolverListener(DefaultSMTSettings)}. */ public abstract class AbstractCounterExampleGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCounterExampleGenerator.class); - - /** - * Checks if the required SMT solver is available. - * @return {@code true} solver is available, {@code false} solver is not available. - */ - public static boolean isSolverAvailable() { - return SolverTypes.Z3_CE_SOLVER.isInstalled(true); - } - - /** - * Searches a counter example for the given {@link Sequent}. - * @param ui The {@link UserInterfaceControl} to use. - * @param oldProof The old {@link Proof} used as template to instantiate a new one. - * @param oldSequent The {@link Sequent} to find a counter example for. - * @throws ProofInputException Occurred Exception. - */ - public void searchCounterExample(UserInterfaceControl ui, - Proof oldProof, - Sequent oldSequent) throws ProofInputException { - if (!isSolverAvailable()) { - throw new IllegalStateException("Can't find SMT solver " + SolverTypes.Z3_CE_SOLVER.getName()); - } - - final Proof proof = createProof(ui, oldProof, oldSequent, "Semantics Blasting: " + oldProof.name()); - final SemanticsBlastingMacro macro = new SemanticsBlastingMacro(); - TaskFinishedInfo info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); - final ProverTaskListener ptl = ui.getProofControl().getDefaultProverTaskListener(); - ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - - try { - synchronized(macro) { // TODO: Useless? No other thread has access to macro wait for macro to terminate - info = macro.applyTo(ui, proof, proof.openEnabledGoals(), null, ptl); - } - } catch (InterruptedException e) { - LOGGER.debug("Semantics blasting interrupted"); - } finally { - semanticsBlastingCompleted(ui); - ptl.taskFinished(info); - } - - //invoke z3 for counterexamples - DefaultSMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), - ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), - proof.getSettings().getNewSMTSettings(), proof); - SolverLauncher launcher = new SolverLauncher(settings); - launcher.addListener(createSolverListener(settings, proof)); - - List solvers = new LinkedList(); - solvers.add(SolverTypes.Z3_CE_SOLVER); - - launcher.launch(solvers, - SMTProblem.createSMTProblems(proof), - proof.getServices()); - - - } - - /** - * Creates a new {@link Proof}. - * @param ui The {@link UserInterfaceControl} to use. - * @param oldProof The old {@link Proof} used as template to instantiate a new one. - * @param oldSequent The {@link Sequent} to find a counter example for. - * @param proofName The name for the new proof. - * @return The created {@link Proof}. - * @throws ProofInputException Ocurred Exception - */ - protected abstract Proof createProof(UserInterfaceControl ui, - Proof oldProof, - Sequent oldSequent, - String proofName) throws ProofInputException; - - - /** - * Creates the {@link Sequent} for the new {@link Proof} created by - * {@link #createProof(KeYMediator, Proof, Sequent)}. - * @param oldSequent The {@link Sequent} to find a counter example for. - * @return The new {@link Sequent}. - */ - protected Sequent createNewSequent(Sequent oldSequent) { - return Sequent.createSequent(oldSequent.antecedent(), oldSequent.succedent()); - } - - /** - * This method is called after the {@link SemanticsBlastingMacro} has been executed. - * @param ui The {@link UserInterfaceControl} to use. - */ - protected void semanticsBlastingCompleted(UserInterfaceControl ui) { - } - - /** - * Creates the {@link SolverLauncherListener} which handles the results - * of the launched SMT solver. - * @param settings The {@link DefaultSMTSettings}. - * @param proof The {@link Proof} on which the SMT solver will be performed. - * @return The {@link SolverLauncherListener} to use. - */ - protected abstract SolverLauncherListener createSolverListener(DefaultSMTSettings settings, Proof proof); + private static final Logger LOGGER = + LoggerFactory.getLogger(AbstractCounterExampleGenerator.class); + + /** + * Checks if the required SMT solver is available. + * + * @return {@code true} solver is available, {@code false} solver is not available. + */ + public static boolean isSolverAvailable() { + return SolverTypes.Z3_CE_SOLVER.isInstalled(true); + } + + /** + * Searches a counter example for the given {@link Sequent}. + * + * @param ui The {@link UserInterfaceControl} to use. + * @param oldProof The old {@link Proof} used as template to instantiate a new one. + * @param oldSequent The {@link Sequent} to find a counter example for. + * @throws ProofInputException Occurred Exception. + */ + public void searchCounterExample(UserInterfaceControl ui, Proof oldProof, Sequent oldSequent) + throws ProofInputException { + if (!isSolverAvailable()) { + throw new IllegalStateException( + "Can't find SMT solver " + SolverTypes.Z3_CE_SOLVER.getName()); + } + + final Proof proof = + createProof(ui, oldProof, oldSequent, "Semantics Blasting: " + oldProof.name()); + final SemanticsBlastingMacro macro = new SemanticsBlastingMacro(); + TaskFinishedInfo info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); + final ProverTaskListener ptl = ui.getProofControl().getDefaultProverTaskListener(); + ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); + + try { + synchronized (macro) { // TODO: Useless? No other thread has access to macro wait for + // macro to terminate + info = macro.applyTo(ui, proof, proof.openEnabledGoals(), null, ptl); + } + } catch (InterruptedException e) { + LOGGER.debug("Semantics blasting interrupted"); + } finally { + semanticsBlastingCompleted(ui); + ptl.taskFinished(info); + } + + // invoke z3 for counterexamples + DefaultSMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), + proof.getSettings().getNewSMTSettings(), proof); + SolverLauncher launcher = new SolverLauncher(settings); + launcher.addListener(createSolverListener(settings, proof)); + + List solvers = new LinkedList(); + solvers.add(SolverTypes.Z3_CE_SOLVER); + + launcher.launch(solvers, SMTProblem.createSMTProblems(proof), proof.getServices()); + + + } + + /** + * Creates a new {@link Proof}. + * + * @param ui The {@link UserInterfaceControl} to use. + * @param oldProof The old {@link Proof} used as template to instantiate a new one. + * @param oldSequent The {@link Sequent} to find a counter example for. + * @param proofName The name for the new proof. + * @return The created {@link Proof}. + * @throws ProofInputException Ocurred Exception + */ + protected abstract Proof createProof(UserInterfaceControl ui, Proof oldProof, + Sequent oldSequent, String proofName) throws ProofInputException; + + + /** + * Creates the {@link Sequent} for the new {@link Proof} created by + * {@link #createProof(KeYMediator, Proof, Sequent)}. + * + * @param oldSequent The {@link Sequent} to find a counter example for. + * @return The new {@link Sequent}. + */ + protected Sequent createNewSequent(Sequent oldSequent) { + return Sequent.createSequent(oldSequent.antecedent(), oldSequent.succedent()); + } + + /** + * This method is called after the {@link SemanticsBlastingMacro} has been executed. + * + * @param ui The {@link UserInterfaceControl} to use. + */ + protected void semanticsBlastingCompleted(UserInterfaceControl ui) {} + + /** + * Creates the {@link SolverLauncherListener} which handles the results of the launched SMT + * solver. + * + * @param settings The {@link DefaultSMTSettings}. + * @param proof The {@link Proof} on which the SMT solver will be performed. + * @return The {@link SolverLauncherListener} to use. + */ + protected abstract SolverLauncherListener createSolverListener(DefaultSMTSettings settings, + Proof proof); } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractSideProofCounterExampleGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractSideProofCounterExampleGenerator.java index 7ac86a2e304..1ff71e0d080 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractSideProofCounterExampleGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/counterexample/AbstractSideProofCounterExampleGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.counterexample; import de.uka.ilkd.key.control.UserInterfaceControl; @@ -11,21 +14,23 @@ import de.uka.ilkd.key.util.SideProofUtil; /** - * Implementation of {@link AbstractCounterExampleGenerator} which instantiates - * the new {@link Proof} as side proof. + * Implementation of {@link AbstractCounterExampleGenerator} which instantiates the new + * {@link Proof} as side proof. */ -public abstract class AbstractSideProofCounterExampleGenerator extends AbstractCounterExampleGenerator { - /** - * {@inheritDoc} - */ - @Override - protected Proof createProof(UserInterfaceControl ui, Proof oldProof, Sequent oldSequent, String proofName) throws ProofInputException { - Sequent newSequent = createNewSequent(oldSequent); - ProofEnvironment env = - SideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(oldProof, new Choice("ban", "runtimeExceptions")); - ProofStarter starter = SideProofUtil.createSideProof(env, newSequent, proofName); - Proof proof = starter.getProof(); - OneStepSimplifier.refreshOSS(proof); - return proof; - } +public abstract class AbstractSideProofCounterExampleGenerator + extends AbstractCounterExampleGenerator { + /** + * {@inheritDoc} + */ + @Override + protected Proof createProof(UserInterfaceControl ui, Proof oldProof, Sequent oldSequent, + String proofName) throws ProofInputException { + Sequent newSequent = createNewSequent(oldSequent); + ProofEnvironment env = SideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(oldProof, + new Choice("ban", "runtimeExceptions")); + ProofStarter starter = SideProofUtil.createSideProof(env, newSequent, proofName); + Proof proof = starter.getProof(); + OneStepSimplifier.refreshOSS(proof); + return proof; + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/AbstractTestGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/AbstractTestGenerator.java index 1c41545e974..d1583a3f0ed 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/AbstractTestGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/AbstractTestGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.testgen; import java.io.IOException; @@ -46,411 +49,409 @@ /** * Implementations of this class are used generate test cases or a given {@link Proof}. *

    - * This class provides the full logic independent from the a user interface. - * Subclasses are used to realize the user interface specific functionality. + * This class provides the full logic independent from the a user interface. Subclasses are + * used to realize the user interface specific functionality. */ public abstract class AbstractTestGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestGenerator.class); - private final UserInterfaceControl ui; - private final Proof originalProof; - private SolverLauncher launcher; - private List proofs; + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestGenerator.class); + private final UserInterfaceControl ui; + private final Proof originalProof; + private SolverLauncher launcher; + private List proofs; + + /** + * Constructor. + * + * @param ui The {@link UserInterfaceControl} to use. + * @param originalProof The {@link Proof} to generate test cases for. + */ + protected AbstractTestGenerator(UserInterfaceControl ui, Proof originalProof) { + this.ui = ui; + this.originalProof = originalProof; + } + + public void generateTestCases(final StopRequest stopRequest, final TestGenerationLog log) { - /** - * Constructor. - * @param ui The {@link UserInterfaceControl} to use. - * @param originalProof The {@link Proof} to generate test cases for. - */ - protected AbstractTestGenerator(UserInterfaceControl ui, Proof originalProof) { - this.ui = ui; - this.originalProof = originalProof; - } - public void generateTestCases(final StopRequest stopRequest, - final TestGenerationLog log) { + TestGenerationSettings settings = TestGenerationSettings.getInstance(); - TestGenerationSettings settings = TestGenerationSettings.getInstance(); + if (!SolverTypes.Z3_CE_SOLVER.isInstalled(true)) { + log.writeln("Could not find the z3 SMT solver. Aborting."); + return; + } + if (!SolverTypes.Z3_CE_SOLVER.isSupportedVersion()) { + log.writeln("Warning: z3 supported minimum supported version is: " + + SolverTypes.Z3_CE_SOLVER.getMinimumSupportedVersion()); + } + if (originalProof.closed() && settings.includePostCondition()) { + log.writeln("Cannot generate test cases from closed proof with " + + "\nInclude Postcondition option activated. Aborting."); + return; + } + if (settings.getApplySymbolicExecution()) { + log.writeln("Applying TestGen Macro (bounded symbolic execution)..."); + try { + TestGenMacro macro = new TestGenMacro(); + macro.applyTo(ui, originalProof, originalProof.openEnabledGoals(), null, null); + log.writeln("Finished symbolic execution."); + } catch (Exception ex) { + log.writeException(ex); + } + } + + log.writeln("Extracting test data constraints (path conditions)."); + proofs = createProofsForTesting(settings.removeDuplicates(), + !settings.includePostCondition()); + if (stopRequest != null && stopRequest.shouldStop()) { + return; + } + if (!proofs.isEmpty()) { + log.writeln("Extracted " + proofs.size() + " test data constraints."); + } else { + log.writeln("No test data constraints were extracted."); + } + final Collection problems = new LinkedList<>(); + log.writeln("Test data generation: appling semantic blasting macro on proofs"); + try { + for (final Proof proof : proofs) { + if (stopRequest != null && stopRequest.shouldStop()) { + return; + } + log.write("."); + final SemanticsBlastingMacro macro = new SemanticsBlastingMacro(); + TaskFinishedInfo info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); + final ProverTaskListener ptl = ui.getProofControl().getDefaultProverTaskListener(); + try { + if (stopRequest != null && stopRequest.shouldStop()) { + return; + } + + selectProof(ui, proof); + + ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); + info = macro.applyTo(ui, proof, proof.openEnabledGoals(), null, ptl); + problems.addAll(SMTProblem.createSMTProblems(proof)); + } catch (final InterruptedException e) { + LOGGER.debug("Semantics blasting interrupted"); + log.writeln("\n Warning: semantics blasting was interrupted. " + + "A test case will not be generated."); + } catch (final Exception e) { + log.writeln(e.getLocalizedMessage()); + LOGGER.warn("", e); + } finally { + ptl.taskFinished(info); + } + } + } finally { + handleAllProofsPerformed(ui); + } + log.writeln("\nDone applying semantic blasting."); + selectProof(ui, originalProof); + final Proof proof = originalProof; + + // create special smt settings for test case generation + final ProofIndependentSMTSettings piSettings = + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings().clone(); + piSettings.setMaxConcurrentProcesses(settings.getNumberOfProcesses()); + final ProofDependentSMTSettings pdSettings = proof.getSettings().getSMTSettings().clone(); + final NewSMTTranslationSettings newSettings = + new NewSMTTranslationSettings(proof.getSettings().getNewSMTSettings()); + pdSettings.invariantForall = settings.invariantForAll(); + // invoke z3 for counterexamples + final DefaultSMTSettings smtsettings = + new DefaultSMTSettings(pdSettings, piSettings, newSettings, proof); + launcher = new SolverLauncher(smtsettings); + launcher.addListener(new SolverLauncherListener() { + @Override + public void launcherStopped(SolverLauncher launcher, + Collection finishedSolvers) { + handleLauncherStopped(launcher, finishedSolvers, log); + } - if (!SolverTypes.Z3_CE_SOLVER.isInstalled(true)) { - log - .writeln("Could not find the z3 SMT solver. Aborting."); - return; + @Override + public void launcherStarted(Collection problems, + Collection solverTypes, SolverLauncher launcher) { + handleLauncherStarted(problems, solverTypes, launcher, log); + } + }); + final List solvers = new LinkedList<>(); + solvers.add(SolverTypes.Z3_CE_SOLVER); + SolverTypes.Z3_CE_SOLVER.checkForSupport(); + if (stopRequest != null && stopRequest.shouldStop()) { + return; + } + if (Thread.interrupted()) { + return; + } + launcher.launch(solvers, problems, proof.getServices()); } - if (!SolverTypes.Z3_CE_SOLVER.isSupportedVersion()) { - log.writeln("Warning: z3 supported minimum supported version is: " - + SolverTypes.Z3_CE_SOLVER.getMinimumSupportedVersion()); + + protected void handleAllProofsPerformed(UserInterfaceControl ui) { + // Work has only to be done in the MainWindow implementation. } - if(originalProof.closed() && settings.includePostCondition()){ - log.writeln("Cannot generate test cases from closed proof with " - + "\nInclude Postcondition option activated. Aborting."); - return; + + /** + * Removes all generated proofs. + */ + public void dispose() { + if (proofs != null) { + for (final Proof p : proofs) { + p.dispose(); + } + } } - if(settings.getApplySymbolicExecution()){ - log.writeln("Applying TestGen Macro (bounded symbolic execution)..."); - try { - TestGenMacro macro = new TestGenMacro(); - macro.applyTo(ui, originalProof, originalProof.openEnabledGoals(), null, null); - log.writeln("Finished symbolic execution."); + protected void selectProof(UserInterfaceControl ui, Proof proof) { + // Work has only to be done in the MainWindow implementation. + } + + /** + * Creates a proof for each open node if the selected proof is open and a proof for each node on + * which the emptyModality rules was applied if the selected proof is closed. + * + * @param removeDuplicatePathConditions - if true no identical proofs will be created + * @param removePostCondition - if true, remove post condition + * @return a list of proofs + */ + private List createProofsForTesting(boolean removeDuplicatePathConditions, + boolean removePostCondition) { + final List res = new LinkedList<>(); + final List nodes = new LinkedList<>(); + final ImmutableList oldGoals = originalProof.openGoals(); + if (originalProof.closed()) { + getNodesWithEmptyModalities(originalProof.root(), nodes); + } else { + for (final Goal goal : oldGoals) { + nodes.add(goal.node()); + } } - catch(Exception ex) { - log.writeException(ex); + final Iterator oldGoalIter = nodes.iterator(); + while (oldGoalIter.hasNext()) { + try { + Proof p; + if (removeDuplicatePathConditions) { + p = createProofForTestingNoDuplicate(oldGoalIter.next(), res, + removePostCondition); + } else { + p = createProofForTestingNoDuplicate(oldGoalIter.next(), null, + removePostCondition); + } + if (p != null) { + res.add(p); + } + } catch (final Exception e) { + LOGGER.error("Could not create a proof for testing", e); + } } + return res; } - log.writeln("Extracting test data constraints (path conditions)."); - proofs = createProofsForTesting(settings.removeDuplicates(), ! settings.includePostCondition()); - if (stopRequest != null && stopRequest.shouldStop()) { - return; - } - if (!proofs.isEmpty()) { - log.writeln("Extracted " + proofs.size() - + " test data constraints."); - } else { - log.writeln("No test data constraints were extracted."); + /** + * Adds all nodes on which the emptyModality rule was applied to the list. + * + * @param root the root node + * @param nodes the nodes to be added + */ + private void getNodesWithEmptyModalities(Node root, List nodes) { + if (root.getAppliedRuleApp() != null) { + final RuleApp app = root.getAppliedRuleApp(); + if (app.rule().name().toString().equals("emptyModality")) { + nodes.add(root); + } + } + for (int i = 0; i < root.childrenCount(); ++i) { + getNodesWithEmptyModalities(root.child(i), nodes); + } } - final Collection problems = new LinkedList<>(); - log.writeln("Test data generation: appling semantic blasting macro on proofs"); - try { - for (final Proof proof : proofs) { - if (stopRequest != null && stopRequest.shouldStop()) { - return; - } - log.write("."); - final SemanticsBlastingMacro macro = new SemanticsBlastingMacro(); - TaskFinishedInfo info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); - final ProverTaskListener ptl = ui.getProofControl().getDefaultProverTaskListener(); - try { - if (stopRequest != null && stopRequest.shouldStop()) { - return; - } - - selectProof(ui, proof); - - ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - info = macro.applyTo(ui, proof, proof.openEnabledGoals(), null, ptl); - problems.addAll(SMTProblem.createSMTProblems(proof)); - } catch (final InterruptedException e) { - LOGGER.debug("Semantics blasting interrupted"); - log.writeln("\n Warning: semantics blasting was interrupted. " - + "A test case will not be generated."); - } catch (final Exception e) { - log.writeln(e.getLocalizedMessage()); - LOGGER.warn("",e); - } finally { - ptl.taskFinished(info); - } - } + + /** + * Creates a proof with the specified node as its root. If an identical proof is found in + * otherProofs than null will be returned instead. + * + * @param node the new root node + * @param otherProofs a list of proofs as described above + * @param removePostCondition if true, then remove post condition + * @return the new proof with the specified root node + * @throws ProofInputException exception for proof input + */ + private Proof createProofForTestingNoDuplicate(Node node, List otherProofs, + boolean removePostCondition) throws ProofInputException { + final Proof oldProof = node.proof(); + final Sequent oldSequent = node.sequent(); + Sequent newSequent = + Sequent.createSequent(Semisequent.EMPTY_SEMISEQUENT, Semisequent.EMPTY_SEMISEQUENT); + Iterator it = oldSequent.antecedent().iterator(); + while (it.hasNext()) { + final SequentFormula sf = it.next(); + // Allow updates modailities in the antecedent + if (hasModalities(sf.formula(), false)) { + continue; + } + newSequent = newSequent.addFormula(sf, true, false).sequent(); + } + it = oldSequent.succedent().iterator(); + while (it.hasNext()) { + final SequentFormula sf = it.next(); + if (hasModalities(sf.formula(), removePostCondition)) { + continue; + } + newSequent = newSequent.addFormula(sf, false, false).sequent(); + } + // Check if a proof with the same sequent already exists. + if (otherProofs != null) { + for (final Proof otherProof : otherProofs) { + if (otherProof.root().sequent().equals(newSequent)) { + // Found and skip duplicate proof for node + return null; + } + } + } + return createProof(ui, oldProof, "Test Case for NodeNr: " + node.serialNr(), newSequent); } - finally { - handleAllProofsPerformed(ui); + + protected Proof createProof(UserInterfaceControl ui, Proof oldProof, String newName, + Sequent newSequent) throws ProofInputException { + ProofEnvironment env = SideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(oldProof, + new Choice("ban", "runtimeExceptions")); + ProofStarter starter = SideProofUtil.createSideProof(env, newSequent, newName); + Proof proof = starter.getProof(); + proof.getServices().getSpecificationRepository().registerProof( + proof.getServices().getSpecificationRepository().getProofOblInput(oldProof), proof); + OneStepSimplifier.refreshOSS(proof); + return proof; } - log.writeln("\nDone applying semantic blasting."); - selectProof(ui, originalProof); - final Proof proof = originalProof; - - //create special smt settings for test case generation - final ProofIndependentSMTSettings piSettings = ProofIndependentSettings.DEFAULT_INSTANCE - .getSMTSettings().clone(); - piSettings.setMaxConcurrentProcesses(settings.getNumberOfProcesses()); - final ProofDependentSMTSettings pdSettings = proof.getSettings() - .getSMTSettings().clone(); - final NewSMTTranslationSettings newSettings = - new NewSMTTranslationSettings(proof.getSettings() - .getNewSMTSettings()); - pdSettings.invariantForall = settings.invariantForAll(); - // invoke z3 for counterexamples - final DefaultSMTSettings smtsettings = new DefaultSMTSettings(pdSettings, - piSettings, newSettings, proof); - launcher = new SolverLauncher(smtsettings); - launcher.addListener(new SolverLauncherListener() { - @Override - public void launcherStopped(SolverLauncher launcher, Collection finishedSolvers) { - handleLauncherStopped(launcher, finishedSolvers, log); - } - - @Override - public void launcherStarted(Collection problems, Collection solverTypes, SolverLauncher launcher) { - handleLauncherStarted(problems, solverTypes, launcher, log); - } - }); - final List solvers = new LinkedList<>(); - solvers.add(SolverTypes.Z3_CE_SOLVER); - SolverTypes.Z3_CE_SOLVER.checkForSupport(); - if (stopRequest != null && stopRequest.shouldStop()) { - return; + + private boolean hasModalities(Term t, boolean checkUpdates) { + final JavaBlock jb = t.javaBlock(); + if (jb != null && !jb.isEmpty()) { + return true; + } + if (t.op() == UpdateApplication.UPDATE_APPLICATION && checkUpdates) { + return true; + } + boolean res = false; + for (int i = 0; i < t.arity() && !res; i++) { + res |= hasModalities(t.sub(i), checkUpdates); + } + return res; } - if (Thread.interrupted()) { - return; + + + protected void handleLauncherStarted(Collection problems, + Collection solverTypes, SolverLauncher launcher, TestGenerationLog log) { + log.writeln("Test data generation: solving " + problems.size() + + " SMT problems... \n please wait..."); } - launcher.launch(solvers, problems, proof.getServices()); - } - - protected void handleAllProofsPerformed(UserInterfaceControl ui) { - // Work has only to be done in the MainWindow implementation. - } - - /** - * Removes all generated proofs. - */ - public void dispose() { - if (proofs != null) { - for (final Proof p : proofs) { - p.dispose(); - } - } - } - - protected void selectProof(UserInterfaceControl ui, Proof proof) { - // Work has only to be done in the MainWindow implementation. - } - - /** - * Creates a proof for each open node if the selected proof is open and a - * proof for each node on which the emptyModality rules was applied if the - * selected proof is closed. - * - * @param removeDuplicatePathConditions - * - if true no identical proofs will be created - * @param removePostCondition - * - if true, remove post condition - * @return a list of proofs - */ - private List createProofsForTesting(boolean removeDuplicatePathConditions, boolean removePostCondition) { - final List res = new LinkedList<>(); - final List nodes = new LinkedList<>(); - final ImmutableList oldGoals = originalProof.openGoals(); - if (originalProof.closed()) { - getNodesWithEmptyModalities( - originalProof.root(), nodes); - } else { - for (final Goal goal : oldGoals) { - nodes.add(goal.node()); - } - } - final Iterator oldGoalIter = nodes.iterator(); - while (oldGoalIter.hasNext()) { - try { - Proof p; - if (removeDuplicatePathConditions) { - p = createProofForTestingNoDuplicate(oldGoalIter.next(), - res, removePostCondition); + + protected void handleLauncherStopped(SolverLauncher launcher, + Collection problemSolvers, TestGenerationLog log) { + try { + log.writeln("Finished solving SMT problems: " + problemSolvers.size()); + problemSolvers = filterSolverResultsAndShowSolverStatistics(problemSolvers, log); + if (!problemSolvers.isEmpty()) { + generateFiles(problemSolvers, log, originalProof); } else { - p = createProofForTestingNoDuplicate(oldGoalIter.next(), - null, removePostCondition); - } - if (p != null) { - res.add(p); + log.writeln("No test data was generated."); + informAboutNoTestResults(launcher, problemSolvers, log, originalProof); } - } catch (final Exception e) { - LOGGER.error("Could not create a proof for testing", e); - } - } - return res; - } - - /** - * Adds all nodes on which the emptyModality rule was applied to the list. - * - * @param root the root node - * @param nodes the nodes to be added - */ - private void getNodesWithEmptyModalities(Node root, List nodes) { - if (root.getAppliedRuleApp() != null) { - final RuleApp app = root.getAppliedRuleApp(); - if (app.rule().name().toString().equals("emptyModality")) { - nodes.add(root); - } - } - for (int i = 0; i < root.childrenCount(); ++i) { - getNodesWithEmptyModalities(root.child(i), nodes); - } - } - - /** - * Creates a proof with the specified node as its root. If an identical - * proof is found in otherProofs than null will be returned instead. - * - * @param node the new root node - * @param otherProofs a list of proofs as described above - * @param removePostCondition if true, then remove post condition - * @return the new proof with the specified root node - * @throws ProofInputException exception for proof input - */ - private Proof createProofForTestingNoDuplicate(Node node, List otherProofs, boolean removePostCondition) - throws ProofInputException { - final Proof oldProof = node.proof(); - final Sequent oldSequent = node.sequent(); - Sequent newSequent = Sequent.createSequent( - Semisequent.EMPTY_SEMISEQUENT, Semisequent.EMPTY_SEMISEQUENT); - Iterator it = oldSequent.antecedent().iterator(); - while (it.hasNext()) { - final SequentFormula sf = it.next(); - // Allow updates modailities in the antecedent - if (hasModalities(sf.formula(), false)) { - continue; - } - newSequent = newSequent.addFormula(sf, true, false).sequent(); - } - it = oldSequent.succedent().iterator(); - while (it.hasNext()) { - final SequentFormula sf = it.next(); - if (hasModalities(sf.formula(), removePostCondition)) { - continue; - } - newSequent = newSequent.addFormula(sf, false, false).sequent(); - } - // Check if a proof with the same sequent already exists. - if (otherProofs != null) { - for (final Proof otherProof : otherProofs) { - if (otherProof.root().sequent().equals(newSequent)) { - // Found and skip duplicate proof for node - return null; - } - } - } - return createProof(ui, oldProof, "Test Case for NodeNr: " + node.serialNr(), newSequent); - } - - protected Proof createProof(UserInterfaceControl ui, Proof oldProof, String newName, Sequent newSequent) throws ProofInputException { - ProofEnvironment env = SideProofUtil.cloneProofEnvironmentWithOwnOneStepSimplifier(oldProof, - new Choice("ban", "runtimeExceptions")); - ProofStarter starter = SideProofUtil.createSideProof(env, newSequent, newName); - Proof proof = starter.getProof(); - proof.getServices().getSpecificationRepository().registerProof(proof.getServices().getSpecificationRepository().getProofOblInput(oldProof), proof); - OneStepSimplifier.refreshOSS(proof); - return proof; - } - - private boolean hasModalities(Term t, boolean checkUpdates) { - final JavaBlock jb = t.javaBlock(); - if (jb != null && !jb.isEmpty()) { - return true; - } - if (t.op() == UpdateApplication.UPDATE_APPLICATION && checkUpdates) { - return true; - } - boolean res = false; - for (int i = 0; i < t.arity() && !res; i++) { - res |= hasModalities(t.sub(i), checkUpdates); - } - return res; - } - - - protected void handleLauncherStarted(Collection problems, Collection solverTypes, SolverLauncher launcher, TestGenerationLog log) { - log.writeln("Test data generation: solving "+problems.size()+" SMT problems... \n please wait..."); - } - - protected void handleLauncherStopped(SolverLauncher launcher, Collection problemSolvers, TestGenerationLog log) { - try { - log.writeln("Finished solving SMT problems: " + problemSolvers.size()); - problemSolvers = filterSolverResultsAndShowSolverStatistics(problemSolvers, log); - if (!problemSolvers.isEmpty()) { - generateFiles(problemSolvers, log, originalProof); - } else { - log.writeln("No test data was generated."); - informAboutNoTestResults(launcher, problemSolvers, log, originalProof); - } - log.testGenerationCompleted(); - } - catch (Exception e) { - log.writeException(e); - } - } - - protected void generateFiles(Collection problemSolvers, TestGenerationLog log, Proof originalProof) - throws IOException { - final TestCaseGenerator tg = new TestCaseGenerator(originalProof); - tg.setLogger(log); - - tg.generateJUnitTestSuite(problemSolvers); - if (tg.isJunit()) { - log.writeln("Compile the generated files using a Java compiler."); - } else { - log.writeln("Compile and run the file with openjml!"); - } - } - - /** - * This method is used in the Eclipse world to show a dialog with the log. - */ - protected void informAboutNoTestResults(SolverLauncher launcher, Collection problemSolvers, TestGenerationLog log, Proof originalProof) { - } - - public Collection filterSolverResultsAndShowSolverStatistics(Collection problemSolvers, TestGenerationLog log) { - int unknown = 0; - int infeasiblePaths = 0; - int solvedPaths = 0; - int problem = 0; - final List output = new ArrayList<>(); - for (final SMTSolver solver : problemSolvers) { - try { - final SMTSolverResult.ThreeValuedTruth res = solver - .getFinalResult().isValid(); - if (res == SMTSolverResult.ThreeValuedTruth.UNKNOWN) { - unknown++; - if(solver.getException() != null){ - solver.getException().printStackTrace(); - } - } else if (res == SMTSolverResult.ThreeValuedTruth.FALSIFIABLE) { - solvedPaths++; - if (solver.getSocket().getQuery() != null) { - final Model m = solver.getSocket().getQuery() - .getModel(); - if (TestCaseGenerator.modelIsOK(m)) { - output.add(solver); - } else { - problem++; - } - } else { - problem++; - } - } else if (res == SMTSolverResult.ThreeValuedTruth.VALID) { - infeasiblePaths++; + log.testGenerationCompleted(); + } catch (Exception e) { + log.writeException(e); + } + } + + protected void generateFiles(Collection problemSolvers, TestGenerationLog log, + Proof originalProof) throws IOException { + final TestCaseGenerator tg = new TestCaseGenerator(originalProof); + tg.setLogger(log); + + tg.generateJUnitTestSuite(problemSolvers); + if (tg.isJunit()) { + log.writeln("Compile the generated files using a Java compiler."); + } else { + log.writeln("Compile and run the file with openjml!"); + } + } + + /** + * This method is used in the Eclipse world to show a dialog with the log. + */ + protected void informAboutNoTestResults(SolverLauncher launcher, + Collection problemSolvers, TestGenerationLog log, Proof originalProof) {} + + public Collection filterSolverResultsAndShowSolverStatistics( + Collection problemSolvers, TestGenerationLog log) { + int unknown = 0; + int infeasiblePaths = 0; + int solvedPaths = 0; + int problem = 0; + final List output = new ArrayList<>(); + for (final SMTSolver solver : problemSolvers) { + try { + final SMTSolverResult.ThreeValuedTruth res = solver.getFinalResult().isValid(); + if (res == SMTSolverResult.ThreeValuedTruth.UNKNOWN) { + unknown++; + if (solver.getException() != null) { + solver.getException().printStackTrace(); + } + } else if (res == SMTSolverResult.ThreeValuedTruth.FALSIFIABLE) { + solvedPaths++; + if (solver.getSocket().getQuery() != null) { + final Model m = solver.getSocket().getQuery().getModel(); + if (TestCaseGenerator.modelIsOK(m)) { + output.add(solver); + } else { + problem++; + } + } else { + problem++; + } + } else if (res == SMTSolverResult.ThreeValuedTruth.VALID) { + infeasiblePaths++; + } + } catch (final Exception ex) { + log.writeln(ex.getMessage()); } - } catch (final Exception ex) { - log.writeln(ex.getMessage()); - } - } - log.writeln("--- SMT Solver Results ---\n" + " solved pathconditions:" - + solvedPaths + "\n" + " invalid pre-/pathconditions:" - + infeasiblePaths + "\n" + " unknown:" + unknown); - if (problem > 0) { - log.writeln(" problems :" + problem); - } - if (unknown > 0) { - log.writeln(" Adjust the SMT solver settings (e.g. timeout) in Options->SMT Solvers and restart key.\n Make sure you use Z3 version 4.3.1."); - } - log.writeln("----------------------"); - return output; - } - - public void stopSMTLauncher() { - if (launcher != null) { - launcher.stop(); - } - } - - protected Proof getOriginalProof(){ - return originalProof; - } - - protected List getProofs() { - return proofs; - } - - protected UserInterfaceControl getUI () { - return ui; - } - - /** - * Checks if the required SMT solver is available. - * @return {@code true} solver is available, {@code false} solver is not available. - */ - public static boolean isSolverAvailable() { - return SolverTypes.Z3_CE_SOLVER.isInstalled(true); - } + } + log.writeln("--- SMT Solver Results ---\n" + " solved pathconditions:" + solvedPaths + "\n" + + " invalid pre-/pathconditions:" + infeasiblePaths + "\n" + " unknown:" + unknown); + if (problem > 0) { + log.writeln(" problems :" + problem); + } + if (unknown > 0) { + log.writeln( + " Adjust the SMT solver settings (e.g. timeout) in Options->SMT Solvers and restart key.\n Make sure you use Z3 version 4.3.1."); + } + log.writeln("----------------------"); + return output; + } + + public void stopSMTLauncher() { + if (launcher != null) { + launcher.stop(); + } + } + + protected Proof getOriginalProof() { + return originalProof; + } + + protected List getProofs() { + return proofs; + } + + protected UserInterfaceControl getUI() { + return ui; + } + + /** + * Checks if the required SMT solver is available. + * + * @return {@code true} solver is available, {@code false} solver is not available. + */ + public static boolean isSolverAvailable() { + return SolverTypes.Z3_CE_SOLVER.isInstalled(true); + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/MemoryTestGenerationLog.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/MemoryTestGenerationLog.java index da88aa538af..e5ffb4eb95b 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/MemoryTestGenerationLog.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/MemoryTestGenerationLog.java @@ -1,56 +1,59 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.testgen; import de.uka.ilkd.key.testgen.TestCaseGenerator; /** * Implementation of {@link TestGenerationLog} which stores the log in memory. + * * @author Martin Hentschel */ public class MemoryTestGenerationLog implements TestGenerationLog { - /** - * The {@link StringBuffer} which stores all the content. - */ - private final StringBuffer sb = new StringBuffer(); + /** + * The {@link StringBuffer} which stores all the content. + */ + private final StringBuffer sb = new StringBuffer(); - /** - * {@inheritDoc} - */ - @Override - public void writeln(String string) { - sb.append(string); - sb.append(TestCaseGenerator.NEW_LINE); - } + /** + * {@inheritDoc} + */ + @Override + public void writeln(String string) { + sb.append(string); + sb.append(TestCaseGenerator.NEW_LINE); + } - /** - * {@inheritDoc} - */ - @Override - public void write(String string) { - sb.append(string); - sb.append(TestCaseGenerator.NEW_LINE); - } + /** + * {@inheritDoc} + */ + @Override + public void write(String string) { + sb.append(string); + sb.append(TestCaseGenerator.NEW_LINE); + } - /** - * {@inheritDoc} - */ - @Override - public void writeException(Throwable t) { - sb.append(t.getMessage()); - sb.append(TestCaseGenerator.NEW_LINE); - } + /** + * {@inheritDoc} + */ + @Override + public void writeException(Throwable t) { + sb.append(t.getMessage()); + sb.append(TestCaseGenerator.NEW_LINE); + } - /** - * {@inheritDoc} - */ - @Override - public void testGenerationCompleted() { - } + /** + * {@inheritDoc} + */ + @Override + public void testGenerationCompleted() {} - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return sb.toString(); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return sb.toString(); + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/StopRequest.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/StopRequest.java index 8aa42b33057..aa84c170ea2 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/StopRequest.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/StopRequest.java @@ -1,5 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.testgen; public interface StopRequest { - public boolean shouldStop(); + public boolean shouldStop(); } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/TestGenerationLog.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/TestGenerationLog.java index d05322fe862..b9a9fdcc483 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/TestGenerationLog.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/smt/testgen/TestGenerationLog.java @@ -1,11 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.smt.testgen; public interface TestGenerationLog { - public void writeln(String string); + public void writeln(String string); - public void write(String string); - - public void writeException(Throwable t); - - public void testGenerationCompleted(); + public void write(String string); + + public void writeException(Throwable t); + + public void testGenerationCompleted(); } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/Assignment.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/Assignment.java index b9e2d2b7a63..47aa6144db5 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/Assignment.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/Assignment.java @@ -1,61 +1,70 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; -/** This class creates either assignments or creates calls to setter methods to initiate fields. +/** + * This class creates either assignments or creates calls to setter methods to initiate fields. + * * @author gladisch * @author herda */ public class Assignment { - - - protected final String type; - protected final Object left; - protected final String right; - - public Assignment(String left, String right) { - type = ""; - this.left = left; - this.right = right; - } - - /** The argument left of type RefEx must contains all needed information to invoke a setter method.*/ - public Assignment(RefEx left, String right) { - type = ""; - this.left = left; - this.right = right; - } - - public Assignment(String type, Object left, String right) { - this.type = type; - this.left = left; - this.right = right; - } - - @Override - public String toString() { - return type + " " + left + " = " + right + ";"; - } - - /** @param rfl If this argument is true, then an invokation of a setter method is created, otherwise an assignment is created. - * @return String representation of an assignment or a call to a setter method. */ - public String toString(boolean rfl) { - if(rfl){ - if(left instanceof RefEx){ - final RefEx leftEx = (RefEx)left; - return ReflectionClassCreator.NAME_OF_CLASS + - "."+ - ReflectionClassCreator.SET_PREFIX+ - ReflectionClassCreator.cleanTypeName(leftEx.fieldType)+ - "("+leftEx.rcObjType+".class, "+leftEx.rcObj+", \""+leftEx.field+"\", "+ right+");"; - }else{ - return type + " " + left + " = " + right + ";"; - } - }else{ - return type + " " + left + " = " + right + ";"; - } - } - - - - + + + protected final String type; + protected final Object left; + protected final String right; + + public Assignment(String left, String right) { + type = ""; + this.left = left; + this.right = right; + } + + /** + * The argument left of type RefEx must contains all needed information to invoke a setter + * method. + */ + public Assignment(RefEx left, String right) { + type = ""; + this.left = left; + this.right = right; + } + + public Assignment(String type, Object left, String right) { + this.type = type; + this.left = left; + this.right = right; + } + + @Override + public String toString() { + return type + " " + left + " = " + right + ";"; + } + + /** + * @param rfl If this argument is true, then an invokation of a setter method is created, + * otherwise an assignment is created. + * @return String representation of an assignment or a call to a setter method. + */ + public String toString(boolean rfl) { + if (rfl) { + if (left instanceof RefEx) { + final RefEx leftEx = (RefEx) left; + return ReflectionClassCreator.NAME_OF_CLASS + "." + + ReflectionClassCreator.SET_PREFIX + + ReflectionClassCreator.cleanTypeName(leftEx.fieldType) + "(" + + leftEx.rcObjType + ".class, " + leftEx.rcObj + ", \"" + leftEx.field + + "\", " + right + ");"; + } else { + return type + " " + left + " = " + right + ";"; + } + } else { + return type + " " + left + " = " + right + ";"; + } + } + + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/CustomPrettyPrinter.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/CustomPrettyPrinter.java index b6ea5df8f2f..2c59e321949 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/CustomPrettyPrinter.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/CustomPrettyPrinter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; import java.io.Writer; @@ -8,58 +11,56 @@ import de.uka.ilkd.key.rule.inst.SVInstantiations; public class CustomPrettyPrinter extends PrettyPrinter { - public CustomPrettyPrinter(Writer o) { - super(o); + public CustomPrettyPrinter(Writer o) { + super(o); - } + } - public CustomPrettyPrinter(Writer o, SVInstantiations svi) { - super(o, svi); + public CustomPrettyPrinter(Writer o, SVInstantiations svi) { + super(o, svi); - } + } - public CustomPrettyPrinter(Writer o, boolean noLinefeed) { - super(o, noLinefeed); + public CustomPrettyPrinter(Writer o, boolean noLinefeed) { + super(o, noLinefeed); - } + } - public CustomPrettyPrinter(Writer o, boolean noLinefeed, - SVInstantiations svi) { - super(o, noLinefeed, svi); + public CustomPrettyPrinter(Writer o, boolean noLinefeed, SVInstantiations svi) { + super(o, noLinefeed, svi); - } + } - public void printMethodBodyStatement(MethodBodyStatement x) - throws java.io.IOException { + public void printMethodBodyStatement(MethodBodyStatement x) throws java.io.IOException { - boolean wasNoLinefeed = noLinefeed; - noLinefeed = false; + boolean wasNoLinefeed = noLinefeed; + noLinefeed = false; - printHeader(x); - writeInternalIndentation(x); - markStart(0, x); + printHeader(x); + writeInternalIndentation(x); + markStart(0, x); - IProgramVariable pvar = x.getResultVariable(); - if (pvar != null) { - writeElement(pvar); - write("="); - } + IProgramVariable pvar = x.getResultVariable(); + if (pvar != null) { + writeElement(pvar); + write("="); + } - printMethodReference(x.getMethodReference(), false); -// // CHG: -// write("@"); -// final TypeReference tr = x.getBodySourceAsTypeReference(); -// if (tr instanceof SchemaTypeReference) { -// printSchemaTypeReference((SchemaTypeReference) tr); -// } else if (tr instanceof SchemaVariable) { -// printSchemaVariable((SchemaVariable) tr); -// } else { -// printTypeReference(tr); -// } - write(";"); - markEnd(0, x); - printFooter(x); + printMethodReference(x.getMethodReference(), false); + // // CHG: + // write("@"); + // final TypeReference tr = x.getBodySourceAsTypeReference(); + // if (tr instanceof SchemaTypeReference) { + // printSchemaTypeReference((SchemaTypeReference) tr); + // } else if (tr instanceof SchemaVariable) { + // printSchemaVariable((SchemaVariable) tr); + // } else { + // printTypeReference(tr); + // } + write(";"); + markEnd(0, x); + printFooter(x); - noLinefeed = wasNoLinefeed; - } + noLinefeed = wasNoLinefeed; + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ModelGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ModelGenerator.java index 0c141d1c15d..d1ad84de916 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ModelGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ModelGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; import java.util.Collection; @@ -40,9 +43,9 @@ public class ModelGenerator implements SolverLauncherListener { private int count; - //models that have been found until now + // models that have been found until now private final List models; - //how many models we are looking for + // how many models we are looking for private final int target; @@ -66,40 +69,41 @@ public void launch() { launcher.addListener(this); launcher.launch(problem, services, solver); } + /** * Creates a SolverLauncher with the appropriate settings. + * * @return */ private SolverLauncher prepareLauncher() { final TestGenerationSettings settings = TestGenerationSettings.getInstance(); - final ProofIndependentSMTSettings piSettings = ProofIndependentSettings - .DEFAULT_INSTANCE.getSMTSettings().clone(); + final ProofIndependentSMTSettings piSettings = + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings().clone(); piSettings.setMaxConcurrentProcesses(settings.getNumberOfProcesses()); - final ProofDependentSMTSettings pdSettings = ProofDependentSMTSettings - .getDefaultSettingsData(); + final ProofDependentSMTSettings pdSettings = + ProofDependentSMTSettings.getDefaultSettingsData(); pdSettings.invariantForall = settings.invariantForAll(); // invoke z3 for counterexamples - final DefaultSMTSettings smtsettings = new DefaultSMTSettings(pdSettings, - piSettings, new NewSMTTranslationSettings(), null); + final DefaultSMTSettings smtsettings = new DefaultSMTSettings(pdSettings, piSettings, + new NewSMTTranslationSettings(), null); return new SolverLauncher(smtsettings); } @Override - public void launcherStopped(SolverLauncher launcher, - Collection finishedSolvers) { + public void launcherStopped(SolverLauncher launcher, Collection finishedSolvers) { - for(SMTSolver solver : finishedSolvers) { + for (SMTSolver solver : finishedSolvers) { SMTSolverResult result = solver.getFinalResult(); - if(result.isValid().equals(SMTSolverResult.ThreeValuedTruth.FALSIFIABLE) + if (result.isValid().equals(SMTSolverResult.ThreeValuedTruth.FALSIFIABLE) && models.size() < target) { Model model = solver.getSocket().getQuery().getModel(); models.add(model); addModelToTerm(model); - if(models.size() >= target) { + if (models.size() >= target) { finish(); } else { launch(); @@ -115,10 +119,9 @@ public void launcherStopped(SolverLauncher launcher, /** - * Changes the term such that when evaluated again with z3 another model will be generated. - * If we have a model (c1=v1 & c2 = v2 & ...) where c1, c2, ... - * are integer constants we change the term t to the following form: - * t & !(c1=v1 & c2 = v2 & ...) + * Changes the term such that when evaluated again with z3 another model will be generated. If + * we have a model (c1=v1 & c2 = v2 & ...) where c1, c2, ... are integer constants we change the + * term t to the following form: t & !(c1=v1 & c2 = v2 & ...) * * @param m the model * @return true if the term has been changed @@ -127,14 +130,14 @@ private boolean addModelToTerm(Model m) { TermBuilder tb = services.getTermBuilder(); Namespace variables = services.getNamespaces().programVariables(); Term tmodel = tb.tt(); - for(String c : m.getConstants().keySet()) { + for (String c : m.getConstants().keySet()) { SMTSort sort = m.getTypes().getTypeForConstant(c); - if(sort != null && sort.getId().equals(SMTObjTranslator.BINT_SORT)) { + if (sort != null && sort.getId().equals(SMTObjTranslator.BINT_SORT)) { String val = m.getConstants().get(c); int value = Integer.parseInt(val); - ProgramVariable v = (ProgramVariable)variables.lookup(c); + ProgramVariable v = (ProgramVariable) variables.lookup(c); Term termConst = tb.var(v); Term termVal = tb.zTerm(value); Term termEquals = tb.equals(termConst, termVal); @@ -143,7 +146,7 @@ private boolean addModelToTerm(Model m) { } - if(!tmodel.equals(tb.tt())) { + if (!tmodel.equals(tb.tt())) { Term notTerm = tb.not(tmodel); SequentFormula sf = new SequentFormula(notTerm); goal.addFormula(sf, true, true); @@ -155,15 +158,14 @@ private boolean addModelToTerm(Model m) { private void finish() { LOGGER.info("Finished: found {}", models.size()); - for(Model m : models) { + for (Model m : models) { LOGGER.info("\t{}", m.toString()); } } @Override - public void launcherStarted(Collection problems, - Collection solverTypes, SolverLauncher launcher) { - } + public void launcherStarted(Collection problems, Collection solverTypes, + SolverLauncher launcher) {} public Term sequentToTerm(Sequent s) { diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ProofInfo.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ProofInfo.java index 7c182fb3ed5..5357e59bbfc 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ProofInfo.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ProofInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; import de.uka.ilkd.key.java.PrettyPrinter; @@ -75,10 +78,11 @@ public Term getPreConTerm() { if (c instanceof FunctionalOperationContract) { FunctionalOperationContract t = (FunctionalOperationContract) c; OriginalVariables orig = t.getOrigVars(); - Term post = t.getPre(services.getTypeConverter().getHeapLDT().getHeap(), orig.self, orig.params, orig.atPres, services); + Term post = t.getPre(services.getTypeConverter().getHeapLDT().getHeap(), orig.self, + orig.params, orig.atPres, services); return post; } - //no pre <==> false + // no pre <==> false return services.getTermBuilder().ff(); } @@ -92,7 +96,7 @@ public String getCode() { Term f = getPO(); JavaBlock block = getJavaBlock(f); - // getUpdate(f); + // getUpdate(f); StringWriter sw = new StringWriter(); sw.write(" " + getUpdate(f) + "\n"); PrettyPrinter pw = new CustomPrettyPrinter(sw, false); @@ -174,10 +178,12 @@ public String getUpdate(Term t) { private String processUpdate(Term update) { if (update.op() instanceof ElementaryUpdate) { ElementaryUpdate up = (ElementaryUpdate) update.op(); - if (up.lhs().sort().extendsTrans(services.getTypeConverter().getHeapLDT().targetSort())) { + if (up.lhs().sort() + .extendsTrans(services.getTypeConverter().getHeapLDT().targetSort())) { return ""; } - return " \n" + up.lhs().sort() + " " + up.lhs().toString() + " = " + update.sub(0) + ";"; + return " \n" + up.lhs().sort() + " " + up.lhs().toString() + " = " + update.sub(0) + + ";"; } StringBuilder result = new StringBuilder(); for (Term sub : update.subs()) { diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/RefEx.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/RefEx.java index 27af8f696a2..f32ecd72860 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/RefEx.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/RefEx.java @@ -1,29 +1,35 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; -/** Reference expression +/** + * Reference expression + * * @author gladisch -*/ + */ public class RefEx { - public String rcObjType; - public String rcObj; - public String fieldType; - public String field; + public String rcObjType; + public String rcObj; + public String fieldType; + public String field; - /** Example: rcObj.field, where rcObjType is the type of rcObj. - * The prefix "rc" stands for receiver. - */ - public RefEx(String rcObjType, String rcObj, String fieldType, String field){ - this.rcObjType = rcObjType; - this.rcObj = rcObj; - this.fieldType = fieldType; - this.field = field; - } - - @Override - public String toString() { - if(rcObjType!=null && rcObjType!=""){ - return "(("+rcObjType+")"+ rcObj+")."+field; - } - return rcObj+"."+field; - } + /** + * Example: rcObj.field, where rcObjType is the type of rcObj. The prefix "rc" stands for + * receiver. + */ + public RefEx(String rcObjType, String rcObj, String fieldType, String field) { + this.rcObjType = rcObjType; + this.rcObj = rcObj; + this.fieldType = fieldType; + this.field = field; + } + + @Override + public String toString() { + if (rcObjType != null && rcObjType != "") { + return "((" + rcObjType + ")" + rcObj + ")." + field; + } + return rcObj + "." + field; + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ReflectionClassCreator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ReflectionClassCreator.java index 42b6e5140a2..b34d677d18c 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ReflectionClassCreator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/ReflectionClassCreator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; import de.uka.ilkd.key.logic.sort.Sort; @@ -9,8 +12,8 @@ import java.util.HashSet; /** - * Creates the RFL.java file, that provides setter and getter methods using the reflection API - * as well as object creation functions based on the objenesis library. + * Creates the RFL.java file, that provides setter and getter methods using the reflection API as + * well as object creation functions based on the objenesis library. * * @author mbender * @author gladisch @@ -30,20 +33,19 @@ public class ReflectionClassCreator { public static final String GET_PREFIX = "_get_"; // setter and getter methods will be created for these types. - private static final String[] PRIMITIVE_TYPES = {"int", "long", "byte", - "char", "boolean", "float", "double"}; + private static final String[] PRIMITIVE_TYPES = + { "int", "long", "byte", "char", "boolean", "float", "double" }; // Default values for primitive types - private static final String[] PRIM_TYP_DEF_VAL = {"0", "0", "0", "' '", - "false", "0", "0"}; + private static final String[] PRIM_TYP_DEF_VAL = { "0", "0", "0", "' '", "false", "0", "0" }; - private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionClassCreator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionClassCreator.class); - private final HashSet usedObjectSorts; + private final HashSet usedObjectSorts; private final HashSet usedObjectSortsStrings; - public ReflectionClassCreator() { + public ReflectionClassCreator() { usedObjectSorts = new HashSet<>(); usedObjectSortsStrings = new HashSet<>(); } @@ -62,10 +64,10 @@ public StringBuilder createClass(boolean staticClass) { result.append(instances(sorts)); result.append(getterAndSetter(sorts)); result.append(footer()); - if (!checkBraces(result)) { - throw new IllegalStateException("ReflectionClassCreator.createClass(): " + - "Problem: the number of opening and closing braces of the generated RFL file is not equal!"); - } + if (!checkBraces(result)) { + throw new IllegalStateException("ReflectionClassCreator.createClass(): " + + "Problem: the number of opening and closing braces of the generated RFL file is not equal!"); + } return result; } @@ -92,7 +94,8 @@ private HashSet sortsToString() { String sort = var.toString(); // We only want Object-Types if (!" jbyte jint jlong jfloat jdouble jboolean jchar ".contains(" " + sort + " ")) { - if (" jbyte[] jint[] jlong[] jfloat[] jdouble[] jboolean[] jchar[] ".contains(" " + sort + " ")) { + if (" jbyte[] jint[] jlong[] jfloat[] jdouble[] jboolean[] jchar[] " + .contains(" " + sort + " ")) { sort = sort.substring(1); } if (!isPrimitiveType(sort)) { @@ -103,7 +106,8 @@ private HashSet sortsToString() { for (String sort : usedObjectSortsStrings) { // We only want Object-Types if (!" jbyte jint jlong jfloat jdouble jboolean jchar ".contains(" " + sort + " ")) { - if (" jbyte[] jint[] jlong[] jfloat[] jdouble[] jboolean[] jchar[] ".contains(" " + sort + " ")) { + if (" jbyte[] jint[] jlong[] jfloat[] jdouble[] jboolean[] jchar[] " + .contains(" " + sort + " ")) { sort = sort.substring(1); } if (!isPrimitiveType(sort)) { @@ -120,17 +124,24 @@ private HashSet sortsToString() { private StringBuilder classDecl(boolean staticClass) { final StringBuilder r = new StringBuilder(); r.append(NEW_LINE); - r.append("// This file was generated by KeY Version " + KeYConstants.VERSION + " (www.key-project.org)." + NEW_LINE + NEW_LINE + - "/** This class enables the test suite to read and write protected and private" + NEW_LINE + - " * fields of other classes. It can also simulate ghost fields using a hashmap." + NEW_LINE + - " * Ghostfields are implicit fields that exist in the specification but not in the" + NEW_LINE + - " * actual Java class. Futhermore, this class also enables to create an object of " + NEW_LINE + - " * any class even if it has no default constructor. To create objects the " + NEW_LINE + - " * the objenesis library is required and must be provided when compiling and" + NEW_LINE + - " * executing the test suite. " + NEW_LINE); - r.append(" * @see http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html" + NEW_LINE); - r.append(" * @see http://code.google.com/p/objenesis/" + NEW_LINE + - " * @see http://objenesis.org/" + NEW_LINE); + r.append("// This file was generated by KeY Version " + KeYConstants.VERSION + + " (www.key-project.org)." + NEW_LINE + NEW_LINE + + "/** This class enables the test suite to read and write protected and private" + + NEW_LINE + + " * fields of other classes. It can also simulate ghost fields using a hashmap." + + NEW_LINE + + " * Ghostfields are implicit fields that exist in the specification but not in the" + + NEW_LINE + + " * actual Java class. Futhermore, this class also enables to create an object of " + + NEW_LINE + + " * any class even if it has no default constructor. To create objects the " + + NEW_LINE + + " * the objenesis library is required and must be provided when compiling and" + + NEW_LINE + " * executing the test suite. " + NEW_LINE); + r.append(" * @see http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html" + + NEW_LINE); + r.append(" * @see http://code.google.com/p/objenesis/" + NEW_LINE + + " * @see http://objenesis.org/" + NEW_LINE); r.append(" * @author gladisch" + NEW_LINE); r.append(" * @author mbender" + NEW_LINE); r.append(" */" + NEW_LINE); @@ -143,9 +154,10 @@ private StringBuilder classDecl(boolean staticClass) { } /** - * Writes a hashmap and a utility method for associating ghost/model fiels with objects. + * Writes a hashmap and a utility method for associating ghost/model fiels with objects. * - * @param ghostMapActive becomes are runtime flag that determins if the hashmap should be enabled or not. + * @param ghostMapActive becomes are runtime flag that determins if the hashmap should be + * enabled or not. */ private StringBuilder ghostMapDecls(boolean ghostMapActive) { final StringBuilder r = new StringBuilder(); @@ -155,10 +167,12 @@ private StringBuilder ghostMapDecls(boolean ghostMapActive) { r.append(" public static boolean ghostMapActive;"); - r.append(" public static java.util.HashMap ghostModelFields;" + NEW_LINE + NEW_LINE); + r.append(" public static java.util.HashMap ghostModelFields;" + NEW_LINE + + NEW_LINE); r.append(" public static int getHash(Class c, Object obj, String attr){" + NEW_LINE); - r.append(" return c.hashCode() * (obj!=null?obj.hashCode():1) * attr.hashCode();" + NEW_LINE); + r.append(" return c.hashCode() * (obj!=null?obj.hashCode():1) * attr.hashCode();" + + NEW_LINE); r.append(" }" + NEW_LINE + NEW_LINE); return r; } @@ -169,7 +183,9 @@ private StringBuilder ghostMapDecls(boolean ghostMapActive) { private StringBuilder instanceMethod() { final StringBuilder r = new StringBuilder(); r.append(NEW_LINE + NEW_LINE); - r.append(" /** The Objenesis library can create instances of classes that have no default constructor. */" + NEW_LINE); + r.append( + " /** The Objenesis library can create instances of classes that have no default constructor. */" + + NEW_LINE); r.append(" private static org.objenesis.Objenesis objenesis;" + NEW_LINE + NEW_LINE); r.append(" private static Object newInstance(Class c) throws Exception {" + NEW_LINE); r.append(" Object res=objenesis.newInstance(c);" + NEW_LINE); @@ -193,9 +209,15 @@ private StringBuilder staticInitializer(boolean ghostMapActive) { r.append(tab + "ghostModelFields = new java.util.HashMap();" + NEW_LINE); r.append(tab + "NoSuchFieldExceptionText =" + NEW_LINE); - r.append(tab + tab + " \"This exception occurs when ghost fields or model fields are used in the code or \" +" + NEW_LINE); - r.append(tab + tab + " \"if mock objects are used that have different fields, than the real objects. \" +" + NEW_LINE); - r.append(tab + tab + " \"The tester should extend the handling of such fields in this generated utility class RFL.java.\";" + NEW_LINE); + r.append(tab + tab + + " \"This exception occurs when ghost fields or model fields are used in the code or \" +" + + NEW_LINE); + r.append(tab + tab + + " \"if mock objects are used that have different fields, than the real objects. \" +" + + NEW_LINE); + r.append(tab + tab + + " \"The tester should extend the handling of such fields in this generated utility class RFL.java.\";" + + NEW_LINE); r.append("}" + NEW_LINE + NEW_LINE); @@ -228,10 +250,10 @@ private StringBuilder newRef(final String sort) { } /** - * Takes a string representing a type e.g. "java.lang.Object[]" and returns - * a new name without "." and "[]", e.g. "java_lang_Object_ARRAY_". - * It is used to create correct setter and getter method names. - * This method is also used in Assignment.toString(boolean rfl) to generate the correct method names. + * Takes a string representing a type e.g. "java.lang.Object[]" and returns a new name without + * "." and "[]", e.g. "java_lang_Object_ARRAY_". It is used to create correct setter and getter + * method names. This method is also used in Assignment.toString(boolean rfl) to generate the + * correct method names. */ public static String cleanTypeName(String s) { // WARNING: Make sure this fixed string begins with a SPACE and also @@ -241,12 +263,10 @@ public static String cleanTypeName(String s) { s = s.substring(1); } while (s.indexOf(".") != -1) { - s = s.substring(0, s.indexOf(".")) + "_" - + s.substring(s.indexOf(".") + 1); + s = s.substring(0, s.indexOf(".")) + "_" + s.substring(s.indexOf(".") + 1); } while (s.indexOf("[]") != -1) { - s = s.substring(0, s.indexOf("[]")) + ARRAY - + s.substring(s.indexOf("[]") + 2); + s = s.substring(0, s.indexOf("[]")) + ARRAY + s.substring(s.indexOf("[]") + 2); } return s; } @@ -258,7 +278,8 @@ public static String cleanTypeName(String s) { private StringBuilder newInstance(final String sort) { final StringBuilder r = new StringBuilder(); r.append(NEW_LINE); - r.append(" public static " + sort + " new" + cleanTypeName(sort) + "() throws java.lang.RuntimeException {" + NEW_LINE); + r.append(" public static " + sort + " new" + cleanTypeName(sort) + + "() throws java.lang.RuntimeException {" + NEW_LINE); r.append(" try{" + NEW_LINE); r.append(" return (" + sort + ")newInstance(" + sort + ".class);" + NEW_LINE); r.append(" } catch (java.lang.Throwable e) {" + NEW_LINE); @@ -275,10 +296,9 @@ private StringBuilder newInstance(final String sort) { private StringBuilder newArray(final String sort) { final StringBuilder r = new StringBuilder(); r.append(NEW_LINE); - r.append(" public static " + sort + " new" + cleanTypeName(sort) - + "(int dim){" + NEW_LINE); - r.append(" return new " + sort.substring(0, sort.length() - 2) - + "[dim];" + NEW_LINE); + r.append( + " public static " + sort + " new" + cleanTypeName(sort) + "(int dim){" + NEW_LINE); + r.append(" return new " + sort.substring(0, sort.length() - 2) + "[dim];" + NEW_LINE); r.append(" }" + NEW_LINE); return r; } @@ -294,17 +314,14 @@ private boolean isPrimitiveType(String sort) { private StringBuilder getterAndSetter(final HashSet sorts) { final StringBuilder result = new StringBuilder(); - result - .append(NEW_LINE + " // ---Getter and setter for primitive types---" + NEW_LINE); + result.append(NEW_LINE + " // ---Getter and setter for primitive types---" + NEW_LINE); for (int i = 0; i < 7; i++) { result.append(NEW_LINE); result.append(declareSetter(PRIMITIVE_TYPES[i], true)); - result.append(declareGetter(PRIMITIVE_TYPES[i], - PRIM_TYP_DEF_VAL[i], true)); + result.append(declareGetter(PRIMITIVE_TYPES[i], PRIM_TYP_DEF_VAL[i], true)); } result.append(NEW_LINE); - result - .append(NEW_LINE + " // ---Getter and setter for Reference types---" + NEW_LINE); + result.append(NEW_LINE + " // ---Getter and setter for Reference types---" + NEW_LINE); for (final String sort : sorts) { result.append(NEW_LINE); result.append(declareSetter(sort, false)); @@ -315,13 +332,15 @@ private StringBuilder getterAndSetter(final HashSet sorts) { private StringBuilder declareSetter(final String sort, final boolean prim) { final StringBuilder r = new StringBuilder(); - final String cmd = " " + (prim ? - "f.set" + Character.toUpperCase(sort.charAt(0)) + sort.substring(1) + "(obj, val);" + NEW_LINE - : "f.set(obj, val);" + NEW_LINE); + final String cmd = + " " + (prim + ? "f.set" + Character.toUpperCase(sort.charAt(0)) + sort.substring(1) + + "(obj, val);" + NEW_LINE + : "f.set(obj, val);" + NEW_LINE); r.append(NEW_LINE); r.append(" public static void " + SET_PREFIX + cleanTypeName(sort) - + "(Class c, Object obj, String attr, " + sort - + " val) throws RuntimeException{" + NEW_LINE); + + "(Class c, Object obj, String attr, " + sort + " val) throws RuntimeException{" + + NEW_LINE); r.append(" try {" + NEW_LINE); r.append(" java.lang.reflect.Field f = c.getDeclaredField(attr);" + NEW_LINE); r.append(" f.setAccessible(true);" + NEW_LINE); @@ -330,7 +349,8 @@ private StringBuilder declareSetter(final String sort, final boolean prim) { r.append(" if(ghostMapActive)" + NEW_LINE); r.append(" ghostModelFields.put(getHash(c,obj,attr), val);" + NEW_LINE); r.append(" else" + NEW_LINE); - r.append(" throw new RuntimeException(e.toString() + NoSuchFieldExceptionText);" + NEW_LINE); + r.append(" throw new RuntimeException(e.toString() + NoSuchFieldExceptionText);" + + NEW_LINE); r.append(" } catch(Exception e) {" + NEW_LINE); r.append(" throw new RuntimeException(e);" + NEW_LINE); r.append(" }" + NEW_LINE); @@ -347,17 +367,15 @@ else if (sort.equals("char")) return Character.toUpperCase(sort.charAt(0)) + sort.substring(1); } - private StringBuilder declareGetter(final String sort, final String def, - final boolean prim) { + private StringBuilder declareGetter(final String sort, final String def, final boolean prim) { final StringBuilder r = new StringBuilder(); - final String cmd = " " + (prim ? - "return f.get" + Character.toUpperCase(sort.charAt(0)) + sort.substring(1) + "(obj);" + NEW_LINE - : "return (" + sort + ") f.get(obj);" + NEW_LINE); + final String cmd = + " " + (prim + ? "return f.get" + Character.toUpperCase(sort.charAt(0)) + sort.substring(1) + + "(obj);" + NEW_LINE + : "return (" + sort + ") f.get(obj);" + NEW_LINE); r.append(NEW_LINE); - r.append(" public static " - + sort - + " " + GET_PREFIX - + cleanTypeName(sort) + r.append(" public static " + sort + " " + GET_PREFIX + cleanTypeName(sort) + "(Class c, Object obj, String attr) throws RuntimeException{" + NEW_LINE); r.append(" " + sort + " res = " + def + ";" + NEW_LINE); r.append(" try {" + NEW_LINE); @@ -365,7 +383,8 @@ private StringBuilder declareGetter(final String sort, final String def, r.append(" f.setAccessible(true);" + NEW_LINE); r.append(cmd); r.append(" } catch(NoSuchFieldException e) {" + NEW_LINE); - r.append(" return (" + (prim ? primToWrapClass(sort) : sort) + ")ghostModelFields.get(getHash(c,obj,attr));" + NEW_LINE); + r.append(" return (" + (prim ? primToWrapClass(sort) : sort) + + ")ghostModelFields.get(getHash(c,obj,attr));" + NEW_LINE); r.append(" } catch(Exception e) {" + NEW_LINE); r.append(" throw new RuntimeException(e);" + NEW_LINE); r.append(" }" + NEW_LINE); @@ -389,30 +408,31 @@ private boolean checkBraces(final StringBuilder buf) { int edged = 0; for (int i = 0; i < buf.length(); i++) { switch (buf.charAt(i)) { - case '{': - curly++; - break; - case '}': - curly--; - break; - case '(': - round++; - break; - case ')': - round--; - break; - case '[': - edged++; - break; - case ']': - edged--; - break; + case '{': + curly++; + break; + case '}': + curly--; + break; + case '(': + round++; + break; + case ')': + round--; + break; + case '[': + edged++; + break; + case ']': + edged--; + break; } } if (curly == 0 && round == 0 && edged == 0) { return true; } else { - LOGGER.error("Error braces in RFL.java: curly: {} round: {}: egded: {}", curly, round, edged); + LOGGER.error("Error braces in RFL.java: curly: {} round: {}: egded: {}", curly, round, + edged); return false; } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/TestCaseGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/TestCaseGenerator.java index 7540f26f03e..b06491b7d57 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/TestCaseGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/TestCaseGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen; import de.uka.ilkd.key.java.JavaInfo; @@ -73,8 +76,8 @@ public class TestCaseGenerator { // subdirectory. public static boolean modelIsOK(Model m) { - return m != null && !m.isEmpty() && m.getHeaps() != null - && m.getHeaps().size() > 0 && m.getTypes() != null; + return m != null && !m.isEmpty() && m.getHeaps() != null && m.getHeaps().size() > 0 + && m.getTypes() != null; } private final boolean rflAsInternalClass; @@ -97,31 +100,26 @@ public static boolean modelIsOK(Model m) { // TODO: in future remove this string and provide the file in the // KeY-project private String compileWithOpenJML = "#!/bin/bash" + NEW_LINE + NEW_LINE - + "if [ -e \"openjml.jar\" ]" + NEW_LINE - + "then" + NEW_LINE + + "if [ -e \"openjml.jar\" ]" + NEW_LINE + "then" + NEW_LINE + " java -jar openjml.jar -cp \".\" -rac *" + JAVA_FILE_EXTENSION_WITH_DOT + NEW_LINE - + "else" + NEW_LINE - + " echo \"openjml.jar not found!\"" + NEW_LINE - + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + NEW_LINE - + " echo \"Copy openjml.jar into the directory with test files.\"" + NEW_LINE - + "fi" + NEW_LINE; + + "else" + NEW_LINE + " echo \"openjml.jar not found!\"" + NEW_LINE + + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + + NEW_LINE + " echo \"Copy openjml.jar into the directory with test files.\"" + + NEW_LINE + "fi" + NEW_LINE; private String createCompileWithOpenJML(String openJMLPath, String objenesisPath) { - return "#!/bin/bash" + NEW_LINE + NEW_LINE - + "if [ -e \"" + openJMLPath + File.separator + "openjml.jar\" ] " + NEW_LINE - + "then" + NEW_LINE - + " if [ -e \"" + objenesisPath + File.separator + OBJENESIS_NAME + "\" ]" + NEW_LINE - + " then" + NEW_LINE - + " java -jar " + openJMLPath + File.separator + "openjml.jar -cp \"." + objenesisPath + File.separator + OBJENESIS_NAME + "\" -rac *" + JAVA_FILE_EXTENSION_WITH_DOT + NEW_LINE - + " else" + NEW_LINE - + " echo \"objenesis-2.2.jar not found!\"" + NEW_LINE - + " fi" + NEW_LINE - + "else" + NEW_LINE - + " echo \"openjml.jar not found!\"" + NEW_LINE - - + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + NEW_LINE - + " echo \"Copy openjml.jar into the directory with test files.\"" + NEW_LINE - + "fi" + NEW_LINE; + return "#!/bin/bash" + NEW_LINE + NEW_LINE + "if [ -e \"" + openJMLPath + File.separator + + "openjml.jar\" ] " + NEW_LINE + "then" + NEW_LINE + " if [ -e \"" + + objenesisPath + File.separator + OBJENESIS_NAME + "\" ]" + NEW_LINE + " then" + + NEW_LINE + " java -jar " + openJMLPath + File.separator + + "openjml.jar -cp \"." + objenesisPath + File.separator + OBJENESIS_NAME + + "\" -rac *" + JAVA_FILE_EXTENSION_WITH_DOT + NEW_LINE + " else" + NEW_LINE + + " echo \"objenesis-2.2.jar not found!\"" + NEW_LINE + " fi" + NEW_LINE + + "else" + NEW_LINE + " echo \"openjml.jar not found!\"" + NEW_LINE + + + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + + NEW_LINE + " echo \"Copy openjml.jar into the directory with test files.\"" + + NEW_LINE + "fi" + NEW_LINE; } // TODO: in future remove this string and provide the file in the @@ -129,37 +127,29 @@ private String createCompileWithOpenJML(String openJMLPath, String objenesisPath private final String executeWithOpenJML; private String createExecuteWithOpenJML(String path, String objenesisPath) { - return "#!/bin/bash" + NEW_LINE - + "if [ -e \"" + path + File.separator + "jmlruntime.jar\" ]" + NEW_LINE - + "then" - + " if [ -e \"" + path + File.separator + "jmlspecs.jar\" ]" + NEW_LINE - + " then" + NEW_LINE - + " if [ -e \"" + objenesisPath + File.separator + OBJENESIS_NAME + "\" ]" + NEW_LINE - + " then" + NEW_LINE - + " if [ \"$1\" = \"\" ] ; then" + NEW_LINE - + " echo \"Provide the test driver as an argument (without " + JAVA_FILE_EXTENSION_WITH_DOT + " postfix). For example:\"" + NEW_LINE + return "#!/bin/bash" + NEW_LINE + "if [ -e \"" + path + File.separator + + "jmlruntime.jar\" ]" + NEW_LINE + "then" + " if [ -e \"" + path + File.separator + + "jmlspecs.jar\" ]" + NEW_LINE + " then" + NEW_LINE + " if [ -e \"" + + objenesisPath + File.separator + OBJENESIS_NAME + "\" ]" + NEW_LINE + " then" + + NEW_LINE + " if [ \"$1\" = \"\" ] ; then" + NEW_LINE + + " echo \"Provide the test driver as an argument (without " + + JAVA_FILE_EXTENSION_WITH_DOT + " postfix). For example:\"" + NEW_LINE + " echo \" executeWithOpenJML.sh TestGeneric0 \"" + NEW_LINE - + " echo \"Make sure that jmlruntime.jar and jmlspecs.jar are in the\"" + NEW_LINE - + " echo \"current directory.\"" + NEW_LINE - + " quit" + NEW_LINE - + " else" + NEW_LINE - + " java -cp " + objenesisPath + File.separator + OBJENESIS_NAME + ":" + path + File.separator + "jmlruntime.jar:" + path + File.separator + "jmlspecs.jar:. $1" + NEW_LINE - + " fi" + NEW_LINE - + " else" + NEW_LINE - + " echo \"objenesis-2.2.jar not found!\"" + NEW_LINE - + " fi" + NEW_LINE - + "else" + NEW_LINE + + " echo \"Make sure that jmlruntime.jar and jmlspecs.jar are in the\"" + + NEW_LINE + " echo \"current directory.\"" + NEW_LINE + " quit" + + NEW_LINE + " else" + NEW_LINE + " java -cp " + objenesisPath + + File.separator + OBJENESIS_NAME + ":" + path + File.separator + "jmlruntime.jar:" + + path + File.separator + "jmlspecs.jar:. $1" + NEW_LINE + " fi" + NEW_LINE + + " else" + NEW_LINE + " echo \"objenesis-2.2.jar not found!\"" + + NEW_LINE + " fi" + NEW_LINE + "else" + NEW_LINE + " echo \"jmlspecs.jar not found!\"" + NEW_LINE - + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + NEW_LINE - + " echo \"Copy jmlspecs.jar into the directory with test files.\"" + NEW_LINE - + " quit" + NEW_LINE - + "fi" + NEW_LINE - + "else" + NEW_LINE + + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + + NEW_LINE + " echo \"Copy jmlspecs.jar into the directory with test files.\"" + + NEW_LINE + " quit" + NEW_LINE + "fi" + NEW_LINE + "else" + NEW_LINE + " echo \"jmlruntime.jar not found!\"" + NEW_LINE - + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + NEW_LINE - + " echo \"Copy jmlruntime.jar into the directory with test files.\"" + NEW_LINE - + " quit" + NEW_LINE - + "fi" + NEW_LINE; + + " echo \"Download openJML from http://sourceforge.net/projects/jmlspecs/files/\"" + + NEW_LINE + " echo \"Copy jmlruntime.jar into the directory with test files.\"" + + NEW_LINE + " quit" + NEW_LINE + "fi" + NEW_LINE; } public TestCaseGenerator(Proof proof) { @@ -180,8 +170,10 @@ public TestCaseGenerator(Proof proof, boolean rflAsInternalClass) { info = new ProofInfo(proof); mutName = info.getMUT().getFullName(); rflCreator = new ReflectionClassCreator(); - executeWithOpenJML = createExecuteWithOpenJML(settings.getOpenjmlPath(), settings.getObjenesisPath()); - compileWithOpenJML = createCompileWithOpenJML(settings.getOpenjmlPath(), settings.getObjenesisPath()); + executeWithOpenJML = + createExecuteWithOpenJML(settings.getOpenjmlPath(), settings.getObjenesisPath()); + compileWithOpenJML = + createCompileWithOpenJML(settings.getOpenjmlPath(), settings.getObjenesisPath()); oracleGenerator = new OracleGenerator(services, rflCreator, useRFL); if (junitFormat) { oracleMethods = new LinkedList<>(); @@ -190,8 +182,8 @@ public TestCaseGenerator(Proof proof, boolean rflAsInternalClass) { } /** - * Computes the project specific sub path of the output directory - * ({@link #directory}) in which the generated files will be stored. + * Computes the project specific sub path of the output directory ({@link #directory}) in which + * the generated files will be stored. * * @param modelDir The path to the source files of the performed {@link Proof}. * @return The computed sub path. @@ -247,11 +239,15 @@ protected String buildDummyClassForAbstractSort(Sort sort) { } final var sb = new StringBuilder(); sortDummyClass.put(sort, sb); - // Put the string buffer as soon as possible, due to possible recursive calls of this method. - sb.append("import ").append(sort.declarationString()).append(";").append(NEW_LINE).append(NEW_LINE); - sb.append("class ").append(className).append(" implements ").append(sort.declarationString()).append("{").append(NEW_LINE); - // TODO:extends or implements depending if it is a class or interface. - sb.append(" public ").append(className).append("(){ };").append(NEW_LINE); // default constructor + // Put the string buffer as soon as possible, due to possible recursive calls of this + // method. + sb.append("import ").append(sort.declarationString()).append(";").append(NEW_LINE) + .append(NEW_LINE); + sb.append("class ").append(className).append(" implements ") + .append(sort.declarationString()).append("{").append(NEW_LINE); + // TODO:extends or implements depending if it is a class or interface. + sb.append(" public ").append(className).append("(){ };").append(NEW_LINE); // default + // constructor for (IProgramMethod m : jinfo.getAllProgramMethods(kjt)) { if (m.getFullName().indexOf('<') > -1) { @@ -284,8 +280,7 @@ protected String buildDummyClassForAbstractSort(Sort sort) { sb.append(md.getTypeReference().toString()).append(" "); } sb.append(m.getName()).append("("); - final Iterator pdIter = md.getParameters() - .iterator(); + final Iterator pdIter = md.getParameters().iterator(); int varcount = 0; while (pdIter.hasNext()) { final ParameterDeclaration pd = pdIter.next(); @@ -309,7 +304,8 @@ protected String buildDummyClassForAbstractSort(Sort sort) { } sb.append(")"); if (md.getThrown() != null) { - sb.append(" throws ").append(md.getThrown().getTypeReferenceAt(0)).append(" ").append(NEW_LINE).append(" "); + sb.append(" throws ").append(md.getThrown().getTypeReferenceAt(0)).append(" ") + .append(NEW_LINE).append(" "); } if (md.getTypeReference() == null) { sb.append("{ };"); @@ -324,8 +320,8 @@ protected String buildDummyClassForAbstractSort(Sort sort) { } else { boolean returnNull = true; try { - final String retType = md.getTypeReference() - .getKeYJavaType().getSort().name().toString(); + final String retType = + md.getTypeReference().getKeYJavaType().getSort().name().toString(); if (retType.equals("java.lang.String")) { sb.append("{ return \"").append(className).append("\";}"); returnNull = false; @@ -344,8 +340,7 @@ protected String buildDummyClassForAbstractSort(Sort sort) { return className; } - private void copyFiles(final String srcName, final String targName) - throws IOException { + private void copyFiles(final String srcName, final String targName) throws IOException { // We don't want to copy the Folder with API Reference // Implementation if (srcName.equals(dontCopy)) { @@ -355,12 +350,10 @@ private void copyFiles(final String srcName, final String targName) // it's readable final File srcFile = new File(srcName); if (!srcFile.exists()) { - throw new IOException("FileCopy: " + "no such source file: " - + srcName); + throw new IOException("FileCopy: " + "no such source file: " + srcName); } if (!srcFile.canRead()) { - throw new IOException("FileCopy: " + "source file is unreadable: " - + srcName); + throw new IOException("FileCopy: " + "source file is unreadable: " + srcName); } if (srcFile.isDirectory()) { final String newTarget; @@ -380,12 +373,12 @@ private void copyFiles(final String srcName, final String targName) final File targFile = new File(targDir, srcFile.getName()); if (targFile.exists()) { if (!targFile.canWrite()) { - throw new IOException("FileCopy: " - + "destination file is unwriteable: " + targName); + throw new IOException( + "FileCopy: " + "destination file is unwriteable: " + targName); } } try (var src = new FileInputStream(srcFile); - var targ = new FileOutputStream(targFile)) { + var targ = new FileOutputStream(targFile)) { final byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) { @@ -412,7 +405,8 @@ protected void createDummyClasses() throws IOException { * @throws IOException */ protected void writeRFLFile() throws IOException { - writeToFile(ReflectionClassCreator.NAME_OF_CLASS + JAVA_FILE_EXTENSION_WITH_DOT, createRFLFileContent()); + writeToFile(ReflectionClassCreator.NAME_OF_CLASS + JAVA_FILE_EXTENSION_WITH_DOT, + createRFLFileContent()); } /** @@ -462,7 +456,8 @@ protected String getOracleAssertion(List oracleMethods) { oracleMethods.add(oracle); oracleMethods.addAll(oracleGenerator.getOracleMethods()); - LOGGER.debug("Modifier Set: {}", oracleGenerator.getOracleLocationSet(info.getAssignable())); + LOGGER.debug("Modifier Set: {}", + oracleGenerator.getOracleLocationSet(info.getAssignable())); return "assertTrue(" + oracleCall + ");"; } @@ -475,12 +470,13 @@ public String generateJUnitTestSuite(Collection problemSolvers) throw initFileName(); StringBuilder testSuite = createTestCaseCotent(problemSolvers); writeToFile(fileName + JAVA_FILE_EXTENSION_WITH_DOT, testSuite); - logger.writeln("Writing test file to:" + directory + modDir - + File.separator + fileName + JAVA_FILE_EXTENSION_WITH_DOT); + logger.writeln("Writing test file to:" + directory + modDir + File.separator + fileName + + JAVA_FILE_EXTENSION_WITH_DOT); exportCodeUnderTest(); createDummyClasses(); try { - if (useRFL) writeRFLFile(); + if (useRFL) + writeRFLFile(); } catch (Exception ex) { logger.writeln("Error: The file RFL" + JAVA_FILE_EXTENSION_WITH_DOT + " is either not generated or it has an error."); @@ -496,8 +492,8 @@ public void initFileName() { fileName = "TestGeneric" + TestCaseGenerator.fileCounter; String mut = getMUTCall(); if (mut == null) { - mut = " //Manually write a call to the method under test, " + - "because KeY could not determine it automatically."; + mut = " //Manually write a call to the method under test, " + + "because KeY could not determine it automatically."; } else { fileName += "_" + mutName; } @@ -513,32 +509,39 @@ public StringBuilder createTestCaseCotent(Collection problemSolvers) try { final StringBuilder testMethod = new StringBuilder(); final String originalNodeName = solver.getProblem().getGoal() - /*TODO:Warning this is wrong if we generate a test from an inner node (e.g. closed proof tree), - because goals are mutable. A Node should be used here instead. */ + /* + * TODO:Warning this is wrong if we generate a test from an inner node (e.g. + * closed proof tree), because goals are mutable. A Node should be used here + * instead. + */ .proof().name().toString(); boolean success = false; if (solver.getSocket().getQuery() != null) { final Model m = solver.getSocket().getQuery().getModel(); if (TestCaseGenerator.modelIsOK(m)) { logger.writeln("Generate: " + originalNodeName); - Map typeInfMap = generateTypeInferenceMap(solver.getProblem().getGoal().node()); + Map typeInfMap = + generateTypeInferenceMap(solver.getProblem().getGoal().node()); testMethod.append(" //").append(originalNodeName).append(NEW_LINE); testMethod.append(getTestMethodSignature(i)).append("{").append(NEW_LINE); - testMethod.append(" //Test preamble: creating objects and intializing test data") - .append(generateTestCase(m, typeInfMap)).append(NEW_LINE).append(NEW_LINE); + testMethod.append( + " //Test preamble: creating objects and intializing test data") + .append(generateTestCase(m, typeInfMap)).append(NEW_LINE) + .append(NEW_LINE); Set vars = new HashSet<>(); info.getProgramVariables(info.getPO(), vars); testMethod.append(TAB + "//Other variables").append(NEW_LINE) - .append(getRemainingConstants(m.getConstants().keySet(), vars)).append(NEW_LINE); + .append(getRemainingConstants(m.getConstants().keySet(), vars)) + .append(NEW_LINE); testMethod.append(" //Calling the method under test ").append(NEW_LINE) .append(info.getCode()).append(NEW_LINE); if (junitFormat) { - testMethod.append(" //calling the test oracle").append(NEW_LINE).append(TAB) - .append(oracleMethodCall).append(NEW_LINE); + testMethod.append(" //calling the test oracle").append(NEW_LINE) + .append(TAB).append(oracleMethodCall).append(NEW_LINE); } testMethod.append(" }").append(NEW_LINE).append(NEW_LINE); @@ -554,15 +557,17 @@ public StringBuilder createTestCaseCotent(Collection problemSolvers) for (StackTraceElement ste : ex.getStackTrace()) { logger.writeln(ste.toString()); } - logger.writeln("A test case was not generated due to an exception. Continuing test generation..."); + logger.writeln( + "A test case was not generated due to an exception. Continuing test generation..."); } } if (i == 0) { - logger.writeln("Warning: no test case was generated. Adjust the SMT solver settings (e.g. timeout) " + - "in Options->SMT Solvers."); + logger.writeln( + "Warning: no test case was generated. Adjust the SMT solver settings (e.g. timeout) " + + "in Options->SMT Solvers."); } else if (i < problemSolvers.size()) { - logger.writeln("Warning: SMT solver could not solve all test data constraints. " + - "Adjust the SMT solver settings (e.g. timeout) in Options->SMT Solvers."); + logger.writeln("Warning: SMT solver could not solve all test data constraints. " + + "Adjust the SMT solver settings (e.g. timeout) in Options->SMT Solvers."); } testSuite.append(getMainMethod(fileName, i)).append(NEW_LINE).append(NEW_LINE); testSuite.append(testMethods); @@ -609,11 +614,12 @@ private void generateTypeInferenceMapHelper(Term t, Map map) { LOGGER.warn("Warning: ProgramVariable {} is ambiguous.", name); } } else { - LOGGER.debug("PV {} Sort: {} KeYJavaType: {}", name, pv.sort(), pv.getKeYJavaType()); + LOGGER.debug("PV {} Sort: {} KeYJavaType: {}", name, pv.sort(), + pv.getKeYJavaType()); map.put(name, pv.sort()); } } else if (op instanceof Function && !(op instanceof ObserverFunction)) { - //This case collects fields of classes. The function itself has + // This case collects fields of classes. The function itself has // sort "Field" because it is just the name of the field. To get // the actual class of the field Function func = (Function) t.op(); @@ -663,7 +669,8 @@ private ProgramVariable getProgramVariable(Term locationTerm) { return result; } - private String getRemainingConstants(Collection existingConstants, Collection newConstants) { + private String getRemainingConstants(Collection existingConstants, + Collection newConstants) { StringBuilder result = new StringBuilder(); for (Term c : newConstants) { @@ -673,17 +680,19 @@ private String getRemainingConstants(Collection existingConstants, Colle String init = "null"; if (c.sort().equals(services.getTypeConverter().getIntegerLDT().targetSort())) { init = "0"; - } else if (c.sort().equals(services.getTypeConverter().getBooleanLDT().targetSort())) { + } else if (c.sort() + .equals(services.getTypeConverter().getBooleanLDT().targetSort())) { init = "false"; } - result.append(NEW_LINE).append(TAB).append(NULLABLE) - .append(" ").append(getSafeType(c.sort())).append(" ") - .append(c).append(" = ").append(init).append(";"); + result.append(NEW_LINE).append(TAB).append(NULLABLE).append(" ") + .append(getSafeType(c.sort())).append(" ").append(c).append(" = ") + .append(init).append(";"); if (junitFormat) { result.append(NEW_LINE).append(TAB).append(NULLABLE).append(" ") .append(getSafeType(c.sort())).append(" ") - .append(getPreName(c.toString())).append(" = ").append(init).append(";"); + .append(getPreName(c.toString())).append(" = ").append(init) + .append(";"); } } } @@ -693,26 +702,26 @@ private String getRemainingConstants(Collection existingConstants, Colle private boolean isInPrestate(Collection prestate, ObjectVal o) { return true; - // return prestate.contains(o) && - // services.getTypeConverter().isReferenceType( - // services.getJavaInfo().getKeYJavaType(o.getSort()).getJavaType()) + // return prestate.contains(o) && + // services.getTypeConverter().isReferenceType( + // services.getJavaInfo().getKeYJavaType(o.getSort()).getJavaType()) } private boolean isInPrestate(Collection prestate, String name) { return true; - // // TODO return only needed objects - // for(ObjectVal o : prestate){ - // if (services.getTypeConverter().isReferenceType( - // services.getJavaInfo().getKeYJavaType(o.getSort()).getJavaType())) { - // String oName = createObjectName(o); - // if(oName.equals(name)){ - // return true; - // } - // } - // } - // - // return false; + // // TODO return only needed objects + // for(ObjectVal o : prestate){ + // if (services.getTypeConverter().isReferenceType( + // services.getJavaInfo().getKeYJavaType(o.getSort()).getJavaType())) { + // String oName = createObjectName(o); + // if(oName.equals(name)){ + // return true; + // } + // } + // } + // + // return false; } public String generateModifierSetAssertions(Model m) { @@ -738,7 +747,7 @@ public String generateTestCase(Model m, Map typeInfMap) { } } - //Set prestate = getPrestateObjects(m); + // Set prestate = getPrestateObjects(m); Set prestate = new HashSet<>(); if (heap != null) { @@ -751,8 +760,8 @@ public String generateTestCase(Model m, Map typeInfMap) { final String type = getSafeType(o.getSort()); String right; if (type.endsWith("[]")) { - right = "new " + type.substring(0, type.length() - 2) + "[" - + o.getLength() + "]"; + right = "new " + type.substring(0, type.length() - 2) + "[" + o.getLength() + + "]"; } else if (o.getSort() == null || o.getSort().toString().equals("Null")) { right = "null"; } else { @@ -800,10 +809,11 @@ public String generateTestCase(Model m, Map typeInfMap) { if (junitFormat && (isObject || Character.isJavaIdentifierStart(c.charAt(0))) && isInPrestate(prestate, val)) { if (isLiteral) { - assignments.add(new Assignment(declType, getPreName(c), "(" + type + ")" + val)); + assignments.add(new Assignment(declType, getPreName(c), + "(" + type + ")" + val)); } else { - assignments.add(new Assignment(declType, getPreName(c), "(" + type + ")" - + getPreName(val))); + assignments.add(new Assignment(declType, getPreName(c), + "(" + type + ")" + getPreName(val))); } } @@ -813,7 +823,8 @@ && isInPrestate(prestate, val)) { // init fields if (heap != null) { for (final ObjectVal o : heap.getObjects()) { - if (o.getName().equals("#o0") || o.getSort().name().toString().endsWith("Exception")) { + if (o.getName().equals("#o0") + || o.getSort().name().toString().endsWith("Exception")) { continue; } final String receiverObject = createObjectName(o); @@ -826,19 +837,22 @@ && isInPrestate(prestate, val)) { String val = o.getFieldvalues().get(f); String fieldName2 = f.replace("|", ""); final String vType = this.inferSort(typeInfMap, fieldName2); - //possible bug if vType represents an abstract type or an interface. See: getSafeType. + // possible bug if vType represents an abstract type or an interface. See: + // getSafeType. rflCreator.addSort(vType); LOGGER.debug("Added sort (init fields): {}", vType); val = translateValueExpression(val); final String rcObjType = getSafeType(o.getSort()); - assignments.add(new Assignment( - new RefEx(rcObjType, receiverObject, vType, fieldName), "(" + vType + ")" + val)); + assignments.add( + new Assignment(new RefEx(rcObjType, receiverObject, vType, fieldName), + "(" + vType + ")" + val)); if (junitFormat && isInPrestate(prestate, o)) { - //if value that is pointed to is object and in prestate then use prestate object - if (!vType.equals("int") && !vType.equals("boolean") && isInPrestate(prestate, val) - && !val.equals("null")) { + // if value that is pointed to is object and in prestate then use prestate + // object + if (!vType.equals("int") && !vType.equals("boolean") + && isInPrestate(prestate, val) && !val.equals("null")) { val = getPreName(val); } @@ -849,8 +863,7 @@ && isInPrestate(prestate, val)) { } } - if (o.getSort() != null - && o.getSort().name().toString().endsWith("[]")) { + if (o.getSort() != null && o.getSort().name().toString().endsWith("[]")) { String safeType = getSafeType(o.getSort()); String elementType = safeType.substring(0, safeType.length() - 2); @@ -867,7 +880,8 @@ && isInPrestate(prestate, val)) { && isInPrestate(prestate, val) && !val.equals("null")) { val = getPreName(val); } - assignments.add(new Assignment(getPreName(receiverObject) + fieldName, val)); + assignments.add( + new Assignment(getPreName(receiverObject) + fieldName, val)); } @@ -895,11 +909,11 @@ && isInPrestate(prestate, val) && !val.equals("null")) { } private String createOldMap(Set objNames) { - StringBuilder result = - new StringBuilder(NEW_LINE + TAB + "Map " + OLDMap + " = new HashMap();"); + StringBuilder result = new StringBuilder(NEW_LINE + TAB + "Map " + OLDMap + + " = new HashMap();"); for (String o : objNames) { - result.append(NEW_LINE).append(TAB).append(OLDMap).append(".put(") - .append(getPreName(o)).append(",").append(o).append(");"); + result.append(NEW_LINE).append(TAB).append(OLDMap).append(".put(").append(getPreName(o)) + .append(",").append(o).append(");"); } return result.toString(); } @@ -919,44 +933,43 @@ private String getDummyClassNameFor(Sort sort) { } private String getFilePrefix(String className, String packageName) { - String res = "/** This is a test driver generated by KeY " + KeYConstants.VERSION + " (www.key-project.org). " + NEW_LINE + - " * Possible use cases:" + NEW_LINE + - " * Use Case 1. Using JUnit 4:" + NEW_LINE + - " * javac -cp .:PATH_TO_JUNIT4_JAR *.java" + NEW_LINE + - " * java -cp .:PATH_TO_JUNIT4_JAR:PATH_TO_HAMCREST_JAR org.junit.runner.JUnitCore " + className + NEW_LINE + - " * Use Case 2. Use JML runtime checker: " + NEW_LINE + - " * Compile this file and and execute the main method with a JML runtime checker. On linux you can use the built-in scripts:" + NEW_LINE + - " * ./compileWithOpenJML.sh" + NEW_LINE + - " * ./executeWithOpenJML.sh " + className + NEW_LINE + - " * Use Case 3. Use simply a program debugger to follow and understand the execution of the program." + NEW_LINE + - " * @author Christoph Gladisch" + NEW_LINE + - " * @author Mihai Herda" + NEW_LINE + - " */" + NEW_LINE; + String res = "/** This is a test driver generated by KeY " + KeYConstants.VERSION + + " (www.key-project.org). " + NEW_LINE + " * Possible use cases:" + NEW_LINE + + " * Use Case 1. Using JUnit 4:" + NEW_LINE + + " * javac -cp .:PATH_TO_JUNIT4_JAR *.java" + NEW_LINE + + " * java -cp .:PATH_TO_JUNIT4_JAR:PATH_TO_HAMCREST_JAR org.junit.runner.JUnitCore " + + className + NEW_LINE + " * Use Case 2. Use JML runtime checker: " + NEW_LINE + + " * Compile this file and and execute the main method with a JML runtime checker. On linux you can use the built-in scripts:" + + NEW_LINE + " * ./compileWithOpenJML.sh" + NEW_LINE + + " * ./executeWithOpenJML.sh " + className + NEW_LINE + + " * Use Case 3. Use simply a program debugger to follow and understand the execution of the program." + + NEW_LINE + " * @author Christoph Gladisch" + NEW_LINE + " * @author Mihai Herda" + + NEW_LINE + " */" + NEW_LINE; if (packageName != null) { res += "package " + packageName + ";" + NEW_LINE; } if (junitFormat) { - res += "import java.util.Set;" + NEW_LINE - + "import java.util.HashSet;" + NEW_LINE - + "import java.util.Map;" + NEW_LINE - + "import java.util.HashMap;" + NEW_LINE - + " public class " + className - + " extends junit.framework.TestCase {" + NEW_LINE + NEW_LINE - + " public static junit.framework.Test suite() { " - + " return new junit.framework.JUnit4TestAdapter(" + className + ".class);" + NEW_LINE - + " } " + NEW_LINE - + NEW_LINE + " public " + className + "(){}" + NEW_LINE + NEW_LINE; + res += "import java.util.Set;" + NEW_LINE + "import java.util.HashSet;" + NEW_LINE + + "import java.util.Map;" + NEW_LINE + "import java.util.HashMap;" + NEW_LINE + + " public class " + className + " extends junit.framework.TestCase {" + + NEW_LINE + NEW_LINE + " public static junit.framework.Test suite() { " + + " return new junit.framework.JUnit4TestAdapter(" + className + ".class);" + + NEW_LINE + " } " + NEW_LINE + NEW_LINE + " public " + className + "(){}" + + NEW_LINE + NEW_LINE; } else { - res += "public class " + className + "{ " + NEW_LINE + NEW_LINE + " public " - + className + "(){}" + NEW_LINE; + res += "public class " + className + "{ " + NEW_LINE + NEW_LINE + " public " + className + + "(){}" + NEW_LINE; } return res; } private StringBuilder getMainMethod(String className, int i) { final StringBuilder res = new StringBuilder(); - res.append(" public static void main (java.lang.String[] arg) {").append(NEW_LINE).append(" ").append(className).append(" testSuiteObject;").append(NEW_LINE).append(" testSuiteObject=new ").append(className).append(" ();").append(NEW_LINE).append(NEW_LINE); + res.append(" public static void main (java.lang.String[] arg) {").append(NEW_LINE) + .append(" ").append(className).append(" testSuiteObject;").append(NEW_LINE) + .append(" testSuiteObject=new ").append(className).append(" ();").append(NEW_LINE) + .append(NEW_LINE); for (int j = 0; j < i; j++) { res.append(" testSuiteObject.testcode").append(j).append("();").append(NEW_LINE); } @@ -968,12 +981,11 @@ private StringBuilder getMainMethod(String className, int i) { } private String createBoolSet() { - //bool + // bool String allbool = ALL_BOOLS; - return NEW_LINE + - TAB + "Set " + allbool + "= new HashSet();" + NEW_LINE + - TAB + allbool + ".add(true);" + NEW_LINE + - TAB + allbool + ".add(false);" + NEW_LINE; + return NEW_LINE + TAB + "Set " + allbool + "= new HashSet();" + NEW_LINE + + TAB + allbool + ".add(true);" + NEW_LINE + TAB + allbool + ".add(false);" + + NEW_LINE; } private String createIntSet() { @@ -985,11 +997,11 @@ private String createIntSet() { long hi = (long) (Math.pow(2, size - 1) - 1); String allint = ALL_INTS; - res.append(TAB + "Set ").append(allint).append("= new HashSet();").append(NEW_LINE); + res.append(TAB + "Set ").append(allint).append("= new HashSet();") + .append(NEW_LINE); for (long i = low; i <= hi; i++) { - res.append(TAB).append(allint).append(".add(") - .append(i).append(");").append(NEW_LINE); + res.append(TAB).append(allint).append(".add(").append(i).append(");").append(NEW_LINE); } return res.toString(); } @@ -998,7 +1010,8 @@ private String createObjSet(Heap h) { StringBuilder res = new StringBuilder(); - res.append(TAB + "Set " + ALL_OBJECTS + "= new HashSet();").append(NEW_LINE); + res.append(TAB + "Set " + ALL_OBJECTS + "= new HashSet();") + .append(NEW_LINE); for (ObjectVal o : h.getObjects()) { String name = o.getName(); @@ -1038,14 +1051,12 @@ public boolean isJunit() { } protected boolean isNumericType(String type) { - return type.equals("byte") || type.equals("short") - || type.equals("int") || type.equals("long") - || type.equals("float") || type.equals("double"); + return type.equals("byte") || type.equals("short") || type.equals("int") + || type.equals("long") || type.equals("float") || type.equals("double"); } protected boolean isPrimitiveType(String type) { - return isNumericType(type) || type.equals("boolean") - || type.equals("char"); + return isNumericType(type) || type.equals("boolean") || type.equals("char"); } public void setLogger(TestGenerationLog logger) { diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/ModifiesSetTranslator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/ModifiesSetTranslator.java index 5b145bd7ab0..e77d22a111d 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/ModifiesSetTranslator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/ModifiesSetTranslator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.java.Services; @@ -5,87 +8,87 @@ import de.uka.ilkd.key.logic.Term; public class ModifiesSetTranslator { - - private Services services; - private OracleGenerator gen; - - - public boolean isSingleTon(Term t){ - return t.op().equals(getLocSetLDT().getSingleton()); - } - - public boolean isUnion(Term t){ - return t.op().equals(getLocSetLDT().getUnion()); - } - - public boolean isIntersection(Term t){ - return t.op().equals(getLocSetLDT().getIntersect()); - } - - public boolean isAllFields(Term t){ - return t.op().equals(getLocSetLDT().getAllFields()); - } - - public boolean isAllLocs(Term t){ - return t.op().equals(getLocSetLDT().getAllLocs()); - } - - public boolean isEmpty(Term t){ - return t.op().equals(getLocSetLDT().getEmpty()); - } - - private LocSetLDT getLocSetLDT(){ - return services.getTypeConverter().getLocSetLDT(); - } - - public ModifiesSetTranslator(Services services, OracleGenerator gen) { - this.services = services; - this.gen = gen; - } - - - public OracleLocationSet translate(Term t){ - - if(isSingleTon(t)){ - Term obj = t.sub(0); - Term field = t.sub(1); - String objString = gen.generateOracle(obj, false).toString(); - String fieldString = gen.generateOracle(field, false).toString(); - OracleLocation loc = new OracleLocation(objString, fieldString); - return OracleLocationSet.singleton(loc); - } - - else if(isUnion(t)){ - OracleLocationSet left = translate(t.sub(0)); - OracleLocationSet right = translate(t.sub(1)); - return OracleLocationSet.union(left, right); - } - - else if(isIntersection(t)){ - OracleLocationSet left = translate(t.sub(0)); - OracleLocationSet right = translate(t.sub(1)); - return OracleLocationSet.intersect(left, right); - } - - else if(isAllFields(t)){ - Term obj = t.sub(0); - String objString = gen.generateOracle(obj, false).toString(); - OracleLocation loc = new OracleLocation(objString); - return OracleLocationSet.singleton(loc); - } - - else if(isEmpty(t)){ - return OracleLocationSet.EMPTY; - } - - else if(isAllLocs(t)){ - return OracleLocationSet.ALL_LOCS; - } - - - throw new RuntimeException("Unsupported locset operation: "+t.op()); - } - - - + + private Services services; + private OracleGenerator gen; + + + public boolean isSingleTon(Term t) { + return t.op().equals(getLocSetLDT().getSingleton()); + } + + public boolean isUnion(Term t) { + return t.op().equals(getLocSetLDT().getUnion()); + } + + public boolean isIntersection(Term t) { + return t.op().equals(getLocSetLDT().getIntersect()); + } + + public boolean isAllFields(Term t) { + return t.op().equals(getLocSetLDT().getAllFields()); + } + + public boolean isAllLocs(Term t) { + return t.op().equals(getLocSetLDT().getAllLocs()); + } + + public boolean isEmpty(Term t) { + return t.op().equals(getLocSetLDT().getEmpty()); + } + + private LocSetLDT getLocSetLDT() { + return services.getTypeConverter().getLocSetLDT(); + } + + public ModifiesSetTranslator(Services services, OracleGenerator gen) { + this.services = services; + this.gen = gen; + } + + + public OracleLocationSet translate(Term t) { + + if (isSingleTon(t)) { + Term obj = t.sub(0); + Term field = t.sub(1); + String objString = gen.generateOracle(obj, false).toString(); + String fieldString = gen.generateOracle(field, false).toString(); + OracleLocation loc = new OracleLocation(objString, fieldString); + return OracleLocationSet.singleton(loc); + } + + else if (isUnion(t)) { + OracleLocationSet left = translate(t.sub(0)); + OracleLocationSet right = translate(t.sub(1)); + return OracleLocationSet.union(left, right); + } + + else if (isIntersection(t)) { + OracleLocationSet left = translate(t.sub(0)); + OracleLocationSet right = translate(t.sub(1)); + return OracleLocationSet.intersect(left, right); + } + + else if (isAllFields(t)) { + Term obj = t.sub(0); + String objString = gen.generateOracle(obj, false).toString(); + OracleLocation loc = new OracleLocation(objString); + return OracleLocationSet.singleton(loc); + } + + else if (isEmpty(t)) { + return OracleLocationSet.EMPTY; + } + + else if (isAllLocs(t)) { + return OracleLocationSet.ALL_LOCS; + } + + + throw new RuntimeException("Unsupported locset operation: " + t.op()); + } + + + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleBinTerm.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleBinTerm.java index ce7d6e2b78b..dd99fdc68df 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleBinTerm.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleBinTerm.java @@ -1,37 +1,39 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; -public class OracleBinTerm implements OracleTerm{ - - private String op; - - private OracleTerm left; - - private OracleTerm right; - - public OracleBinTerm(String op, OracleTerm left, - OracleTerm right) { - super(); - this.op = op; - this.left = left; - this.right = right; +public class OracleBinTerm implements OracleTerm { + + private String op; + + private OracleTerm left; + + private OracleTerm right; + + public OracleBinTerm(String op, OracleTerm left, OracleTerm right) { + super(); + this.op = op; + this.left = left; + this.right = right; + } + + public String getOp() { + return op; + } + + public OracleTerm getLeft() { + return left; + } + + public OracleTerm getRight() { + return right; } - public String getOp() { - return op; - } - - public OracleTerm getLeft() { - return left; - } - - public OracleTerm getRight() { - return right; - } - - public String toString(){ - return "("+left.toString()+" "+op+" "+right.toString()+")"; - } - - - + public String toString() { + return "(" + left.toString() + " " + op + " " + right.toString() + ")"; + } + + + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleConstant.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleConstant.java index 6d906fb319b..79c4d4c1e6f 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleConstant.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleConstant.java @@ -1,36 +1,39 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.logic.sort.Sort; public class OracleConstant implements OracleTerm { - - private String value; - - private Sort sort; - - public static final OracleConstant TRUE = new OracleConstant("true", Sort.FORMULA); - public static final OracleConstant FALSE = new OracleConstant("false", Sort.FORMULA); - - public OracleConstant(String value, Sort sort) { - this.value = value; - this.sort = sort; - } - - public String getValue() { - return value; - } - - public Sort getSort() { - return sort; + + private String value; + + private Sort sort; + + public static final OracleConstant TRUE = new OracleConstant("true", Sort.FORMULA); + public static final OracleConstant FALSE = new OracleConstant("false", Sort.FORMULA); + + public OracleConstant(String value, Sort sort) { + this.value = value; + this.sort = sort; + } + + public String getValue() { + return value; } - public void setSort(Sort sort) { - this.sort = sort; + public Sort getSort() { + return sort; } - public String toString(){ - return value; - } - - + public void setSort(Sort sort) { + this.sort = sort; + } + + public String toString() { + return value; + } + + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleGenerator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleGenerator.java index 56d8cb6fc53..d29399ac04a 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleGenerator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleGenerator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.java.Services; @@ -166,7 +169,7 @@ public Set getConstants() { return constants; } - /* TODO: The argument t is never used?*/ + /* TODO: The argument t is never used? */ private List getMethodArgs(Term t) { List result = new LinkedList<>(); @@ -224,23 +227,23 @@ public OracleTerm generateOracle(Term term, boolean initialSelect) { LOGGER.debug("Translate: {} init: {}", term, initialSelect); - //binary terms + // binary terms if (ops.containsKey(op)) { OracleTerm left = generateOracle(term.sub(0), initialSelect); OracleTerm right = generateOracle(term.sub(1), initialSelect); String javaOp = ops.get(op); switch (javaOp) { - case EQUALS: - return eq(left, right); - case AND: - return and(left, right); - case OR: - return or(left, right); + case EQUALS: + return eq(left, right); + case AND: + return and(left, right); + case OR: + return or(left, right); } return new OracleBinTerm(javaOp, left, right); - }//negation + } // negation else if (op == Junctor.NOT) { OracleTerm sub = generateOracle(term.sub(0), initialSelect); if (sub instanceof OracleUnaryTerm) { @@ -249,11 +252,11 @@ else if (op == Junctor.NOT) { } return new OracleUnaryTerm(sub, Op.Neg); } - //true + // true else if (op == Junctor.TRUE) { return OracleConstant.TRUE; } - //false + // false else if (op == Junctor.FALSE) { return OracleConstant.FALSE; } else if (op == Junctor.IMP) { @@ -262,18 +265,17 @@ else if (op == Junctor.FALSE) { OracleTerm notLeft = neg(left); return new OracleBinTerm(OR, notLeft, right); } - //quantifiable variable + // quantifiable variable else if (op instanceof QuantifiableVariable) { QuantifiableVariable qop = (QuantifiableVariable) op; return new OracleVariable(qop.name().toString(), qop.sort()); } - //integers - else if (op == services.getTypeConverter().getIntegerLDT() - .getNumberSymbol()) { + // integers + else if (op == services.getTypeConverter().getIntegerLDT().getNumberSymbol()) { long num = NumberTranslation.translate(term.sub(0)).longValue(); return new OracleConstant(Long.toString(num), term.sort()); } - //forall + // forall else if (op == Quantifier.ALL || op == Quantifier.EX) { Sort field = services.getTypeConverter().getHeapLDT().getFieldSort(); Sort heap = services.getTypeConverter().getHeapLDT().targetSort(); @@ -289,7 +291,7 @@ else if (op == Quantifier.ALL || op == Quantifier.EX) { args.addAll(methodArgs); return new OracleMethodCall(method, args); } - //if-then-else + // if-then-else else if (op == IfThenElse.IF_THEN_ELSE) { OracleMethod method = createIfThenElseMethod(term, initialSelect); oracleMethods.add(method); @@ -298,17 +300,18 @@ else if (op == IfThenElse.IF_THEN_ELSE) { args.addAll(methodArgs); return new OracleMethodCall(method, args); } - //functions + // functions else if (op instanceof Function) { return translateFunction(term, initialSelect); } - //program variables + // program variables else if (op instanceof ProgramVariable) { ProgramVariable var = (ProgramVariable) op; return new OracleConstant(var.name().toString(), var.sort()); } else { LOGGER.debug("Could not translate: {}", term); - throw new RuntimeException("Could not translate oracle for: " + term + " of type " + term.op()); + throw new RuntimeException( + "Could not translate oracle for: " + term + " of type " + term.op()); } } @@ -345,7 +348,7 @@ private OracleTerm translateFunction(Term term, boolean initialSelect) { if (invariants.containsKey(s)) { m = invariants.get(s); } else { - //needed for recursive invariants + // needed for recursive invariants m = createDummyInvariant(s); invariants.put(s, m); @@ -398,11 +401,11 @@ private OracleTerm translateFunction(Term term, boolean initialSelect) { return new OracleUnaryTerm(sub, Op.Minus); } - throw new RuntimeException("Unsupported function found: " + name + " of type " + fun.getClass().getName()); + throw new RuntimeException( + "Unsupported function found: " + name + " of type " + fun.getClass().getName()); } - private OracleTerm translateQuery(Term term, boolean initialSelect, - Operator op) { + private OracleTerm translateQuery(Term term, boolean initialSelect, Operator op) { ProgramMethod pm = (ProgramMethod) op; OracleMethod m = createDummyOracleMethod(pm); @@ -424,7 +427,8 @@ private OracleTerm translateQuery(Term term, boolean initialSelect, LOGGER.info(" isstatic "); return new OracleMethodCall(m, params); } else { - OracleTerm caller = generateOracle(term.sub(1), false /*TODO: what does this parameter mean?*/); + OracleTerm caller = + generateOracle(term.sub(1), false /* TODO: what does this parameter mean? */); LOGGER.info(" non-static caller= {}", caller); return new OracleMethodCall(m, params, caller); } @@ -471,17 +475,20 @@ private OracleTerm translateSelect(Term term, boolean initialSelect) { String value; - value = createLocationString(heapTerm, objTerm, fieldName, object.sort(), term.sort(), initialSelect); + value = createLocationString(heapTerm, objTerm, fieldName, object.sort(), term.sort(), + initialSelect); if (!initialSelect && isPreHeap(heapTerm) && term.sort().extendsTrans(services.getJavaInfo().getJavaLangObject().getSort())) { - return new OracleConstant(TestCaseGenerator.OLDMap + ".get(" + value + ")", term.sort()); + return new OracleConstant(TestCaseGenerator.OLDMap + ".get(" + value + ")", + term.sort()); } return new OracleConstant(value, term.sort()); } - private String createLocationString(OracleTerm heapTerm, OracleTerm objTerm, String fieldName, Sort objSort, Sort fieldSort, boolean initialSelect) { + private String createLocationString(OracleTerm heapTerm, OracleTerm objTerm, String fieldName, + Sort objSort, Sort fieldSort, boolean initialSelect) { String value; String objString = objTerm.toString(); @@ -507,15 +514,10 @@ private String createLocationString(OracleTerm heapTerm, OracleTerm objTerm, Str rflCreator.addSort(objSort); rflCreator.addSort(objSort); - value = ReflectionClassCreator.NAME_OF_CLASS + - "." + - ReflectionClassCreator.GET_PREFIX + - ReflectionClassCreator.cleanTypeName(fieldSort.toString()) + - "(" + - objSort + ".class, " + - objString + ", " + - "\"" + fieldName + "\"" + - ")"; + value = ReflectionClassCreator.NAME_OF_CLASS + "." + + ReflectionClassCreator.GET_PREFIX + + ReflectionClassCreator.cleanTypeName(fieldSort.toString()) + "(" + objSort + + ".class, " + objString + ", " + "\"" + fieldName + "\"" + ")"; } else { value = objString + "." + fieldName; @@ -592,11 +594,8 @@ private OracleMethod createIfThenElseMethod(Term term, boolean initialSelect) { OracleTerm trueCase = generateOracle(term.sub(1), initialSelect); OracleTerm falseCase = generateOracle(term.sub(2), initialSelect); - String body = "if(" + cond + "){" - + "\n return " + trueCase + ";" - + "\n}else{" - + "\n return " + falseCase + ";" - + "\n}"; + String body = "if(" + cond + "){" + "\n return " + trueCase + ";" + "\n}else{" + + "\n return " + falseCase + ";" + "\n}"; return new OracleMethod(methodName, args, body, term.sort()); @@ -616,16 +615,16 @@ private String getSetName(Sort s) { return TestCaseGenerator.ALL_INTS; } else if (s.equals(services.getTypeConverter().getLocSetLDT().targetSort())) { throw new RuntimeException("Not implemented yet."); - //return TestCaseGenerator.ALL_LOCSETS + // return TestCaseGenerator.ALL_LOCSETS } else if (s.equals(services.getTypeConverter().getHeapLDT().getFieldSort())) { throw new RuntimeException("Not implemented yet."); - //return TestCaseGenerator.ALL_FIELDS + // return TestCaseGenerator.ALL_FIELDS } else if (s.equals(services.getTypeConverter().getHeapLDT().targetSort())) { throw new RuntimeException("Not implemented yet."); - //return TestCaseGenerator.ALL_HEAPS + // return TestCaseGenerator.ALL_HEAPS } else if (s.equals(services.getTypeConverter().getSeqLDT().targetSort())) { throw new RuntimeException("Not implemented yet."); - //return TestCaseGenerator.ALL_SEQ + // return TestCaseGenerator.ALL_SEQ } @@ -664,26 +663,20 @@ private OracleMethod createQuantifierMethod(Term term, boolean initialSelect) { return new OracleMethod(methodName, args, body); } - private String createForallBody(QuantifiableVariable qv, String setName, - OracleUnaryTerm neg) { + private String createForallBody(QuantifiableVariable qv, String setName, OracleUnaryTerm neg) { String tab = TestCaseGenerator.TAB; return "\n" + tab + "for(" + qv.sort().name() + " " + qv.name() + " : " + setName + "){" - + "\n" + tab + tab + "if(" + neg.toString() + "){" - + "\n" + tab + tab + tab + "return false;" - + "\n" + tab + tab + "}" - + "\n" + tab + "}" - + "\n" + tab + "return true;"; + + "\n" + tab + tab + "if(" + neg.toString() + "){" + "\n" + tab + tab + tab + + "return false;" + "\n" + tab + tab + "}" + "\n" + tab + "}" + "\n" + tab + + "return true;"; } - private String createExistsBody(QuantifiableVariable qv, String setName, - OracleTerm cond) { + private String createExistsBody(QuantifiableVariable qv, String setName, OracleTerm cond) { String tab = TestCaseGenerator.TAB; return "\n" + tab + "for(" + qv.sort().name() + " " + qv.name() + " : " + setName + "){" - + "\n" + tab + tab + "if(" + cond.toString() + "){" - + "\n" + tab + tab + tab + "return true;" - + "\n" + tab + tab + "}" - + "\n" + tab + "}" - + "\n" + tab + "return false;"; + + "\n" + tab + tab + "if(" + cond.toString() + "){" + "\n" + tab + tab + tab + + "return true;" + "\n" + tab + tab + "}" + "\n" + tab + "}" + "\n" + tab + + "return false;"; } private static OracleTerm neg(OracleTerm t) { @@ -743,4 +736,4 @@ private static OracleTerm or(OracleTerm left, OracleTerm right) { } -} \ No newline at end of file +} diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleInvariantTranslator.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleInvariantTranslator.java index 6cccf3ad4d7..3a8b2c2f369 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleInvariantTranslator.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleInvariantTranslator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.java.JavaInfo; @@ -18,75 +21,72 @@ public class OracleInvariantTranslator { - private Services services; - - public OracleInvariantTranslator(Services services){ - this.services = services; - } + private Services services; - public Term getInvariantTerm(Sort s){ - JavaInfo info = services.getJavaInfo(); - TermBuilder tb = new TermBuilder(services.getTermFactory(), services); - SpecificationRepository spec = services.getSpecificationRepository(); + public OracleInvariantTranslator(Services services) { + this.services = services; + } - Sort heapSort = services.getTypeConverter().getHeapLDT().targetSort(); + public Term getInvariantTerm(Sort s) { + JavaInfo info = services.getJavaInfo(); + TermBuilder tb = new TermBuilder(services.getTermFactory(), services); + SpecificationRepository spec = services.getSpecificationRepository(); - LogicVariable h = new LogicVariable(new Name("h"), heapSort); + Sort heapSort = services.getTypeConverter().getHeapLDT().targetSort(); + LogicVariable h = new LogicVariable(new Name("h"), heapSort); - KeYJavaType kjt = info.getKeYJavaType(s); - if(!(kjt.getJavaType() instanceof ClassDeclaration - || kjt.getJavaType() instanceof InterfaceDeclaration || kjt.getJavaType() instanceof ArrayDeclaration) - ) { - return tb.tt(); - } + KeYJavaType kjt = info.getKeYJavaType(s); - LogicVariable o = new LogicVariable(new Name("o"), kjt.getSort()); - - Term result = tb.tt(); - - for(ClassAxiom c : spec.getClassAxioms(kjt)){ + if (!(kjt.getJavaType() instanceof ClassDeclaration + || kjt.getJavaType() instanceof InterfaceDeclaration + || kjt.getJavaType() instanceof ArrayDeclaration)) { + return tb.tt(); + } - if(c instanceof RepresentsAxiom && c.getKJT().equals(kjt)){ - RepresentsAxiom ra = (RepresentsAxiom) c; - - Term t = ra.getAxiom(h, o, services); - - if(t.op().equals(Equality.EQV)){ - - Term[] heaps = new Term[1]; - heaps[0] = tb.var(h); + LogicVariable o = new LogicVariable(new Name("o"), kjt.getSort()); - Term inv = tb.inv(heaps, tb.var(o)); - Term left = t.sub(0); - Term right = t.sub(1); - - if(left.op().name().equals(inv.op().name())){ - if(!right.equals(tb.tt())){ - result = tb.and(result, right); - } - } - else if(right.op().name().equals(inv.op().name())){ - if(!left.equals(tb.tt())){ - result = tb.and(result, left); - } - } - - - } + Term result = tb.tt(); + for (ClassAxiom c : spec.getClassAxioms(kjt)) { - } + if (c instanceof RepresentsAxiom && c.getKJT().equals(kjt)) { + RepresentsAxiom ra = (RepresentsAxiom) c; - } + Term t = ra.getAxiom(h, o, services); - return tb.tt(); + if (t.op().equals(Equality.EQV)) { + Term[] heaps = new Term[1]; + heaps[0] = tb.var(h); + Term inv = tb.inv(heaps, tb.var(o)); + Term left = t.sub(0); + Term right = t.sub(1); + if (left.op().name().equals(inv.op().name())) { + if (!right.equals(tb.tt())) { + result = tb.and(result, right); + } + } else if (right.op().name().equals(inv.op().name())) { + if (!left.equals(tb.tt())) { + result = tb.and(result, left); + } + } - } + } + + + } + + } + + return tb.tt(); + + + + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocation.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocation.java index eca2f911d82..32a5b2d981c 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocation.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocation.java @@ -1,58 +1,60 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; public class OracleLocation { - - public static String ALL_FIELDS = ""; - - private String object; - - private String field; - - public OracleLocation(String object, String field) { - this.object = object; - this.field = field; - } - - public OracleLocation(String object){ - this.object = object; - this.field = ALL_FIELDS; - } - - - public String getObject() { - return object; - } - - - public String getField() { - return field; - } - - public boolean isAllFields(){ - return field.equals(ALL_FIELDS); - } - - public boolean equals(Object o){ - - if(o instanceof OracleLocation){ - OracleLocation l = (OracleLocation) o; - return object.equals(l.object) && field.equals(l.field); - } - - return false; - - } - - public String toString(){ - - if(field.startsWith("[")){ - return object+field; - } - else{ - return object + "."+ field; - } - - - } - + + public static String ALL_FIELDS = ""; + + private String object; + + private String field; + + public OracleLocation(String object, String field) { + this.object = object; + this.field = field; + } + + public OracleLocation(String object) { + this.object = object; + this.field = ALL_FIELDS; + } + + + public String getObject() { + return object; + } + + + public String getField() { + return field; + } + + public boolean isAllFields() { + return field.equals(ALL_FIELDS); + } + + public boolean equals(Object o) { + + if (o instanceof OracleLocation) { + OracleLocation l = (OracleLocation) o; + return object.equals(l.object) && field.equals(l.field); + } + + return false; + + } + + public String toString() { + + if (field.startsWith("[")) { + return object + field; + } else { + return object + "." + field; + } + + + } + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocationSet.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocationSet.java index 12e73f9cb14..7afc277611c 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocationSet.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleLocationSet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import java.util.HashSet; @@ -5,135 +8,137 @@ public class OracleLocationSet { - private Set locs; - - public static final EmptyOracleLocationSet EMPTY = new EmptyOracleLocationSet(); - - public static final AllLocsLocationSet ALL_LOCS = new AllLocsLocationSet(); - - - public OracleLocationSet() { - locs = new HashSet(); - } - - private void add(OracleLocation loc){ - locs.add(loc); - } - - private void add(OracleLocationSet loc){ - locs.addAll(loc.locs); - } - - public static OracleLocationSet singleton(OracleLocation loc){ - OracleLocationSet result = new OracleLocationSet(); - result.add(loc); - return result; - } - - public static OracleLocationSet union(OracleLocationSet l1, OracleLocationSet l2){ - - if(l1 == ALL_LOCS || l2 == ALL_LOCS){ - return ALL_LOCS; - } - - if(l1 == EMPTY){ - return l2; - } - - if(l2 == EMPTY){ - return l1; - } - - OracleLocationSet result = new OracleLocationSet(); - result.add(l1); - result.add(l2); - return result; - } - - public static OracleLocationSet intersect(OracleLocationSet l1, OracleLocationSet l2){ - - if(l1 == EMPTY || l2 == EMPTY){ - return EMPTY; - } - - if(l1 == ALL_LOCS){ - return l2; - } - - if(l2 == ALL_LOCS){ - return l1; - } - - OracleLocationSet result = new OracleLocationSet(); - for(OracleLocation l : l1.locs){ - if(l2.contains(l)){ - result.add(l); - } - } - - - for(OracleLocation l : l2.locs){ - if(l1.contains(l)){ - result.add(l); - } - } - - return result; - } - - public boolean contains(OracleLocation l){ - for(OracleLocation loc : locs){ - - if(loc.equals(l)){ - return true; - } - - if(loc.isAllFields() && loc.getObject().equals(l.getObject())){ - return true; - } - - } - - return false; - } - - public String toString(){ - - if(this == EMPTY){ - return "Empty"; - } - - if(this == ALL_LOCS){ - return "All"; - } - - - String result = ""; - - result += "{"; - - for(OracleLocation loc : locs){ - result += loc + " "; - } - - result += "}"; - - - return result; - - - } + private Set locs; + + public static final EmptyOracleLocationSet EMPTY = new EmptyOracleLocationSet(); + + public static final AllLocsLocationSet ALL_LOCS = new AllLocsLocationSet(); + + + public OracleLocationSet() { + locs = new HashSet(); + } + + private void add(OracleLocation loc) { + locs.add(loc); + } + + private void add(OracleLocationSet loc) { + locs.addAll(loc.locs); + } + + public static OracleLocationSet singleton(OracleLocation loc) { + OracleLocationSet result = new OracleLocationSet(); + result.add(loc); + return result; + } + + public static OracleLocationSet union(OracleLocationSet l1, OracleLocationSet l2) { + + if (l1 == ALL_LOCS || l2 == ALL_LOCS) { + return ALL_LOCS; + } + + if (l1 == EMPTY) { + return l2; + } + + if (l2 == EMPTY) { + return l1; + } + + OracleLocationSet result = new OracleLocationSet(); + result.add(l1); + result.add(l2); + return result; + } + + public static OracleLocationSet intersect(OracleLocationSet l1, OracleLocationSet l2) { + + if (l1 == EMPTY || l2 == EMPTY) { + return EMPTY; + } + + if (l1 == ALL_LOCS) { + return l2; + } + + if (l2 == ALL_LOCS) { + return l1; + } + + OracleLocationSet result = new OracleLocationSet(); + for (OracleLocation l : l1.locs) { + if (l2.contains(l)) { + result.add(l); + } + } + + + for (OracleLocation l : l2.locs) { + if (l1.contains(l)) { + result.add(l); + } + } + + return result; + } + + public boolean contains(OracleLocation l) { + for (OracleLocation loc : locs) { + + if (loc.equals(l)) { + return true; + } + + if (loc.isAllFields() && loc.getObject().equals(l.getObject())) { + return true; + } + + } + + return false; + } + + public String toString() { + + if (this == EMPTY) { + return "Empty"; + } + + if (this == ALL_LOCS) { + return "All"; + } + + + String result = ""; + + result += "{"; + + for (OracleLocation loc : locs) { + result += loc + " "; + } + + result += "}"; + + + return result; + + + } } -class EmptyOracleLocationSet extends OracleLocationSet{ - public boolean contains(OracleLocation l){ - return false; - } + +class EmptyOracleLocationSet extends OracleLocationSet { + public boolean contains(OracleLocation l) { + return false; + } } -class AllLocsLocationSet extends OracleLocationSet{ - public boolean contains(OracleLocation l){ - return true; - } + +class AllLocsLocationSet extends OracleLocationSet { + public boolean contains(OracleLocation l) { + return true; + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethod.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethod.java index 3b4ef5ae55c..f8d1ba458f7 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethod.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.logic.sort.Sort; @@ -15,16 +18,14 @@ public class OracleMethod { private Sort returnType; - public OracleMethod(String methodName, List args, - String body) { + public OracleMethod(String methodName, List args, String body) { super(); this.methodName = methodName; this.args = args; this.body = body; } - public OracleMethod(String methodName, List args, - String body, Sort sort) { + public OracleMethod(String methodName, List args, String body, Sort sort) { super(); this.methodName = methodName; this.args = args; @@ -60,9 +61,8 @@ public String toString() { if (returnType != null) { retType = returnType.name().toString(); } - return tab + "public " + retType + " " + methodName + "(" + argString + "){\n" - + tab + tab + body + "\n" - + tab + "}"; + return tab + "public " + retType + " " + methodName + "(" + argString + "){\n" + tab + tab + + body + "\n" + tab + "}"; } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethodCall.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethodCall.java index a6ba62085c4..a9e7cbbf465 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethodCall.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleMethodCall.java @@ -1,42 +1,45 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import java.util.List; public class OracleMethodCall implements OracleTerm { - - private OracleMethod method; - private List args; - private OracleTerm caller; - - public OracleMethodCall(OracleMethod method, List args) { - super(); - this.method = method; - this.args = args; - caller = null; + + private OracleMethod method; + private List args; + private OracleTerm caller; + + public OracleMethodCall(OracleMethod method, List args) { + super(); + this.method = method; + this.args = args; + caller = null; + } + + public OracleMethodCall(OracleMethod method, List args, + OracleTerm caller) { + super(); + this.method = method; + this.args = args; + this.caller = caller; } - - public OracleMethodCall(OracleMethod method, List args, OracleTerm caller) { - super(); - this.method = method; - this.args = args; - this.caller = caller; - } - - public String toString(){ - String methodName = method.getMethodName(); - String aString = ""; - for(OracleTerm arg : args){ - aString += " "+arg.toString() + ","; - } - if(!args.isEmpty()){ - aString = aString.substring(0, aString.length()-1); - } - if(caller!=null){ - return caller+"."+methodName+"("+aString+")"; - } - else{ - return methodName+"("+aString+")"; - } - } - + + public String toString() { + String methodName = method.getMethodName(); + String aString = ""; + for (OracleTerm arg : args) { + aString += " " + arg.toString() + ","; + } + if (!args.isEmpty()) { + aString = aString.substring(0, aString.length() - 1); + } + if (caller != null) { + return caller + "." + methodName + "(" + aString + ")"; + } else { + return methodName + "(" + aString + ")"; + } + } + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleTerm.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleTerm.java index 94e63871129..ca98b5b8217 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleTerm.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleTerm.java @@ -1,5 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; public interface OracleTerm { - + } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleType.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleType.java index be912a4887c..2e1c133ec6f 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleType.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleType.java @@ -1,20 +1,23 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.logic.sort.Sort; public class OracleType implements OracleTerm { - - private Sort s; - - public OracleType(Sort s) { - super(); - this.s = s; - } - - public String toString(){ - - return s.name().toString(); - - } + + private Sort s; + + public OracleType(Sort s) { + super(); + this.s = s; + } + + public String toString() { + + return s.name().toString(); + + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleUnaryTerm.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleUnaryTerm.java index 2ff97a830fe..d5524143648 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleUnaryTerm.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleUnaryTerm.java @@ -1,45 +1,51 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import java.util.HashMap; import java.util.Map; -public class OracleUnaryTerm implements OracleTerm{ - - - - public enum Op {Neg, Minus}; - public static String OP_NEG = "!"; - public static String OP_MINUS = "-"; - private static Map op2String; - - static{ - op2String = new HashMap(); - op2String.put(Op.Neg, OP_NEG); - op2String.put(Op.Minus, OP_MINUS); - } - - - private OracleTerm sub; - private Op op; - - public OracleUnaryTerm(OracleTerm sub, Op op) { - this.sub = sub; - this.op = op; - } - - - - public Op getOp() { - return op; - } - - - - public OracleTerm getSub() { - return sub; - } - - public String toString(){ - return op2String.get(op)+sub.toString(); - } +public class OracleUnaryTerm implements OracleTerm { + + + + public enum Op { + Neg, Minus + }; + + public static String OP_NEG = "!"; + public static String OP_MINUS = "-"; + private static Map op2String; + + static { + op2String = new HashMap(); + op2String.put(Op.Neg, OP_NEG); + op2String.put(Op.Minus, OP_MINUS); + } + + + private OracleTerm sub; + private Op op; + + public OracleUnaryTerm(OracleTerm sub, Op op) { + this.sub = sub; + this.op = op; + } + + + + public Op getOp() { + return op; + } + + + + public OracleTerm getSub() { + return sub; + } + + public String toString() { + return op2String.get(op) + sub.toString(); + } } diff --git a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleVariable.java b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleVariable.java index 914360d7b87..718c6063cd3 100644 --- a/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleVariable.java +++ b/key/key.core.testgen/src/main/java/de/uka/ilkd/key/testgen/oracle/OracleVariable.java @@ -1,60 +1,63 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testgen.oracle; import de.uka.ilkd.key.logic.sort.Sort; public class OracleVariable implements OracleTerm { - - private String name; - - private Sort sort; - - public OracleVariable(String name, Sort sort) { - this.name = name; - this.sort = sort; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((sort == null) ? 0 : sort.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OracleVariable other = (OracleVariable) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (sort == null) { - if (other.sort != null) - return false; - } else if (!sort.equals(other.sort)) - return false; - return true; - } - - public String getName() { - return name; - } - - public Sort getSort(){ - return sort; - } - - public String toString(){ - return name; - } - - + + private String name; + + private Sort sort; + + public OracleVariable(String name, Sort sort) { + this.name = name; + this.sort = sort; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((sort == null) ? 0 : sort.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OracleVariable other = (OracleVariable) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (sort == null) { + if (other.sort != null) + return false; + } else if (!sort.equals(other.sort)) + return false; + return true; + } + + public String getName() { + return name; + } + + public Sort getSort() { + return sort; + } + + public String toString() { + return name; + } + + } diff --git a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/suite/util/HelperClassForTestgenTests.java b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/suite/util/HelperClassForTestgenTests.java index 6838144a24a..c12b68bbe8e 100644 --- a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/suite/util/HelperClassForTestgenTests.java +++ b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/suite/util/HelperClassForTestgenTests.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.suite.util; import org.key_project.util.helper.FindResources; diff --git a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/SMTTestSettings.java b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/SMTTestSettings.java index 0d0ac3a73b5..2e08fb23145 100644 --- a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/SMTTestSettings.java +++ b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/SMTTestSettings.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testcase.smt.ce; import de.uka.ilkd.key.rule.Taclet; @@ -9,37 +12,36 @@ import java.io.File; import java.util.Collection; -public class SMTTestSettings implements de.uka.ilkd.key.smt.SMTSettings{ +public class SMTTestSettings implements de.uka.ilkd.key.smt.SMTSettings { - public long getGlobalBound(){ - return 0; - } + public long getGlobalBound() { + return 0; + } @Override public int getMaxConcurrentProcesses() { - return 1; + return 1; } @Override public int getMaxNumberOfGenerics() { - return 2; + return 2; } @Override public String getSMTTemporaryFolder() { - return PathConfig.getKeyConfigDir() - + File.separator + "smt_formula"; + return PathConfig.getKeyConfigDir() + File.separator + "smt_formula"; } @Override public Collection getTaclets() { - return null; + return null; } @Override public long getTimeout() { - return 300000; + return 300000; } @Override @@ -49,86 +51,86 @@ public long getTimeout(SolverType type) { @Override public boolean instantiateNullAssumption() { - return true; + return true; } @Override public boolean makesUseOfTaclets() { - return false; + return false; } @Override public boolean useExplicitTypeHierarchy() { - return false; + return false; } @Override public boolean useBuiltInUniqueness() { - return false; + return false; } @Override public boolean useAssumptionsForBigSmallIntegers() { - return false; + return false; } @Override public boolean useUninterpretedMultiplicationIfNecessary() { - return false; + return false; } -@Override -public long getMaximumInteger() { + @Override + public long getMaximumInteger() { return ProofDependentSMTSettings.getDefaultSettingsData().maxInteger; -} + } -@Override -public long getMinimumInteger() { + @Override + public long getMinimumInteger() { return ProofDependentSMTSettings.getDefaultSettingsData().minInteger; -} + } -@Override -public String getLogic() { - // Set the logic to the most general one according to the SMT-LIB standard. - return "AUFNIRA"; -} + @Override + public String getLogic() { + // Set the logic to the most general one according to the SMT-LIB standard. + return "AUFNIRA"; + } -@Override -public boolean checkForSupport() { - return false; -} + @Override + public boolean checkForSupport() { + return false; + } -@Override -public long getIntBound() { - return 3; -} + @Override + public long getIntBound() { + return 3; + } -@Override -public long getHeapBound() { - return 3; -} + @Override + public long getHeapBound() { + return 3; + } -@Override -public long getSeqBound() { - return 3; -} + @Override + public long getSeqBound() { + return 3; + } -@Override -public long getObjectBound() { - return 3; -} + @Override + public long getObjectBound() { + return 3; + } -@Override -public long getLocSetBound() { - return 3; -} + @Override + public long getLocSetBound() { + return 3; + } -@Override -public boolean invarianForall() { - return false; -} + @Override + public boolean invarianForall() { + return false; + } @Override public NewSMTTranslationSettings getNewSettings() { diff --git a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCE.java b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCE.java index fd59cb3fbae..92e5804c12e 100644 --- a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCE.java +++ b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCE.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testcase.smt.ce; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -21,7 +24,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class TestCE extends TestCommons { - public static final File testFile = new File(HelperClassForTestgenTests.TESTCASE_DIRECTORY, "smt/ce/"); + public static final File testFile = + new File(HelperClassForTestgenTests.TESTCASE_DIRECTORY, "smt/ce/"); private static final String SYSTEM_PROPERTY_SOLVER_PATH = "z3SolverPath"; private static final Logger LOGGER = LoggerFactory.getLogger(TestCE.class); private static boolean isInstalled = false; @@ -32,14 +36,18 @@ public boolean toolNotInstalled() { isInstalled = getSolverType().isInstalled(true); installChecked = true; if (!isInstalled) { - LOGGER.warn("Warning: {} is not installed, tests skipped.", getSolverType().getName()); - LOGGER.warn("Maybe use JVM system property \"{}\" to define the path to the Z3 command.", + LOGGER.warn("Warning: {} is not installed, tests skipped.", + getSolverType().getName()); + LOGGER.warn( + "Maybe use JVM system property \"{}\" to define the path to the Z3 command.", SYSTEM_PROPERTY_SOLVER_PATH); } if (isInstalled && !getSolverType().supportHasBeenChecked()) { if (!getSolverType().checkForSupport()) { - LOGGER.warn("Warning: The version of the solver {} " + - "used for the following tests may not be supported.", getSolverType().getName()); + LOGGER.warn( + "Warning: The version of the solver {} " + + "used for the following tests may not be supported.", + getSolverType().getName()); } } } @@ -50,8 +58,7 @@ public boolean toolNotInstalled() { public SolverType getSolverType() { SolverType type = SolverTypes.Z3_CE_SOLVER; // SolverType type = SolverType.Z3_SOLVER; - String solverPathProperty = System - .getProperty(SYSTEM_PROPERTY_SOLVER_PATH); + String solverPathProperty = System.getProperty(SYSTEM_PROPERTY_SOLVER_PATH); if (solverPathProperty != null && !solverPathProperty.isEmpty()) { type.setSolverCommand(solverPathProperty); } diff --git a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCommons.java b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCommons.java index c4cf4bcef1f..cb762da8bcb 100644 --- a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCommons.java +++ b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/ce/TestCommons.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testcase.smt.ce; import de.uka.ilkd.key.control.KeYEnvironment; @@ -22,12 +25,12 @@ import static org.junit.jupiter.api.Assertions.*; /** - * Use this class for testing SMT: It provides a mechanism to load proofs and - * taclets. Do not modify this class directly but derive subclasses to implement - * tests. + * Use this class for testing SMT: It provides a mechanism to load proofs and taclets. Do not modify + * this class directly but derive subclasses to implement tests. */ public abstract class TestCommons { - protected static File folder = new File(HelperClassForTests.TESTCASE_DIRECTORY, "smt/tacletTranslation"); + protected static File folder = + new File(HelperClassForTests.TESTCASE_DIRECTORY, "smt/tacletTranslation"); /** * The set of taclets */ @@ -55,7 +58,8 @@ protected TermServices getServices() { public abstract boolean toolNotInstalled(); - protected boolean correctResult(String filepath, boolean isValid) throws ProblemLoaderException { + protected boolean correctResult(String filepath, boolean isValid) + throws ProblemLoaderException { if (toolNotInstalled()) { return true; } @@ -110,8 +114,8 @@ protected KeYEnvironment loadProof(String filepath) throws ProblemLoaderExcep } /** - * Returns a set of taclets that can be used for tests. REMARK: First you - * have to call parse to instantiate the set of taclets. + * Returns a set of taclets that can be used for tests. REMARK: First you have to call + * parse to instantiate the set of taclets. * * @return set of taclets. */ @@ -144,8 +148,7 @@ protected ProofAggregate parse() { } /** - * Calls - * parse(File file, Profile profile) with the standard profile for testing. + * Calls parse(File file, Profile profile) with the standard profile for testing. */ protected ProofAggregate parse(File file) { return parse(file, profile); @@ -155,15 +158,14 @@ protected ProofAggregate parse(File file) { * Parses a problem file and returns the corresponding ProofAggregate. * * @param file problem file. - * @param pro determines the profile that should be used. + * @param pro determines the profile that should be used. * @return ProofAggregate of the problem file. */ protected ProofAggregate parse(File file, Profile pro) { assertTrue(file.exists()); ProofAggregate result = null; try { - KeYUserProblemFile po = new KeYUserProblemFile(file.getName(), - file, null, pro); + KeYUserProblemFile po = new KeYUserProblemFile(file.getName(), file, null, pro); if (initializer == null) { initializer = new ProblemInitializer(po.getProfile()); } diff --git a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/testgen/TestTestgen.java b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/testgen/TestTestgen.java index b5e45a4880d..728ce81d9b7 100644 --- a/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/testgen/TestTestgen.java +++ b/key/key.core.testgen/src/test/java/de/uka/ilkd/key/testcase/smt/testgen/TestTestgen.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.testcase.smt.testgen; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; @@ -19,15 +22,15 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; public class TestTestgen extends TestCommons { - public static final File testFile = new File( - HelperClassForTestgenTests.TESTCASE_DIRECTORY, "smt/tg"); + public static final File testFile = + new File(HelperClassForTestgenTests.TESTCASE_DIRECTORY, "smt/tg"); private static final String SYSTEM_PROPERTY_SOLVER_PATH = "z3SolverPath"; private static final Logger LOGGER = LoggerFactory.getLogger(TestTestgen.class); private static boolean isInstalled = false; private static boolean installChecked = false; @BeforeEach - public void setup(){ + public void setup() { assumeFalse(toolNotInstalled()); } @@ -37,14 +40,18 @@ public boolean toolNotInstalled() { isInstalled = getSolverType().isInstalled(true); installChecked = true; if (!isInstalled) { - LOGGER.warn("Warning: {} is not installed, tests skipped.", getSolverType().getName()); - LOGGER.warn("Maybe use JVM system property \"{}\" to define the path to the Z3 command.", + LOGGER.warn("Warning: {} is not installed, tests skipped.", + getSolverType().getName()); + LOGGER.warn( + "Maybe use JVM system property \"{}\" to define the path to the Z3 command.", SYSTEM_PROPERTY_SOLVER_PATH); } if (isInstalled && !getSolverType().supportHasBeenChecked()) { if (!getSolverType().checkForSupport()) { - LOGGER.warn("Warning: The version of the solver {} " + - "used for the following tests may not be supported.", getSolverType().getName()); + LOGGER.warn( + "Warning: The version of the solver {} " + + "used for the following tests may not be supported.", + getSolverType().getName()); } } } @@ -53,8 +60,7 @@ public boolean toolNotInstalled() { public SolverType getSolverType() { SolverType type = SolverTypes.Z3_CE_SOLVER; - String solverPathProperty = System - .getProperty(SYSTEM_PROPERTY_SOLVER_PATH); + String solverPathProperty = System.getProperty(SYSTEM_PROPERTY_SOLVER_PATH); if (solverPathProperty != null && !solverPathProperty.isEmpty()) { type.setSolverCommand(solverPathProperty); } @@ -65,7 +71,8 @@ public SolverType getSolverType() { public void testMiddle() throws Exception { File file = new File(testFile, "middle.key"); assertTrue(file.exists(), "File " + file + " does not exists!"); - KeYEnvironment env = KeYEnvironment.load(file, null, null, null); + KeYEnvironment env = + KeYEnvironment.load(file, null, null, null); try { Proof proof = env.getLoadedProof(); assertNotNull(proof); diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/DefaultSpecificationContainer.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/DefaultSpecificationContainer.java index 8e5eada0cfe..134996d09d7 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/DefaultSpecificationContainer.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/DefaultSpecificationContainer.java @@ -1,4 +1,6 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.util.HashMap; @@ -14,99 +16,98 @@ /** * Default implementation of {@link SpecificationContainer}. - * + * * @author bruns */ public class DefaultSpecificationContainer implements SpecificationContainer { - private final Map field2domain = new HashMap<>(); - private final Map param2domain = new HashMap<>(); - private final Map return2domain = new HashMap<>(); - private final Set> flow = new LinkedHashSet<>(); + private final Map field2domain = new HashMap<>(); + private final Map param2domain = new HashMap<>(); + private final Map return2domain = new HashMap<>(); + private final Set> flow = new LinkedHashSet<>(); - public DefaultSpecificationContainer(Map domainAssignments, - Set> flow2) { - // TODO: this copying is ugly and inefficient - for (final Entry e : domainAssignments.entrySet()) { - if (e.getKey() instanceof Field) { - field2domain.put((Field) e.getKey(), e.getValue()); - } else if (e.getKey() instanceof Parameter) { - param2domain.put((Parameter) e.getKey(), e.getValue()); - } else if (e.getKey() instanceof ReturnValue) { - return2domain.put((ReturnValue) e.getKey(), e.getValue()); - } - } - this.flow.addAll(flow2); - } + public DefaultSpecificationContainer(Map domainAssignments, + Set> flow2) { + // TODO: this copying is ugly and inefficient + for (final Entry e : domainAssignments.entrySet()) { + if (e.getKey() instanceof Field) { + field2domain.put((Field) e.getKey(), e.getValue()); + } else if (e.getKey() instanceof Parameter) { + param2domain.put((Parameter) e.getKey(), e.getValue()); + } else if (e.getKey() instanceof ReturnValue) { + return2domain.put((ReturnValue) e.getKey(), e.getValue()); + } + } + this.flow.addAll(flow2); + } - @Override - public String toString() { - return "Fields: " + field2domain - + "\nParameters: " + param2domain - + "\nReturns: " + return2domain - + "\nFlows: " + flow; - } + @Override + public String toString() { + return "Fields: " + field2domain + "\nParameters: " + param2domain + "\nReturns: " + + return2domain + "\nFlows: " + flow; + } - private String[] extractParamTypes(recoder.java.declaration.MethodDeclaration md) { - final int params = md.getParameterDeclarationCount(); - final String[] paramTypes = new String[params]; - for (int i = 0; i < params; i++) { - final recoder.java.declaration.ParameterDeclaration pd = md - .getParameterDeclarationAt(i); - paramTypes[i] = pd.getTypeReference().getName(); - } - return paramTypes; - } + private String[] extractParamTypes(recoder.java.declaration.MethodDeclaration md) { + final int params = md.getParameterDeclarationCount(); + final String[] paramTypes = new String[params]; + for (int i = 0; i < params; i++) { + final recoder.java.declaration.ParameterDeclaration pd = + md.getParameterDeclarationAt(i); + paramTypes[i] = pd.getTypeReference().getName(); + } + return paramTypes; + } - @Override - public String field(recoder.java.declaration.FieldDeclaration fd, Type type) { - final recoder.java.declaration.FieldSpecification fs = fd.getVariables().get(0); - final recoder.abstraction.ClassTypeContainer ctype = fs.getContainingClassType(); - final String inClass = ctype.getName(); - final String inPackage = ctype.getPackage().getFullName(); - return field(inPackage, inClass, fs.getName(), type); - } + @Override + public String field(recoder.java.declaration.FieldDeclaration fd, Type type) { + final recoder.java.declaration.FieldSpecification fs = fd.getVariables().get(0); + final recoder.abstraction.ClassTypeContainer ctype = fs.getContainingClassType(); + final String inClass = ctype.getName(); + final String inPackage = ctype.getPackage().getFullName(); + return field(inPackage, inClass, fs.getName(), type); + } - @Override - public String field(String inPackage, String inClass, String name, Type type) { - return field2domain.get(new Field(name, inPackage, inClass, type)); - } + @Override + public String field(String inPackage, String inClass, String name, Type type) { + return field2domain.get(new Field(name, inPackage, inClass, type)); + } - @Override - public String parameter(recoder.java.declaration.MethodDeclaration md, int index, Type type) { - final String[] paramTypes = extractParamTypes(md); - final recoder.abstraction.ClassType ctype = md.getContainingClassType(); - return parameter(ctype.getPackage().getFullName(), ctype.getName(), - md.getName(), paramTypes, index, type); - } + @Override + public String parameter(recoder.java.declaration.MethodDeclaration md, int index, Type type) { + final String[] paramTypes = extractParamTypes(md); + final recoder.abstraction.ClassType ctype = md.getContainingClassType(); + return parameter(ctype.getPackage().getFullName(), ctype.getName(), md.getName(), + paramTypes, index, type); + } - @Override - public String parameter(String inPackage, String inClass, - String methodName, String[] paramTypes, int index, Type type) { - return param2domain.get(new Parameter(index, methodName, paramTypes, inPackage, inClass, type)); - } + @Override + public String parameter(String inPackage, String inClass, String methodName, + String[] paramTypes, int index, Type type) { + return param2domain + .get(new Parameter(index, methodName, paramTypes, inPackage, inClass, type)); + } - @Override - public String returnValue(recoder.java.declaration.MethodDeclaration md, Type type) { - final recoder.abstraction.ClassType ctype = md.getContainingClassType(); - return returnValue(ctype.getPackage().getFullName(), ctype.getName(), - md.getName(), extractParamTypes(md), type); - } + @Override + public String returnValue(recoder.java.declaration.MethodDeclaration md, Type type) { + final recoder.abstraction.ClassType ctype = md.getContainingClassType(); + return returnValue(ctype.getPackage().getFullName(), ctype.getName(), md.getName(), + extractParamTypes(md), type); + } - @Override - public String returnValue(String inPackage, String inClass, - String methodName, String[] paramTypes, Type type) { - return return2domain.get(new ReturnValue(methodName, paramTypes, inPackage, inClass, type)); - } + @Override + public String returnValue(String inPackage, String inClass, String methodName, + String[] paramTypes, Type type) { + return return2domain.get(new ReturnValue(methodName, paramTypes, inPackage, inClass, type)); + } - @Override - public Set flows(String domain) { - Set result = new LinkedHashSet<>(); - for (final Entry e : flow) { - if(e.getValue().equals(domain)){ - result.add(e.getKey()); - } - } - return result; - } -} \ No newline at end of file + @Override + public Set flows(String domain) { + Set result = new LinkedHashSet<>(); + for (final Entry e : flow) { + if (e.getValue().equals(domain)) { + result.add(e.getKey()); + } + } + return result; + } +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLHandler.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLHandler.java index 5fffb580f9a..cb05a4b2e59 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLHandler.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLHandler.java @@ -1,4 +1,6 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.text.MessageFormat; @@ -19,10 +21,9 @@ import static de.uka.ilkd.key.util.rifl.SpecificationEntity.*; /** - * XML content handler for the RIFL language. Produces a RIFL - * {@link SpecificationContainer}. May throw obscure exceptions on - * non-wellformed XML documents. - * Refer to the RIFL 1.0 Language definition by Ereth, Mantel, and Perner. + * XML content handler for the RIFL language. Produces a RIFL {@link SpecificationContainer}. May + * throw obscure exceptions on non-wellformed XML documents. Refer to the RIFL 1.0 Language + * definition by Ereth, Mantel, and Perner. * * @author bruns */ @@ -47,7 +48,9 @@ public void fatalError(SAXParseException spe) throws SAXException { private String getParseExceptionInfo(SAXParseException spe) { String systemId = spe.getSystemId(); - if (systemId == null) { systemId = "null"; } + if (systemId == null) { + systemId = "null"; + } return "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); } @@ -73,13 +76,15 @@ private static String printAttributes(Attributes a) { return sb.toString(); } - private final Map> sources2categories = new LinkedHashMap<>(); - private final Map> sinks2categories = new LinkedHashMap<>(); - private final Map, String> categories2domains = new LinkedHashMap<>(); + private final Map> sources2categories = + new LinkedHashMap<>(); + private final Map> sinks2categories = + new LinkedHashMap<>(); + private final Map, String> categories2domains = new LinkedHashMap<>(); private final Map handles2categories = new LinkedHashMap<>(); private Set domains = new LinkedHashSet<>(); private Set> flow = new LinkedHashSet<>(); - private Map> tmpMap = null; + private Map> tmpMap = null; private Type type = null; private String tmpHandle = null; @@ -87,13 +92,12 @@ private static String printAttributes(Attributes a) { private String category = DEFAULT_CATEGORY; - public RIFLHandler() { - } + public RIFLHandler() {} private void assignHandle(Attributes attributes) { final String handle = attributes.getValue("handle").intern(); final String domain = attributes.getValue("domain").intern(); - Pair p = new Pair<>(handle, handles2categories.get(handle)); + Pair p = new Pair<>(handle, handles2categories.get(handle)); categories2domains.put(p, domain); } @@ -124,7 +128,7 @@ private void putField(Attributes attributes) { final String field = attributes.getValue("name"); final String clazz = attributes.getValue("class"); final String packg = attributes.getValue("package"); - final SpecificationEntity se = new Field(field,packg,clazz, type); + final SpecificationEntity se = new Field(field, packg, clazz, type); handles2categories.put(tmpHandle, category); tmpMap.put(se, new Pair<>(tmpHandle, category)); } @@ -134,7 +138,7 @@ private void putParam(Attributes attributes) { final String clazz = attributes.getValue("class"); final String method = attributes.getValue("method"); final int param = Integer.parseInt(attributes.getValue("parameter")); - final SpecificationEntity se = new Parameter(param,method,packg,clazz, type); + final SpecificationEntity se = new Parameter(param, method, packg, clazz, type); handles2categories.put(tmpHandle, category); tmpMap.put(se, new Pair<>(tmpHandle, category)); } @@ -180,23 +184,19 @@ private void checkDomainAssignmentsWithFlows() { // This method tried to remove flows implicitly assumed by JML, // but for more than two domains this would need a default "high domain". - /*final Iterator> it = categories2domains.keySet().iterator(); - for (Pair p = it.next(); it.hasNext(); p = it.next()) { - for(Entry e : flow){ - if(e.getKey().equals(DEFAULT_DOMAIN) && categories2domains.containsKey(p) - && categories2domains.get(p).equals(e.getValue())){ - if (p.first.equals("h")) { - throw new RuntimeException(); - } - it.remove(); - } - } - - }*/ + /* + * final Iterator> it = categories2domains.keySet().iterator(); for + * (Pair p = it.next(); it.hasNext(); p = it.next()) { + * for(Entry e : flow){ if(e.getKey().equals(DEFAULT_DOMAIN) && + * categories2domains.containsKey(p) && categories2domains.get(p).equals(e.getValue())){ if + * (p.first.equals("h")) { throw new RuntimeException(); } it.remove(); } } + * + * } + */ } private void checkFlows() { - for (var p: categories2domains.entrySet()) { + for (var p : categories2domains.entrySet()) { assert domains.contains(categories2domains.get(p.getKey())); } } @@ -219,7 +219,7 @@ public void startElement(String uri, String localName, String qName, Attributes case "assign": assignHandle(attributes); break; - //case "domainassignment": + // case "domainassignment": case "domains": startDomains(); break; @@ -245,16 +245,16 @@ public void startElement(String uri, String localName, String qName, Attributes putFlow(attributes); break; // a lot of elements without their own semantics -// case "riflspec": -// case "attackerio": -// case "top": -// case "bottom": -// case "source": -// case "sink": + // case "riflspec": + // case "attackerio": + // case "top": + // case "bottom": + // case "source": + // case "sink": case "dompair": // TODO -// case "domainhierarchy": + // case "domainhierarchy": case "flowpair": // TODO -// case "flowpolicy": + // case "flowpolicy": default: } } @@ -281,7 +281,7 @@ public void endElement(String uri, String localName, String qName) { } } -// TODO: actions on closing elements? + // TODO: actions on closing elements? private void startDomains() { domains = new LinkedHashSet<>(); @@ -300,4 +300,4 @@ private void startSources() { tmpMap = sources2categories; type = Type.SOURCE; } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLTransformer.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLTransformer.java index cbab760c62c..237260c22a2 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLTransformer.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/RIFLTransformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import de.uka.ilkd.key.util.Debug; @@ -24,14 +27,13 @@ import java.util.*; /** - * Facet class for interpreting RIFL specifications. The Requirements for - * Information Flow Language (RIFL) is a tool-independent specification language - * developed in the RS3 project. Method transform reads a RIFL file - * and Java sources and writes JML* information flow specifications to the - * original Java files. + * Facet class for interpreting RIFL specifications. The Requirements for Information Flow Language + * (RIFL) is a tool-independent specification language developed in the RS3 project. Method + * transform reads a RIFL file and Java sources and writes JML* information flow + * specifications to the original Java files. *

    - * changes (weigl, 2016-08-16): - * changed interfaces to File. This avoid some crud string operations on filenames + * changes (weigl, 2016-08-16): changed interfaces to File. This avoid some crud string + * operations on filenames * * @author bruns * @author weigl, 2016-08-17 @@ -68,12 +70,12 @@ public static void main(String[] args) { * Transforms plain Java files + RIFL specification to Java+JML* specifications. * * @param riflFilename path to a RIFL file - * @param javaSource path to Java sources (should be a directory) - * @param savePath custom save path + * @param javaSource path to Java sources (should be a directory) + * @param savePath custom save path * @param kexh */ - public static boolean transform(File riflFilename, File javaSource, - File savePath, KeYRecoderExcHandler kexh) { + public static boolean transform(File riflFilename, File javaSource, File savePath, + KeYRecoderExcHandler kexh) { if (riflFilename == null || javaSource == null || savePath == null || kexh == null) throw new IllegalArgumentException("A parameter is null"); @@ -82,7 +84,8 @@ public static boolean transform(File riflFilename, File javaSource, rt = new RIFLTransformer(); rt.doTransform(riflFilename, javaSource, savePath); return true; - } catch (final ParserConfigurationException | SAXException | ParserException | IOException e) { + } catch (final ParserConfigurationException | SAXException | ParserException + | IOException e) { kexh.reportException(e); } return false; @@ -103,7 +106,7 @@ public static boolean transform(File riflFilename, File javaSource) { * @return path to the transformed directory */ public static File getDefaultSavePath(File origSourcePath) { - //TODO weigl: Shouldn't we use the old directory, because of reference to other java files? + // TODO weigl: Shouldn't we use the old directory, because of reference to other java files? origSourcePath = getBaseDirPath(origSourcePath); return new File(origSourcePath.getParentFile(), origSourcePath.getName() + "_RIFL"); } @@ -137,21 +140,18 @@ private Map readJava(File root) throws IOException, Parse try (Reader fr = new BufferedReader(new FileReader(javaFile))) { cu = JPF.parseCompilationUnit(fr); - //crud relative + // crud relative File relative = relative(root, javaFile); javaCUs.put(cu, relative); // relative path - serviceConfiguration.getChangeHistory().updateModel(); // workaround to an issue in recoder + serviceConfiguration.getChangeHistory().updateModel(); // workaround to an issue in + // recoder } } return javaCUs; } private File relative(File root, File javaFile) { - return new File( - javaFile.getAbsolutePath().substring( - root.getAbsolutePath().length() - ) - ); + return new File(javaFile.getAbsolutePath().substring(root.getAbsolutePath().length())); } private SpecificationContainer readRIFL(File fileName) @@ -164,16 +164,14 @@ private SpecificationContainer readRIFL(File fileName) SAXParser saxParser = spf.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); - //xmlReader.setFeature("http://xml.org/sax/features/validation", true); + // xmlReader.setFeature("http://xml.org/sax/features/validation", true); xmlReader.setContentHandler(new RIFLHandler()); xmlReader.setErrorHandler(new RIFLHandler.ErrorHandler()); xmlReader.parse(fileName.toURI().toString()); return ((RIFLHandler) xmlReader.getContentHandler()).getSpecification(); } - public void doTransform(final File riflFilename, - final File source, - final File savePath) + public void doTransform(final File riflFilename, final File source, final File savePath) throws IOException, SAXException, ParserException, ParserConfigurationException { ensureTargetDirExists(savePath); final File javaRoot = getBaseDirPath(source); @@ -183,11 +181,11 @@ public void doTransform(final File riflFilename, Map javaCUs = readJava(javaRoot); int counter = 0; // step 2: inject specifications - //TODO rename the public class in the compilation unit and reuse the old java folder, + // TODO rename the public class in the compilation unit and reuse the old java folder, // for ensure interdepences to other files for (CompilationUnit cu : javaCUs.keySet()) { - final SpecificationInjector si = new SpecificationInjector(sc, - JPF.getServiceConfiguration().getSourceInfo()); + final SpecificationInjector si = + new SpecificationInjector(sc, JPF.getServiceConfiguration().getSourceInfo()); cu.accept(si); ClassDeclaration clazz = (ClassDeclaration) cu.getPrimaryTypeDeclaration(); @@ -203,10 +201,8 @@ public void doTransform(final File riflFilename, sb.deleteCharAt(sb.length() - 1); } - String poname = clazz.getFullName() + "[" + - clazz.getFullName() + "\\\\:\\\\:" + - mdecl.getName() + "(" + sb + ")" + "]" - + ".Non-interference contract.0"; + String poname = clazz.getFullName() + "[" + clazz.getFullName() + "\\\\:\\\\:" + + mdecl.getName() + "(" + sb + ")" + "]" + ".Non-interference contract.0"; File problemFileName = new File(javaRoot.getParent(), riflFilename.getName() + "_" + counter++ + ".key"); @@ -236,15 +232,13 @@ private void writeProblemFile(File problemFileName, String newJavaFolder, String Objects.requireNonNull(stream); try (BufferedReader br = new BufferedReader(new InputStreamReader(stream)); - Writer fw = new BufferedWriter(new FileWriter(problemFileName))) { + Writer fw = new BufferedWriter(new FileWriter(problemFileName))) { while ((tmp = br.readLine()) != null) { blueprint.append(tmp).append("\n"); } - fw.write( - blueprint.toString() - .replace("%%JAVA_SOURCE%%", newJavaFolder) - .replace("%%PO_NAME%%", poname)); + fw.write(blueprint.toString().replace("%%JAVA_SOURCE%%", newJavaFolder) + .replace("%%PO_NAME%%", poname)); } catch (IOException e) { e.printStackTrace(); } @@ -263,8 +257,7 @@ private void ensureTargetDirExists(File target) throws IOException { /** * Writes a single Java file. */ - private void writeJavaFile(File target, CompilationUnit cu) - throws IOException { + private void writeJavaFile(File target, CompilationUnit cu) throws IOException { try (var writer = new BufferedWriter(new FileWriter(target))) { LOGGER.debug("Trying to write file {}", target); final String source = cu.toSource(); @@ -281,4 +274,4 @@ private void writeJavaFile(File target, CompilationUnit cu) public List getProblemFiles() { return result; } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SecurityLattice.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SecurityLattice.java index 21a1602ceca..841aec5e570 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SecurityLattice.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SecurityLattice.java @@ -1,13 +1,16 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.util.Set; import java.util.HashSet; /** - * A lattice of security domains in RIFL. - * While the lattice is not necessarily complete, there are distinct top and bottom elements. - * Instances of this class are mutable; new domains can be added and put into a hierarchy. - * However, in any state the integrity is checked (top/bottom, acyclicity). + * A lattice of security domains in RIFL. While the lattice is not necessarily complete, there are + * distinct top and bottom elements. Instances of this class are mutable; new domains can be added + * and put into a hierarchy. However, in any state the integrity is checked (top/bottom, + * acyclicity). */ public class SecurityLattice { @@ -21,7 +24,7 @@ public class SecurityLattice { /** * Creates a two-element lattice. */ - public SecurityLattice () { + public SecurityLattice() { top = new SecurityDomain(TOP); bottom = new SecurityDomain(BOTTOM); top.putSubDomain(bottom); @@ -30,8 +33,9 @@ public SecurityLattice () { } /** - * Creates a new security domain and adds it to the lattice. - * The new domain is a direct subdomain of top and direct super-domain of bottom. + * Creates a new security domain and adds it to the lattice. The new domain is a direct + * subdomain of top and direct super-domain of bottom. + * * @param name name of the new domain (must not be "top" or "bottom") * @return the new domain */ @@ -46,29 +50,39 @@ SecurityDomain addDomain(String name) { } /** - * Refine the lattice by declaring a sub-domain relation between two domains. - * This checks whether the domains are already in the lattice and that the lattice is still acyclic. + * Refine the lattice by declaring a sub-domain relation between two domains. This checks + * whether the domains are already in the lattice and that the lattice is still acyclic. */ void putSubDomain(SecurityDomain sup, SecurityDomain sub) { - if (sup == top || sub == bottom) return; // safely ignore this - if ( ! hash.contains(sup)) - throw new IllegalArgumentException("Security domain "+sup+" must be added to the lattice first."); - if ( ! hash.contains(sub)) - throw new IllegalArgumentException("Security domain "+sub+" must be added to the lattice first."); + if (sup == top || sub == bottom) + return; // safely ignore this + if (!hash.contains(sup)) + throw new IllegalArgumentException( + "Security domain " + sup + " must be added to the lattice first."); + if (!hash.contains(sub)) + throw new IllegalArgumentException( + "Security domain " + sub + " must be added to the lattice first."); if (sup == sub || sub.isSuperDomain(sup)) throw new IllegalArgumentException("Security lattice must be acyclic."); sup.putSubDomain(sub); } - public SecurityDomain top() { return top; } - public SecurityDomain bottom() { return bottom; } - public boolean contains(SecurityDomain d) { return hash.contains(d); } + public SecurityDomain top() { + return top; + } + + public SecurityDomain bottom() { + return bottom; + } + + public boolean contains(SecurityDomain d) { + return hash.contains(d); + } /** - * The kind of elements to the security lattice. - * Keeps track of direct super- and sub-elements. - * Instances are mutable, but only by the lattice owning it. + * The kind of elements to the security lattice. Keeps track of direct super- and + * sub-elements. Instances are mutable, but only by the lattice owning it. */ public final class SecurityDomain { @@ -92,9 +106,11 @@ private void putSubDomain(SecurityDomain sub) { */ // TODO: do we really want strict super-elements?? public boolean isSuperDomain(SecurityDomain other) { - if (other == this) return false; - for (SecurityDomain sub: subDomains) { - if (sub == other || sub.isSuperDomain(other)) return true; + if (other == this) + return false; + for (SecurityDomain sub : subDomains) { + if (sub == other || sub.isSuperDomain(other)) + return true; } return false; } @@ -103,18 +119,24 @@ public boolean isSuperDomain(SecurityDomain other) { * Returns whether this domain is strictly lower in the hierarchy than the other one. */ public boolean isSubDomain(SecurityDomain other) { - if (other == this) return false; - for (SecurityDomain sup: superDomains) { - if (sup == other || sup.isSubDomain(other)) return true; + if (other == this) + return false; + for (SecurityDomain sup : superDomains) { + if (sup == other || sup.isSubDomain(other)) + return true; } return false; } @Override - public String toString () { return name; } + public String toString() { + return name; + } // ensures unique names @Override - public int hashCode () { return name.hashCode(); } + public int hashCode() { + return name.hashCode(); + } } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SimpleRIFLExceptionHandler.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SimpleRIFLExceptionHandler.java index 990e5ea6c92..f4f93b62ff6 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SimpleRIFLExceptionHandler.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SimpleRIFLExceptionHandler.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.util.ArrayList; @@ -24,7 +27,6 @@ public List getExceptions() { @Override public void reportException(Throwable e) { - LoggerFactory.getLogger(SimpleRIFLExceptionHandler.class) - .error("Error occured!", e); + LoggerFactory.getLogger(SimpleRIFLExceptionHandler.class).error("Error occured!", e); } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationContainer.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationContainer.java index 001d73ebbbc..8efb3e03e05 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationContainer.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationContainer.java @@ -1,4 +1,6 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.util.Set; @@ -8,20 +10,18 @@ import recoder.java.declaration.MethodDeclaration; /** - * Container for parsed RIFL specifications. Each query returns the assigned - * security level (domain) for an element represented as a String, - * or null if the element is not assigned a domain. - * RIFL specifications are not validated in any way. - * Categories in RIFL are currently treated opaque. - * + * Container for parsed RIFL specifications. Each query returns the assigned security level (domain) + * for an element represented as a String, or null if the element is not assigned a domain. RIFL + * specifications are not validated in any way. Categories in RIFL are currently treated opaque. + * * @author bruns - * + * */ public interface SpecificationContainer { /** - * Return the security level of the field, represented as a String. - * Convenience method for Recoder AST element. + * Return the security level of the field, represented as a String. Convenience method for + * Recoder AST element. */ public String field(FieldDeclaration fd, Type type); @@ -31,31 +31,31 @@ public interface SpecificationContainer { public String field(String inPackage, String inClass, String name, Type type); /** - * Return the security level of the method parameter, represented as a - * String. Convenience method for Recoder AST element. + * Return the security level of the method parameter, represented as a String. Convenience + * method for Recoder AST element. */ public String parameter(MethodDeclaration md, int index, Type type); /** * Return the security level of the method parameter, represented as a String. */ - public String parameter(String inPackage, String inClass, - String methodName, String[] paramTypes, int index, Type type); + public String parameter(String inPackage, String inClass, String methodName, + String[] paramTypes, int index, Type type); /** - * Return the security level of the method return, represented as a String. - * Convenience method for Recoder AST element. + * Return the security level of the method return, represented as a String. Convenience method + * for Recoder AST element. */ public String returnValue(MethodDeclaration md, Type type); /** * Return the security level of the method return, represented as a String. */ - public String returnValue(String inPackage, String inClass, - String methodName, String[] paramTypes, Type type); + public String returnValue(String inPackage, String inClass, String methodName, + String[] paramTypes, Type type); /** * Return the domains from which the given domain flows */ public Set flows(String domain); -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationEntity.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationEntity.java index 6540a4bd346..2d60b1d2a44 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationEntity.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationEntity.java @@ -1,18 +1,21 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import java.util.Arrays; /** - * Program elements which may be named as sources or sinks in RIFL/Java. - * Currently fields, method parameters, and method return values can be - * named both sources and sinks. - * + * Program elements which may be named as sources or sinks in RIFL/Java. Currently fields, method + * parameters, and method return values can be named both sources and sinks. + * * @author bruns */ public abstract class SpecificationEntity { - static enum Type { SOURCE, SINK } + static enum Type { + SOURCE, SINK + } public static final class Field extends SpecificationEntity { @@ -20,6 +23,7 @@ public static final class Field extends SpecificationEntity { /** * Creates a new specification element for a field. + * * @param n name of the field * @param p package name of the class where the field is declared * @param c name of the class where the field is declared @@ -33,14 +37,14 @@ public static final class Field extends SpecificationEntity { public boolean equals(Object o) { if (super.equals(o) && o instanceof Field) { return name.equals(((Field) o).name); - } else { return false; } + } else { + return false; + } } @Override public int hashCode() { - return 3977 * (inPackage + inClass).hashCode() - + 13 * type.hashCode() - + name.hashCode(); + return 3977 * (inPackage + inClass).hashCode() + 13 * type.hashCode() + name.hashCode(); } @Override @@ -57,6 +61,7 @@ public static final class Parameter extends SpecificationEntity { /** * Creates a new specification element for a method parameter. + * * @param pos the index within the sequence of parameters * @param m name of the method with parameter types in parentheses * @param p package name of the class where the method is declared @@ -72,6 +77,7 @@ public static final class Parameter extends SpecificationEntity { /** * Creates a new specification element for a method parameter. + * * @param pos the index within the sequence of parameters * @param m name of the method * @param pt names of the parameter types of the method @@ -97,10 +103,8 @@ public boolean equals(Object o) { @Override public int hashCode() { - return 3661 * (inPackage + inClass).hashCode() - + 37 * (methodName.hashCode() - + 13 * type.hashCode() - + Arrays.hashCode(paramTypes)) + return 3661 * (inPackage + inClass).hashCode() + 37 + * (methodName.hashCode() + 13 * type.hashCode() + Arrays.hashCode(paramTypes)) + position; } @@ -118,7 +122,7 @@ public String qualifiedName() { sb.append(p); sb.append(','); } - sb.deleteCharAt(sb.length()-1); + sb.deleteCharAt(sb.length() - 1); sb.append(')'); return sb.toString(); } @@ -131,6 +135,7 @@ public static final class ReturnValue extends SpecificationEntity { /** * Creates a new specification element for a method return. + * * @param m name of the method with parameter types in parentheses * @param pt names of the parameter types of the method * @param p package name of the class where the method is declared @@ -145,6 +150,7 @@ public static final class ReturnValue extends SpecificationEntity { /** * Creates a new specification element for a method return. + * * @param m name of the method * @param pt names of the parameter types of the method * @param p package name of the class where the method is declared @@ -161,15 +167,15 @@ public boolean equals(Object o) { if (super.equals(o) && o instanceof ReturnValue) { return (methodName.equals(((ReturnValue) o).methodName) && Arrays.equals(paramTypes, ((ReturnValue) o).paramTypes)); - } else { return false; } + } else { + return false; + } } @Override public int hashCode() { - return 3721 * (inPackage + inClass).hashCode() - + 79 * methodName.hashCode() - + 13 * type.hashCode() - + Arrays.hashCode(paramTypes); + return 3721 * (inPackage + inClass).hashCode() + 79 * methodName.hashCode() + + 13 * type.hashCode() + Arrays.hashCode(paramTypes); } @Override @@ -182,7 +188,7 @@ public String qualifiedName() { sb.append(p); sb.append(','); } - sb.deleteCharAt(sb.length()-1); + sb.deleteCharAt(sb.length() - 1); sb.append(')'); return sb.toString(); } @@ -206,7 +212,9 @@ public boolean equals(Object o) { return (inPackage.equals(((SpecificationEntity) o).inPackage) && inClass.equals(((SpecificationEntity) o).inClass) && (type == ((SpecificationEntity) o).type)); - } else { return false; } + } else { + return false; + } } // ////////////////////////////////////////////////// @@ -222,4 +230,4 @@ public boolean equals(Object o) { public String toString() { return qualifiedName(); } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationInjector.java b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationInjector.java index 25f4ade1748..8eb55919b9b 100644 --- a/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationInjector.java +++ b/key/key.core/rifl/src/main/java/de/uka/ilkd/key/util/rifl/SpecificationInjector.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.util.rifl; import de.uka.ilkd.key.util.rifl.SpecificationEntity.Type; @@ -13,9 +16,9 @@ import java.util.stream.Collectors; /** - * Writes JML* translation of RIFL specifications to Java files. This is a - * manipulating Recoder source visitor. Implementation warning: manipulating the - * AST before traversing it may have unexpected results. + * Writes JML* translation of RIFL specifications to Java files. This is a manipulating Recoder + * source visitor. Implementation warning: manipulating the AST before traversing it may have + * unexpected results. * * @author bruns */ @@ -26,9 +29,8 @@ public class SpecificationInjector extends SourceVisitor { LINE_BREAK + "// JML* comment created by KeY RIFL Transformer." + LINE_BREAK; /** - * Produces JML* respects clauses. Clauses are internally labeled with keys - * (resulting from security domains in RIFL), which are discarded in the - * final output. + * Produces JML* respects clauses. Clauses are internally labeled with keys (resulting from + * security domains in RIFL), which are discarded in the final output. * * @author bruns */ @@ -45,8 +47,7 @@ private static class JMLFactory { private static final String JML_START = LINE_BREAK + DEFAULT_INDENTATION + "/*@ "; private final String indentation; - private final Map>> respects = - new HashMap<>(); + private final Map>> respects = new HashMap<>(); private SpecificationContainer sc; JMLFactory(SpecificationContainer sc) { @@ -95,8 +96,7 @@ String getRespects(Set oneRespect) { } String getRespects(Set> oneRespect, final Type t) { - var r = oneRespect.stream().filter(p -> p.getValue() == t) - .map(Entry::getKey) + var r = oneRespect.stream().filter(p -> p.getValue() == t).map(Entry::getKey) .collect(Collectors.joining(", ")); if (r.isEmpty()) { return " \\nothing"; @@ -204,7 +204,7 @@ private void accessChildren(JavaNonTerminalProgramElement pe) { } private void addComment(JavaProgramElement se, String comment) { - //remember which methods were specified and generate po files only for them + // remember which methods were specified and generate po files only for them if (se instanceof MethodDeclaration) { specifiedMethodDeclarations.add((MethodDeclaration) se); } @@ -289,10 +289,10 @@ public void visitMethodDeclaration(MethodDeclaration md) { factory.addToDetermines(fName, Type.SINK, fieldSnk); } } - //only add comment for methods for which we generated a specification + // only add comment for methods for which we generated a specification String comment = factory.getSpecification(); if (comment != null) { addComment(md, factory.getSpecification()); } } -} \ No newline at end of file +} diff --git a/key/key.core/rifl/src/main/resources/de.uka.ilkd.key.util/rifl/blueprint_rifl.key b/key/key.core/rifl/src/main/resources/de.uka.ilkd.key.util/rifl/blueprint_rifl.key index 8a037c8ce28..318720c42ee 100644 --- a/key/key.core/rifl/src/main/resources/de.uka.ilkd.key.util/rifl/blueprint_rifl.key +++ b/key/key.core/rifl/src/main/resources/de.uka.ilkd.key.util/rifl/blueprint_rifl.key @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ \profile "Java Profile"; \settings { diff --git a/key/key.core/src/main/antlr4/JmlLexer.g4 b/key/key.core/src/main/antlr4/JmlLexer.g4 index b2759275282..11fedfdadb2 100644 --- a/key/key.core/src/main/antlr4/JmlLexer.g4 +++ b/key/key.core/src/main/antlr4/JmlLexer.g4 @@ -1,4 +1,6 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ lexer grammar JmlLexer; @header { diff --git a/key/key.core/src/main/antlr4/JmlParser.g4 b/key/key.core/src/main/antlr4/JmlParser.g4 index a9d584c5830..92a6f6779ed 100644 --- a/key/key.core/src/main/antlr4/JmlParser.g4 +++ b/key/key.core/src/main/antlr4/JmlParser.g4 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ parser grammar JmlParser; options { tokenVocab=JmlLexer; } diff --git a/key/key.core/src/main/antlr4/KeYLexer.g4 b/key/key.core/src/main/antlr4/KeYLexer.g4 index 5560dfbb284..0415233c5ca 100644 --- a/key/key.core/src/main/antlr4/KeYLexer.g4 +++ b/key/key.core/src/main/antlr4/KeYLexer.g4 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ lexer grammar KeYLexer; @header { diff --git a/key/key.core/src/main/antlr4/KeYParser.g4 b/key/key.core/src/main/antlr4/KeYParser.g4 index 17b5d0a9303..a26163c307a 100644 --- a/key/key.core/src/main/antlr4/KeYParser.g4 +++ b/key/key.core/src/main/antlr4/KeYParser.g4 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ parser grammar KeYParser; @header { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/KeYApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/KeYApi.java index a30323d8594..ca5d59c8810 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/KeYApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/KeYApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.control.KeYEnvironment; @@ -10,8 +13,8 @@ /** * The Entry Point. *

    - * This facility is the entry point to the different KeY apis. - * Currently it support the bootstrapping of the {@link KeYEnvironment} and the loading of proofs. + * This facility is the entry point to the different KeY apis. Currently it support the + * bootstrapping of the {@link KeYEnvironment} and the loading of proofs. *

    * Created at 6.4.17 * @@ -26,8 +29,7 @@ public abstract class KeYApi { /** * Create a new KeY API and create the sub APIs */ - private KeYApi() { - } + private KeYApi() {} /** * @@ -57,8 +59,7 @@ public static ProofMacroApi getMacroApi() { * @return * @throws ProblemLoaderException */ - public static ProofManagementApi loadFromKeyFile(File keyFile) - throws ProblemLoaderException { + public static ProofManagementApi loadFromKeyFile(File keyFile) throws ProblemLoaderException { return new ProofManagementApi(KeYEnvironment.load(keyFile)); } @@ -70,11 +71,10 @@ public static ProofManagementApi loadFromKeyFile(File keyFile) * @return * @throws ProblemLoaderException */ - public static ProofManagementApi loadProof(File location, - List classPath, File bootClassPath, List includes) - throws ProblemLoaderException { - return new ProofManagementApi(KeYEnvironment - .load(location, classPath, bootClassPath, includes)); + public static ProofManagementApi loadProof(File location, List classPath, + File bootClassPath, List includes) throws ProblemLoaderException { + return new ProofManagementApi( + KeYEnvironment.load(location, classPath, bootClassPath, includes)); } /** @@ -82,20 +82,20 @@ public static ProofManagementApi loadProof(File location, * @return * @throws ProblemLoaderException */ - public static ProofManagementApi loadProof(File javaSourceCode) - throws ProblemLoaderException { + public static ProofManagementApi loadProof(File javaSourceCode) throws ProblemLoaderException { return loadProof(javaSourceCode, null, null, null); } /** - * Load a proof file, creates a KeY environment that can be accessed with other methods from this facade + * Load a proof file, creates a KeY environment that can be accessed with other methods from + * this facade * - * @param file Path to the source code folder/file or to a *.proof file - * @param classPaths Optionally: Additional specifications for API classes + * @param file Path to the source code folder/file or to a *.proof file + * @param classPaths Optionally: Additional specifications for API classes * @param bootClassPath Optionally: Different default specifications for Java API - * @param includes Optionally: Additional includes to consider + * @param includes Optionally: Additional includes to consider */ - public abstract void loadProofFile(File file, List classPaths, - File bootClassPath, List includes); + public abstract void loadProofFile(File file, List classPaths, File bootClassPath, + List includes); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/Matcher.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/Matcher.java index fb7f7710b9a..58cea9fd4ce 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/Matcher.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/Matcher.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.java.Services; @@ -37,41 +40,43 @@ public Matcher(ProofApi api) { } /** - * Matches a sequent against a sequent pattern (a schematic sequent) returns a list of Nodes containing matching - * results from where the information about instantiated schema variables can be extracted. If no match was - * possible the list is exmpt. + * Matches a sequent against a sequent pattern (a schematic sequent) returns a list of Nodes + * containing matching results from where the information about instantiated schema variables + * can be extracted. If no match was possible the list is exmpt. * - * @param pattern a string representation of the pattern sequent against which the current - * sequent should be matched - * @param currentSeq current concrete sequent - * @param assignments variables appearing in the pattern as schemavariables with their corresponding type in KeY + * @param pattern a string representation of the pattern sequent against which the current + * sequent should be matched + * @param currentSeq current concrete sequent + * @param assignments variables appearing in the pattern as schemavariables with their + * corresponding type in KeY * @return List of VariableAssignments (possibly empty if no match was found) */ - //List of VarAssignment - public List matchPattern(String pattern, Sequent currentSeq, VariableAssignments assignments) { - //copy services in order to not accidently set assignments and namespace for environment + // List of VarAssignment + public List matchPattern(String pattern, Sequent currentSeq, + VariableAssignments assignments) { + // copy services in order to not accidently set assignments and namespace for environment Services copyServices = api.getEnv().getServices().copy(false); - //Aufbau der Deklarationen fuer den NameSpace + // Aufbau der Deklarationen fuer den NameSpace buildNameSpace(assignments, copyServices); - //Zusammenbau des Pseudotaclets - //Parsen des Taclets + // Zusammenbau des Pseudotaclets + // Parsen des Taclets String patternString = "matchPattern{\\assumes(" + pattern + ") \\find (==>) \\add (==>)}"; Taclet t = parseTaclet(patternString, copyServices); - //Build Matcher for Matchpattern + // Build Matcher for Matchpattern LegacyTacletMatcher ltm = new LegacyTacletMatcher(t); - //patternSequent should not be null, as we have created it + // patternSequent should not be null, as we have created it assert t.ifSequent() != null; Sequent patternSeq = t.ifSequent(); int asize = patternSeq.antecedent().size(); int size = asize + patternSeq.succedent().size(); - //Iterator durch die Pattern-Sequent + // Iterator durch die Pattern-Sequent List finalCandidates = new ArrayList<>(100); if (size > 0) { - //Iteratoren durch die Sequent + // Iteratoren durch die Sequent ImmutableList antecCand = IfFormulaInstSeq.createList(currentSeq, true, copyServices); ImmutableList succCand = @@ -84,7 +89,7 @@ public List matchPattern(String pattern, Sequent currentSeq Queue queue = new LinkedList<>(); - //init + // init queue.add(new SearchNode(patternArray, asize, antecCand, succCand)); @@ -93,8 +98,8 @@ public List matchPattern(String pattern, Sequent currentSeq boolean inAntecedent = node.isAntecedent(); LOGGER.debug(inAntecedent ? "In Antec: " : "In Succ"); - IfMatchResult ma = ltm.matchIf((inAntecedent ? - antecCand : succCand), node.getPatternTerm(), node.mc, copyServices); + IfMatchResult ma = ltm.matchIf((inAntecedent ? antecCand : succCand), + node.getPatternTerm(), node.mc, copyServices); if (!ma.getMatchConditions().isEmpty()) { ImmutableList testma = ma.getMatchConditions(); @@ -155,7 +160,8 @@ private void buildNameSpace(VariableAssignments assignments, Services services) /** * Builds a string that is used to create a new schemavariable declaration for the matchpattern * - * @param assignments varaiables appearing as schema varaibels in the match pattern and their types (in KeY) + * @param assignments varaiables appearing as schema varaibels in the match pattern and their + * types (in KeY) * @return a String representing the declaration part of a taclet for teh matchpattern */ private String buildDecls(VariableAssignments assignments) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProjectedNode.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProjectedNode.java index 1b2f14860fd..faba10888bd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProjectedNode.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProjectedNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.logic.Sequent; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofApi.java index 99e3c7ecbe7..91a0178ce22 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.control.KeYEnvironment; @@ -37,7 +40,7 @@ public ScriptApi getScriptApi() { * Save current Proof-> ProofApi */ public void saveProof() throws IOException { - //TODO + // TODO } public KeYEnvironment getEnv() { @@ -50,7 +53,8 @@ public Proof getProof() { public List getOpenGoals() { ImmutableList goals = proof.openGoals(); - return goals.stream().map(g -> new ProjectedNode(g.node(), null)).collect(Collectors.toList()); + return goals.stream().map(g -> new ProjectedNode(g.node(), null)) + .collect(Collectors.toList()); } public ProjectedNode getFirstOpenGoal() { @@ -61,7 +65,8 @@ public Set getRules() { Set s = new TreeSet<>(); Goal goal = proof.getSubtreeGoals(proof.root()).head(); - for (final BuiltInRule br : goal.ruleAppIndex().builtInRuleAppIndex().builtInRuleIndex().rules()) { + for (final BuiltInRule br : goal.ruleAppIndex().builtInRuleAppIndex().builtInRuleIndex() + .rules()) { s.add(br.displayName()); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofMacroApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofMacroApi.java index cce6743f5ce..1c0723eb6f8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofMacroApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofMacroApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.macros.ProofMacro; @@ -40,8 +43,8 @@ public Collection getMacros() { } /** - * Searches for the proof script command in the registered commands by its name. - * If no command is found, null is returned. + * Searches for the proof script command in the registered commands by its name. If no command + * is found, null is returned. * * @param name the non-null name of the search proof script command * @return the proof script command or null diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofManagementApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofManagementApi.java index dd52ed21c74..0a20189f0de 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofManagementApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofManagementApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.control.KeYEnvironment; @@ -16,8 +19,8 @@ import java.util.Set; /** - * This class serves as a facade to all functionalities that are needed for - * proof management, i.e., loading proof files, retrieving the proof obligations + * This class serves as a facade to all functionalities that are needed for proof management, i.e., + * loading proof files, retrieving the proof obligations * * @author Sarah Grebing. */ @@ -37,8 +40,8 @@ public Services getServices() { /** * Retrieve a list of all available contracts * - * @return {@link List}; can be null if no file was loaded before - * (we should throw an exception here) + * @return {@link List}; can be null if no file was loaded before (we should throw an + * exception here) */ public List getProofContracts() { if (proofContracts.isEmpty()) @@ -47,20 +50,18 @@ public List getProofContracts() { } /** - * constructs the possible proof contracts from the - * java info in the environment. + * constructs the possible proof contracts from the java info in the environment. */ private void buildContracts() { proofContracts.clear(); Set kjts = currentEnv.getJavaInfo().getAllKeYJavaTypes(); for (KeYJavaType type : kjts) { if (!KeYTypeUtil.isLibraryClass(type)) { - ImmutableSet targets = currentEnv - .getSpecificationRepository().getContractTargets(type); + ImmutableSet targets = + currentEnv.getSpecificationRepository().getContractTargets(type); for (IObserverFunction target : targets) { - ImmutableSet contracts = currentEnv - .getSpecificationRepository() - .getContracts(type, target); + ImmutableSet contracts = + currentEnv.getSpecificationRepository().getContracts(type, target); for (Contract contract : contracts) { proofContracts.add(contract); } @@ -74,8 +75,7 @@ private void buildContracts() { * @return * @throws ProofInputException */ - public ProofApi startProof(ProofOblInput contract) - throws ProofInputException { + public ProofApi startProof(ProofOblInput contract) throws ProofInputException { return new ProofApi(currentEnv.createProof(contract), currentEnv); } @@ -85,8 +85,7 @@ public ProofApi startProof(ProofOblInput contract) * @throws ProofInputException */ public ProofApi startProof(Contract contract) throws ProofInputException { - return startProof( - contract.createProofObl(currentEnv.getInitConfig(), contract)); + return startProof(contract.createProofObl(currentEnv.getInitConfig(), contract)); } public ProofApi getLoadedProof() { @@ -94,8 +93,8 @@ public ProofApi getLoadedProof() { } /** - * Constructs a set containing all names of a taclets that are registered - * in the current environment. + * Constructs a set containing all names of a taclets that are registered in the current + * environment. *

    * The result is cached to speed up further calls.s * @@ -107,32 +106,22 @@ public Set getRuleNames() { currentEnv.getInitConfig().activatedTaclets() .forEach(taclet -> ruleNames.add(taclet.displayName())); - currentEnv.getInitConfig().builtInRules() - .forEach(t -> ruleNames.add(t.displayName())); + currentEnv.getInitConfig().builtInRules().forEach(t -> ruleNames.add(t.displayName())); } return ruleNames; } /* - public KeYApi.CommandType getCommandType(String identifier) { - if (KeYApi.getMacroApi().getMacro(identifier) != null) { - return KeYApi.CommandType.MACRO; - } - - if (KeYApi.getScriptCommandApi().getScriptCommands(identifier) - != null) { - return KeYApi.CommandType.SCRIPT; - } - - if (getRuleNames().contains(identifier)) { - return KeYApi.CommandType.RULE; - } - - return KeYApi.CommandType.UNKNOWN; - } - - enum CommandType { - SCRIPT, RULE, MACRO, UNKNOWN; - } - */ + * public KeYApi.CommandType getCommandType(String identifier) { if + * (KeYApi.getMacroApi().getMacro(identifier) != null) { return KeYApi.CommandType.MACRO; } + * + * if (KeYApi.getScriptCommandApi().getScriptCommands(identifier) != null) { return + * KeYApi.CommandType.SCRIPT; } + * + * if (getRuleNames().contains(identifier)) { return KeYApi.CommandType.RULE; } + * + * return KeYApi.CommandType.UNKNOWN; } + * + * enum CommandType { SCRIPT, RULE, MACRO, UNKNOWN; } + */ } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandApi.java index 1ebaf282fa9..fa31ce83a2b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.macros.scripts.ProofScriptCommand; @@ -37,8 +40,8 @@ public Collection getScriptCommands() { } /** - * Searches for the proof script command in the registered commands by its name. - * If no command is found, null is returned. + * Searches for the proof script command in the registered commands by its name. If no command + * is found, null is returned. * * @param name the non-null name of the search proof script command * @return the proof script command or null diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandCall.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandCall.java index fd4854c7439..8206d3c64d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandCall.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ProofScriptCommandCall.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.macros.scripts.ProofScriptCommand; @@ -15,4 +18,3 @@ public ProofScriptCommandCall(ProofScriptCommand command, T arguments) { this.command = command; } } - \ No newline at end of file diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptApi.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptApi.java index d6877098240..85a5127b9b2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptApi.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptApi.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import java.util.LinkedList; @@ -34,16 +37,19 @@ public ScriptApi(ProofApi proofApi) { } /** - * Matches a sequent against a sequent pattern (a schematic sequent) returns a list of Nodes containing matching - * results from where the information about instantiated schema variables can be extracted. If no match was possible the list is exmpt. + * Matches a sequent against a sequent pattern (a schematic sequent) returns a list of Nodes + * containing matching results from where the information about instantiated schema variables + * can be extracted. If no match was possible the list is exmpt. * - * @param pattern a string representation of the pattern sequent against which the current sequent should be matched - * @param currentSeq current concrete sequent - * @param assignments variables appearing in the pattern as schemavariables with their corresponding type in KeY - * @return List of VariableAssignments (possibly empty if no match was found) + * @param pattern a string representation of the pattern sequent against which the current + * sequent should be matched + * @param currentSeq current concrete sequent + * @param assignments variables appearing in the pattern as schemavariables with their + * corresponding type in KeY + * @return List of VariableAssignments (possibly empty if no match was found) */ - public List matchPattern(String pattern, - Sequent currentSeq, VariableAssignments assignments) { + public List matchPattern(String pattern, Sequent currentSeq, + VariableAssignments assignments) { return matcher.matchPattern(pattern, currentSeq, assignments); } @@ -51,22 +57,19 @@ public List matchPattern(String pattern, * Execute ScriptCommand onto goal node * * @param command to be applied with parameters set - * @return List of new proof goals (possibly empty) - * Should throw an Exception if command not applicable? + * @return List of new proof goals (possibly empty) Should throw an Exception if command not + * applicable? */ - public ScriptResults executeScriptCommand( - ProofScriptCommandCall call, ProjectedNode onNode) - throws ScriptException, InterruptedException { - //TODO VariableAssignments should be in instantiateCommand + public ScriptResults executeScriptCommand(ProofScriptCommandCall call, + ProjectedNode onNode) throws ScriptException, InterruptedException { + // TODO VariableAssignments should be in instantiateCommand state.setGoal(onNode.getProofNode()); - call.command - .execute((AbstractUserInterfaceControl) api.getEnv().getUi(), - call.parameter, state); + call.command.execute((AbstractUserInterfaceControl) api.getEnv().getUi(), call.parameter, + state); - ImmutableList goals = api.getProof() - .getSubtreeGoals(onNode.getProofNode()); - //TODO filter for open goals if necessary + ImmutableList goals = api.getProof().getSubtreeGoals(onNode.getProofNode()); + // TODO filter for open goals if necessary ScriptResults sr = new ScriptResults(); goals.forEach(g -> sr.add(ScriptResult.create(g.node(), onNode, call))); @@ -76,15 +79,14 @@ public ScriptResults executeScriptCommand( /** * Evaluate the arguments passed to a command + * * @param arguments * @param * @return */ - public ProofScriptCommandCall instantiateCommand( - ProofScriptCommand command, Map arguments) - throws Exception { - return new ProofScriptCommandCall<>(command, - command.evaluateArguments(state, arguments)); + public ProofScriptCommandCall instantiateCommand(ProofScriptCommand command, + Map arguments) throws Exception { + return new ProofScriptCommandCall<>(command, command.evaluateArguments(state, arguments)); } @@ -95,32 +97,29 @@ public ProofScriptCommandCall instantiateCommand( * @return * @throws Exception either for Syntax or Type error */ - public Term toTerm(String term, VariableAssignments assignments) - throws Exception { - //TODO + public Term toTerm(String term, VariableAssignments assignments) throws Exception { + // TODO return null; } /** - * ~> Beweisbaum -> Shallow Copy - * hier implementieren + * ~> Beweisbaum -> Shallow Copy hier implementieren * * @param root * @param end * @return */ - public ProjectedNode getIntermediateTree(ScriptResults root, - ScriptResults end) { + public ProjectedNode getIntermediateTree(ScriptResults root, ScriptResults end) { /* - Baum suche, startet bei allen Nodes von root. - - Endet sobald ein Node von end erreicht ist. + * Baum suche, startet bei allen Nodes von root. + * + * Endet sobald ein Node von end erreicht ist. */ ProjectedNode pseudoRoot = ProjectedNode.pseudoRoot(); Queue queue = new LinkedList<>(); root.forEach(r -> queue.add(r.getProjectedNode().getProofNode())); - while(!queue.isEmpty()){ + while (!queue.isEmpty()) { } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResult.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResult.java index 6e333ec8ae9..4f29ff22968 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResult.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResult.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.java.PositionInfo; @@ -7,9 +10,8 @@ import java.util.Set; /** - * Object that represents one result goal of a script command - * It holds a reference to its parent node and to the list of variables and their values for this result - * Created by S. Grebing + * Object that represents one result goal of a script command It holds a reference to its parent + * node and to the list of variables and their values for this result Created by S. Grebing */ public class ScriptResult { @@ -31,7 +33,7 @@ public class ScriptResult { /** * The reference to the variableassingments for this result */ - //private VariableAssignments assignments; + // private VariableAssignments assignments; /** * The list of labels for the result @@ -43,16 +45,17 @@ public class ScriptResult { */ private List linenumbers; - //getLineNumbers hier + // getLineNumbers hier /** * */ ScriptResult() { - //nulls + // nulls } - public static ScriptResult create(Node node, ProjectedNode onNode, ProofScriptCommandCall call) { + public static ScriptResult create(Node node, ProjectedNode onNode, + ProofScriptCommandCall call) { ScriptResult sr = new ScriptResult(); sr.parentNode = onNode; sr.newNode = new ProjectedNode(node, onNode); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResults.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResults.java index a49cdfadd63..4f11fec336e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResults.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/ScriptResults.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import java.util.*; @@ -13,132 +16,163 @@ public class ScriptResults implements List { private List delegated = new ArrayList<>(); - @Override public int size() { + @Override + public int size() { return delegated.size(); } - @Override public boolean isEmpty() { + @Override + public boolean isEmpty() { return delegated.isEmpty(); } - @Override public boolean contains(Object o) { + @Override + public boolean contains(Object o) { return delegated.contains(o); } - @Override public Iterator iterator() { + @Override + public Iterator iterator() { return delegated.iterator(); } - @Override public Object[] toArray() { + @Override + public Object[] toArray() { return delegated.toArray(); } - @Override public T[] toArray(T[] a) { + @Override + public T[] toArray(T[] a) { return delegated.toArray(a); } - @Override public boolean add(ScriptResult scriptResult) { + @Override + public boolean add(ScriptResult scriptResult) { return delegated.add(scriptResult); } - @Override public boolean remove(Object o) { + @Override + public boolean remove(Object o) { return delegated.remove(o); } - @Override public boolean containsAll(Collection c) { + @Override + public boolean containsAll(Collection c) { return delegated.containsAll(c); } - @Override public boolean addAll(Collection c) { + @Override + public boolean addAll(Collection c) { return delegated.addAll(c); } - @Override public boolean addAll(int index, - Collection c) { + @Override + public boolean addAll(int index, Collection c) { return delegated.addAll(index, c); } - @Override public boolean removeAll(Collection c) { + @Override + public boolean removeAll(Collection c) { return delegated.removeAll(c); } - @Override public boolean retainAll(Collection c) { + @Override + public boolean retainAll(Collection c) { return delegated.retainAll(c); } - @Override public void replaceAll(UnaryOperator operator) { + @Override + public void replaceAll(UnaryOperator operator) { delegated.replaceAll(operator); } - @Override public void sort(Comparator c) { + @Override + public void sort(Comparator c) { delegated.sort(c); } - @Override public void clear() { + @Override + public void clear() { delegated.clear(); } - @Override public boolean equals(Object o) { + @Override + public boolean equals(Object o) { return delegated.equals(o); } - @Override public int hashCode() { + @Override + public int hashCode() { return delegated.hashCode(); } - @Override public ScriptResult get(int index) { + @Override + public ScriptResult get(int index) { return delegated.get(index); } - @Override public ScriptResult set(int index, ScriptResult element) { + @Override + public ScriptResult set(int index, ScriptResult element) { return delegated.set(index, element); } - @Override public void add(int index, ScriptResult element) { + @Override + public void add(int index, ScriptResult element) { delegated.add(index, element); } - @Override public ScriptResult remove(int index) { + @Override + public ScriptResult remove(int index) { return delegated.remove(index); } - @Override public int indexOf(Object o) { + @Override + public int indexOf(Object o) { return delegated.indexOf(o); } - @Override public int lastIndexOf(Object o) { + @Override + public int lastIndexOf(Object o) { return delegated.lastIndexOf(o); } - @Override public ListIterator listIterator() { + @Override + public ListIterator listIterator() { return delegated.listIterator(); } - @Override public ListIterator listIterator(int index) { + @Override + public ListIterator listIterator(int index) { return delegated.listIterator(index); } - @Override public List subList(int fromIndex, int toIndex) { + @Override + public List subList(int fromIndex, int toIndex) { return delegated.subList(fromIndex, toIndex); } - @Override public Spliterator spliterator() { + @Override + public Spliterator spliterator() { return delegated.spliterator(); } - @Override public boolean removeIf(Predicate filter) { + @Override + public boolean removeIf(Predicate filter) { return delegated.removeIf(filter); } - @Override public Stream stream() { + @Override + public Stream stream() { return delegated.stream(); } - @Override public Stream parallelStream() { + @Override + public Stream parallelStream() { return delegated.parallelStream(); } - @Override public void forEach(Consumer action) { + @Override + public void forEach(Consumer action) { delegated.forEach(action); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/SearchNode.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/SearchNode.java index 3c6e6316ff6..d6c09187d12 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/SearchNode.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/SearchNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; import de.uka.ilkd.key.logic.SequentFormula; @@ -19,7 +22,9 @@ public class SearchNode { - public SearchNode(SequentFormula[] pattern, int succAntPos, ImmutableList antec, ImmutableList succ) { + public SearchNode(SequentFormula[] pattern, int succAntPos, + ImmutableList antec, + ImmutableList succ) { this.pattern = pattern; this.succAntPos = succAntPos; this.antec = antec; @@ -31,7 +36,7 @@ public SearchNode(SearchNode parent, MatchConditions cond) { this.pattern = parent.pattern; this.succAntPos = parent.succAntPos; int parentPos = parent.pos; - this.pos = parentPos+1; + this.pos = parentPos + 1; antec = parent.antec; succ = parent.succ; mc = cond; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/VariableAssignments.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/VariableAssignments.java index b6665a744f4..e9d27890251 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/VariableAssignments.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/VariableAssignments.java @@ -1,25 +1,22 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.api; + import java.util.HashMap; import java.util.Map; /** - * Class to represent current Variable assigments. - * Created by S.Grebing + * Class to represent current Variable assigments. Created by S.Grebing */ public class VariableAssignments { public enum VarType { - INT("\\term int"), - BOOL("\\term bool"), - ANY("\\term any"), - INT_ARRAY("\\term int[]"), - OBJECT("\\term Object"), - HEAP("\\term Heap"), - FIELD("\\term Field"), - LOCSET("\\term LocSet"), - FORMULA("\\formula"), - SEQ("\\term Seq"); + INT("\\term int"), BOOL("\\term bool"), ANY("\\term any"), INT_ARRAY( + "\\term int[]"), OBJECT("\\term Object"), HEAP("\\term Heap"), FIELD( + "\\term Field"), LOCSET( + "\\term LocSet"), FORMULA("\\formula"), SEQ("\\term Seq"); private final String declPrefix; @@ -49,9 +46,10 @@ public String getKeYDeclarationPrefix() { /** * Create new, empty variable assignment, to add variables + * * @param parent */ - public VariableAssignments(VariableAssignments parentAssignments){ + public VariableAssignments(VariableAssignments parentAssignments) { this.currentAssignments = new HashMap<>(); this.typeMap = new HashMap<>(); this.parent = parentAssignments; @@ -69,30 +67,31 @@ public VariableAssignments() { /** - * Get the value of a stored variable name - * TODO Exception spezifischer + * Get the value of a stored variable name TODO Exception spezifischer + * * @param varName * @return Value of variable */ public Object getVarValue(String varName) throws Exception { - if(currentAssignments.containsKey(varName)){ + if (currentAssignments.containsKey(varName)) { return currentAssignments.get(varName); - }else{ - if(parent !=null) { + } else { + if (parent != null) { return parent.getVarValue(varName); - }else{ - throw new Exception("Variable "+varName+" could not be found"); + } else { + throw new Exception("Variable " + varName + " could not be found"); } } } /** * Add a variable assignment with type and value + * * @param varName * @param value * @param type */ - public void addAssignmentWithType(String varName, Object value, VarType type){ + public void addAssignmentWithType(String varName, Object value, VarType type) { typeMap.put(varName, type); currentAssignments.put(varName, value); @@ -100,56 +99,57 @@ public void addAssignmentWithType(String varName, Object value, VarType type){ /** * Add a variable assignment without type + * * @param varName * @param value */ public void addAssignment(String varName, Object value) throws Exception { - if(typeMap.containsKey(varName)) { + if (typeMap.containsKey(varName)) { currentAssignments.put(varName, value); - } else{ - throw new Exception("Variable "+ varName +"must be declared first"); + } else { + throw new Exception("Variable " + varName + "must be declared first"); } } /** - * TODO better exception - * Add a new type declaration + * TODO better exception Add a new type declaration + * * @param varName * @param type */ public void addType(String varName, VarType type) throws Exception { - if(typeMap.containsKey(varName)){ - if(typeMap.get(varName) != type){ - throw new Exception("Variable "+varName+ "was already declared with type " + typeMap.get(varName).toString()); + if (typeMap.containsKey(varName)) { + if (typeMap.get(varName) != type) { + throw new Exception("Variable " + varName + "was already declared with type " + + typeMap.get(varName).toString()); } - }else{ + } else { typeMap.put(varName, type); } } /** * Returns the map of ID -> Type mappings + * * @return */ - public Map getTypeMap(){ + public Map getTypeMap() { return this.typeMap; } -/* public Object getValue(String name) { - return null; - } - - public Type getType() { - return null; - } - - public void setType(Type type) { - - } - - public void setValue(String name) { - - }*/ + /* + * public Object getValue(String name) { return null; } + * + * public Type getType() { return null; } + * + * public void setType(Type type) { + * + * } + * + * public void setValue(String name) { + * + * } + */ } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/api/package-info.java b/key/key.core/src/main/java/de/uka/ilkd/key/api/package-info.java index a51da22f0ec..402b65aa83c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/api/package-info.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/api/package-info.java @@ -6,4 +6,4 @@ * @version 1 (21.04.17) * @see de.uka.ilkd.key.api.KeYApi */ -package de.uka.ilkd.key.api; \ No newline at end of file +package de.uka.ilkd.key.api; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainElement.java index 817aec79a4d..49345d75891 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction; import de.uka.ilkd.key.java.Services; @@ -5,47 +8,41 @@ import de.uka.ilkd.key.logic.Term; /** - * An element of an abstract domain. Elements are described by defining axioms; - * the main function of this class is to create such defining axioms for given - * terms, usually Skolem constants or program variables. - * + * An element of an abstract domain. Elements are described by defining axioms; the main function of + * this class is to create such defining axioms for given terms, usually Skolem constants or program + * variables. + * * @author Dominic Scheurer */ public abstract class AbstractDomainElement implements Named { /** *

    - * Return the defining axiom, instantiated for a given Term (skolem constant - * or logical / program variable). The term can be seen as a representative - * of this abstract domain element; the returned formula must formally - * specify this. + * Return the defining axiom, instantiated for a given Term (skolem constant or logical / + * program variable). The term can be seen as a representative of this abstract domain element; + * the returned formula must formally specify this. *

    - * + * *

    - * If this element describes, for instance, all numbers divisible by 2, the - * method could return the formula "varOrConst % 2 == 0". + * If this element describes, for instance, all numbers divisible by 2, the method could return + * the formula "varOrConst % 2 == 0". *

    - * - * @param varOrConst - * The logical / program variable or skolem constant representing - * an instance of this abstract domain element. - * @param services - * A services object. - * @return A JavaDL formula expressing that the given variable or constant - * represents an instance of this abstract domain element. + * + * @param varOrConst The logical / program variable or skolem constant representing an instance + * of this abstract domain element. + * @param services A services object. + * @return A JavaDL formula expressing that the given variable or constant represents an + * instance of this abstract domain element. */ public abstract Term getDefiningAxiom(Term varOrConst, Services services); /** - * Returns a parseable String representation of this - * {@link AbstractDomainElement}. It should always hold that, for an - * {@link AbstractDomainElement} e and the corresponding - * {@link AbstractDomainLattice} l, that - * {@code l.fromString(e.toParseableString(), + * Returns a parseable String representation of this {@link AbstractDomainElement}. It should + * always hold that, for an {@link AbstractDomainElement} e and the corresponding + * {@link AbstractDomainLattice} l, that {@code l.fromString(e.toParseableString(), * services).equals(e)}. - * - * @param services - * The services object. + * + * @param services The services object. * @return A parseable String representation of this domain element. */ public abstract String toParseableString(Services services); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainLattice.java index 0daa1b6fe32..9463cc076c0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/AbstractDomainLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction; import static de.uka.ilkd.key.util.mergerule.MergeRuleUtils.isProvableWithSplitting; @@ -11,51 +14,42 @@ import de.uka.ilkd.key.util.mergerule.SymbolicExecutionState; /** - * An abstract domain is a countable lattice with a partial order relation and a - * join operator. It supplies methods to abstract from a concrete domain to this - * abstract domain, and for iterating through the domain elements, thereby - * respecting the partial order. - * + * An abstract domain is a countable lattice with a partial order relation and a join operator. It + * supplies methods to abstract from a concrete domain to this abstract domain, and for iterating + * through the domain elements, thereby respecting the partial order. + * * @author Dominic Scheurer * * @param */ -public abstract class AbstractDomainLattice implements - PartialComparator, - Iterable { +public abstract class AbstractDomainLattice + implements PartialComparator, Iterable { /** - * Time in milliseconds after which a proof attempt of a defining axiom - * times out. + * Time in milliseconds after which a proof attempt of a defining axiom times out. */ private static final int AXIOM_PROVE_TIMEOUT_MS = 10000; /** - * Abstracts from a given element of the concrete domain by returning a - * suitable abstract element. The returned abstract element should be as - * precise as possible, that is there should not be a smaller abstract - * element that also describes the concrete element. - * - * @param state - * The state in which the abstraction should hold. - * @param term - * Element to abstract from. - * @param services - * The services object. + * Abstracts from a given element of the concrete domain by returning a suitable abstract + * element. The returned abstract element should be as precise as possible, that is there should + * not be a smaller abstract element that also describes the concrete element. + * + * @param state The state in which the abstraction should hold. + * @param term Element to abstract from. + * @param services The services object. * @return A suitable abstract domain element. */ - public AbstractDomainElement abstractFrom(SymbolicExecutionState state, - Term term, Services services) { + public AbstractDomainElement abstractFrom(SymbolicExecutionState state, Term term, + Services services) { Iterator it = iterator(); while (it.hasNext()) { AbstractDomainElement elem = it.next(); - Term toProve = - getSideConditionForAxiom(state, term, elem, services); + Term toProve = getSideConditionForAxiom(state, term, elem, services); - if (isProvableWithSplitting(toProve, services, - AXIOM_PROVE_TIMEOUT_MS)) { + if (isProvableWithSplitting(toProve, services, AXIOM_PROVE_TIMEOUT_MS)) { return elem; } } @@ -64,22 +58,16 @@ public AbstractDomainElement abstractFrom(SymbolicExecutionState state, } /** - * Returns a side condition which has to hold if elem is a correct - * abstraction for term. - * - * @param state - * The state in which the abstraction should hold. - * @param term - * Element to abstract from. - * @param elem - * Abstract domain element to check. - * @param services - * The services object. - * @return Side condition to prove in order to show that elem abstracts from - * term. + * Returns a side condition which has to hold if elem is a correct abstraction for term. + * + * @param state The state in which the abstraction should hold. + * @param term Element to abstract from. + * @param elem Abstract domain element to check. + * @param services The services object. + * @return Side condition to prove in order to show that elem abstracts from term. */ - public static Term getSideConditionForAxiom(SymbolicExecutionState state, - Term term, AbstractDomainElement elem, Services services) { + public static Term getSideConditionForAxiom(SymbolicExecutionState state, Term term, + AbstractDomainElement elem, Services services) { final TermBuilder tb = services.getTermBuilder(); Term axiom = elem.getDefiningAxiom(term, services); @@ -90,22 +78,17 @@ public static Term getSideConditionForAxiom(SymbolicExecutionState state, } /** - * A lattice join operation; finds an abstract element that is the least - * upper bound of the set consisting of the elements a and b. - * - * @param a - * First element to find the least upper bound for. - * @param b - * Second element to find the least upper bound for. - * @return The least upper bound of the set consisting of the elements a and - * b. + * A lattice join operation; finds an abstract element that is the least upper bound of the set + * consisting of the elements a and b. + * + * @param a First element to find the least upper bound for. + * @param b Second element to find the least upper bound for. + * @return The least upper bound of the set consisting of the elements a and b. */ - public abstract AbstractDomainElement join(AbstractDomainElement a, - AbstractDomainElement b); + public abstract AbstractDomainElement join(AbstractDomainElement a, AbstractDomainElement b); @Override - public PartialComparisonResult compare(AbstractDomainElement a, - AbstractDomainElement b) { + public PartialComparisonResult compare(AbstractDomainElement a, AbstractDomainElement b) { if (a.equals(b)) { return PartialComparisonResult.EQ; } @@ -113,39 +96,32 @@ public PartialComparisonResult compare(AbstractDomainElement a, AbstractDomainElement joinRes = join(a, b); if (joinRes.equals(a)) { return PartialComparisonResult.GTE; - } - else if (joinRes.equals(b)) { + } else if (joinRes.equals(b)) { return PartialComparisonResult.LTE; - } - else { + } else { return PartialComparisonResult.UNDEF; } } /** - * Iterates through the abstract domain elements of this abstract domain - * starting by the smallest element; if an element b is returned by the - * iterator after an element a, then either compare(a,b) == LTE, or - * compare(a,b) == UNDEF must hold (i.e., b may not be smaller than a). + * Iterates through the abstract domain elements of this abstract domain starting by the + * smallest element; if an element b is returned by the iterator after an element a, then either + * compare(a,b) == LTE, or compare(a,b) == UNDEF must hold (i.e., b may not be smaller than a). */ @Override public abstract Iterator iterator(); /** - * Constructs an Abstract Domain Element from the given String - * representation. It should always hold that, for an - * {@link AbstractDomainElement} e, that + * Constructs an Abstract Domain Element from the given String representation. It should always + * hold that, for an {@link AbstractDomainElement} e, that * {@code fromString(e.toParseableString(), * services).equals(e)}. - * - * @param s - * String to parse. - * @param services - * The services object. + * + * @param s String to parse. + * @param services The services object. * @return The corresponding {@link AbstractDomainElement}. - * @throws RuntimeException - * if s cannot be parsed. + * @throws RuntimeException if s cannot be parsed. */ public AbstractDomainElement fromString(String s, Services services) { final Iterator it = iterator(); @@ -156,8 +132,7 @@ public AbstractDomainElement fromString(String s, Services services) { } } - throw new RuntimeException( - "No element is represented by the given String '" + s + "'."); + throw new RuntimeException("No element is represented by the given String '" + s + "'."); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/PartialComparator.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/PartialComparator.java index 9940b109cb4..a560c102461 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/PartialComparator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/PartialComparator.java @@ -1,39 +1,44 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction; /** - *

    A comparison function, which imposes a partial ordering on some - * collection of objects.

    - * - *

    The ordering imposed by a comparator c on a set of elements - * S is said to be consistent with equals if and only if - * c.compare(e1, e2)==EQ has the same boolean value as - * e1.equals(e2) for every e1 and e2 in - * S.

    + *

    + * A comparison function, which imposes a partial ordering on some collection of objects. + *

    + * + *

    + * The ordering imposed by a comparator c on a set of elements S is said to be + * consistent with equals if and only if c.compare(e1, e2)==EQ has the same boolean + * value as e1.equals(e2) for every e1 and e2 in S. + *

    * * @param the type of objects that may be compared by this comparator - * + * * @author Dominic Scheurer * @see java.util.Comparator */ public interface PartialComparator { - /** - * Possible results of the comparison. - */ - public static enum PartialComparisonResult { - LTE, GTE, EQ, UNDEF - } - - /** - * Compares its two arguments for order. If the arguments are incomparable, - * UNDEF is returned. Otherwise, the method returns LTE, EQ, or GTE as the - * first argument is less than, equal to, or greater than the second.

    - * - * @param o1 the first object to be compared. - * @param o2 the second object to be compared. - * @return LTE, EQ, or GTE as the first argument is less than, equal to, or - * greater than the second; returns UNDEF if the arguments are incomparable. - */ - public PartialComparisonResult compare(T o1, T o2); - + /** + * Possible results of the comparison. + */ + public static enum PartialComparisonResult { + LTE, GTE, EQ, UNDEF + } + + /** + * Compares its two arguments for order. If the arguments are incomparable, UNDEF is returned. + * Otherwise, the method returns LTE, EQ, or GTE as the first argument is less than, equal to, + * or greater than the second. + *

    + * + * @param o1 the first object to be compared. + * @param o2 the second object to be compared. + * @return LTE, EQ, or GTE as the first argument is less than, equal to, or greater than the + * second; returns UNDEF if the arguments are incomparable. + */ + public PartialComparisonResult compare(T o1, T o2); + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanDomainElem.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanDomainElem.java index 2d5291204e7..dc17ba275a5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanDomainElem.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanDomainElem.java @@ -1,40 +1,43 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement; /** * A domain element of the simple boolean lattice. - * + * * @author Dominic Scheurer */ public abstract class BooleanDomainElem extends AbstractDomainElement { - /** - * @return true iff this element is the bottom element. - */ - public boolean isBottom() { - return this instanceof Bottom; - } - - /** - * @return true iff this element is the false element. - */ - public boolean isFalse() { - return this instanceof False; - } - - /** - * @return true iff this element is the true element. - */ - public boolean isTrue() { - return this instanceof True; - } - - /** - * @return true iff this element is the top element. - */ - public boolean isTop() { - return this instanceof Top; - } - + /** + * @return true iff this element is the bottom element. + */ + public boolean isBottom() { + return this instanceof Bottom; + } + + /** + * @return true iff this element is the false element. + */ + public boolean isFalse() { + return this instanceof False; + } + + /** + * @return true iff this element is the true element. + */ + public boolean isTrue() { + return this instanceof True; + } + + /** + * @return true iff this element is the top element. + */ + public boolean isTop() { + return this instanceof Top; + } + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanLattice.java index 4c9aade8e8a..200e422e8da 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/BooleanLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import java.util.Iterator; @@ -7,7 +10,7 @@ /** * A simple lattice for booleans. - * + * * @author Dominic Scheurer */ public class BooleanLattice extends AbstractDomainLattice { @@ -15,9 +18,8 @@ public class BooleanLattice extends AbstractDomainLattice { /** * All elements of this abstract domain. */ - public static final AbstractDomainElement[] ABSTRACT_DOMAIN_ELEMS = { - Bottom.getInstance(), False.getInstance(), True.getInstance(), - Top.getInstance() }; + public static final AbstractDomainElement[] ABSTRACT_DOMAIN_ELEMS = + { Bottom.getInstance(), False.getInstance(), True.getInstance(), Top.getInstance() }; /** * The singleton instance of the lattice. @@ -27,8 +29,7 @@ public class BooleanLattice extends AbstractDomainLattice { /** * Private constructor: Singleton. */ - private BooleanLattice() { - } + private BooleanLattice() {} /** * @return The singleton instance of this lattice. @@ -38,11 +39,9 @@ public static BooleanLattice getInstance() { } @Override - public AbstractDomainElement join(AbstractDomainElement elem1, - AbstractDomainElement elem2) { + public AbstractDomainElement join(AbstractDomainElement elem1, AbstractDomainElement elem2) { - if (!(elem1 instanceof BooleanDomainElem) - || !(elem2 instanceof BooleanDomainElem)) { + if (!(elem1 instanceof BooleanDomainElem) || !(elem2 instanceof BooleanDomainElem)) { throw new IllegalArgumentException( "Expected arguments of the abstract domain of sign analysis."); } @@ -57,8 +56,7 @@ public AbstractDomainElement join(AbstractDomainElement elem1, if (a.isTrue()) { if (b.isFalse()) { return Top.getInstance(); - } - else { + } else { return True.getInstance(); } } @@ -66,8 +64,7 @@ public AbstractDomainElement join(AbstractDomainElement elem1, if (a.isFalse()) { if (b.isTrue()) { return Top.getInstance(); - } - else { + } else { return False.getInstance(); } } @@ -94,8 +91,7 @@ public AbstractDomainElement next() { } @Override - public void remove() { - } + public void remove() {} }; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Bottom.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Bottom.java index 85909a61f91..94825bcfecd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Bottom.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Bottom.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import de.uka.ilkd.key.java.Services; @@ -7,25 +10,24 @@ import de.uka.ilkd.key.logic.op.LogicVariable; /** - * The Bottom element of the boolean lattice, representing - * no boolean at all. - * + * The Bottom element of the boolean lattice, representing no boolean at all. + * * @author Dominic Scheurer */ public class Bottom extends BooleanDomainElem { - private static final Bottom INSTANCE = new Bottom(); - - private Bottom() {} - - public static Bottom getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("bottom"); - } + private static final Bottom INSTANCE = new Bottom(); + + private Bottom() {} + + public static Bottom getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("bottom"); + } @Override public Term getDefiningAxiom(Term varOrConst, Services services) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/False.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/False.java index 4fa6054fbe8..427bccce8f2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/False.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/False.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The False element of the boolean lattice, representing - * exactly the boolean false. - * + * The False element of the boolean lattice, representing exactly the boolean false. + * * @author Dominic Scheurer */ public class False extends BooleanDomainElem { - private static final False INSTANCE = new False(); - - private False() {} - - public static False getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("false"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return tb.equals(varOrConst, tb.ff()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final False INSTANCE = new False(); + + private False() {} + + public static False getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("false"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return tb.equals(varOrConst, tb.ff()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Top.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Top.java index 157ddfc63e9..7005bde8a10 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Top.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/Top.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Top element of the boolean lattice, representing - * all booleans (i.e., true and false). - * + * The Top element of the boolean lattice, representing all booleans (i.e., true and false). + * * @author Dominic Scheurer */ public class Top extends BooleanDomainElem { - private static final Top INSTANCE = new Top(); - - private Top() {} - - public static Top getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("top"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return tb.tt(); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Top INSTANCE = new Top(); + + private Top() {} + + public static Top getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("top"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return tb.tt(); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/True.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/True.java index 78181860c6b..5be3f8e7d4c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/True.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/boollattice/True.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.boollattice; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The True element of the boolean lattice, representing - * exactly the boolean true. - * + * The True element of the boolean lattice, representing exactly the boolean true. + * * @author Dominic Scheurer */ public class True extends BooleanDomainElem { - private static final True INSTANCE = new True(); - - private True() {} - - public static True getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("true"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return tb.equals(varOrConst, tb.tt()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final True INSTANCE = new True(); + + private True() {} + + public static True getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("true"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return tb.equals(varOrConst, tb.tt()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionDomainElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionDomainElement.java index 14e76a6d84b..b9b163bc0a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionDomainElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionDomainElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.Iterator; @@ -16,15 +19,14 @@ * * @author Dominic Scheurer */ -public abstract class AbstractPredicateAbstractionDomainElement extends - AbstractDomainElement { +public abstract class AbstractPredicateAbstractionDomainElement extends AbstractDomainElement { private ImmutableSet predicates = null; private boolean topElem = false; /** - * Constructs a new {@link AbstractPredicateAbstractionDomainElement} from a - * given list of abstraction predicates. + * Constructs a new {@link AbstractPredicateAbstractionDomainElement} from a given list of + * abstraction predicates. */ public AbstractPredicateAbstractionDomainElement( final ImmutableSet predicates) { @@ -32,18 +34,17 @@ public AbstractPredicateAbstractionDomainElement( } /** - * Constructs a new {@link AbstractPredicateAbstractionDomainElement} that - * is a top element if isTopElem is set to true; otherwise, it is a bottom - * element. + * Constructs a new {@link AbstractPredicateAbstractionDomainElement} that is a top element if + * isTopElem is set to true; otherwise, it is a bottom element. */ protected AbstractPredicateAbstractionDomainElement(boolean isTopElem) { - this.predicates = DefaultImmutableSet. nil(); + this.predicates = DefaultImmutableSet.nil(); this.topElem = isTopElem; } /** - * @return Whether this element is the top element of the lattice (the axiom - * of which is true for every input). + * @return Whether this element is the top element of the lattice (the axiom of which is true + * for every input). */ protected boolean isTopElem() { return topElem; @@ -57,8 +58,7 @@ public ImmutableSet getPredicates() { } /** - * @param predicates - * the abstraction predicates for this domain element to set. + * @param predicates the abstraction predicates for this domain element to set. */ public void setPredicates(ImmutableSet predicates) { this.predicates = predicates; @@ -66,7 +66,7 @@ public void setPredicates(ImmutableSet predicates) { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.Named#name() */ @Override @@ -99,9 +99,8 @@ public String toString() { /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement#getDefiningAxiom + * + * @see de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement#getDefiningAxiom * (de.uka.ilkd.key.logic.Term, de.uka.ilkd.key.java.Services) */ @Override @@ -121,8 +120,7 @@ public Term getDefiningAxiom(Term varOrConst, Services services) { Term application = pred.apply(varOrConst); if (result == null) { result = application; - } - else { + } else { result = combinePredicates(result, application, services); } } @@ -132,27 +130,22 @@ public Term getDefiningAxiom(Term varOrConst, Services services) { /** * Combines the given predicate terms (classically using AND or OR). - * - * @param preds - * Term with all previous predicates. - * @param newPred - * The new predicate to combine preds with. - * @param services - * The services object. + * + * @param preds Term with all previous predicates. + * @param newPred The new predicate to combine preds with. + * @param services The services object. * @return The combination of preds with newPred. */ - protected abstract Term combinePredicates(Term preds, Term newPred, - Services services); + protected abstract Term combinePredicates(Term preds, Term newPred, Services services); /** * NOTE: This method should be defined in accordance with - * {@link AbstractPredicateAbstractionLattice#getPredicateNameCombinationString()} - * . This is probably bad design, but a substitute of the Java shortcoming - * that there are no abstract static methods. - * - * @return The String which is used for combining the names of predicates - * for lattice types where multiple predicates determine an abstract - * element. + * {@link AbstractPredicateAbstractionLattice#getPredicateNameCombinationString()} . This is + * probably bad design, but a substitute of the Java shortcoming that there are no abstract + * static methods. + * + * @return The String which is used for combining the names of predicates for lattice types + * where multiple predicates determine an abstract element. */ public abstract String getPredicateNameCombinationString(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionLattice.java index a1ed49f0b99..f68519efae6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractPredicateAbstractionLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.ArrayList; @@ -13,32 +16,24 @@ import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; /** - * A super class for predicates abstraction lattices. Implements basic join - * functionality and a template for an iterator initializing - * ImmutableFixedLengthBitSets. + * A super class for predicates abstraction lattices. Implements basic join functionality and a + * template for an iterator initializing ImmutableFixedLengthBitSets. * * @author Dominic Scheurer */ -public abstract class AbstractPredicateAbstractionLattice extends - AbstractDomainLattice { +public abstract class AbstractPredicateAbstractionLattice extends AbstractDomainLattice { /** * Joins to abstract elements in the lattice. - * - * @param a - * First domain element for the join. - * @param b - * Second domain element for the join. - * @param combiner - * The combination function (e.g., "AND") for the respective - * predicates of the inputs.. - * @param abstrElemConstructor - * A function constructing abstract domain elements from - * predicates. + * + * @param a First domain element for the join. + * @param b Second domain element for the join. + * @param combiner The combination function (e.g., "AND") for the respective predicates of the + * inputs.. + * @param abstrElemConstructor A function constructing abstract domain elements from predicates. * @return The joined abstract domain element. */ - protected AbstractPredicateAbstractionDomainElement join( - AbstractDomainElement a, + protected AbstractPredicateAbstractionDomainElement join(AbstractDomainElement a, AbstractDomainElement b, BiFunction, ImmutableSet, ImmutableSet> combiner, Function, AbstractPredicateAbstractionDomainElement> abstrElemConstructor) { @@ -71,13 +66,11 @@ protected AbstractPredicateAbstractionDomainElement join( ImmutableSet preds1 = pade1.getPredicates(); ImmutableSet preds2 = pade2.getPredicates(); - ImmutableSet combination = - combiner.apply(preds1, preds2); + ImmutableSet combination = combiner.apply(preds1, preds2); if (combination.size() == 0) { return getTopElem(); - } - else { + } else { return abstrElemConstructor.apply(combination); } } @@ -93,30 +86,28 @@ protected AbstractPredicateAbstractionDomainElement join( protected abstract AbstractPredicateAbstractionDomainElement getBottomElem(); /** - * @return The String which is used for combining the names of predicates - * for lattice types where multiple predicates determine an abstract - * element. + * @return The String which is used for combining the names of predicates for lattice types + * where multiple predicates determine an abstract element. */ public abstract String getPredicateNameCombinationString(); /** - * An abstract iterator which basically only sets up the bit sets used for - * building up complex iterators. + * An abstract iterator which basically only sets up the bit sets used for building up complex + * iterators. * * @author Dominic Scheurer */ - protected abstract class AbstractPredicateLatticeIterator implements - Iterator { + protected abstract class AbstractPredicateLatticeIterator + implements Iterator { private final ArrayList> bitSetsByNumZeroes = new ArrayList>(); /** - * Constructs a new {@link AbstractPredicateLatticeIterator}; - * initializes the bit sets for the iteration. - * - * @param numApplPreds - * The number of applicable predicates for the lattice. + * Constructs a new {@link AbstractPredicateLatticeIterator}; initializes the bit sets for + * the iteration. + * + * @param numApplPreds The number of applicable predicates for the lattice. */ public AbstractPredicateLatticeIterator(int numApplPreds) { // We work with bit sets of length n (where n is the number of @@ -126,13 +117,11 @@ public AbstractPredicateLatticeIterator(int numApplPreds) { // Initialize the list. for (int i = 0; i < numApplPreds + 1; i++) { - bitSetsByNumZeroes - .add(new ArrayList()); + bitSetsByNumZeroes.add(new ArrayList()); } // bitSet initially represents the number 0. - ImmutableFixedLengthBitSet bitSet = - new ImmutableFixedLengthBitSet(numApplPreds); + ImmutableFixedLengthBitSet bitSet = new ImmutableFixedLengthBitSet(numApplPreds); for (int i = 0; i < MergeRuleUtils.intPow(2, numApplPreds); i++) { int numZeroes = bitSet.getNumOfZeroBits(); @@ -145,8 +134,7 @@ public AbstractPredicateLatticeIterator(int numApplPreds) { } /** - * @return The list of bit sets for all given numbers of zeroes - * occurrences. + * @return The list of bit sets for all given numbers of zeroes occurrences. */ public ArrayList> getBitSetsByNumZeroes() { return bitSetsByNumZeroes; @@ -154,7 +142,7 @@ public ArrayList> getBitSetsByNumZeroes() /* * (non-Javadoc) - * + * * @see java.util.Iterator#remove() */ @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractionPredicate.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractionPredicate.java index 8378217fe6c..b1e6d79af81 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractionPredicate.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/AbstractionPredicate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.ArrayList; @@ -27,14 +30,12 @@ import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; /** - * Interface for predicates used for predicate abstraction. An abstraction - * predicate is a mapping from program variables or constants to formulae - * instantiated for the respective variable. + * Interface for predicates used for predicate abstraction. An abstraction predicate is a mapping + * from program variables or constants to formulae instantiated for the respective variable. * * @author Dominic Scheurer */ -public abstract class AbstractionPredicate - implements Function, Named { +public abstract class AbstractionPredicate implements Function, Named { /** * The sort for the argument of this {@link AbstractionPredicate}. @@ -42,8 +43,8 @@ public abstract class AbstractionPredicate private Sort argSort; /** - * The predicate term. Contains a placeholder ({@link #placeholderVariable}) - * which is to be replaced by the concrete argument of the predicate. + * The predicate term. Contains a placeholder ({@link #placeholderVariable}) which is to be + * replaced by the concrete argument of the predicate. *

    * * This field is needed to save proofs with abstraction predicates. @@ -51,9 +52,8 @@ public abstract class AbstractionPredicate private Term predicateFormWithPlaceholder = null; /** - * The placeholder variable occurring in - * {@link #predicateFormWithPlaceholder} which is to be replaced by the - * concrete argument of the predicate. + * The placeholder variable occurring in {@link #predicateFormWithPlaceholder} which is to be + * replaced by the concrete argument of the predicate. *

    * * This field is needed to save proofs with abstraction predicates.s @@ -61,66 +61,56 @@ public abstract class AbstractionPredicate private LocationVariable placeholderVariable = null; /** - * Creates a new {@link AbstractionPredicate}. Constructor is hidden since - * elements fo this class should be created by the factory method - * {@link #create(String, Function)}. + * Creates a new {@link AbstractionPredicate}. Constructor is hidden since elements fo this + * class should be created by the factory method {@link #create(String, Function)}. * - * @param argSort - * The expected sort for the arguments of the predicate. + * @param argSort The expected sort for the arguments of the predicate. */ private AbstractionPredicate(Sort argSort) { this.argSort = argSort; } /** - * @return The placeholder variable and the function term that this - * predicate has been constructed with. + * @return The placeholder variable and the function term that this predicate has been + * constructed with. */ public Pair getPredicateFormWithPlaceholder() { - return new Pair(placeholderVariable, - predicateFormWithPlaceholder); + return new Pair(placeholderVariable, predicateFormWithPlaceholder); } /** - * Creates a new {@link AbstractionPredicate} with the given name and - * mapping. You may use nice Java 8 lambdas for the second argument! + * Creates a new {@link AbstractionPredicate} with the given name and mapping. You may use nice + * Java 8 lambdas for the second argument! *

    * * This method has been created for testing purposes; you should rather user * {@link #create(Term, LocationVariable, Services)} instead. * - * @param argSort - * The expected sort for the arguments of the predicate. - * @param mapping - * The mapping from input terms of the adequate type to formulae, - * e.g. "(Term input) -> (tb.gt(input, tb.zero()))" where tb is a - * {@link TermBuilder}. - * @param services - * The services object. + * @param argSort The expected sort for the arguments of the predicate. + * @param mapping The mapping from input terms of the adequate type to formulae, e.g. "(Term + * input) -> (tb.gt(input, tb.zero()))" where tb is a {@link TermBuilder}. + * @param services The services object. * @return An abstraction predicate encapsulating the given mapping. */ public static AbstractionPredicate create(final Sort argSort, final Function mapping, Services services) { - LocationVariable placeholder = MergeRuleUtils - .getFreshLocVariableForPrefix("_ph", argSort, services); + LocationVariable placeholder = + MergeRuleUtils.getFreshLocVariableForPrefix("_ph", argSort, services); - return create(mapping.apply(services.getTermBuilder().var(placeholder)), - placeholder, services); + return create(mapping.apply(services.getTermBuilder().var(placeholder)), placeholder, + services); } /** - * Creates a new {@link AbstractionPredicate} for the given predicate. The - * predicate should contain the given placeholder variable, which is - * substituted by the argument supplied to the generated mapping. + * Creates a new {@link AbstractionPredicate} for the given predicate. The predicate should + * contain the given placeholder variable, which is substituted by the argument supplied to the + * generated mapping. * - * @param predicate - * The predicate formula containing the placeholder. - * @param placeholder - * The placeholder to replace in the generated mapping. - * @param services - * The services object. - * @return An abstraction predicate mapping terms to the predicate with the - * placeholder substituted by the respective term. + * @param predicate The predicate formula containing the placeholder. + * @param placeholder The placeholder to replace in the generated mapping. + * @param services The services object. + * @return An abstraction predicate mapping terms to the predicate with the placeholder + * substituted by the respective term. */ public static AbstractionPredicate create(final Term predicate, final LocationVariable placeholder, Services services) { @@ -129,8 +119,7 @@ public static AbstractionPredicate create(final Term predicate, final Sort fInputSort = placeholder.sort(); AbstractionPredicate result = new AbstractionPredicate(fInputSort) { - private final Name name = new Name( - "abstrPred_" + predicate.op().toString()); + private final Name name = new Name("abstrPred_" + predicate.op().toString()); private Function mapping = null; @Override @@ -138,14 +127,12 @@ public Term apply(Term input) { if (mapping == null) { mapping = (Term param) -> { if (param.sort() != fInputSort) { - throw new IllegalArgumentException( - "Input must be of sort \"" + fInputSort - + "\", given: \"" + param.sort() - + "\"."); + throw new IllegalArgumentException("Input must be of sort \"" + + fInputSort + "\", given: \"" + param.sort() + "\"."); } - return OpReplacer.replace(tb.var(placeholder), param, - predicate, tf, services.getProof()); + return OpReplacer.replace(tb.var(placeholder), param, predicate, tf, + services.getProof()); }; } @@ -190,27 +177,22 @@ public String toString() { } /** - * Returns a parseable String representation of this abstraction predicate - * of the form "('[[TYPE]] [[PLACEHOLDER]]', '[[PREDICATE]]')". + * Returns a parseable String representation of this abstraction predicate of the form + * "('[[TYPE]] [[PLACEHOLDER]]', '[[PREDICATE]]')". * - * @param services - * The services object. + * @param services The services object. * @return A parseable String representation of this predicate. */ public String toParseableString(final Services services) { StringBuilder sb = new StringBuilder(); - Pair predicateFormWithPlaceholder = getPredicateFormWithPlaceholder(); + Pair predicateFormWithPlaceholder = + getPredicateFormWithPlaceholder(); - sb.append("(").append("'") - .append(predicateFormWithPlaceholder.first.sort()).append(" ") + sb.append("(").append("'").append(predicateFormWithPlaceholder.first.sort()).append(" ") .append(predicateFormWithPlaceholder.first).append("', '") - .append(OutputStreamProofSaver - .escapeCharacters(OutputStreamProofSaver - .printAnything( - predicateFormWithPlaceholder.second, - services, false) - .toString().trim() - .replaceAll("(\\r|\\n|\\r\\n)+", ""))) + .append(OutputStreamProofSaver.escapeCharacters(OutputStreamProofSaver + .printAnything(predicateFormWithPlaceholder.second, services, false) + .toString().trim().replaceAll("(\\r|\\n|\\r\\n)+", ""))) .append("')"); return sb.toString(); @@ -219,23 +201,16 @@ public String toParseableString(final Services services) { /** * Parses the String representation of an abstraction predicates. * - * @param s - * {@link String} to parse. - * @param services - * The {@link Services} object. - * @param localNamespaces - * The local {@link NamespaceSet}. + * @param s {@link String} to parse. + * @param services The {@link Services} object. + * @param localNamespaces The local {@link NamespaceSet}. * @return The parsed {@link String}. - * @throws ParserException - * If there is a syntax error. - * @throws NameAlreadyBoundException - * If the given placeholder is already known to the system. - * @throws SortNotKnownException - * If the given sort is not known to the system. + * @throws ParserException If there is a syntax error. + * @throws NameAlreadyBoundException If the given placeholder is already known to the system. + * @throws SortNotKnownException If the given sort is not known to the system. */ - public static List fromString(final String s, - final Services services, NamespaceSet localNamespaces) - throws ParserException { + public static List fromString(final String s, final Services services, + NamespaceSet localNamespaces) throws ParserException { final ArrayList result = new ArrayList(); Pattern p = Pattern.compile("\\('(.+?)', '(.+?)'\\)"); @@ -246,9 +221,8 @@ public static List fromString(final String s, matched = true; for (int i = 1; i < m.groupCount(); i += 2) { - assert i + 1 <= m - .groupCount() : "Wrong format of join abstraction predicates: " - + "There should always be pairs of placeholders and predicate terms."; + assert i + 1 <= m.groupCount() : "Wrong format of join abstraction predicates: " + + "There should always be pairs of placeholders and predicate terms."; final String phStr = m.group(i); final String predStr = m.group(i + 1); @@ -258,24 +232,20 @@ public static List fromString(final String s, ph = MergeRuleUtils.parsePlaceholder(phStr, false, services); // Add placeholder to namespaces, if necessary - Namespace variables = services.getNamespaces() - .programVariables(); + Namespace variables = services.getNamespaces().programVariables(); if (variables.lookup(ph.second) == null) { - variables.add(new LocationVariable( - new ProgramElementName(ph.second.toString()), + variables.add(new LocationVariable(new ProgramElementName(ph.second.toString()), ph.first)); } // Parse the predicate result.add(MergeRuleUtils.parsePredicate(predStr, - MergeRuleUtils.singletonArrayList(ph), localNamespaces, - services)); + MergeRuleUtils.singletonArrayList(ph), localNamespaces, services)); } } if (!matched) { - throw new ParserException( - "Wrong format of join abstraction predicates", null); + throw new ParserException("Wrong format of join abstraction predicates", null); } return result; @@ -290,8 +260,7 @@ public boolean equals(Object obj) { final AbstractionPredicate otherPred = (AbstractionPredicate) obj; return otherPred.placeholderVariable.equals(placeholderVariable) - && otherPred.predicateFormWithPlaceholder - .equals(predicateFormWithPlaceholder); + && otherPred.predicateFormWithPlaceholder.equals(predicateFormWithPlaceholder); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionDomainElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionDomainElement.java index 5c4038bbdb2..58fb5b59581 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionDomainElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionDomainElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import org.key_project.util.collection.ImmutableSet; @@ -6,13 +9,13 @@ import de.uka.ilkd.key.logic.Term; /** - * An abstract domain element for a predicate abstraction lattice based on the - * conjunction of predicates. + * An abstract domain element for a predicate abstraction lattice based on the conjunction of + * predicates. * * @author Dominic Scheurer */ -public class ConjunctivePredicateAbstractionDomainElement extends - AbstractPredicateAbstractionDomainElement { +public class ConjunctivePredicateAbstractionDomainElement + extends AbstractPredicateAbstractionDomainElement { /** * The bottom element of any predicate abstraction lattice. @@ -27,8 +30,8 @@ public class ConjunctivePredicateAbstractionDomainElement extends new ConjunctivePredicateAbstractionDomainElement(true); /** - * Constructs a new {@link ConjunctivePredicateAbstractionDomainElement} - * from a given list of abstraction predicates. + * Constructs a new {@link ConjunctivePredicateAbstractionDomainElement} from a given list of + * abstraction predicates. */ public ConjunctivePredicateAbstractionDomainElement( final ImmutableSet predicates) { @@ -36,9 +39,8 @@ public ConjunctivePredicateAbstractionDomainElement( } /** - * Constructs a new {@link ConjunctivePredicateAbstractionDomainElement} - * that is a top element if isTopElem is set to true; otherwise, it is a - * bottom element. + * Constructs a new {@link ConjunctivePredicateAbstractionDomainElement} that is a top element + * if isTopElem is set to true; otherwise, it is a bottom element. */ private ConjunctivePredicateAbstractionDomainElement(boolean isTopElem) { super(isTopElem); @@ -56,17 +58,15 @@ public String getPredicateNameCombinationString() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return obj instanceof ConjunctivePredicateAbstractionDomainElement - && (this != TOP || obj == TOP) - && (this != BOTTOM || obj == BOTTOM) + && (this != TOP || obj == TOP) && (this != BOTTOM || obj == BOTTOM) && this.getPredicates().equals( - ((ConjunctivePredicateAbstractionDomainElement) obj) - .getPredicates()); + ((ConjunctivePredicateAbstractionDomainElement) obj).getPredicates()); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionLattice.java index d86a4834e28..659073bd84e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/ConjunctivePredicateAbstractionLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.ArrayList; @@ -13,37 +16,31 @@ import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; /** - * A lattice for all predicates accepting the given sort. This lattice consists - * of 2^n + 1 elements, where n is the number of applicable predicates. Each - * element is a conjunction of the given predicates. The last element is a top - * element which is true for all inputs. + * A lattice for all predicates accepting the given sort. This lattice consists of 2^n + 1 elements, + * where n is the number of applicable predicates. Each element is a conjunction of the given + * predicates. The last element is a top element which is true for all inputs. *

    - * It may happen that certain elements of the lattice are equivalent to the - * bottom element, since the respective combinations of predicates are - * unsatisfiable. It should however not happen that combinations of predicates - * are valid, that is they equal the top element. For efficiency reasons, the - * lattice is only lazily generated on-demand by the iterator. Therefore, the - * unsatisfiable combinations cannot be removed at generation time. + * It may happen that certain elements of the lattice are equivalent to the bottom element, since + * the respective combinations of predicates are unsatisfiable. It should however not happen that + * combinations of predicates are valid, that is they equal the top element. For efficiency reasons, + * the lattice is only lazily generated on-demand by the iterator. Therefore, the unsatisfiable + * combinations cannot be removed at generation time. * * @author Dominic Scheurer */ -public class ConjunctivePredicateAbstractionLattice extends - AbstractPredicateAbstractionLattice { +public class ConjunctivePredicateAbstractionLattice extends AbstractPredicateAbstractionLattice { public static final String PREDICATE_NAME_CONBINATION_STRING = "_AND_"; - private List predicates = - new ArrayList(); + private List predicates = new ArrayList(); /** - * Constructs a new {@link ConjunctivePredicateAbstractionLattice} for the - * given list of applicable predicates. The caller is responsible for making - * sure that none of the predicates is valid. + * Constructs a new {@link ConjunctivePredicateAbstractionLattice} for the given list of + * applicable predicates. The caller is responsible for making sure that none of the predicates + * is valid. * - * @param applicablePredicates - * The predicates to generate the lattice from. + * @param applicablePredicates The predicates to generate the lattice from. */ - public ConjunctivePredicateAbstractionLattice( - List applicablePredicates) { + public ConjunctivePredicateAbstractionLattice(List applicablePredicates) { super(); assert predicates != null : "Do not call this constructor with a null argument."; @@ -52,27 +49,25 @@ public ConjunctivePredicateAbstractionLattice( /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd + * + * @see de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd * .key.axiom_abstraction.AbstractDomainElement, * de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement) */ @Override - public AbstractDomainElement join(AbstractDomainElement a, - AbstractDomainElement b) { + public AbstractDomainElement join(AbstractDomainElement a, AbstractDomainElement b) { /* - * The join result is a PredicateAbstractionDomainElement constructed of - * the intersection of the respective predicates. + * The join result is a PredicateAbstractionDomainElement constructed of the intersection of + * the respective predicates. */ return super.join(a, b, (set1, set2) -> (set1.intersect(set2)), set -> new ConjunctivePredicateAbstractionDomainElement(set)); } /** - * The iterator for this lattice will first return the bottom element, then - * all conjunctions of length n of the predicates, then all conjunctions of - * length n-1, and so on, until finally the top element is returned. + * The iterator for this lattice will first return the bottom element, then all conjunctions of + * length n of the predicates, then all conjunctions of length n-1, and so on, until finally the + * top element is returned. */ @Override public Iterator iterator() { @@ -90,7 +85,7 @@ public int size() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override @@ -107,26 +102,25 @@ public int hashCode() { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - return "Conjunctive Predicate Abstraction Lattice of size " + size() - + " with predicates " + predicates.toString(); + return "Conjunctive Predicate Abstraction Lattice of size " + size() + " with predicates " + + predicates.toString(); } /** * @see ConjunctivePredicateAbstractionLattice#iterator() */ - private class PredicateLatticeIterator extends - AbstractPredicateLatticeIterator { + private class PredicateLatticeIterator extends AbstractPredicateLatticeIterator { private int nrZeroes = -1; private int idx = 0; /** - * Constructs a new {@link PredicateLatticeIterator}; initializes the - * bit sets for the iteration. + * Constructs a new {@link PredicateLatticeIterator}; initializes the bit sets for the + * iteration. */ public PredicateLatticeIterator() { super(predicates == null ? 0 : predicates.size()); @@ -143,7 +137,7 @@ public PredicateLatticeIterator() { /* * (non-Javadoc) - * + * * @see java.util.Iterator#hasNext() */ @Override @@ -153,7 +147,7 @@ public boolean hasNext() { /* * (non-Javadoc) - * + * * @see java.util.Iterator#next() */ @Override @@ -169,32 +163,27 @@ public AbstractDomainElement next() { } ImmutableSet predicatesForElem = - DefaultImmutableSet. nil(); + DefaultImmutableSet.nil(); - ImmutableFixedLengthBitSet currBitSet = - getBitSetsByNumZeroes().get(nrZeroes).get(idx); + ImmutableFixedLengthBitSet currBitSet = getBitSetsByNumZeroes().get(nrZeroes).get(idx); for (int nonZeroPosition : currBitSet.getNonzeroPositions()) { try { predicatesForElem = - predicatesForElem.addUnique(predicates - .get(nonZeroPosition)); - } - catch (NotUniqueException e) { + predicatesForElem.addUnique(predicates.get(nonZeroPosition)); + } catch (NotUniqueException e) { // Not unique -- just don't add } } if (getBitSetsByNumZeroes().get(nrZeroes).size() - 1 > idx) { idx++; - } - else { + } else { nrZeroes++; idx = 0; } - return new ConjunctivePredicateAbstractionDomainElement( - predicatesForElem); + return new ConjunctivePredicateAbstractionDomainElement(predicatesForElem); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionDomainElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionDomainElement.java index bb54eb01335..e9079691d41 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionDomainElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionDomainElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import org.key_project.util.collection.ImmutableSet; @@ -6,13 +9,13 @@ import de.uka.ilkd.key.logic.Term; /** - * An abstract domain element for a predicate abstraction lattice based on the - * disjunction of predicates. + * An abstract domain element for a predicate abstraction lattice based on the disjunction of + * predicates. * * @author Dominic Scheurer */ -public class DisjunctivePredicateAbstractionDomainElement extends - AbstractPredicateAbstractionDomainElement { +public class DisjunctivePredicateAbstractionDomainElement + extends AbstractPredicateAbstractionDomainElement { /** * The bottom element of any predicate abstraction lattice. @@ -27,8 +30,8 @@ public class DisjunctivePredicateAbstractionDomainElement extends new DisjunctivePredicateAbstractionDomainElement(true); /** - * Constructs a new {@link DisjunctivePredicateAbstractionDomainElement} - * from a given list of abstraction predicates. + * Constructs a new {@link DisjunctivePredicateAbstractionDomainElement} from a given list of + * abstraction predicates. */ public DisjunctivePredicateAbstractionDomainElement( final ImmutableSet predicates) { @@ -36,9 +39,8 @@ public DisjunctivePredicateAbstractionDomainElement( } /** - * Constructs a new {@link DisjunctivePredicateAbstractionDomainElement} - * that is a top element if isTopElem is set to true; otherwise, it is a - * bottom element. + * Constructs a new {@link DisjunctivePredicateAbstractionDomainElement} that is a top element + * if isTopElem is set to true; otherwise, it is a bottom element. */ private DisjunctivePredicateAbstractionDomainElement(boolean isTopElem) { super(isTopElem); @@ -56,17 +58,15 @@ public String getPredicateNameCombinationString() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return obj instanceof DisjunctivePredicateAbstractionDomainElement - && (this != TOP || obj == TOP) - && (this != BOTTOM || obj == BOTTOM) + && (this != TOP || obj == TOP) && (this != BOTTOM || obj == BOTTOM) && this.getPredicates().equals( - ((DisjunctivePredicateAbstractionDomainElement) obj) - .getPredicates()); + ((DisjunctivePredicateAbstractionDomainElement) obj).getPredicates()); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionLattice.java index d81f342e5eb..ea6f86553e1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/DisjunctivePredicateAbstractionLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.ArrayList; @@ -13,35 +16,29 @@ import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; /** - * A lattice for all predicates accepting the given sort. This lattice consists - * of 2^n + 1 elements, where n is the number of applicable predicates. Each - * element is a disjunction of the given predicates. The last element is a top - * element which is true for all inputs. + * A lattice for all predicates accepting the given sort. This lattice consists of 2^n + 1 elements, + * where n is the number of applicable predicates. Each element is a disjunction of the given + * predicates. The last element is a top element which is true for all inputs. *

    - * It should however not happen that combinations of predicates are valid, that - * is they equal the top element. For efficiency reasons, the lattice is only - * lazily generated on-demand by the iterator. Therefore, the unsatisfiable - * predicates cannot be removed at generation time. + * It should however not happen that combinations of predicates are valid, that is they equal the + * top element. For efficiency reasons, the lattice is only lazily generated on-demand by the + * iterator. Therefore, the unsatisfiable predicates cannot be removed at generation time. * * @author Dominic Scheurer */ -public class DisjunctivePredicateAbstractionLattice extends - AbstractPredicateAbstractionLattice { +public class DisjunctivePredicateAbstractionLattice extends AbstractPredicateAbstractionLattice { public static final String PREDICATE_NAME_CONBINATION_STRING = "_OR_"; - - private List predicates = - new ArrayList(); + + private List predicates = new ArrayList(); /** - * Constructs a new {@link DisjunctivePredicateAbstractionLattice} for the - * given list of applicable predicates. The caller is responsible for making - * sure that no combinations of predicates are valid. + * Constructs a new {@link DisjunctivePredicateAbstractionLattice} for the given list of + * applicable predicates. The caller is responsible for making sure that no combinations of + * predicates are valid. * - * @param applicablePredicates - * The predicates to generate the lattice from. + * @param applicablePredicates The predicates to generate the lattice from. */ - public DisjunctivePredicateAbstractionLattice( - List applicablePredicates) { + public DisjunctivePredicateAbstractionLattice(List applicablePredicates) { super(); assert predicates != null : "Do not call this constructor with a null argument."; @@ -50,27 +47,25 @@ public DisjunctivePredicateAbstractionLattice( /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd + * + * @see de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd * .key.axiom_abstraction.AbstractDomainElement, * de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement) */ @Override - public AbstractDomainElement join(AbstractDomainElement a, - AbstractDomainElement b) { + public AbstractDomainElement join(AbstractDomainElement a, AbstractDomainElement b) { /* - * The join result is a PredicateAbstractionDomainElement constructed of - * the union of the respective predicates. + * The join result is a PredicateAbstractionDomainElement constructed of the union of the + * respective predicates. */ return super.join(a, b, (set1, set2) -> (set1.union(set2)), set -> new DisjunctivePredicateAbstractionDomainElement(set)); } /** - * The iterator for this lattice will first return the bottom element, then - * all conjunctions of length n of the predicates, then all conjunctions of - * length n-1, and so on, until finally the top element is returned. + * The iterator for this lattice will first return the bottom element, then all conjunctions of + * length n of the predicates, then all conjunctions of length n-1, and so on, until finally the + * top element is returned. */ @Override public Iterator iterator() { @@ -88,7 +83,7 @@ public int size() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override @@ -97,7 +92,7 @@ public boolean equals(Object obj) { && ((DisjunctivePredicateAbstractionLattice) obj).predicates .equals(this.predicates); } - + @Override public int hashCode() { return 31 * 2 + predicates.hashCode(); @@ -105,26 +100,25 @@ public int hashCode() { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - return "Disjunctive Predicate Abstraction Lattice of size " + size() - + " with predicates " + predicates.toString(); + return "Disjunctive Predicate Abstraction Lattice of size " + size() + " with predicates " + + predicates.toString(); } /** * @see DisjunctivePredicateAbstractionLattice#iterator() */ - private class PredicateLatticeIterator extends - AbstractPredicateLatticeIterator { + private class PredicateLatticeIterator extends AbstractPredicateLatticeIterator { private int nrZeroes = -1; private int idx = 0; /** - * Constructs a new {@link PredicateLatticeIterator}; initializes the - * bit sets for the iteration. + * Constructs a new {@link PredicateLatticeIterator}; initializes the bit sets for the + * iteration. */ public PredicateLatticeIterator() { super(predicates == null ? 0 : predicates.size()); @@ -137,13 +131,13 @@ public PredicateLatticeIterator() { if (predicates == null) { predicates = new ArrayList(); } - + nrZeroes = predicates.size(); } /* * (non-Javadoc) - * + * * @see java.util.Iterator#hasNext() */ @Override @@ -153,7 +147,7 @@ public boolean hasNext() { /* * (non-Javadoc) - * + * * @see java.util.Iterator#next() */ @Override @@ -169,26 +163,22 @@ public AbstractDomainElement next() { } ImmutableSet predicatesForElem = - DefaultImmutableSet. nil(); + DefaultImmutableSet.nil(); - ImmutableFixedLengthBitSet currBitSet = - getBitSetsByNumZeroes().get(nrZeroes).get(idx); + ImmutableFixedLengthBitSet currBitSet = getBitSetsByNumZeroes().get(nrZeroes).get(idx); for (int nonZeroPosition : currBitSet.getNonzeroPositions()) { try { predicatesForElem = - predicatesForElem.addUnique(predicates - .get(nonZeroPosition)); - } - catch (NotUniqueException e) { + predicatesForElem.addUnique(predicates.get(nonZeroPosition)); + } catch (NotUniqueException e) { // Not unique -- just don't add } } if (getBitSetsByNumZeroes().get(nrZeroes).size() - 1 > idx) { idx++; - } - else { + } else { nrZeroes--; idx = 0; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionDomainElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionDomainElement.java index 3d8e1f6dc1e..5776facb428 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionDomainElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionDomainElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import org.key_project.util.collection.ImmutableSet; @@ -6,13 +9,13 @@ import de.uka.ilkd.key.logic.Term; /** - * An abstract domain element for a predicate abstraction lattice encapsulating - * exactly one abstraction predicate. + * An abstract domain element for a predicate abstraction lattice encapsulating exactly one + * abstraction predicate. * * @author Dominic Scheurer */ -public class SimplePredicateAbstractionDomainElement extends - AbstractPredicateAbstractionDomainElement { +public class SimplePredicateAbstractionDomainElement + extends AbstractPredicateAbstractionDomainElement { /** * The bottom element of any predicate abstraction lattice. @@ -27,8 +30,8 @@ public class SimplePredicateAbstractionDomainElement extends new SimplePredicateAbstractionDomainElement(true); /** - * Constructs a new {@link SimplePredicateAbstractionDomainElement} from a - * given list of abstraction predicates. + * Constructs a new {@link SimplePredicateAbstractionDomainElement} from a given list of + * abstraction predicates. */ public SimplePredicateAbstractionDomainElement( final ImmutableSet predicates) { @@ -36,9 +39,8 @@ public SimplePredicateAbstractionDomainElement( } /** - * Constructs a new {@link SimplePredicateAbstractionDomainElement} that is - * a top element if isTopElem is set to true; otherwise, it is a bottom - * element. + * Constructs a new {@link SimplePredicateAbstractionDomainElement} that is a top element if + * isTopElem is set to true; otherwise, it is a bottom element. */ private SimplePredicateAbstractionDomainElement(boolean isTopElem) { super(isTopElem); @@ -46,8 +48,7 @@ private SimplePredicateAbstractionDomainElement(boolean isTopElem) { @Override protected Term combinePredicates(Term preds, Term newPred, Services services) { - throw new RuntimeException( - "In the simple predicate abstraction lattice, " + throw new RuntimeException("In the simple predicate abstraction lattice, " + "elements should not be combined."); } @@ -58,17 +59,14 @@ public String getPredicateNameCombinationString() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { - return obj instanceof SimplePredicateAbstractionDomainElement - && (this != TOP || obj == TOP) - && (this != BOTTOM || obj == BOTTOM) - && this.getPredicates().equals( - ((SimplePredicateAbstractionDomainElement) obj) - .getPredicates()); + return obj instanceof SimplePredicateAbstractionDomainElement && (this != TOP || obj == TOP) + && (this != BOTTOM || obj == BOTTOM) && this.getPredicates() + .equals(((SimplePredicateAbstractionDomainElement) obj).getPredicates()); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionLattice.java index 6695bf0aa7b..58d1a191164 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/predicateabstraction/SimplePredicateAbstractionLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.predicateabstraction; import java.util.ArrayList; @@ -9,30 +12,24 @@ import de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement; /** - * A lattice for all predicates accepting the given sort. This lattice consists - * of n + 2 elements, where n is the number of applicable predicates. The first - * element is a bottom element, the last a top element, and the elements in - * between correspond to the given predicates. + * A lattice for all predicates accepting the given sort. This lattice consists of n + 2 elements, + * where n is the number of applicable predicates. The first element is a bottom element, the last a + * top element, and the elements in between correspond to the given predicates. * * @author Dominic Scheurer */ -public class SimplePredicateAbstractionLattice extends - AbstractPredicateAbstractionLattice { +public class SimplePredicateAbstractionLattice extends AbstractPredicateAbstractionLattice { public static final String PREDICATE_NAME_CONBINATION_STRING = "<<<<<>>>>>"; - - private List predicates = - new ArrayList(); + + private List predicates = new ArrayList(); /** - * Constructs a new {@link SimplePredicateAbstractionLattice} for the given - * list of applicable predicates. The caller is responsible for making sure - * that none of the predicates is valid. + * Constructs a new {@link SimplePredicateAbstractionLattice} for the given list of applicable + * predicates. The caller is responsible for making sure that none of the predicates is valid. * - * @param applicablePredicates - * The predicates to generate the lattice from. + * @param applicablePredicates The predicates to generate the lattice from. */ - public SimplePredicateAbstractionLattice( - List applicablePredicates) { + public SimplePredicateAbstractionLattice(List applicablePredicates) { super(); assert predicates != null : "Do not call this constructor with a null argument."; @@ -42,27 +39,24 @@ public SimplePredicateAbstractionLattice( /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd + * + * @see de.uka.ilkd.key.axiom_abstraction.AbstractDomainLattice#join(de.uka.ilkd * .key.axiom_abstraction.AbstractDomainElement, * de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement) */ @Override - public AbstractDomainElement join(AbstractDomainElement a, - AbstractDomainElement b) { + public AbstractDomainElement join(AbstractDomainElement a, AbstractDomainElement b) { /* - * The join result is a PredicateAbstractionDomainElement constructed of - * the intersection of the respective predicates. + * The join result is a PredicateAbstractionDomainElement constructed of the intersection of + * the respective predicates. */ return super.join(a, b, (set1, set2) -> (set1.intersect(set2)), set -> new SimplePredicateAbstractionDomainElement(set)); } /** - * The iterator for this lattice will first return the bottom element, then - * the given predicates in the order in which they have been initially - * supplied, and finally the top element. + * The iterator for this lattice will first return the bottom element, then the given predicates + * in the order in which they have been initially supplied, and finally the top element. */ @Override public Iterator iterator() { @@ -81,14 +75,11 @@ public AbstractDomainElement next() { if (oldIdx == 0) { return SimplePredicateAbstractionDomainElement.BOTTOM; - } - else if (oldIdx == size() - 1) { + } else if (oldIdx == size() - 1) { return SimplePredicateAbstractionDomainElement.TOP; - } - else { - return new SimplePredicateAbstractionDomainElement( - DefaultImmutableSet. nil() - .add(predicates.get(oldIdx - 1))); + } else { + return new SimplePredicateAbstractionDomainElement(DefaultImmutableSet + .nil().add(predicates.get(oldIdx - 1))); } } @@ -105,16 +96,15 @@ public int size() { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return obj instanceof SimplePredicateAbstractionLattice - && ((SimplePredicateAbstractionLattice) obj).predicates - .equals(this.predicates); + && ((SimplePredicateAbstractionLattice) obj).predicates.equals(this.predicates); } - + @Override public int hashCode() { return 31 * 3 + predicates.hashCode(); @@ -122,13 +112,13 @@ public int hashCode() { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - return "Simple Predicate Abstraction Lattice of size " + size() - + " with predicates " + predicates.toString(); + return "Simple Predicate Abstraction Lattice of size " + size() + " with predicates " + + predicates.toString(); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Bottom.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Bottom.java index 260958b2796..5eded1ea3d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Bottom.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Bottom.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -7,44 +10,43 @@ import de.uka.ilkd.key.logic.op.LogicVariable; /** - * The Bottom element of the sign lattice, representing - * no number at all. - * + * The Bottom element of the sign lattice, representing no number at all. + * * @author Dominic Scheurer */ public class Bottom extends SignAnalysisDomainElem { - private static final Bottom INSTANCE = new Bottom(); - - private Bottom() {} - - public static Bottom getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("bottom"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - - final Name freshVarName = new Name(tb.newName(varOrConst.sort())); - LogicVariable freshVar = new LogicVariable(freshVarName, varOrConst.sort()); - services.getNamespaces().variables().add(freshVar); - - Term axiom = tb.equals(varOrConst, tb.var(freshVar)); - axiom = tb.not(axiom); - axiom = tb.all(freshVar, axiom); - - return axiom; - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Bottom INSTANCE = new Bottom(); + + private Bottom() {} + + public static Bottom getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("bottom"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + + final Name freshVarName = new Name(tb.newName(varOrConst.sort())); + LogicVariable freshVar = new LogicVariable(freshVarName, varOrConst.sort()); + services.getNamespaces().variables().add(freshVar); + + Term axiom = tb.equals(varOrConst, tb.var(freshVar)); + axiom = tb.not(axiom); + axiom = tb.all(freshVar, axiom); + + return axiom; + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Geq.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Geq.java index 8d9407f53f4..15ab4ef20d9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Geq.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Geq.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Geq element of the sign lattice, representing - * all positive integers and zero. - * + * The Geq element of the sign lattice, representing all positive integers and zero. + * * @author Dominic Scheurer */ public class Geq extends SignAnalysisDomainElem { - private static final Geq INSTANCE = new Geq(); - - private Geq() {} - - public static Geq getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("geq"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return services.getTermBuilder().geq(varOrConst, tb.zero()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Geq INSTANCE = new Geq(); + + private Geq() {} + + public static Geq getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("geq"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return services.getTermBuilder().geq(varOrConst, tb.zero()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Leq.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Leq.java index 8f5d9fd5d74..f4c260a473b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Leq.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Leq.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Leq element of the sign lattice, representing - * all negative numbers and zero. - * + * The Leq element of the sign lattice, representing all negative numbers and zero. + * * @author Dominic Scheurer */ public class Leq extends SignAnalysisDomainElem { - private static final Leq INSTANCE = new Leq(); - - private Leq() {} - - public static Leq getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("leq"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return services.getTermBuilder().leq(varOrConst, tb.zero()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Leq INSTANCE = new Leq(); + + private Leq() {} + + public static Leq getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("leq"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return services.getTermBuilder().leq(varOrConst, tb.zero()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Neg.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Neg.java index dd412663ed0..425f905db86 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Neg.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Neg.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Neg element of the sign lattice, representing - * all strictly negative integers. - * + * The Neg element of the sign lattice, representing all strictly negative integers. + * * @author Dominic Scheurer */ public class Neg extends SignAnalysisDomainElem { - private static final Neg INSTANCE = new Neg(); - - private Neg() {} - - public static Neg getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("neg"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return services.getTermBuilder().lt(varOrConst, tb.zero()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Neg INSTANCE = new Neg(); + + private Neg() {} + + public static Neg getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("neg"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return services.getTermBuilder().lt(varOrConst, tb.zero()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Pos.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Pos.java index 0611e498f90..d12147ea8ef 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Pos.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Pos.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Pos element of the sign lattice, representing - * all strictly positive numbers. - * + * The Pos element of the sign lattice, representing all strictly positive numbers. + * * @author Dominic Scheurer */ public class Pos extends SignAnalysisDomainElem { - private static final Pos INSTANCE = new Pos(); - - private Pos() {} - - public static Pos getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("pos"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return services.getTermBuilder().gt(varOrConst, tb.zero()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Pos INSTANCE = new Pos(); + + private Pos() {} + + public static Pos getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("pos"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return services.getTermBuilder().gt(varOrConst, tb.zero()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisDomainElem.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisDomainElem.java index 26c1d64cbc1..def7f4b1e0b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisDomainElem.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisDomainElem.java @@ -1,61 +1,64 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.axiom_abstraction.AbstractDomainElement; /** * A domain element for sign analysis. - * + * * @author Dominic Scheurer */ public abstract class SignAnalysisDomainElem extends AbstractDomainElement { - /** - * @return true iff this element is the bottom element. - */ - public boolean isBottom() { - return this instanceof Bottom; - } - - /** - * @return true iff this element is the neg element. - */ - public boolean isNeg() { - return this instanceof Neg; - } - - /** - * @return true iff this element is the zero element. - */ - public boolean isZero() { - return this instanceof Zero; - } - - /** - * @return true iff this element is the pos element. - */ - public boolean isPos() { - return this instanceof Pos; - } - - /** - * @return true iff this element is the leq element. - */ - public boolean isLeq() { - return this instanceof Leq; - } - - /** - * @return true iff this element is the geq element. - */ - public boolean isGeq() { - return this instanceof Geq; - } - - /** - * @return true iff this element is the top element. - */ - public boolean isTop() { - return this instanceof Top; - } - + /** + * @return true iff this element is the bottom element. + */ + public boolean isBottom() { + return this instanceof Bottom; + } + + /** + * @return true iff this element is the neg element. + */ + public boolean isNeg() { + return this instanceof Neg; + } + + /** + * @return true iff this element is the zero element. + */ + public boolean isZero() { + return this instanceof Zero; + } + + /** + * @return true iff this element is the pos element. + */ + public boolean isPos() { + return this instanceof Pos; + } + + /** + * @return true iff this element is the leq element. + */ + public boolean isLeq() { + return this instanceof Leq; + } + + /** + * @return true iff this element is the geq element. + */ + public boolean isGeq() { + return this instanceof Geq; + } + + /** + * @return true iff this element is the top element. + */ + public boolean isTop() { + return this instanceof Top; + } + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisLattice.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisLattice.java index b9bc8860453..0392a267ec4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisLattice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/SignAnalysisLattice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import java.util.Iterator; @@ -7,143 +10,137 @@ /** * A lattice for sign analysis of integers. - * + * * @author Dominic Scheurer */ public class SignAnalysisLattice extends AbstractDomainLattice { - - /** - * All elements of this abstract domain. - */ - public static final AbstractDomainElement[] ABSTRACT_DOMAIN_ELEMS = { - Bottom.getInstance(), - Neg.getInstance(), - Zero.getInstance(), - Pos.getInstance(), - Leq.getInstance(), - Geq.getInstance(), - Top.getInstance() - }; - - /** - * The singleton instance of this lattice. - */ - private static final SignAnalysisLattice INSTANCE = new SignAnalysisLattice(); - - /** - * Private constructor (singleton!). - */ - private SignAnalysisLattice() {} - - /** - * @return The singleton instance of this lattice. - */ - public static SignAnalysisLattice getInstance() { - return INSTANCE; - } - - @Override - public AbstractDomainElement join(AbstractDomainElement elem1, - AbstractDomainElement elem2) { - - if (!(elem1 instanceof SignAnalysisDomainElem) || - !(elem2 instanceof SignAnalysisDomainElem)) { - throw new IllegalArgumentException("Expected arguments of the abstract domain of sign analysis."); - } - - SignAnalysisDomainElem a = (SignAnalysisDomainElem) elem1; - SignAnalysisDomainElem b = (SignAnalysisDomainElem) elem2; - - if (a.isTop() || b.isTop()) { - return Top.getInstance(); - } - - if (a.isLeq()) { - if (b.isGeq() || b.isPos()) { - return Top.getInstance(); - } else { - return Leq.getInstance(); - } - } - - if (a.isGeq()) { - if (b.isLeq() || b.isNeg()) { - return Top.getInstance(); - } else { - return Geq.getInstance(); - } - } - - if (b.isLeq()) { - if (a.isGeq() || a.isPos()) { - return Top.getInstance(); - } else { - return Leq.getInstance(); - } - } - - if (b.isGeq()) { - if (a.isLeq() || a.isNeg()) { - return Top.getInstance(); - } else { - return Geq.getInstance(); - } - } - - if (a.isNeg()) { - if (b.isZero()) { - return Leq.getInstance(); - } else if (b.isPos()) { - return Top.getInstance(); - } else { - return Neg.getInstance(); - } - } - - if (a.isZero()) { - if (b.isNeg()) { - return Leq.getInstance(); - } else if (b.isPos()) { - return Geq.getInstance(); - } else { - return Zero.getInstance(); - } - } - - if (a.isPos()) { - if (b.isZero()) { - return Geq.getInstance(); - } else if (b.isNeg()) { + + /** + * All elements of this abstract domain. + */ + public static final AbstractDomainElement[] ABSTRACT_DOMAIN_ELEMS = + { Bottom.getInstance(), Neg.getInstance(), Zero.getInstance(), Pos.getInstance(), + Leq.getInstance(), Geq.getInstance(), Top.getInstance() }; + + /** + * The singleton instance of this lattice. + */ + private static final SignAnalysisLattice INSTANCE = new SignAnalysisLattice(); + + /** + * Private constructor (singleton!). + */ + private SignAnalysisLattice() {} + + /** + * @return The singleton instance of this lattice. + */ + public static SignAnalysisLattice getInstance() { + return INSTANCE; + } + + @Override + public AbstractDomainElement join(AbstractDomainElement elem1, AbstractDomainElement elem2) { + + if (!(elem1 instanceof SignAnalysisDomainElem) + || !(elem2 instanceof SignAnalysisDomainElem)) { + throw new IllegalArgumentException( + "Expected arguments of the abstract domain of sign analysis."); + } + + SignAnalysisDomainElem a = (SignAnalysisDomainElem) elem1; + SignAnalysisDomainElem b = (SignAnalysisDomainElem) elem2; + + if (a.isTop() || b.isTop()) { return Top.getInstance(); - } else { - return Pos.getInstance(); - } - } - - assert(a.isBottom()) : "Bug in sign lattice implementation."; - return b; - } - - @Override - public Iterator iterator() { - return new Iterator() { - - int pos = 0; - final int size = ABSTRACT_DOMAIN_ELEMS.length; - - @Override - public boolean hasNext() { - return pos < size - 1; - } - - @Override - public AbstractDomainElement next() { - return ABSTRACT_DOMAIN_ELEMS[pos++]; - } - - @Override - public void remove() {} - }; - } - + } + + if (a.isLeq()) { + if (b.isGeq() || b.isPos()) { + return Top.getInstance(); + } else { + return Leq.getInstance(); + } + } + + if (a.isGeq()) { + if (b.isLeq() || b.isNeg()) { + return Top.getInstance(); + } else { + return Geq.getInstance(); + } + } + + if (b.isLeq()) { + if (a.isGeq() || a.isPos()) { + return Top.getInstance(); + } else { + return Leq.getInstance(); + } + } + + if (b.isGeq()) { + if (a.isLeq() || a.isNeg()) { + return Top.getInstance(); + } else { + return Geq.getInstance(); + } + } + + if (a.isNeg()) { + if (b.isZero()) { + return Leq.getInstance(); + } else if (b.isPos()) { + return Top.getInstance(); + } else { + return Neg.getInstance(); + } + } + + if (a.isZero()) { + if (b.isNeg()) { + return Leq.getInstance(); + } else if (b.isPos()) { + return Geq.getInstance(); + } else { + return Zero.getInstance(); + } + } + + if (a.isPos()) { + if (b.isZero()) { + return Geq.getInstance(); + } else if (b.isNeg()) { + return Top.getInstance(); + } else { + return Pos.getInstance(); + } + } + + assert (a.isBottom()) : "Bug in sign lattice implementation."; + return b; + } + + @Override + public Iterator iterator() { + return new Iterator() { + + int pos = 0; + final int size = ABSTRACT_DOMAIN_ELEMS.length; + + @Override + public boolean hasNext() { + return pos < size - 1; + } + + @Override + public AbstractDomainElement next() { + return ABSTRACT_DOMAIN_ELEMS[pos++]; + } + + @Override + public void remove() {} + }; + } + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Top.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Top.java index 1bacf7bd28f..799751cbe32 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Top.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Top.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Top element of the sign lattice, representing - * all integers. - * + * The Top element of the sign lattice, representing all integers. + * * @author Dominic Scheurer */ public class Top extends SignAnalysisDomainElem { - private static final Top INSTANCE = new Top(); - - private Top() {} - - public static Top getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("top"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return tb.inInt(varOrConst); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Top INSTANCE = new Top(); + + private Top() {} + + public static Top getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("top"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return tb.inInt(varOrConst); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Zero.java b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Zero.java index d22f2f04e6d..c0271a849e2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Zero.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/axiom_abstraction/signanalysis/Zero.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.axiom_abstraction.signanalysis; import de.uka.ilkd.key.java.Services; @@ -6,35 +9,34 @@ import de.uka.ilkd.key.logic.TermBuilder; /** - * The Zero element of the sign lattice, representing - * only the number 0. - * + * The Zero element of the sign lattice, representing only the number 0. + * * @author Dominic Scheurer */ public class Zero extends SignAnalysisDomainElem { - private static final Zero INSTANCE = new Zero(); - - private Zero() {} - - public static Zero getInstance() { - return INSTANCE; - } - - @Override - public Name name() { - return new Name("zero"); - } - - @Override - public Term getDefiningAxiom(Term varOrConst, Services services) { - TermBuilder tb = services.getTermBuilder(); - return services.getTermBuilder().equals(varOrConst, tb.zero()); - } - - @Override - public String toParseableString(Services services) { - return toString(); - } + private static final Zero INSTANCE = new Zero(); + + private Zero() {} + + public static Zero getInstance() { + return INSTANCE; + } + + @Override + public Name name() { + return new Name("zero"); + } + + @Override + public Term getDefiningAxiom(Term varOrConst, Services services) { + TermBuilder tb = services.getTermBuilder(); + return services.getTermBuilder().equals(varOrConst, tb.zero()); + } + + @Override + public String toParseableString(Services services) { + return toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractProofControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractProofControl.java index eeb418a8537..676177c7d43 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractProofControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractProofControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.util.Iterator; @@ -36,27 +39,29 @@ /** * Provides a basic implementation of {@link ProofControl}. + * * @author Martin Hentschel */ public abstract class AbstractProofControl implements ProofControl { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractProofControl.class); /** - * Optionally, the {@link RuleCompletionHandler} to use. - */ - private final RuleCompletionHandler ruleCompletionHandler; + * Optionally, the {@link RuleCompletionHandler} to use. + */ + private final RuleCompletionHandler ruleCompletionHandler; - /** - * The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - */ - private final ProverTaskListener defaultProverTaskListener; + /** + * The default {@link ProverTaskListener} which will be added to all started + * {@link ApplyStrategy} instances. + */ + private final ProverTaskListener defaultProverTaskListener; - /** - * Contains all available {@link AutoModeListener}. - */ - private final List autoModeListener = new LinkedList<>(); + /** + * Contains all available {@link AutoModeListener}. + */ + private final List autoModeListener = new LinkedList<>(); - private boolean minimizeInteraction; // minimize user interaction + private boolean minimizeInteraction; // minimize user interaction /** * @@ -64,44 +69,48 @@ public abstract class AbstractProofControl implements ProofControl { protected final List interactionListeners = new LinkedList<>(); /** - * Constructor. - * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - */ - public AbstractProofControl(ProverTaskListener defaultProverTaskListener) { - this(defaultProverTaskListener, null); - } - - /** - * Constructor. - * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. - */ - public AbstractProofControl(ProverTaskListener defaultProverTaskListener, - RuleCompletionHandler ruleCompletionHandler) { - this.ruleCompletionHandler = ruleCompletionHandler; - this.defaultProverTaskListener = defaultProverTaskListener; - } - - /** - * {@inheritDoc} - */ - @Override - public ProverTaskListener getDefaultProverTaskListener() { - return defaultProverTaskListener; - } - - @Override - public boolean isMinimizeInteraction() { - return minimizeInteraction; - } - - @Override - public void setMinimizeInteraction(boolean minimizeInteraction) { - this.minimizeInteraction = minimizeInteraction; - } - - @Override - public ImmutableList getBuiltInRule(Goal focusedGoal, PosInOccurrence pos) { + * Constructor. + * + * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added + * to all started {@link ApplyStrategy} instances. + */ + public AbstractProofControl(ProverTaskListener defaultProverTaskListener) { + this(defaultProverTaskListener, null); + } + + /** + * Constructor. + * + * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added + * to all started {@link ApplyStrategy} instances. + * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. + */ + public AbstractProofControl(ProverTaskListener defaultProverTaskListener, + RuleCompletionHandler ruleCompletionHandler) { + this.ruleCompletionHandler = ruleCompletionHandler; + this.defaultProverTaskListener = defaultProverTaskListener; + } + + /** + * {@inheritDoc} + */ + @Override + public ProverTaskListener getDefaultProverTaskListener() { + return defaultProverTaskListener; + } + + @Override + public boolean isMinimizeInteraction() { + return minimizeInteraction; + } + + @Override + public void setMinimizeInteraction(boolean minimizeInteraction) { + this.minimizeInteraction = minimizeInteraction; + } + + @Override + public ImmutableList getBuiltInRule(Goal focusedGoal, PosInOccurrence pos) { ImmutableList rules = ImmutableSLList.nil(); for (RuleApp ruleApp : focusedGoal.ruleAppIndex().getBuiltInRules(focusedGoal, pos)) { @@ -116,62 +125,53 @@ public ImmutableList getBuiltInRule(Goal focusedGoal, PosInOccurren @Override - public ImmutableList getNoFindTaclet(Goal focusedGoal) { - return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex(). - getNoFindTaclet(TacletFilter.TRUE, - focusedGoal.proof().getServices()), null); + public ImmutableList getNoFindTaclet(Goal focusedGoal) { + return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex() + .getNoFindTaclet(TacletFilter.TRUE, focusedGoal.proof().getServices()), null); } @Override - public ImmutableList getFindTaclet(Goal focusedGoal, PosInOccurrence pos) { + public ImmutableList getFindTaclet(Goal focusedGoal, PosInOccurrence pos) { if (pos != null && focusedGoal != null) { LOGGER.debug("NoPosTacletApp: Looking for applicables rule at node {}", focusedGoal.node().serialNr()); - return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex(). - getFindTaclet(TacletFilter.TRUE, - pos, - focusedGoal.proof().getServices()), pos); + return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex() + .getFindTaclet(TacletFilter.TRUE, pos, focusedGoal.proof().getServices()), pos); } return ImmutableSLList.nil(); } @Override - public ImmutableList getRewriteTaclet(Goal focusedGoal, PosInOccurrence pos) { + public ImmutableList getRewriteTaclet(Goal focusedGoal, PosInOccurrence pos) { if (pos != null) { - return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex(). - getRewriteTaclet(TacletFilter.TRUE, - pos, - focusedGoal.proof().getServices()), pos); + return filterTaclet(focusedGoal, focusedGoal.ruleAppIndex().getRewriteTaclet( + TacletFilter.TRUE, pos, focusedGoal.proof().getServices()), pos); } return ImmutableSLList.nil(); } /** - * takes NoPosTacletApps as arguments and returns a duplicate free list of - * the contained TacletApps + * takes NoPosTacletApps as arguments and returns a duplicate free list of the contained + * TacletApps */ - private ImmutableList filterTaclet(Goal focusedGoal, ImmutableList tacletInstances, PosInOccurrence pos) { + private ImmutableList filterTaclet(Goal focusedGoal, + ImmutableList tacletInstances, PosInOccurrence pos) { java.util.HashSet applicableRules = new java.util.HashSet<>(); ImmutableList result = ImmutableSLList.nil(); for (NoPosTacletApp app : tacletInstances) { if (isMinimizeInteraction()) { - ImmutableList ifCandidates - = app.findIfFormulaInstantiations( - focusedGoal.sequent(), - focusedGoal.proof().getServices()); + ImmutableList ifCandidates = app.findIfFormulaInstantiations( + focusedGoal.sequent(), focusedGoal.proof().getServices()); if (ifCandidates.isEmpty()) { continue; // skip this app } if (ifCandidates.size() == 1 && pos != null) { TacletApp a = ifCandidates.head(); - ImmutableList ifs - = a.ifFormulaInstantiations(); - if (ifs != null && ifs.size() == 1 - && ifs.head() instanceof IfFormulaInstSeq) { + ImmutableList ifs = a.ifFormulaInstantiations(); + if (ifs != null && ifs.size() == 1 && ifs.head() instanceof IfFormulaInstSeq) { IfFormulaInstSeq ifis = (IfFormulaInstSeq) ifs.head(); - if (ifis.toPosInOccurrence().equals( - pos.topLevel())) { + if (ifis.toPosInOccurrence().equals(pos.topLevel())) { continue; // skip app if find and if same formula } } @@ -189,8 +189,7 @@ private ImmutableList filterTaclet(Goal focusedGoal, ImmutableList applics = - getAppsForName(goal, taclet.name().toString(), pos); + ImmutableSet applics = getAppsForName(goal, taclet.name().toString(), pos); if (applics.size() == 0) { return false; } @@ -201,46 +200,44 @@ public boolean selectedTaclet(ImmutableSet applics, Goal goal) { final Services services = goal.proof().getServices(); Iterator it = applics.iterator(); if (applics.size() == 1) { - TacletApp firstApp = it.next(); - boolean ifSeqInteraction = - !firstApp.taclet().ifSequent().isEmpty() ; + TacletApp firstApp = it.next(); + boolean ifSeqInteraction = !firstApp.taclet().ifSequent().isEmpty(); if (isMinimizeInteraction() && !firstApp.complete()) { ImmutableList ifSeqCandidates = - firstApp.findIfFormulaInstantiations(goal.sequent(), - services); + firstApp.findIfFormulaInstantiations(goal.sequent(), services); if (ifSeqCandidates.size() == 1) { ifSeqInteraction = false; firstApp = ifSeqCandidates.head(); } TacletApp tmpApp = - firstApp.tryToInstantiate(services.getOverlay(goal.getLocalNamespaces())); - if (tmpApp != null) firstApp = tmpApp; + firstApp.tryToInstantiate(services.getOverlay(goal.getLocalNamespaces())); + if (tmpApp != null) + firstApp = tmpApp; } - if (ifSeqInteraction || !firstApp.complete()) { - LinkedList l = new LinkedList<>(); - l.add(firstApp); - TacletInstantiationModel[] models = completeAndApplyApp(l, goal); - completeAndApplyTacletMatch(models, goal); - } else { - applyInteractive(firstApp, goal); - } - } else if (applics.size() > 1) { + if (ifSeqInteraction || !firstApp.complete()) { + LinkedList l = new LinkedList<>(); + l.add(firstApp); + TacletInstantiationModel[] models = completeAndApplyApp(l, goal); + completeAndApplyTacletMatch(models, goal); + } else { + applyInteractive(firstApp, goal); + } + } else if (applics.size() > 1) { java.util.List appList = new java.util.LinkedList<>(); - for (int i = 0; i < applics.size(); i++) { - TacletApp rapp = it.next(); + for (int i = 0; i < applics.size(); i++) { + TacletApp rapp = it.next(); appList.add(rapp); } - if (appList.size()==0) { - assert false; - return false; + if (appList.size() == 0) { + assert false; + return false; } - TacletInstantiationModel[] models = completeAndApplyApp( - appList, goal); + TacletInstantiationModel[] models = completeAndApplyApp(appList, goal); completeAndApplyTacletMatch(models, goal); @@ -290,35 +287,29 @@ protected void emitInteractiveRuleApplication(Node node, RuleApp app) { } /** - * collects all Taclet applications at the given position of the specified - * taclet + * collects all Taclet applications at the given position of the specified taclet * * @param goal the Goal for which the applications should be returned - * @param name the String with the taclet names whose applications are - * looked for + * @param name the String with the taclet names whose applications are looked for * @param pos the PosInOccurrence describing the position - * @return a list of all found rule applications of the given rule at - * position pos + * @return a list of all found rule applications of the given rule at position pos */ - protected ImmutableSet getAppsForName(Goal goal, String name, - PosInOccurrence pos) { + protected ImmutableSet getAppsForName(Goal goal, String name, PosInOccurrence pos) { return getAppsForName(goal, name, pos, TacletFilter.TRUE); } /** - * collects all taclet applications for the given position and taclet - * (identified by its name) matching the filter condition + * collects all taclet applications for the given position and taclet (identified by its name) + * matching the filter condition * * @param goal the Goal for which the applications should be returned - * @param name the String with the taclet names whose applications are - * looked for + * @param name the String with the taclet names whose applications are looked for * @param pos the PosInOccurrence describing the position * @param filter the TacletFilter expressing restrictions - * @return a list of all found rule applications of the given rule at - * position pos passing the filter + * @return a list of all found rule applications of the given rule at position pos + * passing the filter */ - protected ImmutableSet getAppsForName(Goal goal, String name, - PosInOccurrence pos, + protected ImmutableSet getAppsForName(Goal goal, String name, PosInOccurrence pos, TacletFilter filter) { Services services = goal.proof().getServices(); ImmutableSet result = DefaultImmutableSet.nil(); @@ -326,14 +317,11 @@ protected ImmutableSet getAppsForName(Goal goal, String name, final RuleAppIndex index = goal.ruleAppIndex(); if (pos == null) { - for (NoPosTacletApp noPosTacletApp : index.getNoFindTaclet(filter, - services)) { + for (NoPosTacletApp noPosTacletApp : index.getNoFindTaclet(filter, services)) { fittingApps = fittingApps.prepend(noPosTacletApp); } } else { - fittingApps = index.getTacletAppAt(filter, - pos, - services); + fittingApps = index.getTacletAppAt(filter, pos, services); } // filter fitting applications @@ -345,7 +333,8 @@ protected ImmutableSet getAppsForName(Goal goal, String name, return result; } - public TacletInstantiationModel[] completeAndApplyApp(java.util.List apps, Goal goal) { + public TacletInstantiationModel[] completeAndApplyApp(java.util.List apps, + Goal goal) { TacletInstantiationModel[] origInstModels = new TacletInstantiationModel[apps.size()]; LinkedList recentInstModels = new LinkedList<>(); @@ -353,16 +342,14 @@ public TacletInstantiationModel[] completeAndApplyApp(java.util.List for (final TacletApp tA : apps) { origInstModels[appCounter] = createModel(tA, goal); - if (InstantiationFileHandler.hasInstantiationListsFor(tA - .taclet())) { - for (final List instantiations : - InstantiationFileHandler.getInstantiationListsFor(tA.taclet())) { + if (InstantiationFileHandler.hasInstantiationListsFor(tA.taclet())) { + for (final List instantiations : InstantiationFileHandler + .getInstantiationListsFor(tA.taclet())) { int start = tA.instantiations().size(); - if (origInstModels[appCounter].tableModel().getRowCount() - start == - instantiations.size()) { - TacletInstantiationModel m = createModel(tA, - goal); + if (origInstModels[appCounter].tableModel().getRowCount() + - start == instantiations.size()) { + TacletInstantiationModel m = createModel(tA, goal); recentInstModels.add(m); for (final String inst : instantiations) { m.tableModel().setValueAt(inst, start++, 1); @@ -373,8 +360,8 @@ public TacletInstantiationModel[] completeAndApplyApp(java.util.List appCounter++; } - TacletInstantiationModel[] models = new TacletInstantiationModel[ - origInstModels.length + recentInstModels.size()]; + TacletInstantiationModel[] models = + new TacletInstantiationModel[origInstModels.length + recentInstModels.size()]; int i; for (i = 0; i < origInstModels.length; i++) { models[i] = origInstModels[i]; @@ -388,46 +375,45 @@ public TacletInstantiationModel[] completeAndApplyApp(java.util.List } public TacletInstantiationModel createModel(TacletApp app, Goal goal) { - final Proof proof = goal.proof(); + final Proof proof = goal.proof(); - return new TacletInstantiationModel( - app, goal.sequent(), - goal.getLocalNamespaces(), - proof.abbreviations(), - goal); + return new TacletInstantiationModel(app, goal.sequent(), goal.getLocalNamespaces(), + proof.abbreviations(), goal); } @Override - public void selectedBuiltInRule(Goal goal, BuiltInRule rule, PosInOccurrence pos, boolean forced, boolean interactive) { - assert goal != null; - - ImmutableSet set = getBuiltInRuleApp(goal, rule, pos); - if (set.size() > 1) { - LOGGER.warn("Expected a single app. If it is OK that there are more than one built-in rule apps. " + - "You have to add a selection dialog here"); - LOGGER.warn("Ambiguous applications, taking the first in list."); - } + public void selectedBuiltInRule(Goal goal, BuiltInRule rule, PosInOccurrence pos, + boolean forced, boolean interactive) { + assert goal != null; + + ImmutableSet set = getBuiltInRuleApp(goal, rule, pos); + if (set.size() > 1) { + LOGGER.warn( + "Expected a single app. If it is OK that there are more than one built-in rule apps. " + + "You have to add a selection dialog here"); + LOGGER.warn("Ambiguous applications, taking the first in list."); + } - IBuiltInRuleApp app = set.iterator().next(); + IBuiltInRuleApp app = set.iterator().next(); - if (!app.complete()) { - app = completeBuiltInRuleApp(app, goal, forced); - } + if (!app.complete()) { + app = completeBuiltInRuleApp(app, goal, forced); + } - if (app != null && app.rule() == rule) { - if (interactive) { - applyInteractive(app, goal); - } else { - goal.apply(app); - } + if (app != null && app.rule() == rule) { + if (interactive) { + applyInteractive(app, goal); + } else { + goal.apply(app); + } - return; - } + return; + } } /** - * collects all built-in rule applications for the given rule that are - * applicable at position 'pos' and the current user constraint + * collects all built-in rule applications for the given rule that are applicable at position + * 'pos' and the current user constraint * * @param rule the BuiltInRule for which the applications are collected * @param pos the PosInSequent the position information @@ -438,8 +424,8 @@ public ImmutableSet getBuiltInRuleApp(Goal focusedGoal, BuiltIn ImmutableSet result = DefaultImmutableSet.nil(); - for (final IBuiltInRuleApp app : focusedGoal.ruleAppIndex(). - getBuiltInRules(focusedGoal, pos)) { + for (final IBuiltInRuleApp app : focusedGoal.ruleAppIndex().getBuiltInRules(focusedGoal, + pos)) { if (app.rule() == rule) { result = result.add(app); } @@ -449,25 +435,23 @@ public ImmutableSet getBuiltInRuleApp(Goal focusedGoal, BuiltIn } /** - * collects all applications of a rule given by its name at a give position - * in the sequent + * collects all applications of a rule given by its name at a give position in the sequent * - * @param name the name of the BuiltInRule for which applications are - * collected. - * @param pos the position in the sequent where the BuiltInRule should be - * applied + * @param name the name of the BuiltInRule for which applications are collected. + * @param pos the position in the sequent where the BuiltInRule should be applied * @return a SetOf with all possible applications of the rule */ - protected ImmutableSet getBuiltInRuleAppsForName(Goal focusedGoal, String name, PosInOccurrence pos) { + protected ImmutableSet getBuiltInRuleAppsForName(Goal focusedGoal, String name, + PosInOccurrence pos) { ImmutableSet result = DefaultImmutableSet.nil(); ImmutableList match = ImmutableSLList.nil(); - //get all possible rules for current position in sequent + // get all possible rules for current position in sequent ImmutableList list = getBuiltInRule(focusedGoal, pos); Iterator iter = list.iterator(); - //find all rules that match given name + // find all rules that match given name while (iter.hasNext()) { BuiltInRule rule = iter.next(); if (rule.name().toString().equals(name)) { @@ -477,7 +461,7 @@ protected ImmutableSet getBuiltInRuleAppsForName(Goal focusedGo iter = match.iterator(); - //find all applications for matched rules + // find all applications for matched rules while (iter.hasNext()) { result = result.union(getBuiltInRuleApp(focusedGoal, iter.next(), pos)); } @@ -491,38 +475,39 @@ protected ImmutableSet getBuiltInRuleAppsForName(Goal focusedGo * {@inheritDoc} */ protected void completeAndApplyTacletMatch(TacletInstantiationModel[] models, Goal goal) { - if (ruleCompletionHandler != null) { - ruleCompletionHandler.completeAndApplyTacletMatch(models, goal); - } + if (ruleCompletionHandler != null) { + ruleCompletionHandler.completeAndApplyTacletMatch(models, goal); + } } /** * {@inheritDoc} */ - protected IBuiltInRuleApp completeBuiltInRuleApp(IBuiltInRuleApp app, Goal goal, boolean forced) { - if (ruleCompletionHandler == null) { - return completeBuiltInRuleAppByDefault(app, goal, forced); - } - else { - IBuiltInRuleApp result = ruleCompletionHandler.completeBuiltInRuleApp(app, goal, forced); - if (result != null) { - if (result.complete()) { - return result; - } - else { + protected IBuiltInRuleApp completeBuiltInRuleApp(IBuiltInRuleApp app, Goal goal, + boolean forced) { + if (ruleCompletionHandler == null) { + return completeBuiltInRuleAppByDefault(app, goal, forced); + } else { + IBuiltInRuleApp result = + ruleCompletionHandler.completeBuiltInRuleApp(app, goal, forced); + if (result != null) { + if (result.complete()) { + return result; + } else { + return completeBuiltInRuleAppByDefault(app, goal, forced); + } + } else { return completeBuiltInRuleAppByDefault(app, goal, forced); - } - } - else { - return completeBuiltInRuleAppByDefault(app, goal, forced); - } - } + } + } } /** - * Default implementation of {@link RuleCompletionHandler#completeBuiltInRuleApp(IBuiltInRuleApp, Goal, boolean)}. + * Default implementation of + * {@link RuleCompletionHandler#completeBuiltInRuleApp(IBuiltInRuleApp, Goal, boolean)}. */ - public static IBuiltInRuleApp completeBuiltInRuleAppByDefault(IBuiltInRuleApp app, Goal goal, boolean forced) { + public static IBuiltInRuleApp completeBuiltInRuleAppByDefault(IBuiltInRuleApp app, Goal goal, + boolean forced) { app = forced ? app.forceInstantiate(goal) : app.tryToInstantiate(goal); // cannot complete that app return app.complete() ? app : null; @@ -533,7 +518,7 @@ public static IBuiltInRuleApp completeBuiltInRuleAppByDefault(IBuiltInRuleApp ap */ @Override public boolean isAutoModeSupported(Proof proof) { - return proof != null && !proof.isDisposed(); // All not disposed proofs are supported. + return proof != null && !proof.isDisposed(); // All not disposed proofs are supported. } /** @@ -541,9 +526,9 @@ public boolean isAutoModeSupported(Proof proof) { */ @Override public void addAutoModeListener(AutoModeListener p) { - if (p != null) { - autoModeListener.add(p); - } + if (p != null) { + autoModeListener.add(p); + } } /** @@ -551,29 +536,31 @@ public void addAutoModeListener(AutoModeListener p) { */ @Override public void removeAutoModeListener(AutoModeListener p) { - if (p != null) { - autoModeListener.remove(p); - } + if (p != null) { + autoModeListener.remove(p); + } } /** * fires the event that automatic execution has started */ protected void fireAutoModeStarted(ProofEvent e) { - AutoModeListener[] listener = autoModeListener.toArray(new AutoModeListener[autoModeListener.size()]); - for (AutoModeListener aListenerList : listener) { - aListenerList.autoModeStarted(e); - } + AutoModeListener[] listener = + autoModeListener.toArray(new AutoModeListener[autoModeListener.size()]); + for (AutoModeListener aListenerList : listener) { + aListenerList.autoModeStarted(e); + } } /** * fires the event that automatic execution has stopped */ protected void fireAutoModeStopped(ProofEvent e) { - AutoModeListener[] listener = autoModeListener.toArray(new AutoModeListener[autoModeListener.size()]); - for (AutoModeListener aListenerList : listener) { - aListenerList.autoModeStopped(e); - } + AutoModeListener[] listener = + autoModeListener.toArray(new AutoModeListener[autoModeListener.size()]); + for (AutoModeListener aListenerList : listener) { + aListenerList.autoModeStopped(e); + } } /** @@ -581,7 +568,7 @@ protected void fireAutoModeStopped(ProofEvent e) { */ @Override public void startAutoMode(Proof proof) { - startAutoMode(proof, proof.openEnabledGoals()); + startAutoMode(proof, proof.openEnabledGoals()); } /** @@ -589,8 +576,8 @@ public void startAutoMode(Proof proof) { */ @Override public void startAndWaitForAutoMode(Proof proof) { - startAutoMode(proof); - waitWhileAutoMode(); + startAutoMode(proof); + waitWhileAutoMode(); } /** @@ -598,8 +585,8 @@ public void startAndWaitForAutoMode(Proof proof) { */ @Override public void startAndWaitForAutoMode(Proof proof, ImmutableList goals) { - startAutoMode(proof, goals); - waitWhileAutoMode(); + startAutoMode(proof, goals); + waitWhileAutoMode(); } /** @@ -607,8 +594,8 @@ public void startAndWaitForAutoMode(Proof proof, ImmutableList goals) { */ @Override public void stopAndWaitAutoMode() { - stopAutoMode(); - waitWhileAutoMode(); + stopAutoMode(); + waitWhileAutoMode(); } /** @@ -616,16 +603,16 @@ public void stopAndWaitAutoMode() { */ @Override public void startAutoMode(Proof proof, ImmutableList goals) { - startAutoMode(proof, goals, null); + startAutoMode(proof, goals, null); } - protected abstract void startAutoMode(Proof proof, ImmutableList goals, ProverTaskListener ptl); + protected abstract void startAutoMode(Proof proof, ImmutableList goals, + ProverTaskListener ptl); /** - * starts the execution of rules with active strategy. Restrict the - * application of rules to a particular goal and (for - * focus!=null) to a particular subterm or subformula of that - * goal + * starts the execution of rules with active strategy. Restrict the application of rules to a + * particular goal and (for focus!=null) to a particular subterm or subformula of + * that goal */ @Override public void startFocussedAutoMode(PosInOccurrence focus, Goal goal) { @@ -634,12 +621,13 @@ public void startFocussedAutoMode(PosInOccurrence focus, Goal goal) { final AutomatedRuleApplicationManager realManager = goal.getRuleAppManager(); goal.setRuleAppManager(null); - final AutomatedRuleApplicationManager focusManager - = new FocussedRuleApplicationManager(realManager, goal, focus); + final AutomatedRuleApplicationManager focusManager = + new FocussedRuleApplicationManager(realManager, goal, focus); goal.setRuleAppManager(focusManager); } - startAutoMode(goal.proof(), ImmutableSLList.nil().prepend(goal), new FocussedAutoModeTaskListener(goal.proof())); + startAutoMode(goal.proof(), ImmutableSLList.nil().prepend(goal), + new FocussedAutoModeTaskListener(goal.proof())); } /** @@ -649,16 +637,14 @@ public static final class FocussedAutoModeTaskListener implements ProverTaskList private final Proof proof; public FocussedAutoModeTaskListener(Proof proof) { - this.proof = proof; + this.proof = proof; } @Override - public void taskStarted(TaskStartedInfo info) { - } + public void taskStarted(TaskStartedInfo info) {} @Override - public void taskProgress(int position) { - } + public void taskProgress(int position) {} @Override public void taskFinished(TaskFinishedInfo info) { @@ -671,8 +657,7 @@ public void taskFinished(TaskFinishedInfo info) { final DelegationBasedAutomatedRuleApplicationManager focusManager = // (DelegationBasedAutomatedRuleApplicationManager) ruleAppManager; goal.setRuleAppManager(null); - final AutomatedRuleApplicationManager realManager = focusManager - .getDelegate(); + final AutomatedRuleApplicationManager realManager = focusManager.getDelegate(); realManager.clearCache(); goal.setRuleAppManager(realManager); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractUserInterfaceControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractUserInterfaceControl.java index f9db5587f98..960f05bb640 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractUserInterfaceControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/AbstractUserInterfaceControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.io.File; @@ -29,31 +32,34 @@ /** * Provides a basic implementation of {@link UserInterfaceControl}. + * * @author Martin Hentschel */ -public abstract class AbstractUserInterfaceControl implements UserInterfaceControl, ProblemLoaderControl, ProverTaskListener { +public abstract class AbstractUserInterfaceControl + implements UserInterfaceControl, ProblemLoaderControl, ProverTaskListener { private int numOfInvokedMacros = 0; - + /** * The registered {@link ProverTaskListener}. */ - private final List proverTaskListener = new LinkedList(); - + private final List proverTaskListener = + new LinkedList(); + /** * Constructor. */ public AbstractUserInterfaceControl() { - addProverTaskListener(new ProofMacroListenerAdapter()); + addProverTaskListener(new ProofMacroListenerAdapter()); } - + /** * {@inheritDoc} */ @Override public void addProverTaskListener(ProverTaskListener ptl) { - if (ptl != null) { - proverTaskListener.add(ptl); - } + if (ptl != null) { + proverTaskListener.add(ptl); + } } /** @@ -61,90 +67,99 @@ public void addProverTaskListener(ProverTaskListener ptl) { */ @Override public void removeProverTaskListener(ProverTaskListener ptl) { - if (ptl != null) { - proverTaskListener.remove(ptl); - } + if (ptl != null) { + proverTaskListener.remove(ptl); + } } /** * Fires the event {@link ProverTaskListener#taskStarted(TaskStartedInfo)} to all listener. - * @param info the {@link TaskStartedInfo} containing general information about the task that is just about to start + * + * @param info the {@link TaskStartedInfo} containing general information about the task that is + * just about to start */ protected void fireTaskStarted(TaskStartedInfo info) { - ProverTaskListener[] listener = proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); - for (ProverTaskListener l : listener) { - l.taskStarted(info); - } + ProverTaskListener[] listener = + proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); + for (ProverTaskListener l : listener) { + l.taskStarted(info); + } } /** * Fires the event {@link ProverTaskListener#taskProgress(int)} to all listener. + * * @param position The current position. */ protected void fireTaskProgress(int position) { - ProverTaskListener[] listener = proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); - for (ProverTaskListener l : listener) { - l.taskProgress(position); - } + ProverTaskListener[] listener = + proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); + for (ProverTaskListener l : listener) { + l.taskProgress(position); + } } /** * Fires the event {@link ProverTaskListener#taskFinished(TaskFinishedInfo)} to all listener. + * * @param info The {@link TaskFinishedInfo}. */ protected void fireTaskFinished(TaskFinishedInfo info) { - ProverTaskListener[] listener = proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); - for (ProverTaskListener l : listener) { - l.taskFinished(info); - } + ProverTaskListener[] listener = + proverTaskListener.toArray(new ProverTaskListener[proverTaskListener.size()]); + for (ProverTaskListener l : listener) { + l.taskFinished(info); + } } - @Override - public void taskStarted(TaskStartedInfo info) { - fireTaskStarted(info); - } + @Override + public void taskStarted(TaskStartedInfo info) { + fireTaskStarted(info); + } - @Override - public void taskProgress(int position) { - fireTaskProgress(position); - } + @Override + public void taskProgress(int position) { + fireTaskProgress(position); + } - @Override - public void taskFinished(TaskFinishedInfo info) { - fireTaskFinished(info); - } + @Override + public void taskFinished(TaskFinishedInfo info) { + fireTaskFinished(info); + } - /** + /** * {@inheritDoc} */ @Override - public Proof createProof(InitConfig initConfig, ProofOblInput input) throws ProofInputException { - ProblemInitializer init = createProblemInitializer(initConfig.getProfile()); - ProofAggregate proofList = init.startProver(initConfig, input); - createProofEnvironmentAndRegisterProof(input, proofList, initConfig); - return proofList.getFirstProof(); + public Proof createProof(InitConfig initConfig, ProofOblInput input) + throws ProofInputException { + ProblemInitializer init = createProblemInitializer(initConfig.getProfile()); + ProofAggregate proofList = init.startProver(initConfig, input); + createProofEnvironmentAndRegisterProof(input, proofList, initConfig); + return proofList.getFirstProof(); } /** * registers the proof aggregate at the UI - * + * * @param proofOblInput the {@link ProofOblInput} - * @param proofList the {@link ProofAggregate} + * @param proofList the {@link ProofAggregate} * @param initConfig the {@link InitConfig} to be used * @return the new {@link ProofEnvironment} where the {@link ProofAggregate} has been registered */ - protected abstract ProofEnvironment createProofEnvironmentAndRegisterProof(ProofOblInput proofOblInput, ProofAggregate proofList, InitConfig initConfig); + protected abstract ProofEnvironment createProofEnvironmentAndRegisterProof( + ProofOblInput proofOblInput, ProofAggregate proofList, InitConfig initConfig); /** * {@inheritDoc} */ @Override public void proofCreated(ProblemInitializer sender, ProofAggregate proofAggregate) { - // Nothing to do + // Nothing to do } - + public boolean isAtLeastOneMacroRunning() { - return numOfInvokedMacros != 0; + return numOfInvokedMacros != 0; } protected void macroStarted(TaskStartedInfo info) { @@ -154,9 +169,9 @@ protected void macroStarted(TaskStartedInfo info) { protected synchronized void macroFinished(final ProofMacroFinishedInfo info) { if (numOfInvokedMacros > 0) { numOfInvokedMacros--; - } - else { - Logger.getLogger(this.getClass().getName(), "Number of running macros became negative."); + } else { + Logger.getLogger(this.getClass().getName(), + "Number of running macros became negative."); } } @@ -178,53 +193,47 @@ public void taskProgress(int position) { @Override public void taskFinished(TaskFinishedInfo info) { if (info instanceof ProofMacroFinishedInfo) { - macroFinished((ProofMacroFinishedInfo)info); + macroFinished((ProofMacroFinishedInfo) info); } } } - + /** * {@inheritDoc} */ @Override - public AbstractProblemLoader load(Profile profile, - File file, - List classPath, - File bootClassPath, - List includes, - Properties poPropertiesToForce, - boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { - AbstractProblemLoader loader = null; - try { - loader = new SingleThreadProblemLoader(file, classPath, bootClassPath, includes, profile, forceNewProfileOfNewProofs, - this, false, poPropertiesToForce); - loader.load(); - return loader; - } - catch(ProblemLoaderException e) { - if (loader != null && loader.getProof() != null) { - loader.getProof().dispose(); - } - // rethrow that exception - throw e; - } - catch (Throwable e) { - if (loader != null && loader.getProof() != null) { - loader.getProof().dispose(); - } - throw new ProblemLoaderException(loader, e); - } + public AbstractProblemLoader load(Profile profile, File file, List classPath, + File bootClassPath, List includes, Properties poPropertiesToForce, + boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { + AbstractProblemLoader loader = null; + try { + loader = new SingleThreadProblemLoader(file, classPath, bootClassPath, includes, + profile, forceNewProfileOfNewProofs, this, false, poPropertiesToForce); + loader.load(); + return loader; + } catch (ProblemLoaderException e) { + if (loader != null && loader.getProof() != null) { + loader.getProof().dispose(); + } + // rethrow that exception + throw e; + } catch (Throwable e) { + if (loader != null && loader.getProof() != null) { + loader.getProof().dispose(); + } + throw new ProblemLoaderException(loader, e); + } } /** *

    - * Creates a new {@link ProblemInitializer} instance which is configured - * for this {@link UserInterfaceControl}. + * Creates a new {@link ProblemInitializer} instance which is configured for this + * {@link UserInterfaceControl}. *

    *

    - * This method is used by nearly all Eclipse based product that - * uses KeY. + * This method is used by nearly all Eclipse based product that uses KeY. *

    + * * @param profile The {@link Profile} to use. * @return The instantiated {@link ProblemInitializer}. */ @@ -234,15 +243,17 @@ protected ProblemInitializer createProblemInitializer(Profile profile) { } @Override - public void loadingStarted(AbstractProblemLoader loader) { - } + public void loadingStarted(AbstractProblemLoader loader) {} @Override - public void loadingFinished(AbstractProblemLoader loader, LoadedPOContainer poContainer, ProofAggregate proofList, ReplayResult result) throws ProblemLoaderException { - if (proofList != null) { - // avoid double registration at spec repos as that is done already earlier in createProof - // the UI method should just do the necessarily UI registrations - createProofEnvironmentAndRegisterProof(poContainer.getProofOblInput(), proofList, loader.getInitConfig()); - } - } -} \ No newline at end of file + public void loadingFinished(AbstractProblemLoader loader, LoadedPOContainer poContainer, + ProofAggregate proofList, ReplayResult result) throws ProblemLoaderException { + if (proofList != null) { + // avoid double registration at spec repos as that is done already earlier in + // createProof + // the UI method should just do the necessarily UI registrations + createProofEnvironmentAndRegisterProof(poContainer.getProofOblInput(), proofList, + loader.getInitConfig()); + } + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/AutoModeListener.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/AutoModeListener.java index 876b745a1be..4395f9cdfad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/AutoModeListener.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/AutoModeListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import de.uka.ilkd.key.proof.ProofEvent; @@ -5,14 +8,14 @@ public interface AutoModeListener { - /** + /** * invoked if automatic execution has started */ void autoModeStarted(ProofEvent e); - + /** * invoked if automatic execution has stopped */ void autoModeStopped(ProofEvent e); - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/CompositePTListener.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/CompositePTListener.java index bbd8abdd472..be5964586c5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/CompositePTListener.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/CompositePTListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import de.uka.ilkd.key.prover.ProverTaskListener; @@ -5,9 +8,8 @@ import de.uka.ilkd.key.prover.TaskStartedInfo; /** - * A composite structure for prover task listeners. - * For the moment, this is only used for the application - * of proof macros at the outermost level. + * A composite structure for prover task listeners. For the moment, this is only used for the + * application of proof macros at the outermost level. * * @author Michael Kirsten */ @@ -18,14 +20,13 @@ public CompositePTListener(ProverTaskListener[] l) { this.listeners = l; } - public CompositePTListener(ProverTaskListener ptl1, - ProverTaskListener ptl2) { - this(new ProverTaskListener[]{ptl1, ptl2}); + public CompositePTListener(ProverTaskListener ptl1, ProverTaskListener ptl2) { + this(new ProverTaskListener[] { ptl1, ptl2 }); } @Override public void taskStarted(TaskStartedInfo info) { - for (ProverTaskListener l: listeners) { + for (ProverTaskListener l : listeners) { if (l != null) { l.taskStarted(info); } @@ -34,7 +35,7 @@ public void taskStarted(TaskStartedInfo info) { @Override public void taskProgress(int position) { - for (ProverTaskListener l: listeners) { + for (ProverTaskListener l : listeners) { if (l != null) { l.taskProgress(position); } @@ -43,7 +44,7 @@ public void taskProgress(int position) { @Override public void taskFinished(TaskFinishedInfo info) { - for (int i = listeners.length -1; 0 <= i; i--) { + for (int i = listeners.length - 1; 0 <= i; i--) { ProverTaskListener l = listeners[i]; if (l != null) { l.taskFinished(info); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultProofControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultProofControl.java index e6bdd380714..95c324e4f09 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultProofControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultProofControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import org.key_project.util.collection.ImmutableList; @@ -18,157 +21,160 @@ /** * The default implementation of {@link ProofControl}. + * * @author Martin Hentschel */ public class DefaultProofControl extends AbstractProofControl { - /** - * The {@link UserInterfaceControl} in which this {@link ProofControl} is used. - */ - private final UserInterfaceControl ui; - - /** - * The currently running {@link Thread}. - */ - private Thread autoModeThread; - - /** - * Constructor. - * @param ui The {@link UserInterfaceControl} in which this {@link ProofControl} is used. - * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - */ - public DefaultProofControl(UserInterfaceControl ui, DefaultUserInterfaceControl defaultProverTaskListener) { - super(defaultProverTaskListener); - this.ui = ui; - } - - /** - * Constructor. - * @param ui The {@link UserInterfaceControl} in which this {@link ProofControl} is used. - * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. - */ - public DefaultProofControl(UserInterfaceControl ui, - DefaultUserInterfaceControl defaultProverTaskListener, - RuleCompletionHandler ruleCompletionHandler) { - super(defaultProverTaskListener, ruleCompletionHandler); - this.ui = ui; - } - - @Override - public synchronized void startAutoMode(Proof proof, ImmutableList goals, ProverTaskListener ptl) { - if (!isInAutoMode()) { - autoModeThread = new AutoModeThread(proof, goals, ptl); - autoModeThread.start(); - } - } - - @Override - public synchronized void stopAutoMode() { - if (isInAutoMode()) { - autoModeThread.interrupt(); - } - } - - @Override - public void waitWhileAutoMode() { - while (isInAutoMode()) { // Wait until auto mode has stopped. - try { - Thread.sleep(100); - } - catch (InterruptedException e) { - } - } - } - - @Override - public boolean isInAutoMode() { - return autoModeThread != null; - } - - private class AutoModeThread extends Thread { - private final Proof proof; - - private final ImmutableList goals; - - private final ProverTaskListener ptl; - - public AutoModeThread(Proof proof, ImmutableList goals, ProverTaskListener ptl) { - this.proof = proof; - this.goals = goals; - this.ptl = ptl; - } - - @Override - public void run() { - try { - fireAutoModeStarted(new ProofEvent(proof)); - ProofStarter starter = ptl != null ? - new ProofStarter(new CompositePTListener(getDefaultProverTaskListener(), ptl), false) : - new ProofStarter(getDefaultProverTaskListener(), false); - starter.init(proof); - if (goals != null) { - starter.start(goals); - } - else { - starter.start(); + /** + * The {@link UserInterfaceControl} in which this {@link ProofControl} is used. + */ + private final UserInterfaceControl ui; + + /** + * The currently running {@link Thread}. + */ + private Thread autoModeThread; + + /** + * Constructor. + * + * @param ui The {@link UserInterfaceControl} in which this {@link ProofControl} is used. + * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added + * to all started {@link ApplyStrategy} instances. + */ + public DefaultProofControl(UserInterfaceControl ui, + DefaultUserInterfaceControl defaultProverTaskListener) { + super(defaultProverTaskListener); + this.ui = ui; + } + + /** + * Constructor. + * + * @param ui The {@link UserInterfaceControl} in which this {@link ProofControl} is used. + * @param defaultProverTaskListener The default {@link ProverTaskListener} which will be added + * to all started {@link ApplyStrategy} instances. + * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. + */ + public DefaultProofControl(UserInterfaceControl ui, + DefaultUserInterfaceControl defaultProverTaskListener, + RuleCompletionHandler ruleCompletionHandler) { + super(defaultProverTaskListener, ruleCompletionHandler); + this.ui = ui; + } + + @Override + public synchronized void startAutoMode(Proof proof, ImmutableList goals, + ProverTaskListener ptl) { + if (!isInAutoMode()) { + autoModeThread = new AutoModeThread(proof, goals, ptl); + autoModeThread.start(); + } + } + + @Override + public synchronized void stopAutoMode() { + if (isInAutoMode()) { + autoModeThread.interrupt(); + } + } + + @Override + public void waitWhileAutoMode() { + while (isInAutoMode()) { // Wait until auto mode has stopped. + try { + Thread.sleep(100); + } catch (InterruptedException e) { } - } - finally { - autoModeThread = null; - fireAutoModeStopped(new ProofEvent(proof)); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc) { - if (!isInAutoMode()) { - autoModeThread = new MacroThread(node, macro, posInOcc); - autoModeThread.start(); - } - } - - private class MacroThread extends Thread { - private final Node node; - - private final ProofMacro macro; - - private final PosInOccurrence posInOcc; - - public MacroThread(Node node, ProofMacro macro, PosInOccurrence posInOcc) { - this.node = node; - this.macro = macro; - this.posInOcc = posInOcc; - } - - @Override - public void run() { - Proof proof = node.proof(); - ProverTaskListener ptl = getDefaultProverTaskListener(); - TaskFinishedInfo info = null; - try { - fireAutoModeStarted(new ProofEvent(proof)); - info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); - if (ptl != null) { - ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); + } + } + + @Override + public boolean isInAutoMode() { + return autoModeThread != null; + } + + private class AutoModeThread extends Thread { + private final Proof proof; + + private final ImmutableList goals; + + private final ProverTaskListener ptl; + + public AutoModeThread(Proof proof, ImmutableList goals, ProverTaskListener ptl) { + this.proof = proof; + this.goals = goals; + this.ptl = ptl; + } + + @Override + public void run() { + try { + fireAutoModeStarted(new ProofEvent(proof)); + ProofStarter starter = ptl != null + ? new ProofStarter( + new CompositePTListener(getDefaultProverTaskListener(), ptl), false) + : new ProofStarter(getDefaultProverTaskListener(), false); + starter.init(proof); + if (goals != null) { + starter.start(goals); + } else { + starter.start(); + } + } finally { + autoModeThread = null; + fireAutoModeStopped(new ProofEvent(proof)); } - synchronized(macro) { - info = macro.applyTo(ui, node, posInOcc, ptl); - } - } - catch (Exception e) { - throw new RuntimeException("Macro caused an exception: " + e.getMessage(), e); - } - finally { - if (ptl != null) { - ptl.taskFinished(info); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc) { + if (!isInAutoMode()) { + autoModeThread = new MacroThread(node, macro, posInOcc); + autoModeThread.start(); + } + } + + private class MacroThread extends Thread { + private final Node node; + + private final ProofMacro macro; + + private final PosInOccurrence posInOcc; + + public MacroThread(Node node, ProofMacro macro, PosInOccurrence posInOcc) { + this.node = node; + this.macro = macro; + this.posInOcc = posInOcc; + } + + @Override + public void run() { + Proof proof = node.proof(); + ProverTaskListener ptl = getDefaultProverTaskListener(); + TaskFinishedInfo info = null; + try { + fireAutoModeStarted(new ProofEvent(proof)); + info = ProofMacroFinishedInfo.getDefaultInfo(macro, proof); + if (ptl != null) { + ptl.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); + } + synchronized (macro) { + info = macro.applyTo(ui, node, posInOcc, ptl); + } + } catch (Exception e) { + throw new RuntimeException("Macro caused an exception: " + e.getMessage(), e); + } finally { + if (ptl != null) { + ptl.taskFinished(info); + } + autoModeThread = null; + fireAutoModeStopped(new ProofEvent(proof)); } - autoModeThread = null; - fireAutoModeStopped(new ProofEvent(proof)); - } - } - } + } + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultUserInterfaceControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultUserInterfaceControl.java index 393956afca3..5644dfd2349 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultUserInterfaceControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/DefaultUserInterfaceControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import org.key_project.util.collection.ImmutableSet; @@ -9,156 +12,161 @@ import de.uka.ilkd.key.speclang.PositionedString; /** - * The {@link DefaultUserInterfaceControl} which allows proving in case - * that no specific user interface is available. + * The {@link DefaultUserInterfaceControl} which allows proving in case that no specific user + * interface is available. *

    - * In case that no user interface should be used see also {@link KeYEnvironment} - * which provides static methods to load source code and to instantiate this - * class. + * In case that no user interface should be used see also {@link KeYEnvironment} which provides + * static methods to load source code and to instantiate this class. + * * @author Martin Hentschel * @see KeYEnvironment */ public class DefaultUserInterfaceControl extends AbstractUserInterfaceControl { - /** - * The used {@link TermLabelVisibilityManager}. - */ - private final TermLabelVisibilityManager termLabelVisibilityManager = new TermLabelVisibilityManager(); - - /** - * The used {@link DefaultProofControl}. - */ - private final DefaultProofControl proofControl; - - /** - * Constructor. - */ - public DefaultUserInterfaceControl() { - proofControl = new DefaultProofControl(this, this); - } - - /** - * Constructor. - * @param customization An optional {@link RuleCompletionHandler}. - */ - public DefaultUserInterfaceControl(RuleCompletionHandler customization) { - proofControl = new DefaultProofControl(this, this, customization); - } - - /** - * {@inheritDoc} - */ - @Override - public DefaultProofControl getProofControl() { - return proofControl; - } - - /** - * {@inheritDoc} - */ - @Override - public ProofEnvironment createProofEnvironmentAndRegisterProof(ProofOblInput proofOblInput, ProofAggregate proofList, InitConfig initConfig) { - //TODO: Find out why the proof has to be registered. This method should just return null and do nothing. - initConfig.getServices().getSpecificationRepository().registerProof(proofOblInput, proofList.getFirstProof()); - - // This has to be done to prive the proofList with the environment object. - final ProofEnvironment env = new ProofEnvironment(initConfig); - env.registerProof(proofOblInput, proofList); - return env; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean selectProofObligation(InitConfig initConfig) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void progressStarted(Object sender) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void progressStopped(Object sender) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void reportStatus(Object sender, String status, int progress) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void reportStatus(Object sender, String status) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void resetStatus(Object sender) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void reportException(Object sender, ProofOblInput input, Exception e) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void setProgress(int progress) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void setMaximum(int maximum) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void registerProofAggregate(ProofAggregate pa) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public void reportWarnings(ImmutableSet warnings) { - // Nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public TermLabelVisibilityManager getTermLabelVisibilityManager() { - return termLabelVisibilityManager; - } -} \ No newline at end of file + /** + * The used {@link TermLabelVisibilityManager}. + */ + private final TermLabelVisibilityManager termLabelVisibilityManager = + new TermLabelVisibilityManager(); + + /** + * The used {@link DefaultProofControl}. + */ + private final DefaultProofControl proofControl; + + /** + * Constructor. + */ + public DefaultUserInterfaceControl() { + proofControl = new DefaultProofControl(this, this); + } + + /** + * Constructor. + * + * @param customization An optional {@link RuleCompletionHandler}. + */ + public DefaultUserInterfaceControl(RuleCompletionHandler customization) { + proofControl = new DefaultProofControl(this, this, customization); + } + + /** + * {@inheritDoc} + */ + @Override + public DefaultProofControl getProofControl() { + return proofControl; + } + + /** + * {@inheritDoc} + */ + @Override + public ProofEnvironment createProofEnvironmentAndRegisterProof(ProofOblInput proofOblInput, + ProofAggregate proofList, InitConfig initConfig) { + // TODO: Find out why the proof has to be registered. This method should just return null + // and do nothing. + initConfig.getServices().getSpecificationRepository().registerProof(proofOblInput, + proofList.getFirstProof()); + + // This has to be done to prive the proofList with the environment object. + final ProofEnvironment env = new ProofEnvironment(initConfig); + env.registerProof(proofOblInput, proofList); + return env; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean selectProofObligation(InitConfig initConfig) { + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public void progressStarted(Object sender) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void progressStopped(Object sender) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void reportStatus(Object sender, String status, int progress) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void reportStatus(Object sender, String status) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void resetStatus(Object sender) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void reportException(Object sender, ProofOblInput input, Exception e) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void setProgress(int progress) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaximum(int maximum) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void registerProofAggregate(ProofAggregate pa) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public void reportWarnings(ImmutableSet warnings) { + // Nothing to do + } + + /** + * {@inheritDoc} + */ + @Override + public TermLabelVisibilityManager getTermLabelVisibilityManager() { + return termLabelVisibilityManager; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/InstantiationFileHandler.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/InstantiationFileHandler.java index df0fa2901fa..1fe5b57c342 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/InstantiationFileHandler.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/InstantiationFileHandler.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.io.BufferedReader; @@ -18,152 +21,149 @@ import de.uka.ilkd.key.settings.PathConfig; public class InstantiationFileHandler { - private static final String INSTANTIATION_DIR = - PathConfig.getKeyConfigDir() + File.separator + "instantiations"; + private static final String INSTANTIATION_DIR = + PathConfig.getKeyConfigDir() + File.separator + "instantiations"; - private static final String SEPARATOR1 = "<<<<<<"; + private static final String SEPARATOR1 = "<<<<<<"; - private static final String SEPARATOR2 = ">>>>>>"; + private static final String SEPARATOR2 = ">>>>>>"; - private static final String LINE_END = System - .getProperty("line.separator"); + private static final String LINE_END = System.getProperty("line.separator"); - private static final int SAVE_COUNT = 5; + private static final int SAVE_COUNT = 5; - private static HashMap>> hm; + private static HashMap>> hm; - public static boolean hasInstantiationListsFor(Taclet taclet) { - if (hm == null) { - createHashMap(); - } - return hm.containsKey(taclet.name().toString()); - } + public static boolean hasInstantiationListsFor(Taclet taclet) { + if (hm == null) { + createHashMap(); + } + return hm.containsKey(taclet.name().toString()); + } - public static java.util.List> getInstantiationListsFor(Taclet taclet) { - if (hasInstantiationListsFor(taclet)) { - if (hm.get(taclet.name().toString()) == null) { - createListFor(taclet); - } - return hm.get(taclet.name().toString()); - } - return null; - } + public static java.util.List> getInstantiationListsFor(Taclet taclet) { + if (hasInstantiationListsFor(taclet)) { + if (hm.get(taclet.name().toString()) == null) { + createListFor(taclet); + } + return hm.get(taclet.name().toString()); + } + return null; + } - private static void createHashMap() { - File dir = new File(INSTANTIATION_DIR); - if (!dir.exists()) { - dir.mkdirs(); - } - String[] instFiles = dir.list(); - if (instFiles == null) { - hm = new LinkedHashMap>>(0); - } else { - // Avoid resizing of HashMap - hm = new LinkedHashMap>>(instFiles.length + 1, 1); - for (String instFile : instFiles) { - hm.put(instFile, null); - } - } - } + private static void createHashMap() { + File dir = new File(INSTANTIATION_DIR); + if (!dir.exists()) { + dir.mkdirs(); + } + String[] instFiles = dir.list(); + if (instFiles == null) { + hm = new LinkedHashMap>>(0); + } else { + // Avoid resizing of HashMap + hm = new LinkedHashMap>>(instFiles.length + 1, 1); + for (String instFile : instFiles) { + hm.put(instFile, null); + } + } + } - private static void createListFor(Taclet taclet) { - java.util.List> instList = new LinkedList>(); - java.util.List instantiations = new LinkedList(); - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader( - INSTANTIATION_DIR + File.separator - + taclet.name().toString())); - String line = br.readLine(); - StringBuffer sb = new StringBuffer(); - while (line != null) { - if (line.equals(SEPARATOR1)) { - if (sb.length() > 0) { - instantiations.add(sb.toString()); - } - sb = new StringBuffer(); - if (instantiations.size() > 0) { - instList.add(instantiations); - } - instantiations = new LinkedList(); - } else if (line.equals(SEPARATOR2)) { - if (sb.length() > 0) { - instantiations.add(sb.toString()); - } - sb = new StringBuffer(); - } else { - if (sb.length() > 0) { - sb.append(LINE_END); - } - sb.append(line); - } - line = br.readLine(); - } - if (sb.length() > 0) { - instantiations.add(sb.toString()); - } - } catch (IOException e) { - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - } - } - } - if (instantiations.size() > 0) { - instList.add(instantiations); - } - hm.put(taclet.name().toString(), instList); - } + private static void createListFor(Taclet taclet) { + java.util.List> instList = new LinkedList>(); + java.util.List instantiations = new LinkedList(); + BufferedReader br = null; + try { + br = new BufferedReader( + new FileReader(INSTANTIATION_DIR + File.separator + taclet.name().toString())); + String line = br.readLine(); + StringBuffer sb = new StringBuffer(); + while (line != null) { + if (line.equals(SEPARATOR1)) { + if (sb.length() > 0) { + instantiations.add(sb.toString()); + } + sb = new StringBuffer(); + if (instantiations.size() > 0) { + instList.add(instantiations); + } + instantiations = new LinkedList(); + } else if (line.equals(SEPARATOR2)) { + if (sb.length() > 0) { + instantiations.add(sb.toString()); + } + sb = new StringBuffer(); + } else { + if (sb.length() > 0) { + sb.append(LINE_END); + } + sb.append(line); + } + line = br.readLine(); + } + if (sb.length() > 0) { + instantiations.add(sb.toString()); + } + } catch (IOException e) { + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + } + } + } + if (instantiations.size() > 0) { + instList.add(instantiations); + } + hm.put(taclet.name().toString(), instList); + } - public static void saveListFor(TacletInstantiationModel model) { - Taclet taclet = model.taclet(); - TacletFindModel tableModel = model.tableModel(); - int start = model.tacletApp().instantiations().size(); - java.util.List> instList = getInstantiationListsFor(taclet); - BufferedWriter bw = null; - try { - bw = new BufferedWriter(new FileWriter( - INSTANTIATION_DIR + File.separator - + taclet.name().toString())); - StringBuffer sb = new StringBuffer(); - for (int i = start; i < tableModel.getRowCount(); i++) { - if (i > start) { - sb.append(SEPARATOR2).append(LINE_END); - } - sb.append(tableModel.getValueAt(i, 1)).append(LINE_END); - } - String newInst = sb.toString(); - bw.write(newInst); - if (instList != null) { - final ListIterator> instListIt = instList.listIterator(); - int count = 1; - while (instListIt.hasNext() && count < SAVE_COUNT) { - final ListIterator instIt = instListIt.next().listIterator(); - sb = new StringBuffer(); - for (int i = 0; instIt.hasNext(); i++) { - if (i > 0) { - sb.append(SEPARATOR2).append(LINE_END); - } - sb.append(instIt.next()).append(LINE_END); - } - String oldInst = sb.toString(); - if (!oldInst.equals(newInst)) { - bw.write(SEPARATOR1 + LINE_END + oldInst); - count++; - } - } - } - } catch (IOException e) { - } finally { - if (bw != null) { - try { - bw.close(); - } catch (IOException e) { - } - } - } - hm.put(taclet.name().toString(), null); - } + public static void saveListFor(TacletInstantiationModel model) { + Taclet taclet = model.taclet(); + TacletFindModel tableModel = model.tableModel(); + int start = model.tacletApp().instantiations().size(); + java.util.List> instList = getInstantiationListsFor(taclet); + BufferedWriter bw = null; + try { + bw = new BufferedWriter( + new FileWriter(INSTANTIATION_DIR + File.separator + taclet.name().toString())); + StringBuffer sb = new StringBuffer(); + for (int i = start; i < tableModel.getRowCount(); i++) { + if (i > start) { + sb.append(SEPARATOR2).append(LINE_END); + } + sb.append(tableModel.getValueAt(i, 1)).append(LINE_END); + } + String newInst = sb.toString(); + bw.write(newInst); + if (instList != null) { + final ListIterator> instListIt = instList.listIterator(); + int count = 1; + while (instListIt.hasNext() && count < SAVE_COUNT) { + final ListIterator instIt = instListIt.next().listIterator(); + sb = new StringBuffer(); + for (int i = 0; instIt.hasNext(); i++) { + if (i > 0) { + sb.append(SEPARATOR2).append(LINE_END); + } + sb.append(instIt.next()).append(LINE_END); + } + String oldInst = sb.toString(); + if (!oldInst.equals(newInst)) { + bw.write(SEPARATOR1 + LINE_END + oldInst); + count++; + } + } + } + } catch (IOException e) { + } finally { + if (bw != null) { + try { + bw.close(); + } catch (IOException e) { + } + } + } + hm.put(taclet.name().toString(), null); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/InteractionListener.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/InteractionListener.java index c2d488eaa6d..c7500314a65 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/InteractionListener.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/InteractionListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import de.uka.ilkd.key.logic.PosInOccurrence; @@ -22,10 +25,11 @@ public interface InteractionListener { void runPrune(Node node); - void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc, ProofMacroFinishedInfo info); + void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc, + ProofMacroFinishedInfo info); - void runBuiltInRule(Node node, IBuiltInRuleApp app, BuiltInRule rule, - PosInOccurrence pos, boolean forced); + void runBuiltInRule(Node node, IBuiltInRuleApp app, BuiltInRule rule, PosInOccurrence pos, + boolean forced); void runAutoMode(List initialGoals, Proof proof, ApplyStrategyInfo info); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java index ffc7ecc6a37..32756626c2e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.io.File; @@ -19,255 +22,270 @@ import de.uka.ilkd.key.util.Pair; /** - * Instances of this class are used to collect and access all - * relevant information for verification with KeY. + * Instances of this class are used to collect and access all relevant information for verification + * with KeY. + * * @author Martin Hentschel */ public class KeYEnvironment { - /** - * The {@link UserInterfaceControl} in which the {@link Proof} is loaded. - */ - private final U ui; - - /** - * The loaded project. - */ - private final InitConfig initConfig; - - /** - * An optional {@link Proof} which was loaded by the specified proof file. - */ - private final Proof loadedProof; - - /** - * An optional field denoting a script contained in the proof file. - */ - private final Pair proofScript; + /** + * The {@link UserInterfaceControl} in which the {@link Proof} is loaded. + */ + private final U ui; - /** - * Indicates that this {@link KeYEnvironment} is disposed. - */ - private boolean disposed; + /** + * The loaded project. + */ + private final InitConfig initConfig; - /** - * The {@link ReplayResult} if available. - */ - private final ReplayResult replayResult; + /** + * An optional {@link Proof} which was loaded by the specified proof file. + */ + private final Proof loadedProof; - /** - * Constructor - * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. - * @param initConfig The loaded project. - */ - public KeYEnvironment(U ui, InitConfig initConfig) { - this(ui, initConfig, null, null, null); - } + /** + * An optional field denoting a script contained in the proof file. + */ + private final Pair proofScript; - /** - * Constructor - * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. - * @param initConfig The loaded project. - */ - public KeYEnvironment(U ui, InitConfig initConfig, Proof loadedProof, Pair proofScript, ReplayResult replayResult) { - this.ui = ui; - this.initConfig = initConfig; - this.loadedProof = loadedProof; - this.proofScript = proofScript; - this.replayResult = replayResult; - } + /** + * Indicates that this {@link KeYEnvironment} is disposed. + */ + private boolean disposed; - /** - * Returns the {@link UserInterfaceControl} in which the {@link Proof} is loaded. - * @return The {@link UserInterfaceControl} in which the {@link Proof} is loaded. - */ - public U getUi() { - return ui; - } - - /** - * Returns the {@link ProofControl} of {@link #getUi()}. - * @return The {@link ProofControl} of {@link #getUi()}. - */ - public ProofControl getProofControl() { - return ui != null ? ui.getProofControl() : null; - } + /** + * The {@link ReplayResult} if available. + */ + private final ReplayResult replayResult; - /** - * Returns the loaded project. - * @return The loaded project. - */ - public InitConfig getInitConfig() { - return initConfig; - } + /** + * Constructor + * + * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. + * @param initConfig The loaded project. + */ + public KeYEnvironment(U ui, InitConfig initConfig) { + this(ui, initConfig, null, null, null); + } - /** - * Returns the {@link Services} of {@link #getInitConfig()}. - * @return The {@link Services} of {@link #getInitConfig()}. - */ - public Services getServices() { - return initConfig.getServices(); - } + /** + * Constructor + * + * @param ui The {@link UserInterfaceControl} in which the {@link Proof} is loaded. + * @param initConfig The loaded project. + */ + public KeYEnvironment(U ui, InitConfig initConfig, Proof loadedProof, + Pair proofScript, ReplayResult replayResult) { + this.ui = ui; + this.initConfig = initConfig; + this.loadedProof = loadedProof; + this.proofScript = proofScript; + this.replayResult = replayResult; + } - /** - * Returns the used {@link JavaInfo}. - * @return The used {@link JavaInfo}. - */ - public JavaInfo getJavaInfo() { - return getServices().getJavaInfo(); - } + /** + * Returns the {@link UserInterfaceControl} in which the {@link Proof} is loaded. + * + * @return The {@link UserInterfaceControl} in which the {@link Proof} is loaded. + */ + public U getUi() { + return ui; + } - /** - * Returns the used {@link SpecificationRepository}. - * @return The used {@link SpecificationRepository}. - */ - public SpecificationRepository getSpecificationRepository() { - return getServices().getSpecificationRepository(); - } + /** + * Returns the {@link ProofControl} of {@link #getUi()}. + * + * @return The {@link ProofControl} of {@link #getUi()}. + */ + public ProofControl getProofControl() { + return ui != null ? ui.getProofControl() : null; + } - public Profile getProfile() { - return getInitConfig().getProfile(); - } - - /** - * Returns the loaded {@link Proof} if a proof file was loaded. - * @return The loaded {@link Proof} if available and {@code null} otherwise. - */ - public Proof getLoadedProof() { - return loadedProof; - } + /** + * Returns the loaded project. + * + * @return The loaded project. + */ + public InitConfig getInitConfig() { + return initConfig; + } - /** - * Returns the {@link ReplayResult} if available. - * @return The {@link ReplayResult} or {@code null} if not available. - */ - public ReplayResult getReplayResult() { - return replayResult; - } + /** + * Returns the {@link Services} of {@link #getInitConfig()}. + * + * @return The {@link Services} of {@link #getInitConfig()}. + */ + public Services getServices() { + return initConfig.getServices(); + } - /** - * Creates a new {@link Proof} with help of the {@link UserInterfaceControl}. - * @param input The {@link ProofOblInput} to instantiate {@link Proof} from. - * @return The instantiated {@link Proof}. - * @throws ProofInputException Occurred Exception. - */ - public Proof createProof(ProofOblInput input) throws ProofInputException { - return ui.createProof(getInitConfig(), input); - } - - /** - * Loads the given location and returns all required references as {@link KeYEnvironment}. - * The {@link MainWindow} is not involved in the whole process. - * @param location The location to load. - * @param classPaths The class path entries to use. - * @param bootClassPath The boot class path to use. - * @param includes Optional includes to consider. - * @return The {@link KeYEnvironment} which contains all references to the loaded location. - * @throws ProblemLoaderException Occurred Exception - */ - public static KeYEnvironment load(File location, - List classPaths, - File bootClassPath, - List includes) throws ProblemLoaderException { - return load(null, location, classPaths, bootClassPath, includes, false); - } - - /** - * Loads the given location and returns all required references as {@link KeYEnvironment}. - * The {@link MainWindow} is not involved in the whole process. - * @param location The location to load. - * @param classPaths The class path entries to use. - * @param bootClassPath The boot class path to use. - * @param includes Optional includes to consider. - * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. - * @return The {@link KeYEnvironment} which contains all references to the loaded location. - * @throws ProblemLoaderException Occurred Exception - */ - public static KeYEnvironment load(File location, - List classPaths, - File bootClassPath, - List includes, - RuleCompletionHandler ruleCompletionHandler) throws ProblemLoaderException { - return load(null, location, classPaths, bootClassPath, includes, null, ruleCompletionHandler, false); - } - - /** - * Loads the given location and returns all required references as {@link KeYEnvironment}. - * The {@link MainWindow} is not involved in the whole process. - * @param profile The {@link Profile} to use. - * @param location The location to load. - * @param classPaths The class path entries to use. - * @param bootClassPath The boot class path to use. - * @param includes Optional includes to consider. - * @param forceNewProfileOfNewProofs {@code} true {@link #profileOfNewProofs} will be used as {@link Profile} of new proofs, {@code false} {@link Profile} specified by problem file will be used for new proofs. - * @return The {@link KeYEnvironment} which contains all references to the loaded location. - * @throws ProblemLoaderException Occurred Exception - */ - public static KeYEnvironment load(Profile profile, - File location, - List classPaths, - File bootClassPath, - List includes, - boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { - return load(profile, location, classPaths, bootClassPath, includes, null, null, forceNewProfileOfNewProofs); - } - - /** - * Loads the given location and returns all required references as {@link KeYEnvironment}. - * The {@link MainWindow} is not involved in the whole process. - * @param profile The {@link Profile} to use. - * @param location The location to load. - * @param classPaths The class path entries to use. - * @param bootClassPath The boot class path to use. - * @param includes Optional includes to consider. - * @param poPropertiesToForce Some optional PO {@link Properties} to force. - * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. - * @param forceNewProfileOfNewProofs {@code} true - * {@link AbstractProblemLoader#profileOfNewProofs} will be used as - * {@link Profile} of new proofs, {@code false} {@link Profile} - * specified by problem file will be used for new proofs. - * @return The {@link KeYEnvironment} which contains all references to the loaded location. - * @throws ProblemLoaderException Occurred Exception - */ - public static KeYEnvironment load(Profile profile, - File location, - List classPaths, - File bootClassPath, - List includes, - Properties poPropertiesToForce, - RuleCompletionHandler ruleCompletionHandler, - boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { - DefaultUserInterfaceControl ui = new DefaultUserInterfaceControl(ruleCompletionHandler); - AbstractProblemLoader loader = ui.load(profile, location, classPaths, bootClassPath, includes, poPropertiesToForce, forceNewProfileOfNewProofs); - InitConfig initConfig = loader.getInitConfig(); + /** + * Returns the used {@link JavaInfo}. + * + * @return The used {@link JavaInfo}. + */ + public JavaInfo getJavaInfo() { + return getServices().getJavaInfo(); + } - return new KeYEnvironment(ui, initConfig, loader.getProof(), loader.getProofScript(), loader.getResult()); - } - - public static KeYEnvironment load(File keyFile) throws ProblemLoaderException { - return load(keyFile, null, null, null); - } + /** + * Returns the used {@link SpecificationRepository}. + * + * @return The used {@link SpecificationRepository}. + */ + public SpecificationRepository getSpecificationRepository() { + return getServices().getSpecificationRepository(); + } - /** - * Disposes this {@link KeYEnvironment}. - */ - public void dispose() { - if (loadedProof != null && !loadedProof.isDisposed()) { - loadedProof.dispose(); - } - disposed = true; - } - - /** - * Checks if this {@link KeYEnvironment} is disposed meaning that - * {@link #dispose()} was already executed at least once. - * @return {@code true} disposed, {@code false} not disposed and still functionable. - */ - public boolean isDisposed() { - return disposed; - } + public Profile getProfile() { + return getInitConfig().getProfile(); + } - public Pair getProofScript() { - return proofScript; - } + /** + * Returns the loaded {@link Proof} if a proof file was loaded. + * + * @return The loaded {@link Proof} if available and {@code null} otherwise. + */ + public Proof getLoadedProof() { + return loadedProof; + } -} \ No newline at end of file + /** + * Returns the {@link ReplayResult} if available. + * + * @return The {@link ReplayResult} or {@code null} if not available. + */ + public ReplayResult getReplayResult() { + return replayResult; + } + + /** + * Creates a new {@link Proof} with help of the {@link UserInterfaceControl}. + * + * @param input The {@link ProofOblInput} to instantiate {@link Proof} from. + * @return The instantiated {@link Proof}. + * @throws ProofInputException Occurred Exception. + */ + public Proof createProof(ProofOblInput input) throws ProofInputException { + return ui.createProof(getInitConfig(), input); + } + + /** + * Loads the given location and returns all required references as {@link KeYEnvironment}. The + * {@link MainWindow} is not involved in the whole process. + * + * @param location The location to load. + * @param classPaths The class path entries to use. + * @param bootClassPath The boot class path to use. + * @param includes Optional includes to consider. + * @return The {@link KeYEnvironment} which contains all references to the loaded location. + * @throws ProblemLoaderException Occurred Exception + */ + public static KeYEnvironment load(File location, + List classPaths, File bootClassPath, List includes) + throws ProblemLoaderException { + return load(null, location, classPaths, bootClassPath, includes, false); + } + + /** + * Loads the given location and returns all required references as {@link KeYEnvironment}. The + * {@link MainWindow} is not involved in the whole process. + * + * @param location The location to load. + * @param classPaths The class path entries to use. + * @param bootClassPath The boot class path to use. + * @param includes Optional includes to consider. + * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. + * @return The {@link KeYEnvironment} which contains all references to the loaded location. + * @throws ProblemLoaderException Occurred Exception + */ + public static KeYEnvironment load(File location, + List classPaths, File bootClassPath, List includes, + RuleCompletionHandler ruleCompletionHandler) throws ProblemLoaderException { + return load(null, location, classPaths, bootClassPath, includes, null, + ruleCompletionHandler, false); + } + + /** + * Loads the given location and returns all required references as {@link KeYEnvironment}. The + * {@link MainWindow} is not involved in the whole process. + * + * @param profile The {@link Profile} to use. + * @param location The location to load. + * @param classPaths The class path entries to use. + * @param bootClassPath The boot class path to use. + * @param includes Optional includes to consider. + * @param forceNewProfileOfNewProofs {@code} true {@link #profileOfNewProofs} will be used as + * {@link Profile} of new proofs, {@code false} {@link Profile} specified by problem file + * will be used for new proofs. + * @return The {@link KeYEnvironment} which contains all references to the loaded location. + * @throws ProblemLoaderException Occurred Exception + */ + public static KeYEnvironment load(Profile profile, File location, + List classPaths, File bootClassPath, List includes, + boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { + return load(profile, location, classPaths, bootClassPath, includes, null, null, + forceNewProfileOfNewProofs); + } + + /** + * Loads the given location and returns all required references as {@link KeYEnvironment}. The + * {@link MainWindow} is not involved in the whole process. + * + * @param profile The {@link Profile} to use. + * @param location The location to load. + * @param classPaths The class path entries to use. + * @param bootClassPath The boot class path to use. + * @param includes Optional includes to consider. + * @param poPropertiesToForce Some optional PO {@link Properties} to force. + * @param ruleCompletionHandler An optional {@link RuleCompletionHandler}. + * @param forceNewProfileOfNewProofs {@code} true + * {@link AbstractProblemLoader#profileOfNewProofs} will be used as {@link Profile} of + * new proofs, {@code false} {@link Profile} specified by problem file will be used for + * new proofs. + * @return The {@link KeYEnvironment} which contains all references to the loaded location. + * @throws ProblemLoaderException Occurred Exception + */ + public static KeYEnvironment load(Profile profile, File location, + List classPaths, File bootClassPath, List includes, + Properties poPropertiesToForce, RuleCompletionHandler ruleCompletionHandler, + boolean forceNewProfileOfNewProofs) throws ProblemLoaderException { + DefaultUserInterfaceControl ui = new DefaultUserInterfaceControl(ruleCompletionHandler); + AbstractProblemLoader loader = ui.load(profile, location, classPaths, bootClassPath, + includes, poPropertiesToForce, forceNewProfileOfNewProofs); + InitConfig initConfig = loader.getInitConfig(); + + return new KeYEnvironment(ui, initConfig, loader.getProof(), + loader.getProofScript(), loader.getResult()); + } + + public static KeYEnvironment load(File keyFile) + throws ProblemLoaderException { + return load(keyFile, null, null, null); + } + + /** + * Disposes this {@link KeYEnvironment}. + */ + public void dispose() { + if (loadedProof != null && !loadedProof.isDisposed()) { + loadedProof.dispose(); + } + disposed = true; + } + + /** + * Checks if this {@link KeYEnvironment} is disposed meaning that {@link #dispose()} was already + * executed at least once. + * + * @return {@code true} disposed, {@code false} not disposed and still functionable. + */ + public boolean isDisposed() { + return disposed; + } + + public Pair getProofScript() { + return proofScript; + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/ProofControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/ProofControl.java index 86680ccaddf..a3c58055d46 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/ProofControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/ProofControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import org.key_project.util.collection.ImmutableList; @@ -18,149 +21,163 @@ * A {@link ProofControl} provides the user interface independent logic to apply rules on a proof. * This includes: *

      - *
    • Functionality to reduce the available rules ({@link #isMinimizeInteraction()} and {@link #setMinimizeInteraction(boolean)}).
    • - *
    • Functionality to list available rules.
    • - *
    • Functionality to apply a rule interactively.
    • - *
    • Functionality to apply rules by the auto mode synchronous or asynchronously in a different {@link Thread}.
    • - *
    • Functionality to execute a macro.
    • + *
    • Functionality to reduce the available rules ({@link #isMinimizeInteraction()} and + * {@link #setMinimizeInteraction(boolean)}).
    • + *
    • Functionality to list available rules.
    • + *
    • Functionality to apply a rule interactively.
    • + *
    • Functionality to apply rules by the auto mode synchronous or asynchronously in a different + * {@link Thread}.
    • + *
    • Functionality to execute a macro.
    • *
    + * * @author Martin Hentschel */ public interface ProofControl { - public boolean isMinimizeInteraction(); - - public void setMinimizeInteraction(boolean minimizeInteraction); - - /** - * collects all applicable RewriteTaclets of the current goal (called by the - * SequentViewer) - * - * @return a list of Taclets with all applicable RewriteTaclets - */ - public ImmutableList getRewriteTaclet(Goal focusedGoal, PosInOccurrence pos); - - /** - * collects all applicable FindTaclets of the current goal (called by the - * SequentViewer) - * - * @return a list of Taclets with all applicable FindTaclets - */ - public ImmutableList getFindTaclet(Goal focusedGoal, PosInOccurrence pos); - - /** - * collects all applicable NoFindTaclets of the current goal (called by the - * SequentViewer) - * - * @return a list of Taclets with all applicable NoFindTaclets - */ - public ImmutableList getNoFindTaclet(Goal focusedGoal); - - /** - * collects all built-in rules that are applicable at the given sequent - * position 'pos'. - * - * @param pos - * the PosInSequent where to look for applicable rules - */ - public ImmutableList getBuiltInRule(Goal focusedGoal, PosInOccurrence pos); - - public boolean selectedTaclet(Taclet taclet, Goal goal, PosInOccurrence pos); - - /** - * Apply a RuleApp and continue with update simplification or strategy - * application according to current settings. - * @param app - * @param goal - */ - public void applyInteractive(RuleApp app, Goal goal); - - /** selected rule to apply - * @param rule the selected built-in rule - * @param pos the PosInSequent describes the position where to apply the - * rule - * @param forced a boolean indicating that if the rule is complete or can be made complete - * automatically then the rule should be applied automatically without asking the user at all - * (e.g. if a loop invariant is available do not ask the user to provide one) - * @param interactive whether the rule was applied by the user - */ - public void selectedBuiltInRule(Goal goal, BuiltInRule rule, PosInOccurrence pos, boolean forced, boolean interactive); - - /** - * Returns the default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - * @return The default {@link ProverTaskListener} which will be added to all started {@link ApplyStrategy} instances. - */ - public ProverTaskListener getDefaultProverTaskListener(); - - public void addAutoModeListener(AutoModeListener p); - - public void removeAutoModeListener(AutoModeListener p); - - /** - * Checks if the auto mode of this {@link UserInterfaceControl} supports the given {@link Proof}. - * @param proof The {@link Proof} to check. - * @return {@code true} auto mode support proofs, {@code false} auto mode don't support proof. - */ - boolean isAutoModeSupported(Proof proof); - - /** - * Checks if the auto mode is currently running. - * @return {@code true} auto mode is running, {@code false} auto mode is not running. - */ - boolean isInAutoMode(); - - /** - * Starts the auto mode for the given {@link Proof}. - * @param proof The {@link Proof} to start auto mode of. - */ - void startAutoMode(Proof proof); - - /** - * Starts the auto mode for the given {@link Proof} and the given {@link Goal}s. - * @param proof The {@link Proof} to start auto mode of. - * @param goals The {@link Goal}s to close. - */ - void startAutoMode(Proof proof, ImmutableList goals); - - /** - * Requests to stop the current auto mode without blocking the current {@link Thread} until the auto mode has stopped. - */ - void stopAutoMode(); - - /** - * Stops the currently running auto mode and blocks the current {@link Thread} until auto mode has stopped. - */ - void stopAndWaitAutoMode(); - - /** - * Blocks the current {@link Thread} while the auto mode of this - * {@link UserInterfaceControl} is active. - */ - void waitWhileAutoMode(); - - /** - * Starts the auto mode for the given proof which must be contained - * in this user interface and blocks the current thread until it - * has finished. - * @param proof The {@link Proof} to start auto mode and to wait for. - * @param goals The {@link Goal}s to close. - */ - void startAndWaitForAutoMode(Proof proof, ImmutableList goals); - - /** - * Starts the auto mode for the given proof which must be contained - * in this user interface and blocks the current thread until it - * has finished. - * @param proof The {@link Proof} to start auto mode and to wait for. - */ - void startAndWaitForAutoMode(Proof proof); - - public void startFocussedAutoMode(PosInOccurrence focus, Goal goal); - - /** - * Runs the given {@link ProofMacro} at the given {@link PosInOccurrence} on the given {@link Node}. - * @param node The {@link Node} to start macro at. - * @param macro The {@link ProofMacro} to execute. - * @param posInOcc The exact {@link PosInOccurrence} at which the {@link ProofMacro} is started at. - */ - public void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc); + public boolean isMinimizeInteraction(); + + public void setMinimizeInteraction(boolean minimizeInteraction); + + /** + * collects all applicable RewriteTaclets of the current goal (called by the SequentViewer) + * + * @return a list of Taclets with all applicable RewriteTaclets + */ + public ImmutableList getRewriteTaclet(Goal focusedGoal, PosInOccurrence pos); + + /** + * collects all applicable FindTaclets of the current goal (called by the SequentViewer) + * + * @return a list of Taclets with all applicable FindTaclets + */ + public ImmutableList getFindTaclet(Goal focusedGoal, PosInOccurrence pos); + + /** + * collects all applicable NoFindTaclets of the current goal (called by the SequentViewer) + * + * @return a list of Taclets with all applicable NoFindTaclets + */ + public ImmutableList getNoFindTaclet(Goal focusedGoal); + + /** + * collects all built-in rules that are applicable at the given sequent position 'pos'. + * + * @param pos the PosInSequent where to look for applicable rules + */ + public ImmutableList getBuiltInRule(Goal focusedGoal, PosInOccurrence pos); + + public boolean selectedTaclet(Taclet taclet, Goal goal, PosInOccurrence pos); + + /** + * Apply a RuleApp and continue with update simplification or strategy application according to + * current settings. + * + * @param app + * @param goal + */ + public void applyInteractive(RuleApp app, Goal goal); + + /** + * selected rule to apply + * + * @param rule the selected built-in rule + * @param pos the PosInSequent describes the position where to apply the rule + * @param forced a boolean indicating that if the rule is complete or can be made complete + * automatically then the rule should be applied automatically without asking the user at + * all (e.g. if a loop invariant is available do not ask the user to provide one) + * @param interactive whether the rule was applied by the user + */ + public void selectedBuiltInRule(Goal goal, BuiltInRule rule, PosInOccurrence pos, + boolean forced, boolean interactive); + + /** + * Returns the default {@link ProverTaskListener} which will be added to all started + * {@link ApplyStrategy} instances. + * + * @return The default {@link ProverTaskListener} which will be added to all started + * {@link ApplyStrategy} instances. + */ + public ProverTaskListener getDefaultProverTaskListener(); + + public void addAutoModeListener(AutoModeListener p); + + public void removeAutoModeListener(AutoModeListener p); + + /** + * Checks if the auto mode of this {@link UserInterfaceControl} supports the given + * {@link Proof}. + * + * @param proof The {@link Proof} to check. + * @return {@code true} auto mode support proofs, {@code false} auto mode don't support proof. + */ + boolean isAutoModeSupported(Proof proof); + + /** + * Checks if the auto mode is currently running. + * + * @return {@code true} auto mode is running, {@code false} auto mode is not running. + */ + boolean isInAutoMode(); + + /** + * Starts the auto mode for the given {@link Proof}. + * + * @param proof The {@link Proof} to start auto mode of. + */ + void startAutoMode(Proof proof); + + /** + * Starts the auto mode for the given {@link Proof} and the given {@link Goal}s. + * + * @param proof The {@link Proof} to start auto mode of. + * @param goals The {@link Goal}s to close. + */ + void startAutoMode(Proof proof, ImmutableList goals); + + /** + * Requests to stop the current auto mode without blocking the current {@link Thread} until the + * auto mode has stopped. + */ + void stopAutoMode(); + + /** + * Stops the currently running auto mode and blocks the current {@link Thread} until auto mode + * has stopped. + */ + void stopAndWaitAutoMode(); + + /** + * Blocks the current {@link Thread} while the auto mode of this {@link UserInterfaceControl} is + * active. + */ + void waitWhileAutoMode(); + + /** + * Starts the auto mode for the given proof which must be contained in this user interface and + * blocks the current thread until it has finished. + * + * @param proof The {@link Proof} to start auto mode and to wait for. + * @param goals The {@link Goal}s to close. + */ + void startAndWaitForAutoMode(Proof proof, ImmutableList goals); + + /** + * Starts the auto mode for the given proof which must be contained in this user interface and + * blocks the current thread until it has finished. + * + * @param proof The {@link Proof} to start auto mode and to wait for. + */ + void startAndWaitForAutoMode(Proof proof); + + public void startFocussedAutoMode(PosInOccurrence focus, Goal goal); + + /** + * Runs the given {@link ProofMacro} at the given {@link PosInOccurrence} on the given + * {@link Node}. + * + * @param node The {@link Node} to start macro at. + * @param macro The {@link ProofMacro} to execute. + * @param posInOcc The exact {@link PosInOccurrence} at which the {@link ProofMacro} is started + * at. + */ + public void runMacro(Node node, ProofMacro macro, PosInOccurrence posInOcc); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/RuleCompletionHandler.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/RuleCompletionHandler.java index 94522efa6ea..47e77eafc29 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/RuleCompletionHandler.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/RuleCompletionHandler.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import de.uka.ilkd.key.control.instantiation_model.TacletInstantiationModel; @@ -6,25 +9,30 @@ import de.uka.ilkd.key.rule.Rule; /** - * Instances of this class are used by an {@link AbstractProofControl} to complete a {@link Rule} completion. + * Instances of this class are used by an {@link AbstractProofControl} to complete a {@link Rule} + * completion. + * * @author Martin Hentschel */ public interface RuleCompletionHandler { - /** - * called to complete and apply a taclet instantiations - * @param models the partial models with all different possible instantiations found automatically - * @param goal the Goal where to apply - */ - public void completeAndApplyTacletMatch(TacletInstantiationModel[] models, Goal goal); + /** + * called to complete and apply a taclet instantiations + * + * @param models the partial models with all different possible instantiations found + * automatically + * @param goal the Goal where to apply + */ + public void completeAndApplyTacletMatch(TacletInstantiationModel[] models, Goal goal); - /** - * completes rule applications of built in rules - * @param app the DefaultBuiltInRuleApp to be completed - * @param goal the Goal where the app will later be applied to - * @param forced a boolean indicating if the rule should be applied without any - * additional interaction from the user provided that the application object can be - * made complete automatically - * @return a complete app or null if no completion was possible - */ - public IBuiltInRuleApp completeBuiltInRuleApp(IBuiltInRuleApp app, Goal goal, boolean forced); -} \ No newline at end of file + /** + * completes rule applications of built in rules + * + * @param app the DefaultBuiltInRuleApp to be completed + * @param goal the Goal where the app will later be applied to + * @param forced a boolean indicating if the rule should be applied without any additional + * interaction from the user provided that the application object can be made complete + * automatically + * @return a complete app or null if no completion was possible + */ + public IBuiltInRuleApp completeBuiltInRuleApp(IBuiltInRuleApp app, Goal goal, boolean forced); +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/TermLabelVisibilityManager.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/TermLabelVisibilityManager.java index 91907fcae40..cb811c16c48 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/TermLabelVisibilityManager.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/TermLabelVisibilityManager.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.util.Collections; @@ -22,7 +25,7 @@ public class TermLabelVisibilityManager implements VisibleTermLabels { /** * The names of all term labels that should not be printed by default. */ - private static final Name[] HIDDEN_BY_DEFAULT = { }; + private static final Name[] HIDDEN_BY_DEFAULT = {}; /** * The names of all term labels that should never be printed. @@ -35,16 +38,16 @@ public class TermLabelVisibilityManager implements VisibleTermLabels { private boolean showLabels = true; /** - * The names of all term labels that should not be printed, this contains - * also the labels in {@link TermLabelVisibilityManager#HIDDEN_BY_DEFAULT}. + * The names of all term labels that should not be printed, this contains also the labels in + * {@link TermLabelVisibilityManager#HIDDEN_BY_DEFAULT}. */ private final Set hiddenLabels = new HashSet(); /** * All available {@link TermLabelVisibilityManagerListener}s. */ - private final List listeners - = new LinkedList(); + private final List listeners = + new LinkedList(); /** * Constructs a new TermLabelVisibilityManager. @@ -62,6 +65,7 @@ public TermLabelVisibilityManager() { /** * Gives the information whether currently term labels should be shown or not. + * * @return A boolean value whether currently term labels should be shown. */ public boolean isShowLabels() { @@ -70,6 +74,7 @@ public boolean isShowLabels() { /** * Set the switch whether term labels should be shown to passed value. + * * @param showLabels A boolean value whether term labels should be shown */ public void setShowLabels(boolean showLabels) { @@ -81,6 +86,7 @@ public void setShowLabels(boolean showLabels) { /** * Gives the information whether the term label with the passed name is currently hidden. + * * @param labelName The name of a term label * @return A boolean value whether the investigated term label is hidden. */ @@ -90,6 +96,7 @@ public boolean isHidden(Name labelName) { /** * Sets the state of the term label with the passed name to hidden or not. + * * @param labelName The name of a term label * @param hidden The boolean value whether the term label should be hidden or not */ @@ -127,6 +134,7 @@ public boolean contains(Name labelName) { /** * Registers the given {@link TermLabelVisibilityManagerListener}. + * * @param l The {@link TermLabelVisibilityManagerListener} to add. */ public void addTermLabelVisibilityManagerListener(TermLabelVisibilityManagerListener l) { @@ -137,6 +145,7 @@ public void addTermLabelVisibilityManagerListener(TermLabelVisibilityManagerList /** * Unregisters the given {@link TermLabelVisibilityManagerListener}. + * * @param l The {@link TermLabelVisibilityManagerListener} to remove. */ public void removeTermLabelVisibilityManagerListener(TermLabelVisibilityManagerListener l) { @@ -147,6 +156,7 @@ public void removeTermLabelVisibilityManagerListener(TermLabelVisibilityManagerL /** * Returns all available {@link TermLabelVisibilityManagerListener}. + * * @return all available {@link TermLabelVisibilityManagerListener}. */ public TermLabelVisibilityManagerListener[] getTermLabelVisibilityManagerListeners() { @@ -155,9 +165,9 @@ public TermLabelVisibilityManagerListener[] getTermLabelVisibilityManagerListene /** * Fires the event - * {@link TermLabelVisibilityManagerListener#visibleLabelsChanged( - * TermLabelVisibilityManagerEvent)} + * {@link TermLabelVisibilityManagerListener#visibleLabelsChanged( TermLabelVisibilityManagerEvent)} * to all listeners. + * * @param e The event object. */ protected void fireVisibleLabelsChanged(TermLabelVisibilityManagerEvent e) { @@ -169,6 +179,7 @@ protected void fireVisibleLabelsChanged(TermLabelVisibilityManagerEvent e) { /** * Returns a sorted list of all term label names supported by the given {@link Proof}. + * * @param proof The given {@link Proof}. * @return The sorted list of supported term label names. */ @@ -178,6 +189,7 @@ public static List getSortedTermLabelNames(Proof proof) { /** * Returns a sorted list of all term label names supported by the given {@link Profile}. + * * @param profile The given {@link Profile}. * @return The sorted list of supported term label names. */ @@ -188,6 +200,7 @@ public static List getSortedTermLabelNames(Profile profile) { /** * Returns a sorted list of all term TermLabelManager names supported by the given * {@link TermLabelManager}. + * * @param manager The given {@link Profile}. * @return The sorted list of supported term label names. */ diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/UserInterfaceControl.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/UserInterfaceControl.java index b1f6087be1a..d4a8d9e67e2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/UserInterfaceControl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/UserInterfaceControl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control; import java.io.File; @@ -18,84 +21,89 @@ /** * Provides the user interface independent logic to manage multiple proofs. This includes: *
      - *
    • Functionality to load files via - * {@link #load(Profile, File, List, File, List, Properties, - * boolean)}.
    • - *
    • Functionality to instantiate new {@link Proof}s via {@link #createProof(InitConfig, ProofOblInput)}.
    • - *
    • Functionality to register existing {@link Proof}s in the user interface via {@link #registerProofAggregate(ProofAggregate)}.
    • - *
    • Access to the {@link ProofControl} via {@link #getProofControl()}.
    • + *
    • Functionality to load files via {@link #load(Profile, File, List, File, List, + * Properties, boolean)}.
    • + *
    • Functionality to instantiate new {@link Proof}s via + * {@link #createProof(InitConfig, ProofOblInput)}.
    • + *
    • Functionality to register existing {@link Proof}s in the user interface via + * {@link #registerProofAggregate(ProofAggregate)}.
    • + *
    • Access to the {@link ProofControl} via {@link #getProofControl()}.
    • *
    + * * @author Martin Hentschel */ public interface UserInterfaceControl { - /** - * Registers the given {@link ProverTaskListener} which will be informed about all events. - * @param ptl The {@link ProverTaskListener} to add. - */ - void addProverTaskListener(ProverTaskListener ptl); - - /** - * Removes the given {@link ProverTaskListener}. - * @param ptl The {@link ProverTaskListener} to remove. - */ - void removeProverTaskListener(ProverTaskListener ptl); - + /** + * Registers the given {@link ProverTaskListener} which will be informed about all events. + * + * @param ptl The {@link ProverTaskListener} to add. + */ + void addProverTaskListener(ProverTaskListener ptl); + + /** + * Removes the given {@link ProverTaskListener}. + * + * @param ptl The {@link ProverTaskListener} to remove. + */ + void removeProverTaskListener(ProverTaskListener ptl); + /** *

    - * Opens a java file in this {@link UserInterfaceControl} and returns the instantiated {@link AbstractProblemLoader} - * which can be used to instantiated proofs programmatically. + * Opens a java file in this {@link UserInterfaceControl} and returns the instantiated + * {@link AbstractProblemLoader} which can be used to instantiated proofs programmatically. *

    *

    * The loading is performed in the {@link Thread} of the caller! *

    - * @param profile An optional {@link Profile} to use. If it is {@code null} - * the default profile {@link AbstractProfile#getDefaultProfile()} is used. + * + * @param profile An optional {@link Profile} to use. If it is {@code null} the default profile + * {@link AbstractProfile#getDefaultProfile()} is used. * @param file The java file to open. * @param classPaths The class path entries to use. * @param bootClassPath The boot class path to use. * @param includes Optional includes to consider. - * @param poPropertiesToForce Some optional {@link Properties} for the PO which extend or overwrite saved PO {@link Properties}. + * @param poPropertiesToForce Some optional {@link Properties} for the PO which extend or + * overwrite saved PO {@link Properties}. * @param forceNewProfileOfNewProofs {@code} true - * {@link AbstractProblemLoader#profileOfNewProofs} will be used as - * {@link Profile} of new proofs, {@code false} {@link Profile} - * specified by problem file will be used for new proofs. + * {@link AbstractProblemLoader#profileOfNewProofs} will be used as {@link Profile} of + * new proofs, {@code false} {@link Profile} specified by problem file will be used for + * new proofs. * @return The opened {@link AbstractProblemLoader}. * @throws ProblemLoaderException Occurred Exception. */ - AbstractProblemLoader load(Profile profile, - File file, - List classPaths, - File bootClassPath, - List includes, - Properties poPropertiesToForce, - boolean forceNewProfileOfNewProofs) throws ProblemLoaderException; - + AbstractProblemLoader load(Profile profile, File file, List classPaths, + File bootClassPath, List includes, Properties poPropertiesToForce, + boolean forceNewProfileOfNewProofs) throws ProblemLoaderException; + /** * Instantiates a new {@link Proof} in this {@link UserInterfaceControl} for the given * {@link ProofOblInput} based on the {@link InitConfig}. + * * @param initConfig The {@link InitConfig} which provides the source code. * @param input The description of the {@link Proof} to instantiate. * @return The instantiated {@link Proof}. * @throws ProofInputException Occurred Exception. */ - Proof createProof(InitConfig initConfig, - ProofOblInput input) throws ProofInputException; + Proof createProof(InitConfig initConfig, ProofOblInput input) throws ProofInputException; /** * Registers an already created {@link ProofAggregate} in this {@link UserInterfaceControl}. + * * @param pa The {@link ProofAggregate} to register. */ void registerProofAggregate(ProofAggregate pa); /** * Returns the used {@link ProofControl}. + * * @return The used {@link ProofControl}. */ public ProofControl getProofControl(); - + /** * Returns the {@link TermLabelVisibilityManager}. + * * @return The {@link TermLabelVisibilityManager}. */ public TermLabelVisibilityManager getTermLabelVisibilityManager(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerEvent.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerEvent.java index 8aea6f34704..88b946505e9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerEvent.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerEvent.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control.event; import java.util.EventObject; @@ -6,27 +9,29 @@ /** * An event thrown by a {@link TermLabelVisibilityManager}. + * * @author Martin Hentschel */ public class TermLabelVisibilityManagerEvent extends EventObject { - /** - * Generated UID. - */ - private static final long serialVersionUID = 2827200355462914026L; + /** + * Generated UID. + */ + private static final long serialVersionUID = 2827200355462914026L; - /** - * Constructor. - * @param source The source {@link TermLabelVisibilityManager}. - */ - public TermLabelVisibilityManagerEvent(TermLabelVisibilityManager source) { - super(source); - } + /** + * Constructor. + * + * @param source The source {@link TermLabelVisibilityManager}. + */ + public TermLabelVisibilityManagerEvent(TermLabelVisibilityManager source) { + super(source); + } - /** - * {@inheritDoc} - */ - @Override - public TermLabelVisibilityManager getSource() { - return (TermLabelVisibilityManager) super.getSource(); - } + /** + * {@inheritDoc} + */ + @Override + public TermLabelVisibilityManager getSource() { + return (TermLabelVisibilityManager) super.getSource(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerListener.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerListener.java index b42188a6651..740cb72a815 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerListener.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/event/TermLabelVisibilityManagerListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control.event; import java.util.EventListener; @@ -6,12 +9,14 @@ /** * Observes changes on a {@link TermLabelVisibilityManager}. + * * @author Martin Hentschel */ public interface TermLabelVisibilityManagerListener extends EventListener { - /** - * When the visible term labels have changed. - * @param e The change event. - */ - public void visibleLabelsChanged(TermLabelVisibilityManagerEvent e); + /** + * When the visible term labels have changed. + * + * @param e The change event. + */ + public void visibleLabelsChanged(TermLabelVisibilityManagerEvent e); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletAssumesModel.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletAssumesModel.java index 35f5bbe63e4..8a39b9176fb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletAssumesModel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletAssumesModel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control.instantiation_model; import java.util.Iterator; @@ -105,8 +108,7 @@ public Term parseFormula(String s) throws RecognitionException { } /** - * @param pos int describes position of the if-sequent (only required for error - * message) + * @param pos int describes position of the if-sequent (only required for error message) * @return the selected instantiation of the if sequent * @throws SVInstantiationParserException * @throws MissingInstantiationException @@ -125,13 +127,11 @@ public IfFormulaInstantiation getSelection(int pos) Term term = parseFormula(manualInput); - if (ProofIndependentSettings.DEFAULT_INSTANCE - .getTermLabelSettings().getUseOriginLabels()) { - term = services.getTermBuilder().addLabelToAllSubs(term, new OriginTermLabel( - new NodeOrigin( - SpecType.USER_INTERACTION, - app.rule().displayName(), - goal.node().serialNr()))); + if (ProofIndependentSettings.DEFAULT_INSTANCE.getTermLabelSettings() + .getUseOriginLabels()) { + term = services.getTermBuilder().addLabelToAllSubs(term, + new OriginTermLabel(new NodeOrigin(SpecType.USER_INTERACTION, + app.rule().displayName(), goal.node().serialNr()))); } return new IfFormulaInstDirect(new SequentFormula(term)); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletFindModel.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletFindModel.java index 46ba9014355..1fc7034892d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletFindModel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletFindModel.java @@ -1,4 +1,7 @@ - package de.uka.ilkd.key.control.instantiation_model; +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ +package de.uka.ilkd.key.control.instantiation_model; import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.Services; @@ -94,8 +97,8 @@ private NamespaceSet namespaces() { */ private ArrayList> createEntryArray(TacletApp tacletApp) { ArrayList> rowVec = new ArrayList<>(); - final Iterator>> it = tacletApp - .instantiations().pairIterator(); + final Iterator>> it = + tacletApp.instantiations().pairIterator(); int count = 0; while (it.hasNext()) { @@ -161,12 +164,11 @@ public boolean isCellEditable(int rowIndex, int columnIndex) { } /** - * parses the given string that represents the term (or formula) using the given - * variable namespace and the given namespace for functions and default - * namespaces for the others + * parses the given string that represents the term (or formula) using the given variable + * namespace and the given namespace for functions and default namespaces for the others * - * @param s the String to parse - * @param varNS the variable namespace + * @param s the String to parse + * @param varNS the variable namespace * @param functNS the function namespace */ private Term parseTerm(String s, Namespace varNS, @@ -179,18 +181,19 @@ private Term parseTerm(String s, Namespace varNS, } /** - * Parse the declaration of an identifier (i.e. the declaration of a variable or - * skolem function) + * Parse the declaration of an identifier (i.e. the declaration of a variable or skolem + * function) */ private IdDeclaration parseIdDeclaration(String s) throws ParserException { - KeYParser.Id_declarationContext ctx = ParsingFacade.parseIdDeclaration(CharStreams.fromString(s)); + KeYParser.Id_declarationContext ctx = + ParsingFacade.parseIdDeclaration(CharStreams.fromString(s)); Sort sort = ctx.s != null ? services.getNamespaces().sorts().lookup(ctx.s.getText()) : null; return new IdDeclaration(ctx.id.getText(), sort); } /** - * throws an exception iff no input in indicated row, and no metavariable - * instantiation is possible + * throws an exception iff no input in indicated row, and no metavariable instantiation is + * possible * */ @@ -212,11 +215,10 @@ private boolean isInputAvailable(int irow) { } /** - * parses the indicated row and returns a Term corresponding to the entry in the - * row + * parses the indicated row and returns a Term corresponding to the entry in the row * - * @param irow the row to be parsed - * @param varNS the variable namespace that will be passed to parseTerm + * @param irow the row to be parsed + * @param varNS the variable namespace that will be passed to parseTerm * @param functNS the function namespace that will be passed to parseTerm * @return the parsed term */ @@ -246,8 +248,8 @@ private Term parseRow(int irow, Namespace varNS, } /** - * parses the indicated row and returns a identifier declaration corresponding - * to the entry in the row + * parses the indicated row and returns a identifier declaration corresponding to the entry in + * the row * * @param irow the row to be parsed * @return the parsed declaration @@ -280,18 +282,15 @@ private Term addOrigin(Term term) { if (ProofIndependentSettings.DEFAULT_INSTANCE.getTermLabelSettings().getUseOriginLabels()) { return services.getTermBuilder().addLabelToAllSubs( OriginTermLabel.removeOriginLabels(term, services), - new OriginTermLabel(new NodeOrigin( - SpecType.USER_INTERACTION, - originalApp.rule().displayName(), - goal.node().serialNr()))); + new OriginTermLabel(new NodeOrigin(SpecType.USER_INTERACTION, + originalApp.rule().displayName(), goal.node().serialNr()))); } else { return term; } } /** - * parses the indicated row and returns the ProgramElement corresponding to the - * entry in the row + * parses the indicated row and returns the ProgramElement corresponding to the entry in the row * * @param irow the row to be parsed * @return the parsed term @@ -301,8 +300,8 @@ private ProgramElement parseRow(int irow) throws SVInstantiationParserException String instantiation = (String) getValueAt(irow, 1); SchemaVariable sv = (SchemaVariable) getValueAt(irow, 0); - ContextInstantiationEntry contextInstantiation = originalApp.instantiations() - .getContextInstantiation(); + ContextInstantiationEntry contextInstantiation = + originalApp.instantiations().getContextInstantiation(); final PosInProgram prefix; if (contextInstantiation == null) { @@ -404,11 +403,11 @@ public TacletApp createTacletAppFromVarInsts() throws SVInstantiationException { result = result.addCheckedInstantiation(sv, pe, services, true); } else { if (isInputAvailable(irow)) { - final Namespace extVarNS = result - .extendVarNamespaceForSV(nss.variables(), sv); + final Namespace extVarNS = + result.extendVarNamespaceForSV(nss.variables(), sv); - Namespace functNS = result - .extendedFunctionNameSpace(nss.functions()); + Namespace functNS = + result.extendedFunctionNameSpace(nss.functions()); final Term instance = parseRow(irow, extVarNS, functNS); sort = instance.sort(); @@ -457,8 +456,7 @@ public Object getValueAt(int row, int col) { /** * returns the index of the row the given Schemavariable stands * - * @return the index of the row the given Schemavariable stands (-1 if not - * found) + * @return the index of the row the given Schemavariable stands (-1 if not found) */ private int getSVRow(SchemaVariable sv) { int rowIndex = 0; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletInstantiationModel.java b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletInstantiationModel.java index cc3c8a5945a..295057c00aa 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletInstantiationModel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/control/instantiation_model/TacletInstantiationModel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.control.instantiation_model; import java.util.Iterator; @@ -40,8 +43,8 @@ public class TacletInstantiationModel { private final TacletFindModel tableModel; /** - * the application of the Taclet of which this model is used to complete the - * instantiations of the schemavariables and/or if-sequent + * the application of the Taclet of which this model is used to complete the instantiations of + * the schemavariables and/or if-sequent */ private TacletApp app; @@ -62,8 +65,8 @@ public class TacletInstantiationModel { private final Goal goal; /** - * Create new data model for the apply Taclet dialog wrapping a combo box model - * and a table model. + * Create new data model for the apply Taclet dialog wrapping a combo box model and a table + * model. * * @param app * @param seq @@ -131,10 +134,10 @@ private void initIfChoiceModels() { int size = asize + ifseq.succedent().size(); if (size > 0) { - ImmutableList antecCand = IfFormulaInstSeq.createList(seq, true, - services); - ImmutableList succCand = IfFormulaInstSeq.createList(seq, false, - services); + ImmutableList antecCand = + IfFormulaInstSeq.createList(seq, true, services); + ImmutableList succCand = + IfFormulaInstSeq.createList(seq, false, services); Iterator it = ifseq.iterator(); Term ifFma; @@ -144,9 +147,10 @@ private void initIfChoiceModels() { for (int i = 0; i < size; i++) { ifFma = it.next().formula(); - ifChoiceModel[i] = new TacletAssumesModel(ifFma, taclet().getMatcher() - .matchIf((i < asize ? antecCand : succCand), ifFma, matchCond, services) - .getFormulas(), app, goal, services, nss, scm); + ifChoiceModel[i] = new TacletAssumesModel( + ifFma, taclet().getMatcher().matchIf((i < asize ? antecCand : succCand), + ifFma, matchCond, services).getFormulas(), + app, goal, services, nss, scm); } } else { ifChoiceModel = EMPTY_IF_CHOICES; @@ -156,8 +160,8 @@ private void initIfChoiceModels() { private TacletApp createTacletAppFromIfs(TacletApp tacletApp) throws IfMismatchException, SVInstantiationParserException, MissingInstantiationException, SortMismatchException { - ImmutableList instList = ImmutableSLList - .nil(); + ImmutableList instList = + ImmutableSLList.nil(); for (int i = ifChoiceModel.length - 1; i >= 0; --i) { instList = instList.prepend(ifChoiceModel[i].getSelection(i)); @@ -218,9 +222,9 @@ public void setManualInput(int i, String s) { } /** - * replaces the TacletApp of this ApplyTacletDialogModel by an TacletApp where - * all name conflicts are resolved and thus the parser is enabled to accept - * variables from the context or the prefix of the Taclet. + * replaces the TacletApp of this ApplyTacletDialogModel by an TacletApp where all name + * conflicts are resolved and thus the parser is enabled to accept variables from the context or + * the prefix of the Taclet. * */ public void prepareUnmatchedInstantiation() { @@ -240,4 +244,4 @@ public Services getServices() { return services; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AbstractFinishAuxiliaryComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AbstractFinishAuxiliaryComputationMacro.java index 5ad8f57631b..b00a7aa0268 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AbstractFinishAuxiliaryComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AbstractFinishAuxiliaryComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import java.util.Map; @@ -46,15 +49,11 @@ public String getDescription() { return "Finish auxiliary computation."; } - static Term calculateResultingTerm(Proof proof, - IFProofObligationVars ifVars, - Goal initGoal) { + static Term calculateResultingTerm(Proof proof, IFProofObligationVars ifVars, Goal initGoal) { final Term[] goalFormulas1 = - buildExecution(ifVars.c1, ifVars.getMapFor(ifVars.c1), - proof.openGoals(), initGoal); + buildExecution(ifVars.c1, ifVars.getMapFor(ifVars.c1), proof.openGoals(), initGoal); final Term[] goalFormulas2 = - buildExecution(ifVars.c2, ifVars.getMapFor(ifVars.c2), - proof.openGoals(), initGoal); + buildExecution(ifVars.c2, ifVars.getMapFor(ifVars.c2), proof.openGoals(), initGoal); final TermBuilder tb = proof.getServices().getTermBuilder(); Term composedStates = tb.ff(); for (int i = 0; i < goalFormulas1.length; i++) { @@ -92,23 +91,17 @@ private final void mergeNamespace(Namespace tar, Namespace< } } - private static Term[] buildExecution(ProofObligationVars c, - Map vsMap, - ImmutableList symbExecGoals, - Goal initGoal) { + private static Term[] buildExecution(ProofObligationVars c, Map vsMap, + ImmutableList symbExecGoals, Goal initGoal) { Services services = initGoal.proof().getServices(); final Term[] goalFormulas = buildFormulasFromGoals(symbExecGoals); - final InfFlowProgVarRenamer renamer = - new InfFlowProgVarRenamer(goalFormulas, vsMap, - c.postfix, initGoal, - services.getOverlay(initGoal.getLocalNamespaces())); - final Term[] renamedGoalFormulas = - renamer.renameVariablesAndSkolemConstants(); + final InfFlowProgVarRenamer renamer = new InfFlowProgVarRenamer(goalFormulas, vsMap, + c.postfix, initGoal, services.getOverlay(initGoal.getLocalNamespaces())); + final Term[] renamedGoalFormulas = renamer.renameVariablesAndSkolemConstants(); Term[] result = new Term[renamedGoalFormulas.length]; final TermBuilder tb = services.getTermBuilder(); for (int i = 0; i < renamedGoalFormulas.length; i++) { - result[i] = - tb.applyElementary(c.pre.heap, renamedGoalFormulas[i]); + result[i] = tb.applyElementary(c.pre.heap, renamedGoalFormulas[i]); } return result; } @@ -137,12 +130,10 @@ private static Term buildFormulaFromGoal(Goal symbExecGoal) { return result; } - protected static void addContractApplicationTaclets(Goal initiatingGoal, - Proof symbExecProof) { + protected static void addContractApplicationTaclets(Goal initiatingGoal, Proof symbExecProof) { final ImmutableList openGoals = symbExecProof.openGoals(); for (final Goal openGoal : openGoals) { - final Set ruleApps = - openGoal.indexOfTaclets().allNoPosTacletApps(); + final Set ruleApps = openGoal.indexOfTaclets().allNoPosTacletApps(); for (final NoPosTacletApp ruleApp : ruleApps) { final Taclet t = ruleApp.taclet(); if (t.getSurviveSymbExec()) { @@ -151,4 +142,4 @@ protected static void addContractApplicationTaclets(Goal initiatingGoal, } } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AuxiliaryComputationAutoPilotMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AuxiliaryComputationAutoPilotMacro.java index 9ac88e490eb..6b64a799a03 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AuxiliaryComputationAutoPilotMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/AuxiliaryComputationAutoPilotMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import de.uka.ilkd.key.macros.FinishSymbolicExecutionMacro; @@ -25,9 +28,8 @@ public String getCategory() { @Override public String getDescription() { - return "
    1. Start auxiliary computation" + - "
    2. Finish symbolic execution" + - "
    3. Try to close as many goals as possible
    "; + return "
    1. Start auxiliary computation" + "
    2. Finish symbolic execution" + + "
    3. Try to close as many goals as possible
    "; } @@ -35,43 +37,58 @@ public String getDescription() { ProofMacro getProofMacro() { return new SequentialOnLastGoalProofMacro() { /** - * The number of proof steps that should be run by the - * {@link TryCloseMacro} before retracting. This overrides the - * strategy setting. + * The number of proof steps that should be run by the {@link TryCloseMacro} before + * retracting. This overrides the strategy setting. */ private final int NUMBER_OF_TRY_STEPS = Integer.getInteger("key.autopilot.closesteps", 1000); @Override - public String getName() { return ""; } + public String getName() { + return ""; + } + @Override - public String getCategory() { return null; } + public String getCategory() { + return null; + } + @Override - public String getDescription() { return "Anonymous Macro"; } + public String getDescription() { + return "Anonymous Macro"; + } @Override protected ProofMacro[] createProofMacroArray() { // The FinishSymbolicExecutionMacro and the TryCloseMacro shall be // started at the same node. Therefore they are encapsulated in an // own (anonymous) SequentialProofMacro. - SequentialProofMacro finishSymbExecAndTryToClose = - new SequentialProofMacro() { + SequentialProofMacro finishSymbExecAndTryToClose = new SequentialProofMacro() { @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[]{ new FinishSymbolicExecutionMacro(), - new TryCloseMacro(NUMBER_OF_TRY_STEPS)}; + return new ProofMacro[] { new FinishSymbolicExecutionMacro(), + new TryCloseMacro(NUMBER_OF_TRY_STEPS) }; } + @Override - public String getName() { return ""; } + public String getName() { + return ""; + } + @Override - public String getCategory() { return null; } + public String getCategory() { + return null; + } + @Override - public String getDescription() { return "Anonymous Macro"; } + public String getDescription() { + return "Anonymous Macro"; + } }; - return new ProofMacro[]{ new StartAuxiliaryComputationMacro(), - finishSymbExecAndTryToClose }; + return new ProofMacro[] { new StartAuxiliaryComputationMacro(), + finishSymbExecAndTryToClose }; } }; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/ExhaustiveProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/ExhaustiveProofMacro.java index 4a5f31da063..b8ac66956ff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/ExhaustiveProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/ExhaustiveProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; @@ -24,20 +27,17 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * The abstract class ExhaustiveProofMacro can be used to create compound macros - * which either apply the macro given by {@link getProofMacro()} directly, or - * --if not directly applicable-- search on the sequent for any applicable - * posInOcc and apply it on the first applicable one or --if not applicable - * anywhere on the sequent-- do not apply it. + * The abstract class ExhaustiveProofMacro can be used to create compound macros which either apply + * the macro given by {@link getProofMacro()} directly, or --if not directly applicable-- search on + * the sequent for any applicable posInOcc and apply it on the first applicable one or --if not + * applicable anywhere on the sequent-- do not apply it. * * @author Michael Kirsten */ public abstract class ExhaustiveProofMacro extends AbstractProofMacro { - private PosInOccurrence getApplicablePosInOcc(Proof proof, - Goal goal, - PosInOccurrence posInOcc, - ProofMacro macro) { + private PosInOccurrence getApplicablePosInOcc(Proof proof, Goal goal, PosInOccurrence posInOcc, + ProofMacro macro) { if (posInOcc == null || posInOcc.subTerm() == null) { return null; } else if (macro.canApplyTo(proof, ImmutableSLList.nil().prepend(goal), posInOcc)) { @@ -52,7 +52,9 @@ private PosInOccurrence getApplicablePosInOcc(Proof proof, } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getName() */ @Override @@ -60,34 +62,34 @@ public String getName() { return "Apply macro on first applicable position in the sequent."; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getDescription() */ @Override - public String getDescription() { - return "Applies specificed macro --if it is applicable anywhere on" + - "the sequent-- either directly or on the first applicable" + - "position found."; + public String getDescription() { + return "Applies specificed macro --if it is applicable anywhere on" + + "the sequent-- either directly or on the first applicable" + "position found."; } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { final Services services = proof.getServices(); - - final Map applicableOnNodeAtPos = services.getCaches().getExhaustiveMacroCache(); - + + final Map applicableOnNodeAtPos = + services.getCaches().getExhaustiveMacroCache(); + Sequent seq = null; boolean applicable = false; - final ProofMacro macro = getProofMacro(); - for (final Goal goal: goals) { - seq = goal.sequent(); - synchronized(applicableOnNodeAtPos) { + final ProofMacro macro = getProofMacro(); + for (final Goal goal : goals) { + seq = goal.sequent(); + synchronized (applicableOnNodeAtPos) { if (!applicableOnNodeAtPos.containsKey(goal.node())) { // node has not been checked before, so do it - for (int i = 1; i <= seq.size() && - applicableOnNodeAtPos.get(goal.node()) == null; i++) { + for (int i = 1; i <= seq.size() + && applicableOnNodeAtPos.get(goal.node()) == null; i++) { PosInOccurrence searchPos = PosInOccurrence.findInSequent(seq, i, PosInTerm.getTopLevel()); PosInOccurrence applicableAt = @@ -96,24 +98,23 @@ public boolean canApplyTo(Proof proof, } } } - + applicable = applicable || applicableOnNodeAtPos.get(goal.node()) != null; } return applicable; } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception { - - final Map applicableOnNodeAtPos = proof.getServices().getCaches().getExhaustiveMacroCache(); - ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals); + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception { + + final Map applicableOnNodeAtPos = + proof.getServices().getCaches().getExhaustiveMacroCache(); + ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals); final ProofMacro macro = getProofMacro(); - - synchronized(applicableOnNodeAtPos) { + + synchronized (applicableOnNodeAtPos) { for (final Goal goal : goals) { boolean isCached; isCached = applicableOnNodeAtPos.containsKey(goal.node()); @@ -129,7 +130,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, } } - final PosInOccurrence applicableAt; + final PosInOccurrence applicableAt; applicableAt = applicableOnNodeAtPos.get(goal.node()); @@ -137,7 +138,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final ProverTaskListener pml = new ProofMacroListener(macro.getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, getName(), 0)); - synchronized(macro) { + synchronized (macro) { // wait for macro to terminate info = macro.applyTo(uic, proof, ImmutableSLList.nil().prepend(goal), applicableAt, pml); @@ -154,7 +155,8 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, /** * Gets the proof macros. *

    + * * @return the proofMacro. */ abstract ProofMacro getProofMacro(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryBlockComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryBlockComputationMacro.java index ba254b6d503..56c5ddb614b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryBlockComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryBlockComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -25,18 +28,15 @@ * * @author christoph */ -public class FinishAuxiliaryBlockComputationMacro - extends AbstractFinishAuxiliaryComputationMacro { +public class FinishAuxiliaryBlockComputationMacro extends AbstractFinishAuxiliaryComputationMacro { @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof != null && proof.getServices() != null) { final ProofOblInput poForProof = proof.getServices().getSpecificationRepository().getProofOblInput(proof); if (poForProof instanceof BlockExecutionPO) { - final Goal initiatingGoal = ((BlockExecutionPO)poForProof).getInitiatingGoal(); + final Goal initiatingGoal = ((BlockExecutionPO) poForProof).getInitiatingGoal(); if (initiatingGoal.node().parent() != null) { final RuleApp app = initiatingGoal.node().parent().getAppliedRuleApp(); if (app instanceof BlockContractInternalBuiltInRuleApp) { @@ -49,11 +49,8 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - final Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) { assert canApplyTo(proof, goals, posInOcc); final ProofOblInput poForProof = @@ -72,7 +69,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final RuleApp app = initiatingGoal.node().parent().getAppliedRuleApp(); final BlockContractInternalBuiltInRuleApp blockRuleApp = - (BlockContractInternalBuiltInRuleApp)app; + (BlockContractInternalBuiltInRuleApp) app; final BlockContract contract = blockRuleApp.getContract(); IFProofObligationVars ifVars = blockRuleApp.getInformationFlowProofObligationVars(); ifVars = ifVars.labelHeapAtPreAsAnonHeapFunc(); @@ -81,15 +78,15 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, // create and register resulting taclets final Term result = calculateResultingTerm(proof, ifVars, initiatingGoal); - final Taclet rwTaclet = buildBlockInfFlowUnfoldTaclet( - services, blockRuleApp, contract, ifVars, result); + final Taclet rwTaclet = + buildBlockInfFlowUnfoldTaclet(services, blockRuleApp, contract, ifVars, result); initiatingProof.addLabeledTotalTerm(result); initiatingProof.addLabeledIFSymbol(rwTaclet); initiatingGoal.addTaclet(rwTaclet, SVInstantiations.EMPTY_SVINSTANTIATIONS, true); addContractApplicationTaclets(initiatingGoal, proof); - initiatingProof.unionIFSymbols(((InfFlowProof)proof).getIFSymbols()); + initiatingProof.unionIFSymbols(((InfFlowProof) proof).getIFSymbols()); initiatingProof.getIFSymbols().useProofSymbols(); // close auxiliary computation proof @@ -101,18 +98,18 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, /** * constructs a taclet to unfold block contracts for information flow reasoning + * * @param services the Services * @param blockRuleApp the rule application of the block contract * @param contract the block contract * @param ifVars variables specific for the IF proof obligation - * @param result the term representing the result (?) // TODO: someone who knows what the taclet does please provide a description + * @param result the term representing the result (?) // TODO: someone who knows what the taclet + * does please provide a description * @return the created taclet */ - private Taclet buildBlockInfFlowUnfoldTaclet( - final Services services, - final BlockContractInternalBuiltInRuleApp blockRuleApp, - final BlockContract contract, IFProofObligationVars ifVars, - final Term result) { + private Taclet buildBlockInfFlowUnfoldTaclet(final Services services, + final BlockContractInternalBuiltInRuleApp blockRuleApp, final BlockContract contract, + IFProofObligationVars ifVars, final Term result) { final BlockInfFlowUnfoldTacletBuilder tacletBuilder = new BlockInfFlowUnfoldTacletBuilder(services); tacletBuilder.setContract(contract); @@ -121,4 +118,4 @@ private Taclet buildBlockInfFlowUnfoldTaclet( tacletBuilder.setReplacewith(result); return tacletBuilder.buildTaclet(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryComputationMacro.java index 0090e9026c8..7e073842085 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import de.uka.ilkd.key.macros.AlternativeMacro; @@ -28,7 +31,7 @@ public String getScriptCommandName() { @Override protected ProofMacro[] createProofMacroArray() { return new ProofMacro[] { new FinishAuxiliaryMethodComputationMacro(), - new FinishAuxiliaryLoopComputationMacro(), - new FinishAuxiliaryBlockComputationMacro()}; + new FinishAuxiliaryLoopComputationMacro(), + new FinishAuxiliaryBlockComputationMacro() }; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryLoopComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryLoopComputationMacro.java index e82c1de35a7..77b3bd3ac26 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryLoopComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryLoopComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -21,21 +24,19 @@ import de.uka.ilkd.key.rule.inst.SVInstantiations; import de.uka.ilkd.key.speclang.LoopSpecification; -public class FinishAuxiliaryLoopComputationMacro extends - AbstractFinishAuxiliaryComputationMacro { +public class FinishAuxiliaryLoopComputationMacro extends AbstractFinishAuxiliaryComputationMacro { @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof != null && proof.getServices() != null) { final ProofOblInput poForProof = proof.getServices().getSpecificationRepository().getProofOblInput(proof); if (poForProof instanceof LoopInvExecutionPO) { - final Node parentOfInitiatingGoal = ((LoopInvExecutionPO) poForProof).getInitiatingGoal().node().parent(); - if (parentOfInitiatingGoal != null && - parentOfInitiatingGoal.getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp) { + final Node parentOfInitiatingGoal = + ((LoopInvExecutionPO) poForProof).getInitiatingGoal().node().parent(); + if (parentOfInitiatingGoal != null && parentOfInitiatingGoal + .getAppliedRuleApp() instanceof LoopInvariantBuiltInRuleApp) { return true; } } @@ -45,11 +46,8 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - final Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) { final ProofOblInput poForProof = proof.getServices().getSpecificationRepository().getProofOblInput(proof); final LoopInvExecutionPO loopInvExecPO = (LoopInvExecutionPO) poForProof; @@ -92,4 +90,4 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryMethodComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryMethodComputationMacro.java index eb422323ce2..2d76fa2b1d5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryMethodComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FinishAuxiliaryMethodComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -24,16 +27,13 @@ * * @author christoph */ -public class FinishAuxiliaryMethodComputationMacro - extends AbstractFinishAuxiliaryComputationMacro { +public class FinishAuxiliaryMethodComputationMacro extends AbstractFinishAuxiliaryComputationMacro { @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof != null && proof.getServices() != null) { final ProofOblInput poForProof = - proof.getServices().getSpecificationRepository().getProofOblInput(proof); + proof.getServices().getSpecificationRepository().getProofOblInput(proof); if (poForProof instanceof SymbolicExecutionPO) { return true; } @@ -42,20 +42,16 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - final Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) { final ProofOblInput poForProof = proof.getServices().getSpecificationRepository().getProofOblInput(proof); final Goal initiatingGoal = ((SymbolicExecutionPO) poForProof).getInitiatingGoal(); final InfFlowProof initiatingProof = (InfFlowProof) initiatingGoal.proof(); final Services services = initiatingProof.getServices(); - final InfFlowContractPO ifPO = - (InfFlowContractPO) services.getSpecificationRepository() - .getProofOblInput(initiatingProof); + final InfFlowContractPO ifPO = (InfFlowContractPO) services.getSpecificationRepository() + .getProofOblInput(initiatingProof); final IFProofObligationVars ifVars = ifPO.getIFVars().labelHeapAtPreAsAnonHeapFunc(); final InformationFlowContract ifContract = ifPO.getContract(); @@ -84,4 +80,4 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullInformationFlowAutoPilotMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullInformationFlowAutoPilotMacro.java index 8c594762e22..ace2fa12dc5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullInformationFlowAutoPilotMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullInformationFlowAutoPilotMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -19,9 +22,8 @@ public class FullInformationFlowAutoPilotMacro extends DoWhileFinallyMacro { /** - * The number of proof steps that should be run by the {@link TryCloseMacro} - * before retracting. This overrides the strategy setting if set to a value - * greater or equal to 0. + * The number of proof steps that should be run by the {@link TryCloseMacro} before retracting. + * This overrides the strategy setting if set to a value greater or equal to 0. */ private static final int NUMBER_OF_TRY_STEPS = -1; @@ -42,62 +44,82 @@ public String getScriptCommandName() { @Override public String getDescription() { - return "

    1. Search exhaustively for applicable position, then" + - "
    2. Start auxiliary computation" + - "
    3. Finish symbolic execution" + - "
    4. Try to close as many goals as possible" + - "
    5. Apply macro recursively" + - "
    6. Finish auxiliary computation" + - "
    7. Use information flow contracts" + - "
    8. Try to close as many goals as possible
    "; + return "
    1. Search exhaustively for applicable position, then" + + "
    2. Start auxiliary computation" + "
    3. Finish symbolic execution" + + "
    4. Try to close as many goals as possible" + "
    5. Apply macro recursively" + + "
    6. Finish auxiliary computation" + "
    7. Use information flow contracts" + + "
    8. Try to close as many goals as possible
    "; } @Override protected ProofMacro getProofMacro() { - final SequentialProofMacro stateExpansionAndCloseMacro = - new SequentialProofMacro() { - @Override - protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { - new StateExpansionAndInfFlowContractApplicationMacro(), - new TryCloseMacro(NUMBER_OF_TRY_STEPS) }; - } - @Override - public String getName() { return ""; } - @Override - public String getCategory() { return null; } - @Override - public String getDescription() { return "Anonymous Macro"; } + final SequentialProofMacro stateExpansionAndCloseMacro = new SequentialProofMacro() { + @Override + protected ProofMacro[] createProofMacroArray() { + return new ProofMacro[] { new StateExpansionAndInfFlowContractApplicationMacro(), + new TryCloseMacro(NUMBER_OF_TRY_STEPS) }; + } + + @Override + public String getName() { + return ""; + } + + @Override + public String getCategory() { + return null; + } + + @Override + public String getDescription() { + return "Anonymous Macro"; + } }; - final SequentialProofMacro finishMainCompMacro = - new SequentialOnLastGoalProofMacro() { - @Override - protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { new FinishAuxiliaryComputationMacro(), - stateExpansionAndCloseMacro }; - } - @Override - public String getName() { return ""; } - @Override - public String getCategory() { return null; } - @Override - public String getDescription() { return "Anonymous Macro"; } + final SequentialProofMacro finishMainCompMacro = new SequentialOnLastGoalProofMacro() { + @Override + protected ProofMacro[] createProofMacroArray() { + return new ProofMacro[] { new FinishAuxiliaryComputationMacro(), + stateExpansionAndCloseMacro }; + } + + @Override + public String getName() { + return ""; + } + + @Override + public String getCategory() { + return null; + } + + @Override + public String getDescription() { + return "Anonymous Macro"; + } }; - final AlternativeMacro alternativesMacro = - new AlternativeMacro() { - @Override - public String getName() { return ""; } - @Override - public String getCategory() { return null; } - @Override - public String getDescription() { return "Anonymous Macro"; } - @Override - protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { new AuxiliaryComputationAutoPilotMacro(), - finishMainCompMacro }; - } + final AlternativeMacro alternativesMacro = new AlternativeMacro() { + @Override + public String getName() { + return ""; + } + + @Override + public String getCategory() { + return null; + } + + @Override + public String getDescription() { + return "Anonymous Macro"; + } + + @Override + protected ProofMacro[] createProofMacroArray() { + return new ProofMacro[] { new AuxiliaryComputationAutoPilotMacro(), + finishMainCompMacro }; + } }; return alternativesMacro; @@ -112,19 +134,17 @@ protected ProofMacro getAltProofMacro() { protected boolean getCondition() { return true; } - + /** * {@inheritDoc} * *

    - * This compound macro is applicable if and only if the first macro is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if the first macro is applicable. If there is + * no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof == null) { return false; } @@ -134,6 +154,7 @@ public boolean canApplyTo(Proof proof, } final ProofOblInput poForProof = services.getSpecificationRepository().getProofOblInput(proof); - return (poForProof instanceof AbstractInfFlowPO) && super.canApplyTo(proof, goals, posInOcc); + return (poForProof instanceof AbstractInfFlowPO) + && super.canApplyTo(proof, goals, posInOcc); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullUseInformationFlowContractMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullUseInformationFlowContractMacro.java index e11860622ac..1c8e73cb61e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullUseInformationFlowContractMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/FullUseInformationFlowContractMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -30,8 +33,8 @@ public String getCategory() { @Override public String getDescription() { - return "Applies all applicable information flow contract rules and " + - "prepares the information flow pre branches."; + return "Applies all applicable information flow contract rules and " + + "prepares the information flow pre branches."; } @Override @@ -41,23 +44,19 @@ public String getScriptCommandName() { @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { - new UseInformationFlowContractMacro(), - new PrepareInfFlowContractPreBranchesMacro() - }; + return new ProofMacro[] { new UseInformationFlowContractMacro(), + new PrepareInfFlowContractPreBranchesMacro() }; } /** * {@inheritDoc} * *

    - * This compound macro is applicable if and only if the first macro is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if the first macro is applicable. If there is + * no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof == null) { return false; } @@ -67,6 +66,7 @@ public boolean canApplyTo(Proof proof, } final ProofOblInput poForProof = services.getSpecificationRepository().getProofOblInput(proof); - return (poForProof instanceof AbstractInfFlowPO) && super.canApplyTo(proof, goals, posInOcc); + return (poForProof instanceof AbstractInfFlowPO) + && super.canApplyTo(proof, goals, posInOcc); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/SelfcompositionStateExpansionMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/SelfcompositionStateExpansionMacro.java index e64e6698355..f67e7371d22 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/SelfcompositionStateExpansionMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/SelfcompositionStateExpansionMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import java.util.Set; @@ -23,10 +26,9 @@ import de.uka.ilkd.key.strategy.TopRuleAppCost; /** - * The macro SelfcompositionStateExpansionMacro applies rules to extract - * the self-composed states after the merge of the symbolic execution goals - * which is included in the proof obligation generation from information flow - * contracts. This macro splits the goal. + * The macro SelfcompositionStateExpansionMacro applies rules to extract the self-composed states + * after the merge of the symbolic execution goals which is included in the proof obligation + * generation from information flow contracts. This macro splits the goal. * * The rules that are applied can be set in {@link #ADMITTED_RULES}. * @@ -46,9 +48,8 @@ public String getDescription() { + "obligation generation from information flow contracts."; } - private static final String[] ADMITTED_RULES = { - "andLeft", "orLeft", "impRight", "unfold_computed_formula", "andRight" - }; + private static final String[] ADMITTED_RULES = + { "andLeft", "orLeft", "impRight", "unfold_computed_formula", "andRight" }; private static final String INF_FLOW_UNFOLD_PREFIX = "unfold_computed_formula"; @@ -65,28 +66,27 @@ protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { } @Override - protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { + protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, PosInOccurrence pio, + Goal goal) { String ruleName = ruleApp.rule().name().toString(); - if ("andLeft".equals(ruleName) && - pio.sequentFormula().formula().op() instanceof UpdateApplication) { + if ("andLeft".equals(ruleName) + && pio.sequentFormula().formula().op() instanceof UpdateApplication) { return false; } else { return true; } } - + /** * {@inheritDoc} * *

    - * This compound macro is applicable if and only if the first macro is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if the first macro is applicable. If there is + * no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof == null) { return false; @@ -97,7 +97,8 @@ public boolean canApplyTo(Proof proof, } final ProofOblInput poForProof = services.getSpecificationRepository().getProofOblInput(proof); - return (poForProof instanceof AbstractInfFlowPO) && super.canApplyTo(proof, goals, posInOcc); + return (poForProof instanceof AbstractInfFlowPO) + && super.canApplyTo(proof, goals, posInOcc); } @Override @@ -106,14 +107,13 @@ protected boolean allowOSS() { } /** - * This strategy accepts all rule apps for which the rule name is in the - * admitted set or has INF_FLOW_UNFOLD_PREFIX as a prefix and rejects everything else. + * This strategy accepts all rule apps for which the rule name is in the admitted set or has + * INF_FLOW_UNFOLD_PREFIX as a prefix and rejects everything else. */ private class SelfCompExpansionStrategy implements Strategy { - private final Name NAME = - new Name(SelfcompositionStateExpansionMacro.SelfCompExpansionStrategy - .class.getSimpleName()); + private final Name NAME = new Name( + SelfcompositionStateExpansionMacro.SelfCompExpansionStrategy.class.getSimpleName()); private final Set admittedRuleNames; @@ -127,18 +127,13 @@ public Name name() { } @Override - public RuleAppCost computeCost(RuleApp ruleApp, - PosInOccurrence pio, - Goal goal) { + public RuleAppCost computeCost(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { String name = ruleApp.rule().name().toString(); - if ( ( admittedRuleNames.contains(name) - || name.startsWith(INF_FLOW_UNFOLD_PREFIX)) - && ruleApplicationInContextAllowed(ruleApp, pio, goal)) { - JavaCardDLStrategyFactory strategyFactory = - new JavaCardDLStrategyFactory(); + if ((admittedRuleNames.contains(name) || name.startsWith(INF_FLOW_UNFOLD_PREFIX)) + && ruleApplicationInContextAllowed(ruleApp, pio, goal)) { + JavaCardDLStrategyFactory strategyFactory = new JavaCardDLStrategyFactory(); Strategy javaDlStrategy = - strategyFactory.create(goal.proof(), - new StrategyProperties()); + strategyFactory.create(goal.proof(), new StrategyProperties()); RuleAppCost costs = javaDlStrategy.computeCost(ruleApp, pio, goal); if ("orLeft".equals(name)) { costs = costs.add(NumberRuleAppCost.create(100)); @@ -156,12 +151,11 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { @Override public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, - RuleAppCostCollector collector) { - } + RuleAppCostCollector collector) {} @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryBlockComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryBlockComputationMacro.java index f2502deb07f..12e2fe6068e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryBlockComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryBlockComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -26,7 +29,8 @@ * * @author christoph */ -public class StartAuxiliaryBlockComputationMacro extends AbstractProofMacro implements StartSideProofMacro { +public class StartAuxiliaryBlockComputationMacro extends AbstractProofMacro + implements StartSideProofMacro { @Override public String getName() { @@ -40,24 +44,20 @@ public String getCategory() { @Override public String getDescription() { - return "In order to increase the efficiency of self-composition " + - "proofs, this macro starts a side calculation which does " + - "the symbolic execution only once. The result is " + - "instantiated twice with the variable to be used in the " + - "two executions of the self-composition."; + return "In order to increase the efficiency of self-composition " + + "proofs, this macro starts a side calculation which does " + + "the symbolic execution only once. The result is " + + "instantiated twice with the variable to be used in the " + + "two executions of the self-composition."; } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { - if (goals == null || goals.head() == null - || goals.head().node() == null + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { + if (goals == null || goals.head() == null || goals.head().node() == null || goals.head().node().parent() == null) { return false; } - if (posInOcc == null - || posInOcc.subTerm() == null) { + if (posInOcc == null || posInOcc.subTerm() == null) { return false; } @@ -70,18 +70,13 @@ public boolean canApplyTo(Proof proof, final BlockContractInternalBuiltInRuleApp blockRuleApp = (BlockContractInternalBuiltInRuleApp) app; final BlockContract contract = blockRuleApp.getContract(); - final IFProofObligationVars ifVars = - blockRuleApp.getInformationFlowProofObligationVars(); + final IFProofObligationVars ifVars = blockRuleApp.getInformationFlowProofObligationVars(); if (ifVars == null) { return false; } - final InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(contract, - ifVars.c1, - ifVars.c2, - blockRuleApp.getExecutionContext(), - services); + final InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(contract, ifVars.c1, + ifVars.c2, blockRuleApp.getExecutionContext(), services); final Term selfComposedExec = f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_BLOCK_WITH_PRE_RELATION); @@ -89,34 +84,30 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws Exception { final BlockContractInternalBuiltInRuleApp blockRuleApp = - (BlockContractInternalBuiltInRuleApp) - goals.head().node().parent().getAppliedRuleApp(); + (BlockContractInternalBuiltInRuleApp) goals.head().node().parent() + .getAppliedRuleApp(); final InitConfig initConfig = proof.getEnv().getInitConfigForEnvironment(); final BlockContract contract = blockRuleApp.getContract(); final IFProofObligationVars ifVars = blockRuleApp.getInformationFlowProofObligationVars(); - final BlockExecutionPO blockExecPO = - new BlockExecutionPO(initConfig, contract, - ifVars.symbExecVars.labelHeapAtPreAsAnonHeapFunc(), - goals.head(), blockRuleApp.getExecutionContext(), - proof.getServices()); + final BlockExecutionPO blockExecPO = new BlockExecutionPO(initConfig, contract, + ifVars.symbExecVars.labelHeapAtPreAsAnonHeapFunc(), goals.head(), + blockRuleApp.getExecutionContext(), proof.getServices()); final InfFlowProof p; synchronized (blockExecPO) { p = (InfFlowProof) uic.createProof(initConfig, blockExecPO); } p.unionIFSymbols(((InfFlowProof) proof).getIFSymbols()); - + ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, p); info.addInfo(PROOF_MACRO_FINISHED_INFO_KEY_ORIGINAL_PROOF, proof); return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryComputationMacro.java index 8671d5806c8..09463a4edfc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import de.uka.ilkd.key.macros.AlternativeMacro; @@ -17,11 +20,11 @@ public String getCategory() { @Override public String getDescription() { - return "In order to increase the efficiency of self-composition " + - "proofs, this macro starts a side calculation which does " + - "the symbolic execution only once. The result is " + - "instantiated twice with the variable to be used in the " + - "two executions of the self-composition."; + return "In order to increase the efficiency of self-composition " + + "proofs, this macro starts a side calculation which does " + + "the symbolic execution only once. The result is " + + "instantiated twice with the variable to be used in the " + + "two executions of the self-composition."; } @Override @@ -31,9 +34,9 @@ public String getScriptCommandName() { @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] {new StartAuxiliaryMethodComputationMacro(), - new StartAuxiliaryLoopComputationMacro(), - new StartAuxiliaryBlockComputationMacro()}; + return new ProofMacro[] { new StartAuxiliaryMethodComputationMacro(), + new StartAuxiliaryLoopComputationMacro(), + new StartAuxiliaryBlockComputationMacro() }; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryLoopComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryLoopComputationMacro.java index 223861c51a0..5404d2e6bc0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryLoopComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryLoopComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -22,7 +25,8 @@ import de.uka.ilkd.key.rule.RuleApp; import de.uka.ilkd.key.speclang.LoopSpecification; -public class StartAuxiliaryLoopComputationMacro extends AbstractProofMacro implements StartSideProofMacro { +public class StartAuxiliaryLoopComputationMacro extends AbstractProofMacro + implements StartSideProofMacro { @Override public String getName() { @@ -36,24 +40,20 @@ public String getCategory() { @Override public String getDescription() { - return "In order to increase the efficiency of self-composition " + - "proofs, this macro starts a side calculation which does " + - "the symbolic execution only once. The result is " + - "instantiated twice with the variable to be used in the " + - "two executions of the self-composition."; + return "In order to increase the efficiency of self-composition " + + "proofs, this macro starts a side calculation which does " + + "the symbolic execution only once. The result is " + + "instantiated twice with the variable to be used in the " + + "two executions of the self-composition."; } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { - if (goals == null || goals.head() == null - || goals.head().node() == null + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { + if (goals == null || goals.head() == null || goals.head().node() == null || goals.head().node().parent() == null) { return false; } - if (posInOcc == null - || posInOcc.subTerm() == null) { + if (posInOcc == null || posInOcc.subTerm() == null) { return false; } final Services services = proof.getServices(); @@ -62,22 +62,17 @@ public boolean canApplyTo(Proof proof, if (!(app instanceof LoopInvariantBuiltInRuleApp)) { return false; } - final LoopInvariantBuiltInRuleApp loopInvRuleApp = - (LoopInvariantBuiltInRuleApp) app; + final LoopInvariantBuiltInRuleApp loopInvRuleApp = (LoopInvariantBuiltInRuleApp) app; final LoopSpecification loopInv = loopInvRuleApp.getSpec(); - final IFProofObligationVars ifVars = - loopInvRuleApp.getInformationFlowProofObligationVars(); + final IFProofObligationVars ifVars = loopInvRuleApp.getInformationFlowProofObligationVars(); if (ifVars == null) { return false; } - final ExecutionContext executionContext = - loopInvRuleApp.getExecutionContext(); + final ExecutionContext executionContext = loopInvRuleApp.getExecutionContext(); final Term guardTerm = loopInvRuleApp.getGuard(); - final InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(loopInv, ifVars.c1, - ifVars.c2, executionContext, - guardTerm, services); + final InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(loopInv, ifVars.c1, + ifVars.c2, executionContext, guardTerm, services); final Term selfComposedExec = f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_LOOP_WITH_INV_RELATION); @@ -85,38 +80,31 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws Exception { - final LoopInvariantBuiltInRuleApp loopInvRuleApp = (LoopInvariantBuiltInRuleApp) - goals.head().node().parent().getAppliedRuleApp(); + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws Exception { + final LoopInvariantBuiltInRuleApp loopInvRuleApp = + (LoopInvariantBuiltInRuleApp) goals.head().node().parent().getAppliedRuleApp(); final InitConfig initConfig = proof.getEnv().getInitConfigForEnvironment(); final LoopSpecification loopInv = loopInvRuleApp.getSpec(); - final IFProofObligationVars ifVars = - loopInvRuleApp.getInformationFlowProofObligationVars(); - final ExecutionContext executionContext = - loopInvRuleApp.getExecutionContext(); + final IFProofObligationVars ifVars = loopInvRuleApp.getInformationFlowProofObligationVars(); + final ExecutionContext executionContext = loopInvRuleApp.getExecutionContext(); final Term guardTerm = loopInvRuleApp.getGuard(); - final LoopInvExecutionPO loopInvExecPO = - new LoopInvExecutionPO(initConfig, loopInv, - ifVars.symbExecVars.labelHeapAtPreAsAnonHeapFunc(), - goals.head(), executionContext, - guardTerm, - proof.getServices()); - + final LoopInvExecutionPO loopInvExecPO = new LoopInvExecutionPO(initConfig, loopInv, + ifVars.symbExecVars.labelHeapAtPreAsAnonHeapFunc(), goals.head(), executionContext, + guardTerm, proof.getServices()); + final InfFlowProof p; synchronized (loopInvExecPO) { p = (InfFlowProof) uic.createProof(initConfig, loopInvExecPO); } p.unionIFSymbols(((InfFlowProof) proof).getIFSymbols()); - + ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, p); info.addInfo(PROOF_MACRO_FINISHED_INFO_KEY_ORIGINAL_PROOF, proof); return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryMethodComputationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryMethodComputationMacro.java index ecbaa4137a8..20e13be6e5e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryMethodComputationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartAuxiliaryMethodComputationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -23,7 +26,8 @@ * * @author christoph */ -public class StartAuxiliaryMethodComputationMacro extends AbstractProofMacro implements StartSideProofMacro { +public class StartAuxiliaryMethodComputationMacro extends AbstractProofMacro + implements StartSideProofMacro { @Override public String getName() { @@ -37,36 +41,30 @@ public String getCategory() { @Override public String getDescription() { - return "In order to increase the efficiency of self-composition " + - "proofs, this macro starts a side calculation which does " + - "the symbolic execution only once. The result is " + - "instantiated twice with the variable to be used in the " + - "two executions of the self-composition."; + return "In order to increase the efficiency of self-composition " + + "proofs, this macro starts a side calculation which does " + + "the symbolic execution only once. The result is " + + "instantiated twice with the variable to be used in the " + + "two executions of the self-composition."; } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (goals == null || goals.head() == null) { return false; } - if (posInOcc == null - || posInOcc.subTerm() == null) { + if (posInOcc == null || posInOcc.subTerm() == null) { return false; } Services services = proof.getServices(); - ProofOblInput poForProof = - services.getSpecificationRepository().getProofOblInput(proof); + ProofOblInput poForProof = services.getSpecificationRepository().getProofOblInput(proof); if (!(poForProof instanceof InfFlowContractPO)) { return false; } final InfFlowContractPO po = (InfFlowContractPO) poForProof; - final InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(po.getContract(), - po.getIFVars().c1, - po.getIFVars().c2, services); + final InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(po.getContract(), + po.getIFVars().c1, po.getIFVars().c2, services); final Term selfComposedExec = f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_EXECUTION_WITH_PRE_RELATION); @@ -74,29 +72,27 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws Exception { final Services services = proof.getServices(); - final InfFlowContractPO po = (InfFlowContractPO) services.getSpecificationRepository().getProofOblInput(proof); + final InfFlowContractPO po = + (InfFlowContractPO) services.getSpecificationRepository().getProofOblInput(proof); final InitConfig initConfig = proof.getEnv().getInitConfigForEnvironment(); - final SymbolicExecutionPO symbExecPO = - new SymbolicExecutionPO(initConfig, po.getContract(), - po.getIFVars().symbExecVars.labelHeapAtPreAsAnonHeapFunc(), - goals.head(), proof.getServices()); - + final SymbolicExecutionPO symbExecPO = new SymbolicExecutionPO(initConfig, po.getContract(), + po.getIFVars().symbExecVars.labelHeapAtPreAsAnonHeapFunc(), goals.head(), + proof.getServices()); + final InfFlowProof p; synchronized (symbExecPO) { p = (InfFlowProof) uic.createProof(initConfig, symbExecPO); } p.unionIFSymbols(((InfFlowProof) proof).getIFSymbols()); - + ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, p); info.addInfo(PROOF_MACRO_FINISHED_INFO_KEY_ORIGINAL_PROOF, proof); return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartSideProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartSideProofMacro.java index a1138045cc4..1ca892223eb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartSideProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StartSideProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import de.uka.ilkd.key.macros.ProofMacro; @@ -5,8 +8,8 @@ import de.uka.ilkd.key.proof.Proof; public interface StartSideProofMacro extends ProofMacro { - /** - * Key used in {@link ProofMacroFinishedInfo} to store the original {@link Proof}. - */ - public static final String PROOF_MACRO_FINISHED_INFO_KEY_ORIGINAL_PROOF = "originalProof"; + /** + * Key used in {@link ProofMacroFinishedInfo} to store the original {@link Proof}. + */ + public static final String PROOF_MACRO_FINISHED_INFO_KEY_ORIGINAL_PROOF = "originalProof"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StateExpansionAndInfFlowContractApplicationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StateExpansionAndInfFlowContractApplicationMacro.java index e364aef20b6..6fe78ea2581 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StateExpansionAndInfFlowContractApplicationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/StateExpansionAndInfFlowContractApplicationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import org.key_project.util.collection.ImmutableList; @@ -37,17 +40,15 @@ public String getScriptCommandName() { public String getDescription() { return "Extract the self-composed states after the merge of the " + "symbolic execution goals which is included in the proof " - + "obligation generation from information flow contracts " + - "and apply all relevant information flow contracts."; + + "obligation generation from information flow contracts " + + "and apply all relevant information flow contracts."; } @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { - new SelfcompositionStateExpansionMacro(), + return new ProofMacro[] { new SelfcompositionStateExpansionMacro(), new PropositionalExpansionWithSimplificationMacro(), - new FullUseInformationFlowContractMacro() - }; + new FullUseInformationFlowContractMacro() }; } @@ -55,13 +56,11 @@ protected ProofMacro[] createProofMacroArray() { * {@inheritDoc} * *

    - * This compound macro is applicable if and only if the first macro is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if the first macro is applicable. If there is + * no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (proof == null) { return false; } @@ -71,6 +70,7 @@ public boolean canApplyTo(Proof proof, } final ProofOblInput poForProof = services.getSpecificationRepository().getProofOblInput(proof); - return (poForProof instanceof AbstractInfFlowPO) && super.canApplyTo(proof, goals, posInOcc); + return (poForProof instanceof AbstractInfFlowPO) + && super.canApplyTo(proof, goals, posInOcc); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/UseInformationFlowContractMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/UseInformationFlowContractMacro.java index 25e748ed34b..8a3685f51db 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/UseInformationFlowContractMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/macros/UseInformationFlowContractMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.macros; import java.util.Arrays; @@ -26,11 +29,11 @@ /** - * The macro UseInformationFlowContractMacro applies all applicable information - * flow contracts. + * The macro UseInformationFlowContractMacro applies all applicable information flow contracts. *

    * The rules that are applied can be set in {@link #ADMITTED_RULENAMES}. *

    + * * @author christoph */ public class UseInformationFlowContractMacro extends StrategyProofMacro { @@ -39,6 +42,7 @@ public class UseInformationFlowContractMacro extends StrategyProofMacro { public String getName() { return "Use information flow contracts"; } + @Override public String getCategory() { return "Information Flow"; @@ -49,27 +53,23 @@ public String getDescription() { return "Applies all applicable information flow contract rules."; } - private static final String INF_FLOW_RULENAME_PREFIX = - "Use_information_flow_contract_for_"; + private static final String INF_FLOW_RULENAME_PREFIX = "Use_information_flow_contract_for_"; private static final String IMP_LEFT_RULENAME = "impLeft"; private static final String DOUBLE_IMP_LEFT_RULENAME = "doubleImpLeft"; - private static final String[] ADMITTED_RULENAMES = { - }; + private static final String[] ADMITTED_RULENAMES = {}; - private static final Set ADMITTED_RULENAME_SET = - asSet(ADMITTED_RULENAMES); + private static final Set ADMITTED_RULENAME_SET = asSet(ADMITTED_RULENAMES); - private static ImmutableSet appliedInfFlowRules = - DefaultImmutableSet.nil(); + private static ImmutableSet appliedInfFlowRules = DefaultImmutableSet.nil(); /** * Gets the set of admitted rule names. *

    - * @return a constant non- - * null set + * + * @return a constant non- null set */ protected Set getAdmittedRuleNames() { return ADMITTED_RULENAME_SET; @@ -85,25 +85,23 @@ protected static Set asSet(String[] strings) { @Override - protected UseInformationFlowContractMacro.PropExpansionStrategy createStrategy( - Proof proof, + protected UseInformationFlowContractMacro.PropExpansionStrategy createStrategy(Proof proof, PosInOccurrence posInOcc) { return new UseInformationFlowContractMacro.PropExpansionStrategy(getAdmittedRuleNames()); } /** - * Checks whether the application of the passed rule is ok in the given - * context. + * Checks whether the application of the passed rule is ok in the given context. *

    + * * @param ruleApp rule to be applied - * @param pio context - * @param goal context + * @param pio context + * @param goal context * @return true if rule may be applied */ - protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, - PosInOccurrence pio, - Goal goal) { + protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, PosInOccurrence pio, + Goal goal) { return true; } @@ -116,34 +114,36 @@ protected void doPostProcessing(Proof proof) { // set intuitive branch labels Node node = openGoal.node(); Node parent = node.parent(); - // int i = 0; - // while (i < numOfAppliedRules && parent != null) { + // int i = 0; + // while (i < numOfAppliedRules && parent != null) { while (parent != null) { - if (parent.parent() != null && - getAppRuleName(parent).equals(IMP_LEFT_RULENAME) && - getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX)) { + if (parent.parent() != null && getAppRuleName(parent).equals(IMP_LEFT_RULENAME) + && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX)) { String appName = getAppRuleName(parent.parent()); appName = appName.substring(INF_FLOW_RULENAME_PREFIX.length()); node.getNodeInfo().setBranchLabel("post " + appName + " (information flow)"); - parent.child(0).getNodeInfo().setBranchLabel("pre " + appName + " (information flow)"); + parent.child(0).getNodeInfo() + .setBranchLabel("pre " + appName + " (information flow)"); node = parent.parent(); parent = node.parent(); - // i += 2; - } else if (parent.parent() != null && - getAppRuleName(parent).equals(DOUBLE_IMP_LEFT_RULENAME) && - getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX)) { + // i += 2; + } else if (parent.parent() != null + && getAppRuleName(parent).equals(DOUBLE_IMP_LEFT_RULENAME) + && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX)) { String appName = getAppRuleName(parent.parent()); appName = appName.substring(INF_FLOW_RULENAME_PREFIX.length()); node.getNodeInfo().setBranchLabel("post " + appName + " (information flow)"); - parent.child(1).getNodeInfo().setBranchLabel("pre " + appName + " (information flow)"); - parent.child(0).getNodeInfo().setBranchLabel("pre_A & pre_B " + appName + " (information flow)"); + parent.child(1).getNodeInfo() + .setBranchLabel("pre " + appName + " (information flow)"); + parent.child(0).getNodeInfo() + .setBranchLabel("pre_A & pre_B " + appName + " (information flow)"); node = parent.parent(); parent = node.parent(); - // i += 2; + // i += 2; } else { node = parent; parent = node.parent(); - // i++; + // i++; } } } @@ -158,13 +158,13 @@ private String getAppRuleName(Node parent) { /** - * This strategy accepts all rule apps for which the rule name starts with a - * string in the admitted set and rejects everything else. + * This strategy accepts all rule apps for which the rule name starts with a string in the + * admitted set and rejects everything else. */ protected class PropExpansionStrategy implements Strategy { - private final Name NAME = - new Name(UseInformationFlowContractMacro.PropExpansionStrategy.class.getSimpleName()); + private final Name NAME = new Name( + UseInformationFlowContractMacro.PropExpansionStrategy.class.getSimpleName()); private final Set admittedRuleNames; @@ -181,29 +181,26 @@ public Name name() { @Override - public RuleAppCost computeCost(RuleApp ruleApp, - PosInOccurrence pio, - Goal goal) { + public RuleAppCost computeCost(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { // first try to apply - // - impLeft on previous information flow contract application - // formula, else - // - try to apply information flow contract, else - // - try to apply other allowed rules (andLeft) + // - impLeft on previous information flow contract application + // formula, else + // - try to apply information flow contract, else + // - try to apply other allowed rules (andLeft) String name = ruleApp.rule().name().toString(); - if (name.startsWith(INF_FLOW_RULENAME_PREFIX) && - ruleApplicationInContextAllowed(ruleApp, pio, goal)) { - return InfFlowContractAppFeature.INSTANCE.computeCost( - ruleApp, pio, goal); + if (name.startsWith(INF_FLOW_RULENAME_PREFIX) + && ruleApplicationInContextAllowed(ruleApp, pio, goal)) { + return InfFlowContractAppFeature.INSTANCE.computeCost(ruleApp, pio, goal); } else if (name.equals(DOUBLE_IMP_LEFT_RULENAME)) { - RuleAppCost impLeftCost = - FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE.computeCost(ruleApp, pio, goal); + RuleAppCost impLeftCost = FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE + .computeCost(ruleApp, pio, goal); return impLeftCost.add(NumberRuleAppCost.create(-10010)); } else if (name.equals(IMP_LEFT_RULENAME)) { - RuleAppCost impLeftCost = - FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE.computeCost(ruleApp, pio, goal); + RuleAppCost impLeftCost = FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE + .computeCost(ruleApp, pio, goal); return impLeftCost.add(NumberRuleAppCost.create(-10000)); - } else if (admittedRuleNames.contains(name) && - ruleApplicationInContextAllowed(ruleApp, pio, goal)) { + } else if (admittedRuleNames.contains(name) + && ruleApplicationInContextAllowed(ruleApp, pio, goal)) { return NumberRuleAppCost.getZeroCost(); } else { return TopRuleAppCost.INSTANCE; @@ -212,26 +209,25 @@ public RuleAppCost computeCost(RuleApp ruleApp, @Override - public boolean isApprovedApp(RuleApp app, - PosInOccurrence pio, - Goal goal) { + public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { // abort if - // - the parent.parent rule application is an information - // flow contract rule application, - // - the parent rule application is an impLeft rule application - // and - // - we are in the branch where we have to show the left hand side - // of the implication - if (goal.node().parent() != null && - goal.node().parent().parent() != null) { + // - the parent.parent rule application is an information + // flow contract rule application, + // - the parent rule application is an impLeft rule application + // and + // - we are in the branch where we have to show the left hand side + // of the implication + if (goal.node().parent() != null && goal.node().parent().parent() != null) { Node parent = goal.node().parent(); final boolean approved = !(getAppRuleName(parent).equals(IMP_LEFT_RULENAME) - && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) + && getAppRuleName(parent.parent()).startsWith( + INF_FLOW_RULENAME_PREFIX) && parent.child(0) == goal.node() || getAppRuleName(parent).equals(DOUBLE_IMP_LEFT_RULENAME) - && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) - && parent.child(2) != goal.node()); + && getAppRuleName(parent.parent()) + .startsWith(INF_FLOW_RULENAME_PREFIX) + && parent.child(2) != goal.node()); final String name = app.rule().name().toString(); if (approved && name.startsWith(INF_FLOW_RULENAME_PREFIX)) { if (appliedInfFlowRules.contains(name)) { @@ -249,15 +245,12 @@ && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) @Override - public void instantiateApp(RuleApp app, - PosInOccurrence pio, - Goal goal, - RuleAppCostCollector collector) { - } + public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, + RuleAppCostCollector collector) {} @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/AbstractInfFlowPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/AbstractInfFlowPO.java index 814e5252eb1..7b2fca71e53 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/AbstractInfFlowPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/AbstractInfFlowPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import de.uka.ilkd.key.informationflow.proof.InfFlowCheckInfo; @@ -19,34 +22,26 @@ public AbstractInfFlowPO(InitConfig initConfig, String name) { super(initConfig, name); } - public Proof createProof(String proofName, - Term poTerm, - InitConfig proofConfig) { + public Proof createProof(String proofName, Term poTerm, InitConfig proofConfig) { final Proof proof = super.createProof(proofName, poTerm, proofConfig); - StrategyInfoUndoMethod undo = - new StrategyInfoUndoMethod() { + StrategyInfoUndoMethod undo = new StrategyInfoUndoMethod() { @Override - public void undo( - de.uka.ilkd.key.util.properties.Properties strategyInfos) { + public void undo(de.uka.ilkd.key.util.properties.Properties strategyInfos) { strategyInfos.put(InfFlowCheckInfo.INF_FLOW_CHECK_PROPERTY, true); } }; - proof.openGoals().head().addStrategyInfo(InfFlowCheckInfo.INF_FLOW_CHECK_PROPERTY, true, undo); + proof.openGoals().head().addStrategyInfo(InfFlowCheckInfo.INF_FLOW_CHECK_PROPERTY, true, + undo); return proof; } - public InfFlowProof createProofObject(String proofName, - String proofHeader, - Term poTerm, - InitConfig proofConfig) { - final InfFlowProof proof = new InfFlowProof(proofName, - poTerm, - proofHeader, - proofConfig); + public InfFlowProof createProofObject(String proofName, String proofHeader, Term poTerm, + InitConfig proofConfig) { + final InfFlowProof proof = new InfFlowProof(proofName, poTerm, proofHeader, proofConfig); return proof; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/BlockExecutionPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/BlockExecutionPO.java index c49bf1db0aa..4a1309cce36 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/BlockExecutionPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/BlockExecutionPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.io.IOException; @@ -34,8 +37,7 @@ * * @author christoph */ -public class BlockExecutionPO extends AbstractInfFlowPO - implements InfFlowCompositePO { +public class BlockExecutionPO extends AbstractInfFlowPO implements InfFlowCompositePO { private final BlockContract contract; private final ProofObligationVars symbExecVars; @@ -43,35 +45,28 @@ public class BlockExecutionPO extends AbstractInfFlowPO private final ExecutionContext context; /** - * For saving and loading Information-Flow proofs, we need to remember the - * according taclets, program variables, functions and such. + * For saving and loading Information-Flow proofs, we need to remember the according taclets, + * program variables, functions and such. */ private InfFlowProofSymbols infFlowSymbols = new InfFlowProofSymbols(); - /** To be used only for auxiliary proofs where the services object of - * the actual proof has to be used instead of the initial services form - * the InitConfig. + /** + * To be used only for auxiliary proofs where the services object of the actual proof has to be + * used instead of the initial services form the InitConfig. */ - public BlockExecutionPO(InitConfig initConfig, - BlockContract contract, - ProofObligationVars symbExecVars, - Goal initiatingGoal, - ExecutionContext context, - Services services) { + public BlockExecutionPO(InitConfig initConfig, BlockContract contract, + ProofObligationVars symbExecVars, Goal initiatingGoal, ExecutionContext context, + Services services) { this(initConfig, contract, symbExecVars, initiatingGoal, context); this.environmentServices = services; } - public BlockExecutionPO(InitConfig initConfig, - BlockContract contract, - ProofObligationVars symbExecVars, - Goal initiatingGoal, - ExecutionContext context) { + public BlockExecutionPO(InitConfig initConfig, BlockContract contract, + ProofObligationVars symbExecVars, Goal initiatingGoal, ExecutionContext context) { super(initConfig, - ContractFactory.generateContractName(contract.getName(), contract.getKJT(), - contract.getTarget(), - contract.getTarget().getContainerType(), - contract.getBlock().getStartPosition().getLine())); + ContractFactory.generateContractName(contract.getName(), contract.getKJT(), + contract.getTarget(), contract.getTarget().getContainerType(), + contract.getBlock().getStartPosition().getLine())); this.contract = contract; this.symbExecVars = symbExecVars; this.initiatingGoal = initiatingGoal; @@ -83,17 +78,15 @@ public void readProblem() throws ProofInputException { postInit(); // generate snippet factory for symbolic execution - BasicPOSnippetFactory symbExecFactory = - POSnippetFactory.getBasicFactory(contract, symbExecVars, - context, environmentServices); + BasicPOSnippetFactory symbExecFactory = POSnippetFactory.getBasicFactory(contract, + symbExecVars, context, environmentServices); // symbolic execution final Term symExec = symbExecFactory.create(BasicPOSnippetFactory.Snippet.BLOCK_EXEC_WITH_PRE); // final symbolic execution term - final Term finalTerm = tb.applyElementary(symbExecVars.pre.heap, - tb.not(symExec)); + final Term finalTerm = tb.applyElementary(symbExecVars.pre.heap, tb.not(symExec)); // register final term assignPOTerms(finalTerm); @@ -173,9 +166,9 @@ public ExecutionContext getExecutionContext() { } -// public IFProofObligationVars getIFProofObligationVars() { -// return if -// } + // public IFProofObligationVars getIFProofObligationVars() { + // return if + // } /** * {@inheritDoc} @@ -223,11 +216,8 @@ public void unionLabeledIFSymbols(InfFlowProofSymbols symbols) { } @Override - protected Term getGlobalDefs(LocationVariable heap, - Term heapTerm, - Term selfTerm, - ImmutableList paramTerms, - Services services) { + protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, Term selfTerm, + ImmutableList paramTerms, Services services) { // information flow contracts do not have global defs return null; } @@ -240,9 +230,9 @@ public AbstractInfFlowPO getChildPO() { Services initiatingServices = initiatingProof.getServices(); ProofOblInput initiatingPO = initiatingServices.getSpecificationRepository().getProofOblInput(initiatingProof); - assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + - "proof started from within non-information flow proof!?!"; - return (AbstractInfFlowPO)initiatingPO; + assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + + "proof started from within non-information flow proof!?!"; + return (AbstractInfFlowPO) initiatingPO; } @@ -256,59 +246,48 @@ public IFProofObligationVars getLeafIFVars() { @Override @Deprecated protected ImmutableList buildOperationBlocks( - ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPre(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, + Map atPreVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPost(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - ProgramVariable resultVar, - ProgramVariable exceptionVar, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPost(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, ProgramVariable resultVar, + ProgramVariable exceptionVar, Map atPreVars, + Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term buildFrameClause(List modHeaps, - Map heapToAtPre, - ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term buildFrameClause(List modHeaps, Map heapToAtPre, + ProgramVariable selfVar, ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated protected Term generateMbyAtPreDef(ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/IFProofObligationVars.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/IFProofObligationVars.java index d3857b1e1e7..72181413d9c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/IFProofObligationVars.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/IFProofObligationVars.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.util.HashMap; @@ -11,8 +14,8 @@ /** - * This class contains the set of four sets of ProofObligationVars necessary for - * information flow proofs. + * This class contains the set of four sets of ProofObligationVars necessary for information flow + * proofs. * * @author christoph * @@ -24,24 +27,20 @@ public class IFProofObligationVars { private final Map> infFlowToSymbExecVarsMaps; - public IFProofObligationVars(ProofObligationVars symbExecVars, - Services services) { + public IFProofObligationVars(ProofObligationVars symbExecVars, Services services) { this(new ProofObligationVars(symbExecVars, "_A", services), - new ProofObligationVars(symbExecVars, "_B", services), - symbExecVars); + new ProofObligationVars(symbExecVars, "_B", services), symbExecVars); } - public IFProofObligationVars(ProofObligationVars c1, - ProofObligationVars c2, - ProofObligationVars symbExecVars) { + public IFProofObligationVars(ProofObligationVars c1, ProofObligationVars c2, + ProofObligationVars symbExecVars) { this.c1 = c1; this.c2 = c2; this.symbExecVars = symbExecVars; assert symbExecVars != null; - infFlowToSymbExecVarsMaps = - new HashMap>(); + infFlowToSymbExecVarsMaps = new HashMap>(); infFlowToSymbExecVarsMaps.put(c1, new HashMap()); infFlowToSymbExecVarsMaps.put(c2, new HashMap()); linkSymbExecVarsToCopies(); @@ -64,9 +63,7 @@ private void linkSymbExecVarsToCopies() { } - private void linkStateVarsToCopies(StateVars ifVars, - StateVars seVars, - Map map) { + private void linkStateVarsToCopies(StateVars ifVars, StateVars seVars, Map map) { final Iterator ifVarsIt = ifVars.termList.iterator(); for (final Term symbTerm : seVars.termList) { final Term ifTerm = ifVarsIt.next(); @@ -86,4 +83,4 @@ public Map getMapFor(ProofObligationVars vars) { public String toString() { return "[" + symbExecVars + "," + c1 + "," + c2 + "]"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowCompositePO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowCompositePO.java index c4e13e75e4b..be7495f5df1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowCompositePO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowCompositePO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowContractPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowContractPO.java index 88c3d859ee7..4009a81cb7a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowContractPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowContractPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.io.IOException; @@ -32,8 +35,7 @@ * * @author christoph */ -public class InfFlowContractPO extends AbstractInfFlowPO - implements ContractPO, InfFlowLeafPO { +public class InfFlowContractPO extends AbstractInfFlowPO implements ContractPO, InfFlowLeafPO { private final InformationFlowContract contract; @@ -42,20 +44,18 @@ public class InfFlowContractPO extends AbstractInfFlowPO private final IFProofObligationVars ifVars; /** - * For saving and loading Information-Flow proofs, we need to remember the - * according taclets, program variables, functions and such. + * For saving and loading Information-Flow proofs, we need to remember the according taclets, + * program variables, functions and such. */ private InfFlowProofSymbols infFlowSymbols = new InfFlowProofSymbols(); - public InfFlowContractPO(InitConfig initConfig, - InformationFlowContract contract) { + public InfFlowContractPO(InitConfig initConfig, InformationFlowContract contract) { super(initConfig, contract.getName()); this.contract = contract; // generate proof obligation variables final IProgramMethod pm = contract.getTarget(); - symbExecVars = - new ProofObligationVars(pm, contract.getKJT(), environmentServices); + symbExecVars = new ProofObligationVars(pm, contract.getKJT(), environmentServices); assert (symbExecVars.pre.self == null) == (pm.isStatic()); ifVars = new IFProofObligationVars(symbExecVars, environmentServices); @@ -81,12 +81,10 @@ public void readProblem() throws ProofInputException { // create proof obligation InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(contract, ifVars.c1, - ifVars.c2, proofServices); + POSnippetFactory.getInfFlowFactory(contract, ifVars.c1, ifVars.c2, proofServices); final Term selfComposedExec = f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_EXECUTION_WITH_PRE_RELATION); - final Term post = - f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_INPUT_OUTPUT_RELATION); + final Term post = f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_INPUT_OUTPUT_RELATION); final Term finalTerm = tb.imp(selfComposedExec, post); addLabeledIFSymbol(selfComposedExec); @@ -94,7 +92,7 @@ public void readProblem() throws ProofInputException { assignPOTerms(finalTerm); collectClassAxioms(contract.getKJT(), proofConfig); - for (final NoPosTacletApp t: taclets) { + for (final NoPosTacletApp t : taclets) { if (t.taclet().name().toString().startsWith("Class_invariant_axiom")) { addIFSymbol(t.taclet()); } @@ -189,20 +187,20 @@ public void fillSaveProperties(Properties properties) throws IOException { /** * Instantiates a new proof obligation with the given settings. + * * @param initConfig The already load {@link InitConfig}. * @param properties The settings of the proof obligation to instantiate. * @return The instantiated proof obligation. */ public static LoadedPOContainer loadFrom(InitConfig initConfig, Properties properties) { - final String contractName = properties.getProperty("contract"); - final Contract contract = - initConfig.getServices().getSpecificationRepository().getContractByName(contractName); - if (contract == null) { - throw new RuntimeException("Contract not found: " + contractName); - } - else { - return new LoadedPOContainer(contract.createProofObl(initConfig), 0); - } + final String contractName = properties.getProperty("contract"); + final Contract contract = initConfig.getServices().getSpecificationRepository() + .getContractByName(contractName); + if (contract == null) { + throw new RuntimeException("Contract not found: " + contractName); + } else { + return new LoadedPOContainer(contract.createProofObl(initConfig), 0); + } } @@ -243,11 +241,8 @@ public void unionLabeledIFSymbols(InfFlowProofSymbols symbols) { } @Override - protected Term getGlobalDefs(LocationVariable heap, - Term heapTerm, - Term selfTerm, - ImmutableList paramTerms, - Services services) { + protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, Term selfTerm, + ImmutableList paramTerms, Services services) { // information flow contracts do not have global defs return null; } @@ -263,60 +258,49 @@ public IFProofObligationVars getLeafIFVars() { @Override @Deprecated protected ImmutableList buildOperationBlocks( - ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPre(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, + Map atPreVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPost(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - ProgramVariable resultVar, - ProgramVariable exceptionVar, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPost(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, ProgramVariable resultVar, + ProgramVariable exceptionVar, Map atPreVars, + Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term buildFrameClause(List modHeaps, - Map heapToAtPre, - ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term buildFrameClause(List modHeaps, Map heapToAtPre, + ProgramVariable selfVar, ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated protected Term generateMbyAtPreDef(ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } /** @@ -324,6 +308,6 @@ protected Term generateMbyAtPreDef(ProgramVariable selfVar, */ @Override public KeYJavaType getContainerType() { - return getContract().getKJT(); + return getContract().getKJT(); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowLeafPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowLeafPO.java index a82613415f5..4655c58126f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowLeafPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowLeafPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowPO.java index cb5561a1ad2..88d327b6715 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import de.uka.ilkd.key.logic.Named; @@ -7,10 +10,10 @@ public interface InfFlowPO extends ProofOblInput { /** - * Get the information flow proof obligation variables (set of four sets of - * proof obligation variables necessary for information flow proofs) for - * the "leaf" (i.e., child of child of ..) information flow proof - * obligation. + * Get the information flow proof obligation variables (set of four sets of proof obligation + * variables necessary for information flow proofs) for the "leaf" (i.e., child of child of ..) + * information flow proof obligation. + * * @return the information flow proof obligation variables. */ public IFProofObligationVars getLeafIFVars(); @@ -26,5 +29,5 @@ public interface InfFlowPO extends ProofOblInput { public void addLabeledIFSymbol(Named n); public void unionLabeledIFSymbols(InfFlowProofSymbols symbols); - + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowProofSymbols.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowProofSymbols.java index f6ac89ae220..a0da34e294f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowProofSymbols.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/InfFlowProofSymbols.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.util.Comparator; @@ -37,48 +40,40 @@ public class InfFlowProofSymbols { private boolean isFreshContract; - private ImmutableSet> sorts - = DefaultImmutableSet.>nil(); + private ImmutableSet> sorts = + DefaultImmutableSet.>nil(); - private ImmutableSet> predicates - = DefaultImmutableSet.>nil(); + private ImmutableSet> predicates = + DefaultImmutableSet.>nil(); - private ImmutableSet> functions - = DefaultImmutableSet.>nil(); + private ImmutableSet> functions = + DefaultImmutableSet.>nil(); - private ImmutableSet> programVariables - = DefaultImmutableSet.>nil(); + private ImmutableSet> programVariables = + DefaultImmutableSet.>nil(); - private ImmutableSet> schemaVariables - = DefaultImmutableSet.>nil(); + private ImmutableSet> schemaVariables = + DefaultImmutableSet.>nil(); - private ImmutableSet> taclets - = DefaultImmutableSet.>nil(); + private ImmutableSet> taclets = + DefaultImmutableSet.>nil(); - /*private static final ImmutableSet tacletPrefixes - = DefaultImmutableSet.nil().add("unfold_computed_formula") - .add("Class_invariant_axiom") - .add("Use_information_flow_contract") - .add("Split_post") - .add("Remove_post");*/ + /* + * private static final ImmutableSet tacletPrefixes = + * DefaultImmutableSet.nil().add("unfold_computed_formula") + * .add("Class_invariant_axiom") .add("Use_information_flow_contract") .add("Split_post") + * .add("Remove_post"); + */ public InfFlowProofSymbols() { isFreshContract = true; } - /*public InfFlowProofSymbols(ImmutableSet taclets) { - this(); - String name = null; - for (Taclet t: taclets) { - name = t.name().toString(); - if (t instanceof RewriteTaclet) - for (String s: tacletPrefixes) { - if (name.startsWith(s)) { - add(t); - } - } - } - }*/ + /* + * public InfFlowProofSymbols(ImmutableSet taclets) { this(); String name = null; for + * (Taclet t: taclets) { name = t.name().toString(); if (t instanceof RewriteTaclet) for (String + * s: tacletPrefixes) { if (name.startsWith(s)) { add(t); } } } } + */ private InfFlowProofSymbols getLabeledSymbols() { InfFlowProofSymbols symbols = new InfFlowProofSymbols(); @@ -97,7 +92,7 @@ private InfFlowProofSymbols getLabeledSymbols() { private ImmutableSet> getLabeledSorts() { ImmutableSet> labeledSorts = DefaultImmutableSet.>nil(); - for (Pair s: sorts) { + for (Pair s : sorts) { if (s.second) { labeledSorts = labeledSorts.add(new Pair(s.first, false)); } @@ -108,7 +103,7 @@ private ImmutableSet> getLabeledSorts() { private ImmutableSet> getLabeledPredicates() { ImmutableSet> labeledPredicates = DefaultImmutableSet.>nil(); - for (Pair p: predicates) { + for (Pair p : predicates) { if (p.second) { labeledPredicates = labeledPredicates.add(new Pair(p.first, false)); @@ -120,7 +115,7 @@ private ImmutableSet> getLabeledPredicates() { private ImmutableSet> getLabeledFunctions() { ImmutableSet> labeledFunctions = DefaultImmutableSet.>nil(); - for (Pair f: functions) { + for (Pair f : functions) { if (f.second) { labeledFunctions = labeledFunctions.add(new Pair(f.first, false)); @@ -132,10 +127,10 @@ private ImmutableSet> getLabeledFunctions() { private ImmutableSet> getLabeledProgramVariables() { ImmutableSet> labeledProgramVariables = DefaultImmutableSet.>nil(); - for (Pair pv: programVariables) { + for (Pair pv : programVariables) { if (pv.second) { - labeledProgramVariables = labeledProgramVariables.add( - new Pair(pv.first, false)); + labeledProgramVariables = labeledProgramVariables + .add(new Pair(pv.first, false)); } } return labeledProgramVariables; @@ -144,10 +139,10 @@ private ImmutableSet> getLabeledProgramVariables( private ImmutableSet> getLabeledSchemaVariables() { ImmutableSet> labeledSchemaVariables = DefaultImmutableSet.>nil(); - for (Pair sv: schemaVariables) { + for (Pair sv : schemaVariables) { if (sv.second) { - labeledSchemaVariables = labeledSchemaVariables.add( - new Pair(sv.first, false)); + labeledSchemaVariables = labeledSchemaVariables + .add(new Pair(sv.first, false)); } } return labeledSchemaVariables; @@ -156,7 +151,7 @@ private ImmutableSet> getLabeledSchemaVariables() private ImmutableSet> getLabeledTaclets() { ImmutableSet> labeledTaclets = DefaultImmutableSet.>nil(); - for (Pair t: taclets) { + for (Pair t : taclets) { if (t.second) { labeledTaclets = labeledTaclets.add(new Pair(t.first, false)); } @@ -165,11 +160,9 @@ private ImmutableSet> getLabeledTaclets() { } private boolean containsSort(Sort s) { - ImmutableSet> ps = - DefaultImmutableSet.>nil() - .add(new Pair (s, true)) - .add(new Pair (s, false)); - for (Pair p: sorts) { + ImmutableSet> ps = DefaultImmutableSet.>nil() + .add(new Pair(s, true)).add(new Pair(s, false)); + for (Pair p : sorts) { if (ps.contains(p)) { return true; } @@ -178,15 +171,14 @@ private boolean containsSort(Sort s) { } private boolean containsPredicate(Function f) { - ImmutableSet> ps = - DefaultImmutableSet.>nil() - .add(new Pair (f, true)) - .add(new Pair (f, false)); - if (!f.name().toString().startsWith("RELATED_BY") && - !f.name().toString().startsWith("EXECUTION_OF")) { + ImmutableSet> ps = DefaultImmutableSet + .>nil().add(new Pair(f, true)) + .add(new Pair(f, false)); + if (!f.name().toString().startsWith("RELATED_BY") + && !f.name().toString().startsWith("EXECUTION_OF")) { return false; } - for (Pair p: predicates) { + for (Pair p : predicates) { if (ps.contains(p)) { return true; } @@ -195,11 +187,10 @@ private boolean containsPredicate(Function f) { } private boolean containsFunction(Function f) { - ImmutableSet> ps = - DefaultImmutableSet.>nil() - .add(new Pair (f, true)) - .add(new Pair (f, false)); - for (Pair p: functions) { + ImmutableSet> ps = DefaultImmutableSet + .>nil().add(new Pair(f, true)) + .add(new Pair(f, false)); + for (Pair p : functions) { if (ps.contains(p)) { return true; } @@ -210,9 +201,9 @@ private boolean containsFunction(Function f) { private boolean containsProgramVariable(ProgramVariable pv) { ImmutableSet> ps = DefaultImmutableSet.>nil() - .add(new Pair (pv, true)) - .add(new Pair (pv, false)); - for (Pair p: programVariables) { + .add(new Pair(pv, true)) + .add(new Pair(pv, false)); + for (Pair p : programVariables) { if (ps.contains(p)) { return true; } @@ -223,9 +214,9 @@ private boolean containsProgramVariable(ProgramVariable pv) { private boolean containsSchemaVariable(SchemaVariable sv) { ImmutableSet> ps = DefaultImmutableSet.>nil() - .add(new Pair (sv, true)) - .add(new Pair (sv, false)); - for (Pair p: schemaVariables) { + .add(new Pair(sv, true)) + .add(new Pair(sv, false)); + for (Pair p : schemaVariables) { if (ps.contains(p)) { return true; } @@ -234,11 +225,9 @@ private boolean containsSchemaVariable(SchemaVariable sv) { } private boolean containsTaclet(Taclet t) { - ImmutableSet> ps = - DefaultImmutableSet.>nil() - .add(new Pair (t, true)) - .add(new Pair (t, false)); - for (Pair p: taclets) { + ImmutableSet> ps = DefaultImmutableSet.>nil() + .add(new Pair(t, true)).add(new Pair(t, false)); + for (Pair p : taclets) { if (ps.contains(p)) { return true; } @@ -253,29 +242,28 @@ private void addTaclet(Taclet t, boolean labeled) { } private void addSort(Sort s, boolean labeled) { - if (!(s instanceof NullSort) && - !containsSort(s)) { + if (!(s instanceof NullSort) && !containsSort(s)) { sorts = sorts.add(new Pair(s, !labeled)); } } private boolean isPredicate(Operator f) { assert f != null; - if (f.name().toString().startsWith("RELATED_BY") || - f.name().toString().startsWith("EXECUTION_OF")) { + if (f.name().toString().startsWith("RELATED_BY") + || f.name().toString().startsWith("EXECUTION_OF")) { return true; } else { return false; } } - private void addPredicate (Function p, boolean labeled) { + private void addPredicate(Function p, boolean labeled) { if (!containsPredicate(p)) { predicates = predicates.add(new Pair(p, !labeled)); } } - private void addFunction (Function f, boolean labeled) { + private void addFunction(Function f, boolean labeled) { if (!containsFunction(f)) functions = functions.add(new Pair(f, !labeled)); } @@ -296,7 +284,8 @@ private void addSchemaVariable(SchemaVariable sv, boolean labeled) { private void addProgramVariable(ProgramVariable pv, boolean labeled) { if (!containsProgramVariable(pv)) { - programVariables = programVariables.add(new Pair(pv, !labeled)); + programVariables = + programVariables.add(new Pair(pv, !labeled)); } } @@ -316,7 +305,7 @@ public static ProgramVariable searchPV(String s, Services services) { n = ns.lookup(s + "_" + i); } assert n instanceof ProgramVariable; - return (ProgramVariable)n; + return (ProgramVariable) n; } public void add(Named symb) { @@ -324,27 +313,27 @@ public void add(Named symb) { boolean l = false; if (symb instanceof Sort) { - final Sort s = (Sort)symb; + final Sort s = (Sort) symb; addSort(s, l); } if (symb instanceof SortedOperator) { - final SortedOperator s = (SortedOperator)symb; + final SortedOperator s = (SortedOperator) symb; addSort(s.sort(), l); } if (symb instanceof Function) { - final Function f = (Function)symb; + final Function f = (Function) symb; addFunc(f, l); } if (symb instanceof ProgramVariable) { - final ProgramVariable pv = (ProgramVariable)symb; + final ProgramVariable pv = (ProgramVariable) symb; addProgramVariable(pv, l); } if (symb instanceof SchemaVariable) { - final SchemaVariable sv = (SchemaVariable)symb; + final SchemaVariable sv = (SchemaVariable) symb; addSchemaVariable(sv, l); } if (symb instanceof Taclet) { - final Taclet t = (Taclet)symb; + final Taclet t = (Taclet) symb; addTaclet(t, l); } } @@ -354,27 +343,27 @@ public void addLabeled(Named symb) { boolean l = true; if (symb instanceof Sort) { - final Sort s = (Sort)symb; + final Sort s = (Sort) symb; addSort(s, l); } if (symb instanceof SortedOperator) { - final SortedOperator s = (SortedOperator)symb; + final SortedOperator s = (SortedOperator) symb; addSort(s.sort(), l); } if (symb instanceof Function) { - final Function f = (Function)symb; + final Function f = (Function) symb; addFunc(f, l); } if (symb instanceof ProgramVariable) { - final ProgramVariable pv = (ProgramVariable)symb; + final ProgramVariable pv = (ProgramVariable) symb; addProgramVariable(pv, l); } if (symb instanceof SchemaVariable) { - final SchemaVariable sv = (SchemaVariable)symb; + final SchemaVariable sv = (SchemaVariable) symb; addSchemaVariable(sv, l); } if (symb instanceof Taclet) { - final Taclet t = (Taclet)symb; + final Taclet t = (Taclet) symb; addTaclet(t, l); } } @@ -384,7 +373,7 @@ public void add(Term t) { t = TermBuilder.goBelowUpdates(t); if (!isPredicate(t.op())) { if (t.arity() > 0) { - for (final Term s: t.subs()) { + for (final Term s : t.subs()) { add(s); } } @@ -396,7 +385,7 @@ public void addLabeled(Term t) { assert t != null; t = TermBuilder.goBelowUpdates(t); if (t.arity() > 0) { - for (final Term s: t.subs()) { + for (final Term s : t.subs()) { addLabeled(s); } } @@ -441,11 +430,11 @@ public void addTotalTerm(Term t) { addTotalTerm(UpdateApplication.getTarget(t)); } if (t.op() instanceof ElementaryUpdate) { - add(((ElementaryUpdate)t.op()).lhs()); + add(((ElementaryUpdate) t.op()).lhs()); } t = TermBuilder.goBelowUpdates(t); if (t.arity() > 0) { - for (final Term s: t.subs()) { + for (final Term s : t.subs()) { addTotalTerm(s); } } @@ -459,11 +448,11 @@ public void addLabeledTotalTerm(Term t) { addLabeledTotalTerm(UpdateApplication.getTarget(t)); } if (t.op() instanceof ElementaryUpdate) { - addLabeled(((ElementaryUpdate)t.op()).lhs()); + addLabeled(((ElementaryUpdate) t.op()).lhs()); } t = TermBuilder.goBelowUpdates(t); if (t.arity() > 0) { - for (final Term s: t.subs()) { + for (final Term s : t.subs()) { addLabeledTotalTerm(s); } } @@ -472,15 +461,15 @@ public void addLabeledTotalTerm(Term t) { private ImmutableSet getSorts() { ImmutableSet sorts = DefaultImmutableSet.nil(); - for (Pair s: this.sorts) { + for (Pair s : this.sorts) { sorts = sorts.add(s.first); } return sorts; } - private LinkedList ensureRightOrderOfSorts(ImmutableSet s){ + private LinkedList ensureRightOrderOfSorts(ImmutableSet s) { LinkedList> sortContainers = new LinkedList>(); - for (final Sort sort: s) { + for (final Sort sort : s) { boolean added = false; for (TreeSet container : sortContainers) { if (container.add(sort)) { @@ -512,7 +501,7 @@ public int compare(Sort s1, Sort s2) { return sorts; } - private LinkedList removeArraySorts(LinkedList sorts){ + private LinkedList removeArraySorts(LinkedList sorts) { Iterator it = sorts.iterator(); while (it.hasNext()) { Sort s = it.next(); @@ -525,7 +514,7 @@ private LinkedList removeArraySorts(LinkedList sorts){ private ImmutableSet getPredicates() { ImmutableSet predicates = DefaultImmutableSet.nil(); - for (Pair p: this.predicates) { + for (Pair p : this.predicates) { predicates = predicates.add(p.first); } return predicates; @@ -533,7 +522,7 @@ private ImmutableSet getPredicates() { private ImmutableSet getFunctions() { ImmutableSet functions = DefaultImmutableSet.nil(); - for (Pair f: this.functions) { + for (Pair f : this.functions) { functions = functions.add(f.first); } return functions; @@ -541,7 +530,7 @@ private ImmutableSet getFunctions() { private ImmutableSet getProgramVariables() { ImmutableSet programVariables = DefaultImmutableSet.nil(); - for (Pair pv: this.programVariables) { + for (Pair pv : this.programVariables) { programVariables = programVariables.add(pv.first); } return programVariables; @@ -549,7 +538,7 @@ private ImmutableSet getProgramVariables() { private ImmutableSet getSchemaVariables() { ImmutableSet schemaVariables = DefaultImmutableSet.nil(); - for (Pair sv: this.schemaVariables) { + for (Pair sv : this.schemaVariables) { schemaVariables = schemaVariables.add(sv.first); } return schemaVariables; @@ -557,7 +546,7 @@ private ImmutableSet getSchemaVariables() { private ImmutableSet getTaclets() { ImmutableSet taclets = DefaultImmutableSet.nil(); - for (Pair t: this.taclets) { + for (Pair t : this.taclets) { taclets = taclets.add(t.first); } return taclets; @@ -580,7 +569,7 @@ private String printSorts() { // bugfix (CS): array types need not to be added as sorts // (and they cannot be parsed...) sortsList = removeArraySorts(sortsList); - for (final Sort sort: sortsList) { + for (final Sort sort : sortsList) { result.append(sort.name()); if (!sort.extendsSorts().isEmpty()) { String res = "\\extends "; @@ -593,7 +582,7 @@ private String printSorts() { } if (extendsAtLeastOneSort) { final int index = res.lastIndexOf(", "); - res = res.substring(0,index == -1 ? res.length() : index); + res = res.substring(0, index == -1 ? res.length() : index); result.append(res); } } @@ -610,13 +599,13 @@ private String printPredicates() { StringBuffer result = new StringBuffer(); result.append("\\predicates{\n"); - for (final Function pred: getPredicates()) { + for (final Function pred : getPredicates()) { result.append(pred.name()); String s = ""; for (int i = 0; i < pred.arity(); i++) { - s+= (i == 0 ? "(" : ","); - s+= (pred.argSort(i)); - s+= (i == pred.arity() - 1 ? ")" : ""); + s += (i == 0 ? "(" : ","); + s += (pred.argSort(i)); + s += (i == pred.arity() - 1 ? ")" : ""); } result.append(s); result.append(";\n"); @@ -632,14 +621,14 @@ private String printFunctions() { StringBuffer result = new StringBuffer(); result.append("\\functions{\n"); - for (final Function f: getFunctions()) { + for (final Function f : getFunctions()) { result.append(f.sort().name() + " "); result.append(f.name()); String s = ""; for (int i = 0; i < f.arity(); i++) { - s+= (i == 0 ? "(" : ","); - s+= (f.argSort(i)); - s+= (i == f.arity() - 1 ? ")" : ""); + s += (i == 0 ? "(" : ","); + s += (f.argSort(i)); + s += (i == f.arity() - 1 ? ")" : ""); } result.append(s); result.append(";\n"); @@ -655,7 +644,7 @@ private String printProgramVariables() { StringBuffer result = new StringBuffer(); result.append("\\programVariables{\n"); - for (final ProgramVariable pv: getProgramVariables()) { + for (final ProgramVariable pv : getProgramVariables()) { result.append(pv.sort().name() + " "); result.append(pv.name()); result.append(";\n"); @@ -672,9 +661,9 @@ private String printSchemaVariables() { StringBuffer result = new StringBuffer(); result.append("\\schemaVariables{\n"); - for (final SchemaVariable sv: getSchemaVariables()) { - final String prefix = sv instanceof FormulaSV ? "\\formula " : - sv instanceof TermSV? "\\term " : "\\variables "; + for (final SchemaVariable sv : getSchemaVariables()) { + final String prefix = sv instanceof FormulaSV ? "\\formula " + : sv instanceof TermSV ? "\\term " : "\\variables "; result.append(prefix); result.append(sv.sort().name() + " "); result.append(sv.name()); @@ -691,7 +680,7 @@ private String printTaclets() { NotationInfo info = new NotationInfo(); StringBackend backend = new StringBackend(80); - LogicPrinter printer = new LogicPrinter(new ProgramPrinter(),info, backend,null,true); + LogicPrinter printer = new LogicPrinter(new ProgramPrinter(), info, backend, null, true); StringBuffer buffer = new StringBuffer(); buffer.append("\\rules{"); @@ -700,17 +689,17 @@ private String printTaclets() { info = new NotationInfo(); backend = new StringBackend(80); - printer = new LogicPrinter(new ProgramPrinter(),info, backend,null,true); + printer = new LogicPrinter(new ProgramPrinter(), info, backend, null, true); printer.printTaclet(taclet); - final StringBuffer t = new StringBuffer(backend.getString()+";"); + final StringBuffer t = new StringBuffer(backend.getString() + ";"); buffer.append(t); } buffer.append("\n}"); String string = buffer.toString(); // bugfix (CS): the following two lines changed array types to their // base type -- which is no good idea. Thus I removed the lines. -// string = string.replaceAll("\\[", ""); -// string = string.replaceAll("\\]", ""); + // string = string.replaceAll("\\[", ""); + // string = string.replaceAll("\\]", ""); buffer = new StringBuffer(); buffer.append(string); buffer.append("\n\n"); @@ -725,9 +714,9 @@ public String printProofSymbols() { result.append(printPredicates()); result.append(printFunctions()); result.append(printProgramVariables()); - //result.append(printSchemaVariables()); + // result.append(printSchemaVariables()); result.append(printTaclets()); return result.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/LoopInvExecutionPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/LoopInvExecutionPO.java index b1086b45a9f..b4904d64c70 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/LoopInvExecutionPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/LoopInvExecutionPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.io.IOException; @@ -30,9 +33,8 @@ import de.uka.ilkd.key.speclang.LoopSpecification; import de.uka.ilkd.key.util.InfFlowSpec; -public class LoopInvExecutionPO extends AbstractInfFlowPO - implements InfFlowCompositePO { - +public class LoopInvExecutionPO extends AbstractInfFlowPO implements InfFlowCompositePO { + private final LoopSpecification loopInvariant; private final ProofObligationVars symbExecVars; @@ -44,40 +46,30 @@ public class LoopInvExecutionPO extends AbstractInfFlowPO private final ExecutionContext context; /** - * For saving and loading Information-Flow proofs, we need to remember the - * according taclets, program variables, functions and such. + * For saving and loading Information-Flow proofs, we need to remember the according taclets, + * program variables, functions and such. */ private InfFlowProofSymbols infFlowSymbols = new InfFlowProofSymbols(); - /** To be used only for auxiliary proofs where the services object of - * the actual proof has to be used instead of the initial services form - * the InitConfig. + /** + * To be used only for auxiliary proofs where the services object of the actual proof has to be + * used instead of the initial services form the InitConfig. */ - public LoopInvExecutionPO(InitConfig initConfig, - LoopSpecification loopInv, - ProofObligationVars symbExecVars, - Goal initiatingGoal, - ExecutionContext context, - Term guardTerm, - Services services) { - this(initConfig, loopInv, symbExecVars, initiatingGoal, context, - guardTerm); + public LoopInvExecutionPO(InitConfig initConfig, LoopSpecification loopInv, + ProofObligationVars symbExecVars, Goal initiatingGoal, ExecutionContext context, + Term guardTerm, Services services) { + this(initConfig, loopInv, symbExecVars, initiatingGoal, context, guardTerm); this.environmentServices = services; } - public LoopInvExecutionPO(InitConfig initConfig, - LoopSpecification loopInv, - ProofObligationVars symbExecVars, - Goal initiatingGoal, - ExecutionContext context, - Term guardTerm) { + public LoopInvExecutionPO(InitConfig initConfig, LoopSpecification loopInv, + ProofObligationVars symbExecVars, Goal initiatingGoal, ExecutionContext context, + Term guardTerm) { super(initConfig, - ContractFactory.generateContractName(loopInv.getName(), - loopInv.getKJT(), - loopInv.getTarget(), - loopInv.getTarget().getContainerType(), - loopInv.getLoop().getStartPosition().getLine())); + ContractFactory.generateContractName(loopInv.getName(), loopInv.getKJT(), + loopInv.getTarget(), loopInv.getTarget().getContainerType(), + loopInv.getLoop().getStartPosition().getLine())); this.loopInvariant = loopInv; this.symbExecVars = symbExecVars; this.initiatingGoal = initiatingGoal; @@ -85,15 +77,15 @@ public LoopInvExecutionPO(InitConfig initConfig, this.guardTerm = guardTerm; // consistency check - assert preAndPostExpressionsEqual() : - "Information flow loop invariant malformed. Pre expressions" + - "do not match post expressions."; + assert preAndPostExpressionsEqual() + : "Information flow loop invariant malformed. Pre expressions" + + "do not match post expressions."; } private boolean preAndPostExpressionsEqual() { - for (InfFlowSpec infFlowSpec: loopInvariant.getInfFlowSpecs(environmentServices)) { - if(infFlowSpec.preExpressions == infFlowSpec.postExpressions) { + for (InfFlowSpec infFlowSpec : loopInvariant.getInfFlowSpecs(environmentServices)) { + if (infFlowSpec.preExpressions == infFlowSpec.postExpressions) { return false; } } @@ -106,17 +98,14 @@ public void readProblem() throws ProofInputException { postInit(); // generate snippet factory for symbolic execution - BasicPOSnippetFactory symbExecFactory = - POSnippetFactory.getBasicFactory(loopInvariant, symbExecVars, - context, guardTerm, environmentServices); + BasicPOSnippetFactory symbExecFactory = POSnippetFactory.getBasicFactory(loopInvariant, + symbExecVars, context, guardTerm, environmentServices); // symbolic execution - Term symExec = - symbExecFactory.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV); + Term symExec = symbExecFactory.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV); // final symbolic execution term - Term finalTerm = tb.applyElementary(symbExecVars.pre.heap, - tb.not(symExec)); + Term finalTerm = tb.applyElementary(symbExecVars.pre.heap, tb.not(symExec)); // register final term assignPOTerms(finalTerm); @@ -229,11 +218,8 @@ public void unionLabeledIFSymbols(InfFlowProofSymbols symbols) { } @Override - protected Term getGlobalDefs(LocationVariable heap, - Term heapTerm, - Term selfTerm, - ImmutableList paramTerms, - Services services) { + protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, Term selfTerm, + ImmutableList paramTerms, Services services) { // information flow contracts do not have global defs return null; } @@ -246,9 +232,9 @@ public AbstractInfFlowPO getChildPO() { Services initiatingServices = initiatingProof.getServices(); ProofOblInput initiatingPO = initiatingServices.getSpecificationRepository().getProofOblInput(initiatingProof); - assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + - "proof started from within non-information flow proof!?!"; - return (AbstractInfFlowPO)initiatingPO; + assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + + "proof started from within non-information flow proof!?!"; + return (AbstractInfFlowPO) initiatingPO; } @@ -262,50 +248,44 @@ public IFProofObligationVars getLeafIFVars() { @Override @Deprecated protected ImmutableList buildOperationBlocks( - ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated protected Term generateMbyAtPreDef(ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPre(List modHeaps, - ProgramVariable selfVar, ImmutableList paramVars, + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, Map atPreVars, Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPost(List modHeaps, - ProgramVariable selfVar, ImmutableList paramVars, - ProgramVariable resultVar, ProgramVariable exceptionVar, - Map atPreVars, Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPost(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, ProgramVariable resultVar, + ProgramVariable exceptionVar, Map atPreVars, + Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term buildFrameClause(List modHeaps, - Map heapToAtPre, - ProgramVariable selfVar, - ImmutableList paramVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term buildFrameClause(List modHeaps, Map heapToAtPre, + ProgramVariable selfVar, ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/SymbolicExecutionPO.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/SymbolicExecutionPO.java index 600ceec7073..f4df346a42c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/SymbolicExecutionPO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/SymbolicExecutionPO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po; import java.io.IOException; @@ -42,35 +45,28 @@ public class SymbolicExecutionPO extends AbstractInfFlowPO private final Goal initiatingGoal; /** - * For saving and loading Information-Flow proofs, we need to remember the - * according taclets, program variables, functions and such. + * For saving and loading Information-Flow proofs, we need to remember the according taclets, + * program variables, functions and such. */ private InfFlowProofSymbols infFlowSymbols = new InfFlowProofSymbols(); - /** To be used only for auxiliary proofs where the services object of - * the actual proof has to be used instead of the initial services form - * the InitConfig. + /** + * To be used only for auxiliary proofs where the services object of the actual proof has to be + * used instead of the initial services form the InitConfig. */ - public SymbolicExecutionPO(InitConfig initConfig, - InformationFlowContract contract, - ProofObligationVars symbExecVars, - Goal initiatingGoal, - Services services) { + public SymbolicExecutionPO(InitConfig initConfig, InformationFlowContract contract, + ProofObligationVars symbExecVars, Goal initiatingGoal, Services services) { this(initConfig, contract, symbExecVars, initiatingGoal); this.environmentServices = services; } - public SymbolicExecutionPO(InitConfig initConfig, - InformationFlowContract contract, - ProofObligationVars symbExecVars, - Goal initiatingGoal) { + public SymbolicExecutionPO(InitConfig initConfig, InformationFlowContract contract, + ProofObligationVars symbExecVars, Goal initiatingGoal) { super(initConfig, - ContractFactory.generateContractName(contract.getPODisplayName(), - contract.getKJT(), - contract.getTarget(), - contract.getTarget().getContainerType(), - contract.getTarget().getStartPosition().getLine())); + ContractFactory.generateContractName(contract.getPODisplayName(), contract.getKJT(), + contract.getTarget(), contract.getTarget().getContainerType(), + contract.getTarget().getStartPosition().getLine())); this.contract = contract; this.symbExecVars = symbExecVars; this.initiatingGoal = initiatingGoal; @@ -82,9 +78,8 @@ public void readProblem() throws ProofInputException { postInit(); // generate snippet factory for symbolic execution - BasicPOSnippetFactory symbExecFactory = - POSnippetFactory.getBasicFactory(contract, symbExecVars, - initiatingGoal.proof().getServices()); + BasicPOSnippetFactory symbExecFactory = POSnippetFactory.getBasicFactory(contract, + symbExecVars, initiatingGoal.proof().getServices()); // symbolic execution under precondition final Term symExec = @@ -226,11 +221,8 @@ public void unionLabeledIFSymbols(InfFlowProofSymbols symbols) { } @Override - protected Term getGlobalDefs(LocationVariable heap, - Term heapTerm, - Term selfTerm, - ImmutableList paramTerms, - Services services) { + protected Term getGlobalDefs(LocationVariable heap, Term heapTerm, Term selfTerm, + ImmutableList paramTerms, Services services) { // information flow contracts do not have global defs return null; } @@ -243,9 +235,9 @@ public AbstractInfFlowPO getChildPO() { Services initiatingServices = initiatingProof.getServices(); ProofOblInput initiatingPO = initiatingServices.getSpecificationRepository().getProofOblInput(initiatingProof); - assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + - "proof started from within non-information flow proof!?!"; - return (AbstractInfFlowPO)initiatingPO; + assert initiatingPO instanceof AbstractInfFlowPO : "Information flow auxiliary " + + "proof started from within non-information flow proof!?!"; + return (AbstractInfFlowPO) initiatingPO; } @@ -255,52 +247,44 @@ public IFProofObligationVars getLeafIFVars() { } -// the following code is legacy code + // the following code is legacy code @Override @Deprecated protected ImmutableList buildOperationBlocks( - ImmutableList formalParVars, - ProgramVariable selfVar, - ProgramVariable resultVar, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + ImmutableList formalParVars, ProgramVariable selfVar, + ProgramVariable resultVar, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPre(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPre(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, + Map atPreVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term getPost(List modHeaps, - ProgramVariable selfVar, - ImmutableList paramVars, - ProgramVariable resultVar, - ProgramVariable exceptionVar, - Map atPreVars, - Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term getPost(List modHeaps, ProgramVariable selfVar, + ImmutableList paramVars, ProgramVariable resultVar, + ProgramVariable exceptionVar, Map atPreVars, + Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @Override @Deprecated - protected Term buildFrameClause(List modHeaps, - Map heapToAtPre, ProgramVariable selfVar, - ImmutableList paramVars, Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + protected Term buildFrameClause(List modHeaps, Map heapToAtPre, + ProgramVariable selfVar, ImmutableList paramVars, Services services) { + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } @@ -308,8 +292,8 @@ protected Term buildFrameClause(List modHeaps, @Deprecated protected Term generateMbyAtPreDef(ProgramVariable selfVar, ImmutableList paramVars, Services services) { - throw new UnsupportedOperationException("Not supported any more. " + - "Please use the POSnippetFactory instead."); + throw new UnsupportedOperationException( + "Not supported any more. " + "Please use the POSnippetFactory instead."); } /** @@ -317,6 +301,6 @@ protected Term generateMbyAtPreDef(ProgramVariable selfVar, */ @Override public KeYJavaType getContainerType() { - return getContract().getKJT(); + return getContract().getKJT(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BasicBlockExecutionSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BasicBlockExecutionSnippet.java index 215cfd417ed..316d74d9b1a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BasicBlockExecutionSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BasicBlockExecutionSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import java.util.Iterator; @@ -25,12 +28,10 @@ * * @author christoph */ -class BasicBlockExecutionSnippet extends ReplaceAndRegisterMethod - implements FactoryMethod { +class BasicBlockExecutionSnippet extends ReplaceAndRegisterMethod implements FactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars) + public Term produce(BasicSnippetData d, ProofObligationVars poVars) throws UnsupportedOperationException { ImmutableList posts = ImmutableSLList.nil(); if (poVars.post.self != null) { @@ -42,34 +43,28 @@ public Term produce(BasicSnippetData d, posts = posts.append(d.tb.equals(localPostVars.next(), localVars.next())); } if (poVars.post.result != null) { - posts = posts.append(d.tb.equals(poVars.post.result, - poVars.pre.result)); + posts = posts.append(d.tb.equals(poVars.post.result, poVars.pre.result)); } if (poVars.pre.exception != null && poVars.post.exception != null) { - posts = posts.append(d.tb.equals(poVars.post.exception, - poVars.pre.exception)); + posts = posts.append(d.tb.equals(poVars.post.exception, poVars.pre.exception)); } posts = posts.append(d.tb.equals(poVars.post.heap, d.tb.getBaseHeap())); final Term prog = buildProgramTerm(d, poVars, d.tb.and(posts), d.tb); return prog; } - private Term buildProgramTerm(BasicSnippetData d, - ProofObligationVars vs, - Term postTerm, - TermBuilder tb) { + private Term buildProgramTerm(BasicSnippetData d, ProofObligationVars vs, Term postTerm, + TermBuilder tb) { if (d.get(BasicSnippetData.Key.MODALITY) == null) { - throw new UnsupportedOperationException("Tried to produce a " + - "program-term for a " + - "contract without modality."); + throw new UnsupportedOperationException( + "Tried to produce a " + "program-term for a " + "contract without modality."); } - //create java block - Modality modality = - (Modality) d.get(BasicSnippetData.Key.MODALITY); + // create java block + Modality modality = (Modality) d.get(BasicSnippetData.Key.MODALITY); final JavaBlock jb = buildJavaBlock(d, vs); - //create program term + // create program term final Modality symbExecMod; if (modality == Modality.BOX) { symbExecMod = Modality.DIA; @@ -78,43 +73,37 @@ private Term buildProgramTerm(BasicSnippetData d, } final Term programTerm = tb.prog(symbExecMod, jb, postTerm); - //create update + // create update Term update = tb.skip(); Iterator paramIt = vs.pre.localVars.iterator(); Iterator origParamIt = d.origVars.localVars.iterator(); while (paramIt.hasNext()) { - Term paramUpdate = - d.tb.elementary(origParamIt.next(), paramIt.next()); + Term paramUpdate = d.tb.elementary(origParamIt.next(), paramIt.next()); update = tb.parallel(update, paramUpdate); } if (vs.post.self != null) { final Term selfTerm = (Term) d.get(BasicSnippetData.Key.BLOCK_SELF); - final Term selfUpdate = - d.tb.elementary(selfTerm, vs.pre.self); + final Term selfUpdate = d.tb.elementary(selfTerm, vs.pre.self); update = tb.parallel(selfUpdate, update); } return tb.apply(update, programTerm); } - private JavaBlock buildJavaBlock(BasicSnippetData d, - ProofObligationVars poVars) { + private JavaBlock buildJavaBlock(BasicSnippetData d, ProofObligationVars poVars) { final ExecutionContext context = (ExecutionContext) d.get(BasicSnippetData.Key.EXECUTION_CONTEXT); final ProgramVariable exceptionParameter = poVars.exceptionParameter.op(ProgramVariable.class); - //create block call + // create block call final Label[] labelsArray = (Label[]) d.get(BasicSnippetData.Key.LABELS); final ImmutableArray

    + * * @author christoph */ class BasicSnippetData { @@ -54,18 +58,16 @@ class BasicSnippetData { /** * Unified contract content. */ - private final EnumMap contractContents = - new EnumMap(Key.class) { + private final EnumMap contractContents = new EnumMap(Key.class) { - private static final long serialVersionUID = -8548805965130100236L; + private static final long serialVersionUID = -8548805965130100236L; - @Override - public Object put(Key key, - Object value) { - assert value == null || key.getType().isInstance(value); - return super.put(key, value); - } - }; + @Override + public Object put(Key key, Object value) { + assert value == null || key.getType().isInstance(value); + return super.put(key, value); + } + }; /** @@ -74,8 +76,8 @@ public Object put(Key key, static enum Key { /** - * Returns the KeYJavaType representing the class/interface to which the - * specification element belongs. + * Returns the KeYJavaType representing the class/interface to which the specification + * element belongs. */ FOR_CLASS(KeYJavaType.class), /** @@ -85,20 +87,14 @@ static enum Key { /** * Returns the contracted block. */ - TARGET_BLOCK(StatementBlock.class), - PRECONDITION(Term.class), + TARGET_BLOCK(StatementBlock.class), PRECONDITION(Term.class), /** * Returns the free precondition. */ - FREE_PRECONDITION(Term.class), - POSTCONDITION(Term.class), - LOOP_INVARIANT(LoopSpecification.class), - LOOP_INVARIANT_TERM(Term.class), - MODIFIES(Term.class), - DEPENDENS(Term.class), - MEASURED_BY(Term.class), - MODALITY(Modality.class), - INF_FLOW_SPECS(ImmutableList.class), + FREE_PRECONDITION(Term.class), POSTCONDITION(Term.class), LOOP_INVARIANT( + LoopSpecification.class), LOOP_INVARIANT_TERM(Term.class), MODIFIES( + Term.class), DEPENDENS(Term.class), MEASURED_BY(Term.class), MODALITY( + Modality.class), INF_FLOW_SPECS(ImmutableList.class), /** * Self term of the transformed block contract */ @@ -106,9 +102,8 @@ static enum Key { /** * Variables originally used during parsing. */ - BLOCK_VARS(AuxiliaryContract.Variables.class), - LABELS(Label[].class), - EXECUTION_CONTEXT(ExecutionContext.class); // this does not fit well here + BLOCK_VARS(AuxiliaryContract.Variables.class), LABELS(Label[].class), EXECUTION_CONTEXT( + ExecutionContext.class); // this does not fit well here private final Class type; @@ -124,8 +119,7 @@ public Class getType() { }; - BasicSnippetData(FunctionalOperationContract contract, - Services services) { + BasicSnippetData(FunctionalOperationContract contract, Services services) { this.hasMby = contract.hasMby(); this.services = services; this.tb = services.getTermBuilder(); @@ -139,15 +133,12 @@ public Class getType() { contractContents.put(Key.MODALITY, contract.getModality()); final Term heap = tb.getBaseHeap(); - origVars = - new StateVars(contract.getSelf(), contract.getParams(), - contract.getResult(), contract.getExc(), heap); + origVars = new StateVars(contract.getSelf(), contract.getParams(), contract.getResult(), + contract.getExc(), heap); } - BasicSnippetData(LoopSpecification invariant, - ExecutionContext context, - Term guardTerm, - Services services) { + BasicSnippetData(LoopSpecification invariant, ExecutionContext context, Term guardTerm, + Services services) { this.hasMby = false; this.services = services; this.tb = services.getTermBuilder(); @@ -163,18 +154,13 @@ public Class getType() { // add guard term to information flow specs (necessary for soundness) // and add the modified specs to the table - ImmutableList infFlowSpecs = - invariant.getInfFlowSpecs(services); - ImmutableList modifedSpecs = - ImmutableSLList.nil(); - for(InfFlowSpec infFlowSpec : infFlowSpecs) { - ImmutableList modifiedPreExps = - infFlowSpec.preExpressions.append(guardTerm); - ImmutableList modifiedPostExps = - infFlowSpec.postExpressions.append(guardTerm); + ImmutableList infFlowSpecs = invariant.getInfFlowSpecs(services); + ImmutableList modifedSpecs = ImmutableSLList.nil(); + for (InfFlowSpec infFlowSpec : infFlowSpecs) { + ImmutableList modifiedPreExps = infFlowSpec.preExpressions.append(guardTerm); + ImmutableList modifiedPostExps = infFlowSpec.postExpressions.append(guardTerm); InfFlowSpec modifiedSpec = - new InfFlowSpec(modifiedPreExps, modifiedPostExps, - infFlowSpec.newObjects); + new InfFlowSpec(modifiedPreExps, modifiedPostExps, infFlowSpec.newObjects); modifedSpecs = modifedSpecs.append(modifiedSpec); } contractContents.put(Key.INF_FLOW_SPECS, modifedSpecs); @@ -187,16 +173,15 @@ public Class getType() { final ImmutableList localInTerms = toTermList(localInVariables); final ImmutableList localOutTerms = toTermList(localOutVariables); final ImmutableList localInsWithoutOutDuplicates = - MiscTools.filterOutDuplicates(localInTerms, localOutTerms); - final ImmutableList localVarsTerms = localInsWithoutOutDuplicates.append(localOutTerms); + MiscTools.filterOutDuplicates(localInTerms, localOutTerms); + final ImmutableList localVarsTerms = + localInsWithoutOutDuplicates.append(localOutTerms); - origVars = new StateVars(invariant.getInternalSelfTerm(), - guardTerm, localVarsTerms, heap); + origVars = new StateVars(invariant.getInternalSelfTerm(), guardTerm, localVarsTerms, heap); } - BasicSnippetData(InformationFlowContract contract, - Services services) { + BasicSnippetData(InformationFlowContract contract, Services services) { this.hasMby = contract.hasMby(); this.services = services; this.tb = services.getTermBuilder(); @@ -212,15 +197,12 @@ public Class getType() { contractContents.put(Key.INF_FLOW_SPECS, contract.getInfFlowSpecs()); final Term heap = tb.getBaseHeap(); - origVars = - new StateVars(contract.getSelf(), contract.getParams(), - contract.getResult(), contract.getExc(), heap); + origVars = new StateVars(contract.getSelf(), contract.getParams(), contract.getResult(), + contract.getExc(), heap); } - BasicSnippetData(BlockContract contract, - ExecutionContext context, - Services services) { + BasicSnippetData(BlockContract contract, ExecutionContext context, Services services) { this.hasMby = false; // Mby of block contracts is not further considered this.services = services; this.tb = services.getTermBuilder(); @@ -236,8 +218,7 @@ public Class getType() { contractContents.put(Key.MODALITY, contract.getModality()); contractContents.put(Key.INF_FLOW_SPECS, contract.getInfFlowSpecs()); List

    + * * @author christoph */ class BlockCallPredicateSnippet extends TwoStateMethodPredicateSnippet { @Override - String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv) { - final String nameString = - MiscTools.toValidTacletName("RELATED_BY_BLOCK_" + "at_line_" + - block.getStartPosition().getLine() + - "_in_" + pm.getUniqueName()).toString(); + String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv) { + final String nameString = MiscTools + .toValidTacletName("RELATED_BY_BLOCK_" + "at_line_" + + block.getStartPosition().getLine() + "_in_" + pm.getUniqueName()) + .toString(); return nameString; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BlockCallWithPreconditionPredicateSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BlockCallWithPreconditionPredicateSnippet.java index 2935ae5f51e..3cbeb3564a7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BlockCallWithPreconditionPredicateSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/BlockCallWithPreconditionPredicateSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.java.StatementBlock; @@ -9,18 +12,17 @@ /** * Generate term "self != null". *

    + * * @author christoph */ class BlockCallWithPreconditionPredicateSnippet extends TwoStateMethodPredicateSnippet { @Override - String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv) { - final String nameString = - MiscTools.toValidTacletName("EXECUTION_OF_BLOCK_" + "at_line_" + - block.getStartPosition().getLine() + - "_in_" + pm.getUniqueName() + "_WITH_PRE").toString(); + String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv) { + final String nameString = MiscTools.toValidTacletName("EXECUTION_OF_BLOCK_" + "at_line_" + + block.getStartPosition().getLine() + "_in_" + pm.getUniqueName() + "_WITH_PRE") + .toString(); return nameString; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/FactoryMethod.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/FactoryMethod.java index f0319d12c5c..d9ef3646d9e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/FactoryMethod.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/FactoryMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -9,7 +12,6 @@ */ interface FactoryMethod { - Term produce(BasicSnippetData d, - ProofObligationVars poVars) + Term produce(BasicSnippetData d, ProofObligationVars poVars) throws UnsupportedOperationException; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppInOutRelationSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppInOutRelationSnippet.java index e0c7897dd0e..a2eb5057784 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppInOutRelationSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppInOutRelationSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; @@ -21,11 +24,8 @@ class InfFlowContractAppInOutRelationSnippet extends InfFlowInputOutputRelationS // proof obligation where we have to show that there is an isomorphism. @Override protected Term buildObjectSensitivePostRelation(InfFlowSpec infFlowSpec1, - InfFlowSpec infFlowSpec2, - BasicSnippetData d, - ProofObligationVars vs1, - ProofObligationVars vs2, - Term eqAtLocsTerm) { + InfFlowSpec infFlowSpec2, BasicSnippetData d, ProofObligationVars vs1, + ProofObligationVars vs2, Term eqAtLocsTerm) { // build equalities for newObjects terms ImmutableList newObjEqs = ImmutableSLList.nil(); Iterator newObjects1It = infFlowSpec1.newObjects.iterator(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppSnippet.java index 58680044793..36892677144 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowContractAppSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -9,28 +12,22 @@ * * @author christoph */ -class InfFlowContractAppSnippet extends ReplaceAndRegisterMethod - implements InfFlowFactoryMethod { +class InfFlowContractAppSnippet extends ReplaceAndRegisterMethod implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) - throws UnsupportedOperationException { - BasicPOSnippetFactory f1 = - POSnippetFactory.getBasicFactory(d, poVars1); - BasicPOSnippetFactory f2 = - POSnippetFactory.getBasicFactory(d, poVars2); + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) throws UnsupportedOperationException { + BasicPOSnippetFactory f1 = POSnippetFactory.getBasicFactory(d, poVars1); + BasicPOSnippetFactory f2 = POSnippetFactory.getBasicFactory(d, poVars2); Term preCond1 = f1.create(BasicPOSnippetFactory.Snippet.CONTRACT_PRE); Term preCond2 = f2.create(BasicPOSnippetFactory.Snippet.CONTRACT_PRE); - - InfFlowPOSnippetFactory iff = - POSnippetFactory.getInfFlowFactory(d, poVars1, poVars2); + + InfFlowPOSnippetFactory iff = POSnippetFactory.getInfFlowFactory(d, poVars1, poVars2); Term inOutRelations = iff.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APP_INOUT_RELATION); return d.tb.imp(d.tb.and(preCond1, preCond2), inOutRelations); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowFactoryMethod.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowFactoryMethod.java index b213d20f89b..b79783ef0ea 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowFactoryMethod.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowFactoryMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -9,8 +12,6 @@ */ interface InfFlowFactoryMethod { - Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) + Term produce(BasicSnippetData d, ProofObligationVars poVars1, ProofObligationVars poVars2) throws UnsupportedOperationException; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowInputOutputRelationSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowInputOutputRelationSnippet.java index b37bbc80a14..d0033418f13 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowInputOutputRelationSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowInputOutputRelationSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; @@ -19,22 +22,19 @@ * @author christoph */ class InfFlowInputOutputRelationSnippet extends ReplaceAndRegisterMethod - implements InfFlowFactoryMethod { + implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) - throws UnsupportedOperationException { + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) throws UnsupportedOperationException { // get information flow specification terms if (d.get(BasicSnippetData.Key.INF_FLOW_SPECS) == null) { - throw new UnsupportedOperationException("Tried to produce " + - "information flow relations for a contract without " + - "information flow specification."); + throw new UnsupportedOperationException( + "Tried to produce " + "information flow relations for a contract without " + + "information flow specification."); } assert ImmutableList.class.equals(BasicSnippetData.Key.INF_FLOW_SPECS.getType()); @SuppressWarnings("unchecked") - ImmutableList - origInfFlowSpecs = + ImmutableList origInfFlowSpecs = (ImmutableList) d.get(BasicSnippetData.Key.INF_FLOW_SPECS); // the information-flow-specification-sequents evaluated in the pre-state @@ -42,48 +42,36 @@ public Term produce(BasicSnippetData d, InfFlowSpec[] infFlowSpecsAtPre2 = replace(origInfFlowSpecs, d.origVars, poVars2.pre, d.tb); // the information-flow-specification-sequents evaluated in the post-state - InfFlowSpec[] infFlowSpecsAtPost1 = replace(origInfFlowSpecs, d.origVars, poVars1.post, d.tb); - InfFlowSpec[] infFlowSpecsAtPost2 = replace(origInfFlowSpecs, d.origVars, poVars2.post, d.tb); + InfFlowSpec[] infFlowSpecsAtPost1 = + replace(origInfFlowSpecs, d.origVars, poVars1.post, d.tb); + InfFlowSpec[] infFlowSpecsAtPost2 = + replace(origInfFlowSpecs, d.origVars, poVars2.post, d.tb); // create input-output-relations final Term[] relations = new Term[infFlowSpecsAtPre1.length]; for (int i = 0; i < infFlowSpecsAtPre1.length; i++) { - relations[i] = buildInputOutputRelation(d, poVars1, poVars2, - infFlowSpecsAtPre1[i], - infFlowSpecsAtPre2[i], - infFlowSpecsAtPost1[i], - infFlowSpecsAtPost2[i]); + relations[i] = buildInputOutputRelation(d, poVars1, poVars2, infFlowSpecsAtPre1[i], + infFlowSpecsAtPre2[i], infFlowSpecsAtPost1[i], infFlowSpecsAtPost2[i]); } return d.tb.and(relations); } - private Term buildInputOutputRelation(BasicSnippetData d, - ProofObligationVars vs1, - ProofObligationVars vs2, - InfFlowSpec infFlowSpecAtPre1, - InfFlowSpec infFlowSpecAtPre2, - InfFlowSpec infFlowSpecAtPost1, - InfFlowSpec infFlowSpecAtPost2) { - Term inputRelation = - buildInputRelation(d, vs1, vs2, infFlowSpecAtPre1, - infFlowSpecAtPre2); + private Term buildInputOutputRelation(BasicSnippetData d, ProofObligationVars vs1, + ProofObligationVars vs2, InfFlowSpec infFlowSpecAtPre1, InfFlowSpec infFlowSpecAtPre2, + InfFlowSpec infFlowSpecAtPost1, InfFlowSpec infFlowSpecAtPost2) { + Term inputRelation = buildInputRelation(d, vs1, vs2, infFlowSpecAtPre1, infFlowSpecAtPre2); Term outputRelation = - buildOutputRelation(d, vs1, vs2, infFlowSpecAtPost1, - infFlowSpecAtPost2); + buildOutputRelation(d, vs1, vs2, infFlowSpecAtPost1, infFlowSpecAtPost2); return d.tb.imp(inputRelation, - d.tb.label(outputRelation, - ParameterlessTermLabel.POST_CONDITION_LABEL)); + d.tb.label(outputRelation, ParameterlessTermLabel.POST_CONDITION_LABEL)); } - private Term buildInputRelation(BasicSnippetData d, - ProofObligationVars vs1, - ProofObligationVars vs2, - InfFlowSpec infFlowSpec1, - InfFlowSpec infFlowSpec2) { + private Term buildInputRelation(BasicSnippetData d, ProofObligationVars vs1, + ProofObligationVars vs2, InfFlowSpec infFlowSpec1, InfFlowSpec infFlowSpec2) { Term[] eqAtLocs = new Term[infFlowSpec1.preExpressions.size()]; Iterator preExp1It = infFlowSpec1.preExpressions.iterator(); @@ -94,8 +82,7 @@ private Term buildInputRelation(BasicSnippetData d, SearchVisitor search = new SearchVisitor(vs1.pre.result, vs1.post.result); preExp1Term.execPreOrder(search); if (!search.termFound) { - eqAtLocs[i] = - d.tb.equals(preExp1Term, preExp2Term); + eqAtLocs[i] = d.tb.equals(preExp1Term, preExp2Term); } else { // terms which contain \result are not included in // the precondition @@ -106,11 +93,8 @@ private Term buildInputRelation(BasicSnippetData d, return d.tb.and(eqAtLocs); } - private Term buildOutputRelation(BasicSnippetData d, - ProofObligationVars vs1, - ProofObligationVars vs2, - InfFlowSpec infFlowSpec1, - InfFlowSpec infFlowSpec2) { + private Term buildOutputRelation(BasicSnippetData d, ProofObligationVars vs1, + ProofObligationVars vs2, InfFlowSpec infFlowSpec1, InfFlowSpec infFlowSpec2) { // build equalities for post expressions ImmutableList eqAtLocs = ImmutableSLList.nil(); @@ -128,18 +112,15 @@ private Term buildOutputRelation(BasicSnippetData d, return eqAtLocsTerm; } else { // object sensitive case - return buildObjectSensitivePostRelation(infFlowSpec1, infFlowSpec2, - d, vs1, vs2, eqAtLocsTerm); + return buildObjectSensitivePostRelation(infFlowSpec1, infFlowSpec2, d, vs1, vs2, + eqAtLocsTerm); } } protected Term buildObjectSensitivePostRelation(InfFlowSpec infFlowSpec1, - InfFlowSpec infFlowSpec2, - BasicSnippetData d, - ProofObligationVars vs1, - ProofObligationVars vs2, - Term eqAtLocsTerm) { + InfFlowSpec infFlowSpec2, BasicSnippetData d, ProofObligationVars vs1, + ProofObligationVars vs2, Term eqAtLocsTerm) { // build equalities for newObjects terms ImmutableList newObjEqs = ImmutableSLList.nil(); Iterator newObjects1It = infFlowSpec1.newObjects.iterator(); @@ -155,23 +136,21 @@ protected Term buildObjectSensitivePostRelation(InfFlowSpec infFlowSpec1, final Term newObjsSeq1 = d.tb.seq(infFlowSpec1.newObjects); final Term newObjsSeq2 = d.tb.seq(infFlowSpec2.newObjects); final Function newObjectsIso = - (Function)d.services.getNamespaces().functions().lookup("newObjectsIsomorphic"); - final Term isoTerm = d.tb.func(newObjectsIso, newObjsSeq1, vs1.pre.heap, - newObjsSeq2, vs2.pre.heap); + (Function) d.services.getNamespaces().functions().lookup("newObjectsIsomorphic"); + final Term isoTerm = + d.tb.func(newObjectsIso, newObjsSeq1, vs1.pre.heap, newObjsSeq2, vs2.pre.heap); // build object oriented post-relation (object sensitive case) - final Term ooPostRelation = - d.tb.and(isoTerm, d.tb.imp(newObjEqsTerm, eqAtLocsTerm)); - if (vs1.pre.guard != null && vs1.post.guard != null - && vs2.pre.guard != null && vs2.post.guard != null) { + final Term ooPostRelation = d.tb.and(isoTerm, d.tb.imp(newObjEqsTerm, eqAtLocsTerm)); + if (vs1.pre.guard != null && vs1.post.guard != null && vs2.pre.guard != null + && vs2.post.guard != null) { // Case of loop invariants. // In this case newObjecs is only considered in case the // loop body is entered. Otherwise no code is executed an // hence also no objects can be created. final Term preGuardFalse1 = d.tb.equals(vs1.pre.guard, d.tb.FALSE()); final Term preGuardFalse2 = d.tb.equals(vs2.pre.guard, d.tb.FALSE()); - return d.tb.ife(d.tb.and(preGuardFalse1, preGuardFalse2), - eqAtLocsTerm, ooPostRelation); + return d.tb.ife(d.tb.and(preGuardFalse1, preGuardFalse2), eqAtLocsTerm, ooPostRelation); } else { // Normal case. return ooPostRelation; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowLoopInvAppSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowLoopInvAppSnippet.java index 13be741db5b..1b642608b91 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowLoopInvAppSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowLoopInvAppSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -8,22 +11,18 @@ public class InfFlowLoopInvAppSnippet extends ReplaceAndRegisterMethod implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) throws UnsupportedOperationException { - BasicPOSnippetFactory f1 = - POSnippetFactory.getBasicFactory(d, poVars1); - BasicPOSnippetFactory f2 = - POSnippetFactory.getBasicFactory(d, poVars2); + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) throws UnsupportedOperationException { + BasicPOSnippetFactory f1 = POSnippetFactory.getBasicFactory(d, poVars1); + BasicPOSnippetFactory f2 = POSnippetFactory.getBasicFactory(d, poVars2); Term loopInv1 = f1.create(BasicPOSnippetFactory.Snippet.LOOP_INV); Term loopInv2 = f2.create(BasicPOSnippetFactory.Snippet.LOOP_INV); - InfFlowPOSnippetFactory iff = - POSnippetFactory.getInfFlowFactory(d, poVars1, poVars2); + InfFlowPOSnippetFactory iff = POSnippetFactory.getInfFlowFactory(d, poVars1, poVars2); Term inOutRelations = iff.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APP_INOUT_RELATION); return d.tb.imp(d.tb.and(loopInv1, loopInv2), inOutRelations); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactory.java index 5a65ea0be9a..656fdea1216 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -12,36 +15,38 @@ public interface InfFlowPOSnippetFactory { * The snippets which can be produced by this factory. */ public static enum Snippet { - // ( {s1}respects = {s2}respects - // & {s1}declassifies = {s2}declassifies ) - // -> {s1_post}respects = {s2_post}respects - INF_FLOW_INPUT_OUTPUT_RELATION (InfFlowInputOutputRelationSnippet.class), - - INF_FLOW_CONTRACT_APP_INOUT_RELATION (InfFlowContractAppInOutRelationSnippet.class), - - // ( {s1}pre & {s2}pre ) - // -> ( ( {s1}respects = {s2}respects - // & {s1}declassifies = {s2}declassifies ) - // -> {s1_post}respects = {s2_post}respects ) - INF_FLOW_CONTRACT_APPL (InfFlowContractAppSnippet.class), - - // ( {s1}inv & {s2}inv ) - // -> ( ( {s1}respects = {s2}respects ) - // & {s1}declassifies = {s2}declassifies ) - // -> {s1_post}respects = {s2_post}respects ) - INF_FLOW_LOOP_INVARIANT_APPL (InfFlowLoopInvAppSnippet.class), - - // {s1}EXECUTION_OF_package.class::m_WITH_PRE(self, param1, ..., paramN, heap, result, exc, heapAtPost) - // & {s2}EXECUTION_OF_package.class::m_WITH_PRE(self, param1, ..., paramN, heap, result, exc, heapAtPost) - SELFCOMPOSED_EXECUTION_WITH_PRE_RELATION (SelfcomposedExecutionSnippet.class), - - // {s1}EXECUTION_OF_package.class::m_WITH_INV(self, localIn1, ..., localInN, heap, + // ( {s1}respects = {s2}respects + // & {s1}declassifies = {s2}declassifies ) + // -> {s1_post}respects = {s2_post}respects + INF_FLOW_INPUT_OUTPUT_RELATION(InfFlowInputOutputRelationSnippet.class), + + INF_FLOW_CONTRACT_APP_INOUT_RELATION(InfFlowContractAppInOutRelationSnippet.class), + + // ( {s1}pre & {s2}pre ) + // -> ( ( {s1}respects = {s2}respects + // & {s1}declassifies = {s2}declassifies ) + // -> {s1_post}respects = {s2_post}respects ) + INF_FLOW_CONTRACT_APPL(InfFlowContractAppSnippet.class), + + // ( {s1}inv & {s2}inv ) + // -> ( ( {s1}respects = {s2}respects ) + // & {s1}declassifies = {s2}declassifies ) + // -> {s1_post}respects = {s2_post}respects ) + INF_FLOW_LOOP_INVARIANT_APPL(InfFlowLoopInvAppSnippet.class), + + // {s1}EXECUTION_OF_package.class::m_WITH_PRE(self, param1, ..., paramN, heap, result, exc, + // heapAtPost) + // & {s2}EXECUTION_OF_package.class::m_WITH_PRE(self, param1, ..., paramN, heap, result, + // exc, heapAtPost) + SELFCOMPOSED_EXECUTION_WITH_PRE_RELATION(SelfcomposedExecutionSnippet.class), + + // {s1}EXECUTION_OF_package.class::m_WITH_INV(self, localIn1, ..., localInN, heap, // localOut1, ..., localOutN, heapAtPost) - // & {s2}EXECUTION_OF_package.class::m_WITH_WITH_INV(self, localIn1, ..., localInN, heap, + // & {s2}EXECUTION_OF_package.class::m_WITH_WITH_INV(self, localIn1, ..., localInN, heap, // localOut1, ..., localOutN, heapAtPost) - SELFCOMPOSED_LOOP_WITH_INV_RELATION (SelfcomposedLoopSnippet.class), + SELFCOMPOSED_LOOP_WITH_INV_RELATION(SelfcomposedLoopSnippet.class), - SELFCOMPOSED_BLOCK_WITH_PRE_RELATION (SelfcomposedBlockSnippet.class); + SELFCOMPOSED_BLOCK_WITH_PRE_RELATION(SelfcomposedBlockSnippet.class); // type of the factory method public final Class c; @@ -53,7 +58,6 @@ public static enum Snippet { }; - public Term create(Snippet snippet) - throws UnsupportedOperationException; + public Term create(Snippet snippet) throws UnsupportedOperationException; -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactoryImpl.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactoryImpl.java index 8e62c7878a6..7c5a9d231c7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactoryImpl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/InfFlowPOSnippetFactoryImpl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import java.lang.reflect.InvocationTargetException; @@ -38,42 +41,33 @@ class InfFlowPOSnippetFactoryImpl implements InfFlowPOSnippetFactory { new EnumMap(Snippet.class); - InfFlowPOSnippetFactoryImpl(InformationFlowContract contract, - ProofObligationVars vars1, - ProofObligationVars vars2, - Services services) { + InfFlowPOSnippetFactoryImpl(InformationFlowContract contract, ProofObligationVars vars1, + ProofObligationVars vars2, Services services) { this.data = new BasicSnippetData(contract, services); this.poVars1 = vars1.labelHeapAtPreAsAnonHeapFunc(); this.poVars2 = vars2.labelHeapAtPreAsAnonHeapFunc(); registerFactoryMethods(); } - InfFlowPOSnippetFactoryImpl(BlockContract contract, - ProofObligationVars vars1, - ProofObligationVars vars2, - ExecutionContext context, - Services services) { + InfFlowPOSnippetFactoryImpl(BlockContract contract, ProofObligationVars vars1, + ProofObligationVars vars2, ExecutionContext context, Services services) { this.data = new BasicSnippetData(contract, context, services); this.poVars1 = vars1.labelHeapAtPreAsAnonHeapFunc(); this.poVars2 = vars2.labelHeapAtPreAsAnonHeapFunc(); registerFactoryMethods(); } - InfFlowPOSnippetFactoryImpl(LoopSpecification invariant, - ProofObligationVars vars1, - ProofObligationVars vars2, - ExecutionContext context, - Term guardTerm, - Services services) { + InfFlowPOSnippetFactoryImpl(LoopSpecification invariant, ProofObligationVars vars1, + ProofObligationVars vars2, ExecutionContext context, Term guardTerm, + Services services) { this.data = new BasicSnippetData(invariant, context, guardTerm, services); this.poVars1 = vars1.labelHeapAtPreAsAnonHeapFunc(); this.poVars2 = vars2.labelHeapAtPreAsAnonHeapFunc(); registerFactoryMethods(); } - InfFlowPOSnippetFactoryImpl(BasicSnippetData d, - ProofObligationVars vars1, - ProofObligationVars vars2) { + InfFlowPOSnippetFactoryImpl(BasicSnippetData d, ProofObligationVars vars1, + ProofObligationVars vars2) { this.data = d; this.poVars1 = vars1.labelHeapAtPreAsAnonHeapFunc(); this.poVars2 = vars2.labelHeapAtPreAsAnonHeapFunc(); @@ -89,23 +83,23 @@ private void registerFactoryMethods() { factoryMethods.put(s, fm); } } catch (InstantiationException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } catch (IllegalAccessException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } catch (IllegalArgumentException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } catch (InvocationTargetException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } catch (NoSuchMethodException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } catch (SecurityException ex) { - Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()). - log(Level.SEVERE, null, ex); + Logger.getLogger(InfFlowPOSnippetFactoryImpl.class.getName()).log(Level.SEVERE, null, + ex); } } @@ -115,15 +109,14 @@ public Term create(Snippet snippet) throws UnsupportedOperationException { try { InfFlowFactoryMethod m = factoryMethods.get(snippet); if (m == null) { - throw new UnsupportedOperationException("Unknown factory " + - "method for snippet \"" + snippet.name() + "."); + throw new UnsupportedOperationException( + "Unknown factory " + "method for snippet \"" + snippet.name() + "."); } Term result = m.produce(data, poVars1, poVars2); return result; } catch (TermCreationException e) { - throw new UnsupportedOperationException("Factory method for " + - "snippet \"" + snippet.name() + "threw " + - "TermCreationException: " + e.getMessage()); + throw new UnsupportedOperationException("Factory method for " + "snippet \"" + + snippet.name() + "threw " + "TermCreationException: " + e.getMessage()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallPredicateSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallPredicateSnippet.java index 7fc8ab9ae03..38e4790611f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallPredicateSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallPredicateSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.java.StatementBlock; @@ -7,13 +10,11 @@ public class LoopCallPredicateSnippet extends TwoStateMethodPredicateSnippet { @Override - String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv) { - final String nameString = - MiscTools.toValidTacletName("RELATED_BY_LOOP_" + "at_line_" + - loopInv.getLoop().getStartPosition().getLine() + - "_in_" + pm.getUniqueName()).toString(); + String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv) { + final String nameString = MiscTools.toValidTacletName("RELATED_BY_LOOP_" + "at_line_" + + loopInv.getLoop().getStartPosition().getLine() + "_in_" + pm.getUniqueName()) + .toString(); return nameString; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallWithInvariantPredicateSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallWithInvariantPredicateSnippet.java index 2036f86f98a..54bf359723e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallWithInvariantPredicateSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/LoopCallWithInvariantPredicateSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.java.StatementBlock; @@ -8,13 +11,12 @@ public class LoopCallWithInvariantPredicateSnippet extends TwoStateMethodPredicateSnippet { @Override - String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv) { - final String nameString = - MiscTools.toValidTacletName("EXECUTION_OF_LOOP_" + "at_line_" + - loopInv.getLoop().getStartPosition().getLine() + - "_in_" + pm.getUniqueName() + "_WITH_INV").toString(); + String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv) { + final String nameString = MiscTools.toValidTacletName( + "EXECUTION_OF_LOOP_" + "at_line_" + loopInv.getLoop().getStartPosition().getLine() + + "_in_" + pm.getUniqueName() + "_WITH_INV") + .toString(); return nameString; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/MethodCallPredicateSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/MethodCallPredicateSnippet.java index 28572571fca..04870d9c78b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/MethodCallPredicateSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/MethodCallPredicateSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import org.key_project.util.collection.ImmutableArray; @@ -14,22 +17,22 @@ /** * Generate term "self != null". *

    + * * @author christoph */ class MethodCallPredicateSnippet extends TwoStateMethodPredicateSnippet { @Override - String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv) { + String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv) { final String nameString = MiscTools.toValidTacletName("RELATED_BY_" + pm.getUniqueName()).toString(); return nameString; } @Override - protected Sort[] generateContApplArgumentSorts( - ImmutableList termList, IProgramMethod pm) { + protected Sort[] generateContApplArgumentSorts(ImmutableList termList, + IProgramMethod pm) { Sort[] argSorts = new Sort[termList.size()]; ImmutableArray pmSorts = pm.argSorts(); @@ -39,8 +42,8 @@ protected Sort[] generateContApplArgumentSorts( // bugfix: Take the first argument sorts from the definition of // the method rather than from the actually provided arguments. // aug 2015 SG + MU - if(i < pmSorts.size() - 1) { - argSorts[i] = pmSorts.get(i+1); + if (i < pmSorts.size() - 1) { + argSorts[i] = pmSorts.get(i + 1); } else { argSorts[i] = arg.sort(); } @@ -49,4 +52,4 @@ protected Sort[] generateContApplArgumentSorts( return argSorts; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/POSnippetFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/POSnippetFactory.java index 1a61fa71541..bb6e231b069 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/POSnippetFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/POSnippetFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.java.Services; @@ -16,77 +19,51 @@ */ public class POSnippetFactory { - public static BasicPOSnippetFactory getBasicFactory( - FunctionalOperationContract contract, - ProofObligationVars vars, - Services services) { + public static BasicPOSnippetFactory getBasicFactory(FunctionalOperationContract contract, + ProofObligationVars vars, Services services) { return new BasicPOSnippetFactoryImpl(contract, vars, services); } - - public static BasicPOSnippetFactory getBasicFactory( - LoopSpecification invariant, - ProofObligationVars vars, - ExecutionContext context, - Term guardTerm, - Services services) { - return new BasicPOSnippetFactoryImpl(invariant, vars, context, - guardTerm, services); + + public static BasicPOSnippetFactory getBasicFactory(LoopSpecification invariant, + ProofObligationVars vars, ExecutionContext context, Term guardTerm, Services services) { + return new BasicPOSnippetFactoryImpl(invariant, vars, context, guardTerm, services); } - public static BasicPOSnippetFactory getBasicFactory( - InformationFlowContract contract, - ProofObligationVars vars, - Services services) { + public static BasicPOSnippetFactory getBasicFactory(InformationFlowContract contract, + ProofObligationVars vars, Services services) { return new BasicPOSnippetFactoryImpl(contract, vars, services); - } + } - public static BasicPOSnippetFactory getBasicFactory( - BlockContract contract, - ProofObligationVars vars, - ExecutionContext context, - Services services) { + public static BasicPOSnippetFactory getBasicFactory(BlockContract contract, + ProofObligationVars vars, ExecutionContext context, Services services) { return new BasicPOSnippetFactoryImpl(contract, vars, context, services); } - static BasicPOSnippetFactory getBasicFactory( - BasicSnippetData data, + static BasicPOSnippetFactory getBasicFactory(BasicSnippetData data, ProofObligationVars poVars) { return new BasicPOSnippetFactoryImpl(data, poVars); } - public static InfFlowPOSnippetFactory getInfFlowFactory( - LoopSpecification invariant, - ProofObligationVars vars1, - ProofObligationVars vars2, - ExecutionContext context, - Term guardTerm, - Services services) { - return new InfFlowPOSnippetFactoryImpl(invariant, vars1, vars2, context, - guardTerm, services); + public static InfFlowPOSnippetFactory getInfFlowFactory(LoopSpecification invariant, + ProofObligationVars vars1, ProofObligationVars vars2, ExecutionContext context, + Term guardTerm, Services services) { + return new InfFlowPOSnippetFactoryImpl(invariant, vars1, vars2, context, guardTerm, + services); } - - public static InfFlowPOSnippetFactory getInfFlowFactory( - InformationFlowContract contract, - ProofObligationVars vars1, - ProofObligationVars vars2, - Services services) { + + public static InfFlowPOSnippetFactory getInfFlowFactory(InformationFlowContract contract, + ProofObligationVars vars1, ProofObligationVars vars2, Services services) { return new InfFlowPOSnippetFactoryImpl(contract, vars1, vars2, services); } - - public static InfFlowPOSnippetFactory getInfFlowFactory( - BlockContract contract, - ProofObligationVars vars1, - ProofObligationVars vars2, - ExecutionContext context, + + public static InfFlowPOSnippetFactory getInfFlowFactory(BlockContract contract, + ProofObligationVars vars1, ProofObligationVars vars2, ExecutionContext context, Services services) { - return new InfFlowPOSnippetFactoryImpl(contract, vars1, vars2, - context, services); + return new InfFlowPOSnippetFactoryImpl(contract, vars1, vars2, context, services); } - static InfFlowPOSnippetFactory getInfFlowFactory( - BasicSnippetData data, - ProofObligationVars vars1, - ProofObligationVars vars2) { + static InfFlowPOSnippetFactory getInfFlowFactory(BasicSnippetData data, + ProofObligationVars vars1, ProofObligationVars vars2) { return new InfFlowPOSnippetFactoryImpl(data, vars1, vars2); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/ReplaceAndRegisterMethod.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/ReplaceAndRegisterMethod.java index 7eb4cce8a84..fe64df07dd1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/ReplaceAndRegisterMethod.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/ReplaceAndRegisterMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.informationflow.proof.init.StateVars; @@ -23,41 +26,35 @@ /** * Generate term "self != null". *

    + * * @author christoph */ abstract class ReplaceAndRegisterMethod { - final Term replace(Term term, - ProofObligationVars origVars, - ProofObligationVars poVars, - TermBuilder tb) { + final Term replace(Term term, ProofObligationVars origVars, ProofObligationVars poVars, + TermBuilder tb) { Term intermediateResult = replace(term, origVars.pre, poVars.pre, tb); return replace(intermediateResult, origVars.post, poVars.post, tb); } - final Term replace(Term term, - StateVars origVars, - StateVars poVars, - TermBuilder tb) { + final Term replace(Term term, StateVars origVars, StateVars poVars, TermBuilder tb) { LinkedHashMap map = new LinkedHashMap<>(); Iterator origVarsIt; Iterator poVarsIt; - assert origVars.paddedTermList.size() == - poVars.paddedTermList.size(); + assert origVars.paddedTermList.size() == poVars.paddedTermList.size(); origVarsIt = origVars.paddedTermList.iterator(); poVarsIt = poVars.paddedTermList.iterator(); while (origVarsIt.hasNext()) { Term origTerm = origVarsIt.next(); Term poTerm = poVarsIt.next(); if (origTerm != null && poTerm != null) { - assert poTerm.sort().equals(origTerm.sort()) || - poTerm.sort().extendsSorts().contains(origTerm.sort()) : - "mismatch of sorts: orignal term " + origTerm + - ", sort " + origTerm.sort() + - "; replacement term" + poTerm + ", sort " + - poTerm.sort(); + assert poTerm.sort().equals(origTerm.sort()) + || poTerm.sort().extendsSorts().contains(origTerm.sort()) + : "mismatch of sorts: orignal term " + origTerm + ", sort " + + origTerm.sort() + "; replacement term" + poTerm + ", sort " + + poTerm.sort(); map.put(origTerm, poTerm); } } @@ -66,10 +63,7 @@ final Term replace(Term term, } - final Term[] replace(Term[] terms, - StateVars origVars, - StateVars poVars, - TermBuilder tb) { + final Term[] replace(Term[] terms, StateVars origVars, StateVars poVars, TermBuilder tb) { final Term[] result = new Term[terms.length]; for (int i = 0; i < terms.length; i++) { result[i] = replace(terms[i], origVars, poVars, tb); @@ -79,10 +73,8 @@ final Term[] replace(Term[] terms, } - final InfFlowSpec replace(InfFlowSpec terms, - StateVars origVars, - StateVars poVars, - TermBuilder tb) { + final InfFlowSpec replace(InfFlowSpec terms, StateVars origVars, StateVars poVars, + TermBuilder tb) { ImmutableList resultPreExps = ImmutableSLList.nil(); for (Term t : terms.preExpressions) { resultPreExps = resultPreExps.append(replace(t, origVars, poVars, tb)); @@ -99,10 +91,8 @@ final InfFlowSpec replace(InfFlowSpec terms, } - final InfFlowSpec[] replace(ImmutableList termss, - StateVars origVars, - StateVars poVars, - TermBuilder tb) { + final InfFlowSpec[] replace(ImmutableList termss, StateVars origVars, + StateVars poVars, TermBuilder tb) { final InfFlowSpec[] result = new InfFlowSpec[termss.size()]; Iterator it = termss.iterator(); for (int i = 0; it.hasNext(); i++) { @@ -112,10 +102,7 @@ final InfFlowSpec[] replace(ImmutableList termss, } - final Term replace(Term term, - Term[] origVars, - Term[] poVars, - TermBuilder tb) { + final Term replace(Term term, Term[] origVars, Term[] poVars, TermBuilder tb) { LinkedHashMap map = new LinkedHashMap<>(); assert origVars.length == poVars.length; @@ -135,8 +122,7 @@ final Term replace(Term term, } - final void register(ProgramVariable pv, - Services services) { + final void register(ProgramVariable pv, Services services) { Namespace progVarNames = services.getNamespaces().programVariables(); if (pv != null && progVarNames.lookup(pv.name()) == null) { progVarNames.addSafely(pv); @@ -144,16 +130,14 @@ final void register(ProgramVariable pv, } - final void register(ImmutableList pvs, - Services services) { + final void register(ImmutableList pvs, Services services) { for (ProgramVariable pv : pvs) { register(pv, services); } } - final void register(Function f, - Services services) { + final void register(Function f, Services services) { Namespace functionNames = services.getNamespaces().functions(); if (f != null && functionNames.lookup(f.name()) == null) { assert f.sort() != Sort.UPDATE; @@ -161,16 +145,14 @@ final void register(Function f, } } - static Term replaceQuantifiableVariables(Term term, - Set qvs, - Services services) { - Map replaceMap = - new LinkedHashMap<>(); - for (QuantifiableVariable qv: qvs) { + static Term replaceQuantifiableVariables(Term term, Set qvs, + Services services) { + Map replaceMap = new LinkedHashMap<>(); + for (QuantifiableVariable qv : qvs) { replaceMap.put(qv, new LogicVariable(qv.name(), qv.sort())); } - final OpReplacer op = new OpReplacer( - replaceMap, services.getTermFactory(), services.getProof()); + final OpReplacer op = + new OpReplacer(replaceMap, services.getTermFactory(), services.getProof()); term = TermLabel.removeIrrelevantLabels(term, services.getTermFactory()); return op.replace(term); } @@ -192,7 +174,8 @@ public boolean visitSubtree(Term visited) { @Override public void visit(Term visited) { final ImmutableArray boundVars = visited.boundVars(); - for (QuantifiableVariable var : boundVars) vars.add(var); + for (QuantifiableVariable var : boundVars) + vars.add(var); } @Override @@ -201,6 +184,8 @@ public void subtreeEntered(Term subtreeRoot) { /* nothing to do */ } @Override public void subtreeLeft(Term subtreeRoot) { /* nothing to do */ } - public Set getResult() { return vars; } + public Set getResult() { + return vars; + } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedBlockSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedBlockSnippet.java index 8a8db44b4a8..9336abdb9c3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedBlockSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedBlockSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -12,34 +15,23 @@ * * @author christoph */ -class SelfcomposedBlockSnippet extends ReplaceAndRegisterMethod - implements InfFlowFactoryMethod { +class SelfcomposedBlockSnippet extends ReplaceAndRegisterMethod implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) { - BasicPOSnippetFactory f1 = - POSnippetFactory.getBasicFactory(d, poVars1); - BasicPOSnippetFactory f2 = - POSnippetFactory.getBasicFactory(d, poVars2); + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) { + BasicPOSnippetFactory f1 = POSnippetFactory.getBasicFactory(d, poVars1); + BasicPOSnippetFactory f2 = POSnippetFactory.getBasicFactory(d, poVars2); - final Term exec1 = - f1.create(BasicPOSnippetFactory.Snippet.BLOCK_EXEC_WITH_PRE); - final Set qvsToReplace = - collectQuantifiableVariables(exec1); + final Term exec1 = f1.create(BasicPOSnippetFactory.Snippet.BLOCK_EXEC_WITH_PRE); + final Set qvsToReplace = collectQuantifiableVariables(exec1); final Term updatedExec1 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars1.pre.heap), - exec1); - final Term exec2 = - replaceQuantifiableVariables( - f2.create(BasicPOSnippetFactory.Snippet.BLOCK_EXEC_WITH_PRE), - qvsToReplace, d.services); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars1.pre.heap), exec1); + final Term exec2 = replaceQuantifiableVariables( + f2.create(BasicPOSnippetFactory.Snippet.BLOCK_EXEC_WITH_PRE), qvsToReplace, + d.services); final Term updatedExec2 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars2.pre.heap), - exec2); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars2.pre.heap), exec2); return d.tb.and(updatedExec1, updatedExec2); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedExecutionSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedExecutionSnippet.java index cb20dc5209c..edde90693bb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedExecutionSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedExecutionSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -14,30 +17,20 @@ class SelfcomposedExecutionSnippet extends ReplaceAndRegisterMethod implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) { - BasicPOSnippetFactory f1 = - POSnippetFactory.getBasicFactory(d, poVars1); - BasicPOSnippetFactory f2 = - POSnippetFactory.getBasicFactory(d, poVars2); + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) { + BasicPOSnippetFactory f1 = POSnippetFactory.getBasicFactory(d, poVars1); + BasicPOSnippetFactory f2 = POSnippetFactory.getBasicFactory(d, poVars2); - final Term exec1 = - f1.create(BasicPOSnippetFactory.Snippet.SYMBOLIC_EXEC_WITH_PRE); - final Set qvsToReplace = - collectQuantifiableVariables(exec1); + final Term exec1 = f1.create(BasicPOSnippetFactory.Snippet.SYMBOLIC_EXEC_WITH_PRE); + final Set qvsToReplace = collectQuantifiableVariables(exec1); final Term updatedExec1 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars1.pre.heap), - exec1); - final Term exec2 = - replaceQuantifiableVariables( - f2.create(BasicPOSnippetFactory.Snippet.SYMBOLIC_EXEC_WITH_PRE), - qvsToReplace, d.services); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars1.pre.heap), exec1); + final Term exec2 = replaceQuantifiableVariables( + f2.create(BasicPOSnippetFactory.Snippet.SYMBOLIC_EXEC_WITH_PRE), qvsToReplace, + d.services); final Term updatedExec2 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars2.pre.heap), - exec2); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars2.pre.heap), exec2); return d.tb.and(updatedExec1, updatedExec2); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedLoopSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedLoopSnippet.java index 867910ab078..a367dce1e53 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedLoopSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/SelfcomposedLoopSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import de.uka.ilkd.key.logic.Term; @@ -7,34 +10,24 @@ import java.util.Set; -public class SelfcomposedLoopSnippet extends ReplaceAndRegisterMethod implements - InfFlowFactoryMethod { +public class SelfcomposedLoopSnippet extends ReplaceAndRegisterMethod + implements InfFlowFactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars1, - ProofObligationVars poVars2) { - BasicPOSnippetFactory f1 = - POSnippetFactory.getBasicFactory(d, poVars1); - BasicPOSnippetFactory f2 = - POSnippetFactory.getBasicFactory(d, poVars2); - final Term exec1 = - f1.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV); - final Set qvsToReplace = - collectQuantifiableVariables(exec1); + public Term produce(BasicSnippetData d, ProofObligationVars poVars1, + ProofObligationVars poVars2) { + BasicPOSnippetFactory f1 = POSnippetFactory.getBasicFactory(d, poVars1); + BasicPOSnippetFactory f2 = POSnippetFactory.getBasicFactory(d, poVars2); + final Term exec1 = f1.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV); + final Set qvsToReplace = collectQuantifiableVariables(exec1); final Term updatedExec1 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars1.pre.heap), - exec1); - final Term exec2 = - replaceQuantifiableVariables( - f2.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV), - qvsToReplace, d.services); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars1.pre.heap), exec1); + final Term exec2 = replaceQuantifiableVariables( + f2.create(BasicPOSnippetFactory.Snippet.LOOP_EXEC_WITH_INV), qvsToReplace, + d.services); final Term updatedExec2 = - d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), - poVars2.pre.heap), - exec2); + d.tb.apply(d.tb.elementary(d.tb.getBaseHeap(), poVars2.pre.heap), exec2); return d.tb.and(updatedExec1, updatedExec2); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/TwoStateMethodPredicateSnippet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/TwoStateMethodPredicateSnippet.java index d8282eaecd3..bd68d43b959 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/TwoStateMethodPredicateSnippet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/po/snippet/TwoStateMethodPredicateSnippet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.po.snippet; import java.util.Iterator; @@ -22,37 +25,33 @@ /** * Generate term "self != null". *

    + * * @author christoph */ abstract class TwoStateMethodPredicateSnippet implements FactoryMethod { @Override - public Term produce(BasicSnippetData d, - ProofObligationVars poVars) + public Term produce(BasicSnippetData d, ProofObligationVars poVars) throws UnsupportedOperationException { IObserverFunction targetMethod = (IObserverFunction) d.get(BasicSnippetData.Key.TARGET_METHOD); final IProgramMethod pm = (IProgramMethod) targetMethod; - StatementBlock targetBlock = - (StatementBlock) d.get(BasicSnippetData.Key.TARGET_BLOCK); - LoopSpecification loopInv = - (LoopSpecification) d.get(BasicSnippetData.Key.LOOP_INVARIANT); + StatementBlock targetBlock = (StatementBlock) d.get(BasicSnippetData.Key.TARGET_BLOCK); + LoopSpecification loopInv = (LoopSpecification) d.get(BasicSnippetData.Key.LOOP_INVARIANT); String nameString = generatePredicateName(pm, targetBlock, loopInv); - final ImmutableList termList = - extractTermListForPredicate(pm, poVars, d.hasMby); - final Sort[] argSorts = - generateContApplArgumentSorts(termList, pm); + final ImmutableList termList = extractTermListForPredicate(pm, poVars, d.hasMby); + final Sort[] argSorts = generateContApplArgumentSorts(termList, pm); final Function contApplPred = generateContApplPredicate(nameString, argSorts, d.tb, d.services); return instantiateContApplPredicate(contApplPred, termList, d.tb); } - protected Sort[] generateContApplArgumentSorts( - ImmutableList termList, IProgramMethod pm) { + protected Sort[] generateContApplArgumentSorts(ImmutableList termList, + IProgramMethod pm) { Sort[] argSorts = new Sort[termList.size()]; - //ImmutableArray pmSorts = pm.argSorts(); + // ImmutableArray pmSorts = pm.argSorts(); int i = 0; for (final Term arg : termList) { @@ -64,17 +63,16 @@ protected Sort[] generateContApplArgumentSorts( } - private Function generateContApplPredicate(String nameString, - Sort[] argSorts, - TermBuilder tb, - Services services) { + private Function generateContApplPredicate(String nameString, Sort[] argSorts, TermBuilder tb, + Services services) { final Name name = new Name(nameString); Namespace functionNS = services.getNamespaces().functions(); - /* This predicate needs to present on all branches and, therefore, must be added - * to the toplevel function namespace. Hence, we rewind to the parent namespace here. + /* + * This predicate needs to present on all branches and, therefore, must be added to the + * toplevel function namespace. Hence, we rewind to the parent namespace here. */ - while(functionNS.parent() != null) + while (functionNS.parent() != null) functionNS = functionNS.parent(); Function pred = (Function) functionNS.lookup(name); @@ -87,9 +85,8 @@ private Function generateContApplPredicate(String nameString, } - private Term instantiateContApplPredicate(Function pred, - ImmutableList termList, - TermBuilder tb) { + private Term instantiateContApplPredicate(Function pred, ImmutableList termList, + TermBuilder tb) { final Sort[] predArgSorts = new Sort[pred.argSorts().size()]; pred.argSorts().toArray(predArgSorts); Term[] predArgs = new Term[predArgSorts.length]; @@ -104,21 +101,19 @@ private Term instantiateContApplPredicate(Function pred, } - abstract String generatePredicateName(IProgramMethod pm, - StatementBlock block, - LoopSpecification loopInv); + abstract String generatePredicateName(IProgramMethod pm, StatementBlock block, + LoopSpecification loopInv); /** - * Parameters and the result of a method only have to appear once in the - * predicate. This method chooses the right variables out of the poVars. - * @param poVars The proof obligation variables. + * Parameters and the result of a method only have to appear once in the predicate. This method + * chooses the right variables out of the poVars. + * + * @param poVars The proof obligation variables. * @return */ - private ImmutableList extractTermListForPredicate( - IProgramMethod pm, - ProofObligationVars poVars, - boolean hasMby) { + private ImmutableList extractTermListForPredicate(IProgramMethod pm, + ProofObligationVars poVars, boolean hasMby) { ImmutableList relevantPreVars = ImmutableSLList.nil(); ImmutableList relevantPostVars = ImmutableSLList.nil(); @@ -173,4 +168,4 @@ private ImmutableList extractTermListForPredicate( return relevantPreVars.append(relevantPostVars); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowCheckInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowCheckInfo.java index fa3e0a393f1..54498e2ba1d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowCheckInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowCheckInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.proof; import de.uka.ilkd.key.proof.Goal; @@ -12,13 +15,10 @@ */ public class InfFlowCheckInfo { public static final Properties.Property INF_FLOW_CHECK_PROPERTY = - new Properties.Property(Boolean.class, - "information flow check property"); + new Properties.Property(Boolean.class, "information flow check property"); - public static void set(Goal goal, - final boolean checkForInfFlow) { - final boolean oldValue = - goal.getStrategyInfo(INF_FLOW_CHECK_PROPERTY); + public static void set(Goal goal, final boolean checkForInfFlow) { + final boolean oldValue = goal.getStrategyInfo(INF_FLOW_CHECK_PROPERTY); StrategyInfoUndoMethod undo = new StrategyInfoUndoMethod() { @Override @@ -35,16 +35,16 @@ public static boolean get(Goal goal) { } public static boolean isInfFlow(Goal goal) { - //StrategyProperties stratProps = - // goal.proof().getSettings().getStrategySettings().getActiveStrategyProperties(); + // StrategyProperties stratProps = + // goal.proof().getSettings().getStrategySettings().getActiveStrategyProperties(); Property ifProp = InfFlowCheckInfo.INF_FLOW_CHECK_PROPERTY; - //String ifStrat = StrategyProperties.INF_FLOW_CHECK_PROPERTY; - //String ifTrue = StrategyProperties.INF_FLOW_CHECK_TRUE; + // String ifStrat = StrategyProperties.INF_FLOW_CHECK_PROPERTY; + // String ifTrue = StrategyProperties.INF_FLOW_CHECK_TRUE; boolean isOriginalIF = (goal.getStrategyInfo(ifProp) != null && goal.getStrategyInfo(ifProp)); // For loaded proofs, InfFlowCheckInfo is not correct without the following - //boolean isLoadedIF = false; //stratProps.getProperty(ifStrat).equals(ifTrue); - return isOriginalIF/* || isLoadedIF*/; + // boolean isLoadedIF = false; //stratProps.getProperty(ifStrat).equals(ifTrue); + return isOriginalIF/* || isLoadedIF */; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowProof.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowProof.java index ddd37ec126f..994a106ae73 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowProof.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/InfFlowProof.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.proof; import org.key_project.util.collection.ImmutableList; @@ -17,17 +20,16 @@ /** * The proof object used by Information Flow Proofs. - * - * It manages some additional data specific to their kind. - * The concept of side proofs is actually more general than just to be useful for - * Information Flow proofs, but as only they are using the feature, it is currently - * moved into this subclass. + * + * It manages some additional data specific to their kind. The concept of side proofs is actually + * more general than just to be useful for Information Flow proofs, but as only they are using the + * feature, it is currently moved into this subclass. */ public class InfFlowProof extends Proof { /** - * For saving and loading Information-Flow proofs, we need to remember the - * according taclets, program variables, functions and such. + * For saving and loading Information-Flow proofs, we need to remember the according taclets, + * program variables, functions and such. */ private InfFlowProofSymbols infFlowSymbols = new InfFlowProofSymbols(); /** @@ -35,14 +37,12 @@ public class InfFlowProof extends Proof { */ private SideProofStatistics sideProofStatistics = null; - public InfFlowProof(String name, Sequent sequent, String header, - TacletIndex rules, BuiltInRuleIndex builtInRules, - InitConfig initConfig) { + public InfFlowProof(String name, Sequent sequent, String header, TacletIndex rules, + BuiltInRuleIndex builtInRules, InitConfig initConfig) { super(name, sequent, header, rules, builtInRules, initConfig); } - public InfFlowProof(String name, Term problem, String header, - InitConfig initConfig) { + public InfFlowProof(String name, Term problem, String header, InitConfig initConfig) { super(name, problem, header, initConfig); } @@ -64,9 +64,9 @@ public InfFlowProofSymbols getIFSymbols() { public void addIFSymbol(Object s) { assert s != null; if (s instanceof Term) { - infFlowSymbols.add((Term)s); + infFlowSymbols.add((Term) s); } else if (s instanceof Named) { - infFlowSymbols.add((Named)s); + infFlowSymbols.add((Named) s); } else { throw new UnsupportedOperationException("Not a valid proof symbol for IF proofs."); } @@ -75,9 +75,9 @@ public void addIFSymbol(Object s) { public void addLabeledIFSymbol(Object s) { assert s != null; if (s instanceof Term) { - infFlowSymbols.addLabeled((Term)s); + infFlowSymbols.addLabeled((Term) s); } else if (s instanceof Named) { - infFlowSymbols.addLabeled((Named)s); + infFlowSymbols.addLabeled((Named) s); } else { throw new UnsupportedOperationException("Not a valid proof symbol for IF proofs."); } @@ -97,11 +97,11 @@ public void addGoalTemplates(Taclet t) { assert t != null; ImmutableList temps = t.goalTemplates(); assert temps != null; - for (TacletGoalTemplate tgt: temps) { - for (SequentFormula sf: tgt.sequent().antecedent().asList()) { + for (TacletGoalTemplate tgt : temps) { + for (SequentFormula sf : tgt.sequent().antecedent().asList()) { addLabeledTotalTerm(sf.formula()); } - for (SequentFormula sf: tgt.sequent().succedent().asList()) { + for (SequentFormula sf : tgt.sequent().succedent().asList()) { addLabeledTotalTerm(sf.formula()); } } @@ -128,12 +128,12 @@ public boolean hasSideProofs() { public void addSideProof(InfFlowProof proof) { assert proof != null; if (proof.hasSideProofs()) { - if (this.hasSideProofs()) { - sideProofStatistics = sideProofStatistics.add(proof.sideProofStatistics); - } else { - sideProofStatistics = SideProofStatistics.create(proof.sideProofStatistics); - } - proof.sideProofStatistics = null; + if (this.hasSideProofs()) { + sideProofStatistics = sideProofStatistics.add(proof.sideProofStatistics); + } else { + sideProofStatistics = SideProofStatistics.create(proof.sideProofStatistics); + } + proof.sideProofStatistics = null; } addSideProofStatistics(proof.getStatistics()); } @@ -149,6 +149,7 @@ private void addSideProofStatistics(Statistics stat) { /** * returns statistics of possible side proofs that contributed to this proof + * * @return the proof statistics */ public SideProofStatistics getSideProofStatistics() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/SideProofStatistics.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/SideProofStatistics.java index 035b6843d34..b83987d6b5d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/SideProofStatistics.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/SideProofStatistics.java @@ -1,9 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.proof; import de.uka.ilkd.key.proof.Statistics; /** * Statistics for additional side proofs as, e.g., performed by information flow macro + * * @author Michael Kirsten */ public final class SideProofStatistics extends Statistics { @@ -15,6 +19,7 @@ public final class SideProofStatistics extends Statistics { /** * Construct new side proof statistics + * * @param sideProofs the amount of side proofs * @param nodes amount of nodes * @param branches amount of branches @@ -31,138 +36,98 @@ public final class SideProofStatistics extends Statistics { * @param loopInvApps amount of loop invariant rule applications * @param autoModeTime accumulated (spent) auto mode time */ - private SideProofStatistics(int sideProofs, - int nodes, - int branches, - int interactiveSteps, - int symbExApps, - int quantifierInstantiations, - int ossApps, - int mergeRuleApps, - int totalRuleApps, - int smtSolverApps, - int dependencyContractApps, - int operationContractApps, - int blockLoopContractApps, - int loopInvApps, - long autoModeTime) { - super(nodes, branches, interactiveSteps, symbExApps, - quantifierInstantiations, ossApps, mergeRuleApps, totalRuleApps, - smtSolverApps, dependencyContractApps, operationContractApps, - blockLoopContractApps, loopInvApps, autoModeTime, - -1, - nodes <= sideProofs ? - .0f - : (autoModeTime / (float)(nodes - sideProofs))); + private SideProofStatistics(int sideProofs, int nodes, int branches, int interactiveSteps, + int symbExApps, int quantifierInstantiations, int ossApps, int mergeRuleApps, + int totalRuleApps, int smtSolverApps, int dependencyContractApps, + int operationContractApps, int blockLoopContractApps, int loopInvApps, + long autoModeTime) { + super(nodes, branches, interactiveSteps, symbExApps, quantifierInstantiations, ossApps, + mergeRuleApps, totalRuleApps, smtSolverApps, dependencyContractApps, + operationContractApps, blockLoopContractApps, loopInvApps, autoModeTime, -1, + nodes <= sideProofs ? .0f : (autoModeTime / (float) (nodes - sideProofs))); this.sideProofs = sideProofs; } /** * Create a new side proof statistics object from existing side proof statistics. + * * @param stat side proof statistics object. - * @return a new identical side proof statistics object, - * but with the side proof number set to one. + * @return a new identical side proof statistics object, but with the side proof number set to + * one. */ static SideProofStatistics create(SideProofStatistics stat) { - return new SideProofStatistics(1, stat.nodes, - stat.branches, - stat.interactiveSteps, - stat.symbExApps, - stat.quantifierInstantiations, - stat.ossApps, - stat.mergeRuleApps, - stat.totalRuleApps, - stat.smtSolverApps, - stat.dependencyContractApps, - stat.operationContractApps, - stat.blockLoopContractApps, - stat.loopInvApps, - stat.autoModeTimeInMillis); + return new SideProofStatistics(1, stat.nodes, stat.branches, stat.interactiveSteps, + stat.symbExApps, stat.quantifierInstantiations, stat.ossApps, stat.mergeRuleApps, + stat.totalRuleApps, stat.smtSolverApps, stat.dependencyContractApps, + stat.operationContractApps, stat.blockLoopContractApps, stat.loopInvApps, + stat.autoModeTimeInMillis); } /** * Create a new side proof statistics object from existing proof statistics. + * * @param stat proof statistics object. - * @return a new identical side proof statistics object, - * but as side proof statistics and with the side proof number set to one. + * @return a new identical side proof statistics object, but as side proof statistics and with + * the side proof number set to one. */ static SideProofStatistics create(Statistics stat) { - return new SideProofStatistics(1, stat.nodes, - stat.branches, - stat.interactiveSteps, - stat.symbExApps, - stat.quantifierInstantiations, - stat.ossApps, - stat.mergeRuleApps, - stat.totalRuleApps, - stat.smtSolverApps, - stat.dependencyContractApps, - stat.operationContractApps, - stat.blockLoopContractApps, - stat.loopInvApps, - stat.autoModeTimeInMillis); + return new SideProofStatistics(1, stat.nodes, stat.branches, stat.interactiveSteps, + stat.symbExApps, stat.quantifierInstantiations, stat.ossApps, stat.mergeRuleApps, + stat.totalRuleApps, stat.smtSolverApps, stat.dependencyContractApps, + stat.operationContractApps, stat.blockLoopContractApps, stat.loopInvApps, + stat.autoModeTimeInMillis); } /** * Add side proof statistics to current one. + * * @param stat another side proof statistics object. * @return the sum of both side proof statistics objects. */ SideProofStatistics add(SideProofStatistics stat) { - return new SideProofStatistics(this.sideProofs + stat.sideProofs, - this.nodes + stat.nodes, - this.branches + stat.branches, - this.interactiveSteps + stat.interactiveSteps, - this.symbExApps + stat.symbExApps, - this.quantifierInstantiations - + stat.quantifierInstantiations, - this.ossApps + stat.ossApps, - this.mergeRuleApps + stat.mergeRuleApps, - this.totalRuleApps + stat.totalRuleApps, - this.smtSolverApps + stat.smtSolverApps, - this.dependencyContractApps + stat.dependencyContractApps, - this.operationContractApps + stat.operationContractApps, - this.blockLoopContractApps + stat.blockLoopContractApps, - this.loopInvApps + stat.loopInvApps, - this.autoModeTimeInMillis + stat.autoModeTimeInMillis); + return new SideProofStatistics(this.sideProofs + stat.sideProofs, this.nodes + stat.nodes, + this.branches + stat.branches, this.interactiveSteps + stat.interactiveSteps, + this.symbExApps + stat.symbExApps, + this.quantifierInstantiations + stat.quantifierInstantiations, + this.ossApps + stat.ossApps, this.mergeRuleApps + stat.mergeRuleApps, + this.totalRuleApps + stat.totalRuleApps, this.smtSolverApps + stat.smtSolverApps, + this.dependencyContractApps + stat.dependencyContractApps, + this.operationContractApps + stat.operationContractApps, + this.blockLoopContractApps + stat.blockLoopContractApps, + this.loopInvApps + stat.loopInvApps, + this.autoModeTimeInMillis + stat.autoModeTimeInMillis); } /** * Add proof statistics to current side proof statistics object. + * * @param stat a proof statistics object. * @return the sum of the proof statistics and the side proof statistics object. */ public SideProofStatistics add(Statistics stat) { return new SideProofStatistics(this.sideProofs + 1, this.nodes + stat.nodes, - this.branches + stat.branches, - this.interactiveSteps + stat.interactiveSteps, - this.symbExApps + stat.symbExApps, - this.quantifierInstantiations - + stat.quantifierInstantiations, - this.ossApps + stat.ossApps, - this.mergeRuleApps + stat.mergeRuleApps, - this.totalRuleApps + stat.totalRuleApps, - this.smtSolverApps + stat.smtSolverApps, - this.dependencyContractApps + stat.dependencyContractApps, - this.operationContractApps + stat.operationContractApps, - this.blockLoopContractApps + stat.blockLoopContractApps, - this.loopInvApps + stat.loopInvApps, - this.autoModeTimeInMillis + stat.autoModeTimeInMillis); + this.branches + stat.branches, this.interactiveSteps + stat.interactiveSteps, + this.symbExApps + stat.symbExApps, + this.quantifierInstantiations + stat.quantifierInstantiations, + this.ossApps + stat.ossApps, this.mergeRuleApps + stat.mergeRuleApps, + this.totalRuleApps + stat.totalRuleApps, this.smtSolverApps + stat.smtSolverApps, + this.dependencyContractApps + stat.dependencyContractApps, + this.operationContractApps + stat.operationContractApps, + this.blockLoopContractApps + stat.blockLoopContractApps, + this.loopInvApps + stat.loopInvApps, + this.autoModeTimeInMillis + stat.autoModeTimeInMillis); } /** * Set time spent in auto mode. + * * @param autoTime auto mode time as long data type. * @return identical side proof statistics object, but with changed auto mode time. */ public SideProofStatistics setAutoModeTime(long autoTime) { - return new SideProofStatistics(sideProofs, nodes, branches, - interactiveSteps, symbExApps, - quantifierInstantiations, ossApps, - mergeRuleApps, totalRuleApps, - smtSolverApps, dependencyContractApps, - operationContractApps, - blockLoopContractApps, loopInvApps, - autoTime); + return new SideProofStatistics(sideProofs, nodes, branches, interactiveSteps, symbExApps, + quantifierInstantiations, ossApps, mergeRuleApps, totalRuleApps, smtSolverApps, + dependencyContractApps, operationContractApps, blockLoopContractApps, loopInvApps, + autoTime); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/init/StateVars.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/init/StateVars.java index 5198ce6b806..574d4921485 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/init/StateVars.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/proof/init/StateVars.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.proof.init; import java.util.Iterator; @@ -27,8 +30,9 @@ /** * Prepare program and location variables. *

    + * * @author christoph - *

    + *

    */ public class StateVars { @@ -51,13 +55,8 @@ public class StateVars { public final Term mbyAtPre; - public StateVars(Term self, - Term guard, - ImmutableList localVars, - Term result, - Term exception, - Term heap, - Term mbyAtPre) { + public StateVars(Term self, Term guard, ImmutableList localVars, Term result, + Term exception, Term heap, Term mbyAtPre) { this.self = self; this.guard = guard; this.localVars = localVars; @@ -66,8 +65,7 @@ public StateVars(Term self, this.heap = heap; this.mbyAtPre = mbyAtPre; - ImmutableList terms = - ImmutableSLList.nil(); + ImmutableList terms = ImmutableSLList.nil(); terms = appendIfNotNull(terms, heap); terms = appendIfNotNull(terms, self); terms = appendIfNotNull(terms, guard); @@ -77,8 +75,7 @@ public StateVars(Term self, terms = appendIfNotNull(terms, mbyAtPre); termList = terms; - ImmutableList allTerms = - ImmutableSLList.nil(); + ImmutableList allTerms = ImmutableSLList.nil(); allTerms = allTerms.append(heap); allTerms = allTerms.append(self); allTerms = allTerms.append(guard); @@ -90,18 +87,13 @@ public StateVars(Term self, } - public StateVars(Term self, - ImmutableList localVars, - Term result, - Term exception, - Term heap, - Term mbyAtPre) { + public StateVars(Term self, ImmutableList localVars, Term result, Term exception, + Term heap, Term mbyAtPre) { this(self, null, localVars, result, exception, heap, mbyAtPre); } - private ImmutableList appendIfNotNull(ImmutableList list, - Term t) { + private ImmutableList appendIfNotNull(ImmutableList list, Term t) { if (t != null) { return list.append(t); } else { @@ -111,7 +103,7 @@ private ImmutableList appendIfNotNull(ImmutableList list, private ImmutableList appendIfNotNull(ImmutableList list, - ImmutableList list2) { + ImmutableList list2) { ImmutableList result = list; for (Term t : list2) { result = appendIfNotNull(result, t); @@ -120,56 +112,41 @@ private ImmutableList appendIfNotNull(ImmutableList list, } - public StateVars(Term self, - Term guard, - ImmutableList localVars, - Term heap) { + public StateVars(Term self, Term guard, ImmutableList localVars, Term heap) { this(self, guard, localVars, null, null, heap, null); } - public StateVars(Term self, - Term guard, - ImmutableList localVars, - Term result, - Term exception, - Term heap) { + public StateVars(Term self, Term guard, ImmutableList localVars, Term result, + Term exception, Term heap) { this(self, guard, localVars, result, exception, heap, null); } - public StateVars(Term self, - ImmutableList localVars, - Term result, - Term exception, - Term heap) { + public StateVars(Term self, ImmutableList localVars, Term result, Term exception, + Term heap) { this(self, localVars, result, exception, heap, null); } - public StateVars(Term self, - ImmutableList localVars, - Term heap) { + public StateVars(Term self, ImmutableList localVars, Term heap) { this(self, localVars, null, null, heap); } - public StateVars(StateVars orig, - String postfix, - Services services) { + public StateVars(StateVars orig, String postfix, Services services) { this(copyVariable(orig.self, postfix, services), - copyVariable(orig.guard, postfix, services), - copyVariables(orig.localVars, postfix, services), - copyVariable(orig.result, postfix, services), - copyVariable(orig.exception, postfix, services), - copyHeapSymbol(orig.heap, postfix, services), - copyFunction(orig.mbyAtPre, postfix, services)); + copyVariable(orig.guard, postfix, services), + copyVariables(orig.localVars, postfix, services), + copyVariable(orig.result, postfix, services), + copyVariable(orig.exception, postfix, services), + copyHeapSymbol(orig.heap, postfix, services), + copyFunction(orig.mbyAtPre, postfix, services)); } - private static ImmutableList copyVariables(ImmutableList ts, - String postfix, - Services services) { + private static ImmutableList copyVariables(ImmutableList ts, String postfix, + Services services) { ImmutableList result = ImmutableSLList.nil(); for (Term t : ts) { result = result.append(copyVariable(t, postfix, services)); @@ -178,14 +155,12 @@ private static ImmutableList copyVariables(ImmutableList ts, } - private static Term copyVariable(Term t, - String postfix, - Services services) { + private static Term copyVariable(Term t, String postfix, Services services) { if (t != null) { final TermBuilder tb = services.getTermBuilder(); Term tWithoutLables = tb.unlabel(t); Term result = - newVariable(tWithoutLables, tWithoutLables.toString() + postfix, services); + newVariable(tWithoutLables, tWithoutLables.toString() + postfix, services); return tb.label(result, t.getLabels()); } else { return null; @@ -193,36 +168,30 @@ private static Term copyVariable(Term t, } - private static Term newVariable(Term t, - String name, - Services services) { + private static Term newVariable(Term t, String name, Services services) { if (t == null) { return null; } - assert t.op() instanceof ProgramVariable : "Expected a program " + - "variable."; + assert t.op() instanceof ProgramVariable : "Expected a program " + "variable."; final TermBuilder tb = services.getTermBuilder(); String newName = tb.newName(name); ProgramElementName pen = new ProgramElementName(newName); ProgramVariable progVar = (ProgramVariable) t.op(); LocationVariable newVar = new LocationVariable(pen, progVar.getKeYJavaType(), - progVar.getContainerType(), - progVar.isStatic(), progVar.isModel()); + progVar.getContainerType(), progVar.isStatic(), progVar.isModel()); register(newVar, services); return tb.var(newVar); } - private static Term copyHeapSymbol(Term t, - String postfix, - Services services) { + private static Term copyHeapSymbol(Term t, String postfix, Services services) { if (t != null) { final TermBuilder tb = services.getTermBuilder(); Term tWithoutLables = tb.unlabel(t); Term result = - newHeapSymbol(tWithoutLables, tWithoutLables.toString() + postfix, services); + newHeapSymbol(tWithoutLables, tWithoutLables.toString() + postfix, services); return tb.label(result, t.getLabels()); } else { return null; @@ -230,9 +199,7 @@ private static Term copyHeapSymbol(Term t, } - private static Term newHeapSymbol(Term t, - String name, - Services services) { + private static Term newHeapSymbol(Term t, String name, Services services) { if (t == null) { return null; } @@ -250,9 +217,7 @@ private static Term newHeapSymbol(Term t, } - private static Term newFunction(Term t, - String name, - Services services) { + private static Term newFunction(Term t, String name, Services services) { if (t == null) { return null; } @@ -263,14 +228,12 @@ private static Term newFunction(Term t, } - private static Term copyFunction(Term t, - String postfix, - Services services) { + private static Term copyFunction(Term t, String postfix, Services services) { if (t != null) { final TermBuilder tb = services.getTermBuilder(); Term tWithoutLables = tb.unlabel(t); Term result = - newFunction(tWithoutLables, tWithoutLables.toString() + postfix, services); + newFunction(tWithoutLables, tWithoutLables.toString() + postfix, services); return tb.label(result, t.getLabels()); } else { return null; @@ -278,68 +241,51 @@ private static Term copyFunction(Term t, } - public static StateVars buildMethodContractPreVars(IProgramMethod pm, - KeYJavaType kjt, - Services services) { + public static StateVars buildMethodContractPreVars(IProgramMethod pm, KeYJavaType kjt, + Services services) { ImmutableArray heapLabels = new ImmutableArray(ParameterlessTermLabel.ANON_HEAP_LABEL); - return new StateVars(buildSelfVar(services, pm, kjt, ""), - buildParamVars(services, "", pm), - buildResultVar(pm, services, ""), - buildExceptionVar(services, "", pm), - buildHeapFunc("AtPre", heapLabels, services), - buildMbyVar("", services)); + return new StateVars(buildSelfVar(services, pm, kjt, ""), buildParamVars(services, "", pm), + buildResultVar(pm, services, ""), buildExceptionVar(services, "", pm), + buildHeapFunc("AtPre", heapLabels, services), buildMbyVar("", services)); } - public static StateVars buildMethodContractPostVars(StateVars preVars, - IProgramMethod pm, - KeYJavaType kjt, - Services services) { + public static StateVars buildMethodContractPostVars(StateVars preVars, IProgramMethod pm, + KeYJavaType kjt, Services services) { final String postfix = "AtPost"; - return new StateVars(buildSelfVar(services, pm, kjt, postfix), - preVars.localVars, // no local out variables - buildResultVar(pm, services, postfix), - buildExceptionVar(services, postfix, pm), - buildHeapFunc(postfix, - new ImmutableArray(), - services), - preVars.mbyAtPre); + return new StateVars(buildSelfVar(services, pm, kjt, postfix), preVars.localVars, // no + // local + // out + // variables + buildResultVar(pm, services, postfix), buildExceptionVar(services, postfix, pm), + buildHeapFunc(postfix, new ImmutableArray(), services), + preVars.mbyAtPre); } - public static StateVars buildInfFlowPreVars(StateVars origPreVars, - String postfix, - Services services) { + public static StateVars buildInfFlowPreVars(StateVars origPreVars, String postfix, + Services services) { return new StateVars(origPreVars, postfix, services); } - public static StateVars buildInfFlowPostVars(StateVars origPreVars, - StateVars origPostVars, - StateVars preVars, - String postfix, - Services services) { + public static StateVars buildInfFlowPostVars(StateVars origPreVars, StateVars origPostVars, + StateVars preVars, String postfix, Services services) { // create new post vars if original pre and original post var differ; // else use pre var - Term self = (origPreVars.self == origPostVars.self) ? - preVars.self : - copyVariable(origPostVars.self, postfix, services); - Term guard = (origPreVars.guard == origPostVars.guard) ? - preVars.guard : - copyVariable(origPostVars.guard, postfix, services); - Term result = (origPreVars.result == origPostVars.result) ? - preVars.result : - copyVariable(origPostVars.result, postfix, services); - Term exception = (origPreVars.exception == origPostVars.exception) ? - preVars.exception : - copyVariable(origPostVars.exception, postfix, services); - Term heap = (origPreVars.heap == origPostVars.heap) ? - preVars.heap : - copyHeapSymbol(origPostVars.heap, postfix, services); - Term mbyAtPre = (origPreVars.mbyAtPre == origPostVars.mbyAtPre) ? - preVars.mbyAtPre : - copyVariable(origPostVars.mbyAtPre, postfix, services); + Term self = (origPreVars.self == origPostVars.self) ? preVars.self + : copyVariable(origPostVars.self, postfix, services); + Term guard = (origPreVars.guard == origPostVars.guard) ? preVars.guard + : copyVariable(origPostVars.guard, postfix, services); + Term result = (origPreVars.result == origPostVars.result) ? preVars.result + : copyVariable(origPostVars.result, postfix, services); + Term exception = (origPreVars.exception == origPostVars.exception) ? preVars.exception + : copyVariable(origPostVars.exception, postfix, services); + Term heap = (origPreVars.heap == origPostVars.heap) ? preVars.heap + : copyHeapSymbol(origPostVars.heap, postfix, services); + Term mbyAtPre = (origPreVars.mbyAtPre == origPostVars.mbyAtPre) ? preVars.mbyAtPre + : copyVariable(origPostVars.mbyAtPre, postfix, services); ImmutableList localPostVars = ImmutableSLList.nil(); Iterator origPreVarsIt = origPreVars.localVars.iterator(); @@ -347,25 +293,16 @@ public static StateVars buildInfFlowPostVars(StateVars origPreVars, for (Term origPostVar : origPostVars.localVars) { Term origPreVar = origPreVarsIt.next(); Term localPreVar = localPreVarsIt.next(); - Term localPostVar = (origPreVar == origPostVar) ? - localPreVar : - copyVariable(origPostVar, postfix, services); + Term localPostVar = (origPreVar == origPostVar) ? localPreVar + : copyVariable(origPostVar, postfix, services); localPostVars = localPostVars.append(localPostVar); } - return new StateVars(self, - guard, - localPostVars, - result, - exception, - heap, - mbyAtPre); + return new StateVars(self, guard, localPostVars, result, exception, heap, mbyAtPre); } - private static Term buildSelfVar(Services services, - IProgramMethod pm, - KeYJavaType kjt, - String postfix) { + private static Term buildSelfVar(Services services, IProgramMethod pm, KeYJavaType kjt, + String postfix) { if (pm.isStatic()) { return null; } @@ -376,42 +313,35 @@ private static Term buildSelfVar(Services services, } - private static ImmutableList buildParamVars(Services services, - String postfix, - IProgramMethod pm) { + private static ImmutableList buildParamVars(Services services, String postfix, + IProgramMethod pm) { final TermBuilder tb = services.getTermBuilder(); - ImmutableList paramVars = - tb.var(tb.paramVars(postfix, pm, true)); + ImmutableList paramVars = tb.var(tb.paramVars(postfix, pm, true)); register(ops(paramVars, ProgramVariable.class), services); return paramVars; } - private static Term buildResultVar(IProgramMethod pm, - Services services, - String postfix) { + private static Term buildResultVar(IProgramMethod pm, Services services, String postfix) { if (pm.isVoid() || pm.isConstructor()) { return null; } final TermBuilder tb = services.getTermBuilder(); - Term resultVar = - tb.var(tb.resultVar("result" + postfix, pm, true)); + Term resultVar = tb.var(tb.resultVar("result" + postfix, pm, true)); register(resultVar.op(ProgramVariable.class), services); return resultVar; } - private static Term buildHeapFunc(String postfix, - ImmutableArray labels, - Services services) { + private static Term buildHeapFunc(String postfix, ImmutableArray labels, + Services services) { HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); final TermBuilder tb = services.getTermBuilder(); if ("".equals(postfix)) { return tb.getBaseHeap(); } else { Name heapName = new Name("heap" + postfix); - Function heap = - new Function(heapName, heapLDT.getHeap().sort()); + Function heap = new Function(heapName, heapLDT.getHeap().sort()); Term heapFunc = tb.func(heap); register(heap, services); return tb.label(heapFunc, labels); @@ -419,9 +349,7 @@ private static Term buildHeapFunc(String postfix, } - private static Term buildExceptionVar(Services services, - String postfix, - IProgramMethod pm) { + private static Term buildExceptionVar(Services services, String postfix, IProgramMethod pm) { final TermBuilder tb = services.getTermBuilder(); Term excVar = tb.var(tb.excVar("exc" + postfix, pm, true)); register(excVar.op(ProgramVariable.class), services); @@ -429,21 +357,17 @@ private static Term buildExceptionVar(Services services, } - private static Term buildMbyVar(String postfix, - Services services) { + private static Term buildMbyVar(String postfix, Services services) { final TermBuilder tb = services.getTermBuilder(); - final Sort intSort = - services.getTypeConverter().getIntegerLDT().targetSort(); + final Sort intSort = services.getTypeConverter().getIntegerLDT().targetSort(); String newName = tb.newName("mbyAtPre" + postfix); - final Function mbyAtPreFunc = - new Function(new Name(newName), intSort); + final Function mbyAtPreFunc = new Function(new Name(newName), intSort); register(mbyAtPreFunc, services); return tb.func(mbyAtPreFunc); } - static void register(ProgramVariable pv, - Services services) { + static void register(ProgramVariable pv, Services services) { Namespace progVarNames = services.getNamespaces().programVariables(); if (pv != null && progVarNames.lookup(pv.name()) == null) { progVarNames.addSafely(pv); @@ -451,16 +375,14 @@ static void register(ProgramVariable pv, } - static void register(ImmutableList pvs, - Services services) { + static void register(ImmutableList pvs, Services services) { for (ProgramVariable pv : pvs) { register(pv, services); } } - static void register(Function f, - Services services) { + static void register(Function f, Services services) { Namespace functionNames = services.getNamespaces().functions(); if (f != null && functionNames.lookup(f.name()) == null) { assert f.sort() != Sort.UPDATE; @@ -473,8 +395,7 @@ static void register(Function f, } - static ImmutableList ops(ImmutableList terms, - Class opClass) + static ImmutableList ops(ImmutableList terms, Class opClass) throws IllegalArgumentException { ImmutableList ops = ImmutableSLList.nil(); for (Term t : terms) { @@ -488,4 +409,4 @@ static ImmutableList ops(ImmutableList terms, public String toString() { return termList.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/InfFlowContractAppTaclet.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/InfFlowContractAppTaclet.java index 39927739d9b..0c23e44652b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/InfFlowContractAppTaclet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/InfFlowContractAppTaclet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule; import org.key_project.util.collection.DefaultImmutableSet; @@ -21,13 +24,12 @@ /** - * A normal RewriteTaclet except that the formula which is added by this taclet - * is also added to the list of formulas contained in the - * INF_FLOW_CONTRACT_APPL_PROPERTY. The INF_FLOW_CONTRACT_APPL_PROPERTY is used - * by the macros UseInformationFlowContractMacro and - * PrepareInfFlowContractPreBranchesMacro to decide how to prepare the formulas - * resulting from information flow contract applications. - * + * A normal RewriteTaclet except that the formula which is added by this taclet is also added to the + * list of formulas contained in the INF_FLOW_CONTRACT_APPL_PROPERTY. The + * INF_FLOW_CONTRACT_APPL_PROPERTY is used by the macros UseInformationFlowContractMacro and + * PrepareInfFlowContractPreBranchesMacro to decide how to prepare the formulas resulting from + * information flow contract applications. + * * @author christoph */ public class InfFlowContractAppTaclet extends RewriteTaclet { @@ -35,7 +37,7 @@ public class InfFlowContractAppTaclet extends RewriteTaclet { public static final String USE_IF = "Use information flow contract for "; private static ImmutableSet alreadyRegistered = DefaultImmutableSet.nil(); - + public static boolean hasType(Rule rule) { return rule != null && rule.name().toString().startsWith(USE_IF); @@ -61,50 +63,40 @@ public static boolean unregister(Name name) { } - public InfFlowContractAppTaclet(Name name, - TacletApplPart applPart, - ImmutableList goalTemplates, - ImmutableList ruleSets, - TacletAttributes attrs, - Term find, - ImmutableMap prefixMap, - int p_applicationRestriction, - ImmutableSet choices, - ImmutableSet tacletAnnotations) { - super(name, applPart, goalTemplates, ruleSets, attrs, find, prefixMap, p_applicationRestriction, choices, tacletAnnotations); + public InfFlowContractAppTaclet(Name name, TacletApplPart applPart, + ImmutableList goalTemplates, ImmutableList ruleSets, + TacletAttributes attrs, Term find, ImmutableMap prefixMap, + int p_applicationRestriction, ImmutableSet choices, + ImmutableSet tacletAnnotations) { + super(name, applPart, goalTemplates, ruleSets, attrs, find, prefixMap, + p_applicationRestriction, choices, tacletAnnotations); } - public InfFlowContractAppTaclet(Name name, - TacletApplPart applPart, - ImmutableList goalTemplates, - ImmutableList ruleSets, - TacletAttributes attrs, - Term find, - ImmutableMap prefixMap, - int p_applicationRestriction, - ImmutableSet choices, - boolean surviveSymbExec, - ImmutableSet tacletAnnotations) { - super(name, applPart, goalTemplates, ruleSets, attrs, find, prefixMap, p_applicationRestriction, choices, surviveSymbExec, tacletAnnotations); + public InfFlowContractAppTaclet(Name name, TacletApplPart applPart, + ImmutableList goalTemplates, ImmutableList ruleSets, + TacletAttributes attrs, Term find, ImmutableMap prefixMap, + int p_applicationRestriction, ImmutableSet choices, boolean surviveSymbExec, + ImmutableSet tacletAnnotations) { + super(name, applPart, goalTemplates, ruleSets, attrs, find, prefixMap, + p_applicationRestriction, choices, surviveSymbExec, tacletAnnotations); } @Override protected void createAndInitializeExecutor() { executor = new InfFlowContractAppTacletExecutor(this); } - + @Override - public InfFlowContractAppTaclet setName(String s) { - final TacletApplPart applPart = - new TacletApplPart(ifSequent(), varsNew(), varsNotFreeIn(), + public InfFlowContractAppTaclet setName(String s) { + final TacletApplPart applPart = new TacletApplPart(ifSequent(), varsNew(), varsNotFreeIn(), varsNewDependingOn(), getVariableConditions()); final TacletAttributes attrs = new TacletAttributes(); attrs.setDisplayName(displayName()); - - return new InfFlowContractAppTaclet(new Name(s), - applPart, goalTemplates(), getRuleSets(), attrs, find, prefixMap, - getApplicationRestriction(), choices, getSurviveSymbExec(), tacletAnnotations); + + return new InfFlowContractAppTaclet(new Name(s), applPart, goalTemplates(), getRuleSets(), + attrs, find, prefixMap, getApplicationRestriction(), choices, getSurviveSymbExec(), + tacletAnnotations); } - + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/executor/InfFlowContractAppTacletExecutor.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/executor/InfFlowContractAppTacletExecutor.java index 8f65757149b..aa633e31bfc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/executor/InfFlowContractAppTacletExecutor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/executor/InfFlowContractAppTacletExecutor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.executor; import org.key_project.util.collection.ImmutableList; @@ -19,56 +22,49 @@ import de.uka.ilkd.key.rule.executor.javadl.RewriteTacletExecutor; import de.uka.ilkd.key.util.properties.Properties; -public class InfFlowContractAppTacletExecutor extends RewriteTacletExecutor { +public class InfFlowContractAppTacletExecutor + extends RewriteTacletExecutor { /** - * Strategy property which saves the list of formulas which where added - * by information flow contract applications. This list is used by the - * macros UseInformationFlowContractMacro and - * PrepareInfFlowContractPreBranchesMacro to decide how to prepare the - * formulas resulting from information flow contract applications. + * Strategy property which saves the list of formulas which where added by information flow + * contract applications. This list is used by the macros UseInformationFlowContractMacro and + * PrepareInfFlowContractPreBranchesMacro to decide how to prepare the formulas resulting from + * information flow contract applications. */ @SuppressWarnings("unchecked") public static final Properties.Property> INF_FLOW_CONTRACT_APPL_PROPERTY = new Properties.Property>( (Class>) (Class) ImmutableList.class, - "information flow contract applicaton property"); + "information flow contract applicaton property"); + - public InfFlowContractAppTacletExecutor(InfFlowContractAppTaclet taclet) { super(taclet); } @Override - protected void addToAntec(Semisequent semi, - TermLabelState termLabelState, - TacletLabelHint labelHint, - SequentChangeInfo currentSequent, - PosInOccurrence pos, - PosInOccurrence applicationPosInOccurrence, - MatchConditions matchCond, - Goal goal, - RuleApp tacletApp, - Services services) { - final ImmutableList replacements = - instantiateSemisequent(semi, termLabelState, labelHint, pos, matchCond, goal, tacletApp, services); - assert replacements.size() == 1 : "information flow taclets must have " + - "exactly one add!"; + protected void addToAntec(Semisequent semi, TermLabelState termLabelState, + TacletLabelHint labelHint, SequentChangeInfo currentSequent, PosInOccurrence pos, + PosInOccurrence applicationPosInOccurrence, MatchConditions matchCond, Goal goal, + RuleApp tacletApp, Services services) { + final ImmutableList replacements = instantiateSemisequent(semi, + termLabelState, labelHint, pos, matchCond, goal, tacletApp, services); + assert replacements.size() == 1 + : "information flow taclets must have " + "exactly one add!"; updateStrategyInfo(services.getProof().openEnabledGoals().head(), replacements.iterator().next().formula()); - super.addToAntec(semi, termLabelState, labelHint, currentSequent, pos, applicationPosInOccurrence, matchCond, goal, tacletApp, services); + super.addToAntec(semi, termLabelState, labelHint, currentSequent, pos, + applicationPosInOccurrence, matchCond, goal, tacletApp, services); } /** - * Add the contract application formula to the list of the - * INF_FLOW_CONTRACT_APPL_PROPERTY. - * @param goal the current goal - * @param applFormula the information contract application formula added - * by this taclet + * Add the contract application formula to the list of the INF_FLOW_CONTRACT_APPL_PROPERTY. + * + * @param goal the current goal + * @param applFormula the information contract application formula added by this taclet */ private void updateStrategyInfo(Goal goal, final Term applFormula) { - ImmutableList applFormulas = - goal.getStrategyInfo(INF_FLOW_CONTRACT_APPL_PROPERTY); + ImmutableList applFormulas = goal.getStrategyInfo(INF_FLOW_CONTRACT_APPL_PROPERTY); if (applFormulas == null) { applFormulas = ImmutableSLList.nil(); } @@ -79,7 +75,8 @@ private void updateStrategyInfo(Goal goal, final Term applFormula) { public void undo(Properties strategyInfos) { ImmutableList applFormulas = strategyInfos.get(INF_FLOW_CONTRACT_APPL_PROPERTY); - strategyInfos.put(INF_FLOW_CONTRACT_APPL_PROPERTY, applFormulas.removeAll(applFormula)); + strategyInfos.put(INF_FLOW_CONTRACT_APPL_PROPERTY, + applFormulas.removeAll(applFormula)); } }; goal.addStrategyInfo(INF_FLOW_CONTRACT_APPL_PROPERTY, applFormulas, undo); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowContractAppTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowContractAppTacletBuilder.java index 9f53e9c37bf..2180ff55912 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowContractAppTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowContractAppTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import java.util.Iterator; @@ -87,13 +90,13 @@ private static Name makeUnique(Name name, Goal goal) { } /** - * Returns a string which uniquely identifies the smallest branch of the proof - * tree containing the specified node, i.e., a string which encodes branching on - * the path from the root to the specified node. + * Returns a string which uniquely identifies the smallest branch of the proof tree containing + * the specified node, i.e., a string which encodes branching on the path from the root to the + * specified node. * * @param node a node. - * @return a string which uniquely identifies the smallest branch of the proof - * tree containing the specified node. + * @return a string which uniquely identifies the smallest branch of the proof tree containing + * the specified node. */ private static String getBranchUID(Node node) { final int base = Character.MAX_RADIX; @@ -166,9 +169,8 @@ private static String getBranchUID(Node node) { * @param services the services object * @return the proof obligation variables */ - ProofObligationVars generateApplicationDataSVs(String schemaPrefix, - ProofObligationVars appData, - Services services) { + ProofObligationVars generateApplicationDataSVs(String schemaPrefix, ProofObligationVars appData, + Services services) { // generate a new schema variable for any pre variable Term selfAtPreSV = createTermSV(appData.pre.self, schemaPrefix, services); ImmutableList localVarsAtPreSVs = @@ -225,13 +227,13 @@ private Taclet genInfFlowContractApplTaclet(Goal goal, ProofObligationVars appDa // generate schemaFind and schemaAssumes terms ProofObligationVars schemaDataFind = generateApplicationDataSVs("find_", appData, services); Term schemaFind = generateSchemaFind(schemaDataFind, services); - ProofObligationVars schemaDataAssumes = generateApplicationDataSVs("assumes_", appData, - services); + ProofObligationVars schemaDataAssumes = + generateApplicationDataSVs("assumes_", appData, services); Term schemaAssumes = generateSchemaAssumes(schemaDataAssumes, services); // generate post term - Term replaceWithTerm = buildContractApplications(schemaDataFind, schemaDataAssumes, - services); + Term replaceWithTerm = + buildContractApplications(schemaDataFind, schemaDataAssumes, services); // collect quantifiable variables of the post term and replace them // by schema variables @@ -247,10 +249,10 @@ private Taclet genInfFlowContractApplTaclet(Goal goal, ProofObligationVars appDa replaceWithTerm = or.replace(replaceWithTerm); // create sequents - Sequent assumesSeq = Sequent - .createAnteSequent(new Semisequent(new SequentFormula(schemaAssumes))); - Sequent replaceWithSeq = Sequent - .createAnteSequent(new Semisequent(new SequentFormula(replaceWithTerm))); + Sequent assumesSeq = + Sequent.createAnteSequent(new Semisequent(new SequentFormula(schemaAssumes))); + Sequent replaceWithSeq = + Sequent.createAnteSequent(new Semisequent(new SequentFormula(replaceWithTerm))); // create taclet InfFlowContractAppRewriteTacletBuilder tacletBuilder = @@ -272,20 +274,17 @@ abstract Term buildContractApplications(ProofObligationVars contAppData, ProofObligationVars contAppData2, Services services); /** - * A normal RewriteTacletBuilder except that an InfFlowContractAppTaclet is - * returned instead of a normal RewriteTaclet. InfFlowContractAppTaclet's are - * normal RewriteTaclet's except that the formula which is added by the taclets - * are also added to the list of formulas contained in the - * INF_FLOW_CONTRACT_APPL_PROPERTY. The INF_FLOW_CONTRACT_APPL_PROPERTY is used - * by the macros UseInformationFlowContractMacro and - * PrepareInfFlowContractPreBranchesMacro to decide how to prepare the formulas - * resulting from information flow contract applications. + * A normal RewriteTacletBuilder except that an InfFlowContractAppTaclet is returned instead of + * a normal RewriteTaclet. InfFlowContractAppTaclet's are normal RewriteTaclet's except that the + * formula which is added by the taclets are also added to the list of formulas contained in the + * INF_FLOW_CONTRACT_APPL_PROPERTY. The INF_FLOW_CONTRACT_APPL_PROPERTY is used by the macros + * UseInformationFlowContractMacro and PrepareInfFlowContractPreBranchesMacro to decide how to + * prepare the formulas resulting from information flow contract applications. */ private class InfFlowContractAppRewriteTacletBuilder extends RewriteTacletBuilder { - InfFlowContractAppRewriteTacletBuilder() { - } + InfFlowContractAppRewriteTacletBuilder() {} @Override public InfFlowContractAppTaclet getRewriteTaclet() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowTacletBuilder.java index 58eb8ec4c7d..2573d1e93d5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import java.util.LinkedHashMap; @@ -29,6 +32,7 @@ /** * Builds the rule which inserts information flow contract applications. *

    + * * @author christoph */ abstract class AbstractInfFlowTacletBuilder extends TermBuilder { @@ -48,9 +52,8 @@ public AbstractInfFlowTacletBuilder(final Services services) { } - ImmutableList createTermSV(ImmutableList ts, - String schemaPrefix, - Services services) { + ImmutableList createTermSV(ImmutableList ts, String schemaPrefix, + Services services) { ImmutableList result = ImmutableSLList.nil(); for (Term t : ts) { result = result.append(createTermSV(t, schemaPrefix, services)); @@ -59,41 +62,33 @@ ImmutableList createTermSV(ImmutableList ts, } - Term createTermSV(Term t, - String schemaPrefix, - Services services) { + Term createTermSV(Term t, String schemaPrefix, Services services) { if (t == null) { return null; } t = unlabel(t); - String svName = MiscTools.toValidVariableName(schemaPrefix + - t.toString()).toString(); + String svName = MiscTools.toValidVariableName(schemaPrefix + t.toString()).toString(); Sort sort = t.sort(); - Name name = - services.getVariableNamer().getTemporaryNameProposal(svName); + Name name = services.getVariableNamer().getTemporaryNameProposal(svName); return var(SchemaVariableFactory.createTermSV(name, sort)); } - SchemaVariable createVariableSV(QuantifiableVariable v, - String schemaPrefix, - Services services) { + SchemaVariable createVariableSV(QuantifiableVariable v, String schemaPrefix, + Services services) { if (v == null) { return null; } - String svName = - MiscTools.toValidVariableName(schemaPrefix + v.name()).toString(); + String svName = MiscTools.toValidVariableName(schemaPrefix + v.name()).toString(); Sort sort = v.sort(); - Name name = - services.getVariableNamer().getTemporaryNameProposal(svName); + Name name = services.getVariableNamer().getTemporaryNameProposal(svName); return SchemaVariableFactory.createVariableSV(name, sort); } void addVarconds(RewriteTacletBuilder tacletBuilder, - Iterable quantifiableSVs) - throws IllegalArgumentException { + Iterable quantifiableSVs) throws IllegalArgumentException { RewriteTacletBuilderSchemaVarCollector svCollector = new RewriteTacletBuilderSchemaVarCollector(tacletBuilder); Set schemaVars = svCollector.collectSchemaVariables(); @@ -108,12 +103,10 @@ void addVarconds(RewriteTacletBuilder tacletBuilder, Map collectQuantifiableVariables(Term replaceWithTerm, - Services services) { - QuantifiableVariableVisitor qvVisitor = - new QuantifiableVariableVisitor(); + Services services) { + QuantifiableVariableVisitor qvVisitor = new QuantifiableVariableVisitor(); replaceWithTerm.execPreOrder(qvVisitor); - LinkedList quantifiableVariables = - qvVisitor.getResult(); + LinkedList quantifiableVariables = qvVisitor.getResult(); final Map quantifiableVarsToSchemaVars = new LinkedHashMap(); for (QuantifiableVariable qv : quantifiableVariables) { @@ -128,6 +121,7 @@ Map collectQuantifiableVariables(Term repl /** * Get eqAtLocs function as a term. + * * @param services the Services object. * @param heap1 the first heap term. * @param locset1 the first location set term. @@ -135,16 +129,15 @@ Map collectQuantifiableVariables(Term repl * @param locset2 the first location set term. * @return The eqAtLocs function term. */ - public Term eqAtLocs(Services services, Term heap1, Term locset1, - Term heap2, Term locset2) { + public Term eqAtLocs(Services services, Term heap1, Term locset1, Term heap2, Term locset2) { return (locset1.equals(empty()) && locset2.equals(empty())) ? tt() - : func((Function) services.getNamespaces().functions() - .lookup(EQUAL_LOCS), - heap1, locset1, heap2, locset2); + : func((Function) services.getNamespaces().functions().lookup(EQUAL_LOCS), heap1, + locset1, heap2, locset2); } /** * Get eqAtLocsPost function as a term. + * * @param services the Services object. * @param heap1Pre the first pre-heap term. * @param heap1Post the first post-heap term. @@ -154,14 +147,11 @@ public Term eqAtLocs(Services services, Term heap1, Term locset1, * @param locset2 the second location set term. * @return The eqAtLocsPost function term. */ - public Term eqAtLocsPost(Services services, - Term heap1Pre, Term heap1Post, Term locset1, - Term heap2Pre, Term heap2Post, Term locset2) { + public Term eqAtLocsPost(Services services, Term heap1Pre, Term heap1Post, Term locset1, + Term heap2Pre, Term heap2Post, Term locset2) { return (locset1.equals(empty()) && locset2.equals(empty())) ? tt() - : func((Function) services.getNamespaces().functions() - .lookup(EQUAL_LOCS_POST), - heap1Pre, heap1Post, locset1, heap2Pre, heap2Post, - locset2); + : func((Function) services.getNamespaces().functions().lookup(EQUAL_LOCS_POST), + heap1Pre, heap1Post, locset1, heap2Pre, heap2Post, locset2); } class QuantifiableVariableVisitor implements Visitor { @@ -175,8 +165,7 @@ public boolean visitSubtree(Term visited) { @Override public void visit(Term visited) { - final ImmutableArray boundVars = - visited.boundVars(); + final ImmutableArray boundVars = visited.boundVars(); for (QuantifiableVariable var : boundVars) { vars.add(var); } @@ -199,4 +188,4 @@ public LinkedList getResult() { return vars; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowUnfoldTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowUnfoldTacletBuilder.java index 6bfec8a3314..0a155f3c831 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowUnfoldTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/AbstractInfFlowUnfoldTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import java.util.Iterator; @@ -29,6 +32,7 @@ /** * Builds the rule which inserts information flow contract applications. *

    + * * @author christoph */ abstract class AbstractInfFlowUnfoldTacletBuilder extends AbstractInfFlowTacletBuilder { @@ -64,8 +68,7 @@ public Taclet buildTaclet() { unfoldCounter++; // create schema vars - IFProofObligationVars schemaVars = - generateApplicationDataSVs(ifVars, services); + IFProofObligationVars schemaVars = generateApplicationDataSVs(ifVars, services); // create find term and replace information flow variables by // schema variables @@ -81,19 +84,19 @@ public Taclet buildTaclet() { // and replace all quantifiable variables by schema variables Map quantifiableVarsToSchemaVars = collectQuantifiableVariables(schemaFind, services); - quantifiableVarsToSchemaVars.putAll( - collectQuantifiableVariables(schemaReplaceWith, services)); - final OpReplacer or = new OpReplacer(quantifiableVarsToSchemaVars, tf()); - schemaFind = or.replace(schemaFind); - schemaReplaceWith = or.replace(schemaReplaceWith); - - //create taclet - final RewriteTacletBuilder tacletBuilder = new RewriteTacletBuilder(); + quantifiableVarsToSchemaVars + .putAll(collectQuantifiableVariables(schemaReplaceWith, services)); + final OpReplacer or = new OpReplacer(quantifiableVarsToSchemaVars, tf()); + schemaFind = or.replace(schemaFind); + schemaReplaceWith = or.replace(schemaReplaceWith); + + // create taclet + final RewriteTacletBuilder tacletBuilder = + new RewriteTacletBuilder(); tacletBuilder.setName(tacletName); tacletBuilder.setFind(schemaFind); tacletBuilder.setApplicationRestriction(RewriteTaclet.ANTECEDENT_POLARITY); - final RewriteTacletGoalTemplate goal = - new RewriteTacletGoalTemplate(schemaReplaceWith); + final RewriteTacletGoalTemplate goal = new RewriteTacletGoalTemplate(schemaReplaceWith); tacletBuilder.addTacletGoalTemplate(goal); tacletBuilder.addRuleSet(new RuleSet(new Name("concrete"))); tacletBuilder.setSurviveSmbExec(true); @@ -103,8 +106,7 @@ public Taclet buildTaclet() { } - private IFProofObligationVars generateApplicationDataSVs( - IFProofObligationVars ifVars, + private IFProofObligationVars generateApplicationDataSVs(IFProofObligationVars ifVars, Services services) { return new IFProofObligationVars( generateApplicationDataSVs(SCHEMA_PREFIX, ifVars.c1, services), @@ -114,30 +116,24 @@ private IFProofObligationVars generateApplicationDataSVs( private ProofObligationVars generateApplicationDataSVs(String schemaPrefix, - ProofObligationVars poVars, - Services services) { + ProofObligationVars poVars, Services services) { Function n = services.getTypeConverter().getHeapLDT().getNull(); // generate a new schema variable for any pre variable - Term selfAtPreSV = - createTermSV(poVars.pre.self, schemaPrefix, services); + Term selfAtPreSV = createTermSV(poVars.pre.self, schemaPrefix, services); ImmutableList localVarsAtPreSVs = createTermSV(poVars.pre.localVars, schemaPrefix, services); - Term guardAtPreSV = - createTermSV(poVars.pre.guard, schemaPrefix, services); + Term guardAtPreSV = createTermSV(poVars.pre.guard, schemaPrefix, services); Term resAtPreSV = null; Term excAtPreSV = null; - Term heapAtPreSV = - createTermSV(poVars.pre.heap, schemaPrefix, services); - Term mbyAtPreSV = - createTermSV(poVars.pre.mbyAtPre, schemaPrefix, services); + Term heapAtPreSV = createTermSV(poVars.pre.heap, schemaPrefix, services); + Term mbyAtPreSV = createTermSV(poVars.pre.mbyAtPre, schemaPrefix, services); // generate a new schema variable only for those post variables // which do not equal the corresponding pre variable; else use // the pre schema variable - Term selfAtPostSV = (poVars.pre.self == poVars.post.self ? - selfAtPreSV : - createTermSV(poVars.post.self, schemaPrefix, services)); + Term selfAtPostSV = (poVars.pre.self == poVars.post.self ? selfAtPreSV + : createTermSV(poVars.post.self, schemaPrefix, services)); ImmutableList localVarsAtPostSVs = ImmutableSLList.nil(); Iterator appDataPreLocalVarsIt = poVars.pre.localVars.iterator(); @@ -148,66 +144,51 @@ private ProofObligationVars generateApplicationDataSVs(String schemaPrefix, if (appDataPostLocalVar == appDataPreLocalVar) { localVarsAtPostSVs = localVarsAtPostSVs.append(localPreVar); } else { - localVarsAtPostSVs = - localVarsAtPostSVs.append(createTermSV(appDataPostLocalVar, - schemaPrefix, - services)); + localVarsAtPostSVs = localVarsAtPostSVs + .append(createTermSV(appDataPostLocalVar, schemaPrefix, services)); } } - Term guardAtPostSV = (poVars.pre.guard == poVars.post.guard) ? - guardAtPreSV : - createTermSV(poVars.post.guard, schemaPrefix, services); - Term resAtPostSV = (poVars.post.result == null || - poVars.post.result.op().equals(n)) ? - null : - createTermSV(poVars.post.result, schemaPrefix, services); - Term excAtPostSV = (poVars.post.exception == null || - poVars.post.exception.op().equals(n)) ? - null : - createTermSV(poVars.post.exception, schemaPrefix, services); - Term heapAtPostSV = (poVars.pre.heap == poVars.post.heap ? - heapAtPreSV : - createTermSV(poVars.post.heap, schemaPrefix, services)); + Term guardAtPostSV = (poVars.pre.guard == poVars.post.guard) ? guardAtPreSV + : createTermSV(poVars.post.guard, schemaPrefix, services); + Term resAtPostSV = (poVars.post.result == null || poVars.post.result.op().equals(n)) ? null + : createTermSV(poVars.post.result, schemaPrefix, services); + Term excAtPostSV = + (poVars.post.exception == null || poVars.post.exception.op().equals(n)) ? null + : createTermSV(poVars.post.exception, schemaPrefix, services); + Term heapAtPostSV = (poVars.pre.heap == poVars.post.heap ? heapAtPreSV + : createTermSV(poVars.post.heap, schemaPrefix, services)); // build state variable container for pre and post state - StateVars pre = - new StateVars(selfAtPreSV, guardAtPreSV, localVarsAtPreSVs, resAtPreSV, - excAtPreSV, heapAtPreSV, mbyAtPreSV); + StateVars pre = new StateVars(selfAtPreSV, guardAtPreSV, localVarsAtPreSVs, resAtPreSV, + excAtPreSV, heapAtPreSV, mbyAtPreSV); pre = filterSchemaVars(poVars.pre, pre); - StateVars post = - new StateVars(selfAtPostSV, guardAtPostSV, localVarsAtPostSVs, resAtPostSV, - excAtPostSV, heapAtPostSV, null); + StateVars post = new StateVars(selfAtPostSV, guardAtPostSV, localVarsAtPostSVs, resAtPostSV, + excAtPostSV, heapAtPostSV, null); post = filterSchemaVars(poVars.post, post); // return proof obligation schema variables - return new ProofObligationVars(pre, post, poVars.exceptionParameter, - poVars.formalParams, services); + return new ProofObligationVars(pre, post, poVars.exceptionParameter, poVars.formalParams, + services); } - private static Term replace(Term term, - IFProofObligationVars origVars, - IFProofObligationVars schemaVars, - Services services) { + private static Term replace(Term term, IFProofObligationVars origVars, + IFProofObligationVars schemaVars, Services services) { Term intermediateResult = replace(term, origVars.c1, schemaVars.c1, services); return replace(intermediateResult, origVars.c2, schemaVars.c2, services); } - private static Term replace(Term term, - ProofObligationVars origVars, - ProofObligationVars schemaVars, - Services services) { + private static Term replace(Term term, ProofObligationVars origVars, + ProofObligationVars schemaVars, Services services) { Term intermediateResult = replace(term, origVars.pre, schemaVars.pre, services); return replace(intermediateResult, origVars.post, schemaVars.post, services); } - private static Term replace(Term term, - StateVars origVars, - StateVars schemaVars, - Services services) { + private static Term replace(Term term, StateVars origVars, StateVars schemaVars, + Services services) { LinkedHashMap map = new LinkedHashMap(); Pair vars = filter(origVars, schemaVars); @@ -220,12 +201,11 @@ private static Term replace(Term term, Term origTerm = origVarsIt.next(); Term svTerm = schemaVarsIt.next(); if (origTerm != null && svTerm != null) { - assert svTerm.sort().equals(origTerm.sort()) || - svTerm.sort().extendsSorts().contains(origTerm.sort()) : - "mismatch of sorts: orignal term " + origTerm + - ", sort " + origTerm.sort() + - "; replacement term" + svTerm + ", sort " + - svTerm.sort(); + assert svTerm.sort().equals(origTerm.sort()) + || svTerm.sort().extendsSorts().contains(origTerm.sort()) + : "mismatch of sorts: orignal term " + origTerm + ", sort " + + origTerm.sort() + "; replacement term" + svTerm + ", sort " + + svTerm.sort(); map.put(origTerm, svTerm); } } @@ -237,16 +217,14 @@ private static Term replace(Term term, } - private static Pair filter(StateVars origVars, - StateVars schemaVars) { + private static Pair filter(StateVars origVars, StateVars schemaVars) { schemaVars = filterSchemaVars(origVars, schemaVars); origVars = filterSchemaVars(schemaVars, origVars); return new Pair(origVars, schemaVars); } - private static StateVars filterSchemaVars(StateVars origVars, - StateVars schemaVars) { + private static StateVars filterSchemaVars(StateVars origVars, StateVars schemaVars) { if (origVars.termList.size() == schemaVars.termList.size()) { return schemaVars; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/BlockInfFlowUnfoldTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/BlockInfFlowUnfoldTacletBuilder.java index 667111ee59f..e5aa1907881 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/BlockInfFlowUnfoldTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/BlockInfFlowUnfoldTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import de.uka.ilkd.key.informationflow.po.IFProofObligationVars; @@ -38,18 +41,15 @@ public void setExecutionContext(ExecutionContext context) { @Override Name getTacletName() { - return MiscTools.toValidTacletName(UNFOLD + unfoldCounter + " of " + - contract.getUniqueName()); + return MiscTools + .toValidTacletName(UNFOLD + unfoldCounter + " of " + contract.getUniqueName()); } @Override Term createFindTerm(IFProofObligationVars ifVars) { - InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(contract, - ifVars.c1, ifVars.c2, - executionContext, - services); + InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(contract, ifVars.c1, + ifVars.c2, executionContext, services); return f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_BLOCK_WITH_PRE_RELATION); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowBlockContractTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowBlockContractTacletBuilder.java index 5bec8137aa5..2743830922b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowBlockContractTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowBlockContractTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import org.key_project.util.collection.DefaultImmutableSet; @@ -48,51 +51,41 @@ Name generateName() { } @Override - Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, - Services services) { - BasicPOSnippetFactory fAssumes = - POSnippetFactory.getBasicFactory(blockContract, schemaDataAssumes, - executionContext, services); + Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, Services services) { + BasicPOSnippetFactory fAssumes = POSnippetFactory.getBasicFactory(blockContract, + schemaDataAssumes, executionContext, services); return fAssumes.create(BasicPOSnippetFactory.Snippet.BLOCK_CALL_RELATION); } @Override - Term generateSchemaFind(ProofObligationVars schemaDataFind, - Services services) { - BasicPOSnippetFactory fFind = - POSnippetFactory.getBasicFactory(blockContract, schemaDataFind, - executionContext, services); + Term generateSchemaFind(ProofObligationVars schemaDataFind, Services services) { + BasicPOSnippetFactory fFind = POSnippetFactory.getBasicFactory(blockContract, + schemaDataFind, executionContext, services); return fFind.create(BasicPOSnippetFactory.Snippet.BLOCK_CALL_RELATION); } @Override Term getContractApplPred(ProofObligationVars appData) { - BasicPOSnippetFactory f = - POSnippetFactory.getBasicFactory(blockContract, appData, - executionContext, services); + BasicPOSnippetFactory f = POSnippetFactory.getBasicFactory(blockContract, appData, + executionContext, services); return f.create(BasicPOSnippetFactory.Snippet.BLOCK_CALL_RELATION); } @Override Term buildContractApplications(ProofObligationVars contAppData, - ProofObligationVars contAppData2, - Services services) { + ProofObligationVars contAppData2, Services services) { ImmutableSet ifContracts = services.getSpecificationRepository().getBlockContracts(blockContract.getBlock()); ifContracts = filterContracts(ifContracts); ImmutableList contractsApplications = ImmutableSLList.nil(); for (BlockContract cont : ifContracts) { - InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(cont, contAppData, - contAppData2, - executionContext, - services); - contractsApplications = - contractsApplications.append( - f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APPL)); + InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(cont, contAppData, + contAppData2, executionContext, services); + contractsApplications = contractsApplications + .append(f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APPL)); } return and(contractsApplications); @@ -102,13 +95,13 @@ Term buildContractApplications(ProofObligationVars contAppData, ImmutableSet filterContracts(ImmutableSet ifContracts) { ImmutableSet result = DefaultImmutableSet.nil(); for (BlockContract cont : ifContracts) { - if ((cont.getBlock().getStartPosition().getLine() == - blockContract.getBlock().getStartPosition().getLine()) && - cont.getTarget().getUniqueName() - .equalsIgnoreCase(blockContract.getTarget().getUniqueName())) { + if ((cont.getBlock().getStartPosition().getLine() == blockContract.getBlock() + .getStartPosition().getLine()) + && cont.getTarget().getUniqueName() + .equalsIgnoreCase(blockContract.getTarget().getUniqueName())) { result = result.add(cont); } } return result; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowLoopInvariantTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowLoopInvariantTacletBuilder.java index ca91ca54f58..1232ecde6cc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowLoopInvariantTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowLoopInvariantTacletBuilder.java @@ -1,4 +1,6 @@ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import de.uka.ilkd.key.informationflow.po.snippet.BasicPOSnippetFactory; @@ -18,15 +20,15 @@ */ public final class InfFlowLoopInvariantTacletBuilder extends AbstractInfFlowContractAppTacletBuilder { - - private LoopSpecification loopinvariant; + + private LoopSpecification loopinvariant; private ExecutionContext executionContext; private Term guard; public InfFlowLoopInvariantTacletBuilder(final Services services) { super(services); } - + public void setInvariant(LoopSpecification invariant) { this.loopinvariant = invariant; } @@ -48,56 +50,38 @@ Name generateName() { } @Override - Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, - Services services) { - BasicPOSnippetFactory fAssumes = - POSnippetFactory.getBasicFactory(loopinvariant, - schemaDataAssumes, - executionContext, - guard, - services); + Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, Services services) { + BasicPOSnippetFactory fAssumes = POSnippetFactory.getBasicFactory(loopinvariant, + schemaDataAssumes, executionContext, guard, services); return fAssumes.create(BasicPOSnippetFactory.Snippet.LOOP_CALL_RELATION); } @Override - Term generateSchemaFind(ProofObligationVars schemaDataFind, - Services services) { - BasicPOSnippetFactory fFind = - POSnippetFactory.getBasicFactory(loopinvariant, - schemaDataFind, - executionContext, - guard, - services); + Term generateSchemaFind(ProofObligationVars schemaDataFind, Services services) { + BasicPOSnippetFactory fFind = POSnippetFactory.getBasicFactory(loopinvariant, + schemaDataFind, executionContext, guard, services); return fFind.create(BasicPOSnippetFactory.Snippet.LOOP_CALL_RELATION); } @Override Term getContractApplPred(ProofObligationVars appData) { - BasicPOSnippetFactory f = - POSnippetFactory.getBasicFactory(loopinvariant, - appData, - executionContext, - guard, - services); + BasicPOSnippetFactory f = POSnippetFactory.getBasicFactory(loopinvariant, appData, + executionContext, guard, services); return f.create(BasicPOSnippetFactory.Snippet.LOOP_CALL_RELATION); } @Override Term buildContractApplications(ProofObligationVars contAppData, - ProofObligationVars contAppData2, - Services services) { + ProofObligationVars contAppData2, Services services) { LoopSpecification ifContract = services.getSpecificationRepository().getLoopSpec(loopinvariant.getLoop()); - InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(ifContract, contAppData, - contAppData2, - executionContext, - guard, services); + InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(ifContract, contAppData, + contAppData2, executionContext, guard, services); Term contractApplication = f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_LOOP_INVARIANT_APPL); return contractApplication; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowMethodContractTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowMethodContractTacletBuilder.java index 5a062cd1c1d..8625592808a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowMethodContractTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/InfFlowMethodContractTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import org.key_project.util.collection.DefaultImmutableSet; @@ -45,8 +48,7 @@ Name generateName() { @Override - Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, - Services services) { + Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, Services services) { BasicPOSnippetFactory fAssumes = POSnippetFactory.getBasicFactory(methodContract, schemaDataAssumes, services); return fAssumes.create(BasicPOSnippetFactory.Snippet.METHOD_CALL_RELATION); @@ -54,8 +56,7 @@ Term generateSchemaAssumes(ProofObligationVars schemaDataAssumes, @Override - Term generateSchemaFind(ProofObligationVars schemaDataFind, - Services services) { + Term generateSchemaFind(ProofObligationVars schemaDataFind, Services services) { BasicPOSnippetFactory fFind = POSnippetFactory.getBasicFactory(methodContract, schemaDataFind, services); return fFind.create(BasicPOSnippetFactory.Snippet.METHOD_CALL_RELATION); @@ -65,27 +66,22 @@ Term generateSchemaFind(ProofObligationVars schemaDataFind, @Override Term getContractApplPred(ProofObligationVars appData) { BasicPOSnippetFactory f = - POSnippetFactory.getBasicFactory(methodContract, appData, - services); + POSnippetFactory.getBasicFactory(methodContract, appData, services); return f.create(BasicPOSnippetFactory.Snippet.METHOD_CALL_RELATION); } @Override Term buildContractApplications(ProofObligationVars contAppData, - ProofObligationVars contAppData2, - Services services) { + ProofObligationVars contAppData2, Services services) { ImmutableSet ifContracts = getInformFlowContracts(methodContract.getTarget(), services); - ImmutableList contractsApplications = - ImmutableSLList.nil(); + ImmutableList contractsApplications = ImmutableSLList.nil(); for (InformationFlowContract cont : ifContracts) { InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(cont, contAppData, - contAppData2, services); - contractsApplications = - contractsApplications.append( - f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APPL)); + POSnippetFactory.getInfFlowFactory(cont, contAppData, contAppData2, services); + contractsApplications = contractsApplications + .append(f.create(InfFlowPOSnippetFactory.Snippet.INF_FLOW_CONTRACT_APPL)); } return and(contractsApplications); @@ -93,7 +89,7 @@ Term buildContractApplications(ProofObligationVars contAppData, private ImmutableSet getInformFlowContracts(IProgramMethod pm, - Services services) { + Services services) { ImmutableSet contracts = services.getSpecificationRepository().getContracts(pm.getContainerType(), pm); ImmutableSet ifContracts = @@ -105,4 +101,4 @@ private ImmutableSet getInformFlowContracts(IProgramMet } return ifContracts; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/LoopInfFlowUnfoldTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/LoopInfFlowUnfoldTacletBuilder.java index 69ec644cd11..f7ba36030a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/LoopInfFlowUnfoldTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/LoopInfFlowUnfoldTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import de.uka.ilkd.key.informationflow.po.IFProofObligationVars; @@ -44,19 +47,15 @@ public void setGuard(Term guard) { @Override Name getTacletName() { - return MiscTools.toValidTacletName(UNFOLD + unfoldCounter + " of " + - loopInv.getUniqueName()); + return MiscTools + .toValidTacletName(UNFOLD + unfoldCounter + " of " + loopInv.getUniqueName()); } @Override Term createFindTerm(IFProofObligationVars ifVars) { - InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(loopInv, - ifVars.c1, ifVars.c2, - executionContext, - guard, - services); + InfFlowPOSnippetFactory f = POSnippetFactory.getInfFlowFactory(loopInv, ifVars.c1, + ifVars.c2, executionContext, guard, services); return f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_LOOP_WITH_INV_RELATION); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/MethodInfFlowUnfoldTacletBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/MethodInfFlowUnfoldTacletBuilder.java index 218be15bcb1..c6070e83895 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/MethodInfFlowUnfoldTacletBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/informationflow/rule/tacletbuilder/MethodInfFlowUnfoldTacletBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.informationflow.rule.tacletbuilder; import de.uka.ilkd.key.informationflow.po.IFProofObligationVars; @@ -31,17 +34,15 @@ public void setContract(InformationFlowContract c) { @Override Name getTacletName() { - return MiscTools.toValidTacletName(UNFOLD + unfoldCounter + " of " + - contract.getTarget().getUniqueName()); + return MiscTools.toValidTacletName( + UNFOLD + unfoldCounter + " of " + contract.getTarget().getUniqueName()); } @Override Term createFindTerm(IFProofObligationVars ifVars) { InfFlowPOSnippetFactory f = - POSnippetFactory.getInfFlowFactory(contract, - ifVars.c1, ifVars.c2, - services); + POSnippetFactory.getInfFlowFactory(contract, ifVars.c1, ifVars.c2, services); return f.create(InfFlowPOSnippetFactory.Snippet.SELFCOMPOSED_EXECUTION_WITH_PRE_RELATION); } } 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 465785eca59..1e1b946cbe8 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,8 +14,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakLabelParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakLabelParameterDeclaration extends CcatchNonstandardParameterDeclaration { private final Label label; 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 81440f2c0ff..da75f35bc56 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,11 +14,9 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakParameterDeclaration extends CcatchNonstandardParameterDeclaration { - public CcatchBreakParameterDeclaration(ExtList children) { - } + public CcatchBreakParameterDeclaration(ExtList children) {} @Override public int getChildCount() { 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 e6302b21c00..f833445339c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,11 +14,9 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakWildcardParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakWildcardParameterDeclaration extends CcatchNonstandardParameterDeclaration { - public CcatchBreakWildcardParameterDeclaration(ExtList children) { - } + public CcatchBreakWildcardParameterDeclaration(ExtList children) {} @Override public int getChildCount() { 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 aa933595b4d..00a5317d644 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,8 +14,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchContinueLabelParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchContinueLabelParameterDeclaration extends CcatchNonstandardParameterDeclaration { private final Label label; 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 da4b277c636..eba4264169f 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,11 +14,9 @@ * * @author Dominic Steinhöfel */ -public class CcatchContinueParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchContinueParameterDeclaration extends CcatchNonstandardParameterDeclaration { - public CcatchContinueParameterDeclaration(ExtList children) { - } + public CcatchContinueParameterDeclaration(ExtList children) {} @Override public int getChildCount() { 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 7699e8ed037..e3238ee168f 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -14,8 +17,7 @@ public class CcatchContinueWildcardParameterDeclaration extends CcatchNonstandardParameterDeclaration { - public CcatchContinueWildcardParameterDeclaration(ExtList children) { - } + public CcatchContinueWildcardParameterDeclaration(ExtList children) {} @Override public int getChildCount() { 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 b698071ec19..237a49d0074 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** @@ -5,7 +8,6 @@ * * @author Dominic Steinhöfel */ -public abstract class CcatchNonstandardParameterDeclaration - extends JavaNonTerminalProgramElement { +public abstract class CcatchNonstandardParameterDeclaration extends JavaNonTerminalProgramElement { -} \ 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 b065bedad2e..8d7f2b47c46 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -11,11 +14,9 @@ * * @author Dominic Steinhöfel */ -public class CcatchReturnParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchReturnParameterDeclaration extends CcatchNonstandardParameterDeclaration { - public CcatchReturnParameterDeclaration(ExtList children) { - } + public CcatchReturnParameterDeclaration(ExtList children) {} @Override public int getChildCount() { 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 b53f60fef66..c121a6f0645 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -15,8 +18,8 @@ * * @author Dominic Steinhöfel */ -public class CcatchReturnValParameterDeclaration extends - CcatchNonstandardParameterDeclaration implements ParameterContainer { +public class CcatchReturnValParameterDeclaration extends CcatchNonstandardParameterDeclaration + implements ParameterContainer { private final ParameterDeclaration delegate; @@ -47,14 +50,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception 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/Comment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Comment.java index 1bf68b56de1..84744c01d03 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Comment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Comment.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.visitor.Visitor; @@ -7,11 +10,11 @@ public class Comment extends JavaSourceElement { private final String text; public Comment() { - this.text = null; + this.text = null; } public Comment(String text) { - this.text = text; + this.text = text; } public Comment(String text, PositionInfo pInfo) { @@ -19,49 +22,49 @@ public Comment(String text, PositionInfo pInfo) { this.text = text; } - public boolean isPrefixed () { - return false; + public boolean isPrefixed() { + return false; } - public void prettyPrint(PrettyPrinter w) { - } + public void prettyPrint(PrettyPrinter w) {} - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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) { - } + public void visit(Visitor v) {} - public String getText(){ - return text; + public String getText() { + return text; } - - + + public String toString() { return getText(); } - /** comments can be ignored + /** + * comments can be ignored */ - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { - return true; - } - - public int hashCode(){ - int result = 17; - result = 37 * result + getText().hashCode(); - return result; - } - - public boolean equals(Object o){ - if (o == this) - return true; - if(!(o instanceof Comment)) - return false; - Comment cmp = (Comment)o; - return (getText().equals(cmp.getText())); - } -} \ No newline at end of file + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { + return true; + } + + public int hashCode() { + int result = 17; + result = 37 * result + getText().hashCode(); + return result; + } + + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Comment)) + return false; + Comment cmp = (Comment) o; + return (getText().equals(cmp.getText())); + } +} 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 66e23a3330a..d35113600a1 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; @@ -14,15 +17,14 @@ import org.slf4j.LoggerFactory; /** - * 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 class CompilationUnit extends JavaNonTerminalProgramElement + implements TypeDeclarationContainer, TypeScope { private static final Logger LOGGER = LoggerFactory.getLogger(CompilationUnit.class); /** @@ -42,33 +44,34 @@ public class CompilationUnit extends JavaNonTerminalProgramElement implements Ty */ protected final ImmutableArray typeDeclarations; - /** creates a compilation unit + /** + * 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) + * @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.packageSpec = packageSpec; + this.imports = new ImmutableArray(imports); + this.typeDeclarations = new ImmutableArray(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)); } - + public SourceElement getFirstElement() { return (getChildCount() > 0) ? getChildAt(0).getFirstElement() : this; @@ -76,50 +79,54 @@ public SourceElement getFirstElement() { @Override public SourceElement getFirstElementIncludingBlocks() { - return (getChildCount() > 0) ? getChildAt(0).getFirstElementIncludingBlocks() : this; + return (getChildCount() > 0) ? getChildAt(0).getFirstElementIncludingBlocks() : this; } public SourceElement getLastElement() { - return - typeDeclarations.get(typeDeclarations.size()-1); + return 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(); + 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 + */ 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++; + if (imports != null) + result += imports.size(); + if (typeDeclarations != null) + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; if (packageSpec != null) { - if (index == 0) return packageSpec; + if (index == 0) + return packageSpec; index--; } if (imports != null) { @@ -136,8 +143,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get imports. - * @return the wrapped import array. + * Get imports. + * + * @return the wrapped import array. */ public ImmutableArray getImports() { @@ -146,8 +154,9 @@ public ImmutableArray getImports() { /** - * Get package specification. - * @return the package specification. + * Get package specification. + * + * @return the package specification. */ public PackageSpecification getPackageSpecification() { @@ -156,49 +165,51 @@ 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. */ public int getTypeDeclarationCount() { - return (typeDeclarations != null) ? - typeDeclarations.size() : 0; + return (typeDeclarations != null) ? typeDeclarations.size() : 0; } /* - Return the type declaration at the specified index in this node's - "virtual" type declaration array. - @param index an index for a type declaration. - @return the type declaration with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the type declaration at the specified index in this node's "virtual" type declaration + * array. + * + * @param index an index for a type declaration. + * + * @return the type declaration with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public TypeDeclaration getTypeDeclarationAt(int index) { if (typeDeclarations != null) { - return typeDeclarations.get(index); + return typeDeclarations.get(index); } throw new ArrayIndexOutOfBoundsException(); } /** - * Get declarations. - * @return the wrapped array of type declarations . + * Get declarations. + * + * @return the wrapped array of type declarations . */ public ImmutableArray getDeclarations() { return typeDeclarations; } /** - * 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 - * declaration, this method returns null. + * 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 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()) { @@ -221,25 +232,27 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printCompilationUnit(this); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnCompilationUnit(this); + v.performActionOnCompilationUnit(this); } /** toString */ 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(); - } -} \ No newline at end of file + 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(); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ConstantExpressionEvaluator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ConstantExpressionEvaluator.java index 4d78bc29d71..ea369d7be32 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ConstantExpressionEvaluator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ConstantExpressionEvaluator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.slf4j.Logger; @@ -10,64 +13,60 @@ public class ConstantExpressionEvaluator { - private static final Logger LOGGER = LoggerFactory.getLogger(ConstantExpressionEvaluator.class); - private Services services = null; + private static final Logger LOGGER = LoggerFactory.getLogger(ConstantExpressionEvaluator.class); + private Services services = null; private ConstantEvaluator recCe = null; - static final int BOOLEAN_TYPE = 0, BYTE_TYPE = 1, - SHORT_TYPE = 2, CHAR_TYPE = 3, INT_TYPE = 4, LONG_TYPE = 5, - FLOAT_TYPE = 6, DOUBLE_TYPE = 7, STRING_TYPE = 8; - + static final int BOOLEAN_TYPE = 0, BYTE_TYPE = 1, SHORT_TYPE = 2, CHAR_TYPE = 3, INT_TYPE = 4, + LONG_TYPE = 5, FLOAT_TYPE = 6, DOUBLE_TYPE = 7, STRING_TYPE = 8; + ConstantExpressionEvaluator(Services s) { - services = s; + services = s; } public Services getServices() { - return services; + return services; } public boolean isCompileTimeConstant(Expression expr) { - return getRecoderConstantEvaluator(). - isCompileTimeConstant(parseExpression(expr)); - + return getRecoderConstantEvaluator().isCompileTimeConstant(parseExpression(expr)); + } - - public boolean isCompileTimeConstant(Expression expr, - ConstantEvaluator.EvaluationResult result) { - return getRecoderConstantEvaluator(). - isCompileTimeConstant(parseExpression(expr), result); - + + public boolean isCompileTimeConstant(Expression expr, + ConstantEvaluator.EvaluationResult result) { + return getRecoderConstantEvaluator().isCompileTimeConstant(parseExpression(expr), result); + } - public KeYJavaType getCompileTimeConstantType(Expression expr) { - recoder.abstraction.Type javaType = getRecoderConstantEvaluator(). - getCompileTimeConstantType(parseExpression(expr)); - return services.getJavaInfo().getKeYJavaType - (javaType.getFullName()); + public KeYJavaType getCompileTimeConstantType(Expression expr) { + recoder.abstraction.Type javaType = + getRecoderConstantEvaluator().getCompileTimeConstantType(parseExpression(expr)); + return services.getJavaInfo().getKeYJavaType(javaType.getFullName()); } private ConstantEvaluator getRecoderConstantEvaluator() { - if (recCe == null) { - KeYCrossReferenceServiceConfiguration servConf = - services.getJavaInfo().getKeYProgModelInfo().getServConf(); - recCe = new DefaultConstantEvaluator(servConf); - } - return recCe; + if (recCe == null) { + KeYCrossReferenceServiceConfiguration servConf = + services.getJavaInfo().getKeYProgModelInfo().getServConf(); + recCe = new DefaultConstantEvaluator(servConf); + } + return recCe; } - private recoder.java.Expression parseExpression(Expression expr) { - recoder.java.Expression recExpr = null; - try { - recExpr = JavaProgramFactory.getInstance().parseExpression(expr.toString()); - } catch (recoder.ParserException exc) { - LOGGER.error("Failed to parse {} as Java expression!", expr); - } - return recExpr; - } -} \ No newline at end of file + private recoder.java.Expression parseExpression(Expression expr) { + recoder.java.Expression recExpr = null; + try { + recExpr = JavaProgramFactory.getInstance().parseExpression(expr.toString()); + } catch (recoder.ParserException exc) { + LOGGER.error("Failed to parse {} as Java expression!", expr); + } + return recExpr; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Context.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Context.java index 21297101070..39255adf8f3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Context.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Context.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import recoder.java.declaration.ClassDeclaration; @@ -8,80 +11,80 @@ import de.uka.ilkd.key.java.recoderext.KeYCrossReferenceServiceConfiguration; import de.uka.ilkd.key.util.SpecDataLocation; -/** this class stores recoder related contextinformation used to parse - * in program parts in which non-declared variables are used +/** + * this class stores recoder related contextinformation used to parse in program parts in which + * non-declared variables are used */ class Context { private recoder.java.CompilationUnit compilationUnitContext; private ClassDeclaration classContext; - public static final String PARSING_CONTEXT_CLASS_NAME = - ""; + public static final String PARSING_CONTEXT_CLASS_NAME = ""; - - /** creates a new context object - * @param compilationUnitContext a - * recoder.java.CompilationUnit + + /** + * creates a new context object + * + * @param compilationUnitContext a recoder.java.CompilationUnit * @param classContext a recoder.java.declaration.ClassDeclaration */ - public Context(KeYCrossReferenceServiceConfiguration servConf, - recoder.java.CompilationUnit compilationUnitContext, - ClassDeclaration classContext) { - this.compilationUnitContext = compilationUnitContext; - this.classContext = classContext; + public Context(KeYCrossReferenceServiceConfiguration servConf, + recoder.java.CompilationUnit compilationUnitContext, ClassDeclaration classContext) { + this.compilationUnitContext = compilationUnitContext; + this.classContext = classContext; } - /** creates a new context object - * @param compilationUnitContext a - * recoder.java.declaration.CompilationUnit + /** + * creates a new context object + * + * @param compilationUnitContext a recoder.java.declaration.CompilationUnit */ public Context(KeYCrossReferenceServiceConfiguration servConf, - recoder.java.CompilationUnit compilationUnitContext) { - this(servConf, compilationUnitContext, createClassDecl(servConf)); + recoder.java.CompilationUnit compilationUnitContext) { + this(servConf, compilationUnitContext, createClassDecl(servConf)); } - - /** creates a new context object + + /** + * creates a new context object + * * @param classContext a recoder.java.declaration.ClassDeclaration */ - public Context(KeYCrossReferenceServiceConfiguration servConf, - ClassDeclaration classContext) { - this(servConf, createCompUnit(classContext), classContext); + public Context(KeYCrossReferenceServiceConfiguration servConf, ClassDeclaration classContext) { + this(servConf, createCompUnit(classContext), classContext); } - private static recoder.java.CompilationUnit createCompUnit - (ClassDeclaration classContext) { - recoder.java.CompilationUnit cu = new recoder.java.CompilationUnit - (null, new ASTArrayList(0), inList(classContext)); - cu.setDataLocation(new SpecDataLocation("INTERNAL", classContext.getFullName())); - return cu; + private static recoder.java.CompilationUnit createCompUnit(ClassDeclaration classContext) { + recoder.java.CompilationUnit cu = new recoder.java.CompilationUnit(null, + new ASTArrayList(0), inList(classContext)); + cu.setDataLocation(new SpecDataLocation("INTERNAL", classContext.getFullName())); + return cu; } public static ASTList inList(TypeDeclaration td) { - ASTList tdml = new ASTArrayList(); - tdml.add(td); - return tdml; + ASTList tdml = new ASTArrayList(); + tdml.add(td); + return tdml; } /** returns the compilation context */ public recoder.java.CompilationUnit getCompilationUnitContext() { - return compilationUnitContext; + return compilationUnitContext; } /** returns the compilation context */ public ClassDeclaration getClassContext() { - return classContext; + return classContext; } - private static recoder.java.declaration.ClassDeclaration createClassDecl - (KeYCrossReferenceServiceConfiguration servConf) { - return servConf.getProgramFactory().createClassDeclaration - (null, new ImplicitIdentifier(PARSING_CONTEXT_CLASS_NAME), - null, null, null); + private static recoder.java.declaration.ClassDeclaration createClassDecl( + KeYCrossReferenceServiceConfiguration servConf) { + return servConf.getProgramFactory().createClassDeclaration(null, + new ImplicitIdentifier(PARSING_CONTEXT_CLASS_NAME), null, null, null); } - -} \ No newline at end of file + +} 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 e3f8665de49..0d3c0c994b4 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -15,29 +18,29 @@ import de.uka.ilkd.key.rule.inst.SVInstantiations; import de.uka.ilkd.key.util.Debug; -/** - * 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 - * of the program. Between the prefix pi and the postfix omega there - * can stand an arbitrary program. This pattern is realized using this - * class. +/** + * 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 of the program. Between the prefix pi and the postfix omega there can stand an + * arbitrary program. This pattern is realized using this class. */ public class ContextStatementBlock extends StatementBlock { - /** - * the last execution context of the context term + /** + * the last execution context of the context term */ private final IExecutionContext executionContext; - /** + /** * length of this progran prefix */ private final int patternPrefixLength; - - /** creates a ContextStatementBlock + + /** + * creates a ContextStatementBlock + * * @param children the body of the context term */ public ContextStatementBlock(ExtList children) { @@ -46,308 +49,289 @@ public ContextStatementBlock(ExtList children) { patternPrefixLength = this.getPrefixLength(); } - /** creates a ContextStatementBlock + /** + * 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; + 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 + * 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 + * @exception 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 - * perform some action/transformation on this element + /** + * 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(); + StringBuffer result = new StringBuffer(); + result.append(".."); + result.append(super.toString()); + result.append("\n"); + result.append("..."); + return result.toString(); } - - + + 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 - * the suffix of this ContextStatementBlock + * 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 + + 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: {}", + 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 + + // 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) { - firstActiveStatement = (ProgramPrefix) - PosInProgram.getProgramAt(relPos.up(), - firstActiveStatement); + lastExecutionContext = (ExecutionContext) ((MethodFrame) firstActiveStatement) + .getExecutionContext(); + } + + start = relPos.get(relPos.depth() - 1); + if (relPos.depth() > 1) { + firstActiveStatement = (ProgramPrefix) 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); - + + matchCond = + makeContextInfoComplete(matchCond, newSource, prefix, pos, relPos, src, services); + if (matchCond == null) { return null; - } - + } + LOGGER.debug("Successful match."); return matchCond; } /** - * completes match of context block by adding the prefix end position - * and the suffix start position + * completes match of context block by adding the prefix end position and the suffix start + * position */ - private MatchConditions makeContextInfoComplete( - MatchConditions matchCond, - SourceData newSource, - ProgramPrefix prefix, - int pos, - PosInProgram relPos, - ProgramElement src, + private MatchConditions makeContextInfoComplete(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); - + + // compute position of the first element not matched + 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)); + matchCond = matchCond.setInstantiations(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 + * 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 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, + 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(); + innerContext = + (ExecutionContext) prefix.getInnerMostMethodFrame().getExecutionContext(); } else { innerContext = services.getJavaInfo().getDefaultExecutionContext(); } } - + if (executionContext != null) { - matchCond = executionContext.match(new SourceData(innerContext, -1, - services), matchCond); + matchCond = + executionContext.match(new SourceData(innerContext, -1, services), matchCond); if (matchCond == null) { LOGGER.debug("Program match. ExecutionContext mismatch."); return null; } 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 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(); } } @@ -364,4 +348,4 @@ private static ProgramPrefix getPrefixElementAt(ProgramPrefix prefix, int i) { } return current; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ConvertException.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ConvertException.java index a8f5d2162d3..1f550e3ddf1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ConvertException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ConvertException.java @@ -1,47 +1,49 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** * This exception class is mainly thrown by Recoder2KeY and its companions. - * - * It stores its reason not only by the cause mechanism of Exceptions but also - * separately if it is a parser error. - * - * This information is then read by the KeYParser to produce helpful error - * messages. - * + * + * It stores its reason not only by the cause mechanism of Exceptions but also separately if it is a + * parser error. + * + * This information is then read by the KeYParser to produce helpful error messages. + * */ public class ConvertException extends RuntimeException { - /** - * + /** + * */ private static final long serialVersionUID = 7112945712992241455L; public ConvertException(String errmsg) { - super(errmsg); - } + super(errmsg); + } - public ConvertException(Throwable pe) { + public ConvertException(Throwable pe) { super(pe); - } + } - public ConvertException(String errmsg, Throwable cause) { - super(errmsg, cause); - } - - public recoder.parser.ParseException parseException() { - if (getCause() instanceof recoder.parser.ParseException) { - return (recoder.parser.ParseException) getCause(); - } else { - return null; - } - } + public ConvertException(String errmsg, Throwable cause) { + super(errmsg, cause); + } - public de.uka.ilkd.key.parser.proofjava.ParseException proofJavaException() { - if (getCause() instanceof de.uka.ilkd.key.parser.proofjava.ParseException) { - return (de.uka.ilkd.key.parser.proofjava.ParseException) getCause(); - } else { - return null; - } - } -} \ No newline at end of file + public recoder.parser.ParseException parseException() { + if (getCause() instanceof recoder.parser.ParseException) { + return (recoder.parser.ParseException) getCause(); + } else { + return null; + } + } + + public de.uka.ilkd.key.parser.proofjava.ParseException proofJavaException() { + if (getCause() instanceof de.uka.ilkd.key.parser.proofjava.ParseException) { + return (de.uka.ilkd.key.parser.proofjava.ParseException) getCause(); + } else { + return null; + } + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/CreateArrayMethodBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/CreateArrayMethodBuilder.java index 947f6957fad..7f57d823682 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/CreateArrayMethodBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/CreateArrayMethodBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.LinkedHashMap; @@ -50,22 +53,20 @@ import de.uka.ilkd.key.logic.sort.Sort; /** - * This class creates the <createArray> method for array - * creation and in particular its helper method - * <createArrayHelper>. This class should be replaced by a - * recoder transformation as soon as we port our array data structures to - * RecodeR. + * This class creates the <createArray> method for array creation and in + * particular its helper method <createArrayHelper>. This class should be + * replaced by a recoder transformation as soon as we port our array data structures to RecodeR. */ public final class CreateArrayMethodBuilder extends KeYJavaASTFactory { - public static final String IMPLICIT_ARRAY_CREATE = ""; + public static final String IMPLICIT_ARRAY_CREATE = ""; - public static final String IMPLICIT_ARRAY_CREATION_HELPER = ""; + public static final String IMPLICIT_ARRAY_CREATION_HELPER = ""; // as these methods are thought to be only preliminary(we cache some // information here) - private final Map cache = - new LinkedHashMap(3); + private final Map cache = + new LinkedHashMap(3); /** * keeps the currently used integer type @@ -76,18 +77,16 @@ public final class CreateArrayMethodBuilder extends KeYJavaASTFactory { * stores the currently used object type */ private final KeYJavaType objectType; - + private final Sort heapSort; - + private final int heapCount; - - + + /** create the method builder for array implict creation methods */ - public CreateArrayMethodBuilder(KeYJavaType integerType, - KeYJavaType objectType, - Sort heapSort, - int heapCount) { + public CreateArrayMethodBuilder(KeYJavaType integerType, KeYJavaType objectType, Sort heapSort, + int heapCount) { this.integerType = integerType; this.objectType = objectType; this.heapSort = heapSort; @@ -95,11 +94,9 @@ public CreateArrayMethodBuilder(KeYJavaType integerType, } /** - * creates the statements which take the next object out of the list of - * available objects - * - * @return the statements which take the next object out of the list of - * available objects + * creates the statements which take the next object out of the list of available objects + * + * @return the statements which take the next object out of the list of available objects */ protected List createArray(ImmutableList fields) { LinkedList result = new LinkedList(); @@ -109,24 +106,20 @@ protected List createArray(ImmutableList fields) { ProgramVariable initialized = findInObjectFields(ImplicitFieldAdder.IMPLICIT_INITIALIZED); if (initialized == null) { // only if createObject for Object is called - initialized = find(ImplicitFieldAdder.IMPLICIT_INITIALIZED, - implicitFields); - } + initialized = find(ImplicitFieldAdder.IMPLICIT_INITIALIZED, implicitFields); + } - result.addLast(assign(attribute(new ThisReference(), initialized), - BooleanLiteral.FALSE)); + result.addLast(assign(attribute(new ThisReference(), initialized), BooleanLiteral.FALSE)); return result; } /** - * extracts all field specifications out of the given list. Therefore it - * descends into field declarations. - * - * @param list - * the ArrayOf with the members of a type - * declaration - * @return a IList the includes all field specifications found int the - * field declaration of the given list + * extracts all field specifications out of the given list. Therefore it descends into field + * declarations. + * + * @param list the ArrayOf with the members of a type declaration + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ protected ImmutableList filterField(ImmutableArray list) { ImmutableList result = ImmutableSLList.nil(); @@ -141,12 +134,10 @@ protected ImmutableList filterField(ImmutableArray lis /** * extracts all fields out of fielddeclaration - * - * @param field - * the FieldDeclaration of which the field specifications have to - * be extracted - * @return a IList the includes all field specifications found int the - * field declaration of the given list + * + * @param field the FieldDeclaration of which the field specifications have to be extracted + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ protected final ImmutableList filterField(FieldDeclaration field) { ImmutableList result = ImmutableSLList.nil(); @@ -159,10 +150,8 @@ protected final ImmutableList filterField(FieldDeclaration field) { /** * extracts all implicit field specifications out of the given list - * - * @param list - * the IList from which the implicit ones have to be - * selected + * + * @param list the IList from which the implicit ones have to be selected * @return a list with all implicit fields found in 'list' */ protected ImmutableList filterImplicitFields(ImmutableList list) { @@ -178,18 +167,15 @@ protected ImmutableList filterImplicitFields(ImmutableList list) { /** * retrieves a field with the given name out of the list - * - * @param name - * a String with the name of the field to be looked for - * @param fields - * the IList where we have to look for the field + * + * @param name a String with the name of the field to be looked for + * @param fields the IList where we have to look for the field * @return the program variable of the given name or null if not found */ protected ProgramVariable find(String name, ImmutableList fields) { for (Field field1 : fields) { Field field = field1; - final ProgramVariable fieldVar = (ProgramVariable) field - .getProgramVariable(); + final ProgramVariable fieldVar = (ProgramVariable) field.getProgramVariable(); if (name.equals(fieldVar.getProgramElementName().getProgramName())) { return fieldVar; } @@ -200,10 +186,10 @@ protected ProgramVariable find(String name, ImmutableList fields) { protected ProgramVariable findInObjectFields(String name) { ProgramVariable var = cache.get(name); if (var == null && objectType.getJavaType() != null) { - final ImmutableList objectFields = filterImplicitFields(filterField(((ClassDeclaration) objectType - .getJavaType()).getMembers())); -// final ListOfField objectFields = filterField(((ClassDeclaration) objectType -// .getJavaType()).getMembers()); + final ImmutableList objectFields = filterImplicitFields( + filterField(((ClassDeclaration) objectType.getJavaType()).getMembers())); + // final ListOfField objectFields = filterField(((ClassDeclaration) objectType + // .getJavaType()).getMembers()); var = find(name, objectFields); if (var != null) { // may be null if object is currently created cache.put(name, var); @@ -215,65 +201,50 @@ protected ProgramVariable findInObjectFields(String name) { // ================ HELPER METHODS ========================= /** - * creates the implicit method <allocate> which is a - * stump and given meaning by a contract + * creates the implicit method <allocate> which is a stump and given meaning + * by a contract */ - public IProgramMethod getArrayInstanceAllocatorMethod( - TypeReference arrayTypeReference) { + public IProgramMethod getArrayInstanceAllocatorMethod(TypeReference arrayTypeReference) { - final Modifier[] modifiers = new Modifier[] { new Private(), - new Static() }; + final Modifier[] modifiers = new Modifier[] { new Private(), new Static() }; final KeYJavaType arrayType = arrayTypeReference.getKeYJavaType(); - - final ProgramVariable paramLength = new LocationVariable( - new ProgramElementName("length"), integerType, true); - - final ParameterDeclaration param = new ParameterDeclaration( - new Modifier[0], new TypeRef(integerType), - new VariableSpecification(paramLength), false); - - final MethodDeclaration md = new MethodDeclaration( - modifiers, - arrayTypeReference, - new ProgramElementName( - InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), - new ParameterDeclaration[]{param}, null, null, false); - - return new ProgramMethod(md, - arrayType, - arrayType, - PositionInfo.UNDEFINED, - heapSort, - heapCount); + + final ProgramVariable paramLength = + new LocationVariable(new ProgramElementName("length"), integerType, true); + + final ParameterDeclaration param = new ParameterDeclaration(new Modifier[0], + new TypeRef(integerType), new VariableSpecification(paramLength), false); + + final MethodDeclaration md = new MethodDeclaration(modifiers, arrayTypeReference, + new ProgramElementName(InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), + new ParameterDeclaration[] { param }, null, null, false); + + return new ProgramMethod(md, arrayType, arrayType, PositionInfo.UNDEFINED, heapSort, + heapCount); } protected StatementBlock getCreateArrayBody(TypeReference arrayRef, - ProgramVariable paramLength) { - - - - final LocalVariableDeclaration local = - declare(new ProgramElementName("newObject"), arrayRef); - final ProgramVariable newObject = (ProgramVariable) local - .getVariables().get(0) - .getProgramVariable(); + ProgramVariable paramLength) { + + + + final LocalVariableDeclaration local = + declare(new ProgramElementName("newObject"), arrayRef); + final ProgramVariable newObject = + (ProgramVariable) local.getVariables().get(0).getProgramVariable(); final LinkedList body = new LinkedList(); body.addLast(local); - body.addLast(assign( - newObject, - new MethodReference( - new ImmutableArray(paramLength), - new ProgramElementName( - InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), - arrayRef))); - - body.add(new MethodReference( - new ImmutableArray(), + body.addLast(assign(newObject, + new MethodReference(new ImmutableArray(paramLength), new ProgramElementName( - CreateArrayMethodBuilder.IMPLICIT_ARRAY_CREATION_HELPER), - newObject)); + InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), + arrayRef))); + + body.add(new MethodReference(new ImmutableArray(), + new ProgramElementName(CreateArrayMethodBuilder.IMPLICIT_ARRAY_CREATION_HELPER), + newObject)); body.add(new Return(newObject)); @@ -282,20 +253,16 @@ protected StatementBlock getCreateArrayBody(TypeReference arrayRef, /** * creates the body of method <createArrayHelper(int - * paramLength)> - * therefore it first adds the statements responsible to take the correct - * one out of the list, then the arrays length attribute is set followed by - * a call to <prepare>() setting the arrays fields on - * their default value. - * - * @param length - * the final public ProgramVariable - * length of the array - * @param fields the IList of the current array - * @param createTransient a boolean indicating if a transient array has + * paramLength)> therefore it first adds the statements responsible to take the + * correct one out of the list, then the arrays length attribute is set followed by a call to + * <prepare>() setting the arrays fields on their default value. + * + * @param length the final public ProgramVariable length of the array + * @param fields the IList of the current array + * @param createTransient a boolean indicating if a transient array has * to be created (this is special to JavaCard) - * @param transientType a ProgramVariable identifying the kind of transient - * @return the StatementBlock which is the method's body

    + * @param transientType a ProgramVariable identifying the kind of transient + * @return the StatementBlock which is the method's body

    * * { * this. = this..; @@ -309,90 +276,71 @@ protected StatementBlock getCreateArrayBody(TypeReference arrayRef, * */ protected StatementBlock getCreateArrayHelperBody(ProgramVariable length, - ImmutableList fields, - boolean createTransient, ProgramVariable transientType) { - assert !createTransient; + ImmutableList fields, boolean createTransient, ProgramVariable transientType) { + assert !createTransient; final ThisReference thisRef = new ThisReference(); final List body = createArray(fields); body.add(new MethodReference(new ImmutableArray(), - new ProgramElementName( - PrepareObjectBuilder.IMPLICIT_OBJECT_PREPARE), null)); + new ProgramElementName(PrepareObjectBuilder.IMPLICIT_OBJECT_PREPARE), null)); - body.add(assign(attribute(thisRef, - findInObjectFields(ImplicitFieldAdder.IMPLICIT_INITIALIZED)), + body.add(assign( + attribute(thisRef, findInObjectFields(ImplicitFieldAdder.IMPLICIT_INITIALIZED)), BooleanLiteral.TRUE)); - + body.add(new Return(thisRef)); return new StatementBlock(body.toArray(new Statement[body.size()])); } /** - * create the method declaration of the - * <createArrayHelper> method + * create the method declaration of the <createArrayHelper> method */ - public IProgramMethod getCreateArrayHelperMethod( - TypeReference arrayTypeReference, ProgramVariable length, - ImmutableList fields) { + public IProgramMethod getCreateArrayHelperMethod(TypeReference arrayTypeReference, + ProgramVariable length, ImmutableList fields) { - final Modifier[] modifiers = new Modifier[] { new Private()}; + final Modifier[] modifiers = new Modifier[] { new Private() }; final KeYJavaType arrayType = arrayTypeReference.getKeYJavaType(); - final MethodDeclaration md = new MethodDeclaration(modifiers, - arrayTypeReference, new ProgramElementName( - IMPLICIT_ARRAY_CREATION_HELPER), - new ParameterDeclaration[0], null, - getCreateArrayHelperBody(length, fields, false, - null), false); - - return new ProgramMethod(md, - arrayType, - arrayType, - PositionInfo.UNDEFINED, - heapSort, - heapCount); + final MethodDeclaration md = new MethodDeclaration(modifiers, arrayTypeReference, + new ProgramElementName(IMPLICIT_ARRAY_CREATION_HELPER), new ParameterDeclaration[0], + null, getCreateArrayHelperBody(length, fields, false, null), false); + + return new ProgramMethod(md, arrayType, arrayType, PositionInfo.UNDEFINED, heapSort, + heapCount); } /** - * creates the implicit method <createArray> it - * fulfills a similar purpose as <createObject> in - * addition it sets the arrays length and calls the prepare method + * creates the implicit method <createArray> it fulfills a similar purpose as + * <createObject> in addition it sets the arrays length and calls the prepare + * method */ public IProgramMethod getCreateArrayMethod(TypeReference arrayTypeReference, IProgramMethod prepare, ImmutableList fields) { - final Modifier[] modifiers = new Modifier[] { new Protected(), - new Static() }; + final Modifier[] modifiers = new Modifier[] { new Protected(), new Static() }; final KeYJavaType arrayType = arrayTypeReference.getKeYJavaType(); - final ProgramVariable paramLength = new LocationVariable( - new ProgramElementName("length"), integerType); - - final ParameterDeclaration param = new ParameterDeclaration( - new Modifier[0], new TypeRef(integerType), - new VariableSpecification(paramLength), false); - - final MethodDeclaration md = new MethodDeclaration(modifiers, - arrayTypeReference, new ProgramElementName( - IMPLICIT_ARRAY_CREATE), - new ParameterDeclaration[] { param }, null, - getCreateArrayBody(arrayTypeReference, paramLength), false); - - return new ProgramMethod(md, - arrayType, - arrayType, - PositionInfo.UNDEFINED, - heapSort, - heapCount); + final ProgramVariable paramLength = + new LocationVariable(new ProgramElementName("length"), integerType); + + final ParameterDeclaration param = new ParameterDeclaration(new Modifier[0], + new TypeRef(integerType), new VariableSpecification(paramLength), false); + + final MethodDeclaration md = new MethodDeclaration(modifiers, arrayTypeReference, + new ProgramElementName(IMPLICIT_ARRAY_CREATE), new ParameterDeclaration[] { param }, + null, getCreateArrayBody(arrayTypeReference, paramLength), false); + + return new ProgramMethod(md, arrayType, arrayType, PositionInfo.UNDEFINED, heapSort, + heapCount); } /** * returns the default value of the given type according to JLS \S 4.5.5 - * + * * @return the default value of the given type according to JLS \S 4.5.5 */ protected Expression getDefaultValue(Type type) { @@ -403,44 +351,36 @@ protected Expression getDefaultValue(Type type) { } /** - * returns the prepare method for arrays initialising all array fields with - * their default value + * returns the prepare method for arrays initialising all array fields with their default value */ - public IProgramMethod getPrepareArrayMethod(TypeRef arrayRef, - ProgramVariable length, Expression defaultValue, ImmutableList fields) { + public IProgramMethod getPrepareArrayMethod(TypeRef arrayRef, ProgramVariable length, + Expression defaultValue, ImmutableList fields) { final KeYJavaType arrayType = arrayRef.getKeYJavaType(); final IntLiteral zero = new IntLiteral(0); - - final LocalVariableDeclaration forInit = KeYJavaASTFactory. - declare(new ProgramElementName("i"), zero, integerType); - final ProgramVariable pv = (ProgramVariable) forInit.getVariables() - .get(0).getProgramVariable(); + final LocalVariableDeclaration forInit = + KeYJavaASTFactory.declare(new ProgramElementName("i"), zero, integerType); + + final ProgramVariable pv = + (ProgramVariable) forInit.getVariables().get(0).getProgramVariable(); - final For forLoop = - new For(new LoopInitializer[] { forInit }, - new LessThan(pv, new FieldReference(length, new ThisReference())), - new Expression[] { new PostIncrement(pv) }, - assign(new ArrayReference(new ThisReference(), - new Expression[] { pv }), defaultValue)); + final For forLoop = new For(new LoopInitializer[] { forInit }, + new LessThan(pv, new FieldReference(length, new ThisReference())), + new Expression[] { new PostIncrement(pv) }, + assign(new ArrayReference(new ThisReference(), new Expression[] { pv }), + defaultValue)); - final StatementBlock body = new StatementBlock( - new Statement[] { forLoop }); + final StatementBlock body = new StatementBlock(new Statement[] { forLoop }); - final MethodDeclaration md = new MethodDeclaration( - new Modifier[] { new Private()}, arrayRef, - new ProgramElementName( - PrepareObjectBuilder.IMPLICIT_OBJECT_PREPARE), + final MethodDeclaration md = new MethodDeclaration(new Modifier[] { new Private() }, + arrayRef, new ProgramElementName(PrepareObjectBuilder.IMPLICIT_OBJECT_PREPARE), new ParameterDeclaration[0], null, body, false); - return new ProgramMethod(md, - arrayType, - KeYJavaType.VOID_TYPE, - PositionInfo.UNDEFINED, - heapSort); + return new ProgramMethod(md, arrayType, KeYJavaType.VOID_TYPE, PositionInfo.UNDEFINED, + heapSort); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Declaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Declaration.java index fb20e0b6101..f05e0268b80 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Declaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Declaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.key_project.util.collection.ImmutableArray; @@ -6,14 +9,14 @@ /** - * Declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Declaration. taken from COMPOST and changed to achieve an immutable structure */ public interface Declaration extends NonTerminalProgramElement { /** * Get the modifiers. + * * @return the (original) list of modifiers wrapped . */ ImmutableArray getModifiers(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Dimension.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Dimension.java index cc15179cef6..cb2db22cab3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Dimension.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Dimension.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; public class Dimension { @@ -5,11 +8,11 @@ public class Dimension { private int dim; public Dimension(int dim) { - this.dim=dim; + this.dim = dim; } public int getDimension() { - return dim; + return dim; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Expression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Expression.java index 7ef9c345916..0e3196f73be 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Expression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Expression.java @@ -1,16 +1,19 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.reference.ExecutionContext; -/** Expression - * taken from COMPOST and changed to achieve an immutable structure +/** + * Expression taken from COMPOST and changed to achieve an immutable structure */ public interface Expression extends ProgramElement { - /** - * returns the {@link KeYJavaType} of an expression + /** + * returns the {@link KeYJavaType} of an expression */ 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/ExpressionContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ExpressionContainer.java index f54bafeb241..58ac66979e3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ExpressionContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ExpressionContainer.java @@ -1,25 +1,29 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Expression container. - * taken from COMPOST and changed to achieve an immutable structure + * Expression container. taken from COMPOST and changed to achieve an immutable structure */ public interface ExpressionContainer extends NonTerminalProgramElement { /** - * 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. */ int getExpressionCount(); /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ Expression getExpressionAt(int index); -} \ 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 cb846748be7..1354b8f1a0a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.key_project.util.ExtList; @@ -8,63 +11,66 @@ 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. - * + * Import. + * */ public class Import extends JavaNonTerminalProgramElement - implements TypeReferenceContainer, PackageReferenceContainer { + implements TypeReferenceContainer, PackageReferenceContainer { /** - * Multi import flag. + * Multi import flag. */ protected final boolean isMultiImport; /** - * Type reference infix. + * Type reference infix. */ protected final TypeReferenceInfix reference; - + /** * children may contain: TypeReference (for import), a Comment - * @param isMultiImport indicates whether the import contains multiple - * imports + * + * @param isMultiImport indicates whether the import contains multiple imports */ public Import(ExtList children, boolean isMultiImport) { - super(children); - reference=children.get(TypeReferenceInfix.class); - this.isMultiImport=isMultiImport; + super(children); + reference = children.get(TypeReferenceInfix.class); + this.isMultiImport = isMultiImport; } /** - * Import. + * Import. */ public Import() { - isMultiImport=false; - reference=null; + isMultiImport = false; + reference = null; } /** - * 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; + reference = t; + isMultiImport = multi; } /** - * Import. - * @param t a package reference. + * Import. + * + * @param t a package reference. */ public Import(PackageReference t) { - reference=t; - isMultiImport=true; + reference = t; + isMultiImport = true; } public SourceElement getLastElement() { @@ -72,9 +78,9 @@ public SourceElement getLastElement() { } /** - * 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() { @@ -82,33 +88,36 @@ 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 + */ public int getChildCount() { int result = 0; - if (reference != null) result++; + if (reference != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ 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. */ public int getTypeReferenceCount() { @@ -116,60 +125,64 @@ public int getTypeReferenceCount() { } /* - 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. - */ + * 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. + */ 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. + */ 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. + */ public TypeReferenceInfix getReference() { return reference; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnImport(this); + v.performActionOnImport(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printImport(this); } -} \ No newline at end of file +} 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 a50cca94a73..38a31bc6a67 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.abstraction.*; @@ -24,12 +27,10 @@ import recoder.service.KeYCrossReferenceSourceInfo; /** - * an instance serves as representation of a Java model underlying a DL - * formula. This class provides calls to access the elements of the Java - * model using the KeY data structures only. Implementation specific - * details like the use of Recoder is hidden in the field of type - * {@link KeYProgModelInfo}. This class can be extended to provide further - * services. + * an instance serves as representation of a Java model underlying a DL formula. This class provides + * calls to access the elements of the Java model using the KeY data structures only. Implementation + * specific details like the use of Recoder is hidden in the field of type {@link KeYProgModelInfo}. + * This class can be extended to provide further services. */ public final class JavaInfo { public static final Logger LOGGER = LoggerFactory.getLogger(JavaInfo.class); @@ -44,33 +45,29 @@ public final class JavaInfo { private KeYJavaType nullType = null; /** - * as accessed very often caches: - * KeYJavaType of - * java.lang.Object, java.lang.Clonable, java.io.Serializable - * in in this order + * as accessed very often caches: KeYJavaType of java.lang.Object, java.lang.Clonable, + * java.io.Serializable in in this order */ protected KeYJavaType[] commonTypes = new KeYJavaType[3]; - //some caches for the getKeYJavaType methods. + // some caches for the getKeYJavaType methods. private HashMap> sort2KJTCache = null; private HashMap type2KJTCache = null; private HashMap name2KJTCache = null; - private LRUCache, ImmutableList> commonSubtypeCache - = new LRUCache<>(200); + private LRUCache, ImmutableList> commonSubtypeCache = + new LRUCache<>(200); private int nameCachedSize = 0; private int sortCachedSize = 0; /** - * The default execution context is for the case of program statements on - * the top level. It is equivalent to a static class belonging the default - * package. This should only be used when using KeY in academic mode, if - * the verification conditions are generated they "must" start with a - * {@link de.uka.ilkd.key.java.statement.MethodBodyStatement} or a - * {@link de.uka.ilkd.key.java.statement.MethodFrame}, which contains a - * valid execution context. + * The default execution context is for the case of program statements on the top level. It is + * equivalent to a static class belonging the default package. This should only be used when + * using KeY in academic mode, if the verification conditions are generated they "must" start + * with a {@link de.uka.ilkd.key.java.statement.MethodBodyStatement} or a + * {@link de.uka.ilkd.key.java.statement.MethodFrame}, which contains a valid execution context. */ protected ExecutionContext defaultExecutionContext; @@ -101,8 +98,8 @@ public final class JavaInfo { /** - * creates a new JavaInfo object by giving a KeYProgModelInfo to access - * the Recoder SourceInfo and using the given {@link Services} object. + * creates a new JavaInfo object by giving a KeYProgModelInfo to access the Recoder SourceInfo + * and using the given {@link Services} object. */ protected JavaInfo(KeYProgModelInfo kpmi, Services s) { this.kpmi = kpmi; @@ -115,8 +112,7 @@ protected JavaInfo(JavaInfo proto, Services s) { } /** - * returns the underlying KeYProgModelInfo providing access to the - * Recoder structures. + * returns the underlying KeYProgModelInfo providing access to the Recoder structures. */ public KeYProgModelInfo getKeYProgModelInfo() { return kpmi; @@ -127,16 +123,16 @@ void setKeYProgModelInfo(KeYProgModelInfo kpmi) { } /** - * convenience method that returns the Recoder-to-KeY mapping underlying - * the KeYProgModelInfo of this JavaInfo + * convenience method that returns the Recoder-to-KeY mapping underlying the KeYProgModelInfo of + * this JavaInfo */ public KeYRecoderMapping rec2key() { return getKeYProgModelInfo().rec2key(); } /** - * copies this JavaInfo and uses the given Services object as the - * Services object of the copied JavaInfo + * copies this JavaInfo and uses the given Services object as the Services object of the copied + * JavaInfo * * @param serv the Services the copy will use and vice versa * @return a copy of the JavaInfo @@ -146,11 +142,9 @@ public JavaInfo copy(Services serv) { } /** - * Don't make this method public, use Services - * instead + * Don't make this method public, use Services instead *

    - * returns the TypeConverter to translate program parts to their - * logic equivalent + * returns the TypeConverter to translate program parts to their logic equivalent */ private TypeConverter getTypeConverter() { return services.getTypeConverter(); @@ -163,11 +157,10 @@ public Services getServices() { return services; } - //------------------- common services ---------------------- + // ------------------- common services ---------------------- /** - * returns the full name of a given {@link - * de.uka.ilkd.key.java.abstraction.KeYJavaType}. + * returns the full name of a given {@link de.uka.ilkd.key.java.abstraction.KeYJavaType}. * * @param t the KeYJavaType including the package prefix * @return the full name @@ -192,8 +185,7 @@ public void resetCaches() { } /** - * looks up the fully qualifying name given by a String - * in the list of all available + * looks up the fully qualifying name given by a String in the list of all available * KeYJavaTypes in the Java model * * @param fullName the String @@ -252,30 +244,31 @@ else if ("short[]".equals(s)) return "[S"; else if ("char[]".equals(s)) return "[C"; -// Strangely, this one is not n -// else if ("boolean[]".equals(s)) -// return "[Z"; -// Not sure if these are needed, commented out for efficiency -// else if ("char[]".equals(s)) -// return "[C"; -// else if ("double[]".equals(s)) -// return "[D"; -// else if ("float[]".equals(s)) -// return "[F"; -// else if ("\\real[]".equals(s)) -// return "[R"; -// else if ("\\bigint[]".equals(s)) -// return "[Y"; + // Strangely, this one is not n + // else if ("boolean[]".equals(s)) + // return "[Z"; + // Not sure if these are needed, commented out for efficiency + // else if ("char[]".equals(s)) + // return "[C"; + // else if ("double[]".equals(s)) + // return "[D"; + // else if ("float[]".equals(s)) + // return "[F"; + // else if ("\\real[]".equals(s)) + // return "[R"; + // else if ("\\bigint[]".equals(s)) + // return "[Y"; return s; } /** - * looks up a KeYJavaType with given name. If the name is a fully - * qualifying name with package prefix an element with this full name is - * taken. In case of an unqualified name to which no type is found in the default package, - * the type is looked for in package cjava.lang + * looks up a KeYJavaType with given name. If the name is a fully qualifying name with package + * prefix an element with this full name is taken. In case of an unqualified name to which no + * type is found in the default package, the type is looked for in package + * cjava.lang * - * @param className the fully qualified class name (or an unqualified name from package java.lang) + * @param className the fully qualified class name (or an unqualified name from package + * java.lang) * @return a class matching the name */ public KeYJavaType getTypeByClassName(String className) { @@ -291,11 +284,9 @@ public TypeDeclaration getTypeDeclaration(String fullName) { /** - * returns all known KeYJavaTypes of the current - * program type model + * returns all known KeYJavaTypes of the current program type model * - * @return all known KeYJavaTypes of the current - * program type model + * @return all known KeYJavaTypes of the current program type model */ public Set getAllKeYJavaTypes() { final Set result = new LinkedHashSet<>(); @@ -309,7 +300,8 @@ public Set getAllKeYJavaTypes() { public KeYJavaType getPrimitiveKeYJavaType(PrimitiveType type) { - if (type == null) throw new IllegalArgumentException("Given type is null"); + if (type == null) + throw new IllegalArgumentException("Given type is null"); if (type2KJTCache != null && type2KJTCache.containsKey(type)) { @@ -331,11 +323,12 @@ public KeYJavaType getPrimitiveKeYJavaType(PrimitiveType type) { Sort sort = sorts.lookup(ldtName); if (sort == null) { - throw new IllegalStateException("Could not find sort " + ldtName + " for type: " + type); + throw new IllegalStateException( + "Could not find sort " + ldtName + " for type: " + type); } KeYJavaType result = new KeYJavaType(type, sort); - if(type2KJTCache != null) { + if (type2KJTCache != null) { type2KJTCache.put(type, result); } @@ -356,22 +349,20 @@ public KeYJavaType getPrimitiveKeYJavaType(String typename) { } /** - * returns a KeYJavaType (either primitive of object type) having the - * full name of the given String fullName + * returns a KeYJavaType (either primitive of object type) having the full name of the given + * String fullName * * @param fullName a String with the type name to lookup */ public KeYJavaType getKeYJavaType(String fullName) { KeYJavaType result = getPrimitiveKeYJavaType(fullName); - return (result == null - ? getTypeByClassName(fullName) - : result); + return (result == null ? getTypeByClassName(fullName) : result); } /** - * returns true iff the given subType KeYJavaType is a sub type of the - * given KeYJavaType superType. + * returns true iff the given subType KeYJavaType is a sub type of the given KeYJavaType + * superType. */ public boolean isSubtype(KeYJavaType subType, KeYJavaType superType) { return kpmi.isSubtype(subType, superType); @@ -383,8 +374,8 @@ public boolean isInterface(KeYJavaType t) { /** - * Checks whether the type is declared as final. - * Returns false for all primitive and array types. + * Checks whether the type is declared as final. Returns false for all primitive and array + * types. * * @param kjt * @return @@ -407,8 +398,9 @@ public static boolean isPrivate(KeYJavaType kjt) { public static boolean isVisibleTo(SpecificationElement ax, KeYJavaType visibleTo) { final KeYJavaType kjt = ax.getKJT(); // elements of private types are not visible - if (isPrivate(kjt)) return kjt.equals(visibleTo); - //TODO: package information not yet available + if (isPrivate(kjt)) + return kjt.equals(visibleTo); + // TODO: package information not yet available // BUGFIX: package-private is understood as private (see bug #1268) final boolean visibleToPackage = false; final VisibilityModifier visibility = ax.getVisibility(); @@ -522,49 +514,42 @@ public ImmutableList getConstructors(KeYJavaType kjt) { return kpmi.getConstructors(kjt); } - public IProgramMethod getConstructor(KeYJavaType kjt, - ImmutableList signature) { + public IProgramMethod getConstructor(KeYJavaType kjt, ImmutableList signature) { return kpmi.getConstructor(kjt, signature); } /** - * returns the program methods defined in the given KeYJavaType with name - * m and the list of types as signature of the method + * returns the program methods defined in the given KeYJavaType with name m and the list of + * types as signature of the method * - * @param classType the KeYJavaType of the class where to look for the - * method + * @param classType the KeYJavaType of the class where to look for the method * @param methodName the name of the method - * @param signature a IList with the arguments types - * @param context the KeYJavaType of the class context from where - * the method is called + * @param signature a IList with the arguments types + * @param context the KeYJavaType of the class context from where the method is called * @return a matching program method */ - public IProgramMethod getProgramMethod(KeYJavaType classType, - String methodName, - ImmutableList signature, - KeYJavaType context) { + public IProgramMethod getProgramMethod(KeYJavaType classType, String methodName, + ImmutableList signature, KeYJavaType context) { return kpmi.getProgramMethod(classType, methodName, signature, context); } - public IProgramMethod getProgramMethod(KeYJavaType classType, - String methodName, - ImmutableArray signature, - KeYJavaType context) { + public IProgramMethod getProgramMethod(KeYJavaType classType, String methodName, + ImmutableArray signature, KeYJavaType context) { return getProgramMethod(classType, methodName, signature.toImmutableList(), context); } private IProgramMethod getProgramMethodFromPartialSignature(KeYJavaType classType, - String methodName, - List> signature, - ImmutableList partialSignature, - KeYJavaType context) { + String methodName, List> signature, + ImmutableList partialSignature, KeYJavaType context) { if (signature.isEmpty()) { return getProgramMethod(classType, methodName, partialSignature, context); } else { List types = signature.get(0); assert !types.isEmpty(); for (KeYJavaType t : types) { - IProgramMethod programMethod = getProgramMethodFromPartialSignature(classType, methodName, signature.subList(1, signature.size()), partialSignature.append(t), context); + IProgramMethod programMethod = getProgramMethodFromPartialSignature(classType, + methodName, signature.subList(1, signature.size()), + partialSignature.append(t), context); if (programMethod != null) { return programMethod; } @@ -574,39 +559,30 @@ private IProgramMethod getProgramMethodFromPartialSignature(KeYJavaType classTyp } /* - * Takes for each signature entry a list of types for all of which - * a corresponding IProgramMethod is looked up. Several types must - * be considered if for one sort several KeYJavaTypes must be considered. - * This is the case for sort int in KeY, which has the following as possible - * corresponding KeYJavaTypes: - * char, byte, short, int, long - */ - public IProgramMethod getProgramMethod(KeYJavaType classType, - String methodName, - List> signature, - KeYJavaType context) { + * Takes for each signature entry a list of types for all of which a corresponding + * IProgramMethod is looked up. Several types must be considered if for one sort several + * KeYJavaTypes must be considered. This is the case for sort int in KeY, which has the + * following as possible corresponding KeYJavaTypes: char, byte, short, int, long + */ + public IProgramMethod getProgramMethod(KeYJavaType classType, String methodName, + List> signature, KeYJavaType context) { ImmutableList partialSignature = ImmutableSLList.nil(); - return getProgramMethodFromPartialSignature(classType, methodName, signature, partialSignature, context); + return getProgramMethodFromPartialSignature(classType, methodName, signature, + partialSignature, context); } /** - * returns the program method defined in the KeYJavaType of the program - * variable clv, with the name m, and the KeYJavaTypes of the given array - * of program variables as signatures. + * returns the program method defined in the KeYJavaType of the program variable clv, with the + * name m, and the KeYJavaTypes of the given array of program variables as signatures. * - * @param classType the KeYJavaType of the class where to look for the - * method + * @param classType the KeYJavaType of the class where to look for the method * @param methodName the name of the method - * @param args an array of ProgramVariables as the arguments of the - * method - * @param context the KeYJavaType of the class context from where - * the method is called + * @param args an array of ProgramVariables as the arguments of the method + * @param context the KeYJavaType of the class context from where the method is called * @return a matching program method */ - public IProgramMethod getProgramMethod(KeYJavaType classType, - String methodName, - ProgramVariable[] args, - KeYJavaType context) { + public IProgramMethod getProgramMethod(KeYJavaType classType, String methodName, + ProgramVariable[] args, KeYJavaType context) { ImmutableList types = ImmutableSLList.nil(); for (int i = args.length - 1; i >= 0; i--) { types = types.prepend(args[i].getKeYJavaType()); @@ -614,17 +590,14 @@ public IProgramMethod getProgramMethod(KeYJavaType classType, return getProgramMethod(classType, methodName, types, context); } - public IProgramMethod getToplevelPM(KeYJavaType kjt, - String methodName, - ImmutableList sig) { + public IProgramMethod getToplevelPM(KeYJavaType kjt, String methodName, + ImmutableList sig) { return findToplevelPM(kjt, methodName, sig, kjt); } /* This method has been introduced as bugfix to #1487 */ - private IProgramMethod findToplevelPM(KeYJavaType kjt, - String methodName, - ImmutableList sig, - KeYJavaType context) { + private IProgramMethod findToplevelPM(KeYJavaType kjt, String methodName, + ImmutableList sig, KeYJavaType context) { ImmutableList allSupertypes = getAllSupertypes(kjt); ImmutableList removed = allSupertypes.removeAll(kjt); @@ -640,11 +613,8 @@ private IProgramMethod findToplevelPM(KeYJavaType kjt, public IProgramMethod getToplevelPM(KeYJavaType kjt, IProgramMethod pm) { final String methodName = pm.getName(); - final ImmutableList sig - = ImmutableSLList.nil() - .append(pm.getParamTypes() - .toArray( - new KeYJavaType[pm.getNumParams()])); + final ImmutableList sig = ImmutableSLList.nil() + .append(pm.getParamTypes().toArray(new KeYJavaType[pm.getNumParams()])); return getToplevelPM(kjt, methodName, sig); } @@ -663,11 +633,8 @@ public Term getStaticProgramMethodTerm(String methodName, Term[] args, String cl return getTermFromProgramMethod(pm, methodName, className, args, null); } - public Term getProgramMethodTerm(Term prefix, - String methodName, - Term[] args, - String className, - boolean traverseHierarchy) { + public Term getProgramMethodTerm(Term prefix, String methodName, Term[] args, String className, + boolean traverseHierarchy) { /* * This is just a safety measure. To avoid null pointers, try to call @@ -694,28 +661,30 @@ public Term getProgramMethodTerm(Term prefix, pm = getProgramMethod(next, methodName, signature, next); if (pm != null && pm.isPrivate() && !next.equals(classKJT)) { /* - * Private methods from supertypes are not visible in their - * subtypes. They will not be selected here. + * Private methods from supertypes are not visible in their subtypes. They will + * not be selected here. */ pm = null; } } } else { /* - * Do not traverse type hierarchy. pm stays null in case classKJT - * does not contain a method with the specified name. + * Do not traverse type hierarchy. pm stays null in case classKJT does not contain a + * method with the specified name. */ pm = getProgramMethod(classKJT, methodName, signature, classKJT); } return getTermFromProgramMethod(pm, methodName, className, args, prefix); } - public Term getTermFromProgramMethod(IProgramMethod pm, String methodName, String className, Term[] args, Term prefix) throws IllegalArgumentException { + public Term getTermFromProgramMethod(IProgramMethod pm, String methodName, String className, + Term[] args, Term prefix) throws IllegalArgumentException { if (pm == null) { - throw new IllegalArgumentException("Program method " + methodName - + " in " + className + " not found."); + throw new IllegalArgumentException( + "Program method " + methodName + " in " + className + " not found."); } - Term[] subs = new Term[pm.getHeapCount(services) * pm.getStateCount() + args.length + (pm.isStatic() ? 0 : 1)]; + Term[] subs = new Term[pm.getHeapCount(services) * pm.getStateCount() + args.length + + (pm.isStatic() ? 0 : 1)]; int offset = 0; for (LocationVariable heap : HeapContext.getModHeaps(services, false)) { if (offset >= pm.getHeapCount(services)) { @@ -732,17 +701,15 @@ public Term getTermFromProgramMethod(IProgramMethod pm, String methodName, Strin className = translateArrayType(className); assert pm.getReturnType() != null; if (pm.isVoid()) { - throw new IllegalArgumentException("Program method " + methodName - + " in " + className + " must have" - + " a non-void type."); + throw new IllegalArgumentException("Program method " + methodName + " in " + className + + " must have" + " a non-void type."); } return services.getTermBuilder().tf().createTerm(pm, subs); } /** - * returns all direct supertypes (local declared types in extends and - * implements) if extends is not given explict java.lang.Object is added - * (it is not added for interfaces) + * returns all direct supertypes (local declared types in extends and implements) if extends is + * not given explict java.lang.Object is added (it is not added for interfaces) */ public ImmutableList getDirectSuperTypes(KeYJavaType type) { final ClassType javaType = (ClassType) type.getJavaType(); @@ -771,8 +738,7 @@ public ImmutableList getDirectSuperTypes(KeYJavaType type) { /** * retrieves the direct extended superclass for the given class * - * @param type the KeYJavaType of the type whose superclass - * has to be determined + * @param type the KeYJavaType of the type whose superclass has to be determined * @return KeYJavaType of the extended supertype */ public KeYJavaType getSuperclass(KeYJavaType type) { @@ -816,8 +782,7 @@ private ImmutableList getKeYJavaTypes(ImmutableArray= 0; i--) { final Expression argument = args.get(i); - result = result.prepend - (getTypeConverter().getKeYJavaType(argument)); + result = result.prepend(getTypeConverter().getKeYJavaType(argument)); } } return result; @@ -827,18 +792,17 @@ private ImmutableList getKeYJavaTypes(ImmutableArray of which we try to construct a - * signature + * @param arguments ArrayOf of which we try to construct a signature * @return the signature */ - public ImmutableList createSignature(ImmutableArray arguments) { + public ImmutableList createSignature( + ImmutableArray arguments) { return getKeYJavaTypes(arguments); } /** - * retrieves all attributes locally declared in class cl - * (inclusive the implicit attributes) - * The returned list is in source code order. + * retrieves all attributes locally declared in class cl (inclusive the implicit + * attributes) The returned list is in source code order. * * @param classDecl the ClassDeclaration whose attributes shall be collected * @return all attributes declared in class cl @@ -848,11 +812,10 @@ public ImmutableList getAllFields(TypeDeclaration classDecl) { } /** - * retrieves all implicit attributes locally declared in the given class - * The returned list is in source code order. + * retrieves all implicit attributes locally declared in the given class The returned list is in + * source code order. * - * @param cl the ClassDeclaration where to look for the implicit - * attributes + * @param cl the ClassDeclaration where to look for the implicit attributes * @return all implicit attributes declared in cl */ public ImmutableList getImplicitFields(ClassDeclaration cl) { @@ -860,18 +823,15 @@ public ImmutableList getImplicitFields(ClassDeclaration cl) { } /** - * retrieves all attributes locally declared in class cl - * (inclusive the implicit attributes) satisfying the given filter - * The returned list is in source code order. + * retrieves all attributes locally declared in class cl (inclusive the implicit + * attributes) satisfying the given filter The returned list is in source code order. * * @param classDecl the ClassDeclaration whose attributes shall be collected - * @param filter the Filter to be satisifed by the attributes to - * be returned - * @return all attributes declared in class cl satisfying the - * given filter + * @param filter the Filter to be satisifed by the attributes to be returned + * @return all attributes declared in class cl satisfying the given filter */ private ImmutableList filterLocalDeclaredFields(TypeDeclaration classDecl, - Filter filter) { + Filter filter) { ImmutableList fields = ImmutableSLList.nil(); final ImmutableArray members = classDecl.getMembers(); for (int i = members.size() - 1; i >= 0; i--) { @@ -890,19 +850,18 @@ private ImmutableList filterLocalDeclaredFields(TypeDeclaration classDecl return fields; } - //----------------- parsing services -------------------------- + // ----------------- parsing services -------------------------- /** - * reads a Java block given as a string java as it was in the given - * TypeDeclaration asIn. + * reads a Java block given as a string java as it was in the given TypeDeclaration asIn. */ public JavaBlock readJavaBlock(String java, TypeDeclaration asIn) { ClassDeclaration cd = null; if (asIn instanceof ClassDeclaration) { cd = (ClassDeclaration) asIn; } else { - LOGGER.debug("Reading Java Block from an InterfaceDeclaration:" - + " Not yet implemented."); + LOGGER.debug( + "Reading Java Block from an InterfaceDeclaration:" + " Not yet implemented."); } final NamespaceSet nss = services.getNamespaces().copy(); final JavaBlock block = kpmi.readBlock(java, cd, nss); @@ -932,25 +891,21 @@ public JavaBlock readJavaBlock(String java) { * reads a Java statement not necessarily a block */ public ProgramElement readJava(String java) { - return ((StatementBlock) readJavaBlock("{" + java + "}") - .program()).getChildAt(0); + return ((StatementBlock) readJavaBlock("{" + java + "}").program()).getChildAt(0); } /** * retrieves a field with the given name out of the list * * @param programName a String with the name of the field to be looked for - * @param fields the IList where we have to look for the field - * @return the program variable of the given name or null if not - * found + * @param fields the IList where we have to look for the field + * @return the program variable of the given name or null if not found */ - private final ProgramVariable find(String programName, - ImmutableList fields) { + private final ProgramVariable find(String programName, ImmutableList fields) { for (Field field1 : fields) { Field field = field1; if (programName.equals(field.getProgramName())) { - return (ProgramVariable) - field.getProgramVariable(); + return (ProgramVariable) field.getProgramVariable(); } } return null; @@ -959,10 +914,9 @@ private final ProgramVariable find(String programName, /** * extracts all fields out of fielddeclaration * - * @param field the FieldDeclaration of which the field - * specifications have to be extracted - * @return a IList the includes all field specifications found - * int the field declaration of the given list + * @param field the FieldDeclaration of which the field specifications have to be extracted + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ private final ImmutableList getFields(FieldDeclaration field) { ImmutableList result = ImmutableSLList.nil(); @@ -974,42 +928,38 @@ private final ImmutableList getFields(FieldDeclaration field) { } /** - * extracts all field specifications out of the given - * list. Therefore it descends into field declarations. + * extracts all field specifications out of the given list. Therefore it descends into field + * declarations. * - * @param list the ArrayOf with the members of a - * type declaration - * @return a IList the includes all field specifications found - * int the field declaration of the given list + * @param list the ArrayOf with the members of a type declaration + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ private ImmutableList getFields(ImmutableArray list) { ImmutableList result = ImmutableSLList.nil(); for (int i = list.size() - 1; i >= 0; i--) { final MemberDeclaration pe = list.get(i); if (pe instanceof FieldDeclaration) { - result = result.append - (getFields((FieldDeclaration) pe)); + result = result.append(getFields((FieldDeclaration) pe)); } } return result; } /** - * returns the programvariable for the specified attribute. The attribute - * has to be fully qualified, i.e. declarationType::attributeName + * returns the programvariable for the specified attribute. The attribute has to be fully + * qualified, i.e. declarationType::attributeName * - * @param fullyQualifiedName the String with the fully qualified attribute - * name + * @param fullyQualifiedName the String with the fully qualified attribute name * @return an attribute program variable of the given name - * @throws IllegalArgumentException if the given name is not fully - * qualified + * @throws IllegalArgumentException if the given name is not fully qualified */ public ProgramVariable getAttribute(String fullyQualifiedName) { final int idx = fullyQualifiedName.indexOf("::"); if (idx == -1) { - throw new IllegalArgumentException(fullyQualifiedName + - " is not a fully qualified attribute name"); + throw new IllegalArgumentException( + fullyQualifiedName + " is not a fully qualified attribute name"); } return getAttribute(fullyQualifiedName.substring(idx + 2), @@ -1018,19 +968,15 @@ public ProgramVariable getAttribute(String fullyQualifiedName) { /** - * returns the programvariable for the specified attribute declared in - * the specified class + * returns the programvariable for the specified attribute declared in the specified class * - * @param programName the String with the name of the attribute - * @param qualifiedClassName the String with the full (inclusive package) qualified - * class name + * @param programName the String with the name of the attribute + * @param qualifiedClassName the String with the full (inclusive package) qualified class name * @return the attribute program variable of the given name - * @throws IllegalArgumentException if the qualified class name is empty or - * null + * @throws IllegalArgumentException if the qualified class name is empty or null * @throws UnknownJavaTypeException if the qualified name refers to an unknown type */ - public ProgramVariable getAttribute(String programName, - String qualifiedClassName) { + public ProgramVariable getAttribute(String programName, String qualifiedClassName) { if (qualifiedClassName == null || qualifiedClassName.length() == 0) { throw new IllegalArgumentException("Missing qualified classname"); } @@ -1054,31 +1000,25 @@ public ProgramVariable getAttribute(String programName, /** - * returns the program variable representing the attribute of the given - * name declared locally in class classType + * returns the program variable representing the attribute of the given name declared locally in + * class classType * * @return the attribute of the given name declared in classType */ - public ProgramVariable getAttribute(final String name, - KeYJavaType classType) { + public ProgramVariable getAttribute(final String name, KeYJavaType classType) { if (classType.getJavaType() instanceof ArrayDeclaration) { ProgramVariable res = find(name, - getFields(((ArrayDeclaration) classType.getJavaType()) - .getMembers())); + getFields(((ArrayDeclaration) classType.getJavaType()).getMembers())); if (res == null) { return getAttribute(name, getJavaLangObject()); } return res; } else { - final ImmutableList list = kpmi - .getAllFieldsLocallyDeclaredIn(classType); + final ImmutableList list = kpmi.getAllFieldsLocallyDeclaredIn(classType); for (Field aList : list) { final Field f = aList; - if (f != null - && (f.getName().equals(name) || f.getProgramName() - .equals(name))) { - return (ProgramVariable) f - .getProgramVariable(); + if (f != null && (f.getName().equals(name) || f.getProgramName().equals(name))) { + return (ProgramVariable) f.getProgramVariable(); } } } @@ -1086,8 +1026,7 @@ public ProgramVariable getAttribute(final String name, } /** - * returns an attribute named attributeName declared locally - * in object type s + * returns an attribute named attributeName declared locally in object type s */ public ProgramVariable getAttribute(String attributeName, Sort s) { assert s.extendsTrans(objectSort()); @@ -1095,13 +1034,13 @@ public ProgramVariable getAttribute(String attributeName, Sort s) { } /* - * Traverses the type hierarchy to find the first {@link KeYJavaType} in which - * a field of name {@code fieldName} is declared, starting from parameter {@code kjt}. And - * then returns a {@link ProgramVariable} for that field/type combination. - - * Type detection in this method is canonical, i.e. selecting a field of name - * {@code fieldName} on an object of (dynamic) type {@code kjt} during Java program - * execution would end up in the same type as the type of the returned {@link ProgramVariable}. + * Traverses the type hierarchy to find the first {@link KeYJavaType} in which a field of name + * {@code fieldName} is declared, starting from parameter {@code kjt}. And then returns a {@link + * ProgramVariable} for that field/type combination. + * + * Type detection in this method is canonical, i.e. selecting a field of name {@code fieldName} + * on an object of (dynamic) type {@code kjt} during Java program execution would end up in the + * same type as the type of the returned {@link ProgramVariable}. */ public ProgramVariable getCanonicalFieldProgramVariable(String fieldName, KeYJavaType kjt) { ImmutableList allAttributes = getAllAttributes(fieldName, kjt, false); @@ -1112,42 +1051,33 @@ public ProgramVariable getCanonicalFieldProgramVariable(String fieldName, KeYJav } } - public ImmutableList getAllAttributes(String programName, - KeYJavaType type) { + public ImmutableList getAllAttributes(String programName, KeYJavaType type) { return getAllAttributes(programName, type, true); } /** - * returns a list of all attributes with the given program name - * declared in one of type's sub- or supertype including - * its own attributes - * Attention: + * returns a list of all attributes with the given program name declared in one of + * type's sub- or supertype including its own attributes Attention: * The type must not denote the null type * * - * @param programName the String with name of the attribute as declared - * in a program - * @param type the KeYJavaType specifying the part of the hierarchy - * where to look for - * @param traverseSubtypes The method will visit subtypes of {@code type} - * while traversing its type hierarchy iff this is set to true. Otherwise - * only supertypes will be visited. + * @param programName the String with name of the attribute as declared in a program + * @param type the KeYJavaType specifying the part of the hierarchy where to look for + * @param traverseSubtypes The method will visit subtypes of {@code type} while traversing its + * type hierarchy iff this is set to true. Otherwise only supertypes will be visited. * @return list of found attributes with name programName */ - public ImmutableList getAllAttributes(String programName, - KeYJavaType type, - boolean traverseSubtypes) { - ImmutableList result = - ImmutableSLList.nil(); + public ImmutableList getAllAttributes(String programName, KeYJavaType type, + boolean traverseSubtypes) { + ImmutableList result = ImmutableSLList.nil(); if (!(type.getSort().extendsTrans(objectSort()))) { return result; } if (type.getJavaType() instanceof ArrayType) { - ProgramVariable var = find(programName, getFields - (((ArrayDeclaration) type.getJavaType()) - .getMembers())); + ProgramVariable var = find(programName, + getFields(((ArrayDeclaration) type.getJavaType()).getMembers())); if (var != null) { result = result.prepend(var); } @@ -1168,7 +1098,7 @@ public ImmutableList getAllAttributes(String programName, } hierarchy = hierarchy.prepend(kpmi.getAllSupertypes(type)); - //weigl: unclear assertion: assert hierarchy.head() == type; + // weigl: unclear assertion: assert hierarchy.head() == type; final Iterator it = hierarchy.iterator(); @@ -1187,10 +1117,11 @@ public ImmutableList getAllAttributes(String programName, protected void fillCommonTypesCache() { - if (commonTypesCacheValid) return; + if (commonTypesCacheValid) + return; - final String[] fullNames = new String[]{"java.lang.Object", - "java.lang.Cloneable", "java.io.Serializable"}; + final String[] fullNames = + new String[] { "java.lang.Object", "java.lang.Cloneable", "java.io.Serializable" }; for (int i = 0; i < fullNames.length; i++) { commonTypes[i] = getTypeByClassName(fullNames[i]); @@ -1267,8 +1198,7 @@ public Sort nullSort() { } /** - * tests if sort represents java.lang.Object, java.lang.Cloneable or - * java.io.Serializable + * tests if sort represents java.lang.Object, java.lang.Cloneable or java.io.Serializable */ public boolean isAJavaCommonSort(Sort sort) { if (!commonTypesCacheValid) { @@ -1283,21 +1213,20 @@ public boolean isAJavaCommonSort(Sort sort) { } /** - * returns the KeYJavaType representing the type of 'null' + * returns the KeYJavaType representing the type of 'null' */ public KeYJavaType getNullType() { if (nullType == null) { nullType = getTypeByClassName("null"); - Debug.assertTrue(nullType != null - , "we should already have it in the map"); + Debug.assertTrue(nullType != null, "we should already have it in the map"); } return nullType; } /** - * returns the default execution context. This is equiavlent to executing the program - * in a static method of a class placed in the default package + * returns the default execution context. This is equiavlent to executing the program in a + * static method of a class placed in the default package * * @return the default execution context */ @@ -1307,10 +1236,9 @@ public ExecutionContext getDefaultExecutionContext() { if (!kpmi.rec2key().parsedSpecial()) { readJava("{}"); } - final KeYJavaType kjt = - getTypeByClassName(DEFAULT_EXECUTION_CONTEXT_CLASS); - defaultExecutionContext = - new ExecutionContext(new TypeRef(kjt), getToplevelPM(kjt, DEFAULT_EXECUTION_CONTEXT_METHOD, ImmutableSLList.nil()), null); + final KeYJavaType kjt = getTypeByClassName(DEFAULT_EXECUTION_CONTEXT_CLASS); + defaultExecutionContext = new ExecutionContext(new TypeRef(kjt), getToplevelPM(kjt, + DEFAULT_EXECUTION_CONTEXT_METHOD, ImmutableSLList.nil()), null); } return defaultExecutionContext; } @@ -1353,28 +1281,24 @@ private ImmutableList getSuperSorts(Sort sort) { } /** - * looks up for a field of the given program name - * visible in the specified class type belonging to the type - * or one of its supertypes + * looks up for a field of the given program name visible in the specified class type + * belonging to the type or one of its supertypes * - * @param programName the String containing the name of the - * field to be looked up. The name is in short notation, - * i.e. not fully qualified - * @param classType the KeYJavaType of the class used as context + * @param programName the String containing the name of the field to be looked up. The name is + * in short notation, i.e. not fully qualified + * @param classType the KeYJavaType of the class used as context * @return the field of the given name */ - public ProgramVariable lookupVisibleAttribute(String programName, - KeYJavaType classType) { + public ProgramVariable lookupVisibleAttribute(String programName, KeYJavaType classType) { return find(programName, kpmi.getAllVisibleFields(classType)); } /** - * returns the list of all common subtypes of types k1 and k2 - * (inclusive one of them if they are equal or subtypes themselves) - * attention: Null is not a jav atype only a logic sort, i.e. - * if null is the only element shared between k1 and k2 - * the returned list will be empty + * returns the list of all common subtypes of types k1 and k2 (inclusive one + * of them if they are equal or subtypes themselves) attention: Null is not a jav atype + * only a logic sort, i.e. if null is the only element shared between k1 and + * k2 the returned list will be empty * * @param k1 the first KeYJavaType denoting a class type * @param k2 the second KeYJavaType denoting a classtype @@ -1416,11 +1340,8 @@ public ImmutableList getCommonSubtypes(KeYJavaType k1, KeYJavaType public ProgramVariable getArrayLength() { if (length == null) { final SuperArrayDeclaration sad = - (SuperArrayDeclaration) - rec2key().getSuperArrayType().getJavaType(); - length = - (ProgramVariable) sad.length().getVariables(). - get(0).getProgramVariable(); + (SuperArrayDeclaration) rec2key().getSuperArrayType().getJavaType(); + length = (ProgramVariable) sad.length().getVariables().get(0).getProgramVariable(); assert "length".equals(length.name().toString()) : "Wrong array length"; } @@ -1428,24 +1349,33 @@ public ProgramVariable getArrayLength() { } /** - * Returns the special symbol <inv> which stands for the class invariant of an object. + * Returns the special symbol <inv> which stands for the class invariant of + * an object. * * @see #getInvProgramVar() */ public IObserverFunction getInv() { - // TODO: Create function when source code is parsed and register it in namespace. Return only function from namespace here. No lazy creation to ensure that all proofs of the same proof environment have the same symbol. - if (inv == null || inv.getHeapCount(services) != HeapContext.getModHeaps(services, false).size()) { // TODO: Why is the initial check with the heaps needed? - inv = (ObserverFunction) services.getNamespaces().functions().lookup(ObserverFunction.createName("", getJavaLangObject())); + // TODO: Create function when source code is parsed and register it in namespace. Return + // only function from namespace here. No lazy creation to ensure that all proofs of the same + // proof environment have the same symbol. + if (inv == null + || inv.getHeapCount(services) != HeapContext.getModHeaps(services, false).size()) { // TODO: + // Why + // is + // the + // initial + // check + // with + // the + // heaps + // needed? + inv = (ObserverFunction) services.getNamespaces().functions() + .lookup(ObserverFunction.createName("", getJavaLangObject())); if (inv == null) { - inv = new ObserverFunction("", - Sort.FORMULA, - null, - services.getTypeConverter().getHeapLDT().targetSort(), - getJavaLangObject(), - false, - new ImmutableArray<>(), - HeapContext.getModHeaps(services, false).size(), - 1); + inv = new ObserverFunction("", Sort.FORMULA, null, + services.getTypeConverter().getHeapLDT().targetSort(), getJavaLangObject(), + false, new ImmutableArray<>(), + HeapContext.getModHeaps(services, false).size(), 1); services.getNamespaces().functions().add(inv); } } @@ -1453,39 +1383,37 @@ public IObserverFunction getInv() { } /** - * Returns the special program variable symbol <inv> - * which stands for the class invariant of an object. + * Returns the special program variable symbol <inv> which stands for the + * class invariant of an object. * * @see #getInv() */ public ProgramVariable getInvProgramVar() { if (invProgVar == null) { ProgramElementName pen = new ProgramElementName("", "java.lang.Object"); - invProgVar = new LocationVariable(pen, - getPrimitiveKeYJavaType(PrimitiveType.JAVA_BOOLEAN), - getJavaLangObject(), false, true); + invProgVar = + new LocationVariable(pen, getPrimitiveKeYJavaType(PrimitiveType.JAVA_BOOLEAN), + getJavaLangObject(), false, true); } return invProgVar; } /** - * Returns the special symbol <staticInv> which stands for the static invariant of a type. + * Returns the special symbol <staticInv> which stands for the static + * invariant of a type. */ public IObserverFunction getStaticInv(KeYJavaType target) { - // TODO: Create functions when source code is parsed and register them in namespace. Return only functions from namespace here. No lazy creation to ensure that all proofs of the same proof environment have the same <$inv> symbols. + // TODO: Create functions when source code is parsed and register them in namespace. Return + // only functions from namespace here. No lazy creation to ensure that all proofs of the + // same proof environment have the same <$inv> symbols. ObserverFunction inv = staticInvs.get(target); if (inv == null) { - inv = (ObserverFunction) services.getNamespaces().functions().lookup(ObserverFunction.createName("<$inv>", target)); + inv = (ObserverFunction) services.getNamespaces().functions() + .lookup(ObserverFunction.createName("<$inv>", target)); if (inv == null) { - inv = new ObserverFunction("<$inv>", - Sort.FORMULA, - null, - services.getTypeConverter().getHeapLDT().targetSort(), - target, - true, - new ImmutableArray<>(), - HeapContext.getModHeaps(services, false).size(), - 1); + inv = new ObserverFunction("<$inv>", Sort.FORMULA, null, + services.getTypeConverter().getHeapLDT().targetSort(), target, true, + new ImmutableArray<>(), HeapContext.getModHeaps(services, false).size(), 1); services.getNamespaces().functions().add(inv); } staticInvs.put(target, inv); @@ -1496,11 +1424,11 @@ public IObserverFunction getStaticInv(KeYJavaType target) { /** * This is used for pretty printing observer terms. * - * @param method the program method. + * @param method the program method. * @param context the KeYJavaType. * @return whether the program method is canonical. - * @throws NullPointerException e.g., if the receiver of the observer happens to be - * replaced by "null". + * @throws NullPointerException e.g., if the receiver of the observer happens to be replaced by + * "null". */ public boolean isCanonicalProgramMethod(IProgramMethod method, KeYJavaType context) throws NullPointerException { @@ -1514,7 +1442,8 @@ public boolean isCanonicalProgramMethod(IProgramMethod method, KeYJavaType conte */ ImmutableList allSupertypes = kpmi.getAllSupertypes(context); Iterator iterator = allSupertypes.iterator(); - iterator.next(); // skip first element (it equals context and was already processed above) + iterator.next(); // skip first element (it equals context and was already processed + // above) while (iterator.hasNext()) { KeYJavaType next = iterator.next(); IProgramMethod programMethod = getProgramMethod(next, name, paramTypes, context); @@ -1542,8 +1471,8 @@ public boolean isSatisfiedBy(ProgramElement pe) { }; /** - * this filter is satisfied if the given program element is an - * instanceof ImplicitFieldSpecification + * this filter is satisfied if the given program element is an instanceof + * ImplicitFieldSpecification */ final static Filter IMPLICITFIELD = new Filter() { @@ -1553,23 +1482,20 @@ public boolean isSatisfiedBy(ProgramElement pe) { }; /** - * decides whether the given program element fulfills the filter condition - * or not + * decides whether the given program element fulfills the filter condition or not * * @param pe the ProgramElement to be filtered - * @return true iff program element pe satisfies the filter - * condition + * @return true iff program element pe satisfies the filter condition */ public abstract boolean isSatisfiedBy(ProgramElement pe); } /** - * retrieves the KeYJavaType of the given type name. If the type is not fully qualified, - * it is looked for in the context of the containerType first and - * then in the java.lang - * package. + * retrieves the KeYJavaType of the given type name. If the type is not fully qualified, it is + * looked for in the context of the containerType first and then in the + * java.lang package. * - * @param name the name of the type (if possible fully qualified) + * @param name the name of the type (if possible fully qualified) * @param containerType the KeYJavaType of the context in which the type should be resolved * @return the KeYJavaType of the given type or null if type name is unknown */ @@ -1581,14 +1507,13 @@ public KeYJavaType getTypeByClassName(String name, KeYJavaType containerType) { } if (result == null) { - final int lastSep = (containerType == null ? - -1 : containerType.getFullName().lastIndexOf('.')); + final int lastSep = + (containerType == null ? -1 : containerType.getFullName().lastIndexOf('.')); // try if class is in same package if (lastSep >= 0) { result = getTypeByClassName( - containerType.getFullName().substring(0, lastSep) + - "." + name); + containerType.getFullName().substring(0, lastSep) + "." + name); } if (result == null) { 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 3a41d6a692b..86887fbc7e2 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.key_project.util.ExtList; @@ -7,154 +10,151 @@ import de.uka.ilkd.key.util.Debug; /** - * Top level implementation of a Java {@link NonTerminalProgramElement}. - * taken from COMPOST and changed to achieve an immutable structure + * 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 { + + public JavaNonTerminalProgramElement() {} + - /** * Java program element. + * * @param list as ExtList with children of the node */ public JavaNonTerminalProgramElement(ExtList list) { super(list); } - + 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 - * implemented easy). - * - * + * 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 implemented easy). + * + * * @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 + * @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 varns, String s); -} \ No newline at end of file +} 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 4739bfc6d4e..61d2e8921c6 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.BufferedReader; @@ -19,25 +22,25 @@ import de.uka.ilkd.key.util.KeYResourceManager; /** - * This is a special {@link FileCollection} which allows to retrieve the - * internally stored java boot sources and to iterate over them. - * + * 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. - * + * 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. - * + * {@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 { /** - * The location where the libraries to be parsed can be found. It will be - * used as a resource path relative to the path of the package. + * The location where the libraries to be parsed can be found. It will be used as a resource + * path relative to the path of the package. */ public static final String JAVA_SRC_DIR = "JavaRedux"; @@ -45,45 +48,38 @@ 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. + * This list stores all resources to be retrieved. It is fed by the constructor. */ private List resources = new ArrayList(); /** * 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 + * + * The list of resources is retreived and interpreted. The resources themselves are not yet + * read. + * + * @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."); + throw new FileNotFoundException("Resource " + resourceString + " cannot be opened."); } - BufferedReader r = new BufferedReader(new InputStreamReader(jlURL - .openStream())); + BufferedReader r = new BufferedReader(new InputStreamReader(jlURL.openStream())); for (String jl = r.readLine(); (jl != null); jl = r.readLine()) { // ignore comments and empty lines @@ -98,13 +94,12 @@ public JavaReduxFileCollection(Profile profile) throws IOException { /** * {@inheritDoc} - * + * * This class only supports walker for a single file type: .java */ public Walker createWalker(String extension) throws IOException { if (!".java".equals(extension)) { - throw new IllegalStateException( - "This collection can only list .java files"); + throw new IllegalStateException("This collection can only list .java files"); } return new Walker(resources.iterator()); @@ -113,13 +108,12 @@ 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 { if (extensions == null || extensions.length < 1 || !".java".equals(extensions[0])) { - throw new IllegalStateException( - "This collection can only list .java files"); + throw new IllegalStateException("This collection can only list .java files"); } return new Walker(resources.iterator()); @@ -127,8 +121,8 @@ public Walker createWalker(String[] extensions) throws IOException { } /* - * The Class Walker wraps a string iterator and creates URL, streams and - * DataLocation elements on demand. + * The Class Walker wraps a string iterator and creates URL, streams and DataLocation elements + * on demand. */ private class Walker implements FileCollection.Walker { @@ -147,15 +141,14 @@ private class Walker implements FileCollection.Walker { */ private URL currentURL = null; - + private Walker(Iterator iterator) { this.iterator = iterator; } - public DataLocation getCurrentDataLocation() - throws NoSuchElementException { + 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); } @@ -168,27 +161,24 @@ public String getType() { return "internal"; } - public InputStream openCurrent() throws IOException, - NoSuchElementException { + public InputStream openCurrent() throws IOException, NoSuchElementException { if (current == null) throw new NoSuchElementException(); if (currentURL == null) { - throw new FileNotFoundException("cannot find " - + resourceLocation - + "/" + current); + throw new FileNotFoundException("cannot find " + resourceLocation + "/" + current); } return currentURL.openStream(); } @Override - public InputStream openCurrent(FileRepo fileRepo) throws IOException, - NoSuchElementException { + public InputStream openCurrent(FileRepo fileRepo) + throws IOException, NoSuchElementException { if (fileRepo != null) { return fileRepo.getInputStream(currentURL); } else { - return openCurrent(); // fallback without FileRepo + return openCurrent(); // fallback without FileRepo } } @@ -200,16 +190,16 @@ public boolean step() { } current = iterator.next(); - + final String currentFileName = current.replace('.', '/').concat(".java"); // may be null! - currentURL = KeYResourceManager.getManager().getResourceFile( - Recoder2KeY.class, resourceLocation + "/" + currentFileName); - + currentURL = KeYResourceManager.getManager().getResourceFile(Recoder2KeY.class, + resourceLocation + "/" + currentFileName); + return true; } } -} \ No newline at end of file +} 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 690ced074ec..d951f250633 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -10,8 +13,8 @@ /** - * 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}. taken from COMPOST and changed to + * achieve an immutable structure */ public abstract class JavaSourceElement implements SourceElement { private static final Logger LOGGER = LoggerFactory.getLogger(JavaSourceElement.class); @@ -20,28 +23,29 @@ public abstract class JavaSourceElement implements SourceElement { /** - * Java source element. + * Java source element. */ public JavaSourceElement() { - posInfo=PositionInfo.UNDEFINED; + posInfo = PositionInfo.UNDEFINED; } - - /** - * Java source element. - * @param pi PositionInfo the PositionInfo of the element - */ + + /** + * Java source element. + * + * @param pi PositionInfo the PositionInfo of the element + */ public JavaSourceElement(PositionInfo pi) { - posInfo=getPosInfo(pi); - } + posInfo = getPosInfo(pi); + } /** - * Java source element. - * @param children a list of the children of this element. May contain: - * PositionInfo + * Java source element. + * + * @param children a list of the children of this element. May contain: PositionInfo */ public JavaSourceElement(ExtList children) { - posInfo = getPosInfo(children.get(PositionInfo.class)); + posInfo = getPosInfo(children.get(PositionInfo.class)); } @@ -50,34 +54,33 @@ public JavaSourceElement(ExtList children, PositionInfo pos) { } /** - * 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 + * 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 */ - private PositionInfo getPosInfo(PositionInfo p) { + private PositionInfo getPosInfo(PositionInfo p) { final PositionInfo pos; - if (p==null) { + if (p == null) { pos = PositionInfo.UNDEFINED; } else { pos = p; } return pos; - } + } /** - * 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() */ public SourceElement getFirstElement() { @@ -86,18 +89,18 @@ public SourceElement getFirstElement() { @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() */ public SourceElement getLastElement() { @@ -107,67 +110,67 @@ public SourceElement getLastElement() { /** - * Pretty printing the source element. + * Pretty printing the source element. */ public abstract void prettyPrint(PrettyPrinter w) throws IOException; /** - * Creates a syntactical representation of the source element using - * the {@link #prettyPrint} method. + * 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(); + 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 */ 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){ + + /* Sometimes CompilableJavaPP must be given as argument instead of the ordinary PrettyPrinter */ + public String toString(PrettyPrinter pp, StringWriter sw) { try { pp.setIndentationLevel(0); prettyPrint(pp); @@ -175,23 +178,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 */ public String getParentClass() { return posInfo.getParentClass(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaTools.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaTools.java index cf5bac95228..2e6f32cf853 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaTools.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/JavaTools.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.key_project.util.ExtList; @@ -11,8 +14,10 @@ import de.uka.ilkd.key.logic.JavaBlock; import de.uka.ilkd.key.logic.ProgramPrefix; -/** Miscellaneous static methods related to Java blocks or statements in KeY. - * Mostly moved from key.util.MiscTools here. +/** + * Miscellaneous static methods related to Java blocks or statements in KeY. Mostly moved from + * key.util.MiscTools here. + * * @author bruns * */ @@ -25,10 +30,8 @@ public static SourceElement getActiveStatement(JavaBlock jb) { assert jb.program() != null; SourceElement result = jb.program().getFirstElement(); - while ((result instanceof ProgramPrefix - || result instanceof CatchAllStatement) - && !(result instanceof StatementBlock - && ((StatementBlock) result).isEmpty())) { + while ((result instanceof ProgramPrefix || result instanceof CatchAllStatement) + && !(result instanceof StatementBlock && ((StatementBlock) result).isEmpty())) { if (result instanceof LabeledStatement) { result = ((LabeledStatement) result).getChildAt(1); } else if (result instanceof CatchAllStatement) { @@ -43,12 +46,10 @@ public static SourceElement getActiveStatement(JavaBlock jb) { /** * Returns the passed java block without its active statement. */ - public static JavaBlock removeActiveStatement(JavaBlock jb, - Services services) { + public static JavaBlock removeActiveStatement(JavaBlock jb, Services services) { assert jb.program() != null; final SourceElement activeStatement = JavaTools.getActiveStatement(jb); - Statement newProg = (Statement) - (new CreatingASTVisitor(jb.program(), false, services) { + Statement newProg = (Statement) (new CreatingASTVisitor(jb.program(), false, services) { private boolean done = false; public ProgramElement go() { @@ -70,8 +71,7 @@ public void doAction(ProgramElement node) { } }).go(); - StatementBlock newSB = newProg instanceof StatementBlock - ? (StatementBlock) newProg + StatementBlock newSB = newProg instanceof StatementBlock ? (StatementBlock) newProg : new StatementBlock(newProg); return JavaBlock.createJavaBlock(newSB); } @@ -79,8 +79,7 @@ public void doAction(ProgramElement node) { /** * Returns the innermost method frame of the passed java block */ - public static MethodFrame getInnermostMethodFrame(ProgramElement pe, - Services services) { + public static MethodFrame getInnermostMethodFrame(ProgramElement pe, Services services) { final MethodFrame result = new JavaASTVisitor(pe, services) { private MethodFrame res; @@ -106,18 +105,13 @@ public MethodFrame run() { /** * Returns the innermost method frame of the passed java block */ - public static MethodFrame getInnermostMethodFrame(JavaBlock jb, - Services services) { + public static MethodFrame getInnermostMethodFrame(JavaBlock jb, Services services) { return getInnermostMethodFrame(jb.program(), services); } - public static ExecutionContext getInnermostExecutionContext( - JavaBlock jb, - Services services) { + public static ExecutionContext getInnermostExecutionContext(JavaBlock jb, Services services) { final MethodFrame frame = getInnermostMethodFrame(jb, services); - return frame == null - ? null - : (ExecutionContext) frame.getExecutionContext(); + return frame == null ? null : (ExecutionContext) frame.getExecutionContext(); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYJavaASTFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYJavaASTFactory.java index 28c50d06b72..d3e0cd5aae9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYJavaASTFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/KeYJavaASTFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.List; @@ -77,3051 +80,2539 @@ public abstract class KeYJavaASTFactory { * creates an assignment lhs:=rhs */ public static CopyAssignment assign(Expression lhs, Expression rhs) { - return new CopyAssignment(lhs, rhs); + return new CopyAssignment(lhs, rhs); } /** * creates an assignment lhs:=rhs */ - public static CopyAssignment assign(Expression lhs, Expression rhs, - PositionInfo posInfo) { - return assign(new ExtList(new Object[] { lhs, rhs, posInfo })); + public static CopyAssignment assign(Expression lhs, Expression rhs, PositionInfo posInfo) { + return assign(new ExtList(new Object[] { lhs, rhs, posInfo })); } /** * Create an assignment. - * - * @param parameters - * the assignment parameters (variable, expression) as - * {@link ExtList} - * @return a new {@link CopyAssignment} as defined by - * parameters + * + * @param parameters the assignment parameters (variable, expression) as {@link ExtList} + * @return a new {@link CopyAssignment} as defined by parameters */ public static CopyAssignment assign(final ExtList parameters) { - final CopyAssignment assignment = new CopyAssignment(parameters); + final CopyAssignment assignment = new CopyAssignment(parameters); - return assignment; + return assignment; } /** * creates an attribute access prefix.field */ - public static Expression attribute(ReferencePrefix prefix, - ProgramVariable field) { - return new FieldReference(field, prefix); + public static Expression attribute(ReferencePrefix prefix, ProgramVariable field) { + return new FieldReference(field, prefix); } /** * creates a local variable declaration typeRef name; */ - public static LocalVariableDeclaration declare - (ProgramElementName name, TypeReference typeRef) { - return new LocalVariableDeclaration - (typeRef, new VariableSpecification - (new LocationVariable(name, - typeRef.getKeYJavaType()))); + public static LocalVariableDeclaration declare(ProgramElementName name, TypeReference typeRef) { + return new LocalVariableDeclaration(typeRef, + new VariableSpecification(new LocationVariable(name, typeRef.getKeYJavaType()))); } /** * Create a local variable declaration without initialization. - * + * *

          * type name;
          * 
    - * - * @param name - * the {@link ProgramElementName} of the variable to be declared - * @param type - * the static {@link KeYJavaType} of the variable to be declared - * @return a new {@link LocalVariableDeclaration} of a variable with static - * type type and name name + * + * @param name the {@link ProgramElementName} of the variable to be declared + * @param type the static {@link KeYJavaType} of the variable to be declared + * @return a new {@link LocalVariableDeclaration} of a variable with static type + * type and name name */ - public static LocalVariableDeclaration declare( - final ProgramElementName name, final KeYJavaType type) { - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - name, null, type); + public static LocalVariableDeclaration declare(final ProgramElementName name, + final KeYJavaType type) { + final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare(name, null, type); - return declaration; + return declaration; } /** - * create a local variable declaration

    - * type name = init; + * create a local variable declaration
    + *
    + * type name = init; */ - public static LocalVariableDeclaration declare - (ProgramElementName name, Expression init, KeYJavaType type) { - return new LocalVariableDeclaration - (new TypeRef(type), - new VariableSpecification - (new LocationVariable(name, type), - init, type)); + public static LocalVariableDeclaration declare(ProgramElementName name, Expression init, + KeYJavaType type) { + return new LocalVariableDeclaration(new TypeRef(type), + new VariableSpecification(new LocationVariable(name, type), init, type)); } /** * Create a local variable declaration. - * + * *
          * type var = init;
          * 
    - * - * @param var - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} var is initialized with - * @param type - * the static {@link KeYJavaType} of var - * @return a {@link LocalVariableDeclaration} of var with - * static type type and initial value init + * + * @param var the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} var is initialized with + * @param type the static {@link KeYJavaType} of var + * @return a {@link LocalVariableDeclaration} of var with static type + * type and initial value init */ - public static LocalVariableDeclaration declare - (IProgramVariable var, Expression init, KeYJavaType type) { - return KeYJavaASTFactory.declare(new Modifier[0], var, init, type); + public static LocalVariableDeclaration declare(IProgramVariable var, Expression init, + KeYJavaType type) { + return KeYJavaASTFactory.declare(new Modifier[0], var, init, type); } /** * Create a local variable declaration with a unique name. - * + * *
          * type name{unique} = initializer;
          * 
    - * - * @param services - * the {@link Services} whose {@link VariableNamer} is used to - * determine a unique variable name - * @param name - * the {@link String} on which the variable's unique name is - * based - * @param initializer - * the {@link Expression} the declared variable is initialized - * with - * @param type - * the static {@link KeYJavaType} of the to be declared variable - * @return a {@link LocalVariableDeclaration} of variable named uniquely - * after name with static type type and - * initial value initializer - */ - public static LocalVariableDeclaration declare(final Services services, - final String name, final Expression initializer, - final KeYJavaType type) { - final ProgramElementName uniqueName = services.getVariableNamer() - .getTemporaryNameProposal(name); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - uniqueName, initializer, type); - - return declaration; + * + * @param services the {@link Services} whose {@link VariableNamer} is used to determine a + * unique variable name + * @param name the {@link String} on which the variable's unique name is based + * @param initializer the {@link Expression} the declared variable is initialized with + * @param type the static {@link KeYJavaType} of the to be declared variable + * @return a {@link LocalVariableDeclaration} of variable named uniquely after name + * with static type type and initial value initializer + */ + public static LocalVariableDeclaration declare(final Services services, final String name, + final Expression initializer, final KeYJavaType type) { + final ProgramElementName uniqueName = + services.getVariableNamer().getTemporaryNameProposal(name); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(uniqueName, initializer, type); + + return declaration; } /** * Create a local variable declaration without initialization. - * + * *
          * type var;
          * 
    - * - * @param var - * the named and typed {@link IProgramVariable} to be declared - * @param type - * the static {@link KeYJavaType} of var - * @return a {@link LocalVariableDeclaration} of var with - * static type type + * + * @param var the named and typed {@link IProgramVariable} to be declared + * @param type the static {@link KeYJavaType} of var + * @return a {@link LocalVariableDeclaration} of var with static type + * type */ - public static LocalVariableDeclaration declare - (IProgramVariable var, KeYJavaType type) { - return KeYJavaASTFactory.declare(var, null, type); + public static LocalVariableDeclaration declare(IProgramVariable var, KeYJavaType type) { + return KeYJavaASTFactory.declare(var, null, type); } /** * create a local variable declaration */ public static LocalVariableDeclaration declare(String name, KeYJavaType type) { - return new LocalVariableDeclaration - (new TypeRef(type), - new VariableSpecification - (new LocationVariable(new ProgramElementName(name), type))); + return new LocalVariableDeclaration(new TypeRef(type), new VariableSpecification( + new LocationVariable(new ProgramElementName(name), type))); } /** * create a parameter declaration */ - public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, - KeYJavaType kjt, - String name) { - return new ParameterDeclaration - (new Modifier[0], javaInfo.createTypeReference(kjt), - new VariableSpecification(localVariable(name, kjt)), false); + public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, KeYJavaType kjt, + String name) { + return new ParameterDeclaration(new Modifier[0], javaInfo.createTypeReference(kjt), + new VariableSpecification(localVariable(name, kjt)), false); } /** * Create a parameter declaration. - * + * *
          * kjt var
          * 
    - * - * @param javaInfo - * the Java model containing kjt - * @param kjt - * the static {@link KeYJavaType} of var - * @param var - * the named and typed {@link IProgramVariable} to be declared as - * parameter - * @return a {@link ParameterDeclaration} of var with static - * type kjt + * + * @param javaInfo the Java model containing kjt + * @param kjt the static {@link KeYJavaType} of var + * @param var the named and typed {@link IProgramVariable} to be declared as parameter + * @return a {@link ParameterDeclaration} of var with static type kjt */ - public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, - KeYJavaType kjt, - IProgramVariable var) { - return new ParameterDeclaration - (new Modifier[0], javaInfo.createTypeReference(kjt), - new VariableSpecification(var), false); + public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, KeYJavaType kjt, + IProgramVariable var) { + return new ParameterDeclaration(new Modifier[0], javaInfo.createTypeReference(kjt), + new VariableSpecification(var), false); } - public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, - String type, - String name) { - KeYJavaType kjt = javaInfo.getKeYJavaType(type); - return new ParameterDeclaration - (new Modifier[0], javaInfo.createTypeReference(kjt), - new VariableSpecification(localVariable(name, kjt)), false); + public static ParameterDeclaration parameterDeclaration(JavaInfo javaInfo, String type, + String name) { + KeYJavaType kjt = javaInfo.getKeYJavaType(type); + return new ParameterDeclaration(new Modifier[0], javaInfo.createTypeReference(kjt), + new VariableSpecification(localVariable(name, kjt)), false); } /** * Create a parenthesized expression. - * + * *
          * (expression)
          * 
    - * - * @param expression - * the {@link Expression} to be parenthesized + * + * @param expression the {@link Expression} to be parenthesized * @return a new {@link ParenthesizedExpression} of expression */ - public static ParenthesizedExpression parenthesizedExpression( - final Expression expression) { - final ParenthesizedExpression parenthesized = new ParenthesizedExpression( - expression); + public static ParenthesizedExpression parenthesizedExpression(final Expression expression) { + final ParenthesizedExpression parenthesized = new ParenthesizedExpression(expression); - return parenthesized; + return parenthesized; } /** * Create an inactive expression. - * - * @param expression - * the {@link Expression} to be marked inactive - * @return a new {@link PassiveExpression} version of - * expression + * + * @param expression the {@link Expression} to be marked inactive + * @return a new {@link PassiveExpression} version of expression */ - public static PassiveExpression passiveExpression( - final Expression expression) { - final PassiveExpression passive = new PassiveExpression(expression); + public static PassiveExpression passiveExpression(final Expression expression) { + final PassiveExpression passive = new PassiveExpression(expression); - return passive; + return passive; } /** * create a local variable */ - public static ProgramVariable localVariable(String name, - KeYJavaType kjt) { - return localVariable(new ProgramElementName(name), kjt); + public static ProgramVariable localVariable(String name, KeYJavaType kjt) { + return localVariable(new ProgramElementName(name), kjt); } /** * create a local variable */ - public static ProgramVariable localVariable(ProgramElementName name, - KeYJavaType kjt) { - return new LocationVariable(name, kjt); + public static ProgramVariable localVariable(ProgramElementName name, KeYJavaType kjt) { + return new LocationVariable(name, kjt); } /** * Create a local variable with a unique name. - * - * @param services - * the {@link Services} whose {@link VariableNamer} is used - * @param name - * the {@link String} on which the variable's unique name is - * based - * @param type - * the variable's static {@link KeYJavaType} - * @return a new {@link ProgramVariable} of static type type - * and with a unique name based on name + * + * @param services the {@link Services} whose {@link VariableNamer} is used + * @param name the {@link String} on which the variable's unique name is based + * @param type the variable's static {@link KeYJavaType} + * @return a new {@link ProgramVariable} of static type type and with a unique name + * based on name */ - public static ProgramVariable localVariable(final Services services, - final String name, final KeYJavaType type) { - final ProgramElementName uniqueName = services.getVariableNamer() - .getTemporaryNameProposal(name); - final ProgramVariable variable = KeYJavaASTFactory.localVariable( - uniqueName, type); + public static ProgramVariable localVariable(final Services services, final String name, + final KeYJavaType type) { + final ProgramElementName uniqueName = + services.getVariableNamer().getTemporaryNameProposal(name); + final ProgramVariable variable = KeYJavaASTFactory.localVariable(uniqueName, type); - return variable; + return variable; } /** * Create a logical and operator. - * + * *
          * left & right
          * 
    - * - * @param left - * the left operand {@link Expression} - * @param right - * the right operand Expression - * @return a new {@link LogicalAnd} of left and - * right + * + * @param left the left operand {@link Expression} + * @param right the right operand Expression + * @return a new {@link LogicalAnd} of left and right */ - public static LogicalAnd logicalAndOperator(final Expression left, - final Expression right) { - final LogicalAnd operator = new LogicalAnd(left, right); + public static LogicalAnd logicalAndOperator(final Expression left, final Expression right) { + final LogicalAnd operator = new LogicalAnd(left, right); - return operator; + return operator; } /** * Create a logical or operator. - * + * *
          * left | right
          * 
    - * - * @param left - * the left operand {@link Expression} - * @param right - * the right operand {@link Expression} - * @return a new {@link LogicalOr} of left and - * right + * + * @param left the left operand {@link Expression} + * @param right the right operand {@link Expression} + * @return a new {@link LogicalOr} of left and right */ - public static LogicalOr logicalOrOperator(final Expression left, - final Expression right) { - final LogicalOr operator = new LogicalOr(left, right); + public static LogicalOr logicalOrOperator(final Expression left, final Expression right) { + final LogicalOr operator = new LogicalOr(left, right); - return operator; + return operator; } /** * Create a catch clause. - * - * @param parameters - * the catch clause parameters (exception, body) as - * {@link ExtList} + * + * @param parameters the catch clause parameters (exception, body) as {@link ExtList} * @return a new {@link Catch} as defined by parameters */ public static Catch catchClause(final ExtList parameters) { - final Catch clause = new Catch(parameters); + final Catch clause = new Catch(parameters); - return clause; + return clause; } /** * create a catch clause */ - public static Catch catchClause(ParameterDeclaration param, - StatementBlock body) { + public static Catch catchClause(ParameterDeclaration param, StatementBlock body) { - return new Catch(param, body); + return new Catch(param, body); } /** * Create a catch clause. - * + * *
          * catch (parameter) {
          *     statements
          * }
          * 
    - * - * @param parameter - * the to be caught {@link ParameterDeclaration} - * @param statements - * the body {@link Statement}s - * @return a new {@link Catch} clause for execution of - * statements in case of parameter + * + * @param parameter the to be caught {@link ParameterDeclaration} + * @param statements the body {@link Statement}s + * @return a new {@link Catch} clause for execution of statements in case of + * parameter */ public static Catch catchClause(final ParameterDeclaration parameter, - final Statement[] statements) { - final StatementBlock body = KeYJavaASTFactory.block(statements); - final Catch clause = KeYJavaASTFactory.catchClause(parameter, body); + final Statement[] statements) { + final StatementBlock body = KeYJavaASTFactory.block(statements); + final Catch clause = KeYJavaASTFactory.catchClause(parameter, body); - return clause; + return clause; } /** * Create a catch clause. - * + * *
          * catch (kjt param)
          *    body
          * 
    - * - * @param javaInfo - * the {@link JavaInfo} containing kjt - * @param param - * the {@link String} name of the exception object variable - * @param kjt - * the {@link KeYJavaType} of the exception object variable - * @param body - * the {@link StatementBlock} catch clause body - * @return a new {@link Catch} with parameter param of static - * type kjt and body body + * + * @param javaInfo the {@link JavaInfo} containing kjt + * @param param the {@link String} name of the exception object variable + * @param kjt the {@link KeYJavaType} of the exception object variable + * @param body the {@link StatementBlock} catch clause body + * @return a new {@link Catch} with parameter param of static type kjt + * and body body */ - public static Catch catchClause(JavaInfo javaInfo, String param, - KeYJavaType kjt, StatementBlock body) { + public static Catch catchClause(JavaInfo javaInfo, String param, KeYJavaType kjt, + StatementBlock body) { - return new Catch(parameterDeclaration(javaInfo, kjt, param), body); + return new Catch(parameterDeclaration(javaInfo, kjt, param), body); } /** * Create a catch clause. - * + * *
          * catch (type param)
          *    body
          * 
    - * - * @param javaInfo - * the {@link JavaInfo} containing a {@link KeYJavaType} named - * type - * @param param - * the {@link String} name of the exception object variable - * @param type - * the String name of the exception object - * variable's KeYJavaType - * @param body - * the {@link StatementBlock} catch clause body - * @return a new {@link Catch} with parameter param of static - * type type and body body + * + * @param javaInfo the {@link JavaInfo} containing a {@link KeYJavaType} named type + * @param param the {@link String} name of the exception object variable + * @param type the String name of the exception object variable's + * KeYJavaType + * @param body the {@link StatementBlock} catch clause body + * @return a new {@link Catch} with parameter param of static type + * type and body body */ - public static Catch catchClause(JavaInfo javaInfo, String param, - String type, StatementBlock body) { + public static Catch catchClause(JavaInfo javaInfo, String param, String type, + StatementBlock body) { - return catchClause(javaInfo, param, - javaInfo.getKeYJavaType(type), body); + return catchClause(javaInfo, param, javaInfo.getKeYJavaType(type), body); } /** * Create a throw clause. - * + * *
          * throw e
          * 
    - * - * @param e - * the throw {@link Expression} + * + * @param e the throw {@link Expression} * @return a new {@link Throw} statement with expression e */ public static Throw throwClause(Expression e) { - return new Throw(e); + return new Throw(e); } /** * Create a transaction statement. - * - * @param type - * the transaction statement type + * + * @param type the transaction statement type * @return a new {@link TransactionStatement} of type type */ public static TransactionStatement transactionStatement(final int type) { - final TransactionStatement statement = new TransactionStatement(type); + final TransactionStatement statement = new TransactionStatement(type); - return statement; + return statement; } /** * Create a true condition. - * + * * @return a new {@link Guard} with expression true */ public static Guard trueGuard() { - final Guard guard = new Guard(BooleanLiteral.TRUE); + final Guard guard = new Guard(BooleanLiteral.TRUE); - return guard; + return guard; } /** * Create a while loop. - * + * *
          * while (condition)
          *     body
          * 
    - * - * @param condition - * the loop condition {@link Expression} - * @param body - * the loop body {@link Statement} - * @return a new {@link While} loop defined by condition and - * body + * + * @param condition the loop condition {@link Expression} + * @param body the loop body {@link Statement} + * @return a new {@link While} loop defined by condition and body */ - public static Statement whileLoop(final Expression condition, - final Statement body) { - final While loop = new While(condition, body); + public static Statement whileLoop(final Expression condition, final Statement body) { + final While loop = new While(condition, body); - return loop; + return loop; } /** * Create a while loop at a specific source position. - * + * *
          * while (condition)
          *     body
          * 
    - * - * @param condition - * the loop condition {@link Expression} - * @param body - * the loop body {@link Statement} - * @param position - * the new source element's {@link PositionInfo} - * @return a new {@link While} loop defined by condition and - * body, and positioned at position + * + * @param condition the loop condition {@link Expression} + * @param body the loop body {@link Statement} + * @param position the new source element's {@link PositionInfo} + * @return a new {@link While} loop defined by condition and body, and + * positioned at position */ - public static While whileLoop(final Expression condition, - final Statement body, final PositionInfo position) { - final While loop = new While(condition, body, position); + public static While whileLoop(final Expression condition, final Statement body, + final PositionInfo position) { + final While loop = new While(condition, body, position); - return loop; + return loop; } /** * Create a return clause. - * + * *
          * return e
          * 
    - * - * @param e - * the return {@link Expression} + * + * @param e the return {@link Expression} * @return a new {@link Return} statement with expression e */ public static Return returnClause(Expression e) { - return new Return(e); + return new Return(e); } /** * Create an if statement with no else branch. - * + * *
          * if (guard)
          *    then
          * 
    - * - * @param guard - * the if statement condition {@link Expression} - * @param then - * the if statement then branch {@link Statement} - * @return an {@link If} with expression guard and then branch - * then + * + * @param guard the if statement condition {@link Expression} + * @param then the if statement then branch {@link Statement} + * @return an {@link If} with expression guard and then branch then */ - public static If ifThen(Expression guard, - Statement then) { - final If statement = KeYJavaASTFactory.ifThen(guard, new Then(then)); + public static If ifThen(Expression guard, Statement then) { + final If statement = KeYJavaASTFactory.ifThen(guard, new Then(then)); - return statement; + return statement; } /** * Create an if statement with no else branch. - * + * *
          * if (guard) {
          *    statements
          * }
          * 
    - * - * @param guard - * the if statement condition {@link Expression} - * @param statements - * the if statement then branch {@link Statement}s + * + * @param guard the if statement condition {@link Expression} + * @param statements the if statement then branch {@link Statement}s * @return an {@link If} with condition guard and then branch * statements */ - public static If ifThen(final Expression guard, - final Statement... statements) { - final StatementBlock block = KeYJavaASTFactory.block(statements); - final If statement = KeYJavaASTFactory.ifThen(guard, block); + public static If ifThen(final Expression guard, final Statement... statements) { + final StatementBlock block = KeYJavaASTFactory.block(statements); + final If statement = KeYJavaASTFactory.ifThen(guard, block); - return statement; + return statement; } /** * Create an if statement with no else branch. - * + * *
          * if (guard)
          *    then
          * 
    - * - * @param guard - * the if statement condition {@link Expression} - * @param then - * the if statement then branch {@link Then} - * @return an {@link If} with expression guard and then branch - * then + * + * @param guard the if statement condition {@link Expression} + * @param then the if statement then branch {@link Then} + * @return an {@link If} with expression guard and then branch then */ public static If ifThen(final Expression guard, final Then then) { - final If statement = new If(guard, then); + final If statement = new If(guard, then); - return statement; + return statement; } /** * Create an if statement. - * - * @param parameters - * the if statement parameters (guard, body, else branch) as - * {@link ExtList} + * + * @param parameters the if statement parameters (guard, body, else branch) as {@link ExtList} * @return a new {@link If} as defined by parameters */ public static If ifStatement(final ExtList parameters) { - final If statement = new If(parameters); + final If statement = new If(parameters); - return statement; + return statement; } /** * Create an if statement including an else branch. - * + * *
          * if (guard)
          *    then
          * else
          *    els
          * 
    - * - * @param guard - * the if statement condition {@link Expression} - * @param then - * the if statement then branch {@link Statement} - * @param els - * the if statement else branch Statement - * @return an {@link If} with expression guard, then branch - * then and else branch els + * + * @param guard the if statement condition {@link Expression} + * @param then the if statement then branch {@link Statement} + * @param els the if statement else branch Statement + * @return an {@link If} with expression guard, then branch then and + * else branch els */ - public static If ifElse(Expression guard, - Then then, - Else els) { - return new If(guard, then, els); + public static If ifElse(Expression guard, Then then, Else els) { + return new If(guard, then, els); } /** * Create an if clause. - * + * *
          * if (guard)
          *    thenStatement
          * else
          *    elseStatement
          * 
    - * - * @param guard - * the if clause condition {@link Expression} - * - * @param thenStatement - * the if clause then branch {@link Statement} - * - * @param elseStatement - * the if clause else branch Statement - * + * + * @param guard the if clause condition {@link Expression} + * + * @param thenStatement the if clause then branch {@link Statement} + * + * @param elseStatement the if clause else branch Statement + * * @return a new {@link If} with condition guard, then branch - * thenStatement and else branch - * elseStatement + * thenStatement and else branch elseStatement */ - public static Statement ifElse(final Expression guard, - final Statement thenStatement, final Statement elseStatement) { - final Then then = new Then(thenStatement); - final Else els = new Else(elseStatement); - final If ifElse = KeYJavaASTFactory.ifElse(guard, then, els); + public static Statement ifElse(final Expression guard, final Statement thenStatement, + final Statement elseStatement) { + final Then then = new Then(thenStatement); + final Else els = new Else(elseStatement); + final If ifElse = KeYJavaASTFactory.ifElse(guard, then, els); - return ifElse; + return ifElse; } /** * Create a break statement. - * - * @param l - * the break destination {@link Label} + * + * @param l the break destination {@link Label} * @return a new {@link Break} with label l */ public static Break breakStatement(Label l) { - return new Break(l); + return new Break(l); } public static Statement breakStatement(Label label, PositionInfo positionInfo) { - return new Break(new ExtList(new Object[] {label, positionInfo})); + return new Break(new ExtList(new Object[] { label, positionInfo })); } /** * Create a case block. - * - * @param parameters - * the case block parameters (body) as {@link ExtList} - * @param expression - * the case block {@link Expression} - * @param position - * the new source element's {@link PositionInfo} - * @return a new {@link Case} as defined by parameters and - * expression + * + * @param parameters the case block parameters (body) as {@link ExtList} + * @param expression the case block {@link Expression} + * @param position the new source element's {@link PositionInfo} + * @return a new {@link Case} as defined by parameters and expression */ - public static Case caseBlock(final ExtList parameters, - final Expression expression, final PositionInfo position) { - final Case block = new Case(parameters, expression, position); + public static Case caseBlock(final ExtList parameters, final Expression expression, + final PositionInfo position) { + final Case block = new Case(parameters, expression, position); - return block; + return block; } /** * Create a case block. - * + * *
          * case (expression)
          *     statement
          * 
    - * - * @param expression - * the case {@link Expression} - * @param statement - * the to be executed {@link Statement} - * @return a new {@link Case} for execution of statement in - * case of expression + * + * @param expression the case {@link Expression} + * @param statement the to be executed {@link Statement} + * @return a new {@link Case} for execution of statement in case of + * expression */ - public static Case caseBlock(final Expression expression, - final Statement statement) { - final Statement[] statements = new Statement[] { statement }; - final Case block = KeYJavaASTFactory.caseBlock(expression, statements); + public static Case caseBlock(final Expression expression, final Statement statement) { + final Statement[] statements = new Statement[] { statement }; + final Case block = KeYJavaASTFactory.caseBlock(expression, statements); - return block; + return block; } /** * Create a case block. - * + * *
          * case (expression) {
          *     statements
          * }
          * 
    - * - * @param expression - * the case {@link Expression} - * @param statements - * the to be executed {@link Statement}s - * @return a new {@link Case} for execution of statements in - * case of expression + * + * @param expression the case {@link Expression} + * @param statements the to be executed {@link Statement}s + * @return a new {@link Case} for execution of statements in case of + * expression */ - public static Case caseBlock(final Expression expression, - final Statement[] statements) { - final Case block = new Case(expression, statements); + public static Case caseBlock(final Expression expression, final Statement[] statements) { + final Case block = new Case(expression, statements); - return block; + return block; } public static Continue continueStatement(Label label) { - return new Continue(label); + return new Continue(label); } /** * Create an empty statement. - * + * * @return a new {@link EmptyStatement} */ public static EmptyStatement emptyStatement() { - return new EmptyStatement(); + return new EmptyStatement(); } /** * Create an enhanced for loop. - * - * @param parameters - * the loop definition parameters (initializer, guard, body) as - * {@link ExtList} + * + * @param parameters the loop definition parameters (initializer, guard, body) as + * {@link ExtList} * @return a new {@link For} as defined by parameters */ public static EnhancedFor enhancedForLoop(final ExtList parameters) { - final EnhancedFor loop = new EnhancedFor(parameters); + final EnhancedFor loop = new EnhancedFor(parameters); - return loop; + return loop; } /** * Create an equality comparison with null. - * + * *
          * expression == null
          * 
    - * - * @param expression - * the {@link Expression} to be compared against - * null - * @return a new {@link Equals} that compares expression - * against null + * + * @param expression the {@link Expression} to be compared against null + * @return a new {@link Equals} that compares expression against null */ public static Equals equalsNullOperator(final Expression expression) { - final Equals operator = KeYJavaASTFactory.equalsOperator(expression, - NullLiteral.NULL); + final Equals operator = KeYJavaASTFactory.equalsOperator(expression, NullLiteral.NULL); - return operator; + return operator; } /** * Create an equals operator. - * + * *
          * left == right
          * 
    - * - * @param left - * the left operand {@link Expression} - * @param right - * the right operand Expression + * + * @param left the left operand {@link Expression} + * @param right the right operand Expression * @return a new {@link Equals} of left and right */ - public static Equals equalsOperator(final Expression left, - final Expression right) { - final Equals statement = new Equals(left, right); + public static Equals equalsOperator(final Expression left, final Expression right) { + final Equals statement = new Equals(left, right); - return statement; + return statement; } /** * Create an equals operator. - * + * *
          * operand{1} == operand{2}
          * 
    - * - * @param operands - * the operands {@link ExtList} + * + * @param operands the operands {@link ExtList} * @return a new {@link Equals} of operands */ public static Equals equalsOperator(final ExtList operands) { - final Equals statement = new Equals(operands); + final Equals statement = new Equals(operands); - return statement; + return statement; } /** * Create an execution context. - * - * @param classType - * the enclosing class {@link KeYJavaType} - * @param method - * the enclosing {@link IProgramMethod} defined in - * classType - * @param reference - * the {@link ReferencePrefix} method is called on - * @return a new {@link ExecutionContext} for calls on - * reference to method from - * classType + * + * @param classType the enclosing class {@link KeYJavaType} + * @param method the enclosing {@link IProgramMethod} defined in classType + * @param reference the {@link ReferencePrefix} method is called on + * @return a new {@link ExecutionContext} for calls on reference to + * method from classType */ - public static ExecutionContext executionContext( - final KeYJavaType classType, final IProgramMethod method, - final ReferencePrefix reference) { - final TypeRef type = new TypeRef(classType); - final ExecutionContext context = new ExecutionContext(type, method, - reference); + public static ExecutionContext executionContext(final KeYJavaType classType, + final IProgramMethod method, final ReferencePrefix reference) { + final TypeRef type = new TypeRef(classType); + final ExecutionContext context = new ExecutionContext(type, method, reference); - return context; + return context; } /** * Insert a statement in a block of statements. - * - * @param statement - * the {@link Statement} to be inserted into block - * @param block - * the {@link StatementBlock} statement is inserted - * into - * @return a new StatementBlock that contains both the - * Statements from block and - * statement - */ - public static StatementBlock insertStatementInBlock( - final Statement statement, final StatementBlock block) { - final Statement[] statements = new Statement[] { statement }; - final StatementBlock statementBlock = KeYJavaASTFactory - .insertStatementInBlock(statements, block); - - return statementBlock; - } - - /** inserts the given statements at the begin of the block + * + * @param statement the {@link Statement} to be inserted into block + * @param block the {@link StatementBlock} statement is inserted into + * @return a new StatementBlock that contains both the Statements from + * block and statement + */ + public static StatementBlock insertStatementInBlock(final Statement statement, + final StatementBlock block) { + final Statement[] statements = new Statement[] { statement }; + final StatementBlock statementBlock = + KeYJavaASTFactory.insertStatementInBlock(statements, block); + + return statementBlock; + } + + /** + * inserts the given statements at the begin of the block + * * @param stmnt array of Statement those have to be inserted * @param b the Statementblock where to insert */ - public static StatementBlock insertStatementInBlock(Statement[] stmnt, - StatementBlock b) { + public static StatementBlock insertStatementInBlock(Statement[] stmnt, StatementBlock b) { - Statement[] block = new Statement[b.getStatementCount()+ - stmnt.length]; - System.arraycopy(stmnt, 0, block, 0, stmnt.length); - b.getBody().arraycopy(0, block, stmnt.length, b.getStatementCount()); - return new StatementBlock(new ImmutableArray(block)); + Statement[] block = new Statement[b.getStatementCount() + stmnt.length]; + System.arraycopy(stmnt, 0, block, 0, stmnt.length); + b.getBody().arraycopy(0, block, stmnt.length, b.getStatementCount()); + return new StatementBlock(new ImmutableArray(block)); } - /** inserts the given statements at the begin of the block + /** + * inserts the given statements at the begin of the block + * * @param stmnt array of Statement those have to be inserted * @param b the Statementblock where to insert */ - public static StatementBlock insertStatementInBlock(StatementBlock stmnt, - StatementBlock b) { - Statement[] stmnts = new Statement[stmnt.getStatementCount()]; - for (int i=0; i * block * statements * - * - * @param block - * the original {@link StatementBlock} - * @param statements - * the inserted {@link Statement}s - * @return a new StatementBlock that contains - * block first and statements second + * + * @param block the original {@link StatementBlock} + * @param statements the inserted {@link Statement}s + * @return a new StatementBlock that contains block first and + * statements second */ - public static StatementBlock insertStatementInBlock( - final StatementBlock block, Statement[] statements) { - final StatementBlock blockEnd = KeYJavaASTFactory.block(statements); - final StatementBlock blockComplete = KeYJavaASTFactory - .insertStatementInBlock(block, blockEnd); + public static StatementBlock insertStatementInBlock(final StatementBlock block, + Statement[] statements) { + final StatementBlock blockEnd = KeYJavaASTFactory.block(statements); + final StatementBlock blockComplete = + KeYJavaASTFactory.insertStatementInBlock(block, blockEnd); - return blockComplete; + return blockComplete; } /** * Create an instance of operator. - * + * *
          * expression instance of type
          * 
    - * - * @param expression - * the {@link Expression} operand, whose runtime type is to be - * checked - * @param type - * the {@link KeYJavaType} operand expression's type - * is checked against - * @return a new {@link Instanceof} for checking expression's - * type against type + * + * @param expression the {@link Expression} operand, whose runtime type is to be checked + * @param type the {@link KeYJavaType} operand expression's type is checked against + * @return a new {@link Instanceof} for checking expression's type against + * type */ - public static Instanceof instanceOf(final Expression expression, - final KeYJavaType type) { - final TypeRef typeRef = new TypeRef(type); - final Instanceof instanceOf = new Instanceof(expression, typeRef); + public static Instanceof instanceOf(final Expression expression, final KeYJavaType type) { + final TypeRef typeRef = new TypeRef(type); + final Instanceof instanceOf = new Instanceof(expression, typeRef); - return instanceOf; + return instanceOf; } /** * Create a local variable declaration that assigns zero initially. - * + * *
          * type variable = 0;
          * 
    - * - * @param type - * the static {@link KeYJavaType} of variable - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value zero + * + * @param type the static {@link KeYJavaType} of variable + * @param variable the named and typed {@link IProgramVariable} to be declared + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value zero */ public static LocalVariableDeclaration declareZero(final KeYJavaType type, - final IProgramVariable variable) { - final IntLiteral zeroLiteral = KeYJavaASTFactory.zeroLiteral(); + final IProgramVariable variable) { + final IntLiteral zeroLiteral = KeYJavaASTFactory.zeroLiteral(); - return KeYJavaASTFactory.declare(variable, zeroLiteral, type); + return KeYJavaASTFactory.declare(variable, zeroLiteral, type); } /** - * Create a local variable declaration that assigns a method's return value - * initially. - * + * Create a local variable declaration that assigns a method's return value initially. + * *
          * type variable = reference.method();
          * 
    - * - * @param type - * the static {@link KeYJavaType} of variable - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param method - * the method's name {@link String} - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value - * reference.method() + * + * @param type the static {@link KeYJavaType} of variable + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param reference the {@link ReferencePrefix} the method is called on + * @param method the method's name {@link String} + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value reference.method() */ - public static LocalVariableDeclaration declareMethodCall( - final KeYJavaType type, final IProgramVariable variable, - final ReferencePrefix reference, final String method) { - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - method); + public static LocalVariableDeclaration declareMethodCall(final KeYJavaType type, + final IProgramVariable variable, final ReferencePrefix reference, final String method) { + final MethodReference call = KeYJavaASTFactory.methodCall(reference, method); - return KeYJavaASTFactory.declare(variable, call, type); + return KeYJavaASTFactory.declare(variable, call, type); } /** - * Create a local variable declaration that assigns a method's return value - * initially. - * + * Create a local variable declaration that assigns a method's return value initially. + * *
          * type variable = reference.method();
          * 
    - * - * where type is variable's {@link KeYJavaType} as it is - * returned by {@link IProgramVariable#getKeYJavaType()}. - * - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param method - * the method's name {@link String} - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value - * reference.method() + * + * where type is variable's {@link KeYJavaType} as it is returned by + * {@link IProgramVariable#getKeYJavaType()}. + * + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param reference the {@link ReferencePrefix} the method is called on + * @param method the method's name {@link String} + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value reference.method() */ - public static LocalVariableDeclaration declareMethodCall( - final IProgramVariable variable, final ReferencePrefix reference, - final String method) { - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - method); + public static LocalVariableDeclaration declareMethodCall(final IProgramVariable variable, + final ReferencePrefix reference, final String method) { + final MethodReference call = KeYJavaASTFactory.methodCall(reference, method); - return KeYJavaASTFactory.declare(variable, call); + return KeYJavaASTFactory.declare(variable, call); } /** * Create a default block. - * - * @param parameters - * the default block parameters (body) as {@link ExtList} + * + * @param parameters the default block parameters (body) as {@link ExtList} * @return a new {@link Default} as defined by parameters */ public static Default defaultBlock(final ExtList parameters) { - final Default block = new Default(parameters); + final Default block = new Default(parameters); - return block; + return block; } /** * Create a default block. - * + * *
          * default
          *     statement
          * 
    - * - * @param statement - * the to be executed {@link Statement} + * + * @param statement the to be executed {@link Statement} * @return a new {@link Default} that contains statement */ public static Default defaultBlock(final Statement statement) { - final Statement[] statements = new Statement[] { statement }; - final Default block = KeYJavaASTFactory.defaultBlock(statements); + final Statement[] statements = new Statement[] { statement }; + final Default block = KeYJavaASTFactory.defaultBlock(statements); - return block; + return block; } /** * Create a default block. - * + * *
          * default {
          *     statements
          * }
          * 
    - * - * @param statements - * the to be executed {@link Statement}s + * + * @param statements the to be executed {@link Statement}s * @return a new {@link Default} that contains statements */ public static Default defaultBlock(final Statement[] statements) { - final Default block = new Default(statements); + final Default block = new Default(statements); - return block; + return block; } /** * Create a do loop. - * + * *
          * do
          *     statement
          * while (condition);
          * 
    - * - * @param condition - * the do-loop condition {@link Expression} - * @param statement - * the do-loop body {@link Statement} - * @param positionInfo - * the new source element's {@link PositionInfo} - * @return a new {@link Do} that executes statement while - * condition holds + * + * @param condition the do-loop condition {@link Expression} + * @param statement the do-loop body {@link Statement} + * @param positionInfo the new source element's {@link PositionInfo} + * @return a new {@link Do} that executes statement while condition + * holds */ - public static Do doLoop(final Expression condition, - final Statement statement, final PositionInfo positionInfo) { - final Do loop = new Do(condition, statement, positionInfo); + public static Do doLoop(final Expression condition, final Statement statement, + final PositionInfo positionInfo) { + final Do loop = new Do(condition, statement, positionInfo); - return loop; + return loop; } /** * Create an else block. - * - * @param parameters - * the else block parameters (body) as {@link ExtList} + * + * @param parameters the else block parameters (body) as {@link ExtList} * @return a new {@link Else} as defined by parameters */ public static Else elseBlock(final ExtList parameters) { - final Else block = new Else(parameters); + final Else block = new Else(parameters); - return block; + return block; } /** * Create an else block. - * + * *
          * else
          *     statement
          * 
    - * - * @param statement - * the {@link Statement} to be executed - * @return a new {@link Else} block consisting of statement - * solely + * + * @param statement the {@link Statement} to be executed + * @return a new {@link Else} block consisting of statement solely */ public static Else elseBlock(final Statement statement) { - final Else block = new Else(statement); + final Else block = new Else(statement); - return block; + return block; } /** * Create an else block. - * + * *
          * else {
          *     statements
          * }
          * 
    - * - * @param statements - * the {@link Statement}s to be executed - * @return a new {@link Else} block consisting of statements - * solely + * + * @param statements the {@link Statement}s to be executed + * @return a new {@link Else} block consisting of statements solely */ public static Else elseBlock(final Statement[] statements) { - final StatementBlock statement = KeYJavaASTFactory.block(statements); - final Else block = KeYJavaASTFactory.elseBlock(statement); + final StatementBlock statement = KeYJavaASTFactory.block(statements); + final Else block = KeYJavaASTFactory.elseBlock(statement); - return block; + return block; } /** * Create a loop initialization that consists of a single statement. - * + * *
          * init
          * 
    - * - * @param init - * the single {@link LoopInitializer} + * + * @param init the single {@link LoopInitializer} * @return a new {@link ILoopInit} that consists of init only */ public static ILoopInit loopInit(final LoopInitializer init) { - final LoopInitializer[] initializers = { init }; + final LoopInitializer[] initializers = { init }; - return new LoopInit(initializers); + return new LoopInit(initializers); } /** - * Create a loop initialization that declares and assigns zero to a local - * variable. - * + * Create a loop initialization that declares and assigns zero to a local variable. + * *
          * type variable = 0
          * 
    - * - * @param type - * the static {@link KeYJavaType} of variable - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @return a new {@link ILoopInit} that declares variable - * variable with static type type and - * initial value zero + * + * @param type the static {@link KeYJavaType} of variable + * @param variable the named and typed {@link IProgramVariable} to be declared + * @return a new {@link ILoopInit} that declares variable variable with static type + * type and initial value zero */ - public static ILoopInit loopInitZero(final KeYJavaType type, - final IProgramVariable variable) { - final LoopInitializer initializer = KeYJavaASTFactory.declareZero(type, - variable); + public static ILoopInit loopInitZero(final KeYJavaType type, final IProgramVariable variable) { + final LoopInitializer initializer = KeYJavaASTFactory.declareZero(type, variable); - return KeYJavaASTFactory.loopInit(initializer); + return KeYJavaASTFactory.loopInit(initializer); } /** * Create an array initializer. - * - * @param expressions - * the initial value {@link Expression}s - * @param type - * the array type {@link KeYJavaType} - * @return a new {@link ArrayInitializer} which contains - * expressions and is of type type + * + * @param expressions the initial value {@link Expression}s + * @param type the array type {@link KeYJavaType} + * @return a new {@link ArrayInitializer} which contains expressions and is of type + * type */ - public static ArrayInitializer arrayInitializer( - final Expression[] expressions, final KeYJavaType type) { - final ArrayInitializer initializer = new ArrayInitializer(expressions, - type); + public static ArrayInitializer arrayInitializer(final Expression[] expressions, + final KeYJavaType type) { + final ArrayInitializer initializer = new ArrayInitializer(expressions, type); - return initializer; + return initializer; } /** * Create an array length access. - * + * *
          * array.length
          * 
    - * - * @param model - * the {@link JavaInfo} to retrieve the array super class type, - * which holds the length attribute, from - * @param array - * the {@link ReferencePrefix} whose length attribute is accessed - * @return a new {@link FieldReference} for array's length - * attribute + * + * @param model the {@link JavaInfo} to retrieve the array super class type, which holds the + * length attribute, from + * @param array the {@link ReferencePrefix} whose length attribute is accessed + * @return a new {@link FieldReference} for array's length attribute */ - public static FieldReference arrayLength(final JavaInfo model, - final ReferencePrefix array) { - final ProgramVariable lengthField = model.getArrayLength(); - final FieldReference reference = new FieldReference(lengthField, array); + public static FieldReference arrayLength(final JavaInfo model, final ReferencePrefix array) { + final ProgramVariable lengthField = model.getArrayLength(); + final FieldReference reference = new FieldReference(lengthField, array); - return reference; + return reference; } /** - * Create a condition that compares two expressions using the less than - * operator. - * + * Create a condition that compares two expressions using the less than operator. + * *
          * left < right
          * 
    - * - * @param left - * the {@link Expression} to be compared less than - * right - * @param right - * the Expression to be compared greater than - * left - * @return a new {@link Guard} that compares left less than - * right + * + * @param left the {@link Expression} to be compared less than right + * @param right the Expression to be compared greater than left + * @return a new {@link Guard} that compares left less than right */ - public static IGuard lessThanGuard(final Expression left, - final Expression right) { - final IGuard guard = new Guard(new LessThan(left, right)); + public static IGuard lessThanGuard(final Expression left, final Expression right) { + final IGuard guard = new Guard(new LessThan(left, right)); - return guard; + return guard; } /** * Create a less than operator. - * + * *
          * left < right
          * 
    - * - * @param left - * the left operand {@link Expression} - * @param right - * the right operand {@link Expression} - * @return a new {@link LessThan} that compares left less than - * right + * + * @param left the left operand {@link Expression} + * @param right the right operand {@link Expression} + * @return a new {@link LessThan} that compares left less than right */ - public static LessThan lessThanOperator(final Expression left, - final Expression right) { - final LessThan operator = new LessThan(left, right); + public static LessThan lessThanOperator(final Expression left, final Expression right) { + final LessThan operator = new LessThan(left, right); - return operator; + return operator; } /** * Create a less than zero operator. - * + * *
          * expression < 0
          * 
    - * - * @param expression - * the left operand {@link Expression} - * @return a new {@link LessThan} that compares expression less - * than 0 + * + * @param expression the left operand {@link Expression} + * @return a new {@link LessThan} that compares expression less than 0 */ public static LessThan lessThanZeroOperator(final Expression expression) { - final IntLiteral zeroLiteral = KeYJavaASTFactory.zeroLiteral(); - final LessThan operator = KeYJavaASTFactory.lessThanOperator( - expression, zeroLiteral); + final IntLiteral zeroLiteral = KeYJavaASTFactory.zeroLiteral(); + final LessThan operator = KeYJavaASTFactory.lessThanOperator(expression, zeroLiteral); - return operator; + return operator; } /** - * Create a condition that compares a variable and an array length using the - * less than operator. - * + * Create a condition that compares a variable and an array length using the less than operator. + * *
          * variable < array.length
          * 
    - * - * @param model - * the {@link JavaInfo} to retrieve the array super class type, - * which holds the length attribute, from - * @param variable - * the {@link ProgramVariable} to be compared less than - * array's length - * @param array - * the {@link ReferencePrefix} whose length attribute is accessed + * + * @param model the {@link JavaInfo} to retrieve the array super class type, which holds the + * length attribute, from + * @param variable the {@link ProgramVariable} to be compared less than array's + * length + * @param array the {@link ReferencePrefix} whose length attribute is accessed * @return a new {@link Guard} that compares variable less than * array's length */ public static IGuard lessThanArrayLengthGuard(final JavaInfo model, - final ProgramVariable variable, final ReferencePrefix array) { - final FieldReference length = KeYJavaASTFactory.arrayLength(model, - array); - final IGuard guard = KeYJavaASTFactory.lessThanGuard(variable, length); + final ProgramVariable variable, final ReferencePrefix array) { + final FieldReference length = KeYJavaASTFactory.arrayLength(model, array); + final IGuard guard = KeYJavaASTFactory.lessThanGuard(variable, length); - return guard; + return guard; } /** * Create a list of loop updates that consists of a single expression. - * + * *
          * update
          * 
    - * - * @param update - * the single update {@link Expression} - * @return a new {@link ForUpdates} that consists of update - * only + * + * @param update the single update {@link Expression} + * @return a new {@link ForUpdates} that consists of update only */ public static IForUpdates forUpdates(final Expression update) { - final IForUpdates forUpdates = new ForUpdates( - new ImmutableArray(update)); + final IForUpdates forUpdates = new ForUpdates(new ImmutableArray(update)); - return forUpdates; + return forUpdates; } /** * Create a loop update expression that post increments a given variable. - * + * *
          * variable++
          * 
    - * - * @param variable - * the {@link ProgramVariable} to be post incremented during the - * loop updates - * @return a new {@link ForUpdates} that consists of the post increment of - * variable + * + * @param variable the {@link ProgramVariable} to be post incremented during the loop updates + * @return a new {@link ForUpdates} that consists of the post increment of variable */ - public static IForUpdates postIncrementForUpdates( - final ProgramVariable variable) { - final Expression update = new PostIncrement(variable); - final IForUpdates forUpdates = KeYJavaASTFactory.forUpdates(update); + public static IForUpdates postIncrementForUpdates(final ProgramVariable variable) { + final Expression update = new PostIncrement(variable); + final IForUpdates forUpdates = KeYJavaASTFactory.forUpdates(update); - return forUpdates; + return forUpdates; } /** * Create an array field access with a single index. - * + * *
          * array[index]
          * 
    - * - * @param array - * the {@link ReferencePrefix} to be accessed - * @param index - * the array access index {@link Expression} - * @return a new {@link ArrayReference} for access of array at - * index + * + * @param array the {@link ReferencePrefix} to be accessed + * @param index the array access index {@link Expression} + * @return a new {@link ArrayReference} for access of array at index */ public static ArrayReference arrayFieldAccess(final ReferencePrefix array, - final Expression index) { - final Expression[] indices = new Expression[] { index }; - final ArrayReference access = new ArrayReference(array, indices); + final Expression index) { + final Expression[] indices = new Expression[] { index }; + final ArrayReference access = new ArrayReference(array, indices); - return access; + return access; } /** * Create a block from an arbitrary number of statements. - * - * @param statements - * the block statements as {@link ExtList} - * @return a new {@link StatementBlock} consisting of - * statements + * + * @param statements the block statements as {@link ExtList} + * @return a new {@link StatementBlock} consisting of statements */ public static StatementBlock block(final ExtList statements) { - final StatementBlock block = new StatementBlock(statements); + final StatementBlock block = new StatementBlock(statements); - return block; + return block; } /** * Create a block from an arbitrary number of statements. - * + * *
          * {
          *   statements;
          * }
          * 
    - * - * @param statements - * the {@link Statement}s to appear in the block - * @return a new {@link StatementBlock} that consists of the given - * statements in the very same order + * + * @param statements the {@link Statement}s to appear in the block + * @return a new {@link StatementBlock} that consists of the given statements in + * the very same order */ public static StatementBlock block(final Statement... statements) { - final StatementBlock block = new StatementBlock(statements); + final StatementBlock block = new StatementBlock(statements); - return block; + return block; } /** * Create a block from an arbitrary number of statements. - * + * *
          * {
          *   statements;
          * }
          * 
    - * - * @param statements - * the {@link Statement}s to appear in the block - * @return a new {@link StatementBlock} that consists of the given - * statements in the very same order + * + * @param statements the {@link Statement}s to appear in the block + * @return a new {@link StatementBlock} that consists of the given statements in + * the very same order */ public static StatementBlock block(final List statements) { - final Statement[] s = new Statement[statements.size()]; - final StatementBlock block = KeYJavaASTFactory.block(statements - .toArray(s)); + final Statement[] s = new Statement[statements.size()]; + final StatementBlock block = KeYJavaASTFactory.block(statements.toArray(s)); - return block; + return block; } /** * Create a for loop. - * - * @param parameters - * the loop definition parameters (initializer, guard, updates, - * body) as {@link ExtList} + * + * @param parameters the loop definition parameters (initializer, guard, updates, body) as + * {@link ExtList} * @return a new {@link For} as defined by parameters */ public static For forLoop(final ExtList parameters) { - final For loop = new For(parameters); + final For loop = new For(parameters); - return loop; + return loop; } /** - * Create a for loop from the loop definition and an arbitrary number of - * body statements. - * + * Create a for loop from the loop definition and an arbitrary number of body statements. + * *
          * for (init; guard; updates) {
          *    statements;
          * }
          * 
    - * - * @param init - * the {@link ILoopInit} loop initializations - * @param guard - * the {@link IGuard} loop condition - * @param updates - * the {@link IForUpdates} loop updates - * @param statements - * the body {@link Statement}s - * @return a new {@link For} with initializers init, condition - * guard, updates updates and body - * statements + * + * @param init the {@link ILoopInit} loop initializations + * @param guard the {@link IGuard} loop condition + * @param updates the {@link IForUpdates} loop updates + * @param statements the body {@link Statement}s + * @return a new {@link For} with initializers init, condition guard, + * updates updates and body statements */ - public static For forLoop(final ILoopInit init, final IGuard guard, - final IForUpdates updates, final Statement... statements) { - final StatementBlock body = KeYJavaASTFactory.block(statements); + public static For forLoop(final ILoopInit init, final IGuard guard, final IForUpdates updates, + final Statement... statements) { + final StatementBlock body = KeYJavaASTFactory.block(statements); - return new For(init, guard, updates, body); + return new For(init, guard, updates, body); } /** * Create a for loop with no initializer. - * + * *
          * for (; guard; updates)
          *     body
          * 
    - * - * @param guard - * the {@link IGuard} loop condition - * @param updates - * the {@link IForUpdates} loop updates - * @param body - * the body {@link Statement} - * @return a new {@link For} with condition guard, updates - * updates and body body + * + * @param guard the {@link IGuard} loop condition + * @param updates the {@link IForUpdates} loop updates + * @param body the body {@link Statement} + * @return a new {@link For} with condition guard, updates updates and + * body body */ - public static For forLoop(final IGuard guard, final IForUpdates updates, - final Statement body) { - final For loop = KeYJavaASTFactory.forLoop(null, guard, updates, body); + public static For forLoop(final IGuard guard, final IForUpdates updates, final Statement body) { + final For loop = KeYJavaASTFactory.forLoop(null, guard, updates, body); - return loop; + return loop; } /** * Create a for loop with no initializer. - * + * *
          * for (; guard; updates)
          *     body
          * 
    - * - * @param guard - * the {@link IGuard} loop condition - * @param updates - * the {@link IForUpdates} loop updates - * @param body - * the body {@link Statement}s - * @return a new {@link For} with condition guard, updates - * updates and body body + * + * @param guard the {@link IGuard} loop condition + * @param updates the {@link IForUpdates} loop updates + * @param body the body {@link Statement}s + * @return a new {@link For} with condition guard, updates updates and + * body body */ public static For forLoop(final IGuard guard, final IForUpdates updates, - final Statement[] body) { - final For loop = KeYJavaASTFactory.forLoop(null, guard, updates, body); + final Statement[] body) { + final For loop = KeYJavaASTFactory.forLoop(null, guard, updates, body); - return loop; + return loop; } /** * Create a statement that assigns an array element to a variable. - * + * *
          * variable = array[index];
          * 
    - * - * @param variable - * the {@link ProgramVariable} to be assigned to - * @param array - * the array {@link ReferencePrefix} to be accessed - * @param index - * the array access index {@link Expression} - * @return a new {@link CopyAssignment} of array element at - * index to variable + * + * @param variable the {@link ProgramVariable} to be assigned to + * @param array the array {@link ReferencePrefix} to be accessed + * @param index the array access index {@link Expression} + * @return a new {@link CopyAssignment} of array element at index to + * variable */ - public static CopyAssignment assignArrayField( - final ProgramVariable variable, final ReferencePrefix array, - final Expression index) { - final ArrayReference element = KeYJavaASTFactory.arrayFieldAccess( - array, index); - final CopyAssignment assignment = KeYJavaASTFactory.assign(variable, - element); + public static CopyAssignment assignArrayField(final ProgramVariable variable, + final ReferencePrefix array, final Expression index) { + final ArrayReference element = KeYJavaASTFactory.arrayFieldAccess(array, index); + final CopyAssignment assignment = KeYJavaASTFactory.assign(variable, element); - return assignment; + return assignment; } /** * Create a local variable declaration without initialization. - * - * @param parameters - * the declaration parameters (modifiers, type reference, - * variable specifications) as {@link ExtList} - * @return a new {@link LocalVariableDeclaration} as defined by - * parameters + * + * @param parameters the declaration parameters (modifiers, type reference, variable + * specifications) as {@link ExtList} + * @return a new {@link LocalVariableDeclaration} as defined by parameters */ public static LocalVariableDeclaration declare(final ExtList parameters) { - final LocalVariableDeclaration declaration = new LocalVariableDeclaration( - parameters); + final LocalVariableDeclaration declaration = new LocalVariableDeclaration(parameters); - return declaration; + return declaration; } /** * Create a local variable declaration without initialization. - * + * *
          * type variable;
          * 
    - * - * where type is variable's {@link KeYJavaType} as - * it is returned by {@link IProgramVariable#getKeYJavaType()}. - * - * @param variable - * the named and typed {@link IProgramVariable} to be declared + * + * where type is variable's {@link KeYJavaType} as it is returned by + * {@link IProgramVariable#getKeYJavaType()}. + * + * @param variable the named and typed {@link IProgramVariable} to be declared * @return a new {@link LocalVariableDeclaration} of variable */ - public static LocalVariableDeclaration declare( - final IProgramVariable variable) { - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - variable, (Expression) null); + public static LocalVariableDeclaration declare(final IProgramVariable variable) { + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(variable, (Expression) null); - return declaration; + return declaration; } /** * Create a local variable declaration. - * + * *
          * type variable = init;
          * 
    - * - * where type is variable's {@link KeYJavaType} as - * it is returned by {@link IProgramVariable#getKeYJavaType()}. - * - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with + * + * where type is variable's {@link KeYJavaType} as it is returned by + * {@link IProgramVariable#getKeYJavaType()}. + * + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with * @return a new {@link LocalVariableDeclaration} of variable */ - public static LocalVariableDeclaration declare( - final IProgramVariable variable, final Expression init) { - final KeYJavaType type = variable.getKeYJavaType(); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - variable, init, type); + public static LocalVariableDeclaration declare(final IProgramVariable variable, + final Expression init) { + final KeYJavaType type = variable.getKeYJavaType(); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(variable, init, type); - return declaration; + return declaration; } /** * Create a local variable declaration with a single modifier. - * + * *
          * modifier type variable = init;
          * 
    - * - * @param modifier - * the {@link Modifier} - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with - * @param type - * the static {@link KeYJavaType} of variable - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value - * init + * + * @param modifier the {@link Modifier} + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with + * @param type the static {@link KeYJavaType} of variable + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value init */ public static LocalVariableDeclaration declare(final Modifier modifier, - final IProgramVariable variable, final Expression init, - final KeYJavaType type) { - final ImmutableArray modifiers = new ImmutableArray( - modifier); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - modifiers, variable, init, type); + final IProgramVariable variable, final Expression init, final KeYJavaType type) { + final ImmutableArray modifiers = new ImmutableArray(modifier); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(modifiers, variable, init, type); - return declaration; + return declaration; } /** - * Create a local variable declaration with an arbitrary number of - * modifiers. - * + * Create a local variable declaration with an arbitrary number of modifiers. + * *
          * modifiers type variable = init;
          * 
    - * - * @param modifiers - * the {@link Modifier}s - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with - * @param type - * the static {@link KeYJavaType} of variable - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value - * init + * + * @param modifiers the {@link Modifier}s + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with + * @param type the static {@link KeYJavaType} of variable + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value init */ public static LocalVariableDeclaration declare(final Modifier[] modifiers, - final IProgramVariable variable, final Expression init, - final KeYJavaType type) { - final ImmutableArray m = new ImmutableArray( - modifiers); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - m, variable, init, type); + final IProgramVariable variable, final Expression init, final KeYJavaType type) { + final ImmutableArray m = new ImmutableArray(modifiers); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(m, variable, init, type); - return declaration; + return declaration; } /** - * Create a local variable declaration with an arbitrary number of - * modifiers. - * + * Create a local variable declaration with an arbitrary number of modifiers. + * *
          * modifiers type variable = init;
          * 
    - * - * @param modifiers - * the {@link Modifier}s - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with - * @param type - * the static {@link KeYJavaType} of variable - * @return a new {@link LocalVariableDeclaration} of variable - * with static type type and initial value - * init + * + * @param modifiers the {@link Modifier}s + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with + * @param type the static {@link KeYJavaType} of variable + * @return a new {@link LocalVariableDeclaration} of variable with static type + * type and initial value init */ - public static LocalVariableDeclaration declare( - final ImmutableArray modifiers, - final IProgramVariable variable, final Expression init, - final KeYJavaType type) { - final TypeRef typeRef = new TypeRef(type); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - modifiers, variable, init, typeRef); + public static LocalVariableDeclaration declare(final ImmutableArray modifiers, + final IProgramVariable variable, final Expression init, final KeYJavaType type) { + final TypeRef typeRef = new TypeRef(type); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(modifiers, variable, init, typeRef); - return declaration; + return declaration; } /** - * Create a local variable declaration with an arbitrary number of - * modifiers. - * + * Create a local variable declaration with an arbitrary number of modifiers. + * *
          * modifiers typeRef variable = init;
          * 
    - * - * @param modifiers - * the {@link Modifier}s - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with - * @param typeRef - * the static {@link TypeRef} of variable - * @return a new {@link LocalVariableDeclaration} of variable - * with static type typeRef and initial value - * init + * + * @param modifiers the {@link Modifier}s + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with + * @param typeRef the static {@link TypeRef} of variable + * @return a new {@link LocalVariableDeclaration} of variable with static type + * typeRef and initial value init */ - public static LocalVariableDeclaration declare( - final ImmutableArray modifiers, - final IProgramVariable variable, final Expression init, - final TypeReference typeRef) { - final VariableSpecification varSpec = KeYJavaASTFactory - .variableSpecification(variable, init, typeRef.getKeYJavaType()); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - modifiers, typeRef, varSpec); + public static LocalVariableDeclaration declare(final ImmutableArray modifiers, + final IProgramVariable variable, final Expression init, final TypeReference typeRef) { + final VariableSpecification varSpec = + KeYJavaASTFactory.variableSpecification(variable, init, typeRef.getKeYJavaType()); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(modifiers, typeRef, varSpec); - return declaration; + return declaration; } /** * Create a local variable declaration. - * + * *
          * modifiers typeRef specification
          * 
    - * - * @param modifiers - * the {@link Modifier}s - * @param typeRef - * the static {@link TypeRef} of the variable to be declared - * @param specification - * the {@link VariableSpecification} of the variable to be - * declared - * @return a new {@link LocalVariableDeclaration} of the variable specified - * by specification with static type - * typeRef + * + * @param modifiers the {@link Modifier}s + * @param typeRef the static {@link TypeRef} of the variable to be declared + * @param specification the {@link VariableSpecification} of the variable to be declared + * @return a new {@link LocalVariableDeclaration} of the variable specified by + * specification with static type typeRef */ - public static LocalVariableDeclaration declare( - final ImmutableArray modifiers, - final TypeReference typeRef, - final VariableSpecification specification) { - final LocalVariableDeclaration declaration = new LocalVariableDeclaration( - modifiers, typeRef, specification); + public static LocalVariableDeclaration declare(final ImmutableArray modifiers, + final TypeReference typeRef, final VariableSpecification specification) { + final LocalVariableDeclaration declaration = + new LocalVariableDeclaration(modifiers, typeRef, specification); - return declaration; + return declaration; } /** * Create local variable declarations. - * + * *
          * modifiers typeRef specification{1}, ...
          * 
    - * - * @param modifiers - * the {@link Modifier}s - * @param typeRef - * the static {@link TypeRef} of the variable to be declared - * @param specifications - * the {@link VariableSpecification}s of the variables to be - * declared - * @return a new {@link LocalVariableDeclaration} of the variables specified - * by specifications with static type - * typeRef + * + * @param modifiers the {@link Modifier}s + * @param typeRef the static {@link TypeRef} of the variable to be declared + * @param specifications the {@link VariableSpecification}s of the variables to be declared + * @return a new {@link LocalVariableDeclaration} of the variables specified by + * specifications with static type typeRef */ - public static LocalVariableDeclaration declare( - final ImmutableArray modifiers, - final TypeReference typeRef, - final VariableSpecification[] specifications) { - final LocalVariableDeclaration declaration = new LocalVariableDeclaration( - modifiers, typeRef, specifications); + public static LocalVariableDeclaration declare(final ImmutableArray modifiers, + final TypeReference typeRef, final VariableSpecification[] specifications) { + final LocalVariableDeclaration declaration = + new LocalVariableDeclaration(modifiers, typeRef, specifications); - return declaration; + return declaration; } /** * Create a method call. - * + * *
          * reference.name(args);
          * 
    - * - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param name - * the method's name {@link String} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on reference with arguments - * args + * + * @param reference the {@link ReferencePrefix} the method is called on + * @param name the method's name {@link String} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * reference with arguments args */ - public static MethodReference methodCall(final ReferencePrefix reference, - final String name, final ImmutableArray args) { - final ProgramElementName method = new ProgramElementName(name); - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - method, args); + public static MethodReference methodCall(final ReferencePrefix reference, final String name, + final ImmutableArray args) { + final ProgramElementName method = new ProgramElementName(name); + final MethodReference call = KeYJavaASTFactory.methodCall(reference, method, args); - return call; + return call; } /** * Create a method call on a type. - * + * *
          * type.name(args);
          * 
    - * - * @param type - * the {@link KeYJavaType} the method is called on - * @param name - * the method's name {@link String} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on type with arguments - * args + * + * @param type the {@link KeYJavaType} the method is called on + * @param name the method's name {@link String} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * type with arguments args */ - public static MethodReference methodCall(final KeYJavaType type, - final String name, final ImmutableArray args) { - final TypeReference typeRef = new TypeRef(type); - final MethodReference call = KeYJavaASTFactory.methodCall(typeRef, - name, args); + public static MethodReference methodCall(final KeYJavaType type, final String name, + final ImmutableArray args) { + final TypeReference typeRef = new TypeRef(type); + final MethodReference call = KeYJavaASTFactory.methodCall(typeRef, name, args); - return call; + return call; } /** * Create a method call on a type. - * + * *
          * type.name(args);
          * 
    - * - * @param type - * the {@link KeYJavaType} the method is called on - * @param name - * the method's name {@link String} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on type with arguments - * args + * + * @param type the {@link KeYJavaType} the method is called on + * @param name the method's name {@link String} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * type with arguments args */ - public static MethodReference methodCall(final KeYJavaType type, - final String name, final Expression... args) { - final TypeReference typeRef = new TypeRef(type); - final MethodReference call = KeYJavaASTFactory.methodCall(typeRef, - name, args); + public static MethodReference methodCall(final KeYJavaType type, final String name, + final Expression... args) { + final TypeReference typeRef = new TypeRef(type); + final MethodReference call = KeYJavaASTFactory.methodCall(typeRef, name, args); - return call; + return call; } /** * Create a method call on a type with no arguments. - * + * *
          * type.name();
          * 
    - * - * @param type - * the {@link KeYJavaType} the method is called on - * @param name - * the method's name {@link String} - * @return a new {@link MethodReference} for call of method - * name on type with arguments - * args + * + * @param type the {@link KeYJavaType} the method is called on + * @param name the method's name {@link String} + * @return a new {@link MethodReference} for call of method name on + * type with arguments args */ - public static MethodReference methodCall(final KeYJavaType type, - final String name) { - final ImmutableArray args = new ImmutableArray(); - final MethodReference call = KeYJavaASTFactory.methodCall(type, name, - args); + public static MethodReference methodCall(final KeYJavaType type, final String name) { + final ImmutableArray args = new ImmutableArray(); + final MethodReference call = KeYJavaASTFactory.methodCall(type, name, args); - return call; + return call; } /** * Create a method call with no arguments. - * + * *
          * reference.name();
          * 
    - * - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param name - * the method's name {@link String} - * @return a new {@link MethodReference} for call of method - * name on reference with no arguments + * + * @param reference the {@link ReferencePrefix} the method is called on + * @param name the method's name {@link String} + * @return a new {@link MethodReference} for call of method name on + * reference with no arguments */ - public static MethodReference methodCall(final ReferencePrefix reference, - final String name) { - final ImmutableArray args = new ImmutableArray(); - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - name, args); + public static MethodReference methodCall(final ReferencePrefix reference, final String name) { + final ImmutableArray args = new ImmutableArray(); + final MethodReference call = KeYJavaASTFactory.methodCall(reference, name, args); - return call; + return call; } /** * Create a method call. - * + * *
          * reference.name(args);
          * 
    - * - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param name - * the method's name {@link String} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on reference with arguments - * args + * + * @param reference the {@link ReferencePrefix} the method is called on + * @param name the method's name {@link String} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * reference with arguments args */ - public static MethodReference methodCall(final ReferencePrefix reference, - final String name, final Expression... args) { - final ImmutableArray a = new ImmutableArray( - args); - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - name, a); + public static MethodReference methodCall(final ReferencePrefix reference, final String name, + final Expression... args) { + final ImmutableArray a = new ImmutableArray(args); + final MethodReference call = KeYJavaASTFactory.methodCall(reference, name, a); - return call; + return call; } /** * Create a method call. - * + * *
          * reference.name(args);
          * 
    - * - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param name - * the {@link MethodName} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on reference with arguments - * args + * + * @param reference the {@link ReferencePrefix} the method is called on + * @param name the {@link MethodName} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * reference with arguments args */ - public static MethodReference methodCall(final ReferencePrefix reference, - final MethodName name, final Expression... args) { - final ImmutableArray a = new ImmutableArray( - args); - final MethodReference call = KeYJavaASTFactory.methodCall(reference, - name, a); + public static MethodReference methodCall(final ReferencePrefix reference, final MethodName name, + final Expression... args) { + final ImmutableArray a = new ImmutableArray(args); + final MethodReference call = KeYJavaASTFactory.methodCall(reference, name, a); - return call; + return call; } /** * Create a method call. - * + * *
          * reference.name(args);
          * 
    - * - * @param reference - * the {@link ReferencePrefix} the method is called on - * @param name - * the {@link MethodName} - * @param args - * the argument {@link Expression}s to be passed to the method - * @return a new {@link MethodReference} for call of method - * name on reference with arguments - * args + * + * @param reference the {@link ReferencePrefix} the method is called on + * @param name the {@link MethodName} + * @param args the argument {@link Expression}s to be passed to the method + * @return a new {@link MethodReference} for call of method name on + * reference with arguments args */ - public static MethodReference methodCall(final ReferencePrefix reference, - final MethodName name, - final ImmutableArray args) { - final MethodReference call = new MethodReference(args, name, reference); + public static MethodReference methodCall(final ReferencePrefix reference, final MethodName name, + final ImmutableArray args) { + final MethodReference call = new MethodReference(args, name, reference); - return call; + return call; } /** * Create a field access. - * + * *
          * (expression).name
          * 
    - * - * @param services - * the {@link Services} to determine both expression - * 's {@link KeYJavaType} and the {@link ProgramVariable} - * corresponding to the field name - * @param name - * the to be accessed field's name {@link String} - * @param expression - * the {@link Expression} on which the field is accessed - * @param context - * the {@link ExecutionContext}, which is needed to determine - * expression's KeYJavaType - * @return a new {@link FieldReference} of field name on - * expression + * + * @param services the {@link Services} to determine both expression 's + * {@link KeYJavaType} and the {@link ProgramVariable} corresponding to the field + * name + * @param name the to be accessed field's name {@link String} + * @param expression the {@link Expression} on which the field is accessed + * @param context the {@link ExecutionContext}, which is needed to determine + * expression's KeYJavaType + * @return a new {@link FieldReference} of field name on expression */ - public static FieldReference fieldReference(final Services services, - final String name, final Expression expression, - final ExecutionContext context) { - final KeYJavaType classType = expression.getKeYJavaType(services, - context); - final ProgramVariable field = services.getJavaInfo().getAttribute(name, - classType); - final FieldReference reference = KeYJavaASTFactory.fieldReference( - new ParenthesizedExpression(expression), field); + public static FieldReference fieldReference(final Services services, final String name, + final Expression expression, final ExecutionContext context) { + final KeYJavaType classType = expression.getKeYJavaType(services, context); + final ProgramVariable field = services.getJavaInfo().getAttribute(name, classType); + final FieldReference reference = + KeYJavaASTFactory.fieldReference(new ParenthesizedExpression(expression), field); - return reference; + return reference; } /** * Create a field access. - * + * *
          * prefix.field
          * 
    - * - * @param prefix - * the {@link ReferencePrefix} on which field is - * accessed - * @param field - * the {@link ProgramVariable} to be accessed - * @return a new {@link FieldReference} of field on - * prefix + * + * @param prefix the {@link ReferencePrefix} on which field is accessed + * @param field the {@link ProgramVariable} to be accessed + * @return a new {@link FieldReference} of field on prefix */ public static FieldReference fieldReference(final ReferencePrefix prefix, - final ProgramVariable field) { - final FieldReference reference = new FieldReference(field, prefix); + final ProgramVariable field) { + final FieldReference reference = new FieldReference(field, prefix); - return reference; + return reference; } /** * Create a finally block. - * - * @param parameters - * the finally block parameters (body) as {@link ExtList} + * + * @param parameters the finally block parameters (body) as {@link ExtList} * @return a new {@link Finally} as defined by parameters */ public static Finally finallyBlock(final ExtList parameters) { - final Finally block = new Finally(parameters); + final Finally block = new Finally(parameters); - return block; + return block; } /** * Create a finally block. - * + * *
          * finally
          *     statement
          * 
    - * - * @param statement - * the {@link Statement} to be executed - * @return a new {@link Finally} block consisting of statement - * solely + * + * @param statement the {@link Statement} to be executed + * @return a new {@link Finally} block consisting of statement solely */ public static Finally finallyBlock(final Statement statement) { - final StatementBlock body = KeYJavaASTFactory.block(statement); - final Finally block = KeYJavaASTFactory.finallyBlock(body); + final StatementBlock body = KeYJavaASTFactory.block(statement); + final Finally block = KeYJavaASTFactory.finallyBlock(body); - return block; + return block; } /** * Create a finally block. - * + * *
          * finally {
          *     statements
          * }
          * 
    - * - * @param statements - * the {@link Statement}s to be executed - * @return a new {@link Finally} block consisting of statements - * solely + * + * @param statements the {@link Statement}s to be executed + * @return a new {@link Finally} block consisting of statements solely */ public static Finally finallyBlock(final Statement[] statements) { - final StatementBlock body = KeYJavaASTFactory.block(statements); - final Finally block = KeYJavaASTFactory.finallyBlock(body); + final StatementBlock body = KeYJavaASTFactory.block(statements); + final Finally block = KeYJavaASTFactory.finallyBlock(body); - return block; + return block; } /** * Create a finally block. - * + * *
          * finally
          *     body
          * 
    - * - * @param body - * the {@link StatementBlock} to be executed - * @return a new {@link Finally} block consisting of body - * solely + * + * @param body the {@link StatementBlock} to be executed + * @return a new {@link Finally} block consisting of body solely */ public static Finally finallyBlock(final StatementBlock body) { - final Finally block = new Finally(body); + final Finally block = new Finally(body); - return block; + return block; } /** - * Create a local array variable declaration with an arbitrary number of - * modifiers. - * + * Create a local array variable declaration with an arbitrary number of modifiers. + * *
          * modifiers typePrefix.baseType[] variable = init;
          * 
    - * - * @param modifiers - * the {@link Modifiers} - * @param variable - * the named and typed {@link IProgramVariable} to be declared - * @param init - * the {@link Expression} variable is initialized - * with - * @param typeName - * the type's {@link ProgramElementName} - * @param dimensions - * the type's dimensions - * @param typePrefix - * the type's {@link ReferencePrefix} - * @param baseType - * the base {@link KeYJavaType} - * @return a new {@link LocalVariableDeclaration} of variable - * with static type baseType[dimensions] and initial - * value init + * + * @param modifiers the {@link Modifiers} + * @param variable the named and typed {@link IProgramVariable} to be declared + * @param init the {@link Expression} variable is initialized with + * @param typeName the type's {@link ProgramElementName} + * @param dimensions the type's dimensions + * @param typePrefix the type's {@link ReferencePrefix} + * @param baseType the base {@link KeYJavaType} + * @return a new {@link LocalVariableDeclaration} of variable with static type + * baseType[dimensions] and initial value init */ - public static ProgramElement declare( - final ImmutableArray modifiers, - final IProgramVariable variable, final Expression init, - final ProgramElementName typeName, final int dimensions, - final ReferencePrefix typePrefix, final KeYJavaType baseType) { - final TypeRef typeRef = new TypeRef(typeName, dimensions, typePrefix, - baseType); - final LocalVariableDeclaration declaration = KeYJavaASTFactory.declare( - modifiers, variable, init, typeRef); + public static ProgramElement declare(final ImmutableArray modifiers, + final IProgramVariable variable, final Expression init, + final ProgramElementName typeName, final int dimensions, + final ReferencePrefix typePrefix, final KeYJavaType baseType) { + final TypeRef typeRef = new TypeRef(typeName, dimensions, typePrefix, baseType); + final LocalVariableDeclaration declaration = + KeYJavaASTFactory.declare(modifiers, variable, init, typeRef); - return declaration; + return declaration; } /** * Create a method body shortcut. - * - * Note that classType is also used as visibility context when - * looking for methodName in its definition. - * - * @param model - * the {@link JavaInfo} that contains - * classType.methodName - * @param result - * the {@link ProgramVariable} the return value is assigned to or - * null - * @param reference - * the {@link ReferencePrefix} invocation target - * @param classType - * the {@link KeYJavaType} in which the method is declared - * @param methodName - * the method's {@link String} name - * @param arguments - * the ProgramVariable and their static types the - * method is called with - * @return a new {@link MethodBodyStatement} for - * classType.methodName when called with - * arguments or null when the former is - * not defined - */ - public static MethodBodyStatement methodBody(final JavaInfo model, - final ProgramVariable result, final ReferencePrefix reference, - final KeYJavaType classType, final String methodName, - final ProgramVariable[] arguments) { - final IProgramMethod method = model.getProgramMethod(classType, - methodName, arguments, classType); - MethodBodyStatement methodBody = null; - - if (method != null) { - methodBody = KeYJavaASTFactory.methodBody(result, reference, - method, arguments); - } - - return methodBody; + * + * Note that classType is also used as visibility context when looking for + * methodName in its definition. + * + * @param model the {@link JavaInfo} that contains classType.methodName + * @param result the {@link ProgramVariable} the return value is assigned to or + * null + * @param reference the {@link ReferencePrefix} invocation target + * @param classType the {@link KeYJavaType} in which the method is declared + * @param methodName the method's {@link String} name + * @param arguments the ProgramVariable and their static types the method is called + * with + * @return a new {@link MethodBodyStatement} for classType.methodName when called + * with arguments or null when the former is not defined + */ + public static MethodBodyStatement methodBody(final JavaInfo model, final ProgramVariable result, + final ReferencePrefix reference, final KeYJavaType classType, final String methodName, + final ProgramVariable[] arguments) { + final IProgramMethod method = + model.getProgramMethod(classType, methodName, arguments, classType); + MethodBodyStatement methodBody = null; + + if (method != null) { + methodBody = KeYJavaASTFactory.methodBody(result, reference, method, arguments); + } + + return methodBody; } /** * Create a method body shortcut. - * - * @param result - * the {@link ProgramVariable} the return value is assigned to or - * null - * @param reference - * the {@link ReferencePrefix} invocation target - * @param method - * the {@link IProgramMethod} reference - * @param arguments - * the Expressions and their static types the method - * is called with - * @return a new {@link MethodBodyStatement} for method when - * called with arguments + * + * @param result the {@link ProgramVariable} the return value is assigned to or + * null + * @param reference the {@link ReferencePrefix} invocation target + * @param method the {@link IProgramMethod} reference + * @param arguments the Expressions and their static types the method is called + * with + * @return a new {@link MethodBodyStatement} for method when called with + * arguments */ public static MethodBodyStatement methodBody(final ProgramVariable result, - final ReferencePrefix reference, final IProgramMethod method, - final Expression[] arguments) { - final MethodBodyStatement methodBody = KeYJavaASTFactory.methodBody( - result, reference, method, new ImmutableArray( - arguments)); + final ReferencePrefix reference, final IProgramMethod method, + final Expression[] arguments) { + final MethodBodyStatement methodBody = KeYJavaASTFactory.methodBody(result, reference, + method, new ImmutableArray(arguments)); - return methodBody; + return methodBody; } /** * Create a method body shortcut. - * - * @param result - * the {@link ProgramVariable} the return value is assigned to or - * null - * @param reference - * the {@link ReferencePrefix} invocation target - * @param method - * the {@link IProgramMethod} reference - * @param arguments - * the Expressions and their static types the method - * is called with - * @return a new {@link MethodBodyStatement} for method when - * called with arguments + * + * @param result the {@link ProgramVariable} the return value is assigned to or + * null + * @param reference the {@link ReferencePrefix} invocation target + * @param method the {@link IProgramMethod} reference + * @param arguments the Expressions and their static types the method is called + * with + * @return a new {@link MethodBodyStatement} for method when called with + * arguments */ public static MethodBodyStatement methodBody(final ProgramVariable result, - final ReferencePrefix reference, final IProgramMethod method, - final ImmutableArray arguments) { - final MethodBodyStatement methodBody = new MethodBodyStatement(method, - reference, result, arguments); + final ReferencePrefix reference, final IProgramMethod method, + final ImmutableArray arguments) { + final MethodBodyStatement methodBody = + new MethodBodyStatement(method, reference, result, arguments); - return methodBody; + return methodBody; } /** * Create a method call substitution. - * - * @param executionContext - * the block's {@link IExecutionContext} - * @param block - * the {@link StatementBlock} to be put in executionContext + * + * @param executionContext the block's {@link IExecutionContext} + * @param block the {@link StatementBlock} to be put in executionContext * @return a new {@link MethodFrame} that associates block with * executionContext */ - public static MethodFrame methodFrame( - final IExecutionContext executionContext, final StatementBlock block) { - final MethodFrame frame = KeYJavaASTFactory.methodFrame(null, - executionContext, block); + public static MethodFrame methodFrame(final IExecutionContext executionContext, + final StatementBlock block) { + final MethodFrame frame = KeYJavaASTFactory.methodFrame(null, executionContext, block); - return frame; + return frame; } /** * Create a method call substitution at a specific source position. - * - * @param executionContext - * the block's {@link IExecutionContext} - * @param block - * the {@link StatementBlock} to be put in - * executionContext - * @param position - * the new source element's {@link PositionInfo} + * + * @param executionContext the block's {@link IExecutionContext} + * @param block the {@link StatementBlock} to be put in executionContext + * @param position the new source element's {@link PositionInfo} * @return a new {@link MethodFrame} that associates block with - * executionContext and positions it at - * position + * executionContext and positions it at position */ - public static MethodFrame methodFrame( - final IExecutionContext executionContext, - final StatementBlock block, final PositionInfo position) { - final MethodFrame frame = KeYJavaASTFactory.methodFrame(null, - executionContext, block, position); + public static MethodFrame methodFrame(final IExecutionContext executionContext, + final StatementBlock block, final PositionInfo position) { + final MethodFrame frame = + KeYJavaASTFactory.methodFrame(null, executionContext, block, position); - return frame; + return frame; } /** * Create a method call substitution with a return value assignment. - * - * @param result - * the {@link IProgramVariable} block's return value - * is assigned to - * @param executionContext - * the block's {@link IExecutionContext} - * @param block - * the {@link StatementBlock} to be put in - * executionContext + * + * @param result the {@link IProgramVariable} block's return value is assigned to + * @param executionContext the block's {@link IExecutionContext} + * @param block the {@link StatementBlock} to be put in executionContext * @return a new {@link MethodFrame} that associates block with * executionContext */ public static MethodFrame methodFrame(final IProgramVariable result, - final IExecutionContext executionContext, final StatementBlock block) { - final MethodFrame frame = new MethodFrame(result, executionContext, - block); - - return frame; - } - - /** - * Create a method call substitution with a return value assignment at a - * specific source position. - * - * @param result - * the {@link IProgramVariable} block's return value - * is assigned to - * @param executionContext - * the block's {@link IExecutionContext} - * @param block - * the {@link StatementBlock} to be put in - * executionContext - * @param position - * the new source element's {@link PositionInfo} + final IExecutionContext executionContext, final StatementBlock block) { + final MethodFrame frame = new MethodFrame(result, executionContext, block); + + return frame; + } + + /** + * Create a method call substitution with a return value assignment at a specific source + * position. + * + * @param result the {@link IProgramVariable} block's return value is assigned to + * @param executionContext the block's {@link IExecutionContext} + * @param block the {@link StatementBlock} to be put in executionContext + * @param position the new source element's {@link PositionInfo} * @return a new {@link MethodFrame} that associates block with - * executionContext and positions it at - * position + * executionContext and positions it at position */ public static MethodFrame methodFrame(final IProgramVariable result, - final IExecutionContext executionContext, - final StatementBlock block, final PositionInfo position) { - final MethodFrame frame = new MethodFrame(result, executionContext, - block, position); + final IExecutionContext executionContext, final StatementBlock block, + final PositionInfo position) { + final MethodFrame frame = new MethodFrame(result, executionContext, block, position); - return frame; + return frame; } /** * Create an integer literal. - * - * @param value - * the {@link Integer} to be turned into an literal + * + * @param value the {@link Integer} to be turned into an literal * @return a new {@link IntLiteral} representing value */ public static IntLiteral intLiteral(final Integer value) { - final IntLiteral literal = new IntLiteral(value); + final IntLiteral literal = new IntLiteral(value); - return literal; + return literal; } /** * Create a labeled statement. - * - * @param parameters - * the parameters (statement) as {@link ExtList} - * @param label - * the {@link Label} - * @param position - * the new source element's {@link PositionInfo} - * @return a new {@link LabeledStatement} as defined by - * parameters and label + * + * @param parameters the parameters (statement) as {@link ExtList} + * @param label the {@link Label} + * @param position the new source element's {@link PositionInfo} + * @return a new {@link LabeledStatement} as defined by parameters and + * label */ - public static LabeledStatement labeledStatement(final ExtList parameters, - final Label label, final PositionInfo position) { - final LabeledStatement statement = new LabeledStatement(parameters, - label, position); + public static LabeledStatement labeledStatement(final ExtList parameters, final Label label, + final PositionInfo position) { + final LabeledStatement statement = new LabeledStatement(parameters, label, position); - return statement; + return statement; } /** * Create a labeled statement. - * + * *
          * label: statement
          * 
    - * - * @param label - * the {@link Label} - * @param statement - * the {@link Statement} to be labeled - * @return a new {@link LabeledStatement} that adds label to - * statement + * + * @param label the {@link Label} + * @param statement the {@link Statement} to be labeled + * @return a new {@link LabeledStatement} that adds label to statement */ - public static LabeledStatement labeledStatement(final Label label, - final Statement statement, PositionInfo pos) { - final LabeledStatement labeled = new LabeledStatement(label, statement, pos); + public static LabeledStatement labeledStatement(final Label label, final Statement statement, + PositionInfo pos) { + final LabeledStatement labeled = new LabeledStatement(label, statement, pos); - return labeled; + return labeled; } /** * Create a labeled block of statements. - * + * *
          * label: {
          *     statements
          * }
          * 
    - * - * @param label - * the {@link Label} - * @param statements - * the {@link Statement}s to be labeled + * + * @param label the {@link Label} + * @param statements the {@link Statement}s to be labeled * @return a new {@link LabeledStatement} that adds label to * statements */ - public static Statement labeledStatement(final Label label, - final Statement[] statements, PositionInfo pos) { - final StatementBlock block = KeYJavaASTFactory.block(statements); - final LabeledStatement labeled = KeYJavaASTFactory.labeledStatement( - label, block, pos); + public static Statement labeledStatement(final Label label, final Statement[] statements, + PositionInfo pos) { + final StatementBlock block = KeYJavaASTFactory.block(statements); + final LabeledStatement labeled = KeYJavaASTFactory.labeledStatement(label, block, pos); - return labeled; + return labeled; } /** * Create an array instantiation. - * + * *
          * new typeRef[sizes{1}]...[sizes{dimensions}] initializer
          * 
    - * - * @param sizes - * the size {@link Expression}s for each dimension - * @param typeRef - * the static array base type - * @param keyJavaType - * the array element type - * @param initializer - * the {@link ArrayInitializer} - * @param dimensions - * the number of dimensions - * @return a new {@link NewArray} for the instantiation of an array of base - * type typeRef with dimensions dimensions + * + * @param sizes the size {@link Expression}s for each dimension + * @param typeRef the static array base type + * @param keyJavaType the array element type + * @param initializer the {@link ArrayInitializer} + * @param dimensions the number of dimensions + * @return a new {@link NewArray} for the instantiation of an array of base type + * typeRef with dimensions dimensions */ - public static NewArray newArray(final TypeReference typeRef, - final int dimensions, final Expression[] sizes, - final ArrayInitializer initializer, final KeYJavaType keyJavaType) { - final NewArray newArray = new NewArray(sizes, typeRef, keyJavaType, - initializer, dimensions); + public static NewArray newArray(final TypeReference typeRef, final int dimensions, + final Expression[] sizes, final ArrayInitializer initializer, + final KeYJavaType keyJavaType) { + final NewArray newArray = + new NewArray(sizes, typeRef, keyJavaType, initializer, dimensions); - return newArray; + return newArray; } /** * Create an array instantiation. - * + * *
          * new typeRef[sizes{1}]...[sizes{dimensions}]
          * 
    - * - * @param typeRef - * the static array base type - * @param dimensions - * the number of dimensions - * @param sizes - * the size {@link Expression}s for each dimension - * @param keyJavaType - * the array element type - * @return a new {@link NewArray} for the instantiation of an array of base - * type typeRef with dimensions dimensions + * + * @param typeRef the static array base type + * @param dimensions the number of dimensions + * @param sizes the size {@link Expression}s for each dimension + * @param keyJavaType the array element type + * @return a new {@link NewArray} for the instantiation of an array of base type + * typeRef with dimensions dimensions */ - public static NewArray newArray(final TypeReference typeRef, - final int dimensions, final Expression[] sizes, - final KeYJavaType keyJavaType) { - final NewArray newArray = KeYJavaASTFactory.newArray(typeRef, - dimensions, sizes, null, keyJavaType); + public static NewArray newArray(final TypeReference typeRef, final int dimensions, + final Expression[] sizes, final KeYJavaType keyJavaType) { + final NewArray newArray = + KeYJavaASTFactory.newArray(typeRef, dimensions, sizes, null, keyJavaType); - return newArray; + return newArray; } /** * Create an array instantiation. - * + * *
          * new typeRef[size]
          * 
    - * - * @param typeRef - * the static array base type - * @param dimensions - * the number of dimensions - * @param size - * the size {@link Expression} for the first dimension - * @param keyJavaType - * the array element type - * @return a new {@link NewArray} for the instantiation of an array of base - * type typeRef with dimensions dimensions + * + * @param typeRef the static array base type + * @param dimensions the number of dimensions + * @param size the size {@link Expression} for the first dimension + * @param keyJavaType the array element type + * @return a new {@link NewArray} for the instantiation of an array of base type + * typeRef with dimensions dimensions */ - public static NewArray newArray(final TypeReference typeRef, - final int dimensions, final Expression size, - final KeYJavaType keyJavaType) { - final Expression[] sizes = new Expression[] { size }; - final NewArray newArray = KeYJavaASTFactory.newArray(typeRef, - dimensions, sizes, null, keyJavaType); + public static NewArray newArray(final TypeReference typeRef, final int dimensions, + final Expression size, final KeYJavaType keyJavaType) { + final Expression[] sizes = new Expression[] { size }; + final NewArray newArray = + KeYJavaASTFactory.newArray(typeRef, dimensions, sizes, null, keyJavaType); - return newArray; + return newArray; } /** * Create an array instantiation. - * + * *
          * new typeRef[]...[] initializer
          * 
    - * - * @param typeRef - * the static array base type - * @param keyJavaType - * the array element type - * @param initializer - * the {@link ArrayInitializer} - * @param dimensions - * the number of dimensions - * @return a new {@link NewArray} for the instantiation of an array of base - * type typeRef with dimensions dimensions + * + * @param typeRef the static array base type + * @param keyJavaType the array element type + * @param initializer the {@link ArrayInitializer} + * @param dimensions the number of dimensions + * @return a new {@link NewArray} for the instantiation of an array of base type + * typeRef with dimensions dimensions */ - public static NewArray newArray(final TypeReference typeRef, - final int dimensions, final ArrayInitializer initializer, - final KeYJavaType keyJavaType) { - final Expression[] sizes = new Expression[0]; - final NewArray newArray = KeYJavaASTFactory.newArray(typeRef, - dimensions, sizes, initializer, keyJavaType); + public static NewArray newArray(final TypeReference typeRef, final int dimensions, + final ArrayInitializer initializer, final KeYJavaType keyJavaType) { + final Expression[] sizes = new Expression[0]; + final NewArray newArray = + KeYJavaASTFactory.newArray(typeRef, dimensions, sizes, initializer, keyJavaType); - return newArray; + return newArray; } /** * Create an object allocation. - * + * *
          * new referencePrefix.typeReference(args)
          * 
    - * - * @param referencePrefix - * the typeReference's {@link ReferencePrefix} - * @param typeReference - * a {@link TypeReference} to the class type that is instantiated - * @param args - * the {@link Expression} arguments to be passed to the - * constructor + * + * @param referencePrefix the typeReference's {@link ReferencePrefix} + * @param typeReference a {@link TypeReference} to the class type that is instantiated + * @param args the {@link Expression} arguments to be passed to the constructor * @return a new {@link New} operator that allocates a new instance of * typeReference parameterized with args */ public static New newOperator(final ReferencePrefix referencePrefix, - final TypeReference typeReference, final Expression[] args) { - final New operator = new New(args, typeReference, referencePrefix); + final TypeReference typeReference, final Expression[] args) { + final New operator = new New(args, typeReference, referencePrefix); - return operator; + return operator; } /** * Create an object allocation. - * + * *
          * new referencePrefix.type(args)
          * 
    - * - * @param referencePrefix - * the type's {@link ReferencePrefix} - * @param type - * the {@link KeYJavaType} to be instantiated - * @param args - * the {@link Expression} arguments to be passed to the - * constructor - * @return a new {@link New} operator that allocates a new instance of - * type parameterized with args + * + * @param referencePrefix the type's {@link ReferencePrefix} + * @param type the {@link KeYJavaType} to be instantiated + * @param args the {@link Expression} arguments to be passed to the constructor + * @return a new {@link New} operator that allocates a new instance of type + * parameterized with args */ - public static New newOperator(final ReferencePrefix referencePrefix, - final KeYJavaType type, final Expression[] args) { - final TypeReference typeRef = new TypeRef(type); - final New operator = KeYJavaASTFactory.newOperator(referencePrefix, - typeRef, args); + public static New newOperator(final ReferencePrefix referencePrefix, final KeYJavaType type, + final Expression[] args) { + final TypeReference typeRef = new TypeRef(type); + final New operator = KeYJavaASTFactory.newOperator(referencePrefix, typeRef, args); - return operator; + return operator; } /** * Create an object allocation without arguments. - * + * *
          * new referencePrefix.type()
          * 
    - * - * @param referencePrefix - * the type's {@link ReferencePrefix} - * @param type - * the {@link KeYJavaType} to be instantiated - * @return a new {@link New} operator that allocates a new instance of - * type + * + * @param referencePrefix the type's {@link ReferencePrefix} + * @param type the {@link KeYJavaType} to be instantiated + * @return a new {@link New} operator that allocates a new instance of type */ - public static New newOperator(final ReferencePrefix referencePrefix, - final KeYJavaType type) { - final Expression[] args = new Expression[0]; - final New operator = KeYJavaASTFactory.newOperator(referencePrefix, - type, args); + public static New newOperator(final ReferencePrefix referencePrefix, final KeYJavaType type) { + final Expression[] args = new Expression[0]; + final New operator = KeYJavaASTFactory.newOperator(referencePrefix, type, args); - return operator; + return operator; } /** * Create an object allocation without arguments. - * + * *
          * new type()
          * 
    - * - * @param type - * the {@link KeYJavaType} to be instantiated - * @return a new {@link New} operator that allocates a new instance of - * type + * + * @param type the {@link KeYJavaType} to be instantiated + * @return a new {@link New} operator that allocates a new instance of type */ public static New newOperator(final KeYJavaType type) { - final New operator = KeYJavaASTFactory.newOperator(null, type); + final New operator = KeYJavaASTFactory.newOperator(null, type); - return operator; + return operator; } /** * Create an unequal operator. - * + * *
          * operands{1} != operands{2}
          * 
    - * - * @param operands - * the operands {@link ExtList} + * + * @param operands the operands {@link ExtList} * @return a new {@link NotEquals} of operands */ public static NotEquals notEqualsOperator(final ExtList operands) { - final NotEquals operator = new NotEquals(operands); + final NotEquals operator = new NotEquals(operands); - return operator; + return operator; } /** * Create a call to the super constructor. - * + * *
          * super(args)
          * 
    - * - * @param referencePrefix - * the enclosing class type - * @param args - * the {@link Expression} arguments to be passed to constructor - * @return a new {@link SuperConstructorReference} parameterized with - * args + * + * @param referencePrefix the enclosing class type + * @param args the {@link Expression} arguments to be passed to constructor + * @return a new {@link SuperConstructorReference} parameterized with args */ - public static SuperConstructorReference superConstructor( - final ReferencePrefix referencePrefix, final Expression[] args) { - final SuperConstructorReference constructor = new SuperConstructorReference( - args); + public static SuperConstructorReference superConstructor(final ReferencePrefix referencePrefix, + final Expression[] args) { + final SuperConstructorReference constructor = new SuperConstructorReference(args); - return constructor; + return constructor; } /** * Create a reference to super. - * + * * @return a new {@link SuperReference} */ public static SuperReference superReference() { - final SuperReference reference = new SuperReference(); + final SuperReference reference = new SuperReference(); - return reference; + return reference; } /** * Create a switch block. - * + * *
          * switch (expression) {
          *     branches
          * }
          * 
    - * - * @param expression - * the to be evaluated {@link Expression} - * @param branches - * the switch-case {@link Branch}es - * @return a new {@link Switch} block that executes branches - * depending on the value of expression + * + * @param expression the to be evaluated {@link Expression} + * @param branches the switch-case {@link Branch}es + * @return a new {@link Switch} block that executes branches depending on the value + * of expression */ - public static Switch switchBlock(final Expression expression, - final Branch[] branches) { - final Switch block = new Switch(expression, branches); + public static Switch switchBlock(final Expression expression, final Branch[] branches) { + final Switch block = new Switch(expression, branches); - return block; + return block; } /** * Create a switch block. - * - * @param parameters - * the switch-case parameters (guard, body, branches) as - * {@link ExtList} + * + * @param parameters the switch-case parameters (guard, body, branches) as {@link ExtList} * @return a new {@link Switch} as defined by parameters */ public static Switch switchBlock(final ExtList parameters) { - final Switch block = new Switch(parameters); + final Switch block = new Switch(parameters); - return block; + return block; } /** * Create a synchronized block. - * - * @param parameters - * the synchronized block parameters (monitor, body) as - * {@link ExtList} - * @return a new {@link SynchronizedBlock} as defined by - * parameters + * + * @param parameters the synchronized block parameters (monitor, body) as {@link ExtList} + * @return a new {@link SynchronizedBlock} as defined by parameters */ public static SynchronizedBlock synchronizedBlock(final ExtList parameters) { - final SynchronizedBlock block = new SynchronizedBlock(parameters); + final SynchronizedBlock block = new SynchronizedBlock(parameters); - return block; + return block; } /** * Create a then block. - * - * @param parameters - * the then block parameters (body) as {@link ExtList} + * + * @param parameters the then block parameters (body) as {@link ExtList} * @return a new {@link Then} as defined by parameters */ public static Then thenBlock(final ExtList parameters) { - final Then block = new Then(parameters); + final Then block = new Then(parameters); - return block; + return block; } /** * Create a then block. - * + * *
          * then
          *     statement
          * 
    - * - * @param statement - * the to be executed {@link Statement} - * @return a new {@link Then} block that consists of statement - * solely + * + * @param statement the to be executed {@link Statement} + * @return a new {@link Then} block that consists of statement solely */ public static Then thenBlock(final Statement statement) { - final Then block = new Then(statement); + final Then block = new Then(statement); - return block; + return block; } /** * Create a then block. - * + * *
          * then {
          *     statements
          * }
          * 
    - * - * @param statements - * the to be executed {@link Statement}s - * @return a new {@link Then} block that consists of statements - * solely + * + * @param statements the to be executed {@link Statement}s + * @return a new {@link Then} block that consists of statements solely */ public static Then thenBlock(final Statement[] statements) { - final StatementBlock statement = KeYJavaASTFactory.block(statements); - final Then block = KeYJavaASTFactory.thenBlock(statement); + final StatementBlock statement = KeYJavaASTFactory.block(statements); + final Then block = KeYJavaASTFactory.thenBlock(statement); - return block; + return block; } /** * Create a call to a constructor of the current class. - * + * *
          * this(args)
          * 
    - * - * @param args - * the {@link Expression} arguments to be passed to constructor - * @return a new {@link ThisConstructorReference} parameterized with - * args + * + * @param args the {@link Expression} arguments to be passed to constructor + * @return a new {@link ThisConstructorReference} parameterized with args */ - public static ThisConstructorReference thisConstructor( - final Expression[] args) { - final ThisConstructorReference constructor = new ThisConstructorReference( - args); + public static ThisConstructorReference thisConstructor(final Expression[] args) { + final ThisConstructorReference constructor = new ThisConstructorReference(args); - return constructor; + return constructor; } /** * Create a reference to this. - * + * * @return a new {@link ThisReference} */ public static ThisReference thisReference() { - final ThisReference reference = new ThisReference(); + final ThisReference reference = new ThisReference(); - return reference; + return reference; } /** * Create a literal for the truth value true. - * - * @return a {@link BooleanLiteral} that represents the value - * true + * + * @return a {@link BooleanLiteral} that represents the value true */ public static BooleanLiteral trueLiteral() { - return BooleanLiteral.TRUE; + return BooleanLiteral.TRUE; } /** * Create a try block. - * - * @param parameters - * the try-catch parameters (body, branches) as {@link ExtList} + * + * @param parameters the try-catch parameters (body, branches) as {@link ExtList} * @return a new {@link Try} as defined by parameters */ public static Try tryBlock(final ExtList parameters) { - final Try block = new Try(parameters); + final Try block = new Try(parameters); - return block; + return block; } /** * Create a try block. - * + * *
          * try
          *     body
          * branches
          * 
    - * - * @param body - * the {@link StatementBlock} to be executed - * @param branches - * the try-catch {@link Branch}es - * @return a new {@link Try} block for the execution of - * branches depending on the events during the - * execution of body + * + * @param body the {@link StatementBlock} to be executed + * @param branches the try-catch {@link Branch}es + * @return a new {@link Try} block for the execution of branches depending on the + * events during the execution of body */ - public static Try tryBlock(final StatementBlock body, - final Branch[] branches) { - final Try block = new Try(body, branches); + public static Try tryBlock(final StatementBlock body, final Branch[] branches) { + final Try block = new Try(body, branches); - return block; + return block; } /** * Create a try block. - * + * *
          * try
          *     statement
          * branches
          * 
    - * - * @param statement - * the {@link Statement} to be executed - * @param branches - * the try-catch {@link Branch}es - * @return a new {@link Try} block for the execution of - * branches depending on the events during the - * execution of statement + * + * @param statement the {@link Statement} to be executed + * @param branches the try-catch {@link Branch}es + * @return a new {@link Try} block for the execution of branches depending on the + * events during the execution of statement */ - public static Try tryBlock(final Statement statement, - final Branch[] branches) { - final StatementBlock body = KeYJavaASTFactory.block(statement); - final Try tryBlock = KeYJavaASTFactory.tryBlock(body, branches); + public static Try tryBlock(final Statement statement, final Branch[] branches) { + final StatementBlock body = KeYJavaASTFactory.block(statement); + final Try tryBlock = KeYJavaASTFactory.tryBlock(body, branches); - return tryBlock; + return tryBlock; } /** * Create a try block. - * + * *
          * try
          *     statement
          * branch
          * 
    - * - * @param statement - * the {@link Statement} to be executed - * @param branches - * the try-catch {@link Branch} - * @return a new {@link Try} block for the execution of branch - * depending on the events during the execution of - * statement + * + * @param statement the {@link Statement} to be executed + * @param branches the try-catch {@link Branch} + * @return a new {@link Try} block for the execution of branch depending on the + * events during the execution of statement */ public static Try tryBlock(final Statement statement, final Branch branch) { - final Branch[] branches = new Branch[] { branch }; - final Try tryBlock = KeYJavaASTFactory.tryBlock(statement, branches); + final Branch[] branches = new Branch[] { branch }; + final Try tryBlock = KeYJavaASTFactory.tryBlock(statement, branches); - return tryBlock; + return tryBlock; } /** * Create a type reference. - * + * *
          * type
          * 
    - * - * @param type - * the {@link KeYJavaType} to be referenced + * + * @param type the {@link KeYJavaType} to be referenced * @return a new {@link TypeRef} that references type */ public static TypeRef typeRef(final KeYJavaType type) { - final TypeRef typeRef = new TypeRef(type); + final TypeRef typeRef = new TypeRef(type); - return typeRef; + return typeRef; } /** * Create a type reference. - * + * *
          * type[]...[]
          * 
    - * - * @param type - * the base {@link KeYJavaType} - * @param dimensions - * the number of dimensions - * @return a new {@link TypeRef} for dimensions dimensions of - * type + * + * @param type the base {@link KeYJavaType} + * @param dimensions the number of dimensions + * @return a new {@link TypeRef} for dimensions dimensions of type */ public static TypeRef typeRef(final KeYJavaType type, final int dimensions) { - final TypeRef typeRef = new TypeRef(type, dimensions); + final TypeRef typeRef = new TypeRef(type, dimensions); - return typeRef; + return typeRef; } /** * Create a literal for the truth value false. - * - * @return a {@link BooleanLiteral} that represents the value - * true + * + * @return a {@link BooleanLiteral} that represents the value true */ public static BooleanLiteral falseLiteral() { - return BooleanLiteral.FALSE; + return BooleanLiteral.FALSE; } /** * Create a variable specification. - * - * @param variable - * the {@link IProgramVariable} to be specified - * @param dimensions - * the number of dimensions - * @param initializer - * the initializer {@link Expression} - * @param type - * the {@link Type} - * @return a new {@link VariableSpecification} for variable of - * type type[dimensions], initialized to - * initializer + * + * @param variable the {@link IProgramVariable} to be specified + * @param dimensions the number of dimensions + * @param initializer the initializer {@link Expression} + * @param type the {@link Type} + * @return a new {@link VariableSpecification} for variable of type + * type[dimensions], initialized to initializer */ - public static VariableSpecification variableSpecification( - final IProgramVariable variable, final int dimensions, - final Expression initializer, final Type type) { - final VariableSpecification specification = new VariableSpecification( - variable, dimensions, initializer, type); + public static VariableSpecification variableSpecification(final IProgramVariable variable, + final int dimensions, final Expression initializer, final Type type) { + final VariableSpecification specification = + new VariableSpecification(variable, dimensions, initializer, type); - return specification; + return specification; } /** * Create a variable specification. - * - * @param variable - * the {@link IProgramVariable} to be specified - * @param initializer - * the initializer {@link Expression} - * @param keyJavaType - * the {@link KeYJavaType} - * @return a new {@link VariableSpecification} for variable of - * type type, initialized to initializer + * + * @param variable the {@link IProgramVariable} to be specified + * @param initializer the initializer {@link Expression} + * @param keyJavaType the {@link KeYJavaType} + * @return a new {@link VariableSpecification} for variable of type + * type, initialized to initializer */ - public static VariableSpecification variableSpecification( - final IProgramVariable variable, final Expression initializer, - final KeYJavaType keyJavaType) { - final VariableSpecification specification = new VariableSpecification( - variable, initializer, keyJavaType); + public static VariableSpecification variableSpecification(final IProgramVariable variable, + final Expression initializer, final KeYJavaType keyJavaType) { + final VariableSpecification specification = + new VariableSpecification(variable, initializer, keyJavaType); - return specification; + return specification; } /** * Create a literal for the integer zero. - * + * *
          * 0
          * 
    - * - * @return a new {@link IntLiteral} that represents the integer value - * 0 + * + * @return a new {@link IntLiteral} that represents the integer value 0 */ public static IntLiteral zeroLiteral() { - final IntLiteral literal = KeYJavaASTFactory.intLiteral(0); + final IntLiteral literal = KeYJavaASTFactory.intLiteral(0); - return literal; + return literal; } - public static TypeCast cast(final Expression expression, - final KeYJavaType targetType) { + public static TypeCast cast(final Expression expression, final KeYJavaType targetType) { return new TypeCast(expression, new TypeRef(targetType)); } -} \ No newline at end of file +} 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 e09dc1c09e7..78078a4b493 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.abstraction.*; @@ -33,14 +36,14 @@ public class KeYProgModelInfo { private KeYRecoderExcHandler exceptionHandler = null; public KeYProgModelInfo(Services services, TypeConverter typeConverter, - KeYRecoderExcHandler keh) { - this(services, new KeYCrossReferenceServiceConfiguration(keh), - new KeYRecoderMapping(), typeConverter); + KeYRecoderExcHandler keh) { + this(services, new KeYCrossReferenceServiceConfiguration(keh), new KeYRecoderMapping(), + typeConverter); exceptionHandler = keh; } KeYProgModelInfo(Services services, KeYCrossReferenceServiceConfiguration crsc, - KeYRecoderMapping krm, TypeConverter typeConverter) { + KeYRecoderMapping krm, TypeConverter typeConverter) { this.services = services; sc = crsc; this.typeConverter = typeConverter; @@ -61,8 +64,7 @@ public KeYRecoderExcHandler getExceptionHandler() { } /** - * Returns all KeY-elements mapped by Recoder2KeY object of this - * KeYProgModelInfo. + * Returns all KeY-elements mapped by Recoder2KeY object of this KeYProgModelInfo. * * @return a Set object containing the KeY-elements. */ @@ -83,9 +85,8 @@ private List getAllRecoderMethods(KeYJavaType kjt) { /** - * Returns all visible methods that are defined in this - * class type or any of its supertypes. The methods are - * in topological order with respect to the inheritance hierarchy. + * Returns all visible methods that are defined in this class type or any of its supertypes. The + * methods are in topological order with respect to the inheritance hierarchy. * * @return the list of visible methods of this type and its supertypes. */ @@ -95,8 +96,7 @@ public ImmutableList getAllMethods(KeYJavaType kjt) { ImmutableList result = ImmutableSLList.nil(); for (int i = rmethods.size() - 1; i >= 0; i--) { recoder.abstraction.Method rm = rmethods.get(i); - Method m = - ((IProgramMethod) rec2key().toKeY(rm)).getMethodDeclaration(); + Method m = ((IProgramMethod) rec2key().toKeY(rm)).getMethodDeclaration(); result = result.prepend(m); } return result; @@ -104,9 +104,8 @@ public ImmutableList getAllMethods(KeYJavaType kjt) { /** - * Returns all visible methods that are defined in this - * class type or any of its supertypes. The methods are - * in topological order with respect to the inheritance hierarchy. + * Returns all visible methods that are defined in this class type or any of its supertypes. The + * methods are in topological order with respect to the inheritance hierarchy. * * @return the list of visible methods of this type and its supertypes. */ @@ -128,8 +127,7 @@ private List getRecoderTypes(ImmutableList tl - = new ArrayList<>(types.size()); + final ArrayList tl = new ArrayList<>(types.size()); for (final Type n : types) { tl.add((recoder.abstraction.Type) rec2key().toRecoder(n)); } @@ -141,21 +139,22 @@ private List getRecoderTypes(ImmutableList types; if (i.getPackageReference() != null) { - types = sc.getCrossReferenceSourceInfo().getPackage(i.getPackageReference()).getTypes(); + types = sc.getCrossReferenceSourceInfo().getPackage(i.getPackageReference()) + .getTypes(); } else { if (i.isMultiImport()) { - recoder.abstraction.ClassType type = (recoder.abstraction.ClassType) - sc.getCrossReferenceSourceInfo().getType(i.getTypeReference()); + recoder.abstraction.ClassType type = (recoder.abstraction.ClassType) sc + .getCrossReferenceSourceInfo().getType(i.getTypeReference()); types = type.getTypes(); } else { types = new LinkedList<>(); - ((LinkedList) types).add((recoder.abstraction.ClassType) - sc.getCrossReferenceSourceInfo().getType(i.getTypeReference())); + ((LinkedList) types).add( + (recoder.abstraction.ClassType) sc.getCrossReferenceSourceInfo() + .getType(i.getTypeReference())); } } result = searchType(shortName, types); @@ -190,7 +191,7 @@ public KeYJavaType resolveType(String shortName, KeYJavaType context) { } private recoder.abstraction.ClassType searchType(String shortName, - final List types) { + final List types) { for (recoder.abstraction.ClassType type : types) { if (type.getName().equals(shortName)) { return type; @@ -206,20 +207,18 @@ private recoder.abstraction.ClassType searchType(String shortName, */ public String getFullName(KeYJavaType t) { - recoder.abstraction.Type rt - = (recoder.abstraction.Type) rec2key().toRecoder(t); + recoder.abstraction.Type rt = (recoder.abstraction.Type) rec2key().toRecoder(t); return rt.getFullName(); } public recoder.abstraction.Type getType(TypeReference tr) { recoder.abstraction.Type result; if (tr instanceof TypeRef) { - result = (recoder.abstraction.Type) - rec2key().toRecoder(tr.getKeYJavaType()); + result = (recoder.abstraction.Type) rec2key().toRecoder(tr.getKeYJavaType()); return result; } - result = getServConf().getSourceInfo().getType - ((recoder.java.reference.TypeReference) rec2key().toRecoder(tr)); + result = getServConf().getSourceInfo() + .getType((recoder.java.reference.TypeReference) rec2key().toRecoder(tr)); return result; } @@ -237,8 +236,7 @@ public boolean isFinal(KeYJavaType kjt) { /** * Checks whether subType is a subtype of superType or not. * - * @return true if subType is subtype of superType, - * false in the other case. + * @return true if subType is subtype of superType, false in the other case. */ public boolean isSubtype(KeYJavaType subType, KeYJavaType superType) { @@ -247,33 +245,30 @@ public boolean isSubtype(KeYJavaType subType, KeYJavaType superType) { } private boolean isSubtype(recoder.abstraction.Type subType, - recoder.abstraction.Type superType) { - if (subType instanceof recoder.abstraction.ClassType && - superType instanceof recoder.abstraction.ClassType) { + recoder.abstraction.Type superType) { + if (subType instanceof recoder.abstraction.ClassType + && superType instanceof recoder.abstraction.ClassType) { return isSubtype((recoder.abstraction.ClassType) subType, (recoder.abstraction.ClassType) superType); - } else if (superType instanceof recoder.abstraction.ArrayType && - subType instanceof recoder.abstraction.ArrayType) { + } else if (superType instanceof recoder.abstraction.ArrayType + && subType instanceof recoder.abstraction.ArrayType) { return isAssignmentCompatible((recoder.abstraction.ArrayType) subType, (recoder.abstraction.ArrayType) superType); - } else if (subType instanceof recoder.abstraction.ArrayType && - superType instanceof recoder.abstraction.ClassType) { + } else if (subType instanceof recoder.abstraction.ArrayType + && superType instanceof recoder.abstraction.ClassType) { return "java.lang.Object".equals(superType.getFullName()) || "Object".equals(superType.getName()); } // should not occur - throw new RuntimeException("Method isSubtype in class KeYProgModelInfo " + - "currently only supports two class types or two " + - "array type but no mixture!"); + throw new RuntimeException("Method isSubtype in class KeYProgModelInfo " + + "currently only supports two class types or two " + "array type but no mixture!"); } private boolean isSubtype(recoder.abstraction.ClassType classSubType, - recoder.abstraction.ClassType classType) { - boolean isSub = getServConf().getSourceInfo(). - isSubtype(classSubType, classType); + recoder.abstraction.ClassType classType) { + boolean isSub = getServConf().getSourceInfo().isSubtype(classSubType, classType); if (!isSub) { - return getServConf().getByteCodeInfo(). - isSubtype(classSubType, classType); + return getServConf().getByteCodeInfo().isSubtype(classSubType, classType); } else { return true; } @@ -290,39 +285,35 @@ public boolean isPackage(String name) { } /** - * checks whether subType is assignment compatible to type according - * to the rules defined in the java language specification + * checks whether subType is assignment compatible to type according to the rules defined in the + * java language specification */ private boolean isAssignmentCompatible(recoder.abstraction.ArrayType subType, - recoder.abstraction.ArrayType type) { + recoder.abstraction.ArrayType type) { recoder.abstraction.Type bt1 = subType.getBaseType(); recoder.abstraction.Type bt2 = type.getBaseType(); - if (bt1 instanceof recoder.abstraction.PrimitiveType && - bt2 instanceof recoder.abstraction.PrimitiveType) { + if (bt1 instanceof recoder.abstraction.PrimitiveType + && bt2 instanceof recoder.abstraction.PrimitiveType) { return bt1.getFullName().equals(bt2.getFullName()); } - if (bt1 instanceof recoder.abstraction.ClassType && - bt2 instanceof recoder.abstraction.ClassType) + if (bt1 instanceof recoder.abstraction.ClassType + && bt2 instanceof recoder.abstraction.ClassType) return isSubtype((recoder.abstraction.ClassType) bt1, (recoder.abstraction.ClassType) bt2); - if (bt1 instanceof recoder.abstraction.ArrayType && - bt2 instanceof recoder.abstraction.ArrayType) + if (bt1 instanceof recoder.abstraction.ArrayType + && bt2 instanceof recoder.abstraction.ArrayType) return isAssignmentCompatible((recoder.abstraction.ArrayType) bt1, (recoder.abstraction.ArrayType) bt2); - if (bt1 instanceof recoder.abstraction.ClassType && - bt2 instanceof recoder.abstraction.ArrayType) + if (bt1 instanceof recoder.abstraction.ClassType + && bt2 instanceof recoder.abstraction.ArrayType) return false; - if (bt1 instanceof recoder.abstraction.ArrayType && - bt2 instanceof recoder.abstraction.ClassType) { + if (bt1 instanceof recoder.abstraction.ArrayType + && bt2 instanceof recoder.abstraction.ClassType) { if (((recoder.abstraction.ClassType) bt2).isInterface()) { - return bt2. - getFullName().equals("java.lang.Cloneable") || - bt2. - getFullName().equals("java.lang.Serializable") - ; + return bt2.getFullName().equals("java.lang.Cloneable") + || bt2.getFullName().equals("java.lang.Serializable"); } else { - return bt2. - getFullName().equals("java.lang.Object"); + return bt2.getFullName().equals("java.lang.Object"); } } return false; @@ -332,8 +323,7 @@ private List getRecoderMethods(KeYJavaType kjt) { if (kjt.getJavaType() instanceof TypeDeclaration) { Object o = rec2key().toRecoder(kjt); if (o instanceof recoder.abstraction.ClassType) { - recoder.abstraction.ClassType rct - = (recoder.abstraction.ClassType) o; + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) o; return rct.getProgramModelInfo().getMethods(rct); } } @@ -341,50 +331,46 @@ private List getRecoderMethods(KeYJavaType kjt) { } private List getRecoderConstructors(KeYJavaType ct) { - recoder.abstraction.ClassType rct - = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); return rct.getProgramModelInfo().getConstructors(rct); } - private List getRecoderMethods - (KeYJavaType ct, String m, ImmutableList signature, KeYJavaType context) { - recoder.abstraction.ClassType rct - = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); - recoder.abstraction.ClassType rcontext - = (recoder.abstraction.ClassType) rec2key().toRecoder(context); - - return rct.getProgramModelInfo().getMethods(rct, m, - getRecoderTypes(signature), - null, // no generic type variables yet + private List getRecoderMethods(KeYJavaType ct, String m, + ImmutableList signature, KeYJavaType context) { + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); + recoder.abstraction.ClassType rcontext = + (recoder.abstraction.ClassType) rec2key().toRecoder(context); + + return rct.getProgramModelInfo().getMethods(rct, m, getRecoderTypes(signature), null, // no + // generic + // type + // variables + // yet rcontext); } - private List getRecoderConstructors - (KeYJavaType ct, ImmutableList signature) { - recoder.abstraction.ClassType rct - = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); - return rct.getProgramModelInfo().getConstructors( - rct, getRecoderTypes(signature)); + private List getRecoderConstructors(KeYJavaType ct, + ImmutableList signature) { + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); + return rct.getProgramModelInfo().getConstructors(rct, getRecoderTypes(signature)); } /** - * Returns the list of most specific methods with the given - * name that are defined in the given type or in a supertype - * where they are visible for the given type, and have a signature - * that is compatible to the given one. If used to resolve a - * method call, the result should be defined and unambiguous. + * Returns the list of most specific methods with the given name that are defined in the given + * type or in a supertype where they are visible for the given type, and have a signature that + * is compatible to the given one. If used to resolve a method call, the result should be + * defined and unambiguous. * - * @param ct the class type to get methods from. - * @param m the name of the methods in question. + * @param ct the class type to get methods from. + * @param m the name of the methods in question. * @param signature the statical type signature of a callee. */ - public ImmutableList getMethods(KeYJavaType ct, String m, - ImmutableList signature, KeYJavaType context) { - List rml = - getRecoderMethods(ct, m, signature, context); + public ImmutableList getMethods(KeYJavaType ct, String m, ImmutableList signature, + KeYJavaType context) { + List rml = getRecoderMethods(ct, m, signature, context); ImmutableList result = ImmutableSLList.nil(); for (int i = rml.size() - 1; i >= 0; i--) { recoder.abstraction.Method rm = rml.get(i); @@ -396,9 +382,8 @@ public ImmutableList getMethods(KeYJavaType ct, String m, /** - * Returns the methods locally defined within the given - * class type. If the type is represented in source code, - * the returned list matches the syntactic order. + * Returns the methods locally defined within the given class type. If the type is represented + * in source code, the returned list matches the syntactic order. * * @param ct a class type. */ @@ -409,8 +394,7 @@ public ImmutableList getMethods(KeYJavaType ct) { for (int i = rml.size() - 1; i >= 0; i--) { recoder.abstraction.Method rm = rml.get(i); if (!(rm instanceof recoder.bytecode.MethodInfo)) { - Method m = ((IProgramMethod) rec2key().toKeY(rm)). - getMethodDeclaration(); + Method m = ((IProgramMethod) rec2key().toKeY(rm)).getMethodDeclaration(); result = result.prepend(m); } } @@ -418,9 +402,8 @@ public ImmutableList getMethods(KeYJavaType ct) { } /** - * Returns the ProgramMethods locally defined within the given - * class type. If the type is represented in source code, - * the returned list matches the syntactic order. + * Returns the ProgramMethods locally defined within the given class type. If the type is + * represented in source code, the returned list matches the syntactic order. * * @param ct a class type. */ @@ -441,9 +424,8 @@ public ImmutableList getAllProgramMethodsLocallyDeclared(KeYJavaT } /** - * Returns the constructors locally defined within the given - * class type. If the type is represented in source code, - * the returned list matches the syntactic order. + * Returns the constructors locally defined within the given class type. If the type is + * represented in source code, the returned list matches the syntactic order. * * @param ct a class type. */ @@ -462,15 +444,14 @@ public ImmutableList getConstructors(KeYJavaType ct) { } /** - * retrieves the most specific constructor declared in the given type with - * respect to the given signature + * retrieves the most specific constructor declared in the given type with respect to the given + * signature * - * @param ct the KeYJavyType where to look for the constructor + * @param ct the KeYJavyType where to look for the constructor * @param signature IList representing the signature of the constructor * @return the most specific constructor declared in the given type */ - public IProgramMethod getConstructor(KeYJavaType ct, - ImmutableList signature) { + public IProgramMethod getConstructor(KeYJavaType ct, ImmutableList signature) { List constructors = getRecoderConstructors(ct, signature); if (constructors.size() == 1) { @@ -499,39 +480,34 @@ private IProgramMethod getImplicitMethod(KeYJavaType ct, String name) { ImmutableArray members = cd.getMembers(); for (int i = 0; i < members.size(); i++) { final MemberDeclaration member = members.get(i); - if (member instanceof IProgramMethod && - ((IProgramMethod) member).getMethodDeclaration().getName().equals(name)) { + if (member instanceof IProgramMethod + && ((IProgramMethod) member).getMethodDeclaration().getName().equals(name)) { return (IProgramMethod) member; } } - LOGGER.debug("keyprogmodelinfo: implicit method {} not found in {}", - name, ct); + LOGGER.debug("keyprogmodelinfo: implicit method {} not found in {}", name, ct); return null; } /** - * Returns the IProgramMethods with the given name that is defined - * in the given type or in a supertype where it is visible for the - * given type, and has a signature that is compatible to the given one. + * Returns the IProgramMethods with the given name that is defined in the given type or in a + * supertype where it is visible for the given type, and has a signature that is compatible to + * the given one. * - * @param ct the class type to get methods from. - * @param m the name of the methods in question. + * @param ct the class type to get methods from. + * @param m the name of the methods in question. * @param signature the statical type signature of a callee. - * @return the IProgramMethods, if one is found, - * null if none or more than one IProgramMethod is found (in this case - * a debug output is written to console). + * @return the IProgramMethods, if one is found, null if none or more than one IProgramMethod is + * found (in this case a debug output is written to console). */ public IProgramMethod getProgramMethod(KeYJavaType ct, String m, - ImmutableList signature, - KeYJavaType context) { - if (ct.getJavaType() instanceof ArrayType || - context.getJavaType() instanceof ArrayType) { + ImmutableList signature, KeYJavaType context) { + if (ct.getJavaType() instanceof ArrayType || context.getJavaType() instanceof ArrayType) { return getImplicitMethod(ct, m); } - List methodlist = - getRecoderMethods(ct, m, signature, context); + List methodlist = getRecoderMethods(ct, m, signature, context); if (methodlist.size() == 1) { return (IProgramMethod) rec2key().toKeY(methodlist.get(0)); @@ -546,8 +522,7 @@ public IProgramMethod getProgramMethod(KeYJavaType ct, String m, /** - * returns the same fields as given in rfl and returns - * their KeY representation + * returns the same fields as given in rfl and returns their KeY representation * * @param rfl the List of fields to be looked up * @return list with the corresponding fields as KeY datastructures @@ -566,17 +541,16 @@ private ImmutableList asKeYFields(List getAllFieldsLocallyDeclaredIn(KeYJavaType ct) { /** - * returns all in ct visible fields - * declared in ct or one of its supertypes - * in topological order starting with the fields of - * the given type - * If the type is represented in source code, the returned list - * matches the syntactic order. + * returns all in ct visible fields declared in ct or one of its supertypes in + * topological order starting with the fields of the given type If the type is represented in + * source code, the returned list matches the syntactic order. * * @param ct the class type whose fields are returned * @return the list of field members of the given type. @@ -607,10 +578,8 @@ public ImmutableList getAllVisibleFields(KeYJavaType ct) { return getVisibleArrayFields(ct); } - recoder.abstraction.ClassType rct - = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); - List rfl = - rct.getProgramModelInfo().getAllFields(rct); + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); + List rfl = rct.getProgramModelInfo().getAllFields(rct); return asKeYFields(rfl); } @@ -638,14 +607,13 @@ private ImmutableList getVisibleArrayFields(KeYJavaType arrayType) { } } - // fields of java.lang.Object visible in an array - final ImmutableList javaLangObjectField = - getAllVisibleFields((KeYJavaType) rec2key(). - toKeY(sc.getNameInfo().getJavaLangObject())); + // fields of java.lang.Object visible in an array + final ImmutableList javaLangObjectField = getAllVisibleFields( + (KeYJavaType) rec2key().toKeY(sc.getNameInfo().getJavaLangObject())); for (Field aJavaLangObjectField : javaLangObjectField) { - if (!((recoder.abstraction.Field) - rec2key().toRecoder(aJavaLangObjectField)).isPrivate()) { + if (!((recoder.abstraction.Field) rec2key().toRecoder(aJavaLangObjectField)) + .isPrivate()) { result = result.append(aJavaLangObjectField); } } @@ -656,29 +624,27 @@ private ImmutableList getVisibleArrayFields(KeYJavaType arrayType) { * returns all proper subtypes of class ct (i.e. without ct itself) */ private List getAllRecoderSubtypes(KeYJavaType ct) { - return sc.getCrossReferenceSourceInfo(). - getAllSubtypes((recoder.abstraction.ClassType) rec2key().toRecoder(ct)); + return sc.getCrossReferenceSourceInfo() + .getAllSubtypes((recoder.abstraction.ClassType) rec2key().toRecoder(ct)); } /** - * returns all supertypes of the given class type with the type itself as - * first element + * returns all supertypes of the given class type with the type itself as first element */ private List getAllRecoderSupertypes(KeYJavaType ct) { - return sc.getCrossReferenceSourceInfo(). - getAllSupertypes((recoder.abstraction.ClassType) rec2key().toRecoder(ct)); + return sc.getCrossReferenceSourceInfo() + .getAllSupertypes((recoder.abstraction.ClassType) rec2key().toRecoder(ct)); } /** - * returns a list of KeYJavaTypes representing the given recoder types in - * the same order + * returns a list of KeYJavaTypes representing the given recoder types in the same order * * @param rctl the ASTList to be converted - * @return list of KeYJavaTypes representing the given recoder types in - * the same order + * @return list of KeYJavaTypes representing the given recoder types in the same order */ - private ImmutableList asKeYJavaTypes(final List rctl) { + private ImmutableList asKeYJavaTypes( + final List rctl) { ImmutableList result = ImmutableSLList.nil(); for (int i = rctl.size() - 1; i >= 0; i--) { final recoder.abstraction.ClassType rct = rctl.get(i); @@ -691,8 +657,7 @@ private ImmutableList asKeYJavaTypes(final List findImplementations - (Type ct, String name, ImmutableList signature) { + public ImmutableList findImplementations(Type ct, String name, + ImmutableList signature) { // set up recoder inputs - recoder.abstraction.ClassType rct = - (recoder.abstraction.ClassType) rec2key().toRecoder(ct); + recoder.abstraction.ClassType rct = (recoder.abstraction.ClassType) rec2key().toRecoder(ct); // transform the signature up to recoder conventions - ArrayList rsignature = - new ArrayList<>(signature.size()); + ArrayList rsignature = new ArrayList<>(signature.size()); Iterator i = signature.iterator(); int j = 0; while (i.hasNext()) { - rsignature.add(j, (recoder.abstraction.Type) - rec2key().toRecoder(i.next())); + rsignature.add(j, (recoder.abstraction.Type) rec2key().toRecoder(i.next())); j++; } @@ -776,14 +734,14 @@ public JavaBlock readJavaBlock(String block, NamespaceSet nss) { // ct has no implementation, go up List superTypes = rct.getAllSupertypes(); int k = 0; - while (k < superTypes.size() && - !declaresApplicableMethods(superTypes.get(k), - name, rsignature)) k++; + while (k < superTypes.size() + && !declaresApplicableMethods(superTypes.get(k), name, rsignature)) + k++; if (k < superTypes.size()) { rct = superTypes.get(k); KeYJavaType r = (KeYJavaType) mapping.toKeY(rct); if (r == null) { - LOGGER.info("Type {}", rct.getName()); + LOGGER.info("Type {}", rct.getName()); } else { classList = classList.append(r); } @@ -794,18 +752,15 @@ public JavaBlock readJavaBlock(String block, NamespaceSet nss) { } - private ImmutableList recFindImplementations( - recoder.abstraction.ClassType ct, - String name, - List signature, + private ImmutableList recFindImplementations(recoder.abstraction.ClassType ct, + String name, List signature, ImmutableList result) { - recoder.service.CrossReferenceSourceInfo si - = getServConf().getCrossReferenceSourceInfo(); + recoder.service.CrossReferenceSourceInfo si = getServConf().getCrossReferenceSourceInfo(); if (declaresApplicableMethods(ct, name, signature)) { KeYJavaType r = (KeYJavaType) mapping.toKeY(ct); if (r == null) { - LOGGER.info("Type {}: {} not found", ct.getFullName(), name); + LOGGER.info("Type {}: {} not found", ct.getFullName(), name); } else if (!result.contains(r)) { result = result.prepend(r); } @@ -813,10 +768,10 @@ private ImmutableList recFindImplementations( List classes = si.getSubtypes(ct); - //alpha sorting to make order deterministic - recoder.abstraction.ClassType[] classesArray = - classes.toArray(new ClassType[0]); - java.util.Arrays.sort(classesArray, (o1, o2) -> o2.getFullName().compareTo(o1.getFullName())); + // alpha sorting to make order deterministic + recoder.abstraction.ClassType[] classesArray = classes.toArray(new ClassType[0]); + java.util.Arrays.sort(classesArray, + (o1, o2) -> o2.getFullName().compareTo(o1.getFullName())); for (recoder.abstraction.ClassType c : classesArray) { result = recFindImplementations(c, name, signature, result); @@ -825,31 +780,27 @@ private ImmutableList recFindImplementations( } - private boolean declaresApplicableMethods(recoder.abstraction.ClassType ct, - String name, - List signature) { - recoder.service.CrossReferenceSourceInfo si - = getServConf().getCrossReferenceSourceInfo(); + private boolean declaresApplicableMethods(recoder.abstraction.ClassType ct, String name, + List signature) { + recoder.service.CrossReferenceSourceInfo si = getServConf().getCrossReferenceSourceInfo(); List list = si.getMethods(ct); int s = list.size(); int i = 0; while (i < s) { recoder.abstraction.Method m = list.get(i); - if (name.equals(m.getName()) - && si.isCompatibleSignature(signature, m.getSignature()) - && si.isVisibleFor(m, ct) - && !m.isAbstract()) return true; - else i++; + if (name.equals(m.getName()) && si.isCompatibleSignature(signature, m.getSignature()) + && si.isVisibleFor(m, ct) && !m.isAbstract()) + return true; + else + i++; } return false; } - private boolean isDeclaringInterface(recoder.abstraction.ClassType ct, - String name, - List signature) { - recoder.service.CrossReferenceSourceInfo si - = getServConf().getCrossReferenceSourceInfo(); + private boolean isDeclaringInterface(recoder.abstraction.ClassType ct, String name, + List signature) { + recoder.service.CrossReferenceSourceInfo si = getServConf().getCrossReferenceSourceInfo(); Debug.assertTrue(ct.isInterface()); @@ -858,10 +809,11 @@ private boolean isDeclaringInterface(recoder.abstraction.ClassType ct, int i = 0; while (i < s) { recoder.abstraction.Method m = list.get(i); - if (name.equals(m.getName()) - && si.isCompatibleSignature(signature, m.getSignature()) - && si.isVisibleFor(m, ct)) return true; - else i++; + if (name.equals(m.getName()) && si.isCompatibleSignature(signature, m.getSignature()) + && si.isVisibleFor(m, ct)) + return true; + else + i++; } return false; } @@ -877,7 +829,6 @@ public void putImplicitMethod(IProgramMethod m, KeYJavaType t) { public KeYProgModelInfo copy() { - return new KeYProgModelInfo(services, getServConf(), rec2key().copy(), - typeConverter); + return new KeYProgModelInfo(services, getServConf(), rec2key().copy(), typeConverter); } -} \ No newline at end of file +} 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 5418b7ad0ec..62b33db564b 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; @@ -10,109 +13,110 @@ -public class KeYRecoderMapping{ +public class KeYRecoderMapping { /** 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 */ private HashMap revMap; /** a pseudo super class for all arrays used to declare length */ - private KeYJavaType superArrayType=null; + private KeYJavaType superArrayType = null; + - public KeYRecoderMapping() { - this.map = new LinkedHashMap<>(); - this.revMap = new LinkedHashMap<>(); + this.map = new LinkedHashMap<>(); + this.revMap = new LinkedHashMap<>(); } /** - * 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); } public boolean mapped(Object rec) { - return map.containsKey(rec); + return map.containsKey(rec); } - + public Set elemsKeY() { - return revMap.keySet(); + return revMap.keySet(); } public Set elemsRec() { - return map.keySet(); + return map.keySet(); } public void setSuperArrayType(KeYJavaType superArrayType) { @@ -123,43 +127,38 @@ public KeYJavaType getSuperArrayType() { return this.superArrayType; } - + @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); } /** - * 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. + * 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; + return parsedSpecial; } - public int size(){ - return map.size(); + 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 + * 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; + parsedSpecial = b; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Label.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Label.java index 3b9e86db47d..9f2d1e2a202 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Label.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Label.java @@ -1,5 +1,6 @@ -/** represents a java label - */ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.visitor.Visitor; @@ -22,4 +23,4 @@ public interface Label extends TerminalProgramElement { Position getRelativePosition(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/LoopInitializer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/LoopInitializer.java index acd00596233..4ff5da6fc66 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/LoopInitializer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/LoopInitializer.java @@ -1,9 +1,11 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Loop initializer. - * taken from COMPOST and changed to achieve an immutable structure + * Loop initializer. taken from COMPOST and changed to achieve an immutable structure */ public interface LoopInitializer extends Statement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ModelElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ModelElement.java index 8355e54af6a..721c4cd407e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ModelElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ModelElement.java @@ -1,10 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; -/** - * A semantical part of the software model. A source element is - * not necessarily connected to a piece of syntax. +/** + * A semantical part of the software model. A source element is not necessarily connected to a piece + * of syntax. * */ public interface ModelElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/NameAbstractionTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/NameAbstractionTable.java index 0696c5aafdd..a2f1c44db37 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/NameAbstractionTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/NameAbstractionTable.java @@ -1,69 +1,69 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.Iterator; import java.util.LinkedList; import java.util.List; -/** - * This class is used for the equals modulo renaming method in - * SourceElement. The purpose of this class is to abstract from - * names. Therefore it represents a mapping o1 x o2 -> abstractName - * where o1, o2 are of the same type (Label or ProgramVariable). The - * objectif is that the comparing method uses this new name for o1 and - * o2 instead of their real name. For this comparision a method is +/** + * This class is used for the equals modulo renaming method in SourceElement. The purpose of this + * class is to abstract from names. Therefore it represents a mapping o1 x o2 -> abstractName where + * o1, o2 are of the same type (Label or ProgramVariable). The objectif is that the comparing method + * uses this new name for o1 and o2 instead of their real name. For this comparision a method is * offered so that the assigned name is not given outside. */ public class NameAbstractionTable { /** - * The order in which symbols are declared in the two terms or programs that - * are compared. The latest declaration of a symbol will be the first - * matching entry in the list + * The order in which symbols are declared in the two terms or programs that are compared. The + * latest declaration of a symbol will be the first matching entry in the list */ private List declarations0 = null, declarations1 = null; - - /** + + /** * adds the given two elements to the table + * * @param pe1 SourceElement to be added - * @param pe2 SourceElement to be added + * @param pe2 SourceElement to be added */ public void add(SourceElement pe1, SourceElement pe2) { - if ( declarations0 == null ) { - declarations0 = new LinkedList (); - declarations1 = new LinkedList (); + if (declarations0 == null) { + declarations0 = new LinkedList(); + declarations1 = new LinkedList(); } - declarations0.add ( 0, pe1 ); - declarations1.add ( 0, pe2 ); + declarations0.add(0, pe1); + declarations1.add(0, pe2); } - /** - * tests if the given elements have been assigned to the same - * abstract name. - * @param pe0 SourceElement - * @param pe1 SourceElement - * @returns true if the pe1 and pe2 have been assigned to the same - * name + /** + * tests if the given elements have been assigned to the same abstract name. + * + * @param pe0 SourceElement + * @param pe1 SourceElement + * @returns true if the pe1 and pe2 have been assigned to the same name */ public boolean sameAbstractName(SourceElement pe0, SourceElement pe1) { - if ( declarations0 != null ) { - final Iterator it0 = declarations0.iterator (); - final Iterator it1 = declarations1.iterator (); + if (declarations0 != null) { + final Iterator it0 = declarations0.iterator(); + final Iterator it1 = declarations1.iterator(); - while ( it0.hasNext () ) { + while (it0.hasNext()) { // both lists are assumed to hold the same number of elements - final Object o0 = it0.next (); - final Object o1 = it1.next (); + final Object o0 = it0.next(); + final Object o1 = it1.next(); - if ( pe0.equals ( o0 ) ) { - return pe1.equals ( o1 ); - } else if ( pe1.equals ( o1 ) ) { + if (pe0.equals(o0)) { + return pe1.equals(o1); + } else if (pe1.equals(o1)) { return false; } } } - - return pe0.equals ( pe1 ); + + return pe0.equals(pe1); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedModelElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedModelElement.java index 1ed96f51a81..7d087731696 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedModelElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedModelElement.java @@ -1,15 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; -/** +/** * A model element that carries a name. */ public interface NamedModelElement extends ModelElement { - /** + /** * Return the name of the model element. * * @return the name of the model element. */ String getName(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedProgramElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedProgramElement.java index ffe71eb1e38..d8366bd1f28 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedProgramElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/NamedProgramElement.java @@ -1,17 +1,20 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Named program element. - * taken from COMPOST and changed to achieve an immutable structure + * Named program element. taken from COMPOST and changed to achieve an immutable structure */ public interface NamedProgramElement extends NamedModelElement, NonTerminalProgramElement { /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ de.uka.ilkd.key.logic.ProgramElementName getProgramElementName(); -} \ No newline at end of file +} 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 6803c26e41c..d16c54ba7bf 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 @@ -1,26 +1,28 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Non terminal program element. - * taken from COMPOST and changed to achieve an immutable structure + * 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 + * @exception 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 4b6eb5cf6c0..c1a92c621e3 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import org.key_project.util.ExtList; @@ -7,29 +10,28 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Package specification. - * taken from COMPOST and changed to achieve an immutable structure + * Package specification. 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. + * 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); } @@ -39,50 +41,55 @@ 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 + */ public int getChildCount() { int result = 0; - if (reference != null) result++; + if (reference != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ 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. */ public PackageReference getPackageReference() { return reference; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnPackageSpecification(this); + v.performActionOnPackageSpecification(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printPackageSpecification(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParameterContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParameterContainer.java index 282553314d7..90e876cd9e0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParameterContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParameterContainer.java @@ -1,28 +1,31 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.declaration.ParameterDeclaration; /** - * Describes program elements that contain - * {@link recoder.java.declaration.ParameterDeclaration}s. + * Describes program elements that contain {@link recoder.java.declaration.ParameterDeclaration}s. * taken from RECODER and changed to achieve an immutable structure */ public interface ParameterContainer extends StatementContainer { /** - * 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. */ 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. - * @return the parameter declaration with the given index. - * @exception ArrayIndexOutOfBoundsException if index is out - * of bounds. - */ + * Return the parameter declaration at the specified index in this node's "virtual" parameter + * declaration array. + * + * @param index an index for a parameter declaration. + * @return the parameter declaration with the given index. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ ParameterDeclaration getParameterDeclarationAt(int index); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParentIsInterfaceDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParentIsInterfaceDeclaration.java index cf25ed1bca7..e0713719b8c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParentIsInterfaceDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParentIsInterfaceDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; public class ParentIsInterfaceDeclaration { @@ -5,11 +8,11 @@ public class ParentIsInterfaceDeclaration { private boolean value; public ParentIsInterfaceDeclaration(boolean val) { - this.value=val; + this.value = val; } public boolean getValue() { - return value; + return value; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParseExceptionInFile.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParseExceptionInFile.java index d38b5cf96b3..ea9c1f173ba 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ParseExceptionInFile.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ParseExceptionInFile.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.parser.Location; @@ -11,9 +14,8 @@ /** * This exception extends recoder's {@link ParseException} by a filename. *

    - * The filename is used to display the location of an error in the sources. Line - * and column number are not stored here explicitly but retrieved from the - * cause. + * The filename is used to display the location of an error in the sources. Line and column number + * are not stored here explicitly but retrieved from the cause. * * @author mulbrich */ diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/PosConvertException.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/PosConvertException.java index d017b21020e..3ab04e9b984 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/PosConvertException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/PosConvertException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; @@ -33,8 +36,8 @@ public class PosConvertException extends ConvertException implements HasLocation * Instantiates a new exception with position information. * * @param message the message, not null - * @param line the line to point to - * @param column the column to point to + * @param line the line to point to + * @param column the column to point to */ public PosConvertException(String message, int line, int column) { super(message); @@ -45,8 +48,8 @@ public PosConvertException(String message, int line, int column) { /** * Instantiates a new exception with position information. * - * @param cause the exception causing this instance. - * @param line the line to point to + * @param cause the exception causing this instance. + * @param line the line to point to * @param column the column to point to */ public PosConvertException(Throwable cause, int line, int column) { @@ -87,4 +90,4 @@ public Location getLocation() throws MalformedURLException { } return new Location(file, getLine(), getColumn()); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Position.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Position.java index 77a0cbd6b1e..c21093eec8b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Position.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Position.java @@ -1,118 +1,128 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - The position of a source element, given by its line and column - number. - Depending on the implementation, the valid range of defined line and - column numbers may be limited and cut off if superceded. -*/ + * The position of a source element, given by its line and column number. Depending on the + * implementation, the valid range of defined line and column numbers may be limited and cut off if + * superceded. + */ public class Position { /** - The line number. - */ + * The line number. + */ private final int line; /** - The column number. - */ + * The column number. + */ private final int column; /** - The "undefined position" constant used to compare to undefined - positions or remove positional information. - */ - public static final Position UNDEFINED = new Position(); + * The "undefined position" constant used to compare to undefined positions or remove positional + * information. + */ + public static final Position UNDEFINED = new Position(); /** - Constructs a new invalid source code position object. - */ + * Constructs a new invalid source code position object. + */ Position() { - line = column = -1; + line = column = -1; } /** - Constructs a new source code position object. - @param line the line number. - @param column the column number. - */ + * Constructs a new source code position object. + * + * @param line the line number. + * @param column the column number. + */ public Position(int line, int column) { - this.line=line; - this.column=column; + this.line = line; + this.column = column; } /** - Returns the line number of this position. - @return the line number of this position. - */ + * Returns the line number of this position. + * + * @return the line number of this position. + */ public int getLine() { - return line; + return line; } /** - Returns the column number of this position. - @return the column number of this position. - */ + * Returns the column number of this position. + * + * @return the column number of this position. + */ public int getColumn() { - return column; + return column; } /** - Returns the hash code of this position. - @return the hash code of this position. - */ + * Returns the hash code of this position. + * + * @return the hash code of this position. + */ public int hashCode() { - return column | (line << 8); + return column | (line << 8); } /** - Compares this position with the given object for equality. - @return true, if the given object is a position - equals to this position, false otherwise. - */ + * Compares this position with the given object for equality. + * + * @return true, if the given object is a position equals to this position, + * false otherwise. + */ public boolean equals(Object x) { - if (x == this) { - return true; - } - if (!(x instanceof Position)) { - return false; - } - Position p = (Position)x; - return line == p.line && column == p.column; + if (x == this) { + return true; + } + if (!(x instanceof Position)) { + return false; + } + Position p = (Position) x; + return line == p.line && column == p.column; } /** - Compares this position with the given object for order. - An undefined position is less than any defined position. - @param x the position object to compare with. - @return a negative number, zero, or a positive number, if this - position is lower than, equals to, or higher than the given one. - */ + * Compares this position with the given object for order. An undefined position is less than + * any defined position. + * + * @param x the position object to compare with. + * @return a negative number, zero, or a positive number, if this position is lower than, equals + * to, or higher than the given one. + */ public int compareTo(Object x) { - return compareTo((Position)x); + return compareTo((Position) x); } /** - Compares this position with the given object for order. - An undefined position is less than any defined position. - @param p the position to compare with. - @return a negative number, zero, or a positive number, if this - position is lower than, equals to, or higher than the given one. - */ + * Compares this position with the given object for order. An undefined position is less than + * any defined position. + * + * @param p the position to compare with. + * @return a negative number, zero, or a positive number, if this position is lower than, equals + * to, or higher than the given one. + */ public int compareTo(Position p) { - return (line == p.line) ? (column - p.column) : (line - p.line); + return (line == p.line) ? (column - p.column) : (line - p.line); } /** * Helper method for validity checks. + * * @return true iff either line or column are negative */ public boolean isNegative() { @@ -120,16 +130,16 @@ public boolean isNegative() { } /** - Returns a string representation of this object. - */ + * Returns a string representation of this object. + */ public String toString() { - if (this != UNDEFINED) { - StringBuffer buf = new StringBuffer(); - buf.append(line).append('/').append(column - 1); - return buf.toString(); - } else { - return "??/??"; - } + if (this != UNDEFINED) { + StringBuffer buf = new StringBuffer(); + buf.append(line).append('/').append(column - 1); + return buf.toString(); + } else { + return "??/??"; + } } -} \ No newline at end of file +} 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 eba44c2fb13..c296f9875ef 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 @@ -1,11 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.net.URI; import java.nio.file.Paths; /** - * represents a group of three Positions: relativePosition, - * startPosition, endPosition + * represents a group of three Positions: relativePosition, startPosition, endPosition * * 2019-09-10 Wolfram Pfeifer: work with URIs instead of Strings -> more robust, more general */ @@ -28,14 +30,14 @@ public class PositionInfo { private final Position endPos; /** - * The URI of the resource this location refers to. - * Either a meaningful value or {@link #UNKNOWN_URI}, but never null. + * The URI of the resource this location refers to. Either a meaningful value or + * {@link #UNKNOWN_URI}, but never null. */ private final URI fileURI; /** - * The URI of the parent class of this location (the class the statement originates from). - * May be null. + * The URI of the parent class of this location (the class the statement originates from). May + * be null. */ private URI parentClassURI; @@ -48,6 +50,7 @@ private PositionInfo() { /** * Creates a new PositionInfo without resource information but only with positions. + * * @param relPos the relative position * @param startPos the start position * @param endPos the end position @@ -61,6 +64,7 @@ public PositionInfo(Position relPos, Position startPos, Position endPos) { /** * Creates a new PositionInfo without the given resource information. + * * @param relPos the relative position * @param startPos the start position * @param endPos the end position @@ -71,14 +75,16 @@ public PositionInfo(Position relPos, Position startPos, Position endPos, URI fil this.startPos = startPos; this.endPos = endPos; if (fileURI == null) { - this.fileURI = UNKNOWN_URI; // fileURI must not be null! + this.fileURI = UNKNOWN_URI; // fileURI must not be null! } else { this.fileURI = fileURI.normalize(); } } - /** this violates immutability, but the method is only called - * right after the object is created... + /** + * 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) { @@ -86,13 +92,14 @@ void setParentClassURI(URI parent) { } /** - * Returns the path of the parent file the PositionInfo refers to - * (the class the statement originates from). + * 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. + * resources other than files. Use {@link #getParentClassURI()} instead. * @return the filename as a string if parentClass uses the "file" protocol or null otherwise */ - @Deprecated // only kept for compatibility reasons + @Deprecated // only kept for compatibility reasons public String getParentClass() { if (parentClassURI != null && parentClassURI.getScheme().equals("file")) { return Paths.get(parentClassURI).toString(); @@ -102,11 +109,12 @@ public String getParentClass() { /** * Returns the path of the file the PositionInfo refers to. + * * @deprecated This method should no longer be used, as PositionInfo can now be used with - * resources other than files. Use {@link #getURI()} instead. + * 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 + @Deprecated // only kept for compatibility reasons public String getFileName() { if (fileURI.getScheme().equals("file")) { return Paths.get(fileURI).toString(); @@ -135,12 +143,13 @@ 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. + * 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 - * ending at the maximum of the two end positions. + * @return a new PositionInfo starting at the minimum of the two start positions and ending at + * the maximum of the two end positions. */ public static PositionInfo join(PositionInfo p1, PositionInfo p2) { if (p1 == null && p2 == null) { @@ -162,7 +171,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; @@ -179,6 +188,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() { @@ -192,7 +202,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/PrettyPrinter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/PrettyPrinter.java index 8b4f563a4d2..c678d56bbd5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/PrettyPrinter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/PrettyPrinter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -37,33 +40,33 @@ import org.slf4j.LoggerFactory; /** - A configurable pretty printer for Java source elements originally from COMPOST. - - @author AL - - CHANGED FOR KeY. Comments are not printed! + * A configurable pretty printer for Java source elements originally from COMPOST. + * + * @author AL + * + * CHANGED FOR KeY. Comments are not printed! */ public class PrettyPrinter { private static final Logger LOGGER = LoggerFactory.getLogger(PrettyPrinter.class); /** - Line number, not directly used. - */ + * Line number, not directly used. + */ private int line = 0; /** - Column number. Used to keep track of indentations. - */ + * Column number. Used to keep track of indentations. + */ private int column = 0; /** - Level. - */ + * Level. + */ protected int level = 0; protected Writer out; protected StringBuffer outBuf; - protected boolean noLinefeed=false; - protected boolean noSemicolons=false; + protected boolean noLinefeed = false; + protected boolean noSemicolons = false; protected int firstStatementStart = -1; protected int firstStatementEnd = -1; @@ -80,13 +83,13 @@ public class PrettyPrinter { /** creates a new PrettyPrinter */ public PrettyPrinter(Writer o) { - setWriter(o); - outBuf = new StringBuffer(); + setWriter(o); + outBuf = new StringBuffer(); } public PrettyPrinter(Writer o, SVInstantiations svi) { - this(o); - this.instantiations = svi; + this(o); + this.instantiations = svi; } public PrettyPrinter(Writer o, boolean noLinefeed) { @@ -104,97 +107,105 @@ public PrettyPrinter(Writer o, boolean noLinefeed, SVInstantiations svi) { protected int writtenCharacters = 0; protected void output() throws IOException { - if (noSemicolons) removeChar(outBuf, ';'); - if (noLinefeed) removeChar(outBuf, '\n'); - String toWrite = outBuf.toString(); - writtenCharacters += toWrite.length(); - out.write(toWrite); - outBuf=new StringBuffer(); + if (noSemicolons) + removeChar(outBuf, ';'); + if (noLinefeed) + removeChar(outBuf, '\n'); + String toWrite = outBuf.toString(); + writtenCharacters += toWrite.length(); + out.write(toWrite); + outBuf = new StringBuffer(); } /** Numbers of generated characters */ - protected int getCurrentPos(){ - return writtenCharacters + outBuf.length(); + protected int getCurrentPos() { + return writtenCharacters + outBuf.length(); } /** * Marks the start of the first executable statement ... + * * @param n offset from the current position * @param stmt current statement; */ - protected void markStart(int n, Object stmt){ + protected void markStart(int n, Object stmt) { if (!startAlreadyMarked) { firstStatementStart = getCurrentPos() + n; firstStatement = stmt; startAlreadyMarked = true; } } + /** * Marks the end of the first executable statement ... + * * @param n offset from the current position */ - protected void markEnd(int n, Object stmt){ - if (!endAlreadyMarked && (firstStatement == stmt)) { - firstStatementEnd = getCurrentPos() + n; - endAlreadyMarked = true; - } + protected void markEnd(int n, Object stmt) { + if (!endAlreadyMarked && (firstStatement == stmt)) { + firstStatementEnd = getCurrentPos() + n; + endAlreadyMarked = true; + } } /** - * @return the range of the first executable statement that means - * the corresponding start and end position in the string representation + * @return the range of the first executable statement that means the corresponding start and + * end position in the string representation */ - public Range getRangeOfFirstExecutableStatement(){ - return new Range(firstStatementStart,firstStatementEnd); + public Range getRangeOfFirstExecutableStatement() { + return new Range(firstStatementStart, firstStatementEnd); } + /** * Marks the start of a java keyword. */ protected final void markKeywordStart() { - keywordStarts.push(getCurrentPos()); + keywordStarts.push(getCurrentPos()); } + /** * Marks the end of a java keyword and creates a keyword range. */ protected final void markKeywordEnd() { - keywordRanges.add(new Range(keywordStarts.pop(), getCurrentPos())); + keywordRanges.add(new Range(keywordStarts.pop(), getCurrentPos())); } + /** * @return ranges of all java keywords printed. */ public final Range[] getKeywordRanges() { - return keywordRanges.toArray(new Range[keywordRanges.size()]); + return keywordRanges.toArray(new Range[keywordRanges.size()]); } + /** * Resets the state of this pretty printer ... */ - public void reset(){ - firstStatementStart = -1; - firstStatementEnd = -1; - firstStatement = null; - startAlreadyMarked = false; - endAlreadyMarked = false; - writtenCharacters = 0; - outBuf = new StringBuffer(); - keywordRanges = new ArrayList<>(); + public void reset() { + firstStatementStart = -1; + firstStatementEnd = -1; + firstStatement = null; + startAlreadyMarked = false; + endAlreadyMarked = false; + writtenCharacters = 0; + outBuf = new StringBuffer(); + keywordRanges = new ArrayList<>(); } /** - Flag to indicate if a single line comment is being put out. - Needed to disable the worklist meanwhile. - */ + * Flag to indicate if a single line comment is being put out. Needed to disable the worklist + * meanwhile. + */ private boolean isPrintingSingleLineComments = false; - protected HashMap indentMap= new LinkedHashMap<>(); + protected HashMap indentMap = new LinkedHashMap<>(); /** - Set a new stream to write to. Useful to redirect the output - while retaining all other settings. Resets the current source - positions and comments. - */ + * Set a new stream to write to. Useful to redirect the output while retaining all other + * settings. Resets the current source positions and comments. + */ public void setWriter(Writer out) { this.out = out; column = 0; @@ -202,49 +213,55 @@ public void setWriter(Writer out) { } /** - Get current line number. - @return the line number, starting with 0. - */ + * Get current line number. + * + * @return the line number, starting with 0. + */ public int getLine() { return line; } /** - Get current column number. - @return the column number, starting with 0. - */ + * Get current column number. + * + * @return the column number, starting with 0. + */ public int getColumn() { return column; } /** - Get indentation level. - @return the int value. - */ + * Get indentation level. + * + * @return the int value. + */ public int getIndentationLevel() { return level; } /** - Set indentation level. - @param level an int value. - */ + * Set indentation level. + * + * @param level an int value. + */ public void setIndentationLevel(int level) { this.level = level; } /** - Get total indentation. - @return the int value. - */ + * Get total indentation. + * + * @return the int value. + */ public int getTotalIndentation() { return indentation * level; } /** - Change level. - @param delta an int value. - */ + * Change level. + * + * @param delta an int value. + */ public void changeLevel(int delta) { level += delta; } @@ -259,78 +276,81 @@ public void changeLevel(int delta) { } /** - Convenience method to write indentation chars. - */ + * Convenience method to write indentation chars. + */ protected void writeIndentation(int lf, int blanks) throws IOException { - if (!noLinefeed) { - if (lf > 0) { - do { - int n = Math.min(lf, FEEDS.length); - write(FEEDS, 0, n); - lf -= n; - } while (lf > 0); - } - while (blanks > 0) { - int n = Math.min(blanks, BLANKS.length); - write(BLANKS, 0, n); - blanks -= n; - } - } + if (!noLinefeed) { + if (lf > 0) { + do { + int n = Math.min(lf, FEEDS.length); + write(FEEDS, 0, n); + lf -= n; + } while (lf > 0); + } + while (blanks > 0) { + int n = Math.min(blanks, BLANKS.length); + write(BLANKS, 0, n); + blanks -= n; + } + } } /** - Convenience method to write indentation chars. - */ + * Convenience method to write indentation chars. + */ protected void writeIndentation(Position relative) throws IOException { writeIndentation(relative.getLine(), relative.getColumn()); } /** - Write indentation. - @param elem a source element. - @exception IOException occasionally thrown. - */ + * Write indentation. + * + * @param elem a source element. + * @exception IOException occasionally thrown. + */ protected void writeIndentation(SourceElement elem) throws IOException { writeIndentation(getRelativePosition(elem.getFirstElement())); } /** - Write internal indentation. - @param elem a source element. - @exception IOException occasionally thrown. - */ + * Write internal indentation. + * + * @param elem a source element. + * @exception IOException occasionally thrown. + */ protected void writeInternalIndentation(SourceElement elem) throws IOException { writeIndentation(getRelativePosition(elem)); } /** - Write symbol. - @param lf an int value. - @param levelChange an int value. - @param symbol a string. - @exception IOException occasionally thrown. - */ + * Write symbol. + * + * @param lf an int value. + * @param levelChange an int value. + * @param symbol a string. + * @exception IOException occasionally thrown. + */ protected void writeSymbol(int lf, int levelChange, String symbol) throws IOException { level += levelChange; writeIndentation(lf, getTotalIndentation()); boolean isKey = (symbol.equals("int") || symbol.equals("float") || symbol.equals("char") - || symbol.equals("short") || symbol.equals("long") || symbol.equals("boolean")); + || symbol.equals("short") || symbol.equals("long") || symbol.equals("boolean")); if (isKey) { - markKeywordStart(); + markKeywordStart(); } write(symbol); if (isKey) { - markKeywordEnd(); + markKeywordEnd(); } } /** - Replace all unicode characters above ? - by their explicit representation. - @param str the input string. - @return the encoded string. - */ + * Replace all unicode characters above ? by their explicit representation. + * + * @param str the input string. + * @return the encoded string. + */ protected static String encodeUnicodeChars(String str) { int len = str.length(); StringBuilder buf = new StringBuilder(len + 4); @@ -350,18 +370,18 @@ protected static String encodeUnicodeChars(String str) { } /** - Store the given comment until the next line feed is written. - @param slc the comment to delay. + * Store the given comment until the next line feed is written. + * + * @param slc the comment to delay. */ - protected void scheduleComment(SingleLineComment slc) { - } + protected void scheduleComment(SingleLineComment slc) {} /** - Adds indentation for a program element if necessary and if required, - but does not print the indentation itself. - */ - protected void writeElement(int lf, int levelChange, int blanks, - SourceElement elem) throws IOException { + * Adds indentation for a program element if necessary and if required, but does not print the + * indentation itself. + */ + protected void writeElement(int lf, int levelChange, int blanks, SourceElement elem) + throws IOException { level += levelChange; if (lf > 0) { blanks += getTotalIndentation(); @@ -386,7 +406,8 @@ protected Position getRelativePosition(SourceElement first) { if (indentMap.containsKey(first)) { return indentMap.get(first); } else { - if (first!=null) return first.getRelativePosition(); + if (first != null) + return first.getRelativePosition(); } @@ -394,14 +415,13 @@ protected Position getRelativePosition(SourceElement first) { } /** - Writes an implicit terminal token of a NonTerminal, including - its indentation. Sets the indentation if it is necessary or - required. - @see SourceElement#prettyPrint - */ - protected void writeToken(int lf, int blanks, String image, - NonTerminalProgramElement parent) - throws IOException { + * Writes an implicit terminal token of a NonTerminal, including its indentation. Sets the + * indentation if it is necessary or required. + * + * @see SourceElement#prettyPrint + */ + protected void writeToken(int lf, int blanks, String image, NonTerminalProgramElement parent) + throws IOException { if (lf > 0) { blanks += getTotalIndentation(); } @@ -410,181 +430,184 @@ protected void writeToken(int lf, int blanks, String image, indent = new Position(lf, blanks); } else { if (lf > indent.getLine()) { - indent=new Position(lf, indent.getColumn()); + indent = new Position(lf, indent.getColumn()); } if (blanks > indent.getColumn()) { - indent=new Position(indent.getLine(), blanks); + indent = new Position(indent.getLine(), blanks); } } - indentMap.put(parent.getFirstElement(), indent); //needed ????? + indentMap.put(parent.getFirstElement(), indent); // needed ????? writeIndentation(indent); - // if (overwriteParsePositions) { - // parent.setInternalParsedLine(line); - // parent.setInternalParsedColumn(column); - // } + // if (overwriteParsePositions) { + // parent.setInternalParsedLine(line); + // parent.setInternalParsedColumn(column); + // } if (image.equals("catch")) { - markKeywordStart(); - //XXX space before image is a dirty fix for bug where c of catch would not be highlighted - write(" "); + markKeywordStart(); + // XXX space before image is a dirty fix for bug where c of catch would not be + // highlighted + write(" "); } write(image); if (image.equals("catch")) { - markKeywordEnd(); + markKeywordEnd(); } } - protected final void writeToken(int blanks, String image, - NonTerminalProgramElement parent) - throws IOException { + protected final void writeToken(int blanks, String image, NonTerminalProgramElement parent) + throws IOException { writeToken(0, blanks, image, parent); } protected final void writeToken(String image, NonTerminalProgramElement parent) - throws IOException { + throws IOException { writeToken(0, 0, image, parent); } /** - Write a source element. - @param lf an int value. - @param blanks an int value. - @param elem a source element. - @exception IOException occasionally thrown. - */ + * Write a source element. + * + * @param lf an int value. + * @param blanks an int value. + * @param elem a source element. + * @exception IOException occasionally thrown. + */ protected void writeElement(int lf, int blanks, SourceElement elem) throws IOException { writeElement(lf, 0, blanks, elem); } /** - Write source element. - @param blanks an int value. - @param elem a source element. - @exception IOException occasionally thrown. - */ + * Write source element. + * + * @param blanks an int value. + * @param elem a source element. + * @exception IOException occasionally thrown. + */ protected void writeElement(int blanks, SourceElement elem) throws IOException { writeElement(0, 0, blanks, elem); } /** - Write source element. - @param elem a source element. - @exception IOException occasionally thrown. - */ + * Write source element. + * + * @param elem a source element. + * @exception IOException occasionally thrown. + */ protected void writeElement(SourceElement elem) throws IOException { writeElement(0, 0, 0, elem); } /** - Write a complete ArrayOf. - */ - protected void writeImmutableArrayOfProgramElement(int firstLF, - int levelChange, - int firstBlanks, - String separationSymbol, - int separationLF, - int separationBlanks, - ImmutableArray list) - throws IOException { + * Write a complete ArrayOf. + */ + protected void writeImmutableArrayOfProgramElement(int firstLF, int levelChange, + int firstBlanks, String separationSymbol, int separationLF, int separationBlanks, + ImmutableArray list) throws IOException { int s = list.size(); if (s == 0) { return; } - writeElement(firstLF, levelChange, firstBlanks, - list.get(0)); + writeElement(firstLF, levelChange, firstBlanks, list.get(0)); for (int i = 1; i < s; i += 1) { write(separationSymbol); - writeElement(separationLF, separationBlanks, - list.get(i)); + writeElement(separationLF, separationBlanks, list.get(i)); } } /** - Write a complete ArrayOf using "Keyword" style. - */ + * Write a complete ArrayOf using "Keyword" style. + */ protected void writeKeywordList(int firstLF, int levelChange, int firstBlanks, - ImmutableArray list) throws IOException { + ImmutableArray list) throws IOException { writeImmutableArrayOfProgramElement(firstLF, levelChange, firstBlanks, "", 0, 1, list); } /** - Write keyword list. - @param list a program element list. - @exception IOException occasionally thrown. - */ - protected void writeKeywordList(ImmutableArray list) throws IOException { + * Write keyword list. + * + * @param list a program element list. + * @exception IOException occasionally thrown. + */ + protected void writeKeywordList(ImmutableArray list) + throws IOException { writeImmutableArrayOfProgramElement(0, 0, 0, "", 0, 1, list); } /** - Write a complete ArrayOf using "Comma" style. - */ + * Write a complete ArrayOf using "Comma" style. + */ protected void writeCommaList(int firstLF, int levelChange, int firstBlanks, - ImmutableArray list) throws IOException { - writeImmutableArrayOfProgramElement(firstLF, levelChange, - firstBlanks, ",", 0, 1, list); + ImmutableArray list) throws IOException { + writeImmutableArrayOfProgramElement(firstLF, levelChange, firstBlanks, ",", 0, 1, list); } /** - Write comma list. - @param list a program element list. - @exception IOException occasionally thrown. - */ - protected void writeCommaList(int separationBlanks, ImmutableArray list) - throws IOException { + * Write comma list. + * + * @param list a program element list. + * @exception IOException occasionally thrown. + */ + protected void writeCommaList(int separationBlanks, + ImmutableArray list) throws IOException { writeImmutableArrayOfProgramElement(0, 0, 0, ",", 0, separationBlanks, list); } /** - Write comma list. - @param list a program element list. - @exception IOException occasionally thrown. - */ - protected void writeCommaList(ImmutableArray list) throws IOException { + * Write comma list. + * + * @param list a program element list. + * @exception IOException occasionally thrown. + */ + protected void writeCommaList(ImmutableArray list) + throws IOException { writeImmutableArrayOfProgramElement(0, 0, 0, ",", 0, 1, list); } /** - Write a complete ArrayOf using "Line" style. - */ + * Write a complete ArrayOf using "Line" style. + */ protected void writeLineList(int firstLF, int levelChange, int firstBlanks, - ImmutableArray list) throws IOException { + ImmutableArray list) throws IOException { writeImmutableArrayOfProgramElement(firstLF, levelChange, firstBlanks, "", 1, 0, list); } /** - Write line list. - @param list a program element list. - @exception IOException occasionally thrown. - */ + * Write line list. + * + * @param list a program element list. + * @exception IOException occasionally thrown. + */ protected void writeLineList(ImmutableArray list) throws IOException { writeImmutableArrayOfProgramElement(0, 0, 0, "", 1, 0, list); } /** - Write a complete ArrayOf using "Block" style. - */ + * Write a complete ArrayOf using "Block" style. + */ protected void writeBlockList(int firstLF, int levelChange, int firstBlanks, - ImmutableArray list) throws IOException { + ImmutableArray list) throws IOException { writeImmutableArrayOfProgramElement(firstLF, levelChange, firstBlanks, "", 2, 0, list); } /** - Write block list. - @param list a program element list. - @exception IOException occasionally thrown. - */ - protected void writeBlockList(ImmutableArray list) throws IOException { + * Write block list. + * + * @param list a program element list. + * @exception IOException occasionally thrown. + */ + protected void writeBlockList(ImmutableArray list) + throws IOException { writeImmutableArrayOfProgramElement(0, 0, 0, "", 2, 0, list); } - private void dumpComments() throws IOException { - } + private void dumpComments() throws IOException {} /** - Write. - @param c an int value. - @exception IOException occasionally thrown. - */ + * Write. + * + * @param c an int value. + * @exception IOException occasionally thrown. + */ public void write(int c) throws IOException { if (c == '\n') { if (!isPrintingSingleLineComments) { @@ -599,21 +622,23 @@ public void write(int c) throws IOException { } /** - Write. - @param cbuf a char value. - @exception IOException occasionally thrown. - */ + * Write. + * + * @param cbuf a char value. + * @exception IOException occasionally thrown. + */ public void write(char[] cbuf) throws IOException { write(cbuf, 0, cbuf.length); } /** - Write. - @param cbuf an array of char. - @param off an int value. - @param len an int value. - @exception IOException occasionally thrown. - */ + * Write. + * + * @param cbuf an array of char. + * @param off an int value. + * @param len an int value. + * @exception IOException occasionally thrown. + */ public void write(char[] cbuf, int off, int len) throws IOException { boolean col = false; @@ -631,20 +656,20 @@ public void write(char[] cbuf, int off, int len) throws IOException { } if (!col) { column += len; - /* - int i; - for (i = off + len - 1; (i >= off && cbuf[i] != '\n'); i -= 1) ; - column = (i >= off) ? (off + len - 1 - i) : (column + len); - */ + /* + * int i; for (i = off + len - 1; (i >= off && cbuf[i] != '\n'); i -= 1) ; column = (i + * >= off) ? (off + len - 1 - i) : (column + len); + */ } outBuf.append(cbuf, off, len); } /** - Write. - @param str a string. - @exception IOException occasionally thrown. - */ + * Write. + * + * @param str a string. + * @exception IOException occasionally thrown. + */ public void write(String str) throws IOException { int i = str.lastIndexOf('\n'); if (i >= 0) { @@ -661,107 +686,111 @@ public void write(String str) throws IOException { } /** - Write. - @param str a string. - @param off an int value. - @param len an int value. - @exception IOException occasionally thrown. - */ + * Write. + * + * @param str a string. + * @param off an int value. + * @param len an int value. + * @exception IOException occasionally thrown. + */ public void write(String str, int off, int len) throws IOException { write(str.substring(off, off + len)); } /** - Indentation (cached). - */ - private int indentation=2; + * Indentation (cached). + */ + private int indentation = 2; /* - Wrap threshold (cached). - private int wrap; - */ + * Wrap threshold (cached). private int wrap; + */ /** - Overwrite indentation flag (cached). - */ + * Overwrite indentation flag (cached). + */ private boolean overwriteIndentation; /** - Overwrite parse positions flag (cached). + * Overwrite parse positions flag (cached). */ private boolean overwriteParsePositions; /** - Get indentation amount (blanks per level). - @return the value of getIntegerProperty("indentationAmount"). - */ + * Get indentation amount (blanks per level). + * + * @return the value of getIntegerProperty("indentationAmount"). + */ protected int getIndentation() { return indentation; } /** - Returns true if the pretty printer should also reformat existing - code. - @return the value of the overwriteIndentation property. - */ + * Returns true if the pretty printer should also reformat existing code. + * + * @return the value of the overwriteIndentation property. + */ protected boolean isOverwritingIndentation() { return overwriteIndentation; } /** - Returns true if the pretty printer should reset the parse positions - accordingly. - @return the value of the overwriteParsePositions property. - */ + * Returns true if the pretty printer should reset the parse positions accordingly. + * + * @return the value of the overwriteParsePositions property. + */ protected boolean isOverwritingParsePositions() { return overwriteParsePositions; } /** - Print program element header. - @param lf an int value. - @param blanks an int value. - @param elem a program element. - @exception IOException occasionally thrown. - */ - protected void printHeader(int lf, int blanks, ProgramElement elem) - throws IOException { + * Print program element header. + * + * @param lf an int value. + * @param blanks an int value. + * @param elem a program element. + * @exception IOException occasionally thrown. + */ + protected void printHeader(int lf, int blanks, ProgramElement elem) throws IOException { printHeader(lf, 0, blanks, elem); } /** - Print program element header. - @param blanks an int value. - @param elem a program element. - @exception IOException occasionally thrown. - */ + * Print program element header. + * + * @param blanks an int value. + * @param elem a program element. + * @exception IOException occasionally thrown. + */ protected void printHeader(int blanks, ProgramElement elem) throws IOException { printHeader(0, 0, blanks, elem); } /** - Print program element header. - @param elem a program element. - @exception IOException occasionally thrown. - */ + * Print program element header. + * + * @param elem a program element. + * @exception IOException occasionally thrown. + */ protected void printHeader(ProgramElement elem) throws IOException { printHeader(0, 0, 0, elem); } /** - Print program element header. - @param lf number of line feeds. - @param levelChange the level change. - @param blanks number of white spaces. - @param x the program element. - @exception IOException occasionally thrown. - */ + * Print program element header. + * + * @param lf number of line feeds. + * @param levelChange the level change. + * @param blanks number of white spaces. + * @param x the program element. + * @exception IOException occasionally thrown. + */ protected void printHeader(int lf, int levelChange, int blanks, ProgramElement x) - throws IOException { + throws IOException { level += levelChange; if (lf > 0) { @@ -772,11 +801,11 @@ protected void printHeader(int lf, int levelChange, int blanks, ProgramElement x if (indent == Position.UNDEFINED) { indent = new Position(lf, blanks); } else { - if (lf > indent.getLine()) { - indent=new Position(lf, indent.getColumn()); + if (lf > indent.getLine()) { + indent = new Position(lf, indent.getColumn()); } if (blanks > indent.getColumn()) { - indent=new Position(indent.getLine(), blanks); + indent = new Position(indent.getLine(), blanks); } } indentMap.put(first, indent); @@ -784,41 +813,41 @@ protected void printHeader(int lf, int levelChange, int blanks, ProgramElement x /** - Print program element footer. - @param x the program element. - @exception IOException occasionally thrown. - */ + * Print program element footer. + * + * @param x the program element. + * @exception IOException occasionally thrown. + */ protected void printFooter(ProgramElement x) throws IOException { - output(); + output(); } - protected void printOperator(Operator x, String symbol) - throws java.io.IOException { + protected void printOperator(Operator x, String symbol) throws java.io.IOException { // Mark statement start ... - markStart(0,x); + markStart(0, x); ImmutableArray children = x.getArguments(); if (children != null) { -// boolean addParentheses = x.isToBeParenthesized(); -// if (addParentheses) { -// write('('); -// } //???? + // boolean addParentheses = x.isToBeParenthesized(); + // if (addParentheses) { + // write('('); + // } //???? if (!noLinefeed) { - writeSymbol(1,0, ""); + writeSymbol(1, 0, ""); } output(); boolean wasNoSemicolons = noSemicolons; - boolean wasNoLinefeed = noLinefeed; + boolean wasNoLinefeed = noLinefeed; noSemicolons = true; - // noLinefeed=true; + // noLinefeed=true; switch (x.getArity()) { case 2: - noLinefeed=true; + noLinefeed = true; writeElement(0, children.get(0)); writeToken(0, symbol, x); output(); @@ -843,57 +872,54 @@ protected void printOperator(Operator x, String symbol) } output(); noSemicolons = wasNoSemicolons; - noLinefeed = wasNoLinefeed; - // if (addParentheses) { - // write(')'); - // } //???? as above + noLinefeed = wasNoLinefeed; + // if (addParentheses) { + // write(')'); + // } //???? as above if (x instanceof Assignment) { - // if (((Assignment)x).getStatementContainer() != null) { - write(";"); //???? + // if (((Assignment)x).getStatementContainer() != null) { + write(";"); // ???? - // } + // } } output(); // Mark statement end ... - markEnd(0,x); + markEnd(0, x); - /*if (!noLinefeed) { - writeSymbol(1,0, ""); - }*/ + /* + * if (!noLinefeed) { writeSymbol(1,0, ""); } + */ } } - public void printProgramElementName(ProgramElementName x) - throws java.io.IOException { + public void printProgramElementName(ProgramElementName x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); String name = x.getProgramName(); - boolean isKey = (name.equals("int") || name.equals("float") || name.equals("char") || name.equals("short") - || name.equals("long") || name.equals("boolean")); + boolean isKey = (name.equals("int") || name.equals("float") || name.equals("char") + || name.equals("short") || name.equals("long") || name.equals("boolean")); if (isKey) { - markKeywordStart(); + markKeywordStart(); } write(name); if (isKey) { - markKeywordEnd(); + markKeywordEnd(); } printFooter(x); } - public void printProgramVariable(ProgramVariable x) - throws java.io.IOException { + public void printProgramVariable(ProgramVariable x) throws java.io.IOException { - printHeader(x); - writeInternalIndentation(x); + printHeader(x); + writeInternalIndentation(x); - write(x.name().toString()); - printFooter(x); + write(x.name().toString()); + printFooter(x); } - public void printProgramMethod(IProgramMethod x) - throws java.io.IOException { + public void printProgramMethod(IProgramMethod x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); @@ -901,36 +927,34 @@ public void printProgramMethod(IProgramMethod x) printFooter(x); } - public void printProgramMetaConstruct(ProgramTransformer x) - throws java.io.IOException { + public void printProgramMetaConstruct(ProgramTransformer x) throws java.io.IOException { printHeader(x); write(x.name().toString()); writeToken("(", x); - boolean oldNoLinefeed = noLinefeed; - noLinefeed = true; + boolean oldNoLinefeed = noLinefeed; + noLinefeed = true; if (x.getChildAt(0) != null) { writeElement(1, +1, 0, x.getChildAt(0)); writeSymbol(1, -1, ")"); } else { write(")"); } - noLinefeed = oldNoLinefeed; + noLinefeed = oldNoLinefeed; printFooter(x); } - public void printContextStatementBlock(ContextStatementBlock x) - throws java.io.IOException { + public void printContextStatementBlock(ContextStatementBlock x) throws java.io.IOException { printHeader(x); if (x.getStatementCount() > 0) { - writeToken("{ .. ", x); - writeLineList(1, +1, 0, x.getBody()); - writeSymbol(1, -1, " ... }"); + writeToken("{ .. ", x); + writeLineList(1, +1, 0, x.getBody()); + writeSymbol(1, -1, " ... }"); } else { - markStart(0, x); - writeToken("{ .. ", x); + markStart(0, x); + writeToken("{ .. ", x); write(" ... }"); - markEnd(0,x); + markEnd(0, x); } printFooter(x); } @@ -958,7 +982,8 @@ public void printEmptySetLiteral(EmptySetLiteral x) throws java.io.IOException { printFooter(x); } - public void printSingleton(de.uka.ilkd.key.java.expression.operator.adt.Singleton x) throws java.io.IOException { + public void printSingleton(de.uka.ilkd.key.java.expression.operator.adt.Singleton x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\singleton", x); @@ -968,7 +993,8 @@ public void printSingleton(de.uka.ilkd.key.java.expression.operator.adt.Singleto printFooter(x); } - public void printSetUnion(de.uka.ilkd.key.java.expression.operator.adt.SetUnion x) throws java.io.IOException { + public void printSetUnion(de.uka.ilkd.key.java.expression.operator.adt.SetUnion x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\set_union", x); @@ -980,7 +1006,8 @@ public void printSetUnion(de.uka.ilkd.key.java.expression.operator.adt.SetUnion printFooter(x); } - public void printIntersect(de.uka.ilkd.key.java.expression.operator.Intersect x) throws java.io.IOException { + public void printIntersect(de.uka.ilkd.key.java.expression.operator.Intersect x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\intersect", x); @@ -992,7 +1019,8 @@ public void printIntersect(de.uka.ilkd.key.java.expression.operator.Intersect x) printFooter(x); } - public void printSetMinus(de.uka.ilkd.key.java.expression.operator.adt.SetMinus x) throws java.io.IOException { + public void printSetMinus(de.uka.ilkd.key.java.expression.operator.adt.SetMinus x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\set_minus", x); @@ -1005,7 +1033,8 @@ public void printSetMinus(de.uka.ilkd.key.java.expression.operator.adt.SetMinus } - public void printAllFields(de.uka.ilkd.key.java.expression.operator.adt.AllFields x) throws java.io.IOException { + public void printAllFields(de.uka.ilkd.key.java.expression.operator.adt.AllFields x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\all_fields", x); @@ -1015,7 +1044,8 @@ public void printAllFields(de.uka.ilkd.key.java.expression.operator.adt.AllField printFooter(x); } - public void printAllObjects(de.uka.ilkd.key.java.expression.operator.adt.AllObjects x) throws java.io.IOException { + public void printAllObjects(de.uka.ilkd.key.java.expression.operator.adt.AllObjects x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\all_objects", x); @@ -1050,7 +1080,8 @@ public void printSeqGet(SeqGet x) throws java.io.IOException { printFooter(x); } - public void printSeqSingleton(de.uka.ilkd.key.java.expression.operator.adt.SeqSingleton x) throws java.io.IOException { + public void printSeqSingleton(de.uka.ilkd.key.java.expression.operator.adt.SeqSingleton x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\seq_singleton", x); @@ -1060,7 +1091,8 @@ public void printSeqSingleton(de.uka.ilkd.key.java.expression.operator.adt.SeqSi printFooter(x); } - public void printSeqConcat(de.uka.ilkd.key.java.expression.operator.adt.SeqConcat x) throws java.io.IOException { + public void printSeqConcat(de.uka.ilkd.key.java.expression.operator.adt.SeqConcat x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\seq_concat", x); @@ -1072,7 +1104,8 @@ public void printSeqConcat(de.uka.ilkd.key.java.expression.operator.adt.SeqConca printFooter(x); } - public void printIndexOf(de.uka.ilkd.key.java.expression.operator.adt.SeqIndexOf x) throws java.io.IOException { + public void printIndexOf(de.uka.ilkd.key.java.expression.operator.adt.SeqIndexOf x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\indexOf", x); @@ -1084,7 +1117,8 @@ public void printIndexOf(de.uka.ilkd.key.java.expression.operator.adt.SeqIndexOf printFooter(x); } - public void printSeqSub(de.uka.ilkd.key.java.expression.operator.adt.SeqSub x) throws java.io.IOException { + public void printSeqSub(de.uka.ilkd.key.java.expression.operator.adt.SeqSub x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\seq_sub", x); @@ -1098,7 +1132,8 @@ public void printSeqSub(de.uka.ilkd.key.java.expression.operator.adt.SeqSub x) t printFooter(x); } - public void printSeqReverse(de.uka.ilkd.key.java.expression.operator.adt.SeqReverse x) throws java.io.IOException { + public void printSeqReverse(de.uka.ilkd.key.java.expression.operator.adt.SeqReverse x) + throws java.io.IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\seq_reverse", x); @@ -1108,14 +1143,13 @@ public void printSeqReverse(de.uka.ilkd.key.java.expression.operator.adt.SeqReve printFooter(x); } - public void printDLEmbeddedExpression( - DLEmbeddedExpression x) throws IOException { + public void printDLEmbeddedExpression(DLEmbeddedExpression x) throws IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\dl_" + x.getFunctionSymbol().name(), x); write("("); for (int i = 0; i < x.getChildCount(); i++) { - if(i != 0) { + if (i != 0) { write(","); } writeElement(0, x.getChildAt(i)); @@ -1185,8 +1219,7 @@ public void printFloatLiteral(FloatLiteral x) throws java.io.IOException { printFooter(x); } - public void printPackageSpecification(PackageSpecification x) - throws java.io.IOException { + public void printPackageSpecification(PackageSpecification x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); @@ -1201,16 +1234,16 @@ public void printAssert(Assert x) throws java.io.IOException { writeInternalIndentation(x); // Mark statement start ... - markStart(0,x); + markStart(0, x); - boolean wasNoLinefeed = noLinefeed; + boolean wasNoLinefeed = noLinefeed; boolean wasNoSemicolon = noSemicolons; markKeywordStart(); write("assert"); markKeywordEnd(); write(" "); - noLinefeed = true; + noLinefeed = true; noSemicolons = true; writeElement(0, x.getCondition()); @@ -1220,50 +1253,49 @@ public void printAssert(Assert x) throws java.io.IOException { } noSemicolons = wasNoSemicolon; - noLinefeed = wasNoLinefeed; + noLinefeed = wasNoLinefeed; write(";"); output(); // Mark statement end ... - markEnd(0,x); + markEnd(0, x); printFooter(x); } public void printArrayDeclaration(ArrayDeclaration type) throws java.io.IOException { - Type baseType = type.getBaseType().getKeYJavaType().getJavaType(); + Type baseType = type.getBaseType().getKeYJavaType().getJavaType(); assert baseType != null; - if (baseType instanceof ArrayDeclaration) { - printArrayDeclaration((ArrayDeclaration)baseType); - } else { - writeSymbol(1, 0, baseType.getFullName()); - } - write("[]"); + if (baseType instanceof ArrayDeclaration) { + printArrayDeclaration((ArrayDeclaration) baseType); + } else { + writeSymbol(1, 0, baseType.getFullName()); + } + write("[]"); } public void printTypeReference(TypeReference x) throws java.io.IOException { - printTypeReference(x, false); - } - - public void printTypeReference(TypeReference x, boolean fullTypeNames) throws java.io.IOException { - if (x.getKeYJavaType().getJavaType() instanceof ArrayDeclaration) { - printArrayDeclaration - ((ArrayDeclaration)x.getKeYJavaType().getJavaType()); - } else if (x.getProgramElementName() != null) { - printHeader(x); - if (x.getReferencePrefix() != null) { - write(x.getReferencePrefix() + "." + x.getProgramElementName());//XXX -// writeElement(x.getReferencePrefix()); -// writeToken(".", x); - } else { - if (fullTypeNames) { - write(x.getKeYJavaType().getFullName()); - } - else { - writeElement(x.getProgramElementName()); - } - } + printTypeReference(x, false); + } + + public void printTypeReference(TypeReference x, boolean fullTypeNames) + throws java.io.IOException { + if (x.getKeYJavaType().getJavaType() instanceof ArrayDeclaration) { + printArrayDeclaration((ArrayDeclaration) x.getKeYJavaType().getJavaType()); + } else if (x.getProgramElementName() != null) { + printHeader(x); + if (x.getReferencePrefix() != null) { + write(x.getReferencePrefix() + "." + x.getProgramElementName());// XXX + // writeElement(x.getReferencePrefix()); + // writeToken(".", x); + } else { + if (fullTypeNames) { + write(x.getKeYJavaType().getFullName()); + } else { + writeElement(x.getProgramElementName()); + } + } printFooter(x); } } @@ -1278,7 +1310,7 @@ public void printSchemaTypeReference(SchemaTypeReference x) throws java.io.IOExc writeToken(".", x); } - if (x.getProgramElementName() != null) { + if (x.getProgramElementName() != null) { writeElement(x.getProgramElementName()); } printFooter(x); @@ -1287,9 +1319,8 @@ public void printSchemaTypeReference(SchemaTypeReference x) throws java.io.IOExc public void printFieldReference(FieldReference x) throws java.io.IOException { printHeader(x); - if (x.getName()!=null && - "javax.realtime.MemoryArea::currentMemoryArea". - equals(x.getName())){ + if (x.getName() != null + && "javax.realtime.MemoryArea::currentMemoryArea".equals(x.getName())) { write(""); } else { if (x.getReferencePrefix() != null) { @@ -1328,13 +1359,12 @@ public void printThrows(Throws x) throws java.io.IOException { write("throws"); markKeywordEnd(); - writeCommaList(0, 0, 1, x.getExceptions()); + writeCommaList(0, 0, 1, x.getExceptions()); } printFooter(x); } - public void printArrayInitializer(ArrayInitializer x) - throws java.io.IOException { + public void printArrayInitializer(ArrayInitializer x) throws java.io.IOException { printHeader(x); writeToken("{", x); @@ -1342,7 +1372,7 @@ public void printArrayInitializer(ArrayInitializer x) writeCommaList(0, 0, 1, x.getArguments()); } if (x.getArguments() != null && x.getArguments().size() > 0 - && getRelativePosition(x).getLine() > 0) { + && getRelativePosition(x).getLine() > 0) { writeSymbol(1, 0, "}"); } else { @@ -1360,12 +1390,10 @@ public void printCompilationUnit(CompilationUnit x) throws java.io.IOException { } boolean hasImports = (x.getImports() != null) && (x.getImports().size() > 0); if (hasImports) { - writeLineList((x.getPackageSpecification() != null) ? 2 : 0, - 0, 0, x.getImports()); + writeLineList((x.getPackageSpecification() != null) ? 2 : 0, 0, 0, x.getImports()); } if (x.getDeclarations() != null) { - writeBlockList((hasImports || hasPackageSpec) ? 2 : 0, 0, 0, - x.getDeclarations()); + writeBlockList((hasImports || hasPackageSpec) ? 2 : 0, 0, 0, x.getDeclarations()); } printFooter(x); // we do this linefeed here to allow flushing of the pretty printer @@ -1373,15 +1401,14 @@ public void printCompilationUnit(CompilationUnit x) throws java.io.IOException { writeIndentation(1, 0); } - public void printClassDeclaration(ClassDeclaration x) - throws java.io.IOException { + public void printClassDeclaration(ClassDeclaration x) throws java.io.IOException { printHeader(x); int m = 0; if (x.getModifiers() != null) { m = x.getModifiers().size(); } if (m > 0) { - ImmutableArray mods = x.getModifiers(); + ImmutableArray mods = x.getModifiers(); writeKeywordList(mods); m = 1; } @@ -1401,30 +1428,28 @@ public void printClassDeclaration(ClassDeclaration x) write("{"); } if (x.getMembers() != null) { -// services.getJavaInfo().getKeYProgModelInfo().getConstructors(kjt) + // services.getJavaInfo().getKeYProgModelInfo().getConstructors(kjt) writeBlockList(2, 1, 0, x.getMembers()); } writeSymbol(1, (x.getMembers() != null) ? -1 : 0, "}"); printFooter(x); } - protected boolean containsDefaultConstructor(ImmutableArray members){ - for(int i=0; i members) { + for (int i = 0; i < members.size(); i++) { + MemberDeclaration md = members.get(i); + if (md instanceof IProgramMethod) { + md = ((IProgramMethod) md).getMethodDeclaration(); + } + if ((md instanceof ConstructorDeclaration) + && ((ConstructorDeclaration) md).getParameterDeclarationCount() == 0) { + return true; + } + } + return false; } - public void printInterfaceDeclaration(InterfaceDeclaration x) - throws java.io.IOException { + public void printInterfaceDeclaration(InterfaceDeclaration x) throws java.io.IOException { printHeader(x); int m = 0; @@ -1450,103 +1475,100 @@ public void printInterfaceDeclaration(InterfaceDeclaration x) printFooter(x); } - protected ImmutableArray removeFinal(ImmutableArray ma){ - LinkedList l = new LinkedList<>(); - for (Modifier mod : ma){ - if (!(mod instanceof Final)) { - l.add(mod); - } - } - return new ImmutableArray<>(l); - } - - protected ImmutableArray replacePrivateByPublic(ImmutableArray ma){ - LinkedList l = new LinkedList<>(); - boolean publicFound = false; - for(int i=0; i(l); - } - - public void printFieldDeclaration(FieldDeclaration x) - throws java.io.IOException { - printHeader(x); - int m = 0; - if (x.getModifiers() != null) { - ImmutableArray mods = x.getModifiers(); - m = mods.size(); - writeKeywordList(mods); - } - writeElement((m > 0) ? 1 : 0, x.getTypeReference()); - final ImmutableArray varSpecs = x - .getVariables(); - assert varSpecs != null : "Strange: a field declaration without a" - + " variable specification"; - writeCommaList(0, 0, 1, varSpecs); - write(";"); - printFooter(x); - - } - - public static String getTypeNameForAccessMethods(String typeName){ - typeName = typeName.replace('[','_'); - return typeName.replace('.','_'); + protected ImmutableArray removeFinal(ImmutableArray ma) { + LinkedList l = new LinkedList<>(); + for (Modifier mod : ma) { + if (!(mod instanceof Final)) { + l.add(mod); + } + } + return new ImmutableArray<>(l); + } + + protected ImmutableArray replacePrivateByPublic(ImmutableArray ma) { + LinkedList l = new LinkedList<>(); + boolean publicFound = false; + for (int i = 0; i < ma.size(); i++) { + if (ma.get(i) instanceof Private) { + l.add(new Public()); + publicFound = true; + } else if (ma.get(i) instanceof Public) { + l.add(ma.get(i)); + publicFound = true; + } else if (ma.get(i) instanceof Protected) { + l.add(new Public()); + publicFound = true; + } else { + l.add(ma.get(i)); + } + } + if (!publicFound) { + l.add(new Public()); + } + return new ImmutableArray<>(l); + } + + public void printFieldDeclaration(FieldDeclaration x) throws java.io.IOException { + printHeader(x); + int m = 0; + if (x.getModifiers() != null) { + ImmutableArray mods = x.getModifiers(); + m = mods.size(); + writeKeywordList(mods); + } + writeElement((m > 0) ? 1 : 0, x.getTypeReference()); + final ImmutableArray varSpecs = x.getVariables(); + assert varSpecs != null + : "Strange: a field declaration without a" + " variable specification"; + writeCommaList(0, 0, 1, varSpecs); + write(";"); + printFooter(x); + + } + + public static String getTypeNameForAccessMethods(String typeName) { + typeName = typeName.replace('[', '_'); + return typeName.replace('.', '_'); } public void printLocalVariableDeclaration(LocalVariableDeclaration x) - throws java.io.IOException { + throws java.io.IOException { printHeader(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); int m = 0; if (x.getModifiers() != null) { m = x.getModifiers().size(); writeKeywordList(x.getModifiers()); } writeElement((m > 0) ? 1 : 0, x.getTypeReference()); - write(" "); + write(" "); ImmutableArray varSpecs = x.getVariables(); - boolean wasNoSemicolons = noSemicolons; - boolean wasNoLinefeed = noLinefeed; - noSemicolons = true; - noLinefeed = true; + boolean wasNoSemicolons = noSemicolons; + boolean wasNoLinefeed = noLinefeed; + noSemicolons = true; + noLinefeed = true; if (varSpecs != null) { writeCommaList(0, 0, 1, varSpecs); } // !!!!!!!!!! HAS TO BE CHANGED - // if (!(x.getStatementContainer() instanceof LoopStatement)) { + // if (!(x.getStatementContainer() instanceof LoopStatement)) { write(";"); - // } + // } // Mark statement end ... - markEnd(0,x); + markEnd(0, x); noSemicolons = wasNoSemicolons; - noLinefeed = wasNoLinefeed; + noLinefeed = wasNoLinefeed; printFooter(x); } - public void printVariableDeclaration(VariableDeclaration x) - throws java.io.IOException { + public void printVariableDeclaration(VariableDeclaration x) throws java.io.IOException { printHeader(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); int m = 0; if (x.getModifiers() != null) { @@ -1554,67 +1576,64 @@ public void printVariableDeclaration(VariableDeclaration x) writeKeywordList(x.getModifiers()); } writeElement((m > 0) ? 1 : 0, x.getTypeReference()); - write(" "); + write(" "); ImmutableArray varSpecs = x.getVariables(); if (varSpecs != null) { writeCommaList(0, 0, 1, varSpecs); } - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } - public void printMethodDeclaration(MethodDeclaration x) - throws java.io.IOException { - printHeader(x); - Comment[] c = x.getComments(); - int m = c.length; + public void printMethodDeclaration(MethodDeclaration x) throws java.io.IOException { + printHeader(x); + Comment[] c = x.getComments(); + int m = c.length; for (Comment aC : c) { printComment(aC); } - if (x.getModifiers() != null) { - ImmutableArray mods = x.getModifiers(); - m += mods.size(); - writeKeywordList(mods); - } - if (x.getTypeReference() != null) { - if (m > 0) { - writeElement(1, x.getTypeReference()); - } else { - writeElement(x.getTypeReference()); - } - writeElement(1, x.getProgramElementName()); - } else if (x.getTypeReference() == null - && !(x instanceof ConstructorDeclaration)) { - write(" void "); - writeElement(1, x.getProgramElementName()); - } else { - if (m > 0) { - writeElement(1, x.getProgramElementName()); - } else { - writeElement(x.getProgramElementName()); - } - } - write(" ("); - if (x.getParameters() != null) { - writeCommaList(1, x.getParameters()); - } - write(")"); - if (x.getThrown() != null) { - writeElement(1, x.getThrown()); - } - if (x.getBody() != null) { - writeElement(1, x.getBody()); - } else { - write(";"); - } - printFooter(x); - } - - public void printClassInitializer(ClassInitializer x) - throws java.io.IOException { + if (x.getModifiers() != null) { + ImmutableArray mods = x.getModifiers(); + m += mods.size(); + writeKeywordList(mods); + } + if (x.getTypeReference() != null) { + if (m > 0) { + writeElement(1, x.getTypeReference()); + } else { + writeElement(x.getTypeReference()); + } + writeElement(1, x.getProgramElementName()); + } else if (x.getTypeReference() == null && !(x instanceof ConstructorDeclaration)) { + write(" void "); + writeElement(1, x.getProgramElementName()); + } else { + if (m > 0) { + writeElement(1, x.getProgramElementName()); + } else { + writeElement(x.getProgramElementName()); + } + } + write(" ("); + if (x.getParameters() != null) { + writeCommaList(1, x.getParameters()); + } + write(")"); + if (x.getThrown() != null) { + writeElement(1, x.getThrown()); + } + if (x.getBody() != null) { + writeElement(1, x.getBody()); + } else { + write(";"); + } + printFooter(x); + } + + public void printClassInitializer(ClassInitializer x) throws java.io.IOException { printHeader(x); int m = 0; @@ -1631,52 +1650,52 @@ public void printClassInitializer(ClassInitializer x) public void printStatementBlock(StatementBlock x) throws java.io.IOException { printHeader(x); - if (!(x.getBody() != null && x.getBody().size() > 0)) { - // We have an empty statement block ... + if (!(x.getBody() != null && x.getBody().size() > 0)) { + // We have an empty statement block ... - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); - } + } - // Hack to insert space after "if (cond)", etc. but not - // at beginning of diamond. - if (column!=0) { - write(" "); - } - write("{"); - if (x.getBody() != null && x.getBody().size() > 0) { - writeLineList(1, +1, 0, x.getBody()); - writeSymbol(1, -1, "}"); - } else { - write("}"); + // Hack to insert space after "if (cond)", etc. but not + // at beginning of diamond. + if (column != 0) { + write(" "); + } + write("{"); + if (x.getBody() != null && x.getBody().size() > 0) { + writeLineList(1, +1, 0, x.getBody()); + writeSymbol(1, -1, "}"); + } else { + write("}"); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); - } - printFooter(x); + } + printFooter(x); } public void printBreak(Break x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); - markKeywordStart(); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); write("break"); markKeywordEnd(); write(" "); - noLinefeed=true; + noLinefeed = true; if (x.getProgramElementName() != null) { writeElement(1, x.getProgramElementName()); } write(";"); - noLinefeed=false; + noLinefeed = false; - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } @@ -1685,21 +1704,21 @@ public void printContinue(Continue x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); - markKeywordStart(); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); write("continue"); markKeywordEnd(); write(" "); - noLinefeed=true; + noLinefeed = true; if (x.getProgramElementName() != null) { writeElement(1, x.getProgramElementName()); } write(";"); - noLinefeed=false; + noLinefeed = false; - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } @@ -1708,9 +1727,9 @@ public void printReturn(Return x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); - markKeywordStart(); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); write("return"); markKeywordEnd(); write(" "); @@ -1721,8 +1740,8 @@ public void printReturn(Return x) throws java.io.IOException { } write(";"); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } @@ -1731,8 +1750,8 @@ public void printThrow(Throw x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); write("throw "); if (x.getExpression() != null) { @@ -1742,70 +1761,69 @@ public void printThrow(Throw x) throws java.io.IOException { } write(";"); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } public void printDo(Do x) throws java.io.IOException { - printDo(x, true); + printDo(x, true); } public void printDo(Do x, boolean includeBody) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); - markKeywordStart(); - write("do"); - markKeywordEnd(); - if (includeBody) { - if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { - write(";"); - //w.writeElement(1, body); - } else { - if (x.getBody() instanceof StatementBlock) { - writeElement(1, 0, x.getBody()); - } else { - writeElement(1, +1, 0, x.getBody()); - changeLevel(-1); - } - } - } - else { - write(" ... "); - } - writeSymbol(1, 0, "while"); - noLinefeed=true; - noSemicolons=true; - write(" ("); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); + write("do"); + markKeywordEnd(); + if (includeBody) { + if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { + write(";"); + // w.writeElement(1, body); + } else { + if (x.getBody() instanceof StatementBlock) { + writeElement(1, 0, x.getBody()); + } else { + writeElement(1, +1, 0, x.getBody()); + changeLevel(-1); + } + } + } else { + write(" ... "); + } + writeSymbol(1, 0, "while"); + noLinefeed = true; + noSemicolons = true; + write(" ("); if (x.getGuardExpression() != null) { - write(" "); + write(" "); writeElement(x.getGuardExpression()); - write(" "); + write(" "); } - noLinefeed=false; - noSemicolons=false; + noLinefeed = false; + noSemicolons = false; write(");"); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } private static void removeChar(StringBuffer sb, char c) { - for (int i=0; i initializers = x.getInitializers(); - if(initializers != null) { + if (initializers != null) { LoopInitializer loopInit = initializers.get(0); writeElement(1, loopInit); } write(" : "); - if(x.getGuard() != null) + if (x.getGuard() != null) writeElement(1, x.getGuardExpression()); write(")"); @@ -1837,16 +1855,16 @@ public void printEnhancedFor(EnhancedFor x, boolean includeBody) throws IOExcept noSemicolons = false; if (includeBody) { - if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { - write(";"); - } else { - if (x.getBody() instanceof StatementBlock) { - writeElement(1, 0, x.getBody()); - } else { - writeElement(1, +1, 0, x.getBody()); - changeLevel(-1); - } - } + if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { + write(";"); + } else { + if (x.getBody() instanceof StatementBlock) { + writeElement(1, 0, x.getBody()); + } else { + writeElement(1, +1, 0, x.getBody()); + changeLevel(-1); + } + } } // Mark statement end ... @@ -1856,7 +1874,7 @@ public void printEnhancedFor(EnhancedFor x, boolean includeBody) throws IOExcept } public void printFor(For x) throws java.io.IOException { - printFor(x, true); + printFor(x, true); } public void printFor(For x, boolean includeBody) throws java.io.IOException { @@ -1877,8 +1895,8 @@ public void printFor(For x, boolean includeBody) throws java.io.IOException { // there is no "getLoopInit" method // so get the first child of the for loop ILoopInit init = x.getILoopInit(); - if(init != null) { - if(init instanceof ProgramSV) + if (init != null) { + if (init instanceof ProgramSV) writeElement(init); else writeCommaList(x.getInitializers()); @@ -1896,8 +1914,8 @@ public void printFor(For x, boolean includeBody) throws java.io.IOException { noSemicolons = true; IForUpdates upd = x.getIForUpdates(); - if(upd != null) { - if(upd instanceof ProgramSV) + if (upd != null) { + if (upd instanceof ProgramSV) writeElement(1, upd); else writeCommaList(0, 0, 1, x.getUpdates()); @@ -1909,16 +1927,16 @@ public void printFor(For x, boolean includeBody) throws java.io.IOException { noSemicolons = false; if (includeBody) { - if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { - write(";"); - } else { - if (x.getBody() instanceof StatementBlock) { - writeElement(1, 0, x.getBody()); - } else { - writeElement(1, +1, 0, x.getBody()); - changeLevel(-1); - } - } + if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { + write(";"); + } else { + if (x.getBody() instanceof StatementBlock) { + writeElement(1, 0, x.getBody()); + } else { + writeElement(1, +1, 0, x.getBody()); + changeLevel(-1); + } + } } // Mark statement end ... @@ -1928,106 +1946,107 @@ public void printFor(For x, boolean includeBody) throws java.io.IOException { } public void printWhile(While x) throws java.io.IOException { - printWhile(x, true); + printWhile(x, true); } public void printWhile(While x, boolean includeBody) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - output(); - noLinefeed=true; - noSemicolons=true; + output(); + noLinefeed = true; + noSemicolons = true; - // Mark statement start ... - markStart(0,x); - markKeywordStart(); - write("while"); - markKeywordEnd(); - write(" ("); - write(" "); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); + write("while"); + markKeywordEnd(); + write(" ("); + write(" "); if (x.getGuardExpression() != null) { writeElement(x.getGuardExpression()); } - write(" )"); output(); - noLinefeed=false; - noSemicolons=false; + write(" )"); + output(); + noLinefeed = false; + noSemicolons = false; - if (includeBody) { - if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { - write(";"); - } else { - if (x.getBody() instanceof StatementBlock) { - writeElement(0, 0, x.getBody()); - } else { - writeElement(1, +1, 0, x.getBody()); - changeLevel(-1); - } + if (includeBody) { + if (x.getBody() == null || x.getBody() instanceof EmptyStatement) { + write(";"); + } else { + if (x.getBody() instanceof StatementBlock) { + writeElement(0, 0, x.getBody()); + } else { + writeElement(1, +1, 0, x.getBody()); + changeLevel(-1); + } + } } - } - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } public void printIf(If x) throws java.io.IOException { - printIf(x, true); + printIf(x, true); } public void printIf(If x, boolean includeBranches) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - output(); + output(); - noLinefeed = true; - noSemicolons = true; + noLinefeed = true; + noSemicolons = true; - // Mark statement start ... - markStart(0,x); - markKeywordStart(); - write("if"); - markKeywordEnd(); - write(" ("); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); + write("if"); + markKeywordEnd(); + write(" ("); if (x.getExpression() != null) { - writeElement(1, x.getExpression()); + writeElement(1, x.getExpression()); } - write(")"); + write(")"); noLinefeed = false; noSemicolons = false; if (includeBranches) { - if (x.getThen() != null) { - if (x.getThen().getBody() instanceof StatementBlock) { - writeElement(1, 0, x.getThen()); - } else { - writeElement(1, +1, 0, x.getThen()); - changeLevel(-1); - } - } - if (x.getElse() != null) { - writeElement(1, 0, x.getElse()); - } + if (x.getThen() != null) { + if (x.getThen().getBody() instanceof StatementBlock) { + writeElement(1, 0, x.getThen()); + } else { + writeElement(1, +1, 0, x.getThen()); + changeLevel(-1); + } + } + if (x.getElse() != null) { + writeElement(1, 0, x.getElse()); + } } - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } public void printSwitch(Switch x) throws java.io.IOException { - printSwitch(x, true); + printSwitch(x, true); } public void printSwitch(Switch x, boolean includeBranches) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); - markKeywordStart(); + // Mark statement start ... + markStart(0, x); + markKeywordStart(); write("switch"); markKeywordEnd(); write(" ("); @@ -2038,15 +2057,15 @@ public void printSwitch(Switch x, boolean includeBranches) throws java.io.IOExce } write(")"); if (includeBranches) { - write(" {"); - if (x.getBranchList() != null) { - writeLineList(1, 0, 0, x.getBranchList()); - } - writeSymbol(1, 0, "}"); + write(" {"); + if (x.getBranchList() != null) { + writeLineList(1, 0, 0, x.getBranchList()); + } + writeSymbol(1, 0, "}"); } - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } @@ -2055,26 +2074,25 @@ public void printTry(Try x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // // Mark statement start ... - // markStart(0,x); + // // Mark statement start ... + // markStart(0,x); markKeywordStart(); write("try"); markKeywordEnd(); if (x.getBody() != null) { - writeElement(0, 0, x.getBody()); + writeElement(0, 0, x.getBody()); } if (x.getBranchList() != null) { - writeLineList(1, 0, 0, x.getBranchList()); + writeLineList(1, 0, 0, x.getBranchList()); } - // // Mark statement end ... - // markEnd(0,x); + // // Mark statement end ... + // markEnd(0,x); printFooter(x); } - public void printLabeledStatement(LabeledStatement x) - throws java.io.IOException { + public void printLabeledStatement(LabeledStatement x) throws java.io.IOException { printHeader(x); @@ -2085,98 +2103,94 @@ public void printLabeledStatement(LabeledStatement x) } if (x.getBody() != null) { - writeElement(1, 0, x.getBody()); + writeElement(1, 0, x.getBody()); } printFooter(x); } - public void printMethodFrame(MethodFrame x) - throws java.io.IOException { + public void printMethodFrame(MethodFrame x) throws java.io.IOException { printHeader(x); - noLinefeed = false; - markKeywordStart(); - write("method-frame"); - markKeywordEnd(); - write("("); - IProgramVariable pvar = x.getProgramVariable(); - if (pvar != null) { - write("result->"); - writeElement(pvar); + noLinefeed = false; + markKeywordStart(); + write("method-frame"); + markKeywordEnd(); + write("("); + IProgramVariable pvar = x.getProgramVariable(); + if (pvar != null) { + write("result->"); + writeElement(pvar); write(", "); - } + } - if (x.getExecutionContext() instanceof ExecutionContext) { - writeElement(x.getExecutionContext()); - } else { - printSchemaVariable((SchemaVariable)x.getExecutionContext()); - } + if (x.getExecutionContext() instanceof ExecutionContext) { + writeElement(x.getExecutionContext()); + } else { + printSchemaVariable((SchemaVariable) x.getExecutionContext()); + } - write(")"); - writeToken(":", x); + write(")"); + writeToken(":", x); - noLinefeed = false; - noSemicolons = false; + noLinefeed = false; + noSemicolons = false; if (x.getBody() != null) { - writeElement(0, 0, x.getBody()); + writeElement(0, 0, x.getBody()); } printFooter(x); } - public void printCatchAllStatement(CatchAllStatement x) - throws java.io.IOException { + public void printCatchAllStatement(CatchAllStatement x) throws java.io.IOException { printHeader(x); - markStart(0, x); - write("#catchAll"); - write("("); - writeElement(x.getParam()); - write(")"); - writeElement(1, x.getBody()); - markEnd(0, x); + markStart(0, x); + write("#catchAll"); + write("("); + writeElement(x.getParam()); + write(")"); + writeElement(1, x.getBody()); + markEnd(0, x); printFooter(x); } - public void printMethodBodyStatement(MethodBodyStatement x) - throws java.io.IOException { + public void printMethodBodyStatement(MethodBodyStatement x) throws java.io.IOException { - boolean wasNoLinefeed = noLinefeed; - noLinefeed = false; + boolean wasNoLinefeed = noLinefeed; + noLinefeed = false; - printHeader(x); - writeInternalIndentation(x); - markStart(0, x); + printHeader(x); + writeInternalIndentation(x); + markStart(0, x); - IProgramVariable pvar = x.getResultVariable(); - if (pvar != null) { - writeElement(pvar); - write("="); - } + IProgramVariable pvar = x.getResultVariable(); + if (pvar != null) { + writeElement(pvar); + write("="); + } - printMethodReference(x.getMethodReference(), false); - // CHG: - write("@"); - final TypeReference tr = x.getBodySourceAsTypeReference(); - if (tr instanceof SchemaTypeReference) { - printSchemaTypeReference((SchemaTypeReference) tr); - } else if (tr instanceof SchemaVariable) { - printSchemaVariable((SchemaVariable) tr); - } else { - printTypeReference(tr); - } - write(";"); - markEnd(0, x); - printFooter(x); + printMethodReference(x.getMethodReference(), false); + // CHG: + write("@"); + final TypeReference tr = x.getBodySourceAsTypeReference(); + if (tr instanceof SchemaTypeReference) { + printSchemaTypeReference((SchemaTypeReference) tr); + } else if (tr instanceof SchemaVariable) { + printSchemaVariable((SchemaVariable) tr); + } else { + printTypeReference(tr); + } + write(";"); + markEnd(0, x); + printFooter(x); - noLinefeed = wasNoLinefeed; + noLinefeed = wasNoLinefeed; } - public void printSynchronizedBlock(SynchronizedBlock x) - throws java.io.IOException { + public void printSynchronizedBlock(SynchronizedBlock x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); @@ -2193,11 +2207,10 @@ public void printSynchronizedBlock(SynchronizedBlock x) } - public void printLoopScopeBlock(LoopScopeBlock x) - throws java.io.IOException { + public void printLoopScopeBlock(LoopScopeBlock x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); -// write("\u21BB"); // UTF-8 loop scope sign + // write("\u21BB"); // UTF-8 loop scope sign write("loop-scope("); if (x.getIndexPV() != null) { writeElement(x.getIndexPV()); @@ -2206,7 +2219,7 @@ public void printLoopScopeBlock(LoopScopeBlock x) if (x.getBody() != null) { writeElement(1, x.getBody()); } -// write("\u21BA"); // UTF-8 loop scope end sign + // write("\u21BA"); // UTF-8 loop scope end sign printFooter(x); } @@ -2244,8 +2257,7 @@ public void printImplements(Implements x) throws java.io.IOException { printFooter(x); } - public void printVariableSpecification(VariableSpecification x) - throws java.io.IOException { + public void printVariableSpecification(VariableSpecification x) throws java.io.IOException { printHeader(x); @@ -2253,12 +2265,12 @@ public void printVariableSpecification(VariableSpecification x) markStart(0, x); x.getProgramVariable().prettyPrint(this); - //writeElement(x.getProgramElementName()); + // writeElement(x.getProgramElementName()); for (int i = 0; i < x.getDimensions(); i += 1) { write("[]"); } if (x.getInitializer() != null) { - // w.writeIndentation(getInternalLinefeeds(), + // w.writeIndentation(getInternalLinefeeds(), // getInternalIndentation()); write(" = "); writeElement(0, 0, 1, x.getInitializer()); @@ -2272,137 +2284,132 @@ public void printVariableSpecification(VariableSpecification x) public void printBinaryAnd(BinaryAnd x) throws java.io.IOException { printHeader(x); - printOperator(x, "&"); + printOperator(x, "&"); printFooter(x); } - public void printBinaryAndAssignment(BinaryAndAssignment x) - throws java.io.IOException { + public void printBinaryAndAssignment(BinaryAndAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "&="); + printOperator(x, "&="); printFooter(x); } - public void printBinaryOrAssignment(BinaryOrAssignment x) - throws java.io.IOException { + public void printBinaryOrAssignment(BinaryOrAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "|="); + printOperator(x, "|="); printFooter(x); } - public void printBinaryXOrAssignment(BinaryXOrAssignment x) - throws java.io.IOException { + public void printBinaryXOrAssignment(BinaryXOrAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "^="); + printOperator(x, "^="); printFooter(x); } public void printCopyAssignment(CopyAssignment x) throws java.io.IOException { printHeader(x); - //output(); - // noLinefeed=true; - printOperator(x, "="); - // noLinefeed=false; - //write("\n"); + // output(); + // noLinefeed=true; + printOperator(x, "="); + // noLinefeed=false; + // write("\n"); printFooter(x); } public void printDivideAssignment(DivideAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "/="); + printOperator(x, "/="); printFooter(x); } public void printMinusAssignment(MinusAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "-="); + printOperator(x, "-="); printFooter(x); } public void printModuloAssignment(ModuloAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "%="); + printOperator(x, "%="); printFooter(x); } public void printPlusAssignment(PlusAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "+="); + printOperator(x, "+="); printFooter(x); } public void printPostDecrement(PostDecrement x) throws java.io.IOException { printHeader(x); - printOperator(x, "--"); + printOperator(x, "--"); printFooter(x); } public void printPostIncrement(PostIncrement x) throws java.io.IOException { printHeader(x); - printOperator(x, "++"); + printOperator(x, "++"); printFooter(x); } public void printPreDecrement(PreDecrement x) throws java.io.IOException { printHeader(x); - printOperator(x, "--"); + printOperator(x, "--"); printFooter(x); } public void printPreIncrement(PreIncrement x) throws java.io.IOException { printHeader(x); - printOperator(x, "++"); + printOperator(x, "++"); printFooter(x); } - public void printShiftLeftAssignment(ShiftLeftAssignment x) - throws java.io.IOException { + public void printShiftLeftAssignment(ShiftLeftAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "<<="); + printOperator(x, "<<="); printFooter(x); } - public void printShiftRightAssignment(ShiftRightAssignment x) - throws java.io.IOException { + public void printShiftRightAssignment(ShiftRightAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, ">>="); + printOperator(x, ">>="); printFooter(x); } public void printTimesAssignment(TimesAssignment x) throws java.io.IOException { printHeader(x); - printOperator(x, "*="); + printOperator(x, "*="); printFooter(x); } public void printUnsignedShiftRightAssignment(UnsignedShiftRightAssignment x) - throws java.io.IOException { + throws java.io.IOException { printHeader(x); - printOperator(x, ">>>="); + printOperator(x, ">>>="); printFooter(x); } public void printBinaryNot(BinaryNot x) throws java.io.IOException { printHeader(x); - printOperator(x, "~"); + printOperator(x, "~"); printFooter(x); } public void printBinaryOr(BinaryOr x) throws java.io.IOException { printHeader(x); - printOperator(x, "|"); + printOperator(x, "|"); printFooter(x); } public void printBinaryXOr(BinaryXOr x) throws java.io.IOException { printHeader(x); - printOperator(x, "^"); + printOperator(x, "^"); printFooter(x); } @@ -2428,43 +2435,43 @@ public void printConditional(Conditional x) throws java.io.IOException { public void printDivide(Divide x) throws java.io.IOException { printHeader(x); - printOperator(x, "/"); + printOperator(x, "/"); printFooter(x); } public void printEquals(Equals x) throws java.io.IOException { printHeader(x); - printOperator(x, "=="); + printOperator(x, "=="); printFooter(x); } public void printGreaterOrEquals(GreaterOrEquals x) throws java.io.IOException { printHeader(x); - printOperator(x, ">="); + printOperator(x, ">="); printFooter(x); } public void printGreaterThan(GreaterThan x) throws java.io.IOException { printHeader(x); - printOperator(x, ">"); + printOperator(x, ">"); printFooter(x); } public void printLessOrEquals(LessOrEquals x) throws java.io.IOException { printHeader(x); - printOperator(x, "<="); + printOperator(x, "<="); printFooter(x); } public void printLessThan(LessThan x) throws java.io.IOException { printHeader(x); - printOperator(x, "<"); + printOperator(x, "<"); printFooter(x); } public void printNotEquals(NotEquals x) throws java.io.IOException { printHeader(x); - printOperator(x, "!="); + printOperator(x, "!="); printFooter(x); } @@ -2544,8 +2551,8 @@ public void printExactInstanceof(ExactInstanceof x) throws java.io.IOException { public void printNew(New x) throws java.io.IOException { printHeader(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); boolean addParentheses = x.isToBeParenthesized(); if (addParentheses) { @@ -2559,7 +2566,7 @@ public void printNew(New x) throws java.io.IOException { write("new "); writeElement(1, x.getTypeReference()); - write(" ("); + write(" ("); if (x.getArguments() != null) { writeCommaList(x.getArguments()); } @@ -2570,13 +2577,13 @@ public void printNew(New x) throws java.io.IOException { if (addParentheses) { write(")"); } - // !!!!!!!!!! HAS TO BE CHANGED -// if (x.getStatementContainer() != null && fileWriterMode) { -// write(";"); -// } + // !!!!!!!!!! HAS TO BE CHANGED + // if (x.getStatementContainer() != null && fileWriterMode) { + // write(";"); + // } - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); printFooter(x); } @@ -2603,75 +2610,74 @@ public void printTypeCast(TypeCast x) throws java.io.IOException { public void printLogicalAnd(LogicalAnd x) throws java.io.IOException { printHeader(x); - printOperator(x, "&&"); + printOperator(x, "&&"); printFooter(x); } public void printLogicalNot(LogicalNot x) throws java.io.IOException { printHeader(x); - printOperator(x, "!"); + printOperator(x, "!"); printFooter(x); } public void printLogicalOr(LogicalOr x) throws java.io.IOException { printHeader(x); - printOperator(x, "||"); + printOperator(x, "||"); printFooter(x); } public void printMinus(Minus x) throws java.io.IOException { printHeader(x); - printOperator(x, "-"); + printOperator(x, "-"); printFooter(x); } public void printModulo(Modulo x) throws java.io.IOException { printHeader(x); - printOperator(x, "%"); + printOperator(x, "%"); printFooter(x); } public void printNegative(Negative x) throws java.io.IOException { printHeader(x); - printOperator(x, "-"); + printOperator(x, "-"); printFooter(x); } public void printPlus(Plus x) throws java.io.IOException { printHeader(x); - printOperator(x, "+"); + printOperator(x, "+"); printFooter(x); } public void printPositive(Positive x) throws java.io.IOException { printHeader(x); - printOperator(x, "+"); + printOperator(x, "+"); printFooter(x); } public void printShiftLeft(ShiftLeft x) throws java.io.IOException { printHeader(x); - printOperator(x, "<<"); + printOperator(x, "<<"); printFooter(x); } public void printShiftRight(ShiftRight x) throws java.io.IOException { printHeader(x); - printOperator(x, ">>"); + printOperator(x, ">>"); printFooter(x); } public void printTimes(Times x) throws java.io.IOException { printHeader(x); - printOperator(x, "*"); + printOperator(x, "*"); printFooter(x); } - public void printUnsignedShiftRight(UnsignedShiftRight x) - throws java.io.IOException { + public void printUnsignedShiftRight(UnsignedShiftRight x) throws java.io.IOException { printHeader(x); - printOperator(x, ">>>"); + printOperator(x, ">>>"); printFooter(x); } @@ -2691,8 +2697,7 @@ public void printArrayReference(ArrayReference x) throws java.io.IOException { printFooter(x); } - public void printMetaClassReference(MetaClassReference x) - throws java.io.IOException { + public void printMetaClassReference(MetaClassReference x) throws java.io.IOException { printHeader(x); if (x.getTypeReference() != null) { @@ -2703,59 +2708,57 @@ public void printMetaClassReference(MetaClassReference x) printFooter(x); } - public void printMethodReference(MethodReference x) - throws java.io.IOException { + public void printMethodReference(MethodReference x) throws java.io.IOException { printMethodReference(x, !noSemicolons); } - protected void printMethodReference(MethodReference x, - boolean withSemicolon) - throws java.io.IOException { - printHeader(x); - // Mark statement start ... - markStart(0,x); + protected void printMethodReference(MethodReference x, boolean withSemicolon) + throws java.io.IOException { + printHeader(x); + // Mark statement start ... + markStart(0, x); if (x.getReferencePrefix() != null) { writeElement(x.getReferencePrefix()); write("."); } if (x.getProgramElementName() != null) { - x.getMethodName().prettyPrint(this); - //writeElement(x.getProgramElementName()); + x.getMethodName().prettyPrint(this); + // writeElement(x.getProgramElementName()); } - write("("); - boolean wasNoSemicolons = noSemicolons; - boolean wasNoLinefeed = noLinefeed; - noLinefeed = true; - noSemicolons = true; + write("("); + boolean wasNoSemicolons = noSemicolons; + boolean wasNoLinefeed = noLinefeed; + noLinefeed = true; + noSemicolons = true; if (x.getArguments() != null) { writeCommaList(x.getArguments()); } - write(")"); - if (withSemicolon) { + write(")"); + if (withSemicolon) { write(";"); } - noLinefeed = wasNoLinefeed; - noSemicolons = wasNoSemicolons; - output(); + noLinefeed = wasNoLinefeed; + noSemicolons = wasNoSemicolons; + output(); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); } public void printMethod(IProgramMethod x) throws java.io.IOException { - // printHeader(x); - write(x.name().toString()); - // printFooter(x); + // printHeader(x); + write(x.name().toString()); + // printFooter(x); } public void printFullMethodSignature(IProgramMethod x) throws java.io.IOException { - printHeader(x); - writeFullMethodSignature(x); - printFooter(x); + printHeader(x); + writeFullMethodSignature(x); + printFooter(x); } protected void writeFullMethodSignature(IProgramMethod x) throws java.io.IOException { @@ -2765,99 +2768,95 @@ protected void writeFullMethodSignature(IProgramMethod x) throws java.io.IOExcep for (ParameterDeclaration pd : x.getParameters()) { if (afterFirst) { write(", "); - } - else { + } else { afterFirst = true; } boolean originalNoLinefeed = noLinefeed; try { - noLinefeed = true; - printTypeReference(pd.getTypeReference(), true); - } - finally { - noLinefeed = originalNoLinefeed; + noLinefeed = true; + printTypeReference(pd.getTypeReference(), true); + } finally { + noLinefeed = originalNoLinefeed; } } write(")"); } - public void printExecutionContext(ExecutionContext x) - throws java.io.IOException { - write("source="); - writeFullMethodSignature(x.getMethodContext()); - write("@"); - writeElement(x.getTypeReference()); - if (x.getRuntimeInstance() != null) { - write(",this="); - writeElement(x.getRuntimeInstance()); - } + public void printExecutionContext(ExecutionContext x) throws java.io.IOException { + write("source="); + writeFullMethodSignature(x.getMethodContext()); + write("@"); + writeElement(x.getTypeReference()); + if (x.getRuntimeInstance() != null) { + write(",this="); + writeElement(x.getRuntimeInstance()); + } } public void printSuperConstructorReference(SuperConstructorReference x) - throws java.io.IOException { + throws java.io.IOException { printHeader(x); - markStart(0,x); + markStart(0, x); if (x.getReferencePrefix() != null) { writeElement(x.getReferencePrefix()); write("."); } - writeToken("super (", x); + writeToken("super (", x); if (x.getArguments() != null) { writeCommaList(0, 0, 0, x.getArguments()); } write(");"); - markEnd(0,x); + markEnd(0, x); printFooter(x); } public void printThisConstructorReference(ThisConstructorReference x) - throws java.io.IOException { + throws java.io.IOException { printHeader(x); - markStart(0,x); + markStart(0, x); writeInternalIndentation(x); - markKeywordStart(); - write("this"); - markKeywordEnd(); - write(" ("); + markKeywordStart(); + write("this"); + markKeywordEnd(); + write(" ("); if (x.getArguments() != null) { writeCommaList(x.getArguments()); } write(");"); - markEnd(0,x); + markEnd(0, x); printFooter(x); } public void printSuperReference(SuperReference x) throws java.io.IOException { printHeader(x); - markStart(0,x); + markStart(0, x); if (x.getReferencePrefix() != null) { writeElement(x.getReferencePrefix()); writeToken(".super", x); } else { writeToken("super", x); } - markEnd(0,x); + markEnd(0, x); printFooter(x); } public void printThisReference(ThisReference x) throws java.io.IOException { printHeader(x); - markStart(0,x); + markStart(0, x); if (x.getReferencePrefix() != null) { writeElement(x.getReferencePrefix()); writeToken(".this", x); } else { writeToken("this", x); } - markEnd(0,x); + markEnd(0, x); printFooter(x); } - public void printArrayLengthReference(ArrayLengthReference x) - throws java.io.IOException { + public void printArrayLengthReference(ArrayLengthReference x) throws java.io.IOException { printHeader(x); if (x.getReferencePrefix() != null) { writeElement(x.getReferencePrefix()); @@ -2882,13 +2881,13 @@ public void printElse(Else x) throws java.io.IOException { write("else "); markKeywordEnd(); if (x.getBody() != null) { - if (x.getBody() instanceof StatementBlock) { - writeElement(1, 0, x.getBody()); - } else { - writeElement(1, +1, 0, x.getBody()); - changeLevel(-1); - } - } + if (x.getBody() instanceof StatementBlock) { + writeElement(1, 0, x.getBody()); + } else { + writeElement(1, +1, 0, x.getBody()); + changeLevel(-1); + } + } printFooter(x); } @@ -2916,16 +2915,16 @@ public void printCase(Case x) throws java.io.IOException { public void printCatch(Catch x) throws java.io.IOException { printHeader(x); - writeToken("catch", x); - write(" ("); + writeToken("catch", x); + write(" ("); if (x.getParameterDeclaration() != null) { - noLinefeed=true; + noLinefeed = true; noSemicolons = true; writeElement(x.getParameterDeclaration()); } write(")"); noSemicolons = false; - noLinefeed=false; + noLinefeed = false; if (x.getBody() != null) { writeElement(1, x.getBody()); } @@ -2946,10 +2945,10 @@ public void printDefault(Default x) throws java.io.IOException { public void printFinally(Finally x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - noLinefeed = true; - output(); - noLinefeed = false; - markKeywordStart(); + noLinefeed = true; + output(); + noLinefeed = false; + markKeywordStart(); write("finally"); markKeywordEnd(); if (x.getBody() != null) { @@ -2967,33 +2966,34 @@ public void printModifier(Modifier x) throws java.io.IOException { @SuppressWarnings("unchecked") public void printSchemaVariable(SchemaVariable x) throws java.io.IOException { - if(x instanceof ProgramSV){ - if (!noSemicolons) { - markStart(0,x); - } - Object o = instantiations.getInstantiation(x); - if (o == null) { - printHeader((ProgramSV)x); - writeInternalIndentation((ProgramSV)x); - write(x.name().toString()); - printFooter((ProgramSV)x); - } else { - //logger.debug(o.toString() + " " + o.getClass().getName()); - //Debug.assertTrue(o instanceof ProgramElement); - if (o instanceof ProgramElement) { - ((ProgramElement)o).prettyPrint(this); - } else if (o instanceof ImmutableArray/**/) { - writeBlockList((ImmutableArray)o); - } else { - LOGGER.warn("No PrettyPrinting available for {}", o.getClass().getName()); - } - } - if (!noSemicolons) { - markEnd(0,x); - } - }else{ - Debug.fail("That cannot happen! Don't know how to pretty print non program SV in programs."); - } + if (x instanceof ProgramSV) { + if (!noSemicolons) { + markStart(0, x); + } + Object o = instantiations.getInstantiation(x); + if (o == null) { + printHeader((ProgramSV) x); + writeInternalIndentation((ProgramSV) x); + write(x.name().toString()); + printFooter((ProgramSV) x); + } else { + // logger.debug(o.toString() + " " + o.getClass().getName()); + // Debug.assertTrue(o instanceof ProgramElement); + if (o instanceof ProgramElement) { + ((ProgramElement) o).prettyPrint(this); + } else if (o instanceof ImmutableArray/* */) { + writeBlockList((ImmutableArray) o); + } else { + LOGGER.warn("No PrettyPrinting available for {}", o.getClass().getName()); + } + } + if (!noSemicolons) { + markEnd(0, x); + } + } else { + Debug.fail( + "That cannot happen! Don't know how to pretty print non program SV in programs."); + } } @@ -3002,57 +3002,55 @@ public void printEmptyStatement(EmptyStatement x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); write(";"); - // Mark statement end ... - markEnd(0,x); + // Mark statement end ... + markEnd(0, x); - printFooter(x); + printFooter(x); } public void printComment(Comment x) throws java.io.IOException { - write("/*" + x.getText() + "*/"); + write("/*" + x.getText() + "*/"); } - public void printParenthesizedExpression(ParenthesizedExpression x) - throws IOException { + public void printParenthesizedExpression(ParenthesizedExpression x) throws IOException { writeToken("(", x); if (x.getArguments() != null) { writeElement(x.getArguments().get(0)); } write(")"); - output(); + output(); } - public void printPassiveExpression(PassiveExpression x) - throws IOException { + public void printPassiveExpression(PassiveExpression x) throws IOException { writeToken("@(", x); if (x.getArguments() != null) { writeElement(x.getArguments().get(0)); } write(")"); - output(); + output(); } public void printTransactionStatement(TransactionStatement x) throws java.io.IOException { printHeader(x); writeInternalIndentation(x); - // Mark statement start ... - markStart(0,x); + // Mark statement start ... + markStart(0, x); write(x.toString()); write(";"); // Mark statement end ... - markEnd(0,x); + markEnd(0, x); printFooter(x); } @@ -3065,8 +3063,7 @@ public void printEmptyMapLiteral(EmptyMapLiteral x) throws IOException { } /** - * Prints an exec statement. Initial code copied from - * {@link #printTry(Try)}. + * Prints an exec statement. Initial code copied from {@link #printTry(Try)}. * * @param x * @throws IOException @@ -3094,8 +3091,7 @@ public void printExec(Exec x) throws IOException { } /** - * Prints a ccatch statement. Initial code copied from - * {@link #printCatch(Catch)}. + * Prints a ccatch statement. Initial code copied from {@link #printCatch(Catch)}. * * @param x */ @@ -3126,16 +3122,16 @@ public void printCcatch(Ccatch x) throws java.io.IOException { printFooter(x); } - public void printCcatchReturnParameterDeclaration( - CcatchReturnParameterDeclaration x) throws IOException { + public void printCcatchReturnParameterDeclaration(CcatchReturnParameterDeclaration x) + throws IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\Return", x); printFooter(x); } - public void printCcatchReturnValParameterDeclaration( - CcatchReturnValParameterDeclaration x) throws IOException { + public void printCcatchReturnValParameterDeclaration(CcatchReturnValParameterDeclaration x) + throws IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\Return", x); @@ -3144,24 +3140,24 @@ public void printCcatchReturnValParameterDeclaration( printFooter(x); } - public void printCcatchContinueParameterDeclaration( - CcatchContinueParameterDeclaration x) throws IOException { + public void printCcatchContinueParameterDeclaration(CcatchContinueParameterDeclaration x) + throws IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\Continue", x); printFooter(x); } - public void printCcatchBreakParameterDeclaration( - CcatchBreakParameterDeclaration x) throws IOException { + public void printCcatchBreakParameterDeclaration(CcatchBreakParameterDeclaration x) + throws IOException { printHeader(x); writeInternalIndentation(x); writeToken(0, "\\Break", x); printFooter(x); } - public void printCcatchBreakLabelParameterDeclaration( - CcatchBreakLabelParameterDeclaration x) throws IOException { + public void printCcatchBreakLabelParameterDeclaration(CcatchBreakLabelParameterDeclaration x) + throws IOException { printHeader(x); writeInternalIndentation(x); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramElement.java index 3e544465e38..18665b6d04d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramElement.java @@ -1,32 +1,36 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.rule.MatchConditions; /** - * A part of the program syntax that carries semantics in the model. - * taken from COMPOST and changed to achieve an immutable structure + * A part of the program syntax that carries semantics in the model. taken from COMPOST and changed + * to achieve an immutable structure */ public interface ProgramElement extends SourceElement, ModelElement { /** - *Get comments. - *@return the comments. + * Get comments. + * + * @return the comments. */ Comment[] getComments(); - + /** - * matches the source "text" (@link SourceData#getSource()) against the pattern represented - * by this object. In case of a successful match the resulting {@link MatchConditions} with - * the found instantiations of the schemavariables. If the match - * failed, null is returned instead. - * + * matches the source "text" (@link SourceData#getSource()) against the pattern represented by + * this object. In case of a successful match the resulting {@link MatchConditions} with the + * found instantiations of the schemavariables. If the match failed, null is returned + * instead. + * * @param source the SourceData with the program element to match * @param matchCond the MatchConditions found up to this point - * @return the resulting match conditions or null if the match failed + * @return the resulting match conditions or null if the match failed */ MatchConditions match(SourceData source, MatchConditions matchCond); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramPrefixUtil.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramPrefixUtil.java index b1b8264fb6a..cd7c38e3c28 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramPrefixUtil.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramPrefixUtil.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.statement.MethodFrame; @@ -8,16 +11,16 @@ public class ProgramPrefixUtil { public static class ProgramPrefixInfo { private final int length; private final MethodFrame mf; - + public ProgramPrefixInfo(int length, MethodFrame mf) { this.length = length; this.mf = mf; } - + public int getLength() { return length; } - + public MethodFrame getInnerMostMethodFrame() { return mf; } @@ -29,9 +32,9 @@ public static ProgramPrefixInfo computeEssentials(ProgramPrefix prefix) { while (prefix.hasNextPrefixElement()) { prefix = prefix.getNextPrefixElement(); if (prefix instanceof MethodFrame) { - mf = (MethodFrame) prefix; + mf = (MethodFrame) prefix; } - length++; + length++; } return new ProgramPrefixUtil.ProgramPrefixInfo(length, mf); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramVariableName.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramVariableName.java index 8b217c2ccf0..98af27b52a8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramVariableName.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ProgramVariableName.java @@ -1,25 +1,25 @@ -/** represents a name of a program variable - */ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; -public interface ProgramVariableName - extends de.uka.ilkd.key.java.TerminalProgramElement { +public interface ProgramVariableName extends de.uka.ilkd.key.java.TerminalProgramElement { -// public Comment[] getComments(); + // public Comment[] getComments(); -// public SourceElement getFirstElement(); + // public SourceElement getFirstElement(); -// public SourceElement getLastElement(); + // public SourceElement getLastElement(); -// public void prettyPrint(PrettyPrinter w) throws java.io.IOException; + // public void prettyPrint(PrettyPrinter w) throws java.io.IOException; -// public void visit(de.uka.ilkd.key.java.Visitor v); + // public void visit(de.uka.ilkd.key.java.Visitor v); -// public Position getStartPosition(); + // public Position getStartPosition(); -// public Position getEndPosition(); + // public Position getEndPosition(); -// public Position getRelativePosition(); + // public Position getRelativePosition(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeY.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeY.java index c9bf10ccf4b..8465ce593ca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeY.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeY.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -44,25 +47,22 @@ import java.util.*; /** - * This class is the bridge between recoder ast data structures and KeY data - * structures. Syntactical entities and types can be transferred from recoder to - * KeY. - * - * It manages the entire contact with the recoder framework and ensures that - * their cross-referencing data is always uptodate. Prior to reading any source - * code, special classes (i.e. stubs for some needed library classes) are parsed - * in to have them available at any time. - * - * To use a Recoder2KeY bridge to convert data structures you can use the - * functions: {@link #readCompilationUnit(String)}, - * {@link #readCompilationUnitsAsFiles(String[], FileRepo)} or the - * {@link #readBlock(String, Context)}-methods. - * + * This class is the bridge between recoder ast data structures and KeY data structures. Syntactical + * entities and types can be transferred from recoder to KeY. + * + * It manages the entire contact with the recoder framework and ensures that their cross-referencing + * data is always uptodate. Prior to reading any source code, special classes (i.e. stubs for some + * needed library classes) are parsed in to have them available at any time. + * + * To use a Recoder2KeY bridge to convert data structures you can use the functions: + * {@link #readCompilationUnit(String)}, {@link #readCompilationUnitsAsFiles(String[], FileRepo)} or + * the {@link #readBlock(String, Context)}-methods. + * * Results are often stored in caches. - * - * It used to be monolithic but now uses separate classes for doing the actual - * conversion and type conversion. - * + * + * It used to be monolithic but now uses separate classes for doing the actual conversion and type + * conversion. + * * @see Recoder2KeYConverter * @see Recoder2KeYTypeConverter */ @@ -71,25 +71,21 @@ public class Recoder2KeY implements JavaReader { private static final Logger LOGGER = LoggerFactory.getLogger(Recoder2KeY.class); /** - * the set of File objects that describes the classpath to be searched - * for classes. - * it may contain a null file which indicates that the default classes are - * not to be read. + * the set of File objects that describes the classpath to be searched for classes. it may + * contain a null file which indicates that the default classes are not to be read. */ private List classPath; - + /** - * 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. + * 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. - * + * this mapping stores the relation between recoder and KeY entities in a bidirectional way. + * * It is used for syntactical structures and types. */ private final KeYRecoderMapping mapping; @@ -101,13 +97,12 @@ public class Recoder2KeY implements JavaReader { /** * counter used to enumerate the anonymous implicit classes - * + * */ private static int interactCounter = 0; /** - * this flag indicates whether we are currently parsing library classes - * (special classes) + * this flag indicates whether we are currently parsing library classes (special classes) */ private boolean parsingLibs = false; @@ -117,83 +112,70 @@ public class Recoder2KeY implements JavaReader { private final Recoder2KeYConverter converter; /** - * the object that handles the transformation from recoder types to KeY - * types + * the object that handles the transformation from recoder types to KeY types */ private final Recoder2KeYTypeConverter typeConverter; /** - * the list of classnames that contain the classes that are referenced but not - * defined. For those classe types a dummy stub is created at parse time. + * the list of classnames that contain the classes that are referenced but not defined. For + * those classe types a dummy stub is created at parse time. */ private Collection dynamicallyCreatedCompilationUnits; - + private final Services services; /** * create a new Recoder2KeY transformation object. - * - * The converter and type converter associated with this object will be - * created. Several properties of the recoder framework will be set up. - * - * The classpath is set to null, the mapping is retrieved from the services, - * as well as the underlying type converter - * - * @param servConf - * the service configuration to be used, not null - * @param rec2key - * the mapping to store mapped types and mapped ASTs to, not null - * @param nss - * the namespaces to work upon, not null - * @param tc - * the type converter, not null + * + * The converter and type converter associated with this object will be created. Several + * properties of the recoder framework will be set up. + * + * The classpath is set to null, the mapping is retrieved from the services, as well as the + * underlying type converter + * + * @param servConf the service configuration to be used, not null + * @param rec2key the mapping to store mapped types and mapped ASTs to, not null + * @param nss the namespaces to work upon, not null + * @param tc the type converter, not null */ - public Recoder2KeY(Services services, KeYCrossReferenceServiceConfiguration servConf, KeYRecoderMapping rec2key, - NamespaceSet nss, TypeConverter tc) { + public Recoder2KeY(Services services, KeYCrossReferenceServiceConfiguration servConf, + KeYRecoderMapping rec2key, NamespaceSet nss, TypeConverter tc) { this(services, servConf, null, rec2key, nss, tc); } /** * create a new Recoder2KeY transformation object. - * - * The converter and type converter associated with this object will be - * created. Several properties of the recoder framework will be set up. - * - * The classpath is set to null, the mapping is retrieved from the services, - * as well as the underlying type converter - * - * @param services - * services to retrieve objects from, not null - * @param nss - * the namespaces to work upon, not null + * + * The converter and type converter associated with this object will be created. Several + * properties of the recoder framework will be set up. + * + * The classpath is set to null, the mapping is retrieved from the services, as well as the + * underlying type converter + * + * @param services services to retrieve objects from, not null + * @param nss the namespaces to work upon, not null */ public Recoder2KeY(Services services, NamespaceSet nss) { - this(services,services.getJavaInfo().getKeYProgModelInfo().getServConf(), null, + this(services, services.getJavaInfo().getKeYProgModelInfo().getServConf(), null, services.getJavaInfo().rec2key(), nss, services.getTypeConverter()); } /** * create a new Recoder2KeY transformation object. - * - * The converter and type converter associated with this object will be - * created. Several properties of the recoder framework will be set up. - * - * @param servConf - * the service configuration to be used, not null - * @param classPath - * the classpath to look up source files, ignored if null - * @param rec2key - * the mapping to store mapped types and mapped ASTs to, not null - * @param nss - * the namespaces to work upon, not null - * @param tc - * the type converter, not null - * - * @throws IllegalArgumentException - * if arguments are not valid (null e.g.) + * + * The converter and type converter associated with this object will be created. Several + * properties of the recoder framework will be set up. + * + * @param servConf the service configuration to be used, not null + * @param classPath the classpath to look up source files, ignored if null + * @param rec2key the mapping to store mapped types and mapped ASTs to, not null + * @param nss the namespaces to work upon, not null + * @param tc the type converter, not null + * + * @throws IllegalArgumentException if arguments are not valid (null e.g.) */ - private Recoder2KeY(Services services, KeYCrossReferenceServiceConfiguration servConf, String classPath, - KeYRecoderMapping rec2key, NamespaceSet nss, TypeConverter tc) { + private Recoder2KeY(Services services, KeYCrossReferenceServiceConfiguration servConf, + String classPath, KeYRecoderMapping rec2key, NamespaceSet nss, TypeConverter tc) { if (servConf == null) throw new IllegalArgumentException("service configuration is null"); @@ -203,34 +185,36 @@ private Recoder2KeY(Services services, KeYCrossReferenceServiceConfiguration ser if (nss == null) throw new IllegalArgumentException("namespaces is null"); - - if(!(servConf.getProjectSettings().getErrorHandler() instanceof KeYRecoderExcHandler)) - throw new IllegalArgumentException("Recoder2KeY needs a KeyRecoderExcHandler as exception handler"); + + if (!(servConf.getProjectSettings().getErrorHandler() instanceof KeYRecoderExcHandler)) + throw new IllegalArgumentException( + "Recoder2KeY needs a KeyRecoderExcHandler as exception handler"); this.services = services; this.servConf = servConf; this.mapping = rec2key; this.converter = makeConverter(services, nss); this.typeConverter = new Recoder2KeYTypeConverter(services, tc, nss, this); - + // set up recoder: recoder.util.Debug.setLevel(500); - - // do not look up classes anywhere but in the included classes + + // do not look up classes anywhere but in the included classes // or the specified classpaths servConf.getProjectSettings().setProperty(PropertyNames.CLASS_SEARCH_MODE, ""); } - - - + + + /** - * create the ast converter. This is overwritten in SchemaRecoder2KeY to use - * schema-aware converters. - * @param services - * - * @param nss the namespaces provided to the constructor - * + * create the ast converter. This is overwritten in SchemaRecoder2KeY to use schema-aware + * converters. + * + * @param services + * + * @param nss the namespaces provided to the constructor + * * @return a newley created converter */ protected Recoder2KeYConverter makeConverter(Services services, NamespaceSet nss) { @@ -239,7 +223,7 @@ protected Recoder2KeYConverter makeConverter(Services services, NamespaceSet nss /** * return the associated converter object - * + * * @return not null */ public Recoder2KeYConverter getConverter() { @@ -248,7 +232,7 @@ public Recoder2KeYConverter getConverter() { /** * return the associated type converter object - * + * * @return not null */ public Recoder2KeYTypeConverter getTypeConverter() { @@ -257,9 +241,8 @@ public Recoder2KeYTypeConverter getTypeConverter() { /** * set this to true before parsing special classes and to false afterwards. - * - * @param v - * the state of the special parsing flage + * + * @param v the state of the special parsing flage */ private void setParsingLibs(boolean v) { parsingLibs = v; @@ -267,7 +250,7 @@ private void setParsingLibs(boolean v) { /** * are we currently parsing library code (special classes)? - * + * * @return true iff currently parsing special classes. */ public boolean isParsingLibs() { @@ -293,29 +276,25 @@ private void insertToMap(recoder.ModelElement r, ModelElement k) { // ----- parsing of compilation units /** - * parse a list of java files and transform it to the corresponding KeY - * entities. + * 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 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. + * @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 de.uka.ilkd.key.java.CompilationUnit[] - readCompilationUnitsAsFiles(String[] cUnitStrings, FileRepo fileRepo) - throws ParseExceptionInFile { + public de.uka.ilkd.key.java.CompilationUnit[] readCompilationUnitsAsFiles(String[] cUnitStrings, + FileRepo fileRepo) throws ParseExceptionInFile { List cUnits = recoderCompilationUnitsAsFiles(cUnitStrings, fileRepo); - de.uka.ilkd.key.java.CompilationUnit[] result = new de.uka.ilkd.key.java.CompilationUnit[cUnits.size()]; + de.uka.ilkd.key.java.CompilationUnit[] result = + new de.uka.ilkd.key.java.CompilationUnit[cUnits.size()]; for (int i = 0, sz = cUnits.size(); i < sz; i++) { LOGGER.debug("converting now " + cUnitStrings[i]); try { @@ -330,16 +309,17 @@ private void insertToMap(recoder.ModelElement r, ModelElement k) { /** * Helper method for parsing a single compilation unit when a FileRepo is present. + * * @param fileRepo the FileRepo that provides the InputStream * @param filename the name of the file to read * @return the parsed compilation unit * @throws ParseExceptionInFile exceptions are wrapped into this to provide location information */ private CompilationUnit readViaFileRepo(FileRepo fileRepo, String filename) - throws ParseExceptionInFile { + throws ParseExceptionInFile { try (InputStream is = fileRepo.getInputStream(Paths.get(filename)); - Reader fr = new InputStreamReader(is, StandardCharsets.UTF_8); - BufferedReader br = new BufferedReader(fr)) { + Reader fr = new InputStreamReader(is, StandardCharsets.UTF_8); + BufferedReader br = new BufferedReader(fr)) { return servConf.getProgramFactory().parseCompilationUnit(br); } catch (Exception e) { throw new ParseExceptionInFile(filename, e); @@ -349,13 +329,13 @@ private CompilationUnit readViaFileRepo(FileRepo fileRepo, String filename) /** * Helper method for parsing a single compilation unit directly from a file, in case no FileRepo * is present. + * * @param filename the name of the file to read * @return the parsed compilation unit * @throws ParseExceptionInFile exceptions are wrapped into this to provide location information */ private CompilationUnit readWithoutFileRepo(String filename) throws ParseExceptionInFile { - try (Reader fr = new FileReader(filename); - BufferedReader br = new BufferedReader(fr)) { + try (Reader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr)) { return servConf.getProgramFactory().parseCompilationUnit(br); } catch (Exception e) { throw new ParseExceptionInFile(filename, e); @@ -367,12 +347,10 @@ private CompilationUnit readWithoutFileRepo(String filename) throws ParseExcepti * * 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 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. + * @return a new list containing the recoder compilation units corresponding to the given files. */ private List recoderCompilationUnitsAsFiles(String[] cUnitStrings, FileRepo fileRepo) { @@ -407,10 +385,10 @@ private List recoderCompilationUnitsAsFiles(String // transform program transformModel(cUnits); } catch (Exception ex) { - if(ex.getCause() instanceof UnresolvedReferenceException) { - String extraMsg = "Consider using a classpath in your input file if this is a " + - "classtype that cannot be resolved (see " + - "https://key-project.org/docs/user/Classpath for more details)."; + if (ex.getCause() instanceof UnresolvedReferenceException) { + String extraMsg = "Consider using a classpath in your input file if this is a " + + "classtype that cannot be resolved (see " + + "https://key-project.org/docs/user/Classpath for more details)."; String msg = String.format("%s%n%s", ex.getCause().getMessage(), extraMsg); reportError(msg, ex); } else { @@ -419,25 +397,23 @@ private List recoderCompilationUnitsAsFiles(String } return cUnits; } - + /** * read a compilation unit, given as a string. - * - * @param cUnitString - * a string represents a compilation unit + * + * @param cUnitString a string represents a compilation unit * @return a KeY structured compilation unit. */ public de.uka.ilkd.key.java.CompilationUnit readCompilationUnit(String cUnitString) { - final recoder.java.CompilationUnit cc = recoderCompilationUnits(new String[] { cUnitString }).get(0); + final recoder.java.CompilationUnit cc = + recoderCompilationUnits(new String[] { cUnitString }).get(0); return (de.uka.ilkd.key.java.CompilationUnit) getConverter().process(cc); } /** * read a number of compilation units, each given as a string. - * - * @param cUnitStrings - * an array of strings, each element represents a compilation - * unit + * + * @param cUnitStrings an array of strings, each element represents a compilation unit * @return a list of KeY structured compilation units. */ List recoderCompilationUnits(String[] cUnitStrings) { @@ -450,8 +426,8 @@ List recoderCompilationUnits(String[] cUnitStrings for (int i = 0; i < cUnitStrings.length; i++) { current = i; LOGGER.debug("Reading " + trim(cUnitStrings[i])); - sr = new BufferedReader(new StringReader(cUnitStrings[i])); - cUnits.add(servConf.getProgramFactory().parseCompilationUnit(sr)); + sr = new BufferedReader(new StringReader(cUnitStrings[i])); + cUnits.add(servConf.getProgramFactory().parseCompilationUnit(sr)); } // run cross referencer final ChangeHistory changeHistory = servConf.getChangeHistory(); @@ -468,9 +444,10 @@ List recoderCompilationUnits(String[] cUnitStrings transformModel(cUnits); } catch (IOException ioe) { - LOGGER.debug("recoder2key: IO Error when reading" + "compilation unit " + cUnitStrings[current], ioe); - reportError("IOError reading java program " + cUnitStrings[current] + ". " + - "May be file not found or missing permissions.", ioe); + LOGGER.debug("recoder2key: IO Error when reading" + "compilation unit " + + cUnitStrings[current], ioe); + reportError("IOError reading java program " + cUnitStrings[current] + ". " + + "May be file not found or missing permissions.", ioe); } catch (recoder.ParserException pe) { LOGGER.debug("recoder2key: Recoder Parser Error when" + "reading a comiplation unit {}", cUnitStrings[current], pe); @@ -481,11 +458,11 @@ List recoderCompilationUnits(String[] cUnitStrings } } finally { if (sr != null) { - try { - sr.close(); + try { + sr.close(); } catch (IOException e) { - reportError("IOError reading java program " + - cUnitStrings[current] + ". May be file not found or missing permissions.", e); + reportError("IOError reading java program " + cUnitStrings[current] + + ". May be file not found or missing permissions.", e); } } } @@ -493,94 +470,90 @@ List recoderCompilationUnits(String[] cUnitStrings } // ----- parsing libraries - + public void setClassPath(File bootClassPath, List classPath) { this.classPath = classPath; this.bootClassPath = bootClassPath; } /** - * 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. - * + * 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. + * * @author mu, on rb's specification ;) * @return an unmodifiable list of fully qualified class names */ public List getDynamicallyCreatedClasses() { List ret = new ArrayList<>(); - if(dynamicallyCreatedCompilationUnits != null) { + if (dynamicallyCreatedCompilationUnits != null) { for (CompilationUnit cu : dynamicallyCreatedCompilationUnits) { ret.add(cu.getPrimaryTypeDeclaration().getFullName()); } } 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 + * + * 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 */ private void parseInternalClasses(ProgramFactory pf, List rcuList, FileRepo fileRepo) throws IOException, ParserException { - + FileCollection bootCollection; FileCollection.Walker walker; - if(bootClassPath == null) { + if (bootClassPath == null) { bootCollection = new JavaReduxFileCollection(services.getProfile()); walker = bootCollection.createWalker(".java"); } else { bootCollection = new DirectoryFileCollection(bootClassPath); - walker = bootCollection.createWalker(new String[] {".java", ".jml"} ); + walker = bootCollection.createWalker(new String[] { ".java", ".jml" }); } - - - while(walker.step()) { + + + while (walker.step()) { DataLocation loc = walker.getCurrentDataLocation(); try (InputStream is = walker.openCurrent(fileRepo); - Reader isr = new InputStreamReader(is); - Reader f = new BufferedReader(isr)) { + Reader isr = new InputStreamReader(is); + Reader f = new BufferedReader(isr)) { recoder.java.CompilationUnit rcu = pf.parseCompilationUnit(f); rcu.setDataLocation(loc); // done by parser : rcu.makeAllParentRolesValid(); rcuList.add(rcu); - } catch(Exception ex) { + } catch (Exception ex) { throw new ParseExceptionInFile(loc.toString(), ex); } - + if (Debug.ENABLE_DEBUG) { LOGGER.debug("parsed: " + loc); } } - + } - + /** * reads compilation units that will be treated as library classes. - * + * * Proceed as follows: - * + * *

      - *
    1. If "classPath" is set and contains at least one entry + *
    2. 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) + *
      3. read every .java file within the entries (directories or zip files) + *
      4. read every .class file within the entries (directories or zip files) *
      *
    3. else read a special collection of classes that is stored internally *
    @@ -599,9 +572,9 @@ private List parseLibs(FileRepo fileRepo) parseInternalClasses(pf, rcuList, fileRepo); - if(classPath != null) { - for(File cp : classPath) { - if(cp.isDirectory()) { + if (classPath != null) { + for (File cp : classPath) { + if (cp.isDirectory()) { sources.add(new DirectoryFileCollection(cp)); } else { sources.add(new ZipFileCollection(cp)); @@ -609,25 +582,28 @@ private List parseLibs(FileRepo fileRepo) } } - /* 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. */ + /* + * 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. + */ DataLocation currentDataLocation; // -- read jml files -- for (FileCollection fc : sources) { FileCollection.Walker walker = fc.createWalker(".jml"); - while(walker.step()) { + while (walker.step()) { currentDataLocation = walker.getCurrentDataLocation(); try (InputStream is = walker.openCurrent(fileRepo); - Reader isr = new InputStreamReader(is); - Reader f = new BufferedReader(isr)) { + Reader isr = new InputStreamReader(is); + Reader f = new BufferedReader(isr)) { recoder.java.CompilationUnit rcu = pf.parseCompilationUnit(f); rcu.setDataLocation(currentDataLocation); removeCodeFromClasses(rcu, false); rcuList.add(rcu); - } catch(Exception ex) { - throw new ConvertException("Error while loading: " + walker.getCurrentDataLocation(), ex); + } catch (Exception ex) { + throw new ConvertException( + "Error while loading: " + walker.getCurrentDataLocation(), ex); } } } @@ -635,91 +611,89 @@ private List parseLibs(FileRepo fileRepo) // -- read java files -- for (FileCollection fc : sources) { FileCollection.Walker walker = fc.createWalker(".java"); - while(walker.step()) { + while (walker.step()) { currentDataLocation = walker.getCurrentDataLocation(); try (InputStream is = walker.openCurrent(fileRepo); - Reader isr = new InputStreamReader(is); - Reader f = new BufferedReader(isr)) { + Reader isr = new InputStreamReader(is); + Reader f = new BufferedReader(isr)) { recoder.java.CompilationUnit rcu = pf.parseCompilationUnit(f); rcu.setDataLocation(currentDataLocation); removeCodeFromClasses(rcu, true); rcuList.add(rcu); - } catch(Exception ex) { - throw new ConvertException("Error while loading: " + walker.getCurrentDataLocation(), ex); + } catch (Exception ex) { + throw new ConvertException( + "Error while loading: " + walker.getCurrentDataLocation(), ex); } } } // -- read class files -- - ClassFileDeclarationManager manager = new ClassFileDeclarationManager(pf); + ClassFileDeclarationManager manager = new ClassFileDeclarationManager(pf); ByteCodeParser parser = new ByteCodeParser(); for (FileCollection fc : sources) { FileCollection.Walker walker = fc.createWalker(".class"); - while(walker.step()) { + 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); + } catch (Exception ex) { + throw new ConvertException( + "Error while loading: " + walker.getCurrentDataLocation(), ex); } } } rcuList.addAll(manager.getCompilationUnits()); - - recoder.java.CompilationUnit rcu = pf.parseCompilationUnit( - new StringReader("public class " + - JavaInfo.DEFAULT_EXECUTION_CONTEXT_CLASS + " { public static void " + JavaInfo.DEFAULT_EXECUTION_CONTEXT_METHOD + "() {} }")); + + recoder.java.CompilationUnit rcu = pf.parseCompilationUnit(new StringReader("public class " + + JavaInfo.DEFAULT_EXECUTION_CONTEXT_CLASS + " { public static void " + + JavaInfo.DEFAULT_EXECUTION_CONTEXT_METHOD + "() {} }")); rcuList.add(rcu); 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? + * 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) { TreeWalker tw = new TreeWalker(rcu); - - while(tw.next()) { + + while (tw.next()) { ProgramElement pe = tw.getProgramElement(); if (pe instanceof MethodDeclaration) { MethodDeclaration methDecl = (MethodDeclaration) pe; - if(!allowed && methDecl.getBody() != null) { - LOGGER.warn("Method body ("+methDecl.getName()+") should not be allowed: "+rcu.getDataLocation(), - Recoder2KeY.class.getName()); + if (!allowed && methDecl.getBody() != null) { + LOGGER.warn("Method body (" + methDecl.getName() + ") should not be allowed: " + + rcu.getDataLocation(), Recoder2KeY.class.getName()); } methDecl.setBody(null); } /* - // This is deactivated to allow compile time constants in declaration stub files. - // see bug #1114 - if (pe instanceof recoder.java.declaration.FieldSpecification) { - recoder.java.declaration.FieldSpecification fieldSpec = - (recoder.java.declaration.FieldSpecification) pe; - if(!allowed && fieldSpec.getInitializer() != null) { - Debug.log4jWarn("Field initializer ("+fieldSpec.getName()+") should not be allowed: "+rcu.getDataLocation(), - Recoder2KeY.class.getName()); - } - fieldSpec.setInitializer(null); - } - */ + * // This is deactivated to allow compile time constants in declaration stub files. // + * see bug #1114 if (pe instanceof recoder.java.declaration.FieldSpecification) { + * recoder.java.declaration.FieldSpecification fieldSpec = + * (recoder.java.declaration.FieldSpecification) pe; if(!allowed && + * fieldSpec.getInitializer() != null) { + * Debug.log4jWarn("Field initializer ("+fieldSpec.getName()+") should not be allowed: " + * +rcu.getDataLocation(), Recoder2KeY.class.getName()); } + * fieldSpec.setInitializer(null); } + */ if (pe instanceof ClassInitializer) { ClassInitializer classInit = (ClassInitializer) pe; - if(!allowed && classInit.getBody() != null) { + if (!allowed && classInit.getBody() != null) { LOGGER.warn("There should be no class initializers: {}", rcu.getDataLocation()); } classInit.setBody(null); @@ -728,11 +702,10 @@ private void removeCodeFromClasses(CompilationUnit rcu, boolean allowed) { } /** - * makes sure that the special classes (library classes) have been parsed - * in. + * 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. + * If not parsed yet, the special classes are read in and converted. This method throws only + * runtime exceptions for historical reasons. */ public void parseSpecialClasses() { try { @@ -743,11 +716,10 @@ public void parseSpecialClasses() { } /** - * makes sure that the special classes (library classes) have been parsed - * in. + * 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. + * 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 */ @@ -759,8 +731,7 @@ public void parseSpecialClasses(FileRepo fileRepo) { } } - private void parseLibraryClasses0(FileRepo fileRepo) - throws IOException, ParserException { + private void parseLibraryClasses0(FileRepo fileRepo) throws IOException, ParserException { if (mapping.parsedSpecial()) { return; } @@ -776,47 +747,46 @@ private void parseLibraryClasses0(FileRepo fileRepo) // TODO if duplicated files, take first one only! changeHistory.attached(specialClass); } - - + + CrossReferenceSourceInfo sourceInfo = servConf.getCrossReferenceSourceInfo(); - assert sourceInfo instanceof KeYCrossReferenceSourceInfo : - "SourceInfo is not of type KeYCrossReferenceSourceInfo"; - KeYCrossReferenceSourceInfo keySourceInfo = - (KeYCrossReferenceSourceInfo)sourceInfo; - + assert sourceInfo instanceof KeYCrossReferenceSourceInfo + : "SourceInfo is not of type KeYCrossReferenceSourceInfo"; + KeYCrossReferenceSourceInfo keySourceInfo = (KeYCrossReferenceSourceInfo) sourceInfo; + keySourceInfo.setIgnoreUnresolvedClasses(true); if (changeHistory.needsUpdate()) { changeHistory.updateModel(); } - + dynamicallyCreatedCompilationUnits = keySourceInfo.getCreatedStubClasses(); specialClasses.addAll(dynamicallyCreatedCompilationUnits); keySourceInfo.setIgnoreUnresolvedClasses(false); - + changeHistory.updateModel(); transformModel(specialClasses); // make them available to the rec2key mapping - for(recoder.java.CompilationUnit cu : specialClasses) { + for (recoder.java.CompilationUnit cu : specialClasses) { DataLocation dl = cu.getOriginalDataLocation(); assert dl != null : "DataLocation not set on " + cu.toSource(); getConverter().processCompilationUnit(cu, dl); } - + // Ensure that rec2key is complete (at least the NullType needs to be available!) if (!rec2key().mapped(servConf.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); + 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); } - + // tell the mapping that we have parsed the special classes rec2key().parsedSpecial(true); @@ -825,39 +795,35 @@ private void parseLibraryClasses0(FileRepo fileRepo) /** * 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. + * + * 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) { - RecoderModelTransformer.TransformerCache cache = new RecoderModelTransformer.TransformerCache(cUnits); - - ConstructorNormalformBuilder cnb; - + RecoderModelTransformer.TransformerCache cache = + new RecoderModelTransformer.TransformerCache(cUnits); + + ConstructorNormalformBuilder cnb; + RecoderModelTransformer[] transformer = new RecoderModelTransformer[] { - new EnumClassBuilder(servConf, cache), - new JMLTransformer(servConf, cache), + new EnumClassBuilder(servConf, cache), new JMLTransformer(servConf, cache), new ImplicitFieldAdder(servConf, cache), new InstanceAllocationMethodBuilder(servConf, cache), cnb = new ConstructorNormalformBuilder(servConf, cache), new ClassPreparationMethodBuilder(servConf, cache), - new ClassInitializeMethodBuilder(servConf, cache), - new PrepareObjectBuilder(servConf, cache), - new CreateBuilder(servConf, cache), + new ClassInitializeMethodBuilder(servConf, cache), + new PrepareObjectBuilder(servConf, cache), new CreateBuilder(servConf, cache), new CreateObjectBuilder(servConf, cache), new LocalClassTransformation(servConf, cache), - new ConstantStringExpressionEvaluator(servConf, cache) - }; + new ConstantStringExpressionEvaluator(servConf, cache) }; + - final ChangeHistory cHistory = servConf.getChangeHistory(); for (RecoderModelTransformer aTransformer : transformer) { if (Debug.ENABLE_DEBUG) { @@ -865,13 +831,13 @@ protected void transformModel(List cUnits) { } aTransformer.execute(); } - + converter.locClass2finalVar = cnb.getLocalClass2FinalVar(); if (cHistory.needsUpdate()) { cHistory.updateModel(); } - + // recoder changes the data location to some imaginary files // undo this by setting the original locations for (recoder.java.CompilationUnit cu : cUnits) { @@ -883,35 +849,31 @@ protected void transformModel(List cUnits) { /** * wraps a RECODER StatementBlock in a method - * - * it is wrapped in a method called - * <virtual_method_for_parsing>. - * - * @param block - * the recoder.java.StatementBlock to wrap + * + * it is wrapped in a method called <virtual_method_for_parsing>. + * + * @param block the recoder.java.StatementBlock to wrap * @return the enclosing recoder.java.MethodDeclaration */ - protected recoder.java.declaration.MethodDeclaration embedBlock(recoder.java.StatementBlock block) { + protected recoder.java.declaration.MethodDeclaration embedBlock( + recoder.java.StatementBlock block) { /* - * MethodDeclaration(modifiers,return type,Identifier, parameters, - * throws, StatementBlock) + * MethodDeclaration(modifiers,return type,Identifier, parameters, throws, StatementBlock) */ - recoder.java.declaration.MethodDeclaration mdecl = new recoder.java.declaration.MethodDeclaration( - null, null, new ImplicitIdentifier( - ""), null, null, block); + recoder.java.declaration.MethodDeclaration mdecl = + new recoder.java.declaration.MethodDeclaration(null, null, + new ImplicitIdentifier(""), null, null, block); mdecl.makeParentRoleValid(); return mdecl; } /** * wraps a RECODER MethodDeclaration in a class - * - * @param mdecl - * the recoder.java.declaration.MethodDeclaration to wrap - * @param context - * the recoder.java.declaration.ClassDeclaration where the method - * has to be embedded + * + * @param mdecl the recoder.java.declaration.MethodDeclaration to wrap + * @param context the recoder.java.declaration.ClassDeclaration where the method has to be + * embedded * @return the enclosing recoder.java.declaration.ClassDeclaration */ protected recoder.java.declaration.ClassDeclaration embedMethod( @@ -947,7 +909,7 @@ protected recoder.java.declaration.ClassDeclaration embedMethod( /** * creates an empty RECODER compilation unit with a temporary name. - * + * * @return the new recoder.java.CompilationUnit */ public Context createEmptyContext() { @@ -956,11 +918,10 @@ public Context createEmptyContext() { } /** - * create a new context with a temporary name and make a list of variables - * visible from within. Use the default source info. - * - * @param pvs - * a list of variables + * create a new context with a temporary name and make a list of variables visible from within. + * Use the default source info. + * + * @param pvs a list of variables * @return a newly created context. */ @@ -969,17 +930,15 @@ protected Context createContext(ImmutableList pvs) { } /** - * 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 - * + * 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 Context createContext(ImmutableList vars, recoder.service.CrossReferenceSourceInfo csi) { + protected Context createContext(ImmutableList vars, + recoder.service.CrossReferenceSourceInfo csi) { recoder.java.declaration.ClassDeclaration classContext = interactClassDecl(); addProgramVariablesToClassContext(classContext, vars, csi); return new Context(servConf, classContext); @@ -987,15 +946,13 @@ protected Context createContext(ImmutableList vars, recoder.ser /** * add a list of variables to a context - * - * @param classContext - * context to add to - * @param vars - * vars to add + * + * @param classContext context to add to + * @param vars vars to add */ - private void addProgramVariablesToClassContext(recoder.java.declaration.ClassDeclaration classContext, - ImmutableList vars, - recoder.service.CrossReferenceSourceInfo csi) { + private void addProgramVariablesToClassContext( + recoder.java.declaration.ClassDeclaration classContext, + ImmutableList vars, recoder.service.CrossReferenceSourceInfo csi) { HashMap names2var = new LinkedHashMap<>(); @@ -1033,12 +990,15 @@ private void addProgramVariablesToClassContext(recoder.java.declaration.ClassDec String typeName; Type javaType = var.getKeYJavaType().getJavaType(); - if(javaType == null) continue; + if (javaType == null) + continue; typeName = javaType.getFullName(); - recoder.java.declaration.FieldDeclaration recVar = new recoder.java.declaration.FieldDeclaration( - null, name2typeReference(typeName), new ExtendedIdentifier(keyVarSpec.getName()),null); + recoder.java.declaration.FieldDeclaration recVar = + new recoder.java.declaration.FieldDeclaration(null, + name2typeReference(typeName), + new ExtendedIdentifier(keyVarSpec.getName()), null); list.add(recVar); classContext.makeAllParentRolesValid(); @@ -1055,12 +1015,13 @@ private void addProgramVariablesToClassContext(recoder.java.declaration.ClassDec /** * 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) { + if ((o instanceof VariableSpecification) + && ((VariableSpecification) o).getProgramVariable() == pv) { return (VariableSpecification) o; } } @@ -1069,9 +1030,8 @@ private VariableSpecification lookupVarSpec(ProgramVariable pv) { /** * given a name as string, construct a recoder type reference from it. - * - * @param typeName - * non-null type name as string + * + * @param typeName non-null type name as string * @return a freshly created type reference to the given type. */ private recoder.java.reference.TypeReference name2typeReference(String typeName) { @@ -1079,16 +1039,15 @@ private recoder.java.reference.TypeReference name2typeReference(String typeName) String baseType = TypeNameTranslator.getBaseType(typeName); int idx = baseType.indexOf('.'); int lastIndex = 0; - String anonType=""; - while (idx != -1 && baseType.charAt(lastIndex) >= 'a' + String anonType = ""; + while (idx != -1 && baseType.charAt(lastIndex) >= 'a' && baseType.charAt(lastIndex) <= 'z') { String s = baseType.substring(lastIndex, idx); - pr = new recoder.java.reference.PackageReference - (pr, new recoder.java.Identifier(s)); + pr = new recoder.java.reference.PackageReference(pr, new recoder.java.Identifier(s)); lastIndex = idx + 1; idx = baseType.indexOf('.', lastIndex); } - baseType = anonType+baseType; + baseType = anonType + baseType; recoder.java.Identifier typeId; if (baseType.charAt(0) == '<') { typeId = new ImplicitIdentifier(baseType.substring(lastIndex)); @@ -1096,20 +1055,17 @@ private recoder.java.reference.TypeReference name2typeReference(String typeName) typeId = new ObjectTypeIdentifier(baseType.substring(lastIndex)); } recoder.java.reference.TypeReference result = - new recoder.java.reference.TypeReference(pr, typeId); + new recoder.java.reference.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 - * recoder.java.CompilationUnit in which the block has to be - * interpreted + * 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 recoder.java.CompilationUnit in which the block has to be interpreted * @return the parsed and resolved recoder statement block */ recoder.java.StatementBlock recoderBlock(String block, Context context) { @@ -1129,7 +1085,8 @@ recoder.java.StatementBlock recoderBlock(String block, Context context) { // normalise constant string expressions List cunits = new ArrayList<>(); cunits.add(context.getCompilationUnitContext()); - final RecoderModelTransformer.TransformerCache cache = new RecoderModelTransformer.TransformerCache(cunits); + final RecoderModelTransformer.TransformerCache cache = + new RecoderModelTransformer.TransformerCache(cunits); new ConstantStringExpressionEvaluator(servConf, cache).execute(); } catch (UnresolvedReferenceException e) { reportError("Could not resolve reference:" + e.getUnresolvedReference(), e); @@ -1142,13 +1099,14 @@ recoder.java.StatementBlock recoderBlock(String block, Context context) { } catch (IOException e) { LOGGER.debug("recoder2key: IOException detected in: " + block, e); block = trim(block, 25); - reportError("Could not access data stream " + "(e.g. file not found, wrong permissions) " + reportError( + "Could not access data stream " + "(e.g. file not found, wrong permissions) " + "when reading " + block + ": " + trim(e.getMessage()), e); } catch (NullPointerException e) { // to retrieve a more precise message we would need to patch Recoder - reportError("Recoder parser threw exception in block:\n" + block + - "\n Probably a misspelled identifier name.", e); + reportError("Recoder parser threw exception in block:\n" + block + + "\n Probably a misspelled identifier name.", e); } catch (Exception e) { reportError(e.getMessage(), e); } @@ -1156,14 +1114,10 @@ recoder.java.StatementBlock recoderBlock(String block, Context context) { } /** - * parses a given JavaBlock using the context to determine the right - * references - * - * @param block - * a String describing a java block - * @param context - * recoder.java.CompilationUnit in which the block has to be - * interprested + * parses a given JavaBlock using the context to determine the right references + * + * @param block a String describing a java block + * @param context recoder.java.CompilationUnit in which the block has to be interprested * @return the parsed and resolved JavaBlock */ public JavaBlock readBlock(String block, Context context) { @@ -1173,11 +1127,10 @@ public JavaBlock readBlock(String block, Context context) { } /** - * parses a given JavaBlock using the context to determine the right - * references using an empty context - * - * @param block - * a String describing a java block + * 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) { @@ -1185,12 +1138,10 @@ public JavaBlock readBlockWithEmptyContext(String block) { } /** - * 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 + * 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 varns, String s) { @@ -1199,7 +1150,7 @@ public JavaBlock readBlockWithProgramVariables(Namespace varns while (it.hasNext()) { Named n = it.next(); if (n instanceof ProgramVariable) { - pvs = pvs.append((ProgramVariable) n); //preserve the order (nested namespaces!) + pvs = pvs.append((ProgramVariable) n); // preserve the order (nested namespaces!) } } return readBlock(s, createContext(pvs)); @@ -1207,15 +1158,17 @@ public JavaBlock readBlockWithProgramVariables(Namespace varns /** * 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 recoder.java.declaration.ClassDeclaration interactClassDecl() { - recoder.java.declaration.ClassDeclaration classContext = new recoder.java.declaration.ClassDeclaration( - null, new ImplicitIdentifier(""), - null, null, null); + recoder.java.declaration.ClassDeclaration classContext = + new recoder.java.declaration.ClassDeclaration(null, + new ImplicitIdentifier( + ""), + null, null, null); interactCounter++; classContext.setProgramModelInfo(servConf.getCrossReferenceSourceInfo()); return classContext; @@ -1224,8 +1177,7 @@ null, new ImplicitIdentifier(" // ----- helpers /** - * reduce the size of a string to a maximum of 150 characters. Introduces - * ellipses [...] + * reduce the size of a string to a maximum of 150 characters. Introduces ellipses [...] */ private static String trim(String s) { return trim(s, 150); @@ -1257,7 +1209,8 @@ private static int[] extractPositionInfo(String errorMessage) { 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); + LOGGER.debug( + "recoder2key:unresolved reference at " + "line:" + line + " column:" + column); return new int[0]; } catch (StringIndexOutOfBoundsException siexc) { return new int[0]; @@ -1266,25 +1219,22 @@ private static int[] extractPositionInfo(String errorMessage) { } /** - * report an error in form of a ConvertException. The cause is always - * attached to the resulting exception. + * 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 + * @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 (t instanceof ExceptionHandlerException && t.getCause() != null) { + cause = t.getCause(); } - if(cause instanceof PosConvertException) { - throw (PosConvertException)cause; + if (cause instanceof PosConvertException) { + throw (PosConvertException) cause; } int[] pos = extractPositionInfo(cause.toString()); @@ -1299,4 +1249,4 @@ public static void reportError(String message, Throwable t) { throw rte; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYConverter.java index 02f9f61d05a..ca33e269b65 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYConverter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.lang.reflect.Constructor; @@ -60,20 +63,18 @@ import static java.lang.String.format; /** - * Objects of this class can be used to transform an AST returned by the recoder - * library to the corresponding yet immutable KeY data structures. + * Objects of this class can be used to transform an AST returned by the recoder library to the + * corresponding yet immutable KeY data structures. * * Call the method process() to convert an arbitrary object. * - * The method callConvert is used to perform a run-time dispatch upon the - * parameters. + * The method callConvert is used to perform a run-time dispatch upon the parameters. * - * The actual conversion is done in convert-methods which must be declared - * public due to the used reflection method lookup function. + * The actual conversion is done in convert-methods which must be declared public due to the used + * reflection method lookup function. * - * There is a general method {@link #callConvert(recoder.java.ProgramElement)} - * that does the job in general. Several special cases must be treated - * separately. + * There is a general method {@link #callConvert(recoder.java.ProgramElement)} that does the job in + * general. Several special cases must be treated separately. * * This code used to be part of {@link Recoder2KeY} and has been 'out-sourced'. * @@ -93,18 +94,18 @@ public ProgramElement process(recoder.java.ProgramElement pe) { return (ProgramElement) result; } - public IProgramMethod processDefaultConstructor( - recoder.abstraction.DefaultConstructor df) { + public IProgramMethod processDefaultConstructor(recoder.abstraction.DefaultConstructor df) { return convert(df); } - public CompilationUnit processCompilationUnit( - recoder.java.CompilationUnit cu, DataLocation context) { + public CompilationUnit processCompilationUnit(recoder.java.CompilationUnit cu, + DataLocation context) { currentClassURI = MiscTools.extractURI(context); Object result = process(cu); currentClassURI = null; - assert result instanceof CompilationUnit : "a compilation unit must result in a compilation unit!"; + assert result instanceof CompilationUnit + : "a compilation unit must result in a compilation unit!"; return (CompilationUnit) result; } @@ -124,32 +125,32 @@ public Recoder2KeYConverter(Recoder2KeY rec2key, Services services, NamespaceSet private final HashMap, Method> methodCache = new LinkedHashMap, Method>(400); /** - * caches constructor access for reflection. It is a HashMap + * caches constructor access for reflection. It is a HashMap */ private final HashMap, Constructor> constructorCache = - new LinkedHashMap, Constructor>(400); + new LinkedHashMap, Constructor>( + 400); /** - * Hashmap from recoder.java.declaration.FieldSpecification - * to ProgramVariable; this is necessary to avoid cycles - * when converting initializers. Access to this map is performed via the - * method getProgramVariableForFieldSpecification + * Hashmap from recoder.java.declaration.FieldSpecification to + * ProgramVariable; this is necessary to avoid cycles when converting initializers. + * Access to this map is performed via the method + * getProgramVariableForFieldSpecification */ private HashMap fieldSpecificationMapping = - new LinkedHashMap(); + new LinkedHashMap(); /** - * methodsDeclaring contains the recoder method declarations as keys that - * have been started to convert but are not yet finished. The mapped value - * is the reference to the later completed IProgramMethod. + * methodsDeclaring contains the recoder method declarations as keys that have been started to + * convert but are not yet finished. The mapped value is the reference to the later completed + * IProgramMethod. */ private HashMap methodsDeclaring = - new LinkedHashMap(); + new LinkedHashMap(); /** - * locClass2finalVar stores the final variables that need to be passed - * to the constructor of an anonymous class. + * locClass2finalVar stores the final variables that need to be passed to the constructor of an + * anonymous class. */ protected Map locClass2finalVar = null; @@ -169,16 +170,15 @@ public Recoder2KeYConverter(Recoder2KeY rec2key, Services services, NamespaceSet private Recoder2KeY rec2key; /** - * The namespaces are here to provide some conversion functions access to - * previously defined logical symbols. + * The namespaces are here to provide some conversion functions access to previously defined + * logical symbols. */ private final NamespaceSet namespaceSet; /** * retrieve a key type using the converter available from Recoder2KeY * - * @param javaType - * type to look up + * @param javaType type to look up * @return the result from the type converter */ private KeYJavaType getKeYJavaType(Type javaType) { @@ -224,24 +224,20 @@ private boolean isParsingLibs() { } /** - * convert a recoder ProgramElement to a corresponding KeY data structure - * entity. + * convert a recoder ProgramElement to a corresponding KeY data structure entity. * - * Almost always the returned type carries the same Classname but in a KeY - * rather than a recoder package. + * Almost always the returned type carries the same Classname but in a KeY rather than a recoder + * package. * * Determines the right convert method using reflection * - * @param pe - * the recoder.java.JavaProgramElement to be converted, not null. + * @param pe the recoder.java.JavaProgramElement to be converted, not null. * * @return the converted element * - * @throws ConvertException - * if the conversion fails + * @throws ConvertException if the conversion fails */ - protected Object callConvert(recoder.java.ProgramElement pe) - throws ConvertException { + protected Object callConvert(recoder.java.ProgramElement pe) throws ConvertException { if (pe == null) throw new ConvertException("cannot convert 'null'"); @@ -269,8 +265,7 @@ protected Object callConvert(recoder.java.ProgramElement pe) if (m == null) throw new ConvertException( - "Could not find convert method for class " - + pe.getClass()); + "Could not find convert method for class " + pe.getClass()); for (Class aL : l) { methodCache.put(aL, m); @@ -287,16 +282,15 @@ protected Object callConvert(recoder.java.ProgramElement pe) throw new ConvertException("recoder2key: cannot access method", iae); } catch (IllegalArgumentException iarg) { LOGGER.debug("recoder2key: wrong method arguments ", iarg); - throw new ConvertException("recoder2key: wrong method arguments", - iarg); + throw new ConvertException("recoder2key: wrong method arguments", iarg); } catch (InvocationTargetException ite) { - LOGGER.debug("recoder2key: called method " + m + " threw exception ", ite - .getTargetException()); + LOGGER.debug("recoder2key: called method " + m + " threw exception ", + ite.getTargetException()); if (ite.getTargetException() instanceof ConvertException) { throw (ConvertException) ite.getTargetException(); } else { - Recoder2KeY.reportError("called method " + m - + " threw exception.", ite.getTargetException()); + Recoder2KeY.reportError("called method " + m + " threw exception.", + ite.getTargetException()); } } @@ -316,14 +310,12 @@ protected Object callConvert(recoder.java.ProgramElement pe) // ==== HELPER FUNCTIONS =============================================== /** - * iterate over all children and call convert upon them. Gather the - * resulting KeY structures in an ExtList. + * iterate over all children and call convert upon them. Gather the resulting KeY structures in + * an ExtList. * * In addition to the child ast-branches, all comments are gathered also. * - * @param pe - * the NonTerminalProgramElement that needs its children before - * being converted + * @param pe the NonTerminalProgramElement that needs its children before being converted * @return the list of children after conversion */ protected ExtList collectChildren(recoder.java.NonTerminalProgramElement pe) { @@ -345,31 +337,22 @@ protected ExtList collectChildren(recoder.java.NonTerminalProgramElement pe) { } /** - * replace some numbers from anonymous class names. - * needed by the translation of anonymous classes. + * replace some numbers from anonymous class names. needed by the translation of anonymous + * classes. */ - static String makeAdmissibleName(String s){ + static String makeAdmissibleName(String s) { return s; /* - int i = s.indexOf("."); - while(i!=-1){ - if(s.charAt(i+1)<='9' && s.charAt(i+1)>='0') { - s = s.substring(0, i)+"_"+s.substring(i+1); - } - i = s.indexOf(".", i+1); - } - return s; - */ + * int i = s.indexOf("."); while(i!=-1){ if(s.charAt(i+1)<='9' && s.charAt(i+1)>='0') { s = + * s.substring(0, i)+"_"+s.substring(i+1); } i = s.indexOf(".", i+1); } return s; + */ } /** - * collects comments and adds their converted KeY-counterpart to the list of - * children + * collects comments and adds their converted KeY-counterpart to the list of children * - * @param pe - * the ProgramElement that needs its comments before being - * converted + * @param pe the ProgramElement that needs its comments before being converted * @return the list of comments after conversion */ private ExtList collectComments(recoder.java.ProgramElement pe) { @@ -386,10 +369,8 @@ private ExtList collectComments(recoder.java.ProgramElement pe) { /** * collects both comments and children of a program element * - * @param pe - * program element - * @return freshly created list of children after conversion and converted - * comments + * @param pe program element + * @return freshly created list of children after conversion and converted comments */ private ExtList collectChildrenAndComments(recoder.java.ProgramElement pe) { ExtList ret = new ExtList(); @@ -404,17 +385,16 @@ private ExtList collectChildrenAndComments(recoder.java.ProgramElement pe) { /** * convert recoder position info to key position info * - * @param se - * the sourcelement to extract from, not null + * @param se the sourcelement to extract from, not null * @return the newly created PositionInfo */ private PositionInfo positionInfo(recoder.java.SourceElement se) { - Position relPos = new Position(se.getRelativePosition().getLine(), se - .getRelativePosition().getColumn()); - Position startPos = new Position(se.getStartPosition().getLine(), - se.getStartPosition().getColumn()); - Position endPos = new Position(se.getEndPosition().getLine(), se - .getEndPosition().getColumn()); + Position relPos = new Position(se.getRelativePosition().getLine(), + se.getRelativePosition().getColumn()); + Position startPos = + new Position(se.getStartPosition().getLine(), se.getStartPosition().getColumn()); + Position endPos = + new Position(se.getEndPosition().getLine(), se.getEndPosition().getColumn()); if ((!inLoopInit)) return new PositionInfo(relPos, startPos, endPos, currentClassURI); else @@ -425,8 +405,7 @@ private PositionInfo positionInfo(recoder.java.SourceElement se) { /** * @return a literal constant representing the value of p_er */ - private Literal getLiteralFor( - recoder.service.ConstantEvaluator.EvaluationResult p_er) { + private Literal getLiteralFor(recoder.service.ConstantEvaluator.EvaluationResult p_er) { switch (p_er.getTypeCode()) { case recoder.service.ConstantEvaluator.BOOLEAN_TYPE: return BooleanLiteral.getBooleanLiteral(p_er.getBoolean()); @@ -447,10 +426,10 @@ private Literal getLiteralFor( case recoder.service.ConstantEvaluator.STRING_TYPE: if (p_er.getString() == null) return NullLiteral.NULL; - return new StringLiteral("\""+p_er.getString()+"\""); + return new StringLiteral("\"" + p_er.getString() + "\""); default: - throw new ConvertException("Don't know how to handle type " - + p_er.getTypeCode() + " of " + p_er); + throw new ConvertException( + "Don't know how to handle type " + p_er.getTypeCode() + " of " + p_er); } } @@ -458,11 +437,9 @@ private Literal getLiteralFor( /** * extracts all fields out of fielddeclaration * - * @param field - * the FieldDeclaration of which the field specifications have to - * be extracted - * @return a IList the includes all field specifications found int the - * field declaration of the given list + * @param field the FieldDeclaration of which the field specifications have to be extracted + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ private ImmutableList filterField(FieldDeclaration field) { ImmutableList result = ImmutableSLList.nil(); @@ -476,18 +453,15 @@ private ImmutableList filterField(FieldDeclaration field) { /** * retrieves a field with the given name out of the list * - * @param name - * a String with the name of the field to be looked for - * @param fields - * the IList where we have to look for the field + * @param name a String with the name of the field to be looked for + * @param fields the IList where we have to look for the field * @return the program variable of the given name or null if not found */ private ProgramVariable find(String name, ImmutableList fields) { for (Field field1 : fields) { Field field = field1; if (name.equals(field.getName())) { - return (ProgramVariable) ((FieldSpecification) field) - .getProgramVariable(); + return (ProgramVariable) ((FieldSpecification) field).getProgramVariable(); } } return null; @@ -502,14 +476,12 @@ private ProgramVariable find(String name, ImmutableList fields) { * * It iterates over all children, calls convert upon them * - * collect all children, convert them. Create a new instance of the - * corresponding KeY class and call its constructor with the list of - * children. + * collect all children, convert them. Create a new instance of the corresponding KeY class and + * call its constructor with the list of children. * - * @param pe - * the recoder.java.ProgramElement to be converted - * @return the converted de.uka.ilkd.key.java.JavaProgramElement, null if - * there has been an exception + * @param pe the recoder.java.ProgramElement to be converted + * @return the converted de.uka.ilkd.key.java.JavaProgramElement, null if there has been an + * exception */ public ProgramElement convert(recoder.java.JavaProgramElement pe) { ProgramElement result = null; @@ -532,15 +504,18 @@ public ProgramElement convert(recoder.java.JavaProgramElement pe) { final String className = class_.toString().substring(6); final StringBuffer sb = new StringBuffer(className); sb.append('('); - for (Object p: parameter) { + for (Object p : parameter) { sb.append(p.toString()); sb.append(','); } - if (sb.charAt(sb.length()-1)==',') sb.deleteCharAt(sb.length()-1); + if (sb.charAt(sb.length() - 1) == ',') + sb.deleteCharAt(sb.length() - 1); sb.append(')'); final String constructorName = sb.toString(); - LOGGER.debug("recoder2key: invocation of constructor "+constructorName +" failed.", e); - Recoder2KeY.reportError("Invocation of the constructor "+constructorName +" failed", e); + LOGGER.debug("recoder2key: invocation of constructor " + constructorName + " failed.", + e); + Recoder2KeY.reportError("Invocation of the constructor " + constructorName + " failed", + e); throw new Error("unreachable"); // this line is not reachable // because reportError fails under // any circumstances @@ -550,22 +525,24 @@ public ProgramElement convert(recoder.java.JavaProgramElement pe) { /** * gets the KeY-Class related to the recoder one * - * @param recoderClass - * the original Class within recoder + * @param recoderClass the original Class within recoder * @return the related KeY Class - * @throws ConvertException - * for various reasons + * @throws ConvertException for various reasons */ private Class getKeYClass(Class recoderClass) { String className = getKeYName(recoderClass); try { - return Class.forName(className); // Classes are always in this component; ClassLoaderUtil#getClassforName(String) does not need to be used. + return Class.forName(className); // Classes are always in this component; + // ClassLoaderUtil#getClassforName(String) does not + // need to be used. } catch (ClassNotFoundException cnfe) { - LOGGER.debug("There is an AST class " +className + " missing at KeY.", cnfe); - throw new ConvertException("Recoder2KeYConverter could not find a conversion from RecodeR "+recoderClass.getClass()+".\n" - +"Maybe you have added a class to package key.java.recoderext and did not add the equivalent to key.java.expression or its subpackages." - +"\nAt least there is no class named "+className+"." - ,cnfe); + LOGGER.debug("There is an AST class " + className + " missing at KeY.", cnfe); + throw new ConvertException( + "Recoder2KeYConverter could not find a conversion from RecodeR " + + recoderClass.getClass() + ".\n" + + "Maybe you have added a class to package key.java.recoderext and did not add the equivalent to key.java.expression or its subpackages." + + "\nAt least there is no class named " + className + ".", + cnfe); } catch (ExceptionInInitializerError initErr) { LOGGER.debug("recoder2key: Failed initializing class.", initErr); throw new ConvertException("Failed initializing class.", initErr); @@ -578,21 +555,21 @@ private Class getKeYClass(Class re private static int RECODER_PREFIX_LENGTH = "recoder.".length(); /** - * constructs the name of the corresponding KeYClass. - * Expected prefixes are either recoder or ...key.java.recoderext - * @param recoderClass - * Class that is the original recoder + * constructs the name of the corresponding KeYClass. Expected prefixes are either recoder or + * ...key.java.recoderext + * + * @param recoderClass Class that is the original recoder * @return String containing the KeY-Classname */ private String getKeYName(Class recoderClass) { - final String prefix ="de.uka.ilkd.key."; + final String prefix = "de.uka.ilkd.key."; final String recoderClassName = recoderClass.getName(); if (recoderClassName.startsWith("recoder.")) { - return prefix+recoderClassName.substring(RECODER_PREFIX_LENGTH); - } else if (recoderClassName.startsWith(prefix+"java.recoderext.")) { + return prefix + recoderClassName.substring(RECODER_PREFIX_LENGTH); + } else if (recoderClassName.startsWith(prefix + "java.recoderext.")) { return recoderClassName.replaceAll("recoderext\\.", ""); } else { - assert false : "Unexpected class prefix: "+recoderClassName; + assert false : "Unexpected class prefix: " + recoderClassName; return ""; } } @@ -602,18 +579,17 @@ private String getKeYName(Class recod * * Use a cache to only look up classes once. * - * @param recoderClass - * the Class of the recoder AST object + * @param recoderClass the Class of the recoder AST object * @return the Constructor of the right KeY-Class */ - private Constructor getKeYClassConstructor(Class recoderClass) { + private Constructor getKeYClassConstructor( + Class recoderClass) { Constructor result = null; try { result = constructorCache.get(recoderClass); if (result == null) { - result = getKeYClass(recoderClass).getConstructor( - new Class[] { ExtList.class }); + result = getKeYClass(recoderClass).getConstructor(new Class[] { ExtList.class }); constructorCache.put(recoderClass, result); } } catch (NoSuchMethodException nsme) { @@ -627,10 +603,8 @@ private Constructor getKeYClassConstructor(Classkey mapping. * - * @param r - * the recoder element (not null) - * @param k - * the key element (not null) + * @param r the recoder element (not null) + * @param k the key element (not null) */ protected void insertToMap(recoder.ModelElement r, ModelElement k) { @@ -643,14 +617,13 @@ protected void insertToMap(recoder.ModelElement r, ModelElement k) { // ------------------- operators ---------------------- - public Instanceof convert(recoder.java.expression.operator.Instanceof rio) { - return new Instanceof((Expression) callConvert(rio.getExpressionAt(0)), - (TypeReference) callConvert(rio.getTypeReference())); - } + public Instanceof convert(recoder.java.expression.operator.Instanceof rio) { + return new Instanceof((Expression) callConvert(rio.getExpressionAt(0)), + (TypeReference) callConvert(rio.getTypeReference())); + } /** - * converts the recoder.java.expression.operator.NewArray node to the - * KeYDependance + * converts the recoder.java.expression.operator.NewArray node to the KeYDependance */ public NewArray convert(recoder.java.expression.operator.NewArray newArr) { // first we need to collect all children @@ -660,11 +633,10 @@ public NewArray convert(recoder.java.expression.operator.NewArray newArr) { ArrayInitializer arrInit = children.get(ArrayInitializer.class); children.remove(arrInit); - recoder.abstraction.Type javaType = getServiceConfiguration() - .getCrossReferenceSourceInfo().getType(newArr); + recoder.abstraction.Type javaType = + getServiceConfiguration().getCrossReferenceSourceInfo().getType(newArr); - return new NewArray(children, getKeYJavaType(javaType), arrInit, newArr - .getDimensions()); + return new NewArray(children, getKeYJavaType(javaType), arrInit, newArr.getDimensions()); } @@ -683,48 +655,50 @@ public IntLiteral convert(recoder.java.expression.literal.IntLiteral intLit) { } /** convert a recoder BooleanLiteral to a KeY BooleanLiteral */ - public BooleanLiteral convert( - recoder.java.expression.literal.BooleanLiteral booleanLit) { + public BooleanLiteral convert(recoder.java.expression.literal.BooleanLiteral booleanLit) { - // The source code position is very important because a single boolean literal is maybe a complete loop condition and the symbolic execution debugger needs source code position to separate code steps from internal proof steps. For this reason is the usage of the singleton constants not possible. - return booleanLit.getValue() ? - new BooleanLiteral(collectComments(booleanLit), positionInfo(booleanLit), true) : - new BooleanLiteral(collectComments(booleanLit), positionInfo(booleanLit), false); + // The source code position is very important because a single boolean literal is maybe a + // complete loop condition and the symbolic execution debugger needs source code position to + // separate code steps from internal proof steps. For this reason is the usage of the + // singleton constants not possible. + return booleanLit.getValue() + ? new BooleanLiteral(collectComments(booleanLit), positionInfo(booleanLit), true) + : new BooleanLiteral(collectComments(booleanLit), positionInfo(booleanLit), false); } public EmptySetLiteral convert(de.uka.ilkd.key.java.recoderext.adt.EmptySetLiteral e) { - return EmptySetLiteral.LOCSET; + return EmptySetLiteral.LOCSET; } public Singleton convert(de.uka.ilkd.key.java.recoderext.adt.Singleton e) { ExtList children = collectChildren(e); - return new Singleton(children); + return new Singleton(children); } public SetUnion convert(de.uka.ilkd.key.java.recoderext.adt.SetUnion e) { ExtList children = collectChildren(e); - return new SetUnion(children); + return new SetUnion(children); } public Intersect convert(de.uka.ilkd.key.java.recoderext.adt.Intersect e) { ExtList children = collectChildren(e); - return new Intersect(children); + return new Intersect(children); } public SetMinus convert(de.uka.ilkd.key.java.recoderext.adt.SetMinus e) { ExtList children = collectChildren(e); - return new SetMinus(children); + return new SetMinus(children); } public AllFields convert(de.uka.ilkd.key.java.recoderext.adt.AllFields e) { ExtList children = collectChildren(e); - return new AllFields(children); + return new AllFields(children); } public AllObjects convert(de.uka.ilkd.key.java.recoderext.adt.AllObjects e) { ExtList children = collectChildren(e); - return new AllObjects(children); + return new AllObjects(children); } public EmptySeqLiteral convert(de.uka.ilkd.key.java.recoderext.adt.EmptySeqLiteral e) { @@ -733,30 +707,30 @@ public EmptySeqLiteral convert(de.uka.ilkd.key.java.recoderext.adt.EmptySeqLiter public SeqSingleton convert(de.uka.ilkd.key.java.recoderext.adt.SeqSingleton e) { ExtList children = collectChildren(e); - return new SeqSingleton(children); + return new SeqSingleton(children); } public SeqConcat convert(de.uka.ilkd.key.java.recoderext.adt.SeqConcat e) { ExtList children = collectChildren(e); - return new SeqConcat(children); + return new SeqConcat(children); } public SeqSub convert(de.uka.ilkd.key.java.recoderext.adt.SeqSub e) { ExtList children = collectChildren(e); - return new SeqSub(children); + return new SeqSub(children); } - public SeqLength convert(de.uka.ilkd.key.java.recoderext.adt.SeqLength e){ + public SeqLength convert(de.uka.ilkd.key.java.recoderext.adt.SeqLength e) { return new SeqLength(collectChildren(e)); } - public SeqIndexOf convert(de.uka.ilkd.key.java.recoderext.adt.SeqIndexOf e){ - return new SeqIndexOf(collectChildren(e)); + public SeqIndexOf convert(de.uka.ilkd.key.java.recoderext.adt.SeqIndexOf e) { + return new SeqIndexOf(collectChildren(e)); } public SeqReverse convert(de.uka.ilkd.key.java.recoderext.adt.SeqReverse e) { ExtList children = collectChildren(e); - return new SeqReverse(children); + return new SeqReverse(children); } public EmptyMapLiteral convert(de.uka.ilkd.key.java.recoderext.adt.EmptyMapLiteral e) { @@ -764,8 +738,7 @@ public EmptyMapLiteral convert(de.uka.ilkd.key.java.recoderext.adt.EmptyMapLiter } /** - * Resolve the function symbol which is embedded here to its logical - * counterpart. + * Resolve the function symbol which is embedded here to its logical counterpart. */ public DLEmbeddedExpression convert(de.uka.ilkd.key.java.recoderext.EscapeExpression e) { final var PREFIX = "\\dl_DEFAULT_VALUE_"; @@ -773,22 +746,23 @@ public DLEmbeddedExpression convert(de.uka.ilkd.key.java.recoderext.EscapeExpres ExtList children = collectChildren(e); String name = e.getFunctionName(); - if(name.startsWith(PREFIX)) { // handle default value resolution + if (name.startsWith(PREFIX)) { // handle default value resolution String sortName = name.substring(PREFIX.length()).trim(); Sort sort = namespaceSet.sorts().lookup(sortName); - if(sort == null){ + if (sort == null) { throw new ConvertException( - format("Requested to find the default value of an unknown sort '%s'. " + - "Line/Col:%s", sortName, e.getStartPosition())); + format("Requested to find the default value of an unknown sort '%s'. " + + "Line/Col:%s", sortName, e.getStartPosition())); } var doc = sort.getDocumentation(); - if(doc == null){ - throw new ConvertException( - format("Requested to find the default value for the sort '%s', " + - "which does not have a documentary comment. The sort is defined at %s. " + - "Line/Col: %s", sortName, sort.getOrigin(), e.getStartPosition())); + if (doc == null) { + throw new ConvertException(format( + "Requested to find the default value for the sort '%s', " + + "which does not have a documentary comment. The sort is defined at %s. " + + "Line/Col: %s", + sortName, sort.getOrigin(), e.getStartPosition())); } int pos = doc.indexOf(DEFVALUE); @@ -796,31 +770,31 @@ public DLEmbeddedExpression convert(de.uka.ilkd.key.java.recoderext.EscapeExpres int start = doc.indexOf('(', pos) + 1; int closing = doc.indexOf(')', pos); - if(closing<0){ - throw new ConvertException( - format("Forgotten closing parenthesis on @defaultValue annotation for sort '%s' in '%s'", - sortName, sort.getOrigin())); + if (closing < 0) { + throw new ConvertException(format( + "Forgotten closing parenthesis on @defaultValue annotation for sort '%s' in '%s'", + sortName, sort.getOrigin())); } // set this as the function name, as the user had written \dl_XXX name = doc.substring(start, closing); } else { - throw new ConvertException( - format("Could not infer the default value for the given sort '%s'. " + - "The sort found was as '%s' and the sort's documentation is '%s'. " + - "Did you forget @defaultValue(XXX) in the documentation?Line/Col: %s", - sortName, sort, doc, e.getStartPosition())); + throw new ConvertException(format( + "Could not infer the default value for the given sort '%s'. " + + "The sort found was as '%s' and the sort's documentation is '%s'. " + + "Did you forget @defaultValue(XXX) in the documentation?Line/Col: %s", + sortName, sort, doc, e.getStartPosition())); } } Function named = namespaceSet.functions().lookup(new Name(name)); - if(named == null) { + if (named == null) { // TODO provide position information?! - throw new ConvertException( - format("In an embedded DL expression, %s is not a known DL function name. Line/Col:%s", - name, e.getStartPosition())); + throw new ConvertException(format( + "In an embedded DL expression, %s is not a known DL function name. Line/Col:%s", + name, e.getStartPosition())); } DLEmbeddedExpression expression = new DLEmbeddedExpression(named, children); @@ -829,51 +803,51 @@ public DLEmbeddedExpression convert(de.uka.ilkd.key.java.recoderext.EscapeExpres return expression; } - public SeqGet convert(de.uka.ilkd.key.java.recoderext.adt.SeqGet e){ + public SeqGet convert(de.uka.ilkd.key.java.recoderext.adt.SeqGet e) { return new SeqGet(collectChildren(e)); } /** convert a recoder StringLiteral to a KeY StringLiteral */ - public StringLiteral convert( - recoder.java.expression.literal.StringLiteral stringLit) { - return new StringLiteral(collectComments(stringLit), stringLit - .getValue()); + public StringLiteral convert(recoder.java.expression.literal.StringLiteral stringLit) { + return new StringLiteral(collectComments(stringLit), stringLit.getValue()); } /** convert a recoder DoubleLiteral to a KeY DoubleLiteral */ - public DoubleLiteral convert( - recoder.java.expression.literal.DoubleLiteral doubleLit) { - return new DoubleLiteral(collectComments(doubleLit), doubleLit - .getValue()); + public DoubleLiteral convert(recoder.java.expression.literal.DoubleLiteral doubleLit) { + return new DoubleLiteral(collectComments(doubleLit), doubleLit.getValue()); } /** convert a recoder FloatLiteral to a KeY FloatLiteral */ - public FloatLiteral convert( - recoder.java.expression.literal.FloatLiteral floatLit) { + public FloatLiteral convert(recoder.java.expression.literal.FloatLiteral floatLit) { return new FloatLiteral(collectComments(floatLit), floatLit.getValue()); } - /** convert a recoder LongLiteral to a KeY LongLiteral + /** + * convert a recoder LongLiteral to a KeY LongLiteral + * * @param longLit the LongLiteral from recoder - * @return a KeY LongLiteral (immutable)*/ + * @return a KeY LongLiteral (immutable) + */ public LongLiteral convert(recoder.java.expression.literal.LongLiteral longLit) { return new LongLiteral(collectComments(longLit), longLit.getValue()); } - /** convert a recoder CharLiteral to a KeY CharLiteral + /** + * convert a recoder CharLiteral to a KeY CharLiteral + * * @param charLit the CharLiteral from recoder - * @return a KeY CharLiteral (immutable)*/ + * @return a KeY CharLiteral (immutable) + */ public CharLiteral convert(recoder.java.expression.literal.CharLiteral charLit) { return new CharLiteral(collectComments(charLit), charLit.getValue()); } /** convert a recoder NullLiteral to a KeY NullLiteral */ - public NullLiteral convert( - recoder.java.expression.literal.NullLiteral nullLit) { + public NullLiteral convert(recoder.java.expression.literal.NullLiteral nullLit) { - recoder.abstraction.Type javaType = getServiceConfiguration() - .getCrossReferenceSourceInfo().getType(nullLit); + recoder.abstraction.Type javaType = + getServiceConfiguration().getCrossReferenceSourceInfo().getType(nullLit); getKeYJavaType(javaType); // if there are comments to take into consideration @@ -886,18 +860,15 @@ public NullLiteral convert( /** convert a recoder Identifier to a KeY Identifier */ public ProgramElementName convert(recoder.java.Identifier id) { - return VariableNamer.parseName(id.getText(), - collectComments(id).collect(Comment.class)); + return VariableNamer.parseName(id.getText(), collectComments(id).collect(Comment.class)); } public ProgramElementName convert(ImplicitIdentifier id) { - return new ProgramElementName(id.getText(), - collectComments(id).collect(Comment.class)); + return new ProgramElementName(id.getText(), collectComments(id).collect(Comment.class)); } /** convert a recoderext MethodFrameStatement to a KeY MethodFrameStatement */ - public MethodFrame convert( - de.uka.ilkd.key.java.recoderext.MethodCallStatement rmcs) { + public MethodFrame convert(de.uka.ilkd.key.java.recoderext.MethodCallStatement rmcs) { ProgramVariable resVar = null; if (rmcs.getResultVariable() != null) { recoder.java.Expression rvar = rmcs.getResultVariable(); @@ -908,7 +879,7 @@ public MethodFrame convert( resVar = (ProgramVariable) callConvert(rvar); } catch (ClassCastException e) { throw new ConvertException( - "recoder2key: Expression is not a variable reference."); + "recoder2key: Expression is not a variable reference."); } } } @@ -916,23 +887,21 @@ public MethodFrame convert( if (rmcs.getBody() != null) { block = (StatementBlock) callConvert(rmcs.getBody()); } else { - throw new ConvertException("Methodframe statement has no body " + rmcs); + throw new ConvertException("Methodframe statement has no body " + rmcs); } - return new MethodFrame(resVar, convert(rmcs - .getExecutionContext()), block); + return new MethodFrame(resVar, convert(rmcs.getExecutionContext()), block); } /** convert a recoderext MethodBodyStatement to a KeY MethodBodyStatement */ - public MethodBodyStatement convert( - de.uka.ilkd.key.java.recoderext.MethodBodyStatement rmbs) { + public MethodBodyStatement convert(de.uka.ilkd.key.java.recoderext.MethodBodyStatement rmbs) { final TypeReference bodySource = convert(rmbs.getBodySource()); - final IProgramVariable resultVar = rmbs.getResultVariable() != null ? (IProgramVariable) callConvert(rmbs - .getResultVariable()) + final IProgramVariable resultVar = rmbs.getResultVariable() != null + ? (IProgramVariable) callConvert(rmbs.getResultVariable()) : null; - final ReferencePrefix invocationTarget = (ReferencePrefix) callConvert(rmbs - .getReferencePrefix()); + final ReferencePrefix invocationTarget = + (ReferencePrefix) callConvert(rmbs.getReferencePrefix()); final ProgramElementName methodName = convert(rmbs.getMethodName()); final ASTList args = rmbs.getArguments(); @@ -946,23 +915,21 @@ public MethodBodyStatement convert( keyArgs = new Expression[0]; } - final MethodReference mr = new MethodReference(new ImmutableArray( - keyArgs), methodName, invocationTarget); + final MethodReference mr = new MethodReference(new ImmutableArray(keyArgs), + methodName, invocationTarget); return new MethodBodyStatement(bodySource, resultVar, mr); } - public LoopScopeBlock convert( - de.uka.ilkd.key.java.recoderext.LoopScopeBlock lsb) { + public LoopScopeBlock convert(de.uka.ilkd.key.java.recoderext.LoopScopeBlock lsb) { return new LoopScopeBlock((IProgramVariable) callConvert(lsb.getIndexPV()), (StatementBlock) callConvert(lsb.getBody())); } - public MergePointStatement convert( - de.uka.ilkd.key.java.recoderext.MergePointStatement mps) { - final LocationVariable locVar = new LocationVariable( - services.getVariableNamer().getTemporaryNameProposal("x"), - services.getNamespaces().sorts().lookup("boolean")); + public MergePointStatement convert(de.uka.ilkd.key.java.recoderext.MergePointStatement mps) { + final LocationVariable locVar = + new LocationVariable(services.getVariableNamer().getTemporaryNameProposal("x"), + services.getNamespaces().sorts().lookup("boolean")); final Comment[] comments = new Comment[mps.getComments().size()]; for (int i = 0; i < mps.getComments().size(); i++) { @@ -972,11 +939,9 @@ public MergePointStatement convert( return new MergePointStatement(locVar, comments); } - public CatchAllStatement convert( - de.uka.ilkd.key.java.recoderext.CatchAllStatement cas) { - return new CatchAllStatement - ((StatementBlock)callConvert(cas.getStatementAt(0)), - (LocationVariable) callConvert(cas.getVariable())); + public CatchAllStatement convert(de.uka.ilkd.key.java.recoderext.CatchAllStatement cas) { + return new CatchAllStatement((StatementBlock) callConvert(cas.getStatementAt(0)), + (LocationVariable) callConvert(cas.getVariable())); } /** @@ -992,131 +957,104 @@ public JmlAssert convert(de.uka.ilkd.key.java.recoderext.JmlAssert ja) { // ------------------- declaration --------------------- /** convert a recoder ClassDeclaration to a KeY ClassDeclaration */ - public ClassDeclaration convert( - recoder.java.declaration.ClassDeclaration td) { + public ClassDeclaration convert(recoder.java.declaration.ClassDeclaration td) { KeYJavaType kjt = getKeYJavaType(td); ExtList classMembers = collectChildren(td); - ClassDeclaration keYClassDecl - = new ClassDeclaration(classMembers, - new ProgramElementName(makeAdmissibleName(td.getFullName())), - isParsingLibs(), - td.getContainingClassType() != null, - td.getName() == null, - td.getStatementContainer() != null); - // new ProgramElementName(td.getFullName()), isParsingLibs()); + ClassDeclaration keYClassDecl = new ClassDeclaration(classMembers, + new ProgramElementName(makeAdmissibleName(td.getFullName())), isParsingLibs(), + td.getContainingClassType() != null, td.getName() == null, + td.getStatementContainer() != null); + // new ProgramElementName(td.getFullName()), isParsingLibs()); kjt.setJavaType(keYClassDecl); return keYClassDecl; } /** - * convert a recoder EnumDeclaration to a KeY EnumClassDeclaration. Enums - * have already been mapped to classes at an earlier stage + * convert a recoder EnumDeclaration to a KeY EnumClassDeclaration. Enums have already been + * mapped to classes at an earlier stage * * @author m.u. */ - public EnumClassDeclaration convert( - de.uka.ilkd.key.java.recoderext.EnumClassDeclaration td) { + public EnumClassDeclaration convert(de.uka.ilkd.key.java.recoderext.EnumClassDeclaration td) { - KeYJavaType kjt = getKeYJavaType(td); - ExtList classMembers = collectChildren(td); + KeYJavaType kjt = getKeYJavaType(td); + ExtList classMembers = collectChildren(td); - EnumClassDeclaration keyEnumDecl = new EnumClassDeclaration(classMembers, - new ProgramElementName(td.getFullName()), isParsingLibs(), - td.getEnumConstantDeclarations()); + EnumClassDeclaration keyEnumDecl = + new EnumClassDeclaration(classMembers, new ProgramElementName(td.getFullName()), + isParsingLibs(), td.getEnumConstantDeclarations()); - kjt.setJavaType(keyEnumDecl); - return keyEnumDecl; - } + kjt.setJavaType(keyEnumDecl); + return keyEnumDecl; + } - public InterfaceDeclaration convert( - recoder.java.declaration.InterfaceDeclaration td) { + public InterfaceDeclaration convert(recoder.java.declaration.InterfaceDeclaration td) { KeYJavaType kjt = getKeYJavaType(td); ExtList members = collectChildren(td); - InterfaceDeclaration keYInterfaceDecl = new InterfaceDeclaration( - members, new ProgramElementName(td.getFullName()), - isParsingLibs()); + InterfaceDeclaration keYInterfaceDecl = new InterfaceDeclaration(members, + new ProgramElementName(td.getFullName()), isParsingLibs()); kjt.setJavaType(keYInterfaceDecl); return keYInterfaceDecl; } /** - * converts a recoder ParameterDeclaration to a KeY ParameterDeclaration - * (especially the declaration type of its parent is determined and handed - * over) + * converts a recoder ParameterDeclaration to a KeY ParameterDeclaration (especially the + * declaration type of its parent is determined and handed over) */ - public ParameterDeclaration convert( - recoder.java.declaration.ParameterDeclaration pd) { - return new ParameterDeclaration( - collectChildren(pd), + public ParameterDeclaration convert(recoder.java.declaration.ParameterDeclaration pd) { + return new ParameterDeclaration(collectChildren(pd), pd.getASTParent() instanceof recoder.java.declaration.InterfaceDeclaration, pd.isVarArg()); } /** - * convert a recoder FieldDeclaration to a KeY FieldDeclaration (especially - * the declaration type of its parent is determined and handed over) + * convert a recoder FieldDeclaration to a KeY FieldDeclaration (especially the declaration type + * of its parent is determined and handed over) */ - public FieldDeclaration convert( - recoder.java.declaration.FieldDeclaration fd) { - return new FieldDeclaration( - collectChildren(fd), + public FieldDeclaration convert(recoder.java.declaration.FieldDeclaration fd) { + return new FieldDeclaration(collectChildren(fd), fd.getASTParent() instanceof recoder.java.declaration.InterfaceDeclaration); } /** - * convert a recoder ConstructorDeclaration to a KeY IProgramMethod - * (especially the declaration type of its parent is determined and handed - * over) + * convert a recoder ConstructorDeclaration to a KeY IProgramMethod (especially the declaration + * type of its parent is determined and handed over) */ - public IProgramMethod convert( - recoder.java.declaration.ConstructorDeclaration cd) { - ConstructorDeclaration consDecl = new ConstructorDeclaration( - collectChildren(cd), + public IProgramMethod convert(recoder.java.declaration.ConstructorDeclaration cd) { + ConstructorDeclaration consDecl = new ConstructorDeclaration(collectChildren(cd), cd.getASTParent() instanceof recoder.java.declaration.InterfaceDeclaration); - recoder.abstraction.ClassType cont = getServiceConfiguration() - .getCrossReferenceSourceInfo().getContainingClassType( - (recoder.abstraction.Member) cd); + recoder.abstraction.ClassType cont = getServiceConfiguration().getCrossReferenceSourceInfo() + .getContainingClassType((recoder.abstraction.Member) cd); final HeapLDT heapLDT = rec2key.getTypeConverter().getTypeConverter().getHeapLDT(); - Sort heapSort = heapLDT == null - ? Sort.ANY - : heapLDT.targetSort(); + Sort heapSort = heapLDT == null ? Sort.ANY : heapLDT.targetSort(); final KeYJavaType containerKJT = getKeYJavaType(cont); - IProgramMethod result - = new ProgramMethod(consDecl, - containerKJT, - KeYJavaType.VOID_TYPE, - positionInfo(cd), - heapSort, - heapLDT == null ? 1 : heapLDT.getAllHeaps().size() - 1); + IProgramMethod result = new ProgramMethod(consDecl, containerKJT, KeYJavaType.VOID_TYPE, + positionInfo(cd), heapSort, heapLDT == null ? 1 : heapLDT.getAllHeaps().size() - 1); insertToMap(cd, result); return result; } /** - * convert a recoder DefaultConstructor to a KeY IProgramMethod (especially - * the declaration type of its parent is determined and handed over) + * convert a recoder DefaultConstructor to a KeY IProgramMethod (especially the declaration type + * of its parent is determined and handed over) */ public IProgramMethod convert(recoder.abstraction.DefaultConstructor dc) { ExtList children = new ExtList(); children.add(new ProgramElementName(dc.getName())); - ConstructorDeclaration consDecl = new ConstructorDeclaration(children, - dc.getContainingClassType().isInterface()); + ConstructorDeclaration consDecl = + new ConstructorDeclaration(children, dc.getContainingClassType().isInterface()); recoder.abstraction.ClassType cont = dc.getContainingClassType(); final HeapLDT heapLDT = rec2key.getTypeConverter().getTypeConverter().getHeapLDT(); - Sort heapSort = heapLDT == null - ? Sort.ANY - : heapLDT.targetSort(); + Sort heapSort = heapLDT == null ? Sort.ANY : heapLDT.targetSort(); final KeYJavaType containerKJT = getKeYJavaType(cont); - IProgramMethod result = new ProgramMethod(consDecl, - containerKJT, KeYJavaType.VOID_TYPE, - PositionInfo.UNDEFINED, - heapSort, + IProgramMethod result = new ProgramMethod(consDecl, containerKJT, KeYJavaType.VOID_TYPE, + PositionInfo.UNDEFINED, heapSort, heapLDT == null ? 1 : heapLDT.getAllHeaps().size() - 1); insertToMap(dc, result); return result; @@ -1129,12 +1067,10 @@ public TypeCast convert(recoder.java.expression.operator.TypeCast c) { } /** - * converts a SpecialConstructorReference. Special handling because the - * initializing Expressions and the ReferencePrefix accessPath might not be - * disjunct. + * converts a SpecialConstructorReference. Special handling because the initializing Expressions + * and the ReferencePrefix accessPath might not be disjunct. */ - public SuperConstructorReference convert( - recoder.java.reference.SuperConstructorReference scr) { + public SuperConstructorReference convert(recoder.java.reference.SuperConstructorReference scr) { ExtList children = collectChildren(scr); ReferencePrefix prefix = null; @@ -1147,8 +1083,8 @@ public SuperConstructorReference convert( } /** - * Convert a this referene. Special handling because the initializing - * Expressions and the ReferencePrefix accessPath might not be disjunct. + * Convert a this referene. Special handling because the initializing Expressions and the + * ReferencePrefix accessPath might not be disjunct. */ public ThisReference convert(recoder.java.reference.ThisReference tr) { @@ -1164,8 +1100,8 @@ public ThisReference convert(recoder.java.reference.ThisReference tr) { } /** - * Convert a super referene. Special handling because the initializing - * Expressions and the ReferencePrefix accessPath might not be disjunct. + * Convert a super referene. Special handling because the initializing Expressions and the + * ReferencePrefix accessPath might not be disjunct. */ public SuperReference convert(recoder.java.reference.SuperReference sr) { @@ -1180,26 +1116,24 @@ public SuperReference convert(recoder.java.reference.SuperReference sr) { } /** - * convert a recoder VariableSpecification to a KeY VariableSpecification - * (checks dimension and hands it over and insert in hashmap) + * convert a recoder VariableSpecification to a KeY VariableSpecification (checks dimension and + * hands it over and insert in hashmap) */ public VariableSpecification convert( recoder.java.declaration.VariableSpecification recoderVarSpec) { - VariableSpecification varSpec = (VariableSpecification) getMapping() - .toKeY(recoderVarSpec); + VariableSpecification varSpec = (VariableSpecification) getMapping().toKeY(recoderVarSpec); if (varSpec == null) { - recoder.abstraction.Type recoderType = (getServiceConfiguration() - .getSourceInfo()).getType(recoderVarSpec); + recoder.abstraction.Type recoderType = + (getServiceConfiguration().getSourceInfo()).getType(recoderVarSpec); - final ProgramElementName name = VariableNamer - .parseName(makeAdmissibleName(recoderVarSpec.getName())); - final ProgramVariable pv = new LocationVariable(name, - getKeYJavaType(recoderType), recoderVarSpec.isFinal()); - varSpec = new VariableSpecification( - collectChildren(recoderVarSpec), pv, recoderVarSpec - .getDimensions(), pv.getKeYJavaType()); + final ProgramElementName name = + VariableNamer.parseName(makeAdmissibleName(recoderVarSpec.getName())); + final ProgramVariable pv = new LocationVariable(name, getKeYJavaType(recoderType), + recoderVarSpec.isFinal()); + varSpec = new VariableSpecification(collectChildren(recoderVarSpec), pv, + recoderVarSpec.getDimensions(), pv.getKeYJavaType()); insertToMap(recoderVarSpec, varSpec); } @@ -1207,8 +1141,8 @@ public VariableSpecification convert( } /** - * convert a recoder MethodDeclaration to a KeY IProgramMethod (especially - * the declaration type of its parent is determined and handed over) + * convert a recoder MethodDeclaration to a KeY IProgramMethod (especially the declaration type + * of its parent is determined and handed over) */ public IProgramMethod convert(recoder.java.declaration.MethodDeclaration md) { IProgramMethod result = null; @@ -1226,46 +1160,38 @@ public IProgramMethod convert(recoder.java.declaration.MethodDeclaration md) { methodsDeclaring.put(md, result); if (!getMapping().mapped(md)) { - //If the method is 'void', the 'void' type reference - //gets lost in translation: the KeY AST uses "null" instead of - //it. However, the type reference may have attached JML comments - //(in particular, with the "helper" keyword) that we must keep. + // If the method is 'void', the 'void' type reference + // gets lost in translation: the KeY AST uses "null" instead of + // it. However, the type reference may have attached JML comments + // (in particular, with the "helper" keyword) that we must keep. Comment[] voidComments = null; - if(md.getTypeReference() != null - && md.getTypeReference().getName().equals("void")) { - final ASTList trComs - = md.getTypeReference().getComments(); - if(trComs != null) { - voidComments = new Comment[trComs.size()]; - for(int i = 0; i < voidComments.length; i++) { - voidComments[i] = convert(trComs.get(i)); - } - } + if (md.getTypeReference() != null && md.getTypeReference().getName().equals("void")) { + final ASTList trComs = md.getTypeReference().getComments(); + if (trComs != null) { + voidComments = new Comment[trComs.size()]; + for (int i = 0; i < voidComments.length; i++) { + voidComments[i] = convert(trComs.get(i)); + } + } } - final MethodDeclaration methDecl - = new MethodDeclaration( - collectChildren(md), + final MethodDeclaration methDecl = new MethodDeclaration(collectChildren(md), md.getASTParent() instanceof recoder.java.declaration.InterfaceDeclaration, voidComments); - recoder.abstraction.ClassType cont - = getServiceConfiguration().getCrossReferenceSourceInfo() - .getContainingClassType((recoder.abstraction.Member) md); + recoder.abstraction.ClassType cont = + getServiceConfiguration().getCrossReferenceSourceInfo() + .getContainingClassType((recoder.abstraction.Member) md); final HeapLDT heapLDT = rec2key.getTypeConverter().getTypeConverter().getHeapLDT(); - Sort heapSort = heapLDT == null - ? Sort.ANY - : heapLDT.targetSort(); + Sort heapSort = heapLDT == null ? Sort.ANY : heapLDT.targetSort(); final KeYJavaType containerType = getKeYJavaType(cont); assert containerType != null; final Type returnType = md.getReturnType(); // may be null for a void method - final KeYJavaType returnKJT = returnType==null? KeYJavaType.VOID_TYPE : getKeYJavaType(returnType); - result = new ProgramMethod(methDecl, - containerType, - returnKJT, positionInfo(md), - heapSort, - heapLDT == null ? 1 : heapLDT.getAllHeaps().size() - 1); + final KeYJavaType returnKJT = + returnType == null ? KeYJavaType.VOID_TYPE : getKeYJavaType(returnType); + result = new ProgramMethod(methDecl, containerType, returnKJT, positionInfo(md), + heapSort, heapLDT == null ? 1 : heapLDT.getAllHeaps().size() - 1); insertToMap(md, result); } @@ -1275,22 +1201,20 @@ public IProgramMethod convert(recoder.java.declaration.MethodDeclaration md) { } /** - * convert a recoder FieldSpecification to a KeY FieldSpecification (checks - * dimension and hands it over and insert in hash map) + * convert a recoder FieldSpecification to a KeY FieldSpecification (checks dimension and hands + * it over and insert in hash map) */ - public FieldSpecification convert( - recoder.java.declaration.FieldSpecification recoderVarSpec) { + public FieldSpecification convert(recoder.java.declaration.FieldSpecification recoderVarSpec) { if (recoderVarSpec == null) { // %%%%%%%%%%%%% return new FieldSpecification(); } - FieldSpecification varSpec = (FieldSpecification) getMapping().toKeY( - recoderVarSpec); + FieldSpecification varSpec = (FieldSpecification) getMapping().toKeY(recoderVarSpec); if (varSpec == null) { - recoder.abstraction.Type recoderType = (getServiceConfiguration() - .getSourceInfo()).getType(recoderVarSpec); + recoder.abstraction.Type recoderType = + (getServiceConfiguration().getSourceInfo()).getType(recoderVarSpec); ProgramVariable pv = getProgramVariableForFieldSpecification(recoderVarSpec); @@ -1298,12 +1222,10 @@ public FieldSpecification convert( // the modelled field is an implicit one, we have to handle this // one // explicit - varSpec = new ImplicitFieldSpecification(pv, - getKeYJavaType(recoderType)); + varSpec = new ImplicitFieldSpecification(pv, getKeYJavaType(recoderType)); } else { - varSpec = new FieldSpecification( - collectChildren(recoderVarSpec), pv, recoderVarSpec - .getDimensions(), getKeYJavaType(recoderType)); + varSpec = new FieldSpecification(collectChildren(recoderVarSpec), pv, + recoderVarSpec.getDimensions(), getKeYJavaType(recoderType)); } insertToMap(recoderVarSpec, varSpec); } @@ -1321,27 +1243,27 @@ private ProgramVariable getProgramVariableForFieldSpecification( return null; } - ProgramVariable pv = fieldSpecificationMapping - .get(recoderVarSpec); + ProgramVariable pv = fieldSpecificationMapping.get(recoderVarSpec); if (pv == null) { - VariableSpecification varSpec = (VariableSpecification) getMapping() - .toKeY(recoderVarSpec); + VariableSpecification varSpec = + (VariableSpecification) getMapping().toKeY(recoderVarSpec); if (varSpec == null) { - recoder.abstraction.Type recoderType = (getServiceConfiguration() - .getSourceInfo()).getType(recoderVarSpec); - final ClassType recContainingClassType = recoderVarSpec - .getContainingClassType(); - final ProgramElementName pen = new ProgramElementName( - makeAdmissibleName(recoderVarSpec.getName()), - makeAdmissibleName(recContainingClassType.getFullName())); + recoder.abstraction.Type recoderType = + (getServiceConfiguration().getSourceInfo()).getType(recoderVarSpec); + final ClassType recContainingClassType = recoderVarSpec.getContainingClassType(); + final ProgramElementName pen = + new ProgramElementName(makeAdmissibleName(recoderVarSpec.getName()), + makeAdmissibleName(recContainingClassType.getFullName())); - final Literal compileTimeConstant = getCompileTimeConstantInitializer(recoderVarSpec); + final Literal compileTimeConstant = + getCompileTimeConstantInitializer(recoderVarSpec); boolean isModel = false; boolean isFinal = recoderVarSpec.isFinal(); - for(recoder.java.declaration.Modifier mod : recoderVarSpec.getParent().getModifiers()) { - if(mod instanceof de.uka.ilkd.key.java.recoderext.Model) { + for (recoder.java.declaration.Modifier mod : recoderVarSpec.getParent() + .getModifiers()) { + if (mod instanceof de.uka.ilkd.key.java.recoderext.Model) { isModel = true; break; } @@ -1349,13 +1271,12 @@ private ProgramVariable getProgramVariableForFieldSpecification( if (compileTimeConstant == null) { pv = new LocationVariable(pen, getKeYJavaType(recoderType), - getKeYJavaType(recContainingClassType), - recoderVarSpec.isStatic(), + getKeYJavaType(recContainingClassType), recoderVarSpec.isStatic(), isModel, false, isFinal); } else { pv = new ProgramConstant(pen, getKeYJavaType(recoderType), - getKeYJavaType(recContainingClassType), - recoderVarSpec.isStatic(), compileTimeConstant); + getKeYJavaType(recContainingClassType), recoderVarSpec.isStatic(), + compileTimeConstant); } } else { pv = (ProgramVariable) varSpec.getProgramVariable(); @@ -1371,8 +1292,8 @@ private ProgramVariable getProgramVariableForFieldSpecification( * {@link #getProgramVariableForFieldSpecification(recoder.java.declaration.FieldSpecification)}. * * @return a literal constant representing the value of the initializer of - * recoderVarSpec, if the variable is a compile-time - * constant, and null otherwise + * recoderVarSpec, if the variable is a compile-time constant, and + * null otherwise */ private Literal getCompileTimeConstantInitializer( recoder.java.declaration.FieldSpecification recoderVarSpec) { @@ -1384,13 +1305,14 @@ private Literal getCompileTimeConstantInitializer( recoder.java.Expression init = recoderVarSpec.getInitializer(); if (init != null) { - recoder.service.ConstantEvaluator ce = new recoder.service.DefaultConstantEvaluator( - getServiceConfiguration()); - recoder.service.ConstantEvaluator.EvaluationResult er = new recoder.service.ConstantEvaluator.EvaluationResult(); + recoder.service.ConstantEvaluator ce = + new recoder.service.DefaultConstantEvaluator(getServiceConfiguration()); + recoder.service.ConstantEvaluator.EvaluationResult er = + new recoder.service.ConstantEvaluator.EvaluationResult(); try { - if (ce.isCompileTimeConstant(init, er)) - return getLiteralFor(er); + if (ce.isCompileTimeConstant(init, er)) + return getLiteralFor(er); } catch (NumberFormatException t) { } catch (java.lang.ArithmeticException t) { } @@ -1400,8 +1322,7 @@ private Literal getCompileTimeConstantInitializer( } /** - * convert a recoder TypeReference to a KeY TypeReference (checks dimension - * and hands it over) + * convert a recoder TypeReference to a KeY TypeReference (checks dimension and hands it over) */ public TypeReference convert(recoder.java.reference.TypeReference tr) { @@ -1418,22 +1339,19 @@ public TypeReference convert(recoder.java.reference.TypeReference tr) { } /** - * if an UncollatedReferenceQualifier appears throw a ConvertExceception - * because these qualifiers have to be resolved by running the - * CrossReferencer + * if an UncollatedReferenceQualifier appears throw a ConvertExceception because these + * qualifiers have to be resolved by running the CrossReferencer */ - public ProgramElement convert( - recoder.java.reference.UncollatedReferenceQualifier urq) { - recoder.java.ProgramElement pe = getServiceConfiguration() - .getCrossReferenceSourceInfo().resolveURQ(urq); - if (pe != null - && !(pe instanceof recoder.java.reference.UncollatedReferenceQualifier)) { + public ProgramElement convert(recoder.java.reference.UncollatedReferenceQualifier urq) { + recoder.java.ProgramElement pe = + getServiceConfiguration().getCrossReferenceSourceInfo().resolveURQ(urq); + if (pe != null && !(pe instanceof recoder.java.reference.UncollatedReferenceQualifier)) { return (ProgramElement) callConvert(pe); } - throw new PosConvertException("recoder2key: Qualifier " + urq.getName() - + " not resolvable.", urq.getFirstElement().getStartPosition() - .getLine(), urq.getFirstElement().getStartPosition() - .getColumn() - 1); + throw new PosConvertException( + "recoder2key: Qualifier " + urq.getName() + " not resolvable.", + urq.getFirstElement().getStartPosition().getLine(), + urq.getFirstElement().getStartPosition().getColumn() - 1); } /** @@ -1441,18 +1359,15 @@ public ProgramElement convert( */ private recoder.java.declaration.VariableSpecification getRecoderVarSpec( recoder.java.reference.VariableReference vr) { - return getServiceConfiguration().getSourceInfo() - .getVariableSpecification( - getServiceConfiguration().getSourceInfo().getVariable( - vr)); + return getServiceConfiguration().getSourceInfo().getVariableSpecification( + getServiceConfiguration().getSourceInfo().getVariable(vr)); } /** - * converts a recoder variable reference. A ProgramVariable is created - * replacing the variable reference. + * converts a recoder variable reference. A ProgramVariable is created replacing the variable + * reference. * - * @param vr - * the recoder variable reference. + * @param vr the recoder variable reference. */ public ProgramVariable convert(recoder.java.reference.VariableReference vr) { @@ -1462,40 +1377,36 @@ public ProgramVariable convert(recoder.java.reference.VariableReference vr) { insertToMap(recoderVarspec, convert(recoderVarspec)); } - return (ProgramVariable) ((VariableSpecification) getMapping().toKeY( - recoderVarspec)).getProgramVariable(); + return (ProgramVariable) ((VariableSpecification) getMapping().toKeY(recoderVarspec)) + .getProgramVariable(); } /** * converts a recoder array length reference to a usual KeY field reference */ - public FieldReference convert( - recoder.java.reference.ArrayLengthReference alr) { + public FieldReference convert(recoder.java.reference.ArrayLengthReference alr) { recoder.abstraction.Type recoderType = getServiceConfiguration() - .getCrossReferenceSourceInfo() - .getType(alr.getReferencePrefix()); - ArrayDeclaration ad = (ArrayDeclaration) getKeYJavaType(recoderType) - .getJavaType(); + .getCrossReferenceSourceInfo().getType(alr.getReferencePrefix()); + ArrayDeclaration ad = (ArrayDeclaration) getKeYJavaType(recoderType).getJavaType(); final ProgramVariable length = find("length", filterField(ad.length())); // the invocation of callConvert should work well as each array // length reference must have a reference prefix (at least this // is what i think) - return new FieldReference(length, (ReferencePrefix) callConvert(alr - .getReferencePrefix())); + return new FieldReference(length, (ReferencePrefix) callConvert(alr.getReferencePrefix())); } /** - * converts a recoder field reference. A ProgramVariable is created - * replacing the field reference. + * converts a recoder field reference. A ProgramVariable is created replacing the field + * reference. * - * @param fr - * the recoder field reference. + * @param fr the recoder field reference. */ public Expression convert(recoder.java.reference.FieldReference fr) { ProgramVariable pv; - recoder.java.declaration.FieldSpecification recoderVarSpec = (recoder.java.declaration.FieldSpecification) getRecoderVarSpec(fr); + recoder.java.declaration.FieldSpecification recoderVarSpec = + (recoder.java.declaration.FieldSpecification) getRecoderVarSpec(fr); ReferencePrefix prefix = null; @@ -1505,18 +1416,21 @@ public Expression convert(recoder.java.reference.FieldReference fr) { if (recoderVarSpec == null) { // null means only bytecode available for this field %%% - recoder.abstraction.Field recField = getServiceConfiguration().getSourceInfo().getField(fr); - recoder.abstraction.Type recoderType = getServiceConfiguration().getByteCodeInfo().getType(recField); - recoder.java.declaration.FieldSpecification fs = new recoder.java.declaration.FieldSpecification( - fr.getIdentifier()); + recoder.abstraction.Field recField = + getServiceConfiguration().getSourceInfo().getField(fr); + recoder.abstraction.Type recoderType = + getServiceConfiguration().getByteCodeInfo().getType(recField); + recoder.java.declaration.FieldSpecification fs = + new recoder.java.declaration.FieldSpecification(fr.getIdentifier()); final boolean isModel = false; // bytecode-only fields are no model fields final boolean isFinal = fs.isFinal(); - pv = new LocationVariable(new ProgramElementName(makeAdmissibleName(fs.getName()), - makeAdmissibleName(recField.getContainingClassType().getFullName())), - getKeYJavaType(recoderType), getKeYJavaType(recField - .getContainingClassType()), recField.isStatic(), isModel, false, isFinal); + pv = new LocationVariable( + new ProgramElementName(makeAdmissibleName(fs.getName()), + makeAdmissibleName(recField.getContainingClassType().getFullName())), + getKeYJavaType(recoderType), getKeYJavaType(recField.getContainingClassType()), + recField.isStatic(), isModel, false, isFinal); insertToMap(fs, new FieldSpecification(pv)); return new FieldReference(pv, prefix); } @@ -1538,17 +1452,14 @@ public Expression convert(recoder.java.reference.FieldReference fr) { } /** - * converts a recoder method reference. A - * de.uka.ilkd.key.logic.op.ProgramMethod is created replacing the method - * reference. + * converts a recoder method reference. A de.uka.ilkd.key.logic.op.ProgramMethod is created + * replacing the method reference. * - * @param mr - * the recoder method reference. + * @param mr the recoder method reference. * @return the Method the KeY Dependance */ public MethodReference convert(recoder.java.reference.MethodReference mr) { - recoder.service.SourceInfo sourceInfo = getServiceConfiguration() - .getSourceInfo(); + recoder.service.SourceInfo sourceInfo = getServiceConfiguration().getSourceInfo(); recoder.abstraction.Method method = sourceInfo.getMethod(mr); final IProgramMethod pm; @@ -1559,12 +1470,15 @@ public MethodReference convert(recoder.java.reference.MethodReference mr) { final URI oldCurrent = currentClassURI; recoder.io.DataLocation loc = null; - TypeDeclaration td = ((recoder.java.declaration.MethodDeclaration) method).getMemberParent(); + TypeDeclaration td = + ((recoder.java.declaration.MethodDeclaration) method).getMemberParent(); NonTerminalProgramElement tdc = td.getParent(); while (tdc != null && !(tdc instanceof recoder.java.CompilationUnit)) { - tdc = tdc.getASTParent(); + tdc = tdc.getASTParent(); } - loc = tdc instanceof recoder.java.CompilationUnit ? ((recoder.java.CompilationUnit)tdc).getOriginalDataLocation() : null; + loc = tdc instanceof recoder.java.CompilationUnit + ? ((recoder.java.CompilationUnit) tdc).getOriginalDataLocation() + : null; currentClassURI = MiscTools.extractURI(loc); pm = convert((recoder.java.declaration.MethodDeclaration) method); @@ -1588,16 +1502,15 @@ public MethodReference convert(recoder.java.reference.MethodReference mr) { } return new MethodReference(children, - pm == null ? new ProgramElementName(mr.getName()) : pm - .getProgramElementName(), prefix, positionInfo(mr), - (String)null); + pm == null ? new ProgramElementName(mr.getName()) : pm.getProgramElementName(), + prefix, positionInfo(mr), (String) null); } // --------------Special treatment because of ambiguities ---------- /** - * convert a labeled statement. Remove the label from the set of children - * and pass it separately. + * convert a labeled statement. Remove the label from the set of children and pass it + * separately. */ public LabeledStatement convert(recoder.java.statement.LabeledStatement l) { ExtList children = collectChildren(l); @@ -1613,55 +1526,51 @@ public LabeledStatement convert(recoder.java.statement.LabeledStatement l) { /** * converts a For. * - * @param f - * the For of recoder + * @param f the For of recoder * @return the For of KeY */ public For convert(recoder.java.statement.For f) { - return new For(convertLoopInitializers(f), convertGuard(f), - convertUpdates(f), convertBody(f), collectComments(f), - positionInfo(f)); + return new For(convertLoopInitializers(f), convertGuard(f), convertUpdates(f), + convertBody(f), collectComments(f), positionInfo(f)); } - public AnnotationUseSpecification convert(recoder.java.declaration.AnnotationUseSpecification aus){ + public AnnotationUseSpecification convert( + recoder.java.declaration.AnnotationUseSpecification aus) { return new AnnotationUseSpecification((TypeReference) callConvert(aus.getTypeReference())); } /** * converts a java5-enhanced-for. * - * @param f - * the EnhancedFor of recoder + * @param f the EnhancedFor of recoder * @return the EnhancedFor of KeY */ - public EnhancedFor convert(recoder.java.statement.EnhancedFor f) { - return new EnhancedFor(convertLoopInitializers(f), convertGuard(f), - convertBody(f),collectComments(f),positionInfo(f)); - } + public EnhancedFor convert(recoder.java.statement.EnhancedFor f) { + return new EnhancedFor(convertLoopInitializers(f), convertGuard(f), convertBody(f), + collectComments(f), positionInfo(f)); + } /** * converts a While. * - * @param w - * the While of recoder + * @param w the While of recoder * @return the While of KeY */ public While convert(recoder.java.statement.While w) { - return new While(convertGuard(w).getExpression(), convertBody(w), - positionInfo(w), collectComments(w)); + return new While(convertGuard(w).getExpression(), convertBody(w), positionInfo(w), + collectComments(w)); } /** * converts a Do. * - * @param d - * the Do of recoder + * @param d the Do of recoder * @return the Do of KeY */ public Do convert(recoder.java.statement.Do d) { - return new Do(convertGuard(d).getExpression(), convertBody(d), - collectComments(d), positionInfo(d)); + return new Do(convertGuard(d).getExpression(), convertBody(d), collectComments(d), + positionInfo(d)); } /** @@ -1704,22 +1613,18 @@ public ForUpdates convertUpdates(recoder.java.statement.LoopStatement ls) { } /** - * helper for convert(x) with x a LoopStatement. Converts the loop - * initializers of x. + * helper for convert(x) with x a LoopStatement. Converts the loop initializers of x. */ - public LoopInit convertLoopInitializers( - recoder.java.statement.LoopStatement ls) { + public LoopInit convertLoopInitializers(recoder.java.statement.LoopStatement ls) { final LoopInit loopInit; ASTList initializers = ls.getInitializers(); if (initializers != null) { - final LoopInitializer[] result = new LoopInitializer[initializers - .size()]; + final LoopInitializer[] result = new LoopInitializer[initializers.size()]; for (int i = 0, sz = initializers.size(); i < sz; i++) { inLoopInit = true; - result[i] = (LoopInitializer) callConvert(initializers - .get(i)); + result[i] = (LoopInitializer) callConvert(initializers.get(i)); inLoopInit = false; } loopInit = new LoopInit(result); @@ -1730,8 +1635,8 @@ public LoopInit convertLoopInitializers( } /** - * converts an ArrayReference. Special handling because the initializing - * Expressions and the ReferencePrefix accessPath might not be disjunct. + * converts an ArrayReference. Special handling because the initializing Expressions and the + * ReferencePrefix accessPath might not be disjunct. */ public ArrayReference convert(recoder.java.reference.ArrayReference ar) { ExtList children = collectChildren(ar); @@ -1753,13 +1658,12 @@ public Assert convert(recoder.java.statement.Assert a) { } else { message = null; } - return new Assert((Expression) callConvert(a.getCondition()), message, - positionInfo(a)); + return new Assert((Expression) callConvert(a.getCondition()), message, positionInfo(a)); } /** - * converts a Case. Special handling because the initializing Expression and - * Statements might not be disjunct. + * converts a Case. Special handling because the initializing Expression and Statements might + * not be disjunct. */ public Case convert(recoder.java.statement.Case c) { ExtList children = collectChildren(c); @@ -1773,20 +1677,20 @@ public Case convert(recoder.java.statement.Case c) { } /** - * converts a New. Special handling because the ReferencePrefix and the - * TypeReference might not be disjunct. + * converts a New. Special handling because the ReferencePrefix and the TypeReference might not + * be disjunct. */ public New convert(recoder.java.expression.operator.New n) { ASTList args = n.getArguments(); - final recoder.java.reference.ReferencePrefix rp = n - .getReferencePrefix(); - recoder.service.CrossReferenceSourceInfo si = getServiceConfiguration().getCrossReferenceSourceInfo(); + final recoder.java.reference.ReferencePrefix rp = n.getReferencePrefix(); + recoder.service.CrossReferenceSourceInfo si = + getServiceConfiguration().getCrossReferenceSourceInfo(); final recoder.java.reference.TypeReference tr = n.getTypeReference(); final recoder.java.declaration.ClassDeclaration cd = n.getClassDeclaration(); LinkedList outerVars = null; - if (locClass2finalVar != null){ + if (locClass2finalVar != null) { outerVars = (LinkedList) locClass2finalVar.get(cd); } @@ -1795,24 +1699,27 @@ public New convert(recoder.java.expression.operator.New n) { final Expression[] arguments; if (args != null) { - arguments = new Expression[args.size() + numVars]; - for (int i = 0; i < arguments.length - numVars; i++) { - arguments[i] = (Expression)callConvert(args.get(i)); - } + arguments = new Expression[args.size() + numVars]; + for (int i = 0; i < arguments.length - numVars; i++) { + arguments[i] = (Expression) callConvert(args.get(i)); + } } else { arguments = new Expression[numVars]; } if (outerVars != null) { - for (int i = arguments.length-numVars; i paramTypes = ImmutableSLList.nil(); - for (recoder.java.reference.TypeReference tr : arg.getMethodContext().getParamTypes()) { - TypeReference keyTR = convert(tr); - paramTypes = paramTypes.append(keyTR.getKeYJavaType()); - } + ImmutableList paramTypes = ImmutableSLList.nil(); + for (recoder.java.reference.TypeReference tr : arg.getMethodContext().getParamTypes()) { + TypeReference keyTR = convert(tr); + paramTypes = paramTypes.append(keyTR.getKeYJavaType()); + } - methodContext = jInfo.getProgramMethod(classContext.getKeYJavaType(), - arg.getMethodContext().getMethodName().getText(), - paramTypes, - classContext.getKeYJavaType()); - } + methodContext = jInfo.getProgramMethod(classContext.getKeYJavaType(), + arg.getMethodContext().getMethodName().getText(), paramTypes, + classContext.getKeYJavaType()); + } - ReferencePrefix runtimeInstance = null; - if (arg.getRuntimeInstance() != null) { - runtimeInstance = (ReferencePrefix) callConvert(arg.getRuntimeInstance()); - } + ReferencePrefix runtimeInstance = null; + if (arg.getRuntimeInstance() != null) { + runtimeInstance = (ReferencePrefix) callConvert(arg.getRuntimeInstance()); + } - return new ExecutionContext(classContext, methodContext, runtimeInstance); + return new ExecutionContext(classContext, methodContext, runtimeInstance); } public ThisConstructorReference convert(recoder.java.reference.ThisConstructorReference arg) { @@ -2146,25 +2059,29 @@ public ShiftRightAssignment convert(recoder.java.expression.operator.ShiftRightA return new ShiftRightAssignment(collectChildrenAndComments(arg)); } - public UnsignedShiftRightAssignment convert(recoder.java.expression.operator.UnsignedShiftRightAssignment arg) { + public UnsignedShiftRightAssignment convert( + recoder.java.expression.operator.UnsignedShiftRightAssignment arg) { return new UnsignedShiftRightAssignment(collectChildrenAndComments(arg)); } /** - * Converts the Negative from recoder to the corresponding KeY JavaProgramElement. - * If the minus sign belongs to the (decimal) literal, it is included into the literal - * and the corresponding Int-/LongLiteral is returned. Otherwise a KeY Negative is returned. + * Converts the Negative from recoder to the corresponding KeY JavaProgramElement. If the minus + * sign belongs to the (decimal) literal, it is included into the literal and the corresponding + * Int-/LongLiteral is returned. Otherwise a KeY Negative is returned. + * * @param arg the recoder Negative * @return a KeY Int-/LongLiteral if the minus sign belongs to the literal or a KeY Negative - * otherwise + * otherwise */ public JavaProgramElement convert(recoder.java.expression.operator.Negative arg) { - /* if the minus surrounds a decimal Int-/LongLiteral - * -> minus belongs to the literal, no separate javaUnaryMinus(...) */ + /* + * if the minus surrounds a decimal Int-/LongLiteral -> minus belongs to the literal, no + * separate javaUnaryMinus(...) + */ if (arg.getChildCount() > 0) { if (arg.getChildAt(0) instanceof recoder.java.expression.literal.IntLiteral) { recoder.java.expression.literal.IntLiteral lit = - (recoder.java.expression.literal.IntLiteral)arg.getChildAt(0); + (recoder.java.expression.literal.IntLiteral) arg.getChildAt(0); // decimal: unary minus belongs to the literal if (AbstractIntegerLiteral.representsDecLiteral(lit.getValue())) { // encode the minus into the literal @@ -2172,7 +2089,7 @@ public JavaProgramElement convert(recoder.java.expression.operator.Negative arg) } } else if (arg.getChildAt(0) instanceof recoder.java.expression.literal.LongLiteral) { recoder.java.expression.literal.LongLiteral lit = - (recoder.java.expression.literal.LongLiteral)arg.getChildAt(0); + (recoder.java.expression.literal.LongLiteral) arg.getChildAt(0); // decimal: unary minus belongs to the literal if (AbstractIntegerLiteral.representsDecLiteral(lit.getValue())) { // encode the minus into the literal @@ -2223,7 +2140,7 @@ public EmptyStatement convert(recoder.java.statement.EmptyStatement m) { return new EmptyStatement(collectChildrenAndComments(m)); } - //modifiers + // modifiers public Abstract convert(recoder.java.declaration.modifier.Abstract m) { return new Abstract(collectChildrenAndComments(m)); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYTypeConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYTypeConverter.java index e7dc419d4f2..766c6aa5fc4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYTypeConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Recoder2KeYTypeConverter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.List; @@ -52,11 +55,9 @@ import java.util.List; /** - * provide means to convert recoder types to the corresponding KeY type - * structures. + * provide means to convert recoder types to the corresponding KeY type structures. *

    - * Results are stored in a HashMap so that subsequent queries will retrieve the - * same result. + * Results are stored in a HashMap so that subsequent queries will retrieve the same result. *

    * The main method is: *

    @@ -97,7 +98,8 @@ public class Recoder2KeYTypeConverter { private JavaInfo javaInfo; - public Recoder2KeYTypeConverter(Services services, TypeConverter typeConverter, NamespaceSet namespaces, Recoder2KeY recoder2key) { + public Recoder2KeYTypeConverter(Services services, TypeConverter typeConverter, + NamespaceSet namespaces, Recoder2KeY recoder2key) { super(); this.typeConverter = typeConverter; this.namespaces = namespaces; @@ -135,11 +137,10 @@ private Recoder2KeYConverter getRecoder2KeYConverter() { /** * return the corresponding KeY JavaType for a recoder type. *

    - * Return the cached value if present - otherwise create a new type. - * Store this in the cache. + * Return the cached value if present - otherwise create a new type. Store this in the cache. *

    - * This method retrieves the recoder nameinfo and queries it for the - * type for typeName and passes this result to {@link #getKeYJavaType(Type)} + * This method retrieves the recoder nameinfo and queries it for the type for typeName and + * passes this result to {@link #getKeYJavaType(Type)} * * @param typeName name of a type to be converted * @return the KJT for the string representation. @@ -176,10 +177,10 @@ public KeYJavaType getKeYJavaType(recoder.abstraction.Type t) { // create a new KeYJavaType Sort s = null; if (t instanceof recoder.abstraction.PrimitiveType) { - s = typeConverter.getPrimitiveSort(PrimitiveType.getPrimitiveType(t - .getFullName())); + s = typeConverter.getPrimitiveSort(PrimitiveType.getPrimitiveType(t.getFullName())); if (s == null) { - throw new RuntimeException("Cannot assign " + t.getFullName() + " a primitive sort."); + throw new RuntimeException( + "Cannot assign " + t.getFullName() + " a primitive sort."); } addKeYJavaType(t, s); } else if (t instanceof recoder.abstraction.NullType) { @@ -203,8 +204,7 @@ public KeYJavaType getKeYJavaType(recoder.abstraction.Type t) { throw new RuntimeException( "Missing core class: java.lang.Object must always be present"); } - s = createObjectSort(ct, directSuperSorts(ct).add( - objectType.getSort())); + s = createObjectSort(ct, directSuperSorts(ct).add(objectType.getSort())); } else { s = createObjectSort(ct, directSuperSorts(ct)); } @@ -214,8 +214,8 @@ public KeYJavaType getKeYJavaType(recoder.abstraction.Type t) { // the unknown classtype has no modelinfo so surround with null check if (t.getProgramModelInfo() != null) { - List cl = t.getProgramModelInfo().getConstructors( - (recoder.abstraction.ClassType) t); + List cl = + t.getProgramModelInfo().getConstructors((recoder.abstraction.ClassType) t); if (cl.size() == 1 && (cl.get(0) instanceof recoder.abstraction.DefaultConstructor)) { getRecoder2KeYConverter().processDefaultConstructor( @@ -223,8 +223,7 @@ public KeYJavaType getKeYJavaType(recoder.abstraction.Type t) { } } } else if (t instanceof recoder.abstraction.ArrayType) { - recoder.abstraction.Type bt = ((recoder.abstraction.ArrayType) t) - .getBaseType(); + recoder.abstraction.Type bt = ((recoder.abstraction.ArrayType) t).getBaseType(); kjt = getKeYJavaType(bt); @@ -239,11 +238,8 @@ public KeYJavaType getKeYJavaType(recoder.abstraction.Type t) { // I may not use JavaInfo here because the classes may not yet be cached! de.uka.ilkd.key.java.abstraction.Type elemType = kjt.getJavaType(); - s = ArraySort.getArraySort(kjt.getSort(), - elemType, - objectType.getSort(), - cloneableType.getSort(), - serializableType.getSort()); + s = ArraySort.getArraySort(kjt.getSort(), elemType, objectType.getSort(), + cloneableType.getSort(), serializableType.getSort()); addKeYJavaType(t, s); } @@ -260,8 +256,8 @@ private void addKeYJavaType(recoder.abstraction.Type t, Sort s) { type = PrimitiveType.getPrimitiveType(t.getFullName()); result = typeConverter.getKeYJavaType(type); if (result == null) { - LOGGER.debug("create new KeYJavaType for primitive type " - + t + ". This should not happen"); + LOGGER.debug("create new KeYJavaType for primitive type " + t + + ". This should not happen"); result = new KeYJavaType(type, s); } } else if (t instanceof recoder.abstraction.NullType) { @@ -275,15 +271,14 @@ private void addKeYJavaType(recoder.abstraction.Type t, Sort s) { if (namespaces.sorts().lookup(s.name()) == null) { namespaces.sorts().add(s); } - } else if (t == recoder2key.getServiceConfiguration(). - getNameInfo().getUnknownClassType()) { -// result = makeSimpleKeYType((ClassType)t,s); -// //TEMP! -// assert result.getJavaType() != null; + } else if (t == recoder2key.getServiceConfiguration().getNameInfo() + .getUnknownClassType()) { + // result = makeSimpleKeYType((ClassType)t,s); + // //TEMP! + // assert result.getJavaType() != null; } else { LOGGER.debug("recoder2key: unknown type {}", t); - LOGGER.debug("Unknown type: " + t.getClass() + " " - + t.getFullName()); + LOGGER.debug("Unknown type: " + t.getClass() + " " + t.getFullName()); Debug.fail(); } } else { @@ -298,8 +293,8 @@ private void addKeYJavaType(recoder.abstraction.Type t, Sort s) { // to avoid cycles if (t instanceof recoder.abstraction.ArrayType) { result.setJavaType(createArrayType( - getKeYJavaType(((recoder.abstraction.ArrayType) t) - .getBaseType()), lookupInCache(t))); + getKeYJavaType(((recoder.abstraction.ArrayType) t).getBaseType()), + lookupInCache(t))); } // return was never used, so it is removed and method changed to void (mu) @@ -321,12 +316,12 @@ private ImmutableSet directSuperSorts(recoder.abstraction.ClassType classT ImmutableSet ss = DefaultImmutableSet.nil(); for (recoder.abstraction.ClassType aSuper : supers) { ss = ss.add(getKeYJavaType(aSuper).getSort()); - } - - /* ?? - if (classType.getName() == null) { + } - } + /* + * ?? if (classType.getName() == null) { + * + * } */ if (ss.isEmpty() && !isObject(classType)) { @@ -336,21 +331,19 @@ private ImmutableSet directSuperSorts(recoder.abstraction.ClassType classT } /** - * is the full name of this type "java.lang.Object" or the short name - * "Object" + * is the full name of this type "java.lang.Object" or the short name "Object" * * @param ct the type to be checked, not null * @return true iff the name is Object */ private boolean isObject(recoder.abstraction.ClassType ct) { - return "java.lang.Object".equals(ct.getFullName()) - || "Object".equals(ct.getName()); + return "java.lang.Object".equals(ct.getFullName()) || "Object".equals(ct.getName()); } /** * create a sort out of a recoder class * - * @param ct classtype to create for, not null + * @param ct classtype to create for, not null * @param supers the set of (direct?) super-sorts * @return a freshly created Sort object */ @@ -361,11 +354,11 @@ private Sort createObjectSort(recoder.abstraction.ClassType ct, ImmutableSet - * creates the field declaration for the public final integer field - * length + * creates the field declaration for the public final integer field length */ private FieldDeclaration createSuperArrayType() { - KeYJavaType integerType = getKeYJavaType(getServiceConfiguration() - .getNameInfo().getIntType()); + KeYJavaType integerType = + getKeYJavaType(getServiceConfiguration().getNameInfo().getIntType()); final KeYJavaType superArrayType = new KeYJavaType(); recoder2key.rec2key().setSuperArrayType(superArrayType); - FieldSpecification specLength = new FieldSpecification( - new LocationVariable(new ProgramElementName("length"), - integerType, - superArrayType, - false, - false, false, true)); - FieldDeclaration f = new FieldDeclaration(new Modifier[]{ - new Public(), new Final()}, new TypeRef(integerType), - new FieldSpecification[]{specLength}, false); + FieldSpecification specLength = + new FieldSpecification(new LocationVariable(new ProgramElementName("length"), + integerType, superArrayType, false, false, false, true)); + FieldDeclaration f = new FieldDeclaration(new Modifier[] { new Public(), new Final() }, + new TypeRef(integerType), new FieldSpecification[] { specLength }, false); superArrayType.setJavaType(new SuperArrayDeclaration(f)); return f; } @@ -438,25 +425,22 @@ private FieldDeclaration createSuperArrayType() { /** * Adds several implicit fields and methods to given list of members. * - * @param members an ExtList with the members of parent - * @param parent the KeYJavaType of the array to be enriched by its implicit - * members + * @param members an ExtList with the members of parent + * @param parent the KeYJavaType of the array to be enriched by its implicit members * @param baseType the KeYJavaType of the parent's element type */ - private void addImplicitArrayMembers(ExtList members, KeYJavaType parent, - KeYJavaType baseType, ProgramVariable len) { + private void addImplicitArrayMembers(ExtList members, KeYJavaType parent, KeYJavaType baseType, + ProgramVariable len) { de.uka.ilkd.key.java.abstraction.Type base = baseType.getJavaType(); - int dimension = base instanceof ArrayType ? ((ArrayType) base) - .getDimension() + 1 : 1; - TypeRef parentReference = new TypeRef(new ProgramElementName("" - + parent.getSort().name()), dimension, null, parent); + int dimension = base instanceof ArrayType ? ((ArrayType) base).getDimension() + 1 : 1; + TypeRef parentReference = new TypeRef(new ProgramElementName("" + parent.getSort().name()), + dimension, null, parent); // add methods // the only situation where base can be null is in case of a // reference type - Expression defaultValue = (base != null ? base.getDefaultValue() - : NullLiteral.NULL); + Expression defaultValue = (base != null ? base.getDefaultValue() : NullLiteral.NULL); ImmutableList fields = filterField(members); @@ -466,26 +450,21 @@ private void addImplicitArrayMembers(ExtList members, KeYJavaType parent, initArrayMethodBuilder(); } - final IProgramMethod prepare = - arrayMethodBuilder.getPrepareArrayMethod(parentReference, length, - defaultValue, fields); + final IProgramMethod prepare = arrayMethodBuilder.getPrepareArrayMethod(parentReference, + length, defaultValue, fields); - members.add(arrayMethodBuilder - .getArrayInstanceAllocatorMethod(parentReference)); + members.add(arrayMethodBuilder.getArrayInstanceAllocatorMethod(parentReference)); members.add(prepare); - members.add(arrayMethodBuilder.getCreateArrayHelperMethod( - parentReference, length, fields)); - members.add(arrayMethodBuilder.getCreateArrayMethod(parentReference, - prepare, fields)); + members.add(arrayMethodBuilder.getCreateArrayHelperMethod(parentReference, length, fields)); + members.add(arrayMethodBuilder.getCreateArrayMethod(parentReference, prepare, fields)); } /** * extracts all fields out of fielddeclaration * - * @param field the FieldDeclaration of which the field specifications have to - * be extracted - * @return a IList the includes all field specifications found int the - * field declaration of the given list + * @param field the FieldDeclaration of which the field specifications have to be extracted + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ private ImmutableList filterField(FieldDeclaration field) { ImmutableList result = ImmutableSLList.nil(); @@ -497,12 +476,12 @@ private ImmutableList filterField(FieldDeclaration field) { } /** - * extracts all field specifications out of the given list. Therefore it - * descends into field declarations. + * extracts all field specifications out of the given list. Therefore it descends into field + * declarations. * * @param list the ExtList with the members of a type declaration - * @return a IList the includes all field specifications found int the - * field declaration of the given list + * @return a IList the includes all field specifications found int the field declaration + * of the given list */ private ImmutableList filterField(ExtList list) { ImmutableList result = ImmutableSLList.nil(); @@ -516,19 +495,14 @@ private ImmutableList filterField(ExtList list) { } private void initArrayMethodBuilder() { - final KeYJavaType integerType = getKeYJavaType(getServiceConfiguration() - .getNameInfo().getIntType()); + final KeYJavaType integerType = + getKeYJavaType(getServiceConfiguration().getNameInfo().getIntType()); final KeYJavaType objectType = javaInfo.getJavaLangObject(); final HeapLDT heapLDT = typeConverter.getHeapLDT(); - Sort heapSort = heapLDT == null - ? Sort.ANY - : heapLDT.targetSort(); + Sort heapSort = heapLDT == null ? Sort.ANY : heapLDT.targetSort(); int heapCount = (heapLDT == null) ? 1 : (heapLDT.getAllHeaps().size() - 1); - arrayMethodBuilder - = new CreateArrayMethodBuilder(integerType, - objectType, - heapSort, - heapCount); + arrayMethodBuilder = + new CreateArrayMethodBuilder(integerType, objectType, heapSort, heapCount); } public TypeConverter getTypeConverter() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Reference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Reference.java index a5ef8cdb484..2ce1322c9d1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Reference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Reference.java @@ -1,12 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * References are uses of names, variables or members. - * They can have a name (such as TypeReferences) or be - * anonymous (such as ArrayReference). - * taken from COMPOST and changed to achieve an immutable structure + * References are uses of names, variables or members. They can have a name (such as TypeReferences) + * or be anonymous (such as ArrayReference). taken from COMPOST and changed to achieve an immutable + * structure */ public interface Reference extends ProgramElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaJavaReader.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaJavaReader.java index a2a5c891992..dcbee189c07 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaJavaReader.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaJavaReader.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import de.uka.ilkd.key.logic.Namespace; @@ -6,4 +9,4 @@ public interface SchemaJavaReader extends JavaReader { void setSVNamespace(Namespace ns); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeY.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeY.java index e71d13d59bf..89609513175 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeY.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeY.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.BufferedReader; @@ -49,9 +52,8 @@ protected Recoder2KeYConverter makeConverter(Services services, NamespaceSet nss } /** - * returns the hashmap of a concrete RecodeR class to the constructor of its - * corresponding KeY class. Speeds up reflection. Attention must be - * overwritten by subclasses! + * returns the hashmap of a concrete RecodeR class to the constructor of its corresponding KeY + * class. Speeds up reflection. Attention must be overwritten by subclasses! */ protected HashMap getKeYClassConstructorCache() { return recClass2schemakeyClassCons; @@ -67,30 +69,27 @@ public void setSVNamespace(Namespace svns) { /** * creates an empty RECODER compilation unit - * + * * @return the recoder.java.CompilationUnit */ public Context createEmptyContext() { return new Context(schemaServConf, new recoder.java.CompilationUnit(), schemaServConf.getProgramFactory().createClassDeclaration(null, - new ImplicitIdentifier(""), null, - null, null)); + new ImplicitIdentifier(""), null, null, null)); } /** * wraps a RECODER ClassDeclaration in a compilation unit - * - * @param classDecl - * the recoder.java.ClassDeclaration to wrap - * @param context - * the Context containing the recoder.java.CompilationUnit where the class is wrapped + * + * @param classDecl the recoder.java.ClassDeclaration to wrap + * @param context the Context containing the recoder.java.CompilationUnit where the class is + * wrapped * @return the enclosing recoder.java.CompilationUnit */ protected recoder.java.CompilationUnit embedClass( recoder.java.declaration.ClassDeclaration classDecl, Context context) { - recoder.java.CompilationUnit cUnit = context - .getCompilationUnitContext(); + recoder.java.CompilationUnit cUnit = context.getCompilationUnitContext(); // add class to compilation unit ASTList typeDecls = cUnit.getDeclarations(); @@ -112,56 +111,50 @@ protected recoder.java.CompilationUnit embedClass( } /** - * 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 - * recoder.java.CompilationUnit in which the block has to be - * interpreted + * 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 recoder.java.CompilationUnit in which the block has to be interpreted * @return the parsed and resolved recoder statement block */ - protected recoder.java.StatementBlock recoderBlock(String block, - Context context) { + protected recoder.java.StatementBlock recoderBlock(String block, Context context) { recoder.java.StatementBlock bl = null; - SchemaJavaProgramFactory factory = (SchemaJavaProgramFactory) schemaServConf - .getProgramFactory(); + SchemaJavaProgramFactory factory = + (SchemaJavaProgramFactory) schemaServConf.getProgramFactory(); factory.setSVNamespace(svns); Reader br = null; try { br = new BufferedReader(new StringReader(block)); - try { + try { bl = factory.parseStatementBlock(br); } finally { br.close(); } } catch (recoder.ParserException e) { - LOGGER.debug("readSchemaJavaBlock(Reader,CompilationUnit)" - + " caused the " + "exception:\n", e); + LOGGER.debug( + "readSchemaJavaBlock(Reader,CompilationUnit)" + " caused the " + "exception:\n", + e); throw new ConvertException("Parsing: \n **** BEGIN ****\n " + block - + "\n **** END ****\n failed. Thrown Exception:" - + e, e); + + "\n **** END ****\n failed. Thrown Exception:" + e, e); } catch (IOException ioe) { - LOGGER.debug("readSchemaJavaBlock(Reader,CompilationUnit)" - + " caused the IO exception:", ioe); - throw new ConvertException( - "IO Error when parsing: \n **** BEGIN ****\n " + block - + "\n **** END ****\n failed. Thrown IOException:" - + ioe, ioe); - } - + LOGGER.debug( + "readSchemaJavaBlock(Reader,CompilationUnit)" + " caused the IO exception:", + ioe); + throw new ConvertException("IO Error when parsing: \n **** BEGIN ****\n " + block + + "\n **** END ****\n failed. Thrown IOException:" + ioe, ioe); + } + embedClass(embedMethod(embedBlock(bl), context), context); return bl; } /** - * there is no need to parse special classes in this case, so - * this is empty + * there is no need to parse special classes in this case, so this is empty + * * @see de.uka.ilkd.key.java.Recoder2KeY#parseSpecialClasses() */ - public void parseSpecialClasses() { - } + public void parseSpecialClasses() {} } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeYConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeYConverter.java index b9da3e82e8d..82779997041 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeYConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SchemaRecoder2KeYConverter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.List; @@ -26,11 +29,10 @@ import recoder.list.generic.ASTList; /** - * This is an extension of the usual {@link Recoder2KeYConverter} that supports - * schema variables. + * This is an extension of the usual {@link Recoder2KeYConverter} that supports schema variables. * - * Some entities have to be treated differently, but most conversions are - * handled identically (via the superclass). + * Some entities have to be treated differently, but most conversions are handled identically (via + * the superclass). * * @author MU * @@ -40,58 +42,52 @@ public class SchemaRecoder2KeYConverter extends Recoder2KeYConverter { /** * the type that is used for schema variables types. */ - private static KeYJavaType typeSVType - = new KeYJavaType(PrimitiveType.PROGRAM_SV, ProgramSVSort.TYPE); + private static KeYJavaType typeSVType = + new KeYJavaType(PrimitiveType.PROGRAM_SV, ProgramSVSort.TYPE); /** - * create a new schema-recoder-to-key converter. It must be associated with - * a schema recoder2key. + * create a new schema-recoder-to-key converter. It must be associated with a schema + * recoder2key. * - * @param rec2key - * the object to associate to - * @param namespaceSet - * namespaces to resolve entity names - * @param services - * services to be used + * @param rec2key the object to associate to + * @param namespaceSet namespaces to resolve entity names + * @param services services to be used */ - public SchemaRecoder2KeYConverter(SchemaRecoder2KeY rec2key, Services services, NamespaceSet namespaceSet) { + public SchemaRecoder2KeYConverter(SchemaRecoder2KeY rec2key, Services services, + NamespaceSet namespaceSet) { super(rec2key, services, namespaceSet); } // ------ conversion methods /** - * convert a program meta construct creating a new object corresponding to - * the name. + * convert a program meta construct creating a new object corresponding to the name. * - * If you add a ProgramTransformer to the system you will most propably - * have to register it here. + * If you add a ProgramTransformer to the system you will most propably have to register it + * here. */ - public ProgramTransformer convert( - de.uka.ilkd.key.java.recoderext.RKeYMetaConstruct mc) { + public ProgramTransformer convert(de.uka.ilkd.key.java.recoderext.RKeYMetaConstruct mc) { ExtList list = new ExtList(); String mcName = mc.getName(); list.add(callConvert(mc.getChild())); if ("#switch-to-if".equals(mcName)) { - return new SwitchToIf(list - .get(SchemaVariable.class)); + return new SwitchToIf(list.get(SchemaVariable.class)); } else if ("#unwind-loop".equals(mcName)) { final ProgramSV[] labels = mc.getSV(); - return new UnwindLoop(labels[0], labels[1], list - .get(LoopStatement.class)); + return new UnwindLoop(labels[0], labels[1], list.get(LoopStatement.class)); } else if ("#unpack".equals(mcName)) { return new Unpack(list.get(For.class)); } else if ("#forInitUnfoldTransformer".equals(mcName)) { return new ForInitUnfoldTransformer(list.get(ProgramSV.class)); } else if ("#for-to-while".equals(mcName)) { final ProgramSV[] labels = mc.getSV(); - return new ForToWhile(labels[0], labels[1], - list.get(Statement.class)); + return new ForToWhile(labels[0], labels[1], list.get(Statement.class)); } else if ("#enhancedfor-elim".equals(mcName)) { EnhancedFor efor = list.get(EnhancedFor.class); if (efor == null) { - throw new ConvertException("#enhancedfor-elim requires an enhanced for loop as argument"); + throw new ConvertException( + "#enhancedfor-elim requires an enhanced for loop as argument"); } ProgramSV[] svw = mc.getSV(); ProgramSV execSV = null; @@ -103,11 +99,9 @@ public ProgramTransformer convert( } return new EnhancedForElimination(execSV, list.get(EnhancedFor.class)); } else if ("#do-break".equals(mcName)) { - return new DoBreak(list - .get(LabeledStatement.class)); + return new DoBreak(list.get(LabeledStatement.class)); } else if ("#expand-method-body".equals(mcName)) { - return new ExpandMethodBody(list - .get(SchemaVariable.class)); + return new ExpandMethodBody(list.get(SchemaVariable.class)); } else if ("#method-call".equals(mcName)) { ProgramSV[] svw = mc.getSV(); ProgramSV execSV = null; @@ -120,35 +114,27 @@ public ProgramTransformer convert( execSV = svw[i]; } } - return new MethodCall(execSV, returnSV, list - .get(Expression.class)); + return new MethodCall(execSV, returnSV, list.get(Expression.class)); } else if ("#evaluate-arguments".equals(mcName)) { return new EvaluateArgs(list.get(Expression.class)); } else if ("#constructor-call".equals(mcName)) { - return new ConstructorCall(mc.getFirstSV().getSV(), - list.get(Expression.class)); + return new ConstructorCall(mc.getFirstSV().getSV(), list.get(Expression.class)); } else if ("#special-constructor-call".equals(mcName)) { - return new SpecialConstructorCall(list - .get(Expression.class)); + return new SpecialConstructorCall(list.get(Expression.class)); } else if ("#post-work".equals(mcName)) { return new PostWork(list.get(SchemaVariable.class)); } else if ("#static-initialisation".equals(mcName)) { - return new StaticInitialisation(list - .get(Expression.class)); + return new StaticInitialisation(list.get(Expression.class)); } else if ("#resolve-multiple-var-decl".equals(mcName)) { - return new MultipleVarDecl(list - .get(SchemaVariable.class)); + return new MultipleVarDecl(list.get(SchemaVariable.class)); } else if ("#array-post-declaration".equals(mcName)) { - return new ArrayPostDecl(list - .get(SchemaVariable.class)); + return new ArrayPostDecl(list.get(SchemaVariable.class)); } else if ("#init-array-creation".equals(mcName)) { - return new InitArrayCreation(mc.getFirstSV().getSV(), - list.get(Expression.class)); + return new InitArrayCreation(mc.getFirstSV().getSV(), list.get(Expression.class)); } else if ("#reattachLoopInvariant".equals(mcName)) { return new ReattachLoopInvariant(list.get(LoopStatement.class)); } else { - throw new ConvertException("Program meta construct " - + mc.toString() + " unknown."); + throw new ConvertException("Program meta construct " + mc.toString() + " unknown."); } } @@ -169,8 +155,7 @@ public ProgramTransformer convert( } else if ("#length-reference".equals(mcName)) { return new ArrayLength(list.get(Expression.class)); } else { - throw new ConvertException("Program meta construct " - + mc.toString() + " unknown."); + throw new ConvertException("Program meta construct " + mc.toString() + " unknown."); } } @@ -179,15 +164,13 @@ public ProgramTransformer convert( * * If you have a type meta construct you will have to add it here. */ - public ProgramTransformer convert( - de.uka.ilkd.key.java.recoderext.RKeYMetaConstructType mc) { + public ProgramTransformer convert(de.uka.ilkd.key.java.recoderext.RKeYMetaConstructType mc) { ExtList list = new ExtList(); list.add(callConvert(mc.getChild())); if ("#typeof".equals(mc.getName0())) { return new TypeOf(list.get(Expression.class)); } else { - throw new ConvertException("Program meta construct " - + mc.toString() + " unknown."); + throw new ConvertException("Program meta construct " + mc.toString() + " unknown."); } } @@ -196,14 +179,12 @@ public ProgramTransformer convert( */ public MethodFrame convert(de.uka.ilkd.key.java.recoderext.RMethodCallStatement l) { ProgramVariableSVWrapper svw = l.getVariableSV(); - return new MethodFrame((IProgramVariable) (svw != null ? svw.getSV() - : null), (IExecutionContext) callConvert(l - .getExecutionContext()), (StatementBlock) callConvert(l - .getBody())); + return new MethodFrame((IProgramVariable) (svw != null ? svw.getSV() : null), + (IExecutionContext) callConvert(l.getExecutionContext()), + (StatementBlock) callConvert(l.getBody())); } - public LoopScopeBlock convert( - de.uka.ilkd.key.java.recoderext.LoopScopeBlock l) { + public LoopScopeBlock convert(de.uka.ilkd.key.java.recoderext.LoopScopeBlock l) { return new LoopScopeBlock( (de.uka.ilkd.key.logic.op.IProgramVariable) callConvert(l.getIndexPV()), (StatementBlock) callConvert(l.getBody())); @@ -212,10 +193,9 @@ public LoopScopeBlock convert( /** * translate method body statements. */ - public MethodBodyStatement convert( - de.uka.ilkd.key.java.recoderext.RMethodBodyStatement l) { - final IProgramVariable resVar = l.getResultVar() == null ? null - : (IProgramVariable)l.getResultVar().getSV(); + public MethodBodyStatement convert(de.uka.ilkd.key.java.recoderext.RMethodBodyStatement l) { + final IProgramVariable resVar = + l.getResultVar() == null ? null : (IProgramVariable) l.getResultVar().getSV(); final TypeReference tr; if (l.getBodySource() instanceof TypeSVWrapper) { @@ -224,8 +204,7 @@ public MethodBodyStatement convert( tr = convert(l.getBodySource()); } - return new MethodBodyStatement(tr, resVar, convert(l - .getMethodReference())); + return new MethodBodyStatement(tr, resVar, convert(l.getMethodReference())); } /** @@ -234,83 +213,70 @@ public MethodBodyStatement convert( public ContextStatementBlock convert( de.uka.ilkd.key.java.recoderext.ContextStatementBlock csb) { ExtList children = collectChildren(csb); - return new ContextStatementBlock(children, - csb.getExecutionContext() == null ? null - : (IExecutionContext) callConvert(csb - .getExecutionContext())); + return new ContextStatementBlock(children, csb.getExecutionContext() == null ? null + : (IExecutionContext) callConvert(csb.getExecutionContext())); } /** * translate exection contexts */ @Override - public ExecutionContext convert( - de.uka.ilkd.key.java.recoderext.ExecutionContext ec) { + public ExecutionContext convert(de.uka.ilkd.key.java.recoderext.ExecutionContext ec) { return new ExecutionContext((TypeReference) callConvert(ec.getTypeReference()), - (IProgramMethod) callConvert(ec.getMethodContext()), - ec.getRuntimeInstance()!=null? (ReferencePrefix)callConvert(ec.getRuntimeInstance()) : null); + (IProgramMethod) callConvert(ec.getMethodContext()), + ec.getRuntimeInstance() != null + ? (ReferencePrefix) callConvert(ec.getRuntimeInstance()) + : null); } // ----- Schema Variables // SchemaVariables are unwrapped from their wrapping entity. - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.StatementSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.StatementSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.LabelSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.LabelSVWrapper svw) { return svw.getSV(); } @Override - public MergePointStatement convert( - de.uka.ilkd.key.java.recoderext.MergePointStatement l) { - return new MergePointStatement( - (IProgramVariable) callConvert(l.getChildAt(0))); + public MergePointStatement convert(de.uka.ilkd.key.java.recoderext.MergePointStatement l) { + return new MergePointStatement((IProgramVariable) callConvert(l.getChildAt(0))); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.MethodSignatureSVWrapper svw) { - return svw.getSV(); - } + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.MethodSignatureSVWrapper svw) { + return svw.getSV(); + } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.TypeSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.TypeSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.ExecCtxtSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.ExecCtxtSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.CatchSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.CatchSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.CcatchSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.CcatchSVWrapper svw) { return svw.getSV(); } - public SchemaVariable convert( - de.uka.ilkd.key.java.recoderext.ProgramVariableSVWrapper svw) { + public SchemaVariable convert(de.uka.ilkd.key.java.recoderext.ProgramVariableSVWrapper svw) { return svw.getSV(); } /** - * for some reason the this and super references have to be treated - * differently here. + * for some reason the this and super references have to be treated differently here. */ @Override @@ -324,22 +290,17 @@ public SuperReference convert(recoder.java.reference.SuperReference sr) { } /** - * local variable declarations have to be treated differently if they have - * schema vars in them. + * local variable declarations have to be treated differently if they have schema vars in them. */ @Override - public LocalVariableDeclaration convert( - recoder.java.declaration.LocalVariableDeclaration lvd) { + public LocalVariableDeclaration convert(recoder.java.declaration.LocalVariableDeclaration lvd) { if (lvd.getTypeReference() instanceof TypeSVWrapper) { List rspecs = lvd.getVariables(); - VariableSpecification[] varspecs = new VariableSpecification[rspecs - .size()]; + VariableSpecification[] varspecs = new VariableSpecification[rspecs.size()]; for (int i = 0; i < rspecs.size(); i++) { - varspecs[i] = convertVarSpecWithSVType(rspecs - .get(i)); + varspecs[i] = convertVarSpecWithSVType(rspecs.get(i)); } - SchemaVariable typesv = ((TypeSVWrapper) lvd.getTypeReference()) - .getSV(); + SchemaVariable typesv = ((TypeSVWrapper) lvd.getTypeReference()).getSV(); List mods = lvd.getModifiers(); Modifier[] modifiers = new Modifier[mods == null ? 0 : mods.size()]; @@ -347,8 +308,7 @@ public LocalVariableDeclaration convert( modifiers[i] = (Modifier) callConvert(mods.get(i)); } - return new LocalVariableDeclaration(modifiers, (ProgramSV) typesv, - varspecs); + return new LocalVariableDeclaration(modifiers, (ProgramSV) typesv, varspecs); } else { // otherwise use the default case return super.convert(lvd); @@ -360,29 +320,24 @@ public LocalVariableDeclaration convert( */ protected VariableSpecification convertVarSpecWithSVType( recoder.java.declaration.VariableSpecification recoderVarspec) { - VariableSpecification varspec = (VariableSpecification) getMapping() - .toKeY(recoderVarspec); + VariableSpecification varspec = (VariableSpecification) getMapping().toKeY(recoderVarspec); if (varspec == null) { ExtList l = collectChildren(recoderVarspec); - ProgramElement pv - = ProgramSVSort.VARIABLE.getSVWithSort(l, ProgramElementName.class); + ProgramElement pv = ProgramSVSort.VARIABLE.getSVWithSort(l, ProgramElementName.class); if (pv instanceof ProgramElementName) { // sth. like #type i; KeYJavaType kjt = new KeYJavaType(typeSVType); pv = new LocationVariable((ProgramElementName) pv, kjt); } - ProgramElement init = ProgramSVSort.VARIABLEINIT.getSVWithSort(l, - Expression.class); + ProgramElement init = ProgramSVSort.VARIABLEINIT.getSVWithSort(l, Expression.class); varspec = new VariableSpecification((IProgramVariable) pv, - recoderVarspec.getDimensions(), (Expression) init, - typeSVType, null); + recoderVarspec.getDimensions(), (Expression) init, typeSVType, null); insertToMap(recoderVarspec, varspec); } return varspec; } /** - * convert a recoder TypeReference to a KeY TypeReference (checks dimension - * and hands it over) + * convert a recoder TypeReference to a KeY TypeReference (checks dimension and hands it over) */ @Override public TypeReference convert(recoder.java.reference.TypeReference tr) { @@ -393,20 +348,19 @@ public TypeReference convert(recoder.java.reference.TypeReference tr) { while (rp != null) { if (prefix == null) { result = new recoder.java.reference.PackageReference( - ((recoder.java.reference.UncollatedReferenceQualifier) rp) - .getIdentifier()); + ((recoder.java.reference.UncollatedReferenceQualifier) rp).getIdentifier()); prefix = result; } else { - recoder.java.reference.PackageReference prefix2 = new recoder.java.reference.PackageReference( - ((recoder.java.reference.UncollatedReferenceQualifier) rp) - .getIdentifier()); + recoder.java.reference.PackageReference prefix2 = + new recoder.java.reference.PackageReference( + ((recoder.java.reference.UncollatedReferenceQualifier) rp) + .getIdentifier()); prefix.setReferencePrefix(prefix2); prefix = prefix2; } if (rp instanceof recoder.java.reference.ReferenceSuffix) { - rp = ((recoder.java.reference.ReferenceSuffix) rp) - .getReferencePrefix(); + rp = ((recoder.java.reference.ReferenceSuffix) rp).getReferencePrefix(); } else { rp = null; } @@ -414,16 +368,15 @@ public TypeReference convert(recoder.java.reference.TypeReference tr) { // there is no explicit PackageReference convert method // but the cast is safe. - PackageReference packref = result != null ? (PackageReference) convert(result) - : null; + PackageReference packref = result != null ? (PackageReference) convert(result) : null; - return new SchemaTypeReference(new ProgramElementName(tr.getName()), tr - .getDimensions(), packref); + return new SchemaTypeReference(new ProgramElementName(tr.getName()), tr.getDimensions(), + packref); } /** - * convert a recoder VariableSpecification to a KeY VariableSpecification - * (checks dimension and hands it over and insert in hashmap) + * convert a recoder VariableSpecification to a KeY VariableSpecification (checks dimension and + * hands it over and insert in hashmap) */ @Override public VariableSpecification convert( @@ -431,17 +384,15 @@ public VariableSpecification convert( if (!(recoderVarspec.getIdentifier() instanceof ProgramVariableSVWrapper)) { return super.convert(recoderVarspec); } - VariableSpecification varSpec = (VariableSpecification) getMapping() - .toKeY(recoderVarspec); + VariableSpecification varSpec = (VariableSpecification) getMapping().toKeY(recoderVarspec); if (varSpec == null) { ExtList children = collectChildren(recoderVarspec); - IProgramVariable progvar = (IProgramVariable) children - .get(SchemaVariable.class); + IProgramVariable progvar = (IProgramVariable) children.get(SchemaVariable.class); children.remove(progvar); - varSpec = new VariableSpecification(children, progvar, - recoderVarspec.getDimensions(), null); + varSpec = new VariableSpecification(children, progvar, recoderVarspec.getDimensions(), + null); insertToMap(recoderVarspec, varSpec); } @@ -465,10 +416,10 @@ public MethodReference convert(recoder.java.reference.MethodReference mr) { final ReferencePrefix prefix; if (mr.getReferencePrefix() instanceof recoder.java.reference.UncollatedReferenceQualifier) { // type references would be allowed - final recoder.java.reference.UncollatedReferenceQualifier uncoll = (recoder.java.reference.UncollatedReferenceQualifier) mr - .getReferencePrefix(); - prefix = convert(new recoder.java.reference.TypeReference(uncoll - .getReferencePrefix(), uncoll.getIdentifier())); + final recoder.java.reference.UncollatedReferenceQualifier uncoll = + (recoder.java.reference.UncollatedReferenceQualifier) mr.getReferencePrefix(); + prefix = convert(new recoder.java.reference.TypeReference(uncoll.getReferencePrefix(), + uncoll.getIdentifier())); } else { if (mr.getReferencePrefix() != null) { prefix = (ReferencePrefix) callConvert(mr.getReferencePrefix()); @@ -497,8 +448,7 @@ public MethodReference convert(recoder.java.reference.MethodReference mr) { /** * converts a For. * - * @param f - * the For of recoder + * @param f the For of recoder * @return the For of KeY */ @Override @@ -506,12 +456,11 @@ public For convert(recoder.java.statement.For f) { ILoopInit li; IForUpdates ifu; IGuard iGuard; - if (f.getInitializers() != null - && f.getInitializers().get(0) - instanceof de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) { + if (f.getInitializers() != null && f.getInitializers() + .get(0) instanceof de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) { de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper esvw = - (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f - .getInitializers().get(0); // brrrr! + (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f.getInitializers() + .get(0); // brrrr! li = (ProgramSV) esvw.getSV(); } else { li = convertLoopInitializers(f); @@ -519,19 +468,16 @@ public For convert(recoder.java.statement.For f) { if (f.getGuard() instanceof de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) { de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper esvw = - (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f - .getGuard(); + (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f.getGuard(); iGuard = (ProgramSV) esvw.getSV(); } else { iGuard = convertGuard(f); } - if (f.getUpdates() != null - && f.getUpdates().get(0) - instanceof de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) { + if (f.getUpdates() != null && f.getUpdates() + .get(0) instanceof de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) { de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper esvw = - (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f - .getUpdates().get(0); + (de.uka.ilkd.key.java.recoderext.ExpressionSVWrapper) f.getUpdates().get(0); ifu = (ProgramSV) esvw.getSV(); } else { ifu = convertUpdates(f); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ScopeDefiningElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ScopeDefiningElement.java index 1258457c6ad..c3f6a113e85 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ScopeDefiningElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ScopeDefiningElement.java @@ -1,11 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * The property of a non terminal program element to define a scope. - * taken from COMPOST and changed to achieve an immutable structure + * The property of a non terminal program element to define a scope. taken from COMPOST and changed + * to achieve an immutable structure */ public interface ScopeDefiningElement extends NonTerminalProgramElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/ServiceCaches.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/ServiceCaches.java index f6846302d93..ef597de35c8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/ServiceCaches.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/ServiceCaches.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.Map; @@ -26,175 +29,187 @@ /** *

    - * Instances of this class provides all caches used by an individual {@link Proof} - * or more precise by its {@link Services}. + * Instances of this class provides all caches used by an individual {@link Proof} or more precise + * by its {@link Services}. *

    *

    - * This is a redesign of the old static caches which were implemented via final static - * {@link Map}s like + * This is a redesign of the old static caches which were implemented via final static {@link Map}s + * like * {@code private static final Map termTacletAppIndexCache = new LRUCache ( MAX_TERM_TACLET_APP_INDEX_ENTRIES );}. - *

    + *

    *

    - * The old idea that memory is reused and shared between multiple {@link Proof}s - * by static variables is wrong, because in practice it wastes memory. - * The problem is that cached data structures - * can become large, especially in case of {@link #getTermTacletAppIndexCache()}. - * The static cache is filled with these large data structures and - * not freed even if all {@link Proof}s are disposed ({@link Proof#isDisposed()}). - * This can fill quickly (about 30 done {@link Proof}s) the whole memory. - * A new {@link Proof} which does not profit from the cached data structure - * has then no free memory to live in which makes the whole system unusable slow. + * The old idea that memory is reused and shared between multiple {@link Proof}s by static variables + * is wrong, because in practice it wastes memory. The problem is that cached data structures can + * become large, especially in case of {@link #getTermTacletAppIndexCache()}. The static cache is + * filled with these large data structures and not freed even if all {@link Proof}s are disposed + * ({@link Proof#isDisposed()}). This can fill quickly (about 30 done {@link Proof}s) the whole + * memory. A new {@link Proof} which does not profit from the cached data structure has then no free + * memory to live in which makes the whole system unusable slow. *

    *

    - * The goal of this new design is to avoid all static cache variables and - * to collect them instead as instance variables in this class. - * Each {@link Proof} has its own {@link Services} - * which provides a {@link ServiceCaches} instance to use via - * {@link Services#getCaches()}. The advantages are: + * The goal of this new design is to avoid all static cache variables and to collect them instead as + * instance variables in this class. Each {@link Proof} has its own {@link Services} which provides + * a {@link ServiceCaches} instance to use via {@link Services#getCaches()}. The advantages are: *

      - *
    • The cache contains only usable content and nothing from other {@link Proof}s not relevant for the current {@link Proof}.
    • - *
    • The whole memory is freed when a {@link Proof} is disposed via {@link Proof#dispose()}.
    • - *
    • Multiple {@link Proof}s at the same time are faster because they can fill the cache up to the fixed limit. Also the user interface profits from it when a user switches between proofs.
    • - *
    • Even if multiple large {@link Proof}s exist at the same time it seems to be no problem that multiple caches exist.
    • - *
    • The old behavior in which multiple {@link Proof}s use the same cache can be realized just by using the same {@link ServiceCaches} instance. This can be useful for instance in side proofs.
    • + *
    • The cache contains only usable content and nothing from other {@link Proof}s not relevant for + * the current {@link Proof}.
    • + *
    • The whole memory is freed when a {@link Proof} is disposed via {@link Proof#dispose()}.
    • + *
    • Multiple {@link Proof}s at the same time are faster because they can fill the cache up to the + * fixed limit. Also the user interface profits from it when a user switches between proofs.
    • + *
    • Even if multiple large {@link Proof}s exist at the same time it seems to be no problem that + * multiple caches exist.
    • + *
    • The old behavior in which multiple {@link Proof}s use the same cache can be realized just by + * using the same {@link ServiceCaches} instance. This can be useful for instance in side + * proofs.
    • *
    *

    + * * @author Martin Hentschel */ public class ServiceCaches { - /** - * The maximal number of index entries in {@link #getTermTacletAppIndexCache()}. - */ - public static final int MAX_TERM_TACLET_APP_INDEX_ENTRIES = 5000; - - /** - * The cache used by {@link TermTacletAppIndexCacheSet} instances. - */ - private final Map termTacletAppIndexCache = new LRUCache ( MAX_TERM_TACLET_APP_INDEX_ENTRIES ); - - /* - * Table of formulas which could be splitted using the beta rule - * This is the cache the method "isBetaCandidate" uses - * - * keys: Term values: TermInfo - */ - private final LRUCache betaCandidates = new LRUCache (1000); - - private final LRUCache ifThenElseMalusCache = new LRUCache(1000); - - private final LRUCache introductionTimeCache = new LRUCache ( 10000 ); - - private final LRUCache monomialCache = new LRUCache ( 2000 ); - - private final LRUCache polynomialCache = new LRUCache ( 2000 ); - - /**a HashMap from Term to - * TriggersSet uses to cache all created TriggersSets*/ - private final Map triggerSetCache = new LRUCache(1000); - - /** - * Map from Term(allTerm) to ClausesGraph - */ - private final Map graphCache = new LRUCache (1000); - - /** - * Cache used by the TermFactory to avoid unnecessary creation of terms - */ - private final Map termCache = new LRUCache(20000); - - /** - * Cache used by TypeComparisonCondition - */ - private final Map> disjointnessCache = new WeakHashMap>(); - - /** - * Cache used by HandleArith for caching formatted terms - */ - private final LRUCache formattedTermCache = new LRUCache(5000); - - /** - * Caches used bu HandleArith to cache proof results - */ - private final LRUCache provedByArithFstCache = new LRUCache(5000); - - private final LRUCache, Term> provedByArithSndCache = new LRUCache, Term>(5000); - - /** Cache used by the exhaustive macro */ - private final Map exhaustiveMacroCache = new WeakHashMap(); - - /** Cache used by the ifinstantiator */ - private final IfInstantiationCachePool ifInstantiationCache = new IfInstantiationCachePool(); - - /** Cache used IfFormulaInstSeq */ - private final IfFormulaInstantiationCache ifFormulaInstantiationCache = new IfFormulaInstantiationCache(); - - - /** - * Returns the cache used by {@link TermTacletAppIndexCacheSet} instances. - * @return The cache used by {@link TermTacletAppIndexCacheSet} instances. - */ - public final Map getTermTacletAppIndexCache() { - return termTacletAppIndexCache; - } - - public final LRUCache getBetaCandidates() { - return betaCandidates; - } - - public final LRUCache getIfThenElseMalusCache() { - return ifThenElseMalusCache; - } - - public final LRUCache getIntroductionTimeCache() { - return introductionTimeCache; - } - - public final LRUCache getMonomialCache() { - return monomialCache; - } - - public final LRUCache getPolynomialCache() { - return polynomialCache; - } - - public final Map getTriggerSetCache() { - return triggerSetCache; - } - - public final Map getGraphCache() { - return graphCache; - } - - public final Map getTermFactoryCache() { - return termCache; - } - - public final Map> getDisjointnessCache() { - return disjointnessCache; - } - - public final LRUCache getFormattedTermCache() { - return formattedTermCache; - } - - public final LRUCache getProvedByArithFstCache() { - return provedByArithFstCache; - } - - public final LRUCache, Term> getProvedByArithSndCache() { - return provedByArithSndCache; - } - - public final Map getExhaustiveMacroCache() { - return exhaustiveMacroCache; - } - - public final IfInstantiationCachePool getIfInstantiationCache() { - return ifInstantiationCache; - } - - public final IfFormulaInstantiationCache getIfFormulaInstantiationCache() { - return ifFormulaInstantiationCache; - } - -} \ No newline at end of file + /** + * The maximal number of index entries in {@link #getTermTacletAppIndexCache()}. + */ + public static final int MAX_TERM_TACLET_APP_INDEX_ENTRIES = 5000; + + /** + * The cache used by {@link TermTacletAppIndexCacheSet} instances. + */ + private final Map termTacletAppIndexCache = + new LRUCache(MAX_TERM_TACLET_APP_INDEX_ENTRIES); + + /* + * Table of formulas which could be splitted using the beta rule This is the cache the method + * "isBetaCandidate" uses + * + * keys: Term values: TermInfo + */ + private final LRUCache betaCandidates = new LRUCache(1000); + + private final LRUCache ifThenElseMalusCache = + new LRUCache(1000); + + private final LRUCache introductionTimeCache = + new LRUCache(10000); + + private final LRUCache monomialCache = new LRUCache(2000); + + private final LRUCache polynomialCache = new LRUCache(2000); + + /** + * a HashMap from Term to TriggersSet uses to cache all + * created TriggersSets + */ + private final Map triggerSetCache = new LRUCache(1000); + + /** + * Map from Term(allTerm) to ClausesGraph + */ + private final Map graphCache = new LRUCache(1000); + + /** + * Cache used by the TermFactory to avoid unnecessary creation of terms + */ + private final Map termCache = new LRUCache(20000); + + /** + * Cache used by TypeComparisonCondition + */ + private final Map> disjointnessCache = + new WeakHashMap>(); + + /** + * Cache used by HandleArith for caching formatted terms + */ + private final LRUCache formattedTermCache = new LRUCache(5000); + + /** + * Caches used bu HandleArith to cache proof results + */ + private final LRUCache provedByArithFstCache = new LRUCache(5000); + + private final LRUCache, Term> provedByArithSndCache = + new LRUCache, Term>(5000); + + /** Cache used by the exhaustive macro */ + private final Map exhaustiveMacroCache = + new WeakHashMap(); + + /** Cache used by the ifinstantiator */ + private final IfInstantiationCachePool ifInstantiationCache = new IfInstantiationCachePool(); + + /** Cache used IfFormulaInstSeq */ + private final IfFormulaInstantiationCache ifFormulaInstantiationCache = + new IfFormulaInstantiationCache(); + + + /** + * Returns the cache used by {@link TermTacletAppIndexCacheSet} instances. + * + * @return The cache used by {@link TermTacletAppIndexCacheSet} instances. + */ + public final Map getTermTacletAppIndexCache() { + return termTacletAppIndexCache; + } + + public final LRUCache getBetaCandidates() { + return betaCandidates; + } + + public final LRUCache getIfThenElseMalusCache() { + return ifThenElseMalusCache; + } + + public final LRUCache getIntroductionTimeCache() { + return introductionTimeCache; + } + + public final LRUCache getMonomialCache() { + return monomialCache; + } + + public final LRUCache getPolynomialCache() { + return polynomialCache; + } + + public final Map getTriggerSetCache() { + return triggerSetCache; + } + + public final Map getGraphCache() { + return graphCache; + } + + public final Map getTermFactoryCache() { + return termCache; + } + + public final Map> getDisjointnessCache() { + return disjointnessCache; + } + + public final LRUCache getFormattedTermCache() { + return formattedTermCache; + } + + public final LRUCache getProvedByArithFstCache() { + return provedByArithFstCache; + } + + public final LRUCache, Term> getProvedByArithSndCache() { + return provedByArithSndCache; + } + + public final Map getExhaustiveMacroCache() { + return exhaustiveMacroCache; + } + + public final IfInstantiationCachePool getIfInstantiationCache() { + return ifInstantiationCache; + } + + public final IfFormulaInstantiationCache getIfFormulaInstantiationCache() { + return ifFormulaInstantiationCache; + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Services.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Services.java index 78749299b72..213d8ffa59e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Services.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Services.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.HashMap; @@ -28,12 +31,12 @@ import org.key_project.util.lookup.Lookup; /** - * this is a collection of common services to the KeY prover. Services - * include information on the underlying Java model and a converter to - * transform Java program elements to logic (where possible) and back. + * this is a collection of common services to the KeY prover. Services include information on the + * underlying Java model and a converter to transform Java program elements to logic (where + * possible) and back. */ public class Services implements TermServices { - /** + /** * the proof */ private Proof proof; @@ -43,13 +46,15 @@ public class Services implements TermServices { */ private NamespaceSet namespaces = new NamespaceSet(); - /** used to determine whether an expression is a compile-time - * constant and if so the type and result of the expression + /** + * used to determine whether an expression is a compile-time constant and if so the type and + * result of the expression */ private ConstantExpressionEvaluator cee; - /** used to convert types, expressions and so on to logic elements - * (in special into to terms or formulas) + /** + * used to convert types, expressions and so on to logic elements (in special into to terms or + * formulas) */ private TypeConverter typeconverter; @@ -72,64 +77,65 @@ public class Services implements TermServices { * specification repository */ private SpecificationRepository specRepos; - + /* * the Java model (with all paths) */ private JavaModel javaModel; private NameRecorder nameRecorder; - - private ITermProgramVariableCollectorFactory factory = new ITermProgramVariableCollectorFactory(){ - @Override - public TermProgramVariableCollector create(Services services) { - return new TermProgramVariableCollector(services); - }}; + + private ITermProgramVariableCollectorFactory factory = + new ITermProgramVariableCollectorFactory() { + @Override + public TermProgramVariableCollector create(Services services) { + return new TermProgramVariableCollector(services); + } + }; private final Profile profile; - + private final ServiceCaches caches; - + private final TermBuilder termBuilder; private final TermBuilder termBuilderWithoutCache; /** - * creates a new Services object with a new TypeConverter and a new - * JavaInfo object with no information stored at none of these. + * creates a new Services object with a new TypeConverter and a new JavaInfo object with no + * information stored at none of these. */ - public Services(Profile profile){ - assert profile != null; - this.profile = profile; - this.counters = new LinkedHashMap(); - this.caches = new ServiceCaches(); - this.termBuilder = new TermBuilder(new TermFactory(caches.getTermFactoryCache()), this); - this.termBuilderWithoutCache = new TermBuilder(new TermFactory(), this); - this.specRepos = new SpecificationRepository(this); - cee = new ConstantExpressionEvaluator(this); - typeconverter = new TypeConverter(this); - javainfo = new JavaInfo(new KeYProgModelInfo(this, typeconverter, - new KeYRecoderExcHandler()), this); - nameRecorder = new NameRecorder(); - } - - private Services(Profile profile, KeYCrossReferenceServiceConfiguration crsc, KeYRecoderMapping rec2key, - HashMap counters, ServiceCaches caches) { - assert profile != null; - assert counters != null; - assert caches != null; - - this.profile = profile; - this.counters = counters; - this.caches = caches; - this.termBuilder = new TermBuilder(new TermFactory(caches.getTermFactoryCache()), this); + public Services(Profile profile) { + assert profile != null; + this.profile = profile; + this.counters = new LinkedHashMap(); + this.caches = new ServiceCaches(); + this.termBuilder = new TermBuilder(new TermFactory(caches.getTermFactoryCache()), this); + this.termBuilderWithoutCache = new TermBuilder(new TermFactory(), this); + this.specRepos = new SpecificationRepository(this); + cee = new ConstantExpressionEvaluator(this); + typeconverter = new TypeConverter(this); + javainfo = new JavaInfo( + new KeYProgModelInfo(this, typeconverter, new KeYRecoderExcHandler()), this); + nameRecorder = new NameRecorder(); + } + + private Services(Profile profile, KeYCrossReferenceServiceConfiguration crsc, + KeYRecoderMapping rec2key, HashMap counters, ServiceCaches caches) { + assert profile != null; + assert counters != null; + assert caches != null; + + this.profile = profile; + this.counters = counters; + this.caches = caches; + this.termBuilder = new TermBuilder(new TermFactory(caches.getTermFactoryCache()), this); this.termBuilderWithoutCache = new TermBuilder(new TermFactory(), this); - this.specRepos = new SpecificationRepository(this); - cee = new ConstantExpressionEvaluator(this); - typeconverter = new TypeConverter(this); - javainfo = new JavaInfo - (new KeYProgModelInfo(this, crsc, rec2key, typeconverter), this); - nameRecorder = new NameRecorder(); + this.specRepos = new SpecificationRepository(this); + cee = new ConstantExpressionEvaluator(this); + typeconverter = new TypeConverter(this); + javainfo = new JavaInfo(new KeYProgModelInfo(this, crsc, rec2key, typeconverter), this); + nameRecorder = new NameRecorder(); } private Services(Services s) { @@ -159,16 +165,16 @@ public Services getOverlay(NamespaceSet namespaces) { /** * Returns the TypeConverter associated with this Services object. */ - public TypeConverter getTypeConverter(){ - return typeconverter; + public TypeConverter getTypeConverter() { + return typeconverter; } private void setTypeConverter(TypeConverter tc) { - typeconverter = tc; + typeconverter = tc; } - + /** * Returns the ConstantExpressionEvaluator associated with this Services object. */ @@ -176,81 +182,85 @@ public ConstantExpressionEvaluator getConstantExpressionEvaluator() { return cee; } - + /** * Returns the JavaInfo associated with this Services object. */ public JavaInfo getJavaInfo() { return javainfo; } - - + + public NameRecorder getNameRecorder() { return nameRecorder; } - + public void saveNameRecorder(Node n) { n.setNameRecorder(nameRecorder); nameRecorder = new NameRecorder(); } - + public void addNameProposal(Name proposal) { nameRecorder.addProposal(proposal); } - - + + public SpecificationRepository getSpecificationRepository() { - return specRepos; + return specRepos; } - - + + /** * Returns the VariableNamer associated with this Services object. */ public VariableNamer getVariableNamer() { return innerVarNamer; } - + /** - * creates a new services object containing a copy of the java info of - * this object and a new TypeConverter (shallow copy) - * The copy does not belong to a {@link Proof} object and can hence be used for a new proof. - * @param shareCaches {@code true} The created {@link Services} will use the same {@link ServiceCaches} like this instance; {@code false} the created {@link Services} will use a new empty {@link ServiceCaches} instance. + * creates a new services object containing a copy of the java info of this object and a new + * TypeConverter (shallow copy) The copy does not belong to a {@link Proof} object and can hence + * be used for a new proof. + * + * @param shareCaches {@code true} The created {@link Services} will use the same + * {@link ServiceCaches} like this instance; {@code false} the created {@link Services} + * will use a new empty {@link ServiceCaches} instance. * @return the copy */ public Services copy(boolean shareCaches) { - return copy(getProfile(), shareCaches); + return copy(getProfile(), shareCaches); } /** - * Creates a copy of this {@link Services} in which the {@link Profile} is replaced. - * The copy does not belong to a {@link Proof} object and can hence be used for a new proof. + * Creates a copy of this {@link Services} in which the {@link Profile} is replaced. The copy + * does not belong to a {@link Proof} object and can hence be used for a new proof. + * * @param profile The new {@link Profile} to use in the copy of this {@link Services}. - * @param shareCaches {@code true} The created {@link Services} will use the same {@link ServiceCaches} like this instance; {@code false} the created {@link Services} will use a new empty {@link ServiceCaches} instance. + * @param shareCaches {@code true} The created {@link Services} will use the same + * {@link ServiceCaches} like this instance; {@code false} the created {@link Services} + * will use a new empty {@link ServiceCaches} instance. * @return The created copy. */ public Services copy(Profile profile, boolean shareCaches) { - Debug.assertTrue - (!(getJavaInfo().getKeYProgModelInfo().getServConf() - instanceof SchemaCrossReferenceServiceConfiguration), - "services: tried to copy schema cross reference service config."); - ServiceCaches newCaches = shareCaches ? caches : new ServiceCaches(); - Services s = new Services - (profile, getJavaInfo().getKeYProgModelInfo().getServConf(), getJavaInfo().getKeYProgModelInfo().rec2key().copy(), - copyCounters(), newCaches); - s.specRepos = specRepos; - s.setTypeConverter(getTypeConverter().copy(s)); - s.setNamespaces(namespaces.copy()); - nameRecorder = nameRecorder.copy(); - s.setJavaModel(getJavaModel()); - return s; - } - + Debug.assertTrue( + !(getJavaInfo().getKeYProgModelInfo() + .getServConf() instanceof SchemaCrossReferenceServiceConfiguration), + "services: tried to copy schema cross reference service config."); + ServiceCaches newCaches = shareCaches ? caches : new ServiceCaches(); + Services s = new Services(profile, getJavaInfo().getKeYProgModelInfo().getServConf(), + getJavaInfo().getKeYProgModelInfo().rec2key().copy(), copyCounters(), newCaches); + s.specRepos = specRepos; + s.setTypeConverter(getTypeConverter().copy(s)); + s.setNamespaces(namespaces.copy()); + nameRecorder = nameRecorder.copy(); + s.setJavaModel(getJavaModel()); + return s; + } + /** - * Generate a copy of this object. - * All references are copied w/o duplicating their content. + * Generate a copy of this object. All references are copied w/o duplicating their content. * * @return a freshly created Services object */ @@ -259,56 +269,59 @@ public Services shallowCopy() { } /** - * Creates a deep copy of {@link #counters} which means that a new - * list is created with a copy of each contained {@link Counter}. + * Creates a deep copy of {@link #counters} which means that a new list is created with a copy + * of each contained {@link Counter}. + * * @return The created deep copy with new {@link Counter} instances. */ private HashMap copyCounters() { - HashMap result = new LinkedHashMap(); - for (Entry entry : counters.entrySet()) { - result.put(entry.getKey(), entry.getValue().copy()); - } - return result; + HashMap result = new LinkedHashMap(); + for (Entry entry : counters.entrySet()) { + result.put(entry.getKey(), entry.getValue().copy()); + } + return result; } /** - * creates a new service object with the same ldt information - * as the actual one + * creates a new service object with the same ldt information as the actual one */ public Services copyPreservesLDTInformation() { - Debug.assertTrue - (!(javainfo.getKeYProgModelInfo().getServConf() - instanceof SchemaCrossReferenceServiceConfiguration), - "services: tried to copy schema cross reference service config."); + Debug.assertTrue( + !(javainfo.getKeYProgModelInfo() + .getServConf() instanceof SchemaCrossReferenceServiceConfiguration), + "services: tried to copy schema cross reference service config."); Services s = new Services(getProfile()); - s.setTypeConverter(getTypeConverter().copy(s)); - s.setNamespaces(namespaces.copy()); - nameRecorder = nameRecorder.copy(); - s.setJavaModel(getJavaModel()); - - return s; - } - - - /** - * Marks this services as proof specific - * Please make sure that the {@link Services} does not not yet belong to an existing proof - * or that it is owned by a proof environment. In both cases copy the {@link InitConfig} via - * {@link InitConfig#deepCopy()} or one of the other copy methods first. + s.setTypeConverter(getTypeConverter().copy(s)); + s.setNamespaces(namespaces.copy()); + nameRecorder = nameRecorder.copy(); + s.setJavaModel(getJavaModel()); + + return s; + } + + + /** + * Marks this services as proof specific Please make sure that the {@link Services} does not not + * yet belong to an existing proof or that it is owned by a proof environment. In both cases + * copy the {@link InitConfig} via {@link InitConfig#deepCopy()} or one of the other copy + * methods first. + * * @param p_proof the Proof to which this {@link Services} instance belongs */ public void setProof(Proof p_proof) { - if (this.proof != null) { - throw new IllegalStateException("Services are already owned by another proof:" + proof.name()); - } - proof = p_proof; + if (this.proof != null) { + throw new IllegalStateException( + "Services are already owned by another proof:" + proof.name()); + } + proof = p_proof; } - - + + public Services copyProofSpecific(Proof p_proof, boolean shareCaches) { ServiceCaches newCaches = shareCaches ? caches : new ServiceCaches(); - final Services s = new Services(getProfile(), getJavaInfo().getKeYProgModelInfo().getServConf(), getJavaInfo().getKeYProgModelInfo().rec2key(), - copyCounters(), newCaches); + final Services s = + new Services(getProfile(), getJavaInfo().getKeYProgModelInfo().getServConf(), + getJavaInfo().getKeYProgModelInfo().rec2key(), copyCounters(), newCaches); s.proof = p_proof; s.specRepos = specRepos; s.setTypeConverter(getTypeConverter().copy(s)); @@ -319,13 +332,14 @@ public Services copyProofSpecific(Proof p_proof, boolean shareCaches) { return s; } - + /* * returns an existing named counter, creates a new one otherwise */ public Counter getCounter(String name) { Counter c = counters.get(name); - if (c != null) return c; + if (c != null) + return c; c = new Counter(name); counters.put(name, c); return c; @@ -333,78 +347,82 @@ public Counter getCounter(String name) { /** * returns the namespaces for functions, predicates etc. + * * @return the proof specific namespaces */ @Override public NamespaceSet getNamespaces() { return namespaces; } - - + + /** * sets the namespaces of known predicates, functions, variables + * * @param namespaces the NamespaceSet with the proof specific namespaces */ public void setNamespaces(NamespaceSet namespaces) { this.namespaces = namespaces; } - - + + /** - * Returns the proof to which this object belongs, or null if it does not - * belong to any proof. + * Returns the proof to which this object belongs, or null if it does not belong to any proof. */ public Proof getProof() { - return proof; + return proof; } - public interface ITermProgramVariableCollectorFactory{ - public TermProgramVariableCollector create(Services services); + public interface ITermProgramVariableCollectorFactory { + public TermProgramVariableCollector create(Services services); } /** * Returns the sued {@link Profile}. + * * @return The used {@link Profile}. */ public Profile getProfile() { return profile; } - + /** * Returns the used {@link ServiceCaches}. + * * @return The used {@link ServiceCaches}. */ public ServiceCaches getCaches() { return caches; } - + /** - * - * Returns either the cache backed or raw {@link TermBuilder} used to create {@link Term}s. - * Usually the cache backed version is the intended one. The non-cached version is for - * use cases where a lot of intermediate terms are created of which most exist only for a - * very short time. To avoid polluting the cache it is then recommended to use the non-cache - * version - * + * + * Returns either the cache backed or raw {@link TermBuilder} used to create {@link Term}s. + * Usually the cache backed version is the intended one. The non-cached version is for use cases + * where a lot of intermediate terms are created of which most exist only for a very short time. + * To avoid polluting the cache it is then recommended to use the non-cache version + * * @return The {@link TermBuilder} used to create {@link Term}s. */ @Override public TermBuilder getTermBuilder(boolean withCache) { - return withCache ? termBuilder : termBuilderWithoutCache; + return withCache ? termBuilder : termBuilderWithoutCache; } - + /** - * Returns the {@link TermBuilder} used to create {@link Term}s. - * Same as {@link #getTermBuilder(true). + * Returns the {@link TermBuilder} used to create {@link Term}s. Same as + * {@link #getTermBuilder(true). + * * @return The {@link TermBuilder} used to create {@link Term}s. */ @Override public TermBuilder getTermBuilder() { - return termBuilder; + return termBuilder; } /** * Returns the {@link TermFactory} used to create {@link Term}s. + * * @return The {@link TermFactory} used to create {@link Term}s. */ @Override @@ -424,17 +442,18 @@ public void setFactory(ITermProgramVariableCollectorFactory factory) { /** * returns the {@link JavaModel} with all path information + * * @return the {@link JavaModel} on which this services is based on */ - public JavaModel getJavaModel() { - return javaModel; - } + public JavaModel getJavaModel() { + return javaModel; + } - public void setJavaModel(JavaModel javaModel) { - assert this.javaModel == null; - this.javaModel = javaModel; - } + public void setJavaModel(JavaModel javaModel) { + assert this.javaModel == null; + this.javaModel = javaModel; + } public Lookup createLookup() { Lookup lookup = new Lookup(); @@ -448,4 +467,4 @@ public Lookup createLookup() { lookup.register(getVariableNamer()); return lookup; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SingleLineComment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SingleLineComment.java index 4551ffff073..d8e33c9635b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SingleLineComment.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SingleLineComment.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** Any non-SingleLineComment is a multi line comment. */ @@ -5,17 +8,18 @@ public class SingleLineComment extends Comment { /** - Single line comment. + * Single line comment. */ public SingleLineComment() {} /** - Single line comment. - @param text a string. + * Single line comment. + * + * @param text a string. */ public SingleLineComment(String text) { super(text); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceData.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceData.java index 71500d8d073..4265ec96750 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceData.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceData.java @@ -1,52 +1,56 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * This class keeps track of the next element to match, which is provided by - * calling method {@link #getSource()}. The rough idea is to store the parent ast - * node and the index of the child which has to be matched (for convenience reasons - * -1 encodes that the parent node itself has to be matched). - * + * This class keeps track of the next element to match, which is provided by calling method + * {@link #getSource()}. The rough idea is to store the parent ast node and the index of the child + * which has to be matched (for convenience reasons -1 encodes that the parent node itself + * has to be matched). + * * This kind of wrapping is useful when matching list schemavariables. */ public class SourceData { /** - * the program element being either the parent of the program element to be matched or - * the element itself depending on the value of childPos + * the program element being either the parent of the program element to be matched or the + * element itself depending on the value of childPos */ private ProgramElement element; - - /** the position of the children of element which has to be matched - * against the pattern. If childPos is -1 then element has to be matched. + + /** + * the position of the children of element which has to be matched against the pattern. If + * childPos is -1 then element has to be matched. */ private int childPos; /** the services */ private final Services services; - - + + /** - * creates a new source data object with parent node element whose - * childPos-th child has to be matched (-1 denotes element itself - * has to be matched - * @param element the ProgramElement + * creates a new source data object with parent node element whose childPos-th + * child has to be matched (-1 denotes element itself has to be matched + * + * @param element the ProgramElement * @param childPos the int giving the index of the child of element to be matched - * @param services the Services + * @param services the Services */ public SourceData(ProgramElement element, int childPos, Services services) { - assert services != null; - assert element != null; + assert services != null; + assert element != null; this.services = services; - this.element = element; + this.element = element; this.childPos = childPos; } /** * returns index of the child to be matched - * @return an int which is -1 if @link #getElement() - * has to be matched itself otherwise it refers to the index of the child - * of element to be matched + * + * @return an int which is -1 if @link #getElement() has to be matched itself otherwise + * it refers to the index of the child of element to be matched */ public int getChildPos() { return childPos; @@ -55,6 +59,7 @@ public int getChildPos() { /** * sets the index of the child to be matched + * * @param childPos the int with the new index */ public void setChildPos(int childPos) { @@ -63,6 +68,7 @@ public void setChildPos(int childPos) { /** * returns always the parent node + * * @return the parent node */ public ProgramElement getElement() { @@ -72,46 +78,47 @@ public ProgramElement getElement() { /** * sets the parent node + * * @param element the ProgramElement used as new parent node */ public void setElement(ProgramElement element) { this.element = element; } - + /** - * returns the element to be matched, i.e. if @link #getChildPos() is -1 - * it returns @link #getElement() - * otherwise it returns the getChildPos()-th child or null if the returned - * child position is out of bound. - * @return the ProgramElement to be matched next or null if there is no such - * element + * returns the element to be matched, i.e. if @link #getChildPos() is -1 it + * returns @link #getElement() otherwise it returns the getChildPos()-th child or null + * if the returned child position is out of bound. + * + * @return the ProgramElement to be matched next or null if there is no such element */ public ProgramElement getSource() { - if (childPos == -1) return element; + if (childPos == -1) + return element; + + final NonTerminalProgramElement ntpe = (NonTerminalProgramElement) element; - final NonTerminalProgramElement ntpe = - (NonTerminalProgramElement)element; - if (childPos < ntpe.getChildCount()) { return ntpe.getChildAt(childPos); } else { return null; - } + } } - + /** - * increments the child position by one, this means moving on to the next sibling - * (or the first child if childPos has been -1 before + * increments the child position by one, this means moving on to the next sibling (or the first + * child if childPos has been -1 before */ public void next() { - childPos++; + childPos++; } /** - * returns the services object - * @return the services object + * returns the services object + * + * @return the services object */ - public Services getServices() { + public Services getServices() { return services; } @@ -121,5 +128,5 @@ public Services getServices() { public String toString() { return "Source:" + element + " child: " + childPos; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceElement.java index 6d4129a11e5..c71e92efe15 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/SourceElement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.io.IOException; @@ -6,78 +9,83 @@ import de.uka.ilkd.key.logic.op.SVSubstitute; /** - * A source element is a piece of syntax. It does not necessarily have - * a semantics, at least none that is machinable, for instance a - * {@link recoder.java.Comment}. - * taken from RECODER and changed to achieve an immutable structure + * A source element is a piece of syntax. It does not necessarily have a semantics, at least none + * that is machinable, for instance a {@link recoder.java.Comment}. taken from RECODER and changed + * to achieve an immutable structure */ public interface SourceElement extends SVSubstitute { /** - * Finds the source element that occurs first in the source. - * @return the first source element in the syntactical representation of - * this element, may be equals to this element. - * @see #getStartPosition() - */ + * Finds the source element that occurs first in the source. + * + * @return the first source element in the syntactical representation of this element, may be + * equals to this element. + * @see #getStartPosition() + */ SourceElement getFirstElement(); /** - * Finds the source element that occurs first in the source. - * @return the first source element in the syntactical representation of - * this element, may be equals to this element. - * @see #getStartPosition() - */ + * Finds the source element that occurs first in the source. + * + * @return the first source element in the syntactical representation of this element, may be + * equals to this element. + * @see #getStartPosition() + */ SourceElement getFirstElementIncludingBlocks(); /** - * 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. - * @see #getEndPosition() - */ + * 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. + * @see #getEndPosition() + */ SourceElement getLastElement(); - /** - 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. */ Position 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. */ Position 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. */ Position getRelativePosition(); - + /** complete position information */ PositionInfo getPositionInfo(); - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * calls the corresponding method of a visitor in order to perform some action/transformation on + * this element + * * @param v the Visitor */ void visit(Visitor v); /** * Pretty print. + * * @param w a pretty printer. * @exception IOException occasionally thrown. */ @@ -85,23 +93,18 @@ Returns the relative position (number of blank heading lines and /** - * This method returns true if two program parts are equal modulo - * renaming. The equality is mainly a syntactical equality with - * some exceptions: if a variable is declared we abstract from the - * name of the variable, so the first declared variable gets - * e.g. the name decl_1, the second declared decl_2 and so on. - * Look at the following programs: - * {int i; i=0;} and { int j; j=0;} these would be seen like - * {int decl_1; decl_1=0;} and {int decl_1; decl_1=0;} which are - * syntactical equal and therefore true is returned (same thing for - * labels). But {int i; i=0;} and {int j; i=0;} (in the second - * block the variable i is declared somewhere outside) - * would be seen as {int decl_1; decl_1=0;} for the first one but - * {int decl_1; i=0;} for the second one. These are not - * syntactical equal, therefore false is returned. + * This method returns true if two program parts are equal modulo renaming. The equality is + * mainly a syntactical equality with some exceptions: if a variable is declared we abstract + * from the name of the variable, so the first declared variable gets e.g. the name decl_1, the + * second declared decl_2 and so on. Look at the following programs: {int i; i=0;} and { int j; + * j=0;} these would be seen like {int decl_1; decl_1=0;} and {int decl_1; decl_1=0;} which are + * syntactical equal and therefore true is returned (same thing for labels). But {int i; i=0;} + * and {int j; i=0;} (in the second block the variable i is declared somewhere outside) would be + * seen as {int decl_1; decl_1=0;} for the first one but {int decl_1; i=0;} for the second one. + * These are not syntactical equal, therefore false is returned. */ boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat); - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/Statement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/Statement.java index 03568e16e7c..87a04d97d08 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/Statement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/Statement.java @@ -1,11 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Statement. - * taken from COMPOST and changed to achieve an immutable structure + * Statement. taken from COMPOST and changed to achieve an immutable structure */ public interface Statement extends ProgramElement { -} \ No newline at end of file +} 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 dc71868f0aa..e3eb2f54efe 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; import java.util.ArrayList; @@ -15,42 +18,40 @@ import de.uka.ilkd.key.util.Debug; /** - * Statement block. - * taken from COMPOST and changed to achieve an immutable structure + * Statement block. taken from COMPOST and changed to achieve an immutable structure */ -public class StatementBlock extends JavaStatement - implements StatementContainer, TypeDeclarationContainer, - VariableScope, TypeScope, ProgramPrefix { - +public class StatementBlock extends JavaStatement implements StatementContainer, + TypeDeclarationContainer, VariableScope, TypeScope, ProgramPrefix { + /** - * Body. + * Body. */ private final ImmutableArray body; - - private final int prefixLength; - - private final MethodFrame innerMostMethodFrame; - - + + private final int prefixLength; + + private final MethodFrame innerMostMethodFrame; + + public StatementBlock() { body = new ImmutableArray(); prefixLength = 1; innerMostMethodFrame = 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)); + body = new ImmutableArray(children.collect(Statement.class)); - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); } @@ -70,36 +71,39 @@ public StatementBlock(Statement 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) + && (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()); } /** computes the prefix elements for the given array of statment block */ - public static ImmutableArray computePrefixElements(ImmutableArray b, - ProgramPrefix current) { + public static ImmutableArray computePrefixElements( + ImmutableArray b, ProgramPrefix current) { final ArrayList prefix = new ArrayList<>(); prefix.add(current); - + while (current.hasNextPrefixElement()) { current = current.getNextPrefixElement(); prefix.add(current); } - + return new ImmutableArray(prefix); } /** - * Get body. - * @return the statement array wrapper. + * Get body. + * + * @return the statement array wrapper. */ public ImmutableArray getBody() { @@ -107,13 +111,14 @@ public ImmutableArray getBody() { } 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() { @@ -121,12 +126,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 + * 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 */ public ProgramElement getChildAt(int index) { @@ -137,8 +141,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() { @@ -146,13 +151,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null) { @@ -162,8 +168,9 @@ public Statement getStatementAt(int 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() { @@ -179,13 +186,15 @@ public int getTypeDeclarationCount() { } /* - Return the type declaration at the specified index in this node's - "virtual" type declaration array. - @param index an index for a type declaration. - @return the type declaration with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the type declaration at the specified index in this node's "virtual" type declaration + * array. + * + * @param index an index for a type declaration. + * + * @return the type declaration with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public TypeDeclaration getTypeDeclarationAt(int index) { if (body != null) { @@ -194,7 +203,7 @@ public TypeDeclaration getTypeDeclarationAt(int index) { Statement st = body.get(i); if (st instanceof TypeDeclaration) { if (index == 0) { - return (TypeDeclaration)st; + return (TypeDeclaration) st; } index -= 1; } @@ -203,12 +212,14 @@ public TypeDeclaration getTypeDeclarationAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { @@ -217,18 +228,21 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public SourceElement getFirstElement() { - if (isEmpty()) return this; + if (isEmpty()) + return this; final SourceElement e = getBody().get(0); return (e instanceof StatementBlock) ? e.getFirstElement() : e; } @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); @@ -242,12 +256,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; @@ -257,10 +271,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/StatementContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementContainer.java index 53d043dcc70..500df383e9f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/StatementContainer.java @@ -1,26 +1,30 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Statement container. - * taken from COMPOST and changed to achieve an immutable structure + * Statement container. taken from COMPOST and changed to achieve an immutable structure */ public interface StatementContainer extends NonTerminalProgramElement { /** - * 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. */ int getStatementCount(); /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ Statement getStatementAt(int index); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TerminalProgramElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TerminalProgramElement.java index d79c7ce3450..794377d9d17 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TerminalProgramElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TerminalProgramElement.java @@ -1,9 +1,11 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * Terminal program element. - * taken from COMPOST and changed to achieve an immutable structure + * Terminal program element. taken from COMPOST and changed to achieve an immutable structure */ public interface TerminalProgramElement extends ProgramElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java index 28be1efdd98..b2d347a07c8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeConverter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; @@ -40,7 +43,7 @@ public final class TypeConverter { private final Map LDTs = new HashMap<>(); private HeapLDT heapLDT = null; - //private IntegerLDT integerLDT = null; + // private IntegerLDT integerLDT = null; TypeConverter(Services s) { this.services = s; @@ -54,7 +57,7 @@ public void init() { private void init(Map map) { LDTs.putAll(map); heapLDT = getHeapLDT(); - //integerLDT = getIntegerLDT(); + // integerLDT = getIntegerLDT(); } @@ -112,16 +115,18 @@ public CharListLDT getCharListLDT() { return (CharListLDT) getLDT(CharListLDT.NAME); } - private Term translateOperator(de.uka.ilkd.key.java.expression.Operator op, ExecutionContext ec) { + private Term translateOperator(de.uka.ilkd.key.java.expression.Operator op, + ExecutionContext ec) { final Term[] subs = new Term[op.getArity()]; for (int i = 0, n = op.getArity(); i < n; i++) { subs[i] = convertToLogicElement(op.getExpressionAt(i), ec); } - //hack: convert object singleton to location singleton + // hack: convert object singleton to location singleton if (op instanceof Singleton) { - assert heapLDT.getSortOfSelect(subs[0].op()) != null : "unexpected argument of \\singleton: " + subs[0]; + assert heapLDT.getSortOfSelect(subs[0].op()) != null + : "unexpected argument of \\singleton: " + subs[0]; return tb.singleton(subs[0].sub(1), subs[0].sub(2)); } @@ -144,52 +149,51 @@ private Term translateOperator(de.uka.ilkd.key.java.expression.Operator op, Exec TypeCast tc = (TypeCast) op; return tb.cast(tc.getKeYJavaType(services).getSort(), subs[0]); } else { - LOGGER.debug("typeconverter: no data type model " - + "available to convert:{} {}", op, op.getClass()); - throw new IllegalArgumentException("TypeConverter could not handle" - + " this operator: " + op); + LOGGER.debug("typeconverter: no data type model " + "available to convert:{} {}", op, + op.getClass()); + throw new IllegalArgumentException( + "TypeConverter could not handle" + " this operator: " + op); } } - private Term convertReferencePrefix(ReferencePrefix prefix, - ExecutionContext ec) { + private Term convertReferencePrefix(ReferencePrefix prefix, ExecutionContext ec) { LOGGER.debug("typeconverter: (prefix {}, class {})", prefix, (prefix != null ? prefix.getClass() : null)); if (prefix instanceof FieldReference) { return convertVariableReference((FieldReference) prefix, ec); } else if (prefix instanceof MetaClassReference) { - LOGGER.debug("typeconverter: " + - "WARNING: metaclass-references not supported yet"); - throw new IllegalArgumentException("TypeConverter could not handle" - + " this"); + LOGGER.debug("typeconverter: " + "WARNING: metaclass-references not supported yet"); + throw new IllegalArgumentException("TypeConverter could not handle" + " this"); } else if (prefix instanceof ProgramVariable) { // the base case: the leftmost item is a local variable return tb.var((ProgramVariable) prefix); } else if (prefix instanceof VariableReference) { - LOGGER.debug("variablereference: {}", (((VariableReference) prefix).getProgramVariable())); + LOGGER.debug("variablereference: {}", + (((VariableReference) prefix).getProgramVariable())); return tb.var(((VariableReference) prefix).getProgramVariable()); } else if (prefix instanceof ArrayReference) { return convertArrayReference((ArrayReference) prefix, ec); } else if (prefix instanceof ThisReference) { - if (prefix.getReferencePrefix() != null && (prefix.getReferencePrefix() instanceof TypeReference)) { + if (prefix.getReferencePrefix() != null + && (prefix.getReferencePrefix() instanceof TypeReference)) { TypeReference tr = (TypeReference) prefix.getReferencePrefix(); KeYJavaType kjt = tr.getKeYJavaType(); return findThisForSortExact(kjt.getSort(), ec); } return convertToLogicElement(ec.getRuntimeInstance()); } else { - LOGGER.debug("WARNING: unknown reference prefix: {} {}", - prefix, prefix == null ? null : prefix.getClass()); - throw new IllegalArgumentException("TypeConverter failed to convert " - + prefix); + LOGGER.debug("WARNING: unknown reference prefix: {} {}", prefix, + prefix == null ? null : prefix.getClass()); + throw new IllegalArgumentException("TypeConverter failed to convert " + prefix); } } public Term findThisForSortExact(Sort s, ExecutionContext ec) { ProgramElement pe = ec.getRuntimeInstance(); - if (pe == null) return null; + if (pe == null) + return null; Term inst = convertToLogicElement(pe, ec); return findThisForSort(s, inst, ec.getTypeReference().getKeYJavaType(), true); @@ -197,25 +201,21 @@ public Term findThisForSortExact(Sort s, ExecutionContext ec) { public Term findThisForSort(Sort s, ExecutionContext ec) { ProgramElement pe = ec.getRuntimeInstance(); - if (pe == null) return null; + if (pe == null) + return null; Term inst = convertToLogicElement(pe, ec); return findThisForSort(s, inst, ec.getTypeReference().getKeYJavaType(), false); } - public Term findThisForSort(Sort s, - Term self, - KeYJavaType context, - boolean exact) { + public Term findThisForSort(Sort s, Term self, KeYJavaType context, boolean exact) { Term result = self; LocationVariable inst; while (!exact && !context.getSort().extendsTrans(s) || exact && !context.getSort().equals(s)) { - inst = (LocationVariable) - services.getJavaInfo().getAttribute( - ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS, context); - final Function fieldSymbol - = heapLDT.getFieldSymbolForPV(inst, services); + inst = (LocationVariable) services.getJavaInfo() + .getAttribute(ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS, context); + final Function fieldSymbol = heapLDT.getFieldSymbolForPV(inst, services); result = tb.dot(inst.sort(), result, fieldSymbol); context = inst.getKeYJavaType(); } @@ -247,8 +247,7 @@ public Term convertMethodReference(MethodReference mr, ExecutionContext ec) { throw new IllegalArgumentException("TypeConverter could not handle this"); } - public Term convertVariableReference(VariableReference fr, - ExecutionContext ec) { + public Term convertVariableReference(VariableReference fr, ExecutionContext ec) { LOGGER.debug("TypeConverter: FieldReference: {}", fr); final ReferencePrefix prefix = fr.getReferencePrefix(); final ProgramVariable var = fr.getProgramVariable(); @@ -257,49 +256,40 @@ public Term convertVariableReference(VariableReference fr, } else if (var == services.getJavaInfo().getArrayLength()) { return tb.dotLength(convertReferencePrefix(prefix, ec)); } else if (var.isStatic()) { - final Function fieldSymbol - = heapLDT.getFieldSymbolForPV((LocationVariable) var, services); + final Function fieldSymbol = + heapLDT.getFieldSymbolForPV((LocationVariable) var, services); return tb.staticDot(var.sort(), fieldSymbol); } else if (prefix == null) { if (var.isMember()) { - final Function fieldSymbol - = heapLDT.getFieldSymbolForPV((LocationVariable) var, - services); - return tb.dot(var.sort(), - findThisForSort(var.getContainerType().getSort(), - ec), + final Function fieldSymbol = + heapLDT.getFieldSymbolForPV((LocationVariable) var, services); + return tb.dot(var.sort(), findThisForSort(var.getContainerType().getSort(), ec), fieldSymbol); } else { return tb.var(var); } } else if (!(prefix instanceof PackageReference)) { - final Function fieldSymbol - = heapLDT.getFieldSymbolForPV((LocationVariable) var, services); + final Function fieldSymbol = + heapLDT.getFieldSymbolForPV((LocationVariable) var, services); return tb.dot(var.sort(), convertReferencePrefix(prefix, ec), fieldSymbol); } - LOGGER.debug("Not supported reference type (fr {} , class {})", - fr, fr.getClass()); - throw new IllegalArgumentException - ("TypeConverter could not handle this"); + LOGGER.debug("Not supported reference type (fr {} , class {})", fr, fr.getClass()); + throw new IllegalArgumentException("TypeConverter could not handle this"); } - public Term convertArrayReference(ArrayReference ar, - ExecutionContext ec) { + public Term convertArrayReference(ArrayReference ar, ExecutionContext ec) { final Term[] index = new Term[ar.getDimensionExpressions().size()]; final Term t = convertToLogicElement(ar.getReferencePrefix(), ec); for (int i = 0; i < index.length; i++) { - index[i] = - convertToLogicElement(ar.getDimensionExpressions().get(i), ec); + index[i] = convertToLogicElement(ar.getDimensionExpressions().get(i), ec); } assert index.length == 1 : "multi-dimensional arrays not implemented"; return tb.dotArr(t, index[0]); } - private Term convertToInstanceofTerm(Instanceof io, - ExecutionContext ec) { - final KeYJavaType type = ((TypeReference) io.getChildAt(1)). - getKeYJavaType(); + private Term convertToInstanceofTerm(Instanceof io, ExecutionContext ec) { + final KeYJavaType type = ((TypeReference) io.getChildAt(1)).getKeYJavaType(); final Term obj = convertToLogicElement(io.getChildAt(0), ec); final Sort s = type.getSort(); final Function instanceOfSymbol = s.getInstanceofSymbol(services); @@ -307,8 +297,7 @@ private Term convertToInstanceofTerm(Instanceof io, // in JavaDL S::instance(o) is also true if o (for reference types S) // is null in opposite to Java // we create here if (obj = null) then FALSE else S::instance(obj) - return tb.ife(tb.equals(obj, tb.NULL()), tb.FALSE(), - tb.func(instanceOfSymbol, obj)); + return tb.ife(tb.equals(obj, tb.NULL()), tb.FALSE(), tb.func(instanceOfSymbol, obj)); } @@ -317,8 +306,7 @@ public Term convertToLogicElement(ProgramElement pe) { } - public Term convertToLogicElement(ProgramElement pe, - ExecutionContext ec) { + public Term convertToLogicElement(ProgramElement pe, ExecutionContext ec) { LOGGER.debug("called for: {} {}", pe, pe.getClass()); if (pe instanceof ProgramVariable) { return tb.var((ProgramVariable) pe); @@ -335,22 +323,20 @@ public Term convertToLogicElement(ProgramElement pe, } else if (pe instanceof ThisReference) { return convertReferencePrefix((ThisReference) pe, ec); } else if (pe instanceof ParenthesizedExpression) { - return convertToLogicElement - (((ParenthesizedExpression) pe).getChildAt(0), ec); + return convertToLogicElement(((ParenthesizedExpression) pe).getChildAt(0), ec); } else if (pe instanceof Instanceof) { return convertToInstanceofTerm((Instanceof) pe, ec); } else if (pe instanceof de.uka.ilkd.key.java.expression.Operator) { - return translateOperator - ((de.uka.ilkd.key.java.expression.Operator) pe, ec); + return translateOperator((de.uka.ilkd.key.java.expression.Operator) pe, ec); } else if (pe instanceof recoder.abstraction.PrimitiveType) { - throw new IllegalArgumentException("TypeConverter could not handle" - + " this primitive type"); + throw new IllegalArgumentException( + "TypeConverter could not handle" + " this primitive type"); } else if (pe instanceof MetaClassReference) { assert false : "not supported"; } - throw new IllegalArgumentException - ("TypeConverter: Unknown or not convertable ProgramElement " + pe + - " of type " + pe.getClass()); + throw new IllegalArgumentException( + "TypeConverter: Unknown or not convertable ProgramElement " + pe + " of type " + + pe.getClass()); } @@ -374,16 +360,13 @@ private Term convertLiteralExpression(Literal lit) { } } - public static boolean isArithmeticOperator - (de.uka.ilkd.key.java.expression.Operator op) { - if (op instanceof Divide || op instanceof Times || - op instanceof Plus || op instanceof Minus || - op instanceof Modulo || op instanceof ShiftLeft || - op instanceof ShiftRight || op instanceof BinaryAnd || - op instanceof BinaryNot || op instanceof BinaryOr || - op instanceof BinaryXOr || op instanceof Negative || - op instanceof PreIncrement || op instanceof PostIncrement || - op instanceof PreDecrement || op instanceof PostDecrement) { + public static boolean isArithmeticOperator(de.uka.ilkd.key.java.expression.Operator op) { + if (op instanceof Divide || op instanceof Times || op instanceof Plus || op instanceof Minus + || op instanceof Modulo || op instanceof ShiftLeft || op instanceof ShiftRight + || op instanceof BinaryAnd || op instanceof BinaryNot || op instanceof BinaryOr + || op instanceof BinaryXOr || op instanceof Negative || op instanceof PreIncrement + || op instanceof PostIncrement || op instanceof PreDecrement + || op instanceof PostDecrement) { return true; } return false; @@ -395,39 +378,27 @@ private Term convertLiteralExpression(Literal lit) { /** * performs binary numeric promotion on the argument types */ - public KeYJavaType getPromotedType(KeYJavaType type1, - KeYJavaType type2) { + public KeYJavaType getPromotedType(KeYJavaType type1, KeYJavaType type2) { final Type t1 = type1.getJavaType(); final Type t2 = type2.getJavaType(); if ((t1 == PrimitiveType.JAVA_REAL && isNumericalType(t2) || (isNumericalType(t1) && t2 == PrimitiveType.JAVA_REAL))) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_REAL); - else if ((t1 == PrimitiveType.JAVA_BOOLEAN && - t2 == PrimitiveType.JAVA_BOOLEAN)) { + else if ((t1 == PrimitiveType.JAVA_BOOLEAN && t2 == PrimitiveType.JAVA_BOOLEAN)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); - } else if ((t1 == PrimitiveType.JAVA_BYTE || - t1 == PrimitiveType.JAVA_SHORT || - t1 == PrimitiveType.JAVA_CHAR || - t1 == PrimitiveType.JAVA_INT) && - (t2 == PrimitiveType.JAVA_BYTE || - t2 == PrimitiveType.JAVA_SHORT || - t2 == PrimitiveType.JAVA_CHAR || - t2 == PrimitiveType.JAVA_INT)) { + } else if ((t1 == PrimitiveType.JAVA_BYTE || t1 == PrimitiveType.JAVA_SHORT + || t1 == PrimitiveType.JAVA_CHAR || t1 == PrimitiveType.JAVA_INT) + && (t2 == PrimitiveType.JAVA_BYTE || t2 == PrimitiveType.JAVA_SHORT + || t2 == PrimitiveType.JAVA_CHAR || t2 == PrimitiveType.JAVA_INT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_INT); - } else if ((t2 == PrimitiveType.JAVA_LONG) && - (t1 == PrimitiveType.JAVA_BYTE || - t1 == PrimitiveType.JAVA_SHORT || - t1 == PrimitiveType.JAVA_INT || - t1 == PrimitiveType.JAVA_CHAR || - t1 == PrimitiveType.JAVA_LONG)) { + } else if ((t2 == PrimitiveType.JAVA_LONG) && (t1 == PrimitiveType.JAVA_BYTE + || t1 == PrimitiveType.JAVA_SHORT || t1 == PrimitiveType.JAVA_INT + || t1 == PrimitiveType.JAVA_CHAR || t1 == PrimitiveType.JAVA_LONG)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LONG); - } else if ((t1 == PrimitiveType.JAVA_LONG) && - (t2 == PrimitiveType.JAVA_BYTE || - t2 == PrimitiveType.JAVA_SHORT || - t2 == PrimitiveType.JAVA_INT || - t2 == PrimitiveType.JAVA_CHAR || - t2 == PrimitiveType.JAVA_LONG)) { + } else if ((t1 == PrimitiveType.JAVA_LONG) && (t2 == PrimitiveType.JAVA_BYTE + || t2 == PrimitiveType.JAVA_SHORT || t2 == PrimitiveType.JAVA_INT + || t2 == PrimitiveType.JAVA_CHAR || t2 == PrimitiveType.JAVA_LONG)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LONG); } else if ((t1 == PrimitiveType.JAVA_BIGINT) && isIntegerType(t2)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BIGINT); @@ -441,49 +412,36 @@ else if ((t1 == PrimitiveType.JAVA_BOOLEAN && return type1; } else if (type2.equals(services.getJavaInfo().getKeYJavaType("java.lang.String"))) { return type2; - } else if ((t2 == PrimitiveType.JAVA_FLOAT) && - (t1 == PrimitiveType.JAVA_BYTE || - t1 == PrimitiveType.JAVA_SHORT || - t1 == PrimitiveType.JAVA_INT || - t1 == PrimitiveType.JAVA_CHAR || - t1 == PrimitiveType.JAVA_LONG || - t1 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t2 == PrimitiveType.JAVA_FLOAT) + && (t1 == PrimitiveType.JAVA_BYTE || t1 == PrimitiveType.JAVA_SHORT + || t1 == PrimitiveType.JAVA_INT || t1 == PrimitiveType.JAVA_CHAR + || t1 == PrimitiveType.JAVA_LONG || t1 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t1 == PrimitiveType.JAVA_FLOAT) && - (t2 == PrimitiveType.JAVA_BYTE || - t2 == PrimitiveType.JAVA_SHORT || - t2 == PrimitiveType.JAVA_INT || - t2 == PrimitiveType.JAVA_CHAR || - t2 == PrimitiveType.JAVA_LONG || - t2 == PrimitiveType.JAVA_FLOAT)) { + } else if ((t1 == PrimitiveType.JAVA_FLOAT) + && (t2 == PrimitiveType.JAVA_BYTE || t2 == PrimitiveType.JAVA_SHORT + || t2 == PrimitiveType.JAVA_INT || t2 == PrimitiveType.JAVA_CHAR + || t2 == PrimitiveType.JAVA_LONG || t2 == PrimitiveType.JAVA_FLOAT)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); - } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && - (t1 == PrimitiveType.JAVA_BYTE || - t1 == PrimitiveType.JAVA_SHORT || - t1 == PrimitiveType.JAVA_INT || - t1 == PrimitiveType.JAVA_CHAR || - t1 == PrimitiveType.JAVA_LONG || - t1 == PrimitiveType.JAVA_FLOAT || - t1 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t2 == PrimitiveType.JAVA_DOUBLE) && (t1 == PrimitiveType.JAVA_BYTE + || t1 == PrimitiveType.JAVA_SHORT || t1 == PrimitiveType.JAVA_INT + || t1 == PrimitiveType.JAVA_CHAR || t1 == PrimitiveType.JAVA_LONG + || t1 == PrimitiveType.JAVA_FLOAT || t1 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); - } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && - (t2 == PrimitiveType.JAVA_BYTE || - t2 == PrimitiveType.JAVA_SHORT || - t2 == PrimitiveType.JAVA_INT || - t2 == PrimitiveType.JAVA_CHAR || - t2 == PrimitiveType.JAVA_LONG || - t2 == PrimitiveType.JAVA_FLOAT || - t2 == PrimitiveType.JAVA_DOUBLE)) { + } else if ((t1 == PrimitiveType.JAVA_DOUBLE) && (t2 == PrimitiveType.JAVA_BYTE + || t2 == PrimitiveType.JAVA_SHORT || t2 == PrimitiveType.JAVA_INT + || t2 == PrimitiveType.JAVA_CHAR || t2 == PrimitiveType.JAVA_LONG + || t2 == PrimitiveType.JAVA_FLOAT || t2 == PrimitiveType.JAVA_DOUBLE)) { return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); } else { - throw new RuntimeException("Could not determine promoted type " - + "of " + t1 + " and " + t2); + throw new RuntimeException( + "Could not determine promoted type " + "of " + t1 + " and " + t2); } } public boolean isIntegerType(Type t2) { - return (t2 == PrimitiveType.JAVA_BYTE || t2 == PrimitiveType.JAVA_CHAR || t2 == PrimitiveType.JAVA_INT - || t2 == PrimitiveType.JAVA_LONG || t2 == PrimitiveType.JAVA_SHORT || t2 == PrimitiveType.JAVA_BIGINT); + return (t2 == PrimitiveType.JAVA_BYTE || t2 == PrimitiveType.JAVA_CHAR + || t2 == PrimitiveType.JAVA_INT || t2 == PrimitiveType.JAVA_LONG + || t2 == PrimitiveType.JAVA_SHORT || t2 == PrimitiveType.JAVA_BIGINT); } @@ -493,10 +451,8 @@ public KeYJavaType getPromotedType(KeYJavaType type1) { if (t1 == PrimitiveType.JAVA_BOOLEAN) // not really numeric ... return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); - else if (t1 == PrimitiveType.JAVA_BYTE || - t1 == PrimitiveType.JAVA_SHORT || - t1 == PrimitiveType.JAVA_CHAR || - t1 == PrimitiveType.JAVA_INT) + else if (t1 == PrimitiveType.JAVA_BYTE || t1 == PrimitiveType.JAVA_SHORT + || t1 == PrimitiveType.JAVA_CHAR || t1 == PrimitiveType.JAVA_INT) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_INT); else if (t1 == PrimitiveType.JAVA_LONG) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LONG); @@ -512,14 +468,13 @@ else if (t1 == PrimitiveType.JAVA_FLOAT) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); else if (t1 == PrimitiveType.JAVA_DOUBLE) return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_DOUBLE); - else throw new RuntimeException("Could not determine promoted type " + - "of " + type1); + else + throw new RuntimeException("Could not determine promoted type " + "of " + type1); } public KeYJavaType getBooleanType() { - return services.getJavaInfo() - .getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); + return services.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_BOOLEAN); } @@ -529,11 +484,10 @@ public Sort getPrimitiveSort(Type t) { /** - * Retrieves the static type of the expression. This method may only be called - * if the expressions type can be determined without knowledge of context - * information, i.e. it must not be a expression with an ex-/or implicit this - * reference like this.a or a methodcall whose value can only be determined - * when one knows the exact invocation context. + * Retrieves the static type of the expression. This method may only be called if the + * expressions type can be determined without knowledge of context information, i.e. it must not + * be a expression with an ex-/or implicit this reference like this.a or a methodcall whose + * value can only be determined when one knows the exact invocation context. *

    * For these cases please use @link #getKeYJavaType(Expression, ExecutionContext) *

    @@ -545,10 +499,10 @@ public KeYJavaType getKeYJavaType(Expression e) { /** - * retrieves the type of the expression e with respect to - * the context in which it is evaluated + * retrieves the type of the expression e with respect to the context in which it is + * evaluated * - * @param e the Expression whose type has to be retrieved + * @param e the Expression whose type has to be retrieved * @param ec the ExecutionContext of expression e * @return the KeYJavaType of expression e */ @@ -561,8 +515,8 @@ public KeYJavaType getKeYJavaType(Expression e, ExecutionContext ec) { /** - * converts a logical term to an AST node if possible. If this fails - * it throws a runtime exception. + * converts a logical term to an AST node if possible. If this fails it throws a runtime + * exception. * * @param term the Term to be converted * @return the Term as an program AST node of type expression @@ -600,8 +554,8 @@ public Expression convertToProgramElement(Term term) { return tryTranslate; } } - throw new RuntimeException("Cannot convert term to program: " + term - + " " + term.op().getClass()); + throw new RuntimeException( + "Cannot convert term to program: " + term + " " + term.op().getClass()); } @@ -641,7 +595,7 @@ public KeYJavaType getKeYJavaType(Term t) { } if (result == null) { - //HACK + // HACK result = services.getJavaInfo().getKeYJavaType(t.sort().toString()); } if (result == null) { @@ -662,49 +616,57 @@ public KeYJavaType getKeYJavaType(Type t) { */ public boolean isWidening(PrimitiveType from, PrimitiveType to) { // we do not handle null's - if (from == null || to == null) return false; + if (from == null || to == null) + return false; // equal types can be coerced - if (from == to) return true; + if (from == to) + return true; // boolean types cannot be coerced into something else - if (from == PrimitiveType.JAVA_BOOLEAN || - to == PrimitiveType.JAVA_BOOLEAN) + if (from == PrimitiveType.JAVA_BOOLEAN || to == PrimitiveType.JAVA_BOOLEAN) return false; // everything else can be coerced to a \real - if (to == PrimitiveType.JAVA_REAL) return true; + if (to == PrimitiveType.JAVA_REAL) + return true; // everything except \real and \bigint can be coerced to a double - if (to == PrimitiveType.JAVA_DOUBLE) return from != PrimitiveType.JAVA_BIGINT; + if (to == PrimitiveType.JAVA_DOUBLE) + return from != PrimitiveType.JAVA_BIGINT; // but a double cannot be coerced to anything else - if (from == PrimitiveType.JAVA_DOUBLE) return from != PrimitiveType.JAVA_BIGINT; + if (from == PrimitiveType.JAVA_DOUBLE) + return from != PrimitiveType.JAVA_BIGINT; // everything except doubles can be coerced to a float - if (to == PrimitiveType.JAVA_FLOAT) return true; + if (to == PrimitiveType.JAVA_FLOAT) + return true; // but a float cannot be coerced to anything but float or double - if (from == PrimitiveType.JAVA_FLOAT) return false; + if (from == PrimitiveType.JAVA_FLOAT) + return false; // any integral type can be coerced to a \bigint - if (to == PrimitiveType.JAVA_BIGINT) return true; + if (to == PrimitiveType.JAVA_BIGINT) + return true; // everything except the above can be coerced to a long - if (to == PrimitiveType.JAVA_LONG) return true; + if (to == PrimitiveType.JAVA_LONG) + return true; // but a long cannot be coerced to anything but float, double or long - if (from == PrimitiveType.JAVA_LONG) return false; + if (from == PrimitiveType.JAVA_LONG) + return false; // everything except long, float or double can be coerced to an int - if (to == PrimitiveType.JAVA_INT) return true; + if (to == PrimitiveType.JAVA_INT) + return true; // but an int cannot be coerced to the remaining byte, char, short - if (from == PrimitiveType.JAVA_INT) return false; + if (from == PrimitiveType.JAVA_INT) + return false; // between byte, char, short, only one conversion is admissible - return (from == PrimitiveType.JAVA_BYTE && - to == PrimitiveType.JAVA_SHORT); + return (from == PrimitiveType.JAVA_BYTE && to == PrimitiveType.JAVA_SHORT); } public boolean isWidening(ClassType from, ClassType to) { - return isWidening(getKeYJavaType(from), - getKeYJavaType(to)); + return isWidening(getKeYJavaType(from), getKeYJavaType(to)); } public boolean isWidening(ArrayType from, ArrayType to) { KeYJavaType toBase = to.getBaseType().getKeYJavaType(); - if (toBase == - services.getJavaInfo().getJavaLangObject()) { // seems incorrect + if (toBase == services.getJavaInfo().getJavaLangObject()) { // seems incorrect return true; } KeYJavaType fromBase = from.getBaseType().getKeYJavaType(); @@ -717,15 +679,12 @@ public boolean isWidening(ArrayType from, ArrayType to) { public boolean isWidening(Type from, Type to) { if (from instanceof KeYJavaType) - return isWidening((KeYJavaType) from, - getKeYJavaType(to)); + return isWidening((KeYJavaType) from, getKeYJavaType(to)); if (to instanceof KeYJavaType) - return isWidening(getKeYJavaType(from), - (KeYJavaType) to); + return isWidening(getKeYJavaType(from), (KeYJavaType) to); if (from instanceof ClassType) { - return isWidening(getKeYJavaType(from), - getKeYJavaType(to)); + return isWidening(getKeYJavaType(from), getKeYJavaType(to)); } else if (from instanceof PrimitiveType) { if (to instanceof PrimitiveType) { return isWidening((PrimitiveType) from, (PrimitiveType) to); @@ -748,24 +707,18 @@ public boolean isWidening(KeYJavaType from, KeYJavaType to) { Type b = to.getJavaType(); if (a instanceof ClassType || a == null) { - return - from.getSort().extendsTrans(to.getSort()) || - (a == NullType.JAVA_NULL && - b instanceof ArrayType); + return from.getSort().extendsTrans(to.getSort()) + || (a == NullType.JAVA_NULL && b instanceof ArrayType); } else { if (b == null) - return - to == services.getJavaInfo(). - getJavaLangObject() && - a instanceof ArrayType; + return to == services.getJavaInfo().getJavaLangObject() && a instanceof ArrayType; else return isWidening(a, b); } } - public boolean isImplicitNarrowing - (Expression expr, PrimitiveType to) { + public boolean isImplicitNarrowing(Expression expr, PrimitiveType to) { int minValue, maxValue; if (to == PrimitiveType.JAVA_BYTE) { @@ -781,14 +734,12 @@ public boolean isWidening(KeYJavaType from, KeYJavaType to) { return false; } - ConstantExpressionEvaluator cee = - services.getConstantExpressionEvaluator(); + ConstantExpressionEvaluator cee = services.getConstantExpressionEvaluator(); - ConstantEvaluator.EvaluationResult res = - new ConstantEvaluator.EvaluationResult(); + ConstantEvaluator.EvaluationResult res = new ConstantEvaluator.EvaluationResult(); - if (!cee.isCompileTimeConstant(expr, res) || - res.getTypeCode() != ConstantEvaluator.INT_TYPE) { + if (!cee.isCompileTimeConstant(expr, res) + || res.getTypeCode() != ConstantEvaluator.INT_TYPE) { return false; } int value = res.getInt(); @@ -798,8 +749,8 @@ public boolean isWidening(KeYJavaType from, KeYJavaType to) { public boolean isIdentical(Type from, Type to) { // XXX causes bug #1163 -// from = getKeYJavaType ( from ); -// to = getKeYJavaType ( to ); + // from = getKeYJavaType ( from ); + // to = getKeYJavaType ( to ); return from == to; } @@ -810,11 +761,9 @@ public boolean isAssignableTo(Type from, Type to) { public boolean isAssignableTo(Expression expr, Type to, ExecutionContext ec) { - return - (to instanceof PrimitiveType && - isImplicitNarrowing(expr, (PrimitiveType) to)) || - isIdentical(expr.getKeYJavaType(services, ec), to) || - isWidening(expr.getKeYJavaType(services, ec), to); + return (to instanceof PrimitiveType && isImplicitNarrowing(expr, (PrimitiveType) to)) + || isIdentical(expr.getKeYJavaType(services, ec), to) + || isWidening(expr.getKeYJavaType(services, ec), to); } @@ -824,11 +773,9 @@ public boolean isNarrowing(KeYJavaType from, KeYJavaType to) { Type b = to.getJavaType(); if (a instanceof ClassType || a == null) { - return - to.getSort().extendsTrans(from.getSort()) || - (from == services. - getJavaInfo().getJavaLangObject() && - a instanceof ArrayType); + return to.getSort().extendsTrans(from.getSort()) + || (from == services.getJavaInfo().getJavaLangObject() + && a instanceof ArrayType); } else { if (b == null) return false; @@ -840,44 +787,35 @@ public boolean isNarrowing(KeYJavaType from, KeYJavaType to) { public boolean isNarrowing(PrimitiveType from, PrimitiveType to) { // we do not handle null's - if (from == null || to == null) return false; + if (from == null || to == null) + return false; if (from == PrimitiveType.JAVA_BYTE) { return (to == PrimitiveType.JAVA_CHAR); } if (from == PrimitiveType.JAVA_SHORT) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_CHAR); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_CHAR); } if (from == PrimitiveType.JAVA_CHAR) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_SHORT); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_SHORT); } if (from == PrimitiveType.JAVA_INT) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_SHORT || - to == PrimitiveType.JAVA_CHAR); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_SHORT + || to == PrimitiveType.JAVA_CHAR); } if (from == PrimitiveType.JAVA_LONG) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_SHORT || - to == PrimitiveType.JAVA_CHAR || - to == PrimitiveType.JAVA_INT); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_SHORT + || to == PrimitiveType.JAVA_CHAR || to == PrimitiveType.JAVA_INT); } if (from == PrimitiveType.JAVA_FLOAT) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_SHORT || - to == PrimitiveType.JAVA_CHAR || - to == PrimitiveType.JAVA_INT || - to == PrimitiveType.JAVA_LONG); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_SHORT + || to == PrimitiveType.JAVA_CHAR || to == PrimitiveType.JAVA_INT + || to == PrimitiveType.JAVA_LONG); } if (from == PrimitiveType.JAVA_DOUBLE) { - return (to == PrimitiveType.JAVA_BYTE || - to == PrimitiveType.JAVA_SHORT || - to == PrimitiveType.JAVA_CHAR || - to == PrimitiveType.JAVA_INT || - to == PrimitiveType.JAVA_LONG || - to == PrimitiveType.JAVA_FLOAT); + return (to == PrimitiveType.JAVA_BYTE || to == PrimitiveType.JAVA_SHORT + || to == PrimitiveType.JAVA_CHAR || to == PrimitiveType.JAVA_INT + || to == PrimitiveType.JAVA_LONG || to == PrimitiveType.JAVA_FLOAT); } if (from == PrimitiveType.JAVA_BIGINT) { return (to != PrimitiveType.JAVA_REAL && to != from); @@ -890,32 +828,26 @@ public boolean isNarrowing(PrimitiveType from, PrimitiveType to) { public boolean isNarrowing(ClassType from, ClassType to) { - return isNarrowing(getKeYJavaType(from), - getKeYJavaType(to)); + return isNarrowing(getKeYJavaType(from), getKeYJavaType(to)); } public boolean isNarrowing(ArrayType from, ArrayType to) { KeYJavaType toBase = to.getBaseType().getKeYJavaType(); KeYJavaType fromBase = from.getBaseType().getKeYJavaType(); - return - isReferenceType(toBase) && - isReferenceType(fromBase) && - isNarrowing(fromBase, toBase); + return isReferenceType(toBase) && isReferenceType(fromBase) + && isNarrowing(fromBase, toBase); } public boolean isNarrowing(Type from, Type to) { if (from instanceof KeYJavaType) - return isNarrowing((KeYJavaType) from, - getKeYJavaType(to)); + return isNarrowing((KeYJavaType) from, getKeYJavaType(to)); if (to instanceof KeYJavaType) - return isNarrowing(getKeYJavaType(from), - (KeYJavaType) to); + return isNarrowing(getKeYJavaType(from), (KeYJavaType) to); if (from instanceof ClassType) { - return isNarrowing(getKeYJavaType(from), - getKeYJavaType(to)); + return isNarrowing(getKeYJavaType(from), getKeYJavaType(to)); } else if (from instanceof PrimitiveType) { if (to instanceof PrimitiveType) { return isNarrowing((PrimitiveType) from, (PrimitiveType) to); @@ -937,8 +869,7 @@ public boolean isCastingTo(Type from, Type to) { return true; // conversions between numeric types are always possible - if (isNumericalType(from) && - isNumericalType(to)) + if (isNumericalType(from) && isNumericalType(to)) return true; // all widening conversions @@ -953,30 +884,20 @@ public boolean isCastingTo(Type from, Type to) { public boolean isNumericalType(Type t) { if (t instanceof KeYJavaType) t = ((KeYJavaType) t).getJavaType(); - return - t == PrimitiveType.JAVA_BYTE || - t == PrimitiveType.JAVA_SHORT || - t == PrimitiveType.JAVA_INT || - t == PrimitiveType.JAVA_CHAR || - t == PrimitiveType.JAVA_LONG || - t == PrimitiveType.JAVA_BIGINT || - t == PrimitiveType.JAVA_FLOAT || - t == PrimitiveType.JAVA_DOUBLE || - t == PrimitiveType.JAVA_REAL - ; + return t == PrimitiveType.JAVA_BYTE || t == PrimitiveType.JAVA_SHORT + || t == PrimitiveType.JAVA_INT || t == PrimitiveType.JAVA_CHAR + || t == PrimitiveType.JAVA_LONG || t == PrimitiveType.JAVA_BIGINT + || t == PrimitiveType.JAVA_FLOAT || t == PrimitiveType.JAVA_DOUBLE + || t == PrimitiveType.JAVA_REAL; } public boolean isIntegralType(Type t) { if (t instanceof KeYJavaType) t = ((KeYJavaType) t).getJavaType(); - return - t == PrimitiveType.JAVA_BYTE || - t == PrimitiveType.JAVA_SHORT || - t == PrimitiveType.JAVA_INT || - t == PrimitiveType.JAVA_CHAR || - t == PrimitiveType.JAVA_LONG || - t == PrimitiveType.JAVA_BIGINT; + return t == PrimitiveType.JAVA_BYTE || t == PrimitiveType.JAVA_SHORT + || t == PrimitiveType.JAVA_INT || t == PrimitiveType.JAVA_CHAR + || t == PrimitiveType.JAVA_LONG || t == PrimitiveType.JAVA_BIGINT; } @@ -984,26 +905,22 @@ public boolean isReferenceType(Type t) { if (t instanceof KeYJavaType) t = ((KeYJavaType) t).getJavaType(); return - // there is currently no interface handling - t == null || - (t instanceof ClassType && !(t instanceof NullType)) || - t instanceof ArrayType; + // there is currently no interface handling + t == null || (t instanceof ClassType && !(t instanceof NullType)) || t instanceof ArrayType; } public boolean isNullType(Type t) { if (t instanceof KeYJavaType) t = ((KeYJavaType) t).getJavaType(); - return - t == NullType.JAVA_NULL; + return t == NullType.JAVA_NULL; } public boolean isBooleanType(Type t) { if (t instanceof KeYJavaType) t = ((KeYJavaType) t).getJavaType(); - return - t == PrimitiveType.JAVA_BOOLEAN; + return t == PrimitiveType.JAVA_BOOLEAN; } public TypeConverter copy(Services services) { @@ -1012,7 +929,8 @@ public TypeConverter copy(Services services) { return TC; } - private LDT getResponsibleLDT(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, Services services, ExecutionContext ec) { + private LDT getResponsibleLDT(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { for (LDT ldt : LDTs.values()) { if (ldt.isResponsible(op, subs, services, ec)) { return ldt; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeNameTranslator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeNameTranslator.java index 69748e573a1..c04af15823b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeNameTranslator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeNameTranslator.java @@ -1,58 +1,62 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; -public class TypeNameTranslator{ +public class TypeNameTranslator { private TypeNameTranslator() {} /** - * returns the basetype of t. - * example: getBaseType("[[[I") returns "int". + * returns the basetype of t. example: getBaseType("[[[I") returns + * "int". */ - public static String getBaseType(String t){ - if(t==null || !t.startsWith("[")){ - return t; - } - while(t.startsWith("[")){ - t = t.substring(1); - } - if(t.startsWith("L")){ - return t.substring(1); - }else if(t.startsWith("B")){ - return "byte"; - }else if(t.startsWith("C")){ - return "char"; - }else if(t.startsWith("D")){ - return "double"; - }else if(t.startsWith("F")){ - return "float"; - }else if(t.startsWith("I")){ - return "int"; - }else if(t.startsWith("J")){ - return "long"; - }else if(t.startsWith("S")){ - return "short"; - }else if(t.startsWith("Z")){ - return "boolean"; - }else{ - return t; - } + public static String getBaseType(String t) { + if (t == null || !t.startsWith("[")) { + return t; + } + while (t.startsWith("[")) { + t = t.substring(1); + } + if (t.startsWith("L")) { + return t.substring(1); + } else if (t.startsWith("B")) { + return "byte"; + } else if (t.startsWith("C")) { + return "char"; + } else if (t.startsWith("D")) { + return "double"; + } else if (t.startsWith("F")) { + return "float"; + } else if (t.startsWith("I")) { + return "int"; + } else if (t.startsWith("J")) { + return "long"; + } else if (t.startsWith("S")) { + return "short"; + } else if (t.startsWith("Z")) { + return "boolean"; + } else { + return t; + } } - - /** returns the dimensions of an ArrayType. Returns 0 if - * t doesn't represent an ArrayType. + + /** + * returns the dimensions of an ArrayType. Returns 0 if t doesn't represent an + * ArrayType. */ - public static int getDimensions(String t){ - if(t==null || !t.startsWith("[")){ - return 0; - } - int i=0; - while(t.startsWith("[")){ - t = t.substring(1); - i++; - } - return i; + public static int getDimensions(String t) { + if (t == null || !t.startsWith("[")) { + return 0; + } + int i = 0; + while (t.startsWith("[")) { + t = t.substring(1); + i++; + } + return i; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeScope.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeScope.java index f54cbf831fd..82d6b200391 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeScope.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/TypeScope.java @@ -1,12 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * The property of a non terminal program element to define a scope for - * types. - * taken from COMPOST and changed to achieve an immutable structure + * The property of a non terminal program element to define a scope for types. taken from COMPOST + * and changed to achieve an immutable structure */ public interface TypeScope extends ScopeDefiningElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/UnknownJavaTypeException.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/UnknownJavaTypeException.java index 40d4279f79c..8ff5a7e5d53 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/UnknownJavaTypeException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/UnknownJavaTypeException.java @@ -1,14 +1,17 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; public class UnknownJavaTypeException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 3892695426311405161L; + /** + * + */ + private static final long serialVersionUID = 3892695426311405161L; - public UnknownJavaTypeException(String s) { - super(s); - } - -} \ No newline at end of file + public UnknownJavaTypeException(String s) { + super(s); + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/VariableScope.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/VariableScope.java index 6b5b8a6af70..91c378d05ba 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/VariableScope.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/VariableScope.java @@ -1,10 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java; /** - * The property of a non terminal program element to define a scope for - * variables. - * taken from COMPOST and changed to achieve an immutable structure + * The property of a non terminal program element to define a scope for variables. taken from + * COMPOST and changed to achieve an immutable structure */ public interface VariableScope extends ScopeDefiningElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ArrayType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ArrayType.java index a648910cb23..596738bc100 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ArrayType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ArrayType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // Modified by KeY package de.uka.ilkd.key.java.abstraction; @@ -5,22 +8,24 @@ import de.uka.ilkd.key.java.reference.TypeReference; /** - A program model element representing array types. + * A program model element representing array types. */ public interface ArrayType extends Type { /** * returns the type reference to the arrays base type + * * @return the type reference to the arrays base type */ TypeReference getBaseType(); - + /** - * returns the dimension of the array + * returns the dimension of the array + * * @return an int containing the array's dimension */ int getDimension(); - + /** * name of the array type */ @@ -30,10 +35,10 @@ public interface ArrayType extends Type { * full name of the array type */ String getFullName(); - + /** - * full name of the array in alternative form, i.e. - * e.g. int[] instead of [I + * full name of the array in alternative form, i.e. e.g. int[] instead of + * [I */ String getAlternativeNameRepresentation(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassType.java index be48668c2a6..55baab4980c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import org.key_project.util.collection.ImmutableList; @@ -5,85 +8,90 @@ import de.uka.ilkd.key.java.Services; /** - A program model element representing class types. - @author AL - @author RN + * A program model element representing class types. + * + * @author AL + * @author RN */ public interface ClassType extends Type, Member, ClassTypeContainer { /** - Checks if this class type denotes an interface. - @return true if this object represents an interface, - false if it is an ordinary class. + * Checks if this class type denotes an interface. + * + * @return true if this object represents an interface, false if it is + * an ordinary class. */ boolean isInterface(); /** - Checks if this member is abstract. An interface will report - true. - @return true if this member is abstract, - false otherwise. - @see #isInterface() + * Checks if this member is abstract. An interface will report true. + * + * @return true if this member is abstract, false otherwise. + * @see #isInterface() */ boolean isAbstract(); - - /** - Returns the array of locally declared supertypes of this class type. - @return the array of locally defined supertypes of this type. - */ + + /** + * Returns the array of locally declared supertypes of this class type. + * + * @return the array of locally defined supertypes of this type. + */ ImmutableList getSupertypes(); - - /** - Returns the array of all supertypes of this class type, - in topological order, including the class type isself as first element. - The order allows to resolve member overloading or overloading. - @return the array of all supertypes of this type in topological order. - */ + + /** + * Returns the array of all supertypes of this class type, in topological order, including the + * class type isself as first element. The order allows to resolve member overloading or + * overloading. + * + * @return the array of all supertypes of this type in topological order. + */ ImmutableList getAllSupertypes(Services services); - /** - Returns the fields locally defined within this class type. - @return the array of field members of this type. - */ + /** + * Returns the fields locally defined within this class type. + * + * @return the array of field members of this type. + */ ImmutableList getFields(Services services); - - /** - Returns all visible fields that are defined in this class type - or any of its supertypes. The fields are in topological order - with respect to the inheritance hierarchy. - @return the array of visible field members of this type and its - supertypes. - */ + + /** + * Returns all visible fields that are defined in this class type or any of its supertypes. The + * fields are in topological order with respect to the inheritance hierarchy. + * + * @return the array of visible field members of this type and its supertypes. + */ ImmutableList getAllFields(Services services); - /** - Returns the methods locally defined within this class type. - @return the array of methods of this type. - */ + /** + * Returns the methods locally defined within this class type. + * + * @return the array of methods of this type. + */ ImmutableList getMethods(Services services); - /** - Returns all visible methods that are defined in this class type - or any of its supertypes. The methods are in topological order - with respect to the inheritance hierarchy. - @return the array of visible methods of this type and its supertypes. - */ + /** + * Returns all visible methods that are defined in this class type or any of its supertypes. The + * methods are in topological order with respect to the inheritance hierarchy. + * + * @return the array of visible methods of this type and its supertypes. + */ ImmutableList getAllMethods(Services services); - /** - Returns the constructors locally defined within this class type. - @return the array of constructors of this type. - */ + /** + * Returns the constructors locally defined within this class type. + * + * @return the array of constructors of this type. + */ ImmutableList getConstructors(Services services); - - /** - Returns all class types that are inner types of this class type, - including visible inherited types. - @return an array of class types that are members of this type - or any of its supertypes. - @see #getAllSupertypes - */ + + /** + * Returns all class types that are inner types of this class type, including visible inherited + * types. + * + * @return an array of class types that are members of this type or any of its supertypes. + * @see #getAllSupertypes + */ ImmutableList getAllTypes(Services services); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassTypeContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassTypeContainer.java index 7ebd964d7a3..3357365f655 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassTypeContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ClassTypeContainer.java @@ -1,30 +1,35 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element that may contain class types. + * A program model element that may contain class types. */ public interface ClassTypeContainer extends ProgramModelElement { - /** - Returns the class types locally defined within this container. - Returns inner types when this container is a class type. - @return an array of contained class types. - */ - // ClassType[] getTypes(); + /** + * Returns the class types locally defined within this container. Returns inner types when this + * container is a class type. + * + * @return an array of contained class types. + */ + // ClassType[] getTypes(); /** - Returns the package this element is defined in. Packages - have no recursive scope and report themselves. - @return the package of this element. + * Returns the package this element is defined in. Packages have no recursive scope and report + * themselves. + * + * @return the package of this element. */ // Package getPackage(); - + /** - Returns the enclosing package or class type, or method. - A package will report null, a methods its enclosing - class. - @return the container of this element. + * Returns the enclosing package or class type, or method. A package will report null, + * a methods its enclosing class. + * + * @return the container of this element. */ // ClassTypeContainer getContainer(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Constructor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Constructor.java index 6438d66130a..9b2b51413b7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Constructor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Constructor.java @@ -1,8 +1,11 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element representing constructors. - Constructors are modelled as subtypes of methods and will return - the enclosing type as return type. + * A program model element representing constructors. Constructors are modelled as subtypes of + * methods and will return the enclosing type as return type. */ -public interface Constructor extends Method {} \ No newline at end of file +public interface Constructor extends Method { +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/DefaultConstructor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/DefaultConstructor.java index ade71f0c461..b6e560f17ec 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/DefaultConstructor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/DefaultConstructor.java @@ -1,10 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import org.key_project.util.ExtList; /** - Default constructor of class types. - @deprecated is actually never used + * Default constructor of class types. + * + * @deprecated is actually never used */ @Deprecated public class DefaultConstructor implements Constructor { @@ -13,152 +17,169 @@ public class DefaultConstructor implements Constructor { protected final boolean parentIsPublic; - //???use ProgramElementName instead of name????? + // ???use ProgramElementName instead of name????? public DefaultConstructor(ExtList children) { - name=children.get(String.class); - parentIsPublic=children.get(Boolean.class).booleanValue(); + name = children.get(String.class); + parentIsPublic = children.get(Boolean.class).booleanValue(); } /** - Create a new default constructor for the given class type. - The name of the constructor is set appropriately. - @param name of the Constructor - @param parentIsPublic is set true iff the parent is declared public. + * Create a new default constructor for the given class type. The name of the constructor is set + * appropriately. + * + * @param name of the Constructor + * @param parentIsPublic is set true iff the parent is declared public. */ @Deprecated public DefaultConstructor(String name, boolean parentIsPublic) { - this.parentIsPublic = parentIsPublic; - this.name=name; + this.parentIsPublic = parentIsPublic; + this.name = name; } - + /** - Checks if this member is final. - @return false. + * Checks if this member is final. + * + * @return false. */ public boolean isFinal() { - return false; + return false; } - + /** - Checks if this member is static. - @return true. + * Checks if this member is static. + * + * @return true. */ public boolean isStatic() { - return true; + return true; } - + /** - Checks if this member is private. - @return false. + * Checks if this member is private. + * + * @return false. */ public boolean isPrivate() { - return false; + return false; } - + /** - Checks if this member is protected. - @return false. + * Checks if this member is protected. + * + * @return false. */ public boolean isProtected() { - return false; + return false; } - + /** - Checks if this member is public. - @return true, if the containing class type is public, - false otherwise. + * Checks if this member is public. + * + * @return true, if the containing class type is public, false + * otherwise. */ public boolean isPublic() { - return parentIsPublic; - // else, it is package visible + return parentIsPublic; + // else, it is package visible } - + /** - Checks if this member is protected. - @return false. + * Checks if this member is protected. + * + * @return false. */ public boolean isStrictFp() { - return false; + return false; } /** - Checks if this member is abstract. - @return false. + * Checks if this member is abstract. + * + * @return false. */ public boolean isAbstract() { - return false; + return false; } /** - Checks if this member is native. - @return false. + * Checks if this member is native. + * + * @return false. */ public boolean isNative() { - return false; + return false; } - + /** - Checks if this member is synchronized. - @return false. + * Checks if this member is synchronized. + * + * @return false. */ public boolean isSynchronized() { - return false; + return false; } - - /** TO BE IMPLEMENTED - Returns the signature of this constructor. - @return the signature of this constructor. - */ - public Type[] getSignature(){ - return new Type[0]; + + /** + * TO BE IMPLEMENTED Returns the signature of this constructor. + * + * @return the signature of this constructor. + */ + public Type[] getSignature() { + return new Type[0]; } - /** - Returns the return type of this method. - @return the return type of this method. - */ + /** + * Returns the return type of this method. + * + * @return the return type of this method. + */ public Type getReturnType() { return null; } - /** - Returns the (empty) exception list of this constructor. - @return the (empty) exception list of this constructor. - */ + /** + * Returns the (empty) exception list of this constructor. + * + * @return the (empty) exception list of this constructor. + */ public ClassType[] getExceptions() { return new ClassType[0]; } - /** TO BE IMPLEMENTED - Returns the package this element is defined in. - @return the package of this element. + /** + * TO BE IMPLEMENTED Returns the package this element is defined in. + * + * @return the package of this element. */ public Package getPackage() { return null; } - /** TO BE IMPLEMENTED - Returns the (empty) list of class types locally defined within this - container. - @return a list of contained class types. - */ + /** + * TO BE IMPLEMENTED Returns the (empty) list of class types locally defined within this + * container. + * + * @return a list of contained class types. + */ public ClassType[] getTypes() { return new ClassType[0]; } /** - Returns the name of this element. - @return the name of this element. + * Returns the name of this element. + * + * @return the name of this element. */ public String getName() { return name; } - + /** - Returns the name of this element. - @return the name of this element. + * Returns the name of this element. + * + * @return the name of this element. */ public String getFullName() { return name; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Field.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Field.java index f992d2f26c2..3994eb81bf7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Field.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Field.java @@ -1,28 +1,31 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import de.uka.ilkd.key.logic.op.IProgramVariable; /** - A program model element representing fields. - @author AL - @author RN - The file has been modified by the KeY team. + * A program model element representing fields. + * + * @author AL + * @author RN The file has been modified by the KeY team. */ public interface Field extends Variable, Member { - /** - * returns the program variable associated with this field - * @return the program variable associated with this field + /** + * returns the program variable associated with this field + * + * @return the program variable associated with this field */ IProgramVariable getProgramVariable(); /** - * returns the name of the field as used in programs. In the logic - * each field has a unique name which is composed by the class name where - * it is declared and its source code name + * returns the name of the field as used in programs. In the logic each field has a unique name + * which is composed by the class name where it is declared and its source code name * * @return returns the name of the field as used in programs */ String getProgramName(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/KeYJavaType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/KeYJavaType.java index 03331e7c6c8..7f8773f2d14 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/KeYJavaType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/KeYJavaType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import java.util.Comparator; @@ -10,124 +13,123 @@ import de.uka.ilkd.key.util.MiscTools; /** - * The KeY java type realises a tuple (sort, type) of a logic sort and - * the java type (for example a class declaration). - * In contrast to other classes the KeYJavaType is not - * immutable, so use it with care. + * The KeY java type realises a tuple (sort, type) of a logic sort and the java type (for example a + * class declaration). In contrast to other classes the KeYJavaType is not immutable, + * so use it with care. */ public class KeYJavaType implements Type { /** Special return "type" for void methods. */ - public static final KeYJavaType VOID_TYPE = new KeYJavaType(null,Sort.ANY); + public static final KeYJavaType VOID_TYPE = new KeYJavaType(null, Sort.ANY); /** the AST type */ - private Type javaType=null; + private Type javaType = null; /** the logic sort */ - private Sort sort=null; - + private Sort sort = null; + /** creates a new KeYJavaType */ - public KeYJavaType() { - } + public KeYJavaType() {} /** creates a new KeYJavaType */ public KeYJavaType(Type javaType, Sort sort) { - this.javaType = javaType; - this.sort = sort; + this.javaType = javaType; + this.sort = sort; } /** creates a new KeYJavaType */ public KeYJavaType(Sort sort) { - this.sort = sort; + this.sort = sort; } /** creates a new KeYJavaType */ public KeYJavaType(Type type) { - this.javaType = type; + this.javaType = type; } - + public void setJavaType(Type type) { - javaType = type; + javaType = type; } - + public void setSort(Sort s) { - sort = s; + sort = s; } public Type getJavaType() { - return javaType; + return javaType; } public Sort getSort() { - return sort; + return sort; } - /** - * Returns the default value of the given type - * according to JLS Sect. 4.5.5; - * returns null if this is not a real Java type. - * @return the default value of the given type - * according to JLS Sect. 4.5.5 + /** + * Returns the default value of the given type according to JLS Sect. 4.5.5; returns null if + * this is not a real Java type. + * + * @return the default value of the given type according to JLS Sect. 4.5.5 */ public Literal getDefaultValue() { - if (javaType == null) return null; + if (javaType == null) + return null; return javaType.getDefaultValue(); } - + public String toString() { if (this == VOID_TYPE) return "KeYJavaType:void"; - if (javaType == null) return "KeYJavaType:null,"+sort; - return "(type, sort): ("+javaType.getName()+","+sort+")"; + if (javaType == null) + return "KeYJavaType:null," + sort; + return "(type, sort): (" + javaType.getName() + "," + sort + ")"; } public String getFullName() { - return Optional.ofNullable(getJavaType()).map(Type::getFullName) + return Optional.ofNullable(getJavaType()).map(Type::getFullName) .orElse(getSort().name().toString()); } public String getName() { - return Optional.ofNullable(getJavaType()).map(Type::getName) + return Optional.ofNullable(getJavaType()).map(Type::getName) .orElse(getSort().name().toString()); } - + @Override - public boolean equals(Object o){ - if (o == this) { - return true; - } - if (o == null || o.getClass() != this.getClass()) { - return false; - } - try { - return MiscTools.equalsOrNull(javaType,((KeYJavaType)o).javaType) && - MiscTools.equalsOrNull(sort,((KeYJavaType)o).sort); + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o == null || o.getClass() != this.getClass()) { + return false; + } + try { + return MiscTools.equalsOrNull(javaType, ((KeYJavaType) o).javaType) + && MiscTools.equalsOrNull(sort, ((KeYJavaType) o).sort); } catch (Exception e) { - return false; + return false; } } @Override public int hashCode() { - return 0; + return 0; } - - + + public PackageReference createPackagePrefix() { - PackageReference ref = null; - String rest = getFullName(); - if (rest.indexOf(".")>0) { - rest = rest.substring(0, rest.lastIndexOf(".")+1); - while (rest.indexOf(".")>0) { - String name = rest.substring(0, rest.indexOf(".")); - rest = rest.substring(rest.indexOf(".")+1); - ref = new PackageReference(new ProgramElementName(name), ref); - } - } - return ref; + PackageReference ref = null; + String rest = getFullName(); + if (rest.indexOf(".") > 0) { + rest = rest.substring(0, rest.lastIndexOf(".") + 1); + while (rest.indexOf(".") > 0) { + String name = rest.substring(0, rest.indexOf(".")); + rest = rest.substring(rest.indexOf(".") + 1); + ref = new PackageReference(new ProgramElementName(name), ref); + } + } + return ref; } - public static final class LexicographicalKeYJavaTypeOrder - implements Comparator { + public static final class LexicographicalKeYJavaTypeOrder + implements Comparator { public int compare(T arg0, T arg1) { return arg0.getFullName().compareTo(arg1.getFullName()); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Member.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Member.java index ad8d3dfcd02..849ea7f2e3f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Member.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Member.java @@ -1,50 +1,53 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element representing members. + * A program model element representing members. */ public interface Member extends ProgramModelElement { /** - Checks if this member is final. - @return true if this member is final, - false otherwise. + * Checks if this member is final. + * + * @return true if this member is final, false otherwise. */ boolean isFinal(); - + /** - Checks if this member is static. Returns true - for {@link recoder.abstraction.Constructor}s. - @return true if this member is static, - false otherwise. + * Checks if this member is static. Returns true for + * {@link recoder.abstraction.Constructor}s. + * + * @return true if this member is static, false otherwise. */ boolean isStatic(); - + /** - Checks if this member is private. - @return true if this member is private, - false otherwise. + * Checks if this member is private. + * + * @return true if this member is private, false otherwise. */ boolean isPrivate(); - + /** - Checks if this member is protected. - @return true if this member is protected, - false otherwise. + * Checks if this member is protected. + * + * @return true if this member is protected, false otherwise. */ boolean isProtected(); - + /** - Checks if this member is public. - @return true if this member is public, - false otherwise. + * Checks if this member is public. + * + * @return true if this member is public, false otherwise. */ boolean isPublic(); - + /** - Checks if this member is strictfp. - @return true if this member is strictfp, - false otherwise. + * Checks if this member is strictfp. + * + * @return true if this member is strictfp, false otherwise. */ boolean isStrictFp(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Method.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Method.java index d778c98dcc9..0fe639e8554 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Method.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Method.java @@ -1,35 +1,35 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element representing methods. + * A program model element representing methods. */ public interface Method extends Member, ClassTypeContainer { - + /** - Checks if this member is abstract. A constructor will report - false. - @return true if this member is abstract, - false otherwise. - @see recoder.abstraction.Constructor + * Checks if this member is abstract. A constructor will report false. + * + * @return true if this member is abstract, false otherwise. + * @see recoder.abstraction.Constructor */ boolean isAbstract(); /** - Checks if this method is native. A constructor will report - false. - @return true if this method is native, - false otherwise. - @see recoder.abstraction.Constructor + * Checks if this method is native. A constructor will report false. + * + * @return true if this method is native, false otherwise. + * @see recoder.abstraction.Constructor */ boolean isNative(); /** - Checks if this method is synchronized. A constructor will report - false. - @return true if this method is synchronized, - false otherwise. - @see recoder.abstraction.Constructor + * Checks if this method is synchronized. A constructor will report false. + * + * @return true if this method is synchronized, false otherwise. + * @see recoder.abstraction.Constructor */ boolean isSynchronized(); - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/NullType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/NullType.java index fec82ad797b..6aadd7abd82 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/NullType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/NullType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import org.key_project.util.collection.ImmutableList; @@ -6,196 +9,211 @@ import de.uka.ilkd.key.java.expression.Literal; /** - A program model element representing the null type. - @author AL - @author RN + * A program model element representing the null type. + * + * @author AL + * @author RN */ public class NullType implements ClassType { public static final NullType JAVA_NULL = new NullType(); - private NullType(){} + + private NullType() {} /** - The name of this type. + * The name of this type. */ public static final String NULL = "null"; /** - Returns the name of this element. - @return "null". + * Returns the name of this element. + * + * @return "null". */ public String getName() { - return NULL; + return NULL; } /** - Returns the name of this element. - @return "null". + * Returns the name of this element. + * + * @return "null". */ public String getFullName() { - return NULL; + return NULL; } /** - Checks if this member is final. - @return true. + * Checks if this member is final. + * + * @return true. */ public boolean isFinal() { - return true; + return true; } /** - Checks if this member is static. - @return true. + * Checks if this member is static. + * + * @return true. */ public boolean isStatic() { - return true; + return true; } /** - Checks if this member is private. - @return false. + * Checks if this member is private. + * + * @return false. */ public boolean isPrivate() { - return false; + return false; } /** - Checks if this member is protected. - @return false. + * Checks if this member is protected. + * + * @return false. */ public boolean isProtected() { - return false; + return false; } /** - Checks if this member is public. - @return true. + * Checks if this member is public. + * + * @return true. */ public boolean isPublic() { - return true; + return true; } /** - Checks if this member is strictfp. - @return false. + * Checks if this member is strictfp. + * + * @return false. */ public boolean isStrictFp() { - return false; + return false; } /** - Checks if this class type denotes an interface. - @return false. + * Checks if this class type denotes an interface. + * + * @return false. */ public boolean isInterface() { return false; } /** - Checks if this member is abstract. - @return false. + * Checks if this member is abstract. + * + * @return false. */ public boolean isAbstract() { return false; } - /** - Returns the array of locally declared supertypes of this class type. - @return the array of locally defined supertypes of this type. - */ - public ImmutableList getSupertypes(){ + /** + * Returns the array of locally declared supertypes of this class type. + * + * @return the array of locally defined supertypes of this type. + */ + public ImmutableList getSupertypes() { return null; } - - /** - Returns the array of all supertypes of this class type, - in topological order, including the class type isself as first element. - The order allows to resolve member overloading or overloading. - @return the array of all supertypes of this type in topological order. - */ - public ImmutableList getAllSupertypes(Services services){ + + /** + * Returns the array of all supertypes of this class type, in topological order, including the + * class type isself as first element. The order allows to resolve member overloading or + * overloading. + * + * @return the array of all supertypes of this type in topological order. + */ + public ImmutableList getAllSupertypes(Services services) { return null; } - /** - Returns the fields locally defined within this class type. - @return the array of field members of this type. - */ - public ImmutableList getFields(Services services){ + /** + * Returns the fields locally defined within this class type. + * + * @return the array of field members of this type. + */ + public ImmutableList getFields(Services services) { return null; } - - /** - Returns all visible fields that are defined in this class type - or any of its supertypes. The fields are in topological order - with respect to the inheritance hierarchy. - @return the array of visible field members of this type and its - supertypes. - */ - public ImmutableList getAllFields(Services services){ + + /** + * Returns all visible fields that are defined in this class type or any of its supertypes. The + * fields are in topological order with respect to the inheritance hierarchy. + * + * @return the array of visible field members of this type and its supertypes. + */ + public ImmutableList getAllFields(Services services) { return null; } - /** - Returns the methods locally defined within this class type. - @return the array of methods of this type. - */ - public ImmutableList getMethods(Services services){ + /** + * Returns the methods locally defined within this class type. + * + * @return the array of methods of this type. + */ + public ImmutableList getMethods(Services services) { return null; } - /** - Returns all visible methods that are defined in this class type - or any of its supertypes. The methods are in topological order - with respect to the inheritance hierarchy. - @return the array of visible methods of this type and its supertypes. - */ - public ImmutableList getAllMethods(Services services){ + /** + * Returns all visible methods that are defined in this class type or any of its supertypes. The + * methods are in topological order with respect to the inheritance hierarchy. + * + * @return the array of visible methods of this type and its supertypes. + */ + public ImmutableList getAllMethods(Services services) { return null; } - /** - Returns the constructors locally defined within this class type. - @return the array of constructors of this type. - */ - public ImmutableList getConstructors(Services services){ + /** + * Returns the constructors locally defined within this class type. + * + * @return the array of constructors of this type. + */ + public ImmutableList getConstructors(Services services) { return null; } - - /** - Returns all class types that are inner types of this class type, - including visible inherited types. - @return an array of class types that are members of this type - or any of its supertypes. - @see #getAllSupertypes - */ - public ImmutableList getAllTypes(Services services){ + + /** + * Returns all class types that are inner types of this class type, including visible inherited + * types. + * + * @return an array of class types that are members of this type or any of its supertypes. + * @see #getAllSupertypes + */ + public ImmutableList getAllTypes(Services services) { return null; } public Package getPackage() { - return null; + return null; } - /** - * 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 + /** + * 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 Literal getDefaultValue() { - return null; + return null; } - public boolean equals(Object o){ + public boolean equals(Object o) { return o == JAVA_NULL; } - + public int hashCode() { - //singleton + // singleton return System.identityHashCode(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Package.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Package.java index bc224396d05..77c458c5ea8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Package.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Package.java @@ -1,54 +1,62 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element representing packages. - @author AL - @author RN + * A program model element representing packages. + * + * @author AL + * @author RN */ public class Package implements ClassTypeContainer { private String name; /** - Creates a new package with the given name, organized by - the given program model info. - @param name the name of the package. + * Creates a new package with the given name, organized by the given program model info. + * + * @param name the name of the package. */ public Package(String name) { - this.name = name; + this.name = name; } /** - Returns the name of this package. - @return the name of this package. + * Returns the name of this package. + * + * @return the name of this package. */ public String getName() { - return name; + return name; } /** - Returns the name of this package. - @return the full name of this program model element. + * Returns the name of this package. + * + * @return the full name of this program model element. */ public String getFullName() { - return getName(); + return getName(); } /** - Returns the enclosing package or class type, or method. - @return null. + * Returns the enclosing package or class type, or method. + * + * @return null. */ public ClassTypeContainer getContainer() { - return null; + return null; } /** - Returns the enclosing package. - @return null. + * Returns the enclosing package. + * + * @return null. */ - public Package getPackage() { - return this; + public Package getPackage() { + return this; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/PrimitiveType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/PrimitiveType.java index 8d92c90ccca..531066e2435 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/PrimitiveType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/PrimitiveType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import java.util.Collections; @@ -30,43 +33,43 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - A program model element representing primitive types. - @author AL - @author RN + * A program model element representing primitive types. + * + * @author AL + * @author RN */ public final class PrimitiveType implements Type { // must be first in file. - private static final Map typeMap = + private static final Map typeMap = new LinkedHashMap(); // must be first in file. - private static final Map ldtMap = - new LinkedHashMap(); + private static final Map ldtMap = new LinkedHashMap(); - public static final PrimitiveType JAVA_BYTE = - new PrimitiveType("byte", new IntLiteral(0), IntegerLDT.NAME); + public static final PrimitiveType JAVA_BYTE = + new PrimitiveType("byte", new IntLiteral(0), IntegerLDT.NAME); public static final PrimitiveType JAVA_SHORT = - new PrimitiveType("short", new IntLiteral(0), IntegerLDT.NAME); + new PrimitiveType("short", new IntLiteral(0), IntegerLDT.NAME); public static final PrimitiveType JAVA_INT = - new PrimitiveType("int", new IntLiteral(0), IntegerLDT.NAME); + new PrimitiveType("int", new IntLiteral(0), IntegerLDT.NAME); public static final PrimitiveType JAVA_CHAR = - new PrimitiveType("char", new CharLiteral('\u0000'), IntegerLDT.NAME); - public static final PrimitiveType JAVA_LONG = - new PrimitiveType("long", new LongLiteral(0L), IntegerLDT.NAME); + new PrimitiveType("char", new CharLiteral('\u0000'), IntegerLDT.NAME); + public static final PrimitiveType JAVA_LONG = + new PrimitiveType("long", new LongLiteral(0L), IntegerLDT.NAME); public static final PrimitiveType JAVA_BIGINT = new PrimitiveType("\\bigint", new IntLiteral(0), IntegerLDT.NAME); public static final PrimitiveType JAVA_FLOAT = - new PrimitiveType("float", new FloatLiteral(0.0f), FloatLDT.NAME); - public static final PrimitiveType JAVA_DOUBLE = - new PrimitiveType("double", new DoubleLiteral(0.0d), DoubleLDT.NAME); + new PrimitiveType("float", new FloatLiteral(0.0f), FloatLDT.NAME); + public static final PrimitiveType JAVA_DOUBLE = + new PrimitiveType("double", new DoubleLiteral(0.0d), DoubleLDT.NAME); public static final PrimitiveType JAVA_REAL = new PrimitiveType("\\real", new RealLiteral(), RealLDT.NAME); public static final PrimitiveType JAVA_BOOLEAN = - new PrimitiveType("boolean", BooleanLiteral.FALSE, BooleanLDT.NAME); + new PrimitiveType("boolean", BooleanLiteral.FALSE, BooleanLDT.NAME); public static final PrimitiveType JAVA_LOCSET = - new PrimitiveType("\\locset", EmptySetLiteral.LOCSET, LocSetLDT.NAME); + new PrimitiveType("\\locset", EmptySetLiteral.LOCSET, LocSetLDT.NAME); public static final PrimitiveType JAVA_SEQ = - new PrimitiveType("\\seq", EmptySeqLiteral.INSTANCE, SeqLDT.NAME); + new PrimitiveType("\\seq", EmptySeqLiteral.INSTANCE, SeqLDT.NAME); public static final PrimitiveType JAVA_FREE_ADT = new PrimitiveType("\\free", FreeLiteral.INSTANCE, FreeLDT.NAME); public static final PrimitiveType JAVA_MAP = @@ -78,7 +81,7 @@ public final class PrimitiveType implements Type { public static PrimitiveType getPrimitiveType(String name) { - if(!typeMap.containsKey(name) && name.startsWith("\\dl_")){ + if (!typeMap.containsKey(name) && name.startsWith("\\dl_")) { var pt = new PrimitiveType(name, null, null); typeMap.put(name, pt); return pt; @@ -95,124 +98,116 @@ public static PrimitiveType getPrimitiveTypeByLDT(Name ldtName) { private final Name ldtName; private PrimitiveType(String name, Literal defaultValue, Name ldtName) { - this.defaultValue = defaultValue; - this.name = name.intern(); - this.ldtName = ldtName; - typeMap.put(name, this); - - if(ldtName != null) { - ldtMap.put(ldtName, this); - } + this.defaultValue = defaultValue; + this.name = name.intern(); + this.ldtName = ldtName; + typeMap.put(name, this); + + if (ldtName != null) { + ldtMap.put(ldtName, this); + } } /** - Returns the name of this type. - @return the name of this type. + * Returns the name of this type. + * + * @return the name of this type. */ @Override public String getName() { - return name; + return name; } @Override public boolean equals(Object o) { - if (o instanceof PrimitiveType && - ((PrimitiveType)o).getName().equals(name)) { - return true; - } - return false; + if (o instanceof PrimitiveType && ((PrimitiveType) o).getName().equals(name)) { + return true; + } + return false; } @Override public int hashCode() { - return getName().hashCode(); + return getName().hashCode(); } /** - * returns the default value of the given type - * according to JLS ???4.5.5 - * ATTENTION: usually for byte and short this should be (byte) 0 - * (rsp. (short)0) but currently is just 0. - * @return the default value of the given type - * according to JLS ???4.5.5 + * returns the default value of the given type according to JLS ???4.5.5 ATTENTION: + * usually for byte and short this should be (byte) 0 (rsp. (short)0) but currently is just 0. + * + * @return the default value of the given type according to JLS ???4.5.5 */ @Override public Literal getDefaultValue() { - return defaultValue; + return defaultValue; } /** - Returns the name of type. - @return the full name of this program model element. + * Returns the name of type. + * + * @return the full name of this program model element. */ @Override public String getFullName() { - return name; + return name; } /** - Returns the name of type. - @return the full name of this program model element. + * Returns the name of type. + * + * @return the full name of this program model element. */ @Override public String toString() { - return name; + return name; } /** - Returns the specific name of this primitive type used - in array types. + * Returns the specific name of this primitive type used in array types. */ public ProgramElementName getArrayElementName() { - if (arrayElementName == null) { - if (this.getName().equals("byte")) - arrayElementName = new ProgramElementName("[B"); - else if (this.getName().equals("char")) - arrayElementName = new ProgramElementName("[C"); - else if (this.getName().equals("double")) - arrayElementName = new ProgramElementName("[D"); - else if (this.getName().equals("float")) - arrayElementName = new ProgramElementName("[F"); - else if (this.getName().equals("int")) - arrayElementName = new ProgramElementName("[I"); - else if (this.getName().equals("long")) - arrayElementName = new ProgramElementName("[J"); - else if (this.getName().equals("short")) - arrayElementName = new ProgramElementName("[S"); - else if (this.getName().equals("boolean")) - arrayElementName = new ProgramElementName("[Z"); - else if (this.getName().equals("\\locset")) - arrayElementName = new ProgramElementName("[X"); - else if (this.getName().equals("\\bigint")) - arrayElementName = new ProgramElementName("[Y"); - else if (this.getName().equals("\\real")) - arrayElementName = new ProgramElementName("[R"); - } - assert arrayElementName != null; - return arrayElementName; + if (arrayElementName == null) { + if (this.getName().equals("byte")) + arrayElementName = new ProgramElementName("[B"); + else if (this.getName().equals("char")) + arrayElementName = new ProgramElementName("[C"); + else if (this.getName().equals("double")) + arrayElementName = new ProgramElementName("[D"); + else if (this.getName().equals("float")) + arrayElementName = new ProgramElementName("[F"); + else if (this.getName().equals("int")) + arrayElementName = new ProgramElementName("[I"); + else if (this.getName().equals("long")) + arrayElementName = new ProgramElementName("[J"); + else if (this.getName().equals("short")) + arrayElementName = new ProgramElementName("[S"); + else if (this.getName().equals("boolean")) + arrayElementName = new ProgramElementName("[Z"); + else if (this.getName().equals("\\locset")) + arrayElementName = new ProgramElementName("[X"); + else if (this.getName().equals("\\bigint")) + arrayElementName = new ProgramElementName("[Y"); + else if (this.getName().equals("\\real")) + arrayElementName = new ProgramElementName("[R"); + } + assert arrayElementName != null; + return arrayElementName; } /** * Returns whether this is a Java type which translates to int in DL. */ - public boolean isIntegerType () { - return this == JAVA_BYTE - || this == JAVA_CHAR - || this == JAVA_SHORT - || this == JAVA_INT - || this == JAVA_LONG - || this == JAVA_BIGINT; + public boolean isIntegerType() { + return this == JAVA_BYTE || this == JAVA_CHAR || this == JAVA_SHORT || this == JAVA_INT + || this == JAVA_LONG || this == JAVA_BIGINT; } /** * Returns true if this is an integer or floating point type. */ - public boolean isArithmeticType () { - return isIntegerType() - || this == JAVA_FLOAT - || this == JAVA_DOUBLE - || this == JAVA_REAL; + public boolean isArithmeticType() { + return isIntegerType() || this == JAVA_FLOAT || this == JAVA_DOUBLE || this == JAVA_REAL; } /** diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ProgramModelElement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ProgramModelElement.java index dcdeb820426..5a75835f289 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ProgramModelElement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/ProgramModelElement.java @@ -1,19 +1,22 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - An entity of the program meta model. - @author AL - @author RN + * An entity of the program meta model. + * + * @author AL + * @author RN */ -public interface ProgramModelElement - extends de.uka.ilkd.key.java.NamedModelElement { +public interface ProgramModelElement extends de.uka.ilkd.key.java.NamedModelElement { /** - Returns the maximal expanded name including all applicable - qualifiers. - @return the full name of this program model element. + * Returns the maximal expanded name including all applicable qualifiers. + * + * @return the full name of this program model element. */ String getFullName(); - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Type.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Type.java index 7cc8774ee66..ae18dabd9fe 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Type.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Type.java @@ -1,20 +1,23 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; import de.uka.ilkd.key.java.expression.Literal; /** - A program model element representing types. - @author AL - @author RN + * A program model element representing types. + * + * @author AL + * @author RN */ public interface Type extends ProgramModelElement { - /** - * 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 + /** + * 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 */ Literal getDefaultValue(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Variable.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Variable.java index ddbeb15a5eb..d1756fd377a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Variable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/abstraction/Variable.java @@ -1,22 +1,27 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.abstraction; /** - A program model element representing variables. - @author AL - @author RN + * A program model element representing variables. + * + * @author AL + * @author RN */ public interface Variable extends ProgramModelElement { - + /** - Checks if this variable is final. - @return true if this variable is final, - false otherwise. + * Checks if this variable is final. + * + * @return true if this variable is final, false otherwise. */ boolean isFinal(); /** - Returns the type of this variable. - @return the type of this variable. - */ + * Returns the type of this variable. + * + * @return the type of this variable. + */ Type getType(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ArrayDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ArrayDeclaration.java index dd78d6bffc9..f22bd57b9ce 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ArrayDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ArrayDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -16,32 +19,28 @@ import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.ProgramElementName; + /** - * KeY used to model arrays using only the {@link - * de.uka.ilkd.key.java.abstraction.ArrayType}. As the only attribute of - * an array has been the length attribute, it has been handled in a - * different way than members of usual classes. As we need some implicit - * fields for array creation and initialisation, the special handling of - * arrays is not any longer practicable. - * So, this class introduce a 'virtual' declaration for array types - * containing all required members. Please not the array fields accessed - * by an index are not included, so arrays of different lengths with same base - * type belong to the same array declaration. - * Attention: In contrast to the other type declaration, array - * declarations may be added at runtime. + * KeY used to model arrays using only the {@link de.uka.ilkd.key.java.abstraction.ArrayType}. As + * the only attribute of an array has been the length attribute, it has been handled in a different + * way than members of usual classes. As we need some implicit fields for array creation and + * initialisation, the special handling of arrays is not any longer practicable. So, this class + * introduce a 'virtual' declaration for array types containing all required members. Please not the + * array fields accessed by an index are not included, so arrays of different lengths with same base + * type belong to the same array declaration. Attention: In contrast to the other type declaration, + * array declarations may be added at runtime. */ -public class ArrayDeclaration - extends TypeDeclaration implements ArrayType { +public class ArrayDeclaration extends TypeDeclaration implements ArrayType { - /** + /** * reference to the type the elements of this array must subclass */ private final TypeReference basetype; /** - * dimension of the array + * dimension of the array */ private final int dim; @@ -49,57 +48,57 @@ public class ArrayDeclaration private String altNameRepresentation; - private ArrayDeclaration(ExtList children, - TypeReference baseType, - ProgramElementName name, - KeYJavaType superType) { - super(addLength(children, superType), name, name, false); - assert name != null; - this.basetype = baseType; - this.dim = dimension(); - this.superType = superType; + private ArrayDeclaration(ExtList children, TypeReference baseType, ProgramElementName name, + KeYJavaType superType) { + super(addLength(children, superType), name, name, false); + assert name != null; + this.basetype = baseType; + this.dim = dimension(); + this.superType = superType; } private static ExtList addLength(ExtList children, KeYJavaType superType) { - children.add(((SuperArrayDeclaration)superType.getJavaType()).length()); - return children; + children.add(((SuperArrayDeclaration) superType.getJavaType()).length()); + return children; } /** * ArrayDeclaration - * @param children an ExtList with the basetype and member - * declarations of this type + * + * @param children an ExtList with the basetype and member declarations of this type */ - public ArrayDeclaration(ExtList children, - TypeReference baseType, - KeYJavaType superType) { - this(children, baseType, createName(baseType), superType); - } + public ArrayDeclaration(ExtList children, TypeReference baseType, KeYJavaType superType) { + this(children, baseType, createName(baseType), superType); + } /** * 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 (name != null) result ++; - if (basetype != null) result ++; - if (members != null) result += members.size(); + if (modArray != null) + result += modArray.size(); + if (name != null) + result++; + if (basetype != null) + result++; + if (members != null) + result += members.size(); return result; } public FieldDeclaration length() { - return ((SuperArrayDeclaration)superType.getJavaType()).length(); + return ((SuperArrayDeclaration) superType.getJavaType()).length(); } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -111,11 +110,13 @@ public ProgramElement getChildAt(int index) { index -= len; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; index--; } if (basetype != null) { - if (index == 0) return basetype; + if (index == 0) + return basetype; index--; } if (members != null) { @@ -126,6 +127,7 @@ public ProgramElement getChildAt(int index) { /** * Get the element/base type. + * * @return refernce to the base type . */ public TypeReference getBaseType() { @@ -154,101 +156,97 @@ public boolean isVolatile() { } /** - * Arrays are never interfaces (but may have interface types as - * element types) + * Arrays are never interfaces (but may have interface types as element types) */ public boolean isInterface() { return false; } - + /** * return the dimension of this array */ public int getDimension() { - return dim; + return dim; } - /** - * 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 + /** + * 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 Literal getDefaultValue() { - return NullLiteral.NULL; + return NullLiteral.NULL; } /** * computes the dimension of this array */ private int dimension() { - Type javaType = basetype.getKeYJavaType().getJavaType(); - if (javaType instanceof ArrayType) { - return 1+((ArrayType)javaType).getDimension(); - } else { - return 1; - } + Type javaType = basetype.getKeYJavaType().getJavaType(); + if (javaType instanceof ArrayType) { + return 1 + ((ArrayType) javaType).getDimension(); + } else { + return 1; + } } public static ProgramElementName createName(TypeReference basetype) { - Type javaBasetype = basetype.getKeYJavaType().getJavaType(); - - if (javaBasetype == null) { - // entered only if base type is class type - return new ProgramElementName - ("[L"+basetype.getName()); - - } - if(javaBasetype instanceof ArrayDeclaration){ - return new ProgramElementName - ("["+ javaBasetype.getFullName()); - } else if (javaBasetype instanceof TypeDeclaration) { - return new ProgramElementName("[L"+javaBasetype.getFullName()); - } else if (javaBasetype instanceof PrimitiveType) { - return ((PrimitiveType)javaBasetype).getArrayElementName(); - } - assert false; - return null; + Type javaBasetype = basetype.getKeYJavaType().getJavaType(); + + if (javaBasetype == null) { + // entered only if base type is class type + return new ProgramElementName("[L" + basetype.getName()); + + } + if (javaBasetype instanceof ArrayDeclaration) { + return new ProgramElementName("[" + javaBasetype.getFullName()); + } else if (javaBasetype instanceof TypeDeclaration) { + return new ProgramElementName("[L" + javaBasetype.getFullName()); + } else if (javaBasetype instanceof PrimitiveType) { + return ((PrimitiveType) javaBasetype).getArrayElementName(); + } + assert false; + return null; } public String getAlternativeNameRepresentation() { if (altNameRepresentation == null) { - final StringBuffer alt = new StringBuffer(); + final StringBuffer alt = new StringBuffer(); Type baseType = basetype.getKeYJavaType().getJavaType(); - + if (baseType instanceof ArrayType) { - alt.append(((ArrayType) baseType). - getAlternativeNameRepresentation()); + alt.append(((ArrayType) baseType).getAlternativeNameRepresentation()); } else { if (baseType instanceof ClassType) { alt.append(baseType.getFullName()); - } else { + } else { alt.append(baseType.getName()); } - } + } alt.append("[]"); altNameRepresentation = alt.toString(); } return altNameRepresentation; } - - /** + + /** * returns the local declared supertypes */ public ImmutableList getSupertypes() { - return ImmutableSLList.nil().append(superType); + return ImmutableSLList.nil().append(superType); } - /** - * calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnArrayDeclaration(this); + v.performActionOnArrayDeclaration(this); } /** @@ -262,7 +260,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { * toString */ public String toString() { - return name.toString().intern(); + return name.toString().intern(); } -} \ No newline at end of file +} 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 31f51806f49..79ec765e1d6 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -12,148 +15,130 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * There are several types of class declarations: - *

      - *
    • package-less outer classes - *
        - *
      • getClassContainer() == null - *
      • getStatementContainer() == null - *
      • getName() != null - *
      - *
    • ordinary outer classes - *
        - *
      • getClassContainer() instanceof Package - *
      • getStatementContainer() == null - *
      • getName() != null - *
      - *
    • member classes - *
        - *
      • getClassContainer() instanceof ClassDeclaration - *
      • getStatementContainer() == null - *
      • getName() != null - *
      - *
    • local class - *
        - *
      • getClassContainer() == null - *
      • getStatementContainer() != null - *
      • getName() != null - *
      - *
    • local anonymous class - *
        - *
      • getClassContainer() == null - *
      • getStatementContainer() instanceof expression.New - *
      • getName() == null - *
      - *
    - * Anonymous local classes have exactly one supertype and no - * subtypes. - *
    - * Binary classes may have only binary members. - * taken from COMPOST and changed to achieve an immutable structure + * There are several types of class declarations: + *
      + *
    • package-less outer classes + *
        + *
      • getClassContainer() == null + *
      • getStatementContainer() == null + *
      • getName() != null + *
      + *
    • ordinary outer classes + *
        + *
      • getClassContainer() instanceof Package + *
      • getStatementContainer() == null + *
      • getName() != null + *
      + *
    • member classes + *
        + *
      • getClassContainer() instanceof ClassDeclaration + *
      • getStatementContainer() == null + *
      • getName() != null + *
      + *
    • local class + *
        + *
      • getClassContainer() == null + *
      • getStatementContainer() != null + *
      • getName() != null + *
      + *
    • local anonymous class + *
        + *
      • getClassContainer() == null + *
      • getStatementContainer() instanceof expression.New + *
      • getName() == null + *
      + *
    + * Anonymous local classes have exactly one supertype and no subtypes.
    + * Binary classes may have only binary members. taken from COMPOST and changed to achieve an + * immutable structure */ public class ClassDeclaration extends TypeDeclaration implements Statement { - + protected final Extends extending; protected final Implements implementing; - + protected final boolean isInnerClass; - + protected final boolean isLocalClass; - + protected final boolean isAnonymousClass; /** - * Class declaration. + * Class declaration. + * * @param mods a modifier array. * @param name Identifier of the class - * @param members an array containing the memberdeclarations of - * this type - * @param implemented of type Implement containing the - * interfaces implemented by this class - * @param extended Extend containing the class extended by - * the class of this classdeclaration - * @param parentIsInterfaceDeclaration boolean true iff - * parent is an InterfaceDeclaration + * @param members an array containing the memberdeclarations of this type + * @param implemented of type Implement containing the interfaces implemented by this class + * @param extended Extend containing the class extended by the class of this classdeclaration + * @param parentIsInterfaceDeclaration boolean true iff parent is an InterfaceDeclaration */ - public ClassDeclaration(Modifier[] mods, - ProgramElementName name, - Extends extended, - ProgramElementName fullName, - Implements implemented, - MemberDeclaration[] members, - boolean parentIsInterfaceDeclaration, - boolean isLibrary) { - super(mods, - name, - fullName, - members, - parentIsInterfaceDeclaration, - isLibrary); - this.extending = extended; - this.implementing = implemented; - this.isInnerClass = false; - this.isAnonymousClass = false; - this.isLocalClass = false; + public ClassDeclaration(Modifier[] mods, ProgramElementName name, Extends extended, + ProgramElementName fullName, Implements implemented, MemberDeclaration[] members, + boolean parentIsInterfaceDeclaration, boolean isLibrary) { + super(mods, name, fullName, members, parentIsInterfaceDeclaration, isLibrary); + this.extending = extended; + this.implementing = implemented; + this.isInnerClass = false; + this.isAnonymousClass = false; + this.isLocalClass = false; } /** - * uses children list to create non-anonymous class - * @param children the ExtList with all children building up this - * class declaration - * May contain: a Extends (as pointer to a - * class), a Implements (as pointer to an interface) - * ProgramElementName (as name), several MemberDeclaration (as members of - * the type), a parentIsInterfaceDeclaration (indicating if parent is - * interface), several Modifier (as modifiers of the type decl), a Comment + * uses children list to create non-anonymous class + * + * @param children the ExtList with all children building up this class declaration May contain: + * a Extends (as pointer to a class), a Implements (as pointer to an interface) + * ProgramElementName (as name), several MemberDeclaration (as members of the type), a + * parentIsInterfaceDeclaration (indicating if parent is interface), several Modifier (as + * modifiers of the type decl), a Comment * @param fullName the fully qualified ProgramElementName of this class - * @param isLibrary a boolean flag indicating if this class represents a - * library class (such classes have usually no method implementations but - * specifications) + * @param isLibrary a boolean flag indicating if this class represents a library class (such + * classes have usually no method implementations but specifications) */ - public ClassDeclaration(ExtList children, - ProgramElementName fullName, - boolean isLibrary, - boolean innerClass, - boolean anonymousClass, - boolean localClass) { - super(children, fullName, isLibrary); - extending=children.get(Extends.class); - implementing=children.get(Implements.class); - this.isInnerClass = innerClass; - this.isAnonymousClass = anonymousClass; - this.isLocalClass =localClass; - } - - public ClassDeclaration(ExtList children, - ProgramElementName fullName, - boolean isLibrary) { + public ClassDeclaration(ExtList children, ProgramElementName fullName, boolean isLibrary, + boolean innerClass, boolean anonymousClass, boolean localClass) { + super(children, fullName, isLibrary); + extending = children.get(Extends.class); + implementing = children.get(Implements.class); + this.isInnerClass = innerClass; + this.isAnonymousClass = anonymousClass; + this.isLocalClass = localClass; + } + + public ClassDeclaration(ExtList children, ProgramElementName fullName, boolean isLibrary) { this(children, fullName, isLibrary, false, false, false); - } + } /** * 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(name != null) result++; - if(extending != null) result++; - if(implementing != null) result++; - if(members != null) result += members.size(); + if (modArray != null) + result += modArray.size(); + if (name != null) + result++; + if (extending != null) + result++; + if (implementing != null) + result++; + if (members != null) + result += members.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -165,15 +150,18 @@ public ProgramElement getChildAt(int index) { index -= len; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; index--; } if (extending != null) { - if (index == 0) return extending; + if (index == 0) + return extending; index--; } if (implementing != null) { - if (index == 0) return implementing; + if (index == 0) + return implementing; index--; } if (members != null) { @@ -181,9 +169,10 @@ public ProgramElement getChildAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } - + /** * Get extended types. + * * @return the extends. */ public Extends getExtendedTypes() { @@ -192,6 +181,7 @@ public Extends getExtendedTypes() { /** * Get implemented types. + * * @return the implements. */ public Implements getImplementedTypes() { @@ -204,16 +194,16 @@ public Implements getImplementedTypes() { public boolean isTransient() { return false; } - - public boolean isInnerClass(){ + + public boolean isInnerClass() { return isInnerClass; } - - public boolean isAnonymousClass(){ + + public boolean isAnonymousClass() { return isAnonymousClass; } - - public boolean isLocalClass(){ + + public boolean isLocalClass() { return isLocalClass; } @@ -227,31 +217,31 @@ public boolean isVolatile() { public boolean isInterface() { return false; } - - /** + + /** * returns the local declared supertypes */ public ImmutableList getSupertypes() { - ImmutableList types = ImmutableSLList.nil(); - if (implementing != null) { - for (int i = implementing.getTypeReferenceCount()-1; i>=0; i--) { - types = types.prepend(implementing.getTypeReferenceAt(i). - getKeYJavaType()); - } - } - if (extending != null) { - types = types.prepend - (extending.getTypeReferenceAt(0).getKeYJavaType()); - } - return types; + ImmutableList types = ImmutableSLList.nil(); + if (implementing != null) { + for (int i = implementing.getTypeReferenceCount() - 1; i >= 0; i--) { + types = types.prepend(implementing.getTypeReferenceAt(i).getKeYJavaType()); + } + } + if (extending != null) { + types = types.prepend(extending.getTypeReferenceAt(0).getKeYJavaType()); + } + return types; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnClassDeclaration(this); + v.performActionOnClassDeclaration(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/ClassInitializer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ClassInitializer.java index 52d52c57380..aea2f145620 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -13,33 +16,34 @@ -public class ClassInitializer extends JavaDeclaration implements MemberDeclaration, StatementContainer { +public class ClassInitializer extends JavaDeclaration + implements MemberDeclaration, StatementContainer { protected final StatementBlock body; - + public ClassInitializer() { - super(new Modifier[0]); - body=null; + super(new Modifier[0]); + body = null; } public ClassInitializer(Static modifier, StatementBlock body) { - super(new Modifier[]{modifier}); - this.body=body; + super(new Modifier[] { modifier }); + this.body = body; } /** - * Class initializer. - * @param children list with all children. May include: a - * StatementBlock (taken as body of the ClassInitialiyer), - * several Modifier (taken as modifiers of the declaration), a Comment + * Class initializer. + * + * @param children list with all children. May include: a StatementBlock (taken as body of the + * ClassInitialiyer), several Modifier (taken as modifiers of the declaration), a Comment */ public ClassInitializer(ExtList children) { super(children); - body=children.get(StatementBlock.class); + body = children.get(StatementBlock.class); } @@ -54,13 +58,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -69,21 +74,22 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - + public int getChildCount() { int result = 0; - if (modArray != null) result += modArray.size(); - if (body != null) result++; + if (modArray != null) + result += modArray.size(); + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { @@ -96,7 +102,8 @@ public ProgramElement getChildAt(int index) { index -= len; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; } throw new ArrayIndexOutOfBoundsException(); } @@ -145,22 +152,24 @@ public boolean isStrictFp() { */ public boolean isStatic() { - return modArray != null && modArray.size()!=0; + return modArray != null && modArray.size() != 0; } public SourceElement getLastElement() { return body; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnClassInitializer(this); + v.performActionOnClassInitializer(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printClassInitializer(this); } -} \ No newline at end of file +} 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 d49a0f99f81..b763637061c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -9,62 +12,46 @@ /** - * 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 { /** * 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 + * + * @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 */ - public ConstructorDeclaration(ExtList children, - boolean parentIsInterfaceDeclaration) { - super(children, parentIsInterfaceDeclaration, null); + public ConstructorDeclaration(ExtList children, 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 exceptions a throws. * @param body a statement block. - * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff 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. */ @@ -73,7 +60,7 @@ public boolean isAbstract() { return false; } - + /** * Constructors are never final. */ @@ -82,7 +69,7 @@ public boolean isFinal() { return false; } - + /** * Constructors are never native. */ @@ -91,7 +78,7 @@ public boolean isNative() { return false; } - + /** * Constructors are never static. */ @@ -100,7 +87,7 @@ public boolean isStatic() { return false; } - + /** * Constructors are never strictfp. */ @@ -109,7 +96,7 @@ public boolean isStrictFp() { return false; } - + /** * Constructors are never synchronized. */ @@ -119,8 +106,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/EnumClassDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/EnumClassDeclaration.java index 140650e5b74..22134dd27a4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/EnumClassDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/EnumClassDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import java.util.ArrayList; @@ -14,10 +17,11 @@ /** * This class is used for wrapping an enum into a standard class type. - * - *

    In addition the programvariables that represent enum constants are memorized. Thus - * this class is able to have queries on the enum constants. - * + * + *

    + * In addition the programvariables that represent enum constants are memorized. Thus this class is + * able to have queries on the enum constants. + * * @author mulbrich * @since 2006-12-10 */ @@ -30,21 +34,15 @@ public class EnumClassDeclaration extends ClassDeclaration { private List constants = new ArrayList(); /** - * create a new EnumClassDeclaration that describes an enum defintion. It - * merely wraps a ClassDeclaration but has memory about which fields have - * been declared as enum constants. - * - * @param children - * children in the ast (members) - * @param fullName - * of the class/enum - * @param isLibrary - * see class constructor - * @param enumConstantDeclarations - * the declarations for the enum constants + * create a new EnumClassDeclaration that describes an enum defintion. It merely wraps a + * ClassDeclaration but has memory about which fields have been declared as enum constants. + * + * @param children children in the ast (members) + * @param fullName of the class/enum + * @param isLibrary see class constructor + * @param enumConstantDeclarations the declarations for the enum constants */ - public EnumClassDeclaration(ExtList children, ProgramElementName fullName, - boolean isLibrary, + public EnumClassDeclaration(ExtList children, ProgramElementName fullName, boolean isLibrary, List enumConstantDeclarations) { super(children, fullName, isLibrary); @@ -57,11 +55,10 @@ public EnumClassDeclaration(ExtList children, ProgramElementName fullName, /* * find the program variable for a constant given by name. - * - * The "::" have to be prepended to obtain the internal name. - * Throw IllegalStateException if name is not an attribute of this. - * This will never happen. - * + * + * The "::" have to be prepended to obtain the internal name. Throw IllegalStateException + * if name is not an attribute of this. This will never happen. + * */ private IProgramVariable findAttr(String fieldName) { String completeName = getFullName() + "::" + fieldName; @@ -74,8 +71,8 @@ private IProgramVariable findAttr(String fieldName) { } } } - throw new IllegalStateException(fieldName + " is not an attribute of " - + this.getFullName()); + throw new IllegalStateException( + fieldName + " is not an attribute of " + this.getFullName()); } /* @@ -91,6 +88,7 @@ private boolean isLocalEnumConstant(IProgramVariable pv) { /** * get the index of the program variable amongst the enumconstants of THIS enum. + * * @param pv PV to look up * @return -1 if not found, otherwise the 0-based index. */ @@ -104,6 +102,7 @@ private int localIndexOf(ProgramVariable pv) { /** * get the number of defined enum constants in this type. + * * @return the number of defined enum constants in this type */ public int getNumberOfConstants() { @@ -112,6 +111,7 @@ public int getNumberOfConstants() { /** * check whether a PV is an enum constant of any enum type. + * * @param attribute ProgramVariable to check. * @return true iff attribute is an enum constant. */ @@ -123,7 +123,7 @@ public static boolean isEnumConstant(IProgramVariable attribute) { else return false; } - + // TODO DOC public static int indexOf(ProgramVariable attribute) { KeYJavaType kjt = attribute.getKeYJavaType(); @@ -134,4 +134,4 @@ public static int indexOf(ProgramVariable attribute) { return -1; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Extends.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Extends.java index 98478372f76..18fe3cb2d83 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Extends.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Extends.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -5,16 +8,19 @@ import de.uka.ilkd.key.java.PrettyPrinter; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.visitor.Visitor; + /** - * Extends. - * @author AutoDoc + * Extends. + * + * @author AutoDoc */ public class Extends extends InheritanceSpecification { /** - * Extends. - * @param supertype a type reference. + * Extends. + * + * @param supertype a type reference. */ public Extends(TypeReference supertype) { super(supertype); @@ -22,24 +28,25 @@ public Extends(TypeReference supertype) { /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. May - * include: - * several TypeReference (as references to the supertypes) - * a Comment - */ + * + * @param children the children of this AST element as KeY classes. May include: several + * TypeReference (as references to the supertypes) a Comment + */ public Extends(ExtList children) { - super(children); + super(children); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnExtends(this); + v.performActionOnExtends(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printExtends(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 8f77b4bf369..818f0aff249 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -9,52 +12,47 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Field declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Field declaration. taken from COMPOST and changed to achieve an immutable structure */ public class FieldDeclaration extends VariableDeclaration implements MemberDeclaration { /** - * Field specs. + * 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); + public FieldDeclaration(Modifier[] mods, TypeReference typeRef, 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; } @@ -64,25 +62,28 @@ 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 (typeReference != null) result++; - if (fieldSpecs != null) result += fieldSpecs.size(); + if (modArray != null) + result += modArray.size(); + if (typeReference != null) + result++; + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -94,7 +95,8 @@ public ProgramElement getChildAt(int index) { index -= len; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (fieldSpecs != null) { @@ -104,8 +106,7 @@ public ProgramElement getChildAt(int index) { } /** - * Test whether the declaration is final. Fields of interfaces are - * always final. + * Test whether the declaration is final. Fields of interfaces are always final. */ public boolean isFinal() { @@ -129,20 +130,19 @@ public boolean isProtected() { } /** - * Test whether the declaration is public. Fields of interfaces - * are always public. + * Test whether the declaration is public. Fields of interfaces are always public. */ public boolean isPublic() { return parentIsInterfaceDeclaration || super.isPublic(); } - /* * - * Test whether the declaration is static. + /* + * * Test whether the declaration is static. */ public boolean isStatic() { -// return parentIsInterfaceDeclaration || super.isStatic(); - // DB 2012-05-08: interfaces may contain non-static model fields + // return parentIsInterfaceDeclaration || super.isStatic(); + // DB 2012-05-08: interfaces may contain non-static model fields return super.isStatic(); } @@ -161,7 +161,7 @@ public boolean isTransient() { public boolean isStrictFp() { return super.isStrictFp(); } - + /** * Test whether the declaration is model (the jml modifier is meant). */ @@ -178,15 +178,17 @@ public boolean isGhost() { return super.isGhost(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printFieldDeclaration(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldSpecification.java index 2cef72de048..892f287b043 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/FieldSpecification.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -8,15 +11,14 @@ import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.ProgramVariable; -/* FieldSpecification - * taken from COMPOST and changed to achieve an immutable structure +/* + * FieldSpecification taken from COMPOST and changed to achieve an immutable structure */ -public class FieldSpecification extends VariableSpecification - implements Field { +public class FieldSpecification extends VariableSpecification implements Field { /** - * Field specification. + * Field specification. */ public FieldSpecification() {} @@ -26,9 +28,10 @@ public FieldSpecification(ProgramVariable var) { } /** - * Field specification. - * @param var the ProgramVariable representing this concrete field - * @param type the Type of this field + * Field specification. + * + * @param var the ProgramVariable representing this concrete field + * @param type the Type of this field */ public FieldSpecification(ProgramVariable var, Type type) { @@ -36,10 +39,11 @@ public FieldSpecification(ProgramVariable var, Type type) { } /** - * Field specification. - * @param var the ProgramVariable representing this concrete field - * @param init the Expression the field is initialised with. - * @param type the Type of this field + * Field specification. + * + * @param var the ProgramVariable representing this concrete field + * @param init the Expression the field is initialised with. + * @param type the Type of this field */ public FieldSpecification(ProgramVariable var, Expression init, Type type) { @@ -47,51 +51,47 @@ public FieldSpecification(ProgramVariable var, Expression init, Type type) { } /** - * Field specification. - * @param var the ProgramVariable representing this concrete field - * @param dimensions an int defining the dimension - * @param init the Expression the field is initialised with. - * @param type the Type of this field + * Field specification. + * + * @param var the ProgramVariable representing this concrete field + * @param dimensions an int defining the dimension + * @param init the Expression the field is initialised with. + * @param type the Type of this field */ - public FieldSpecification(ProgramVariable var, int dimensions, - Expression init, Type type) { + public FieldSpecification(ProgramVariable var, int dimensions, Expression init, Type type) { super(var, dimensions, init, type, null); } /** - * Field specification. - * @param children an ExtList with the children. - * May contain: - * an Expression (as initializer of the variable) - * a ProgramElementName (as name of the variable) - * a Comment - * @param var the ProgramVariable representing this concrete field - * @param dimensions an int defining the dimension - * @param type the Type of this field + * Field specification. + * + * @param children an ExtList with the children. May contain: an Expression (as initializer of + * the variable) a ProgramElementName (as name of the variable) a Comment + * @param var the ProgramVariable representing this concrete field + * @param dimensions an int defining the dimension + * @param type the Type of this field */ - public FieldSpecification(ExtList children, ProgramVariable var, - int dimensions, Type type) { + public FieldSpecification(ExtList children, ProgramVariable var, int dimensions, Type type) { super(children, var, dimensions, type); } /** - * returns the name of the field as used in programs. In the logic - * each field has a unique name which is composed by the class name where - * it is declared and its source code name + * returns the name of the field as used in programs. In the logic each field has a unique name + * which is composed by the class name where it is declared and its source code name * * @return returns the name of the field as used in programs */ - public String getProgramName(){ - return getProgramElementName().getProgramName(); + public String getProgramName() { + return getProgramElementName().getProgramName(); } - + /** * Test whether the declaration is static. */ public boolean isStatic() { - return ((ProgramVariable)var).isStatic(); + return ((ProgramVariable) var).isStatic(); } /** @@ -102,7 +102,7 @@ public boolean isPrivate() { } /** - * Test whether the declaration is protected.TO BE IMPLEMENTED + * Test whether the declaration is protected.TO BE IMPLEMENTED */ public boolean isProtected() { @@ -110,7 +110,7 @@ public boolean isProtected() { } /** - * Test whether the declaration is public.TO BE IMPLEMENTED + * Test whether the declaration is public.TO BE IMPLEMENTED */ public boolean isPublic() { @@ -119,7 +119,7 @@ public boolean isPublic() { /** - * Test whether the declaration is transient.TO BE IMPLEMENTED + * Test whether the declaration is transient.TO BE IMPLEMENTED */ public boolean isTransient() { @@ -127,25 +127,27 @@ public boolean isTransient() { } /** - * Test whether the declaration is volatile.TO BE IMPLEMENTED + * Test whether the declaration is volatile.TO BE IMPLEMENTED */ public boolean isVolatile() { return false; } - + /** - * Test whether the declaration is strictFp.TO BE IMPLEMENTED + * Test whether the declaration is strictFp.TO BE IMPLEMENTED */ public boolean isStrictFp() { return false; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnFieldSpecification(this); + v.performActionOnFieldSpecification(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Implements.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Implements.java index 18048b55291..fbdfd1d2ebb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Implements.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Implements.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -7,21 +10,22 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Implements. - * + * Implements. + * */ public class Implements extends InheritanceSpecification { /** - * Implements. + * Implements. */ public Implements() {} /** - * Implements. - * @param supertype a type reference. + * Implements. + * + * @param supertype a type reference. */ public Implements(TypeReference supertype) { @@ -29,8 +33,9 @@ public Implements(TypeReference supertype) { } /** - * Implements. - * @param typeRefs a type reference array. + * Implements. + * + * @param typeRefs a type reference array. */ public Implements(TypeReference[] typeRefs) { @@ -38,25 +43,27 @@ public Implements(TypeReference[] typeRefs) { } /** - * Implements. - * @param children containing the children. May include: - * a Comment, - * several TypeReference (as references to the supertypes) - * + * Implements. + * + * @param children containing the children. May include: a Comment, several TypeReference (as + * references to the supertypes) + * */ public Implements(ExtList children) { super(children); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnImplements(this); + v.performActionOnImplements(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printImplements(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ImplicitFieldSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ImplicitFieldSpecification.java index c3082fb7a47..d914ec32581 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ImplicitFieldSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ImplicitFieldSpecification.java @@ -1,13 +1,16 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import de.uka.ilkd.key.java.abstraction.Type; import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.ProgramVariable; -/* An implicit field specification. In KeY we store information about states of - * classes and/or objects as static or instance fields - * (e.g. if a class is initialized or an object created). To avoid name clashes - * the name of implicit fields is enclosed by angle brackets. +/* + * An implicit field specification. In KeY we store information about states of classes and/or + * objects as static or instance fields (e.g. if a class is initialized or an object created). To + * avoid name clashes the name of implicit fields is enclosed by angle brackets. */ public class ImplicitFieldSpecification extends FieldSpecification { @@ -18,6 +21,7 @@ public ImplicitFieldSpecification() {} /** * Implicit Field specification. + * * @param var the ProgramVariable representing this concrete field */ public ImplicitFieldSpecification(ProgramVariable var) { @@ -25,9 +29,10 @@ public ImplicitFieldSpecification(ProgramVariable var) { } /** - * Implicit Field specification. - * @param var the ProgramVariable representing this concrete field - * @param type the Type of this field + * Implicit Field specification. + * + * @param var the ProgramVariable representing this concrete field + * @param type the Type of this field */ public ImplicitFieldSpecification(ProgramVariable var, Type type) { @@ -35,13 +40,15 @@ public ImplicitFieldSpecification(ProgramVariable var, Type type) { } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnImplicitFieldSpecification(this); + v.performActionOnImplicitFieldSpecification(this); } -} \ No newline at end of file +} 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 c7d964c8649..10ff6b581ad 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -10,57 +13,58 @@ import de.uka.ilkd.key.java.reference.TypeReferenceContainer; /** - * Inheritance specification. - * @author AutoDoc + * Inheritance specification. + * + * @author AutoDoc */ -public abstract class InheritanceSpecification - extends JavaNonTerminalProgramElement - implements TypeReferenceContainer { +public abstract class InheritanceSpecification extends JavaNonTerminalProgramElement + implements TypeReferenceContainer { /** - * Supertypes. + * Supertypes. */ protected final ImmutableArray supertypes; /** - * Inheritance specification. + * Inheritance specification. */ public InheritanceSpecification() { - this.supertypes=null; + this.supertypes = 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.supertypes = 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.supertypes = 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)); } @@ -73,24 +77,25 @@ 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 + */ public int getChildCount() { int result = 0; - if (supertypes != null) result += supertypes.size(); + if (supertypes != null) + result += supertypes.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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (supertypes != null) { @@ -100,8 +105,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() { @@ -109,8 +115,9 @@ 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. */ public int getTypeReferenceCount() { @@ -118,13 +125,15 @@ public int getTypeReferenceCount() { } /* - 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. - */ + * 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. + */ public TypeReference getTypeReferenceAt(int index) { if (supertypes != null) { @@ -132,4 +141,4 @@ public TypeReference getTypeReferenceAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InterfaceDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InterfaceDeclaration.java index 0e6b4981150..71f37655f28 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InterfaceDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/InterfaceDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -11,7 +14,7 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * Interface declaration. + * Interface declaration. */ public class InterfaceDeclaration extends TypeDeclaration { @@ -19,72 +22,69 @@ public class InterfaceDeclaration extends TypeDeclaration { public InterfaceDeclaration() { - extending = null; + extending = null; } /** Construct a new outer or member interface class. */ public InterfaceDeclaration(Modifier[] modifiers, ProgramElementName name, - ProgramElementName fullName, - Extends extended, MemberDeclaration[] members, - boolean isLibrary){ + ProgramElementName fullName, Extends extended, MemberDeclaration[] members, + boolean isLibrary) { super(modifiers, name, fullName, members, false, isLibrary); - extending = extended; + extending = extended; } /** Construct a new outer or member interface class. */ - public InterfaceDeclaration(Modifier[] modifiers, ProgramElementName name, - Extends extended, MemberDeclaration[] members, - boolean isLibrary){ + public InterfaceDeclaration(Modifier[] modifiers, ProgramElementName name, Extends extended, + MemberDeclaration[] members, boolean isLibrary) { this(modifiers, name, name, extended, members, isLibrary); } /** - * uses children list to create non-anonymous class - * @param children an ExtList that may contain: an Extends - * (as pointer to a class), ProgramElementName (as name), - * several MemberDeclaration (as members of - * the type), a parentIsInterfaceDeclaration (indicating if parent is - * interface), several Modifier (as modifiers of the type decl), a Comment - * @param fullName the fully qualified ProgramElementName of the declared - * type - * @param isLibrary a boolean flag indicating if this interface is part of - * a library (library interfaces come often with a specification and are - * only available as bytecode) + * uses children list to create non-anonymous class + * + * @param children an ExtList that may contain: an Extends (as pointer to a class), + * ProgramElementName (as name), several MemberDeclaration (as members of the type), a + * parentIsInterfaceDeclaration (indicating if parent is interface), several Modifier (as + * modifiers of the type decl), a Comment + * @param fullName the fully qualified ProgramElementName of the declared type + * @param isLibrary a boolean flag indicating if this interface is part of a library (library + * interfaces come often with a specification and are only available as bytecode) */ - public InterfaceDeclaration(ExtList children, ProgramElementName fullName, - boolean isLibrary) { - super(children, fullName, isLibrary); - extending=children.get(Extends.class); - } + public InterfaceDeclaration(ExtList children, ProgramElementName fullName, boolean isLibrary) { + super(children, fullName, isLibrary); + extending = children.get(Extends.class); + } - public InterfaceDeclaration(ProgramElementName name) { - this (new de.uka.ilkd.key.java.declaration.Modifier[] {}, - name, null, - new de.uka.ilkd.key.java.declaration.MemberDeclaration[]{}, - true); + public InterfaceDeclaration(ProgramElementName name) { + this(new de.uka.ilkd.key.java.declaration.Modifier[] {}, name, null, + new de.uka.ilkd.key.java.declaration.MemberDeclaration[] {}, true); } /** * 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 (name != null) result++; - if (extending != null) result++; - if (members != null) result += members.size(); + if (modArray != null) + result += modArray.size(); + if (name != null) + result++; + if (extending != null) + result++; + if (members != null) + result += members.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -96,11 +96,13 @@ public ProgramElement getChildAt(int index) { index -= len; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; index--; } if (extending != null) { - if (index == 0) return extending; + if (index == 0) + return extending; index--; } if (members != null) { @@ -115,6 +117,7 @@ public ProgramElement getChildAt(int index) { /** * Get extended types. + * * @return the extends. */ public Extends getExtendedTypes() { @@ -182,29 +185,30 @@ public boolean isInterface() { return true; } - /** + /** * returns the local declared supertypes */ public ImmutableList getSupertypes() { - ImmutableList types = ImmutableSLList.nil(); - if (extending != null) { - for (int i = extending.getTypeReferenceCount()-1; i>=0; i--) { - types = types.prepend - (extending.getTypeReferenceAt(i).getKeYJavaType()); - } - } - return types; - } - - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + ImmutableList types = ImmutableSLList.nil(); + if (extending != null) { + for (int i = extending.getTypeReferenceCount() - 1; i >= 0; i--) { + types = types.prepend(extending.getTypeReferenceAt(i).getKeYJavaType()); + } + } + return types; + } + + /** + * 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.performActionOnInterfaceDeclaration(this); + v.performActionOnInterfaceDeclaration(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printInterfaceDeclaration(this); } -} \ No newline at end of file +} 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 84d3b5c612b..29fea618f76 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -23,63 +26,61 @@ import de.uka.ilkd.key.java.declaration.modifier.Volatile; /** - * Java declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Java declaration. taken from COMPOST and changed to achieve an immutable structure */ -public abstract class JavaDeclaration extends JavaNonTerminalProgramElement - implements Declaration { +public abstract class JavaDeclaration extends JavaNonTerminalProgramElement implements Declaration { /** - * Modifiers. - * caches the wrapper for the modifiers. The wrapper is needed to get access - * to the array without hurting immutabilitiy */ + * Modifiers. caches the wrapper for the modifiers. The wrapper is needed to get access to the + * array without hurting immutabilitiy + */ protected final ImmutableArray modArray; - + /** - * Java declaration. + * Java declaration. */ public JavaDeclaration() { - modArray = null; + modArray = null; } public JavaDeclaration(Modifier[] mods) { - modArray = new ImmutableArray(mods); + modArray = new ImmutableArray(mods); } - + public JavaDeclaration(ImmutableArray mods) { - modArray = mods; + modArray = 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 - */ + * + * @param children the children of this AST element as KeY classes. May 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) { @@ -88,7 +89,7 @@ public VisibilityModifier getVisibilityModifier() { 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; @@ -105,7 +106,7 @@ private boolean containsModifier(Class type) { return false; } - + /** * Test whether the declaration is abstract. */ @@ -113,7 +114,7 @@ protected boolean isAbstract() { return containsModifier(Abstract.class); } - + /** * Test whether the declaration is private. */ @@ -121,7 +122,7 @@ protected boolean isPrivate() { return containsModifier(Private.class); } - + /** * Test whether the declaration is protected. */ @@ -129,7 +130,7 @@ protected boolean isProtected() { return containsModifier(Protected.class); } - + /** * Test whether the declaration is public. */ @@ -137,7 +138,7 @@ protected boolean isPublic() { return containsModifier(Public.class); } - + /** * Test whether the declaration is static. */ @@ -145,7 +146,7 @@ protected boolean isStatic() { return containsModifier(Static.class); } - + /** * Test whether the declaration is transient. */ @@ -153,7 +154,7 @@ protected boolean isTransient() { return containsModifier(Transient.class); } - + /** * Test whether the declaration is model (the jml modifier is meant). */ @@ -165,11 +166,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). */ @@ -177,7 +182,7 @@ protected boolean isGhost() { return containsModifier(Ghost.class); } - + /** * Test whether the declaration is volatile. */ @@ -185,7 +190,7 @@ protected boolean isVolatile() { return containsModifier(Volatile.class); } - + /** * Test whether the declaration is strictfp. */ @@ -193,7 +198,7 @@ protected boolean isStrictFp() { return containsModifier(StrictFp.class); } - + /** * Test whether the declaration is final. */ @@ -201,7 +206,7 @@ protected boolean isFinal() { return containsModifier(Final.class); } - + /** * Test whether the declaration is native. */ @@ -209,7 +214,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/LocalVariableDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/LocalVariableDeclaration.java index a58e0ea7dce..eadcd8bbc11 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/LocalVariableDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/LocalVariableDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -10,95 +13,93 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Local variable declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Local variable declaration. taken from COMPOST and changed to achieve an immutable structure */ -public class LocalVariableDeclaration - extends VariableDeclaration implements LoopInitializer { +public class LocalVariableDeclaration extends VariableDeclaration implements LoopInitializer { /** - * Var specs. + * Var specs. */ protected final ImmutableArray varSpecs; /** - * Local variable declaration. + * Local variable declaration. */ public LocalVariableDeclaration() { - super(); - this.varSpecs = null; + super(); + this.varSpecs = null; } /** - * Local variable declaration. - * @param mods a modifier array. - * @param typeRef a type reference. - * @param vars a variable specification array. + * Local variable declaration. + * + * @param mods a modifier array. + * @param typeRef a type reference. + * @param vars a variable specification array. */ - public LocalVariableDeclaration(Modifier[] mods, TypeReference - typeRef, - VariableSpecification[] vars) { - super(mods,typeRef,false); - this.varSpecs=new - ImmutableArray(vars); + public LocalVariableDeclaration(Modifier[] mods, TypeReference typeRef, + VariableSpecification[] vars) { + super(mods, typeRef, false); + this.varSpecs = new ImmutableArray(vars); } /** - * Local variable declaration which declared exactly - * one variable. - * @param typeRef a type reference. - * @param var the variable specification + * Local variable declaration which declared exactly one variable. + * + * @param typeRef a type reference. + * @param var the variable specification */ - public LocalVariableDeclaration(TypeReference typeRef, - VariableSpecification var) { - this(new ImmutableArray(new Modifier[0]),typeRef,var); + public LocalVariableDeclaration(TypeReference typeRef, VariableSpecification var) { + this(new ImmutableArray(new Modifier[0]), typeRef, var); } /** - * Local variable declaration. - * @param mods a modifier array. - * @param typeRef a type reference. - * @param var a variable specification . + * Local variable declaration. + * + * @param mods a modifier array. + * @param typeRef a type reference. + * @param var a variable specification . */ - public LocalVariableDeclaration(ImmutableArray mods, TypeReference - typeRef, VariableSpecification var) { - super(mods,typeRef,false); - this.varSpecs = new ImmutableArray(var); + public LocalVariableDeclaration(ImmutableArray mods, TypeReference typeRef, + VariableSpecification var) { + super(mods, typeRef, false); + this.varSpecs = new ImmutableArray(var); } /** - * Local variable declaration. - * @param mods a modifier array. - * @param typeRef a type reference. - * @param vars a variable specification array. + * Local variable declaration. + * + * @param mods a modifier array. + * @param typeRef a type reference. + * @param vars a variable specification array. */ - public LocalVariableDeclaration(ImmutableArray mods, TypeReference - typeRef, VariableSpecification[] vars) { - super(mods,typeRef,false); - this.varSpecs = new ImmutableArray(vars); + public LocalVariableDeclaration(ImmutableArray mods, TypeReference typeRef, + VariableSpecification[] vars) { + super(mods, typeRef, false); + this.varSpecs = new ImmutableArray(vars); } /** - * Local variable declaration. - * @param children an ExtList containing the children. May include: - * several VariableSpecification (specifying the declared local variable), - * a TypeReference (as reference to the type of the declared variable), - * several Modifier (taken as modifiers of the declaration), - * a Comment + * Local variable declaration. + * + * @param children an ExtList containing the children. May include: several + * VariableSpecification (specifying the declared local variable), a TypeReference (as + * reference to the type of the declared variable), several Modifier (taken as modifiers + * of the declaration), a Comment */ public LocalVariableDeclaration(ExtList children) { super(children, false); - - this.varSpecs = new - ImmutableArray(children.collect(VariableSpecification.class)); + + this.varSpecs = new ImmutableArray( + children.collect(VariableSpecification.class)); } /** @@ -116,26 +117,29 @@ 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 (typeReference != null) result++; - if (varSpecs != null) result += varSpecs.size(); + if (modArray != null) + result += modArray.size(); + if (typeReference != null) + result++; + if (varSpecs != null) + result += varSpecs.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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; @@ -147,7 +151,8 @@ public ProgramElement getChildAt(int index) { index -= len; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (varSpecs != null) { @@ -196,16 +201,18 @@ public boolean isTransient() { return false; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnLocalVariableDeclaration(this); + v.performActionOnLocalVariableDeclaration(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printLocalVariableDeclaration(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MemberDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MemberDeclaration.java index 8ed4d0fea1b..22f57d12341 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MemberDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/MemberDeclaration.java @@ -1,11 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import de.uka.ilkd.key.java.Declaration; import de.uka.ilkd.key.java.NonTerminalProgramElement; /** - * Member declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Member declaration. taken from COMPOST and changed to achieve an immutable structure */ public interface MemberDeclaration extends Declaration, NonTerminalProgramElement { @@ -34,4 +36,4 @@ public interface MemberDeclaration extends Declaration, NonTerminalProgramElemen * Test whether the declaration is strictfp. */ boolean isStrictFp(); -} \ No newline at end of file +} 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 5580115d41d..4c27ac9ddbd 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -19,16 +22,10 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * Method declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Method declaration. taken from COMPOST and changed to achieve an immutable structure */ -public class MethodDeclaration extends JavaDeclaration - implements MemberDeclaration, - TypeReferenceContainer, - NamedProgramElement, - ParameterContainer, - Method, - VariableScope { +public class MethodDeclaration extends JavaDeclaration implements MemberDeclaration, + TypeReferenceContainer, NamedProgramElement, ParameterContainer, Method, VariableScope { protected final TypeReference returnType; protected final Comment[] voidComments; @@ -38,109 +35,95 @@ public class MethodDeclaration extends JavaDeclaration protected final StatementBlock body; - /** this field stores if parent is an InterfaceDeclaration because we will be - * unable to walk the tree upwards to check this + /** + * 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; /** - * 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 + * 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 */ - 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 exceptions a throws. * @param body a statement block. - * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff 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 exceptions a throws. * @param body a statement block. - * @param parentIsInterfaceDeclaration a boolean set true iff - * parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff 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 + @Override public SourceElement getFirstElement() { return getChildAt(0); } - - @Override + + @Override public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } @@ -149,16 +132,22 @@ public SourceElement getLastElement() { @Override public int getChildCount() { int result = 0; - if (modArray != null) result += modArray.size(); - if (returnType != null) result++; - if (name != null) result++; - if (parameters != null) result += parameters.size(); - if (exceptions != null) result++; - if (body != null) result++; + if (modArray != null) + result += modArray.size(); + if (returnType != null) + result++; + if (name != null) + result++; + if (parameters != null) + result += parameters.size(); + if (exceptions != null) + result++; + if (body != null) + result++; return result; } - + @Override public ProgramElement getChildAt(int index) { int len; @@ -170,11 +159,13 @@ public ProgramElement getChildAt(int index) { index -= len; } if (returnType != null) { - if (index == 0) return returnType; + if (index == 0) + return returnType; index--; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; index--; } if (parameters != null) { @@ -185,11 +176,13 @@ public ProgramElement getChildAt(int index) { index -= len; } if (exceptions != null) { - if (index == 0) return exceptions; + if (index == 0) + return exceptions; index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; } throw new ArrayIndexOutOfBoundsException(); } @@ -200,7 +193,7 @@ public int getStatementCount() { return (body != null) ? 1 : 0; } - + @Override public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -215,7 +208,7 @@ public int getTypeReferenceCount() { return (returnType != null) ? 1 : 0; } - + @Override public TypeReference getTypeReferenceAt(int index) { if (returnType != null && index == 0) { @@ -224,13 +217,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) { @@ -239,22 +232,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(); } @@ -264,10 +258,10 @@ public ImmutableArray getParameters() { return parameters; } - - @Override + + @Override public String getFullName() { - return getName(); + return getName(); } @@ -286,47 +280,48 @@ 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. + * Test whether the declaration is public. Methods of interfaces are always public. */ @Override 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(); } /** - * test whether the declaration is a method with a variable number of arguments (i.e. the ellipsis ...) + * test whether the declaration is a method with a variable number of arguments (i.e. the + * ellipsis ...) + * * @return true iff so */ public boolean isVarArgMethod() { @@ -335,26 +330,24 @@ 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. + * 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. + * Test whether the declaration is native. Constructors are never native. */ @Override public boolean isNative() { @@ -367,14 +360,14 @@ 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); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Modifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Modifier.java index 51c3fec3d7e..f0ac71cf3d1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Modifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/Modifier.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -8,50 +11,54 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Modifier. - * taken from COMPOST and changed to achieve an immutable structure + * Modifier. taken from COMPOST and changed to achieve an immutable structure */ public abstract class Modifier extends JavaProgramElement implements TerminalProgramElement { /** - * Modifier. + * Modifier. */ public Modifier() {} /** - * Modifier. + * Modifier. + * * @param children May contain: some Comments */ public Modifier(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected abstract String getSymbol(); /** - * Get symbol text. - * @return the symbol text. + * Get symbol text. + * + * @return the symbol text. */ public String getText() { - return getSymbol(); + return getSymbol(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnModifier(this); + v.performActionOnModifier(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printModifier(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ParameterDeclaration.java index b342a2ad1db..346b6b8ee27 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/ParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -8,90 +11,85 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Formal parameters require a VariableSpecificationList of size() <= 1 - * (size() == 0 for abstract methods) without initializer (for Java). + * Formal parameters require a VariableSpecificationList of size() <= 1 (size() == 0 for abstract + * methods) without initializer (for Java). */ public class ParameterDeclaration extends VariableDeclaration { /** - * Var spec. + * Var spec. */ protected final ImmutableArray varSpec; - - + + /** - * flag to store whether this parameter is a the last arg in a method - * declaration with variable number of arguments. false if not otherwise - * set in the appropriate constructor. + * flag to store whether this parameter is a the last arg in a method declaration with variable + * number of arguments. false if not otherwise set in the appropriate constructor. */ private final boolean varArgParameter; - + /** - * Parameter declaration. + * Parameter declaration. */ public ParameterDeclaration() { - this.varSpec = null; - this.varArgParameter = false; + this.varSpec = null; + this.varArgParameter = false; } - + /** * Parameter declaration. + * * @param mods a modifier array. * @param typeRef a type reference. * @param var the VariableSpecification belonging to this parameter declaration. - * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration - * @param parameterIsVarArg true iff this the last parameter of a method with variable number - * of arguments + * @param parentIsInterfaceDeclaration a boolean set true iff the parent is an + * InterfaceDeclaration + * @param parameterIsVarArg true iff this the last parameter of a method with variable number of + * arguments */ - public ParameterDeclaration(Modifier[] mods, - TypeReference typeRef, - VariableSpecification var, - boolean parentIsInterfaceDeclaration, - boolean parameterIsVarArg) { - super(mods,typeRef,parentIsInterfaceDeclaration); + public ParameterDeclaration(Modifier[] mods, TypeReference typeRef, VariableSpecification var, + boolean parentIsInterfaceDeclaration, boolean parameterIsVarArg) { + super(mods, typeRef, parentIsInterfaceDeclaration); this.varSpec = new ImmutableArray(var); this.varArgParameter = parameterIsVarArg; } - + /** * Parameter declaration. + * * @param mods a modifier array. * @param typeRef a type reference. * @param var the VariableSpecification belonging to this parameter declaration. - * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff the parent is an + * InterfaceDeclaration */ - public ParameterDeclaration(Modifier[] mods, - TypeReference typeRef, - VariableSpecification var, - boolean parentIsInterfaceDeclaration) { + public ParameterDeclaration(Modifier[] mods, TypeReference typeRef, VariableSpecification var, + boolean parentIsInterfaceDeclaration) { this(mods, typeRef, var, parentIsInterfaceDeclaration, false); } - + /** * Parameter declaration. - * @param children an ExtList of children. May contain: - * a VariableSpecification (specifying the parameter) - * 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 iff - * the parent is an InterfaceDeclaration - * @param parameterIsVarArg true iff this the last parameter of a method with variable number - * of arguments + * + * @param children an ExtList of children. May contain: a VariableSpecification (specifying the + * parameter) 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 iff the parent is an + * InterfaceDeclaration + * @param parameterIsVarArg true iff this the last parameter of a method with variable number of + * arguments */ - public ParameterDeclaration(ExtList children, - boolean parentIsInterfaceDeclaration, - boolean parameterIsVarArg) { - super(children,parentIsInterfaceDeclaration); - this.varSpec = new ImmutableArray(children.get(VariableSpecification.class)); - this.varArgParameter = parameterIsVarArg; + public ParameterDeclaration(ExtList children, boolean parentIsInterfaceDeclaration, + boolean parameterIsVarArg) { + super(children, parentIsInterfaceDeclaration); + this.varSpec = new ImmutableArray( + children.get(VariableSpecification.class)); + this.varArgParameter = parameterIsVarArg; } @@ -99,32 +97,35 @@ public VariableSpecification getVariableSpecification() { return varSpec.get(0); } - + public ImmutableArray getVariables() { return varSpec; } /** - * 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 (typeReference != null) result++; - if (varSpec != null) result++; + if (modArray != null) + result += modArray.size(); + if (typeReference != null) + result++; + if (varSpec != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -136,16 +137,18 @@ public ProgramElement getChildAt(int index) { index -= len; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (varSpec != null) { - if (index == 0) return varSpec.get(0); + if (index == 0) + return varSpec.get(0); } throw new ArrayIndexOutOfBoundsException(); } - + /** * Parameters are never private. */ @@ -153,7 +156,7 @@ public boolean isPrivate() { return false; } - + /** * Parameters are never protected. */ @@ -161,7 +164,7 @@ public boolean isProtected() { return false; } - + /** * Parameters are never public. */ @@ -169,8 +172,8 @@ public boolean isProtected() { public boolean isPublic() { return false; } - - + + /** * Parameters are never static. */ @@ -178,7 +181,7 @@ public boolean isStatic() { return false; } - + /** * Parameters are never transient. */ @@ -186,23 +189,24 @@ public boolean isTransient() { return false; } - - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + + /** + * 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.performActionOnParameterDeclaration(this); + v.performActionOnParameterDeclaration(this); } - - + + /** - * returns true iff this parameter is the last in a method with - * a variable number of arguments. - * @return true if the parameter is the last in a method with - * a variable number of arguments + * returns true iff this parameter is the last in a method with a variable number of arguments. + * + * @return true if the parameter is the last in a method with a variable number of arguments */ public boolean isVarArg() { return varArgParameter; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/SuperArrayDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/SuperArrayDeclaration.java index b14777c6fba..73f1da86f2a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/SuperArrayDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/SuperArrayDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.collection.ImmutableList; @@ -9,57 +12,54 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * At the moment the mere purpose of this Class is to provide an encapsulation - * for the length attribute. + * At the moment the mere purpose of this Class is to provide an encapsulation for the length + * attribute. */ -public class SuperArrayDeclaration extends TypeDeclaration{ - +public class SuperArrayDeclaration extends TypeDeclaration { + private FieldDeclaration length = null; - - private SuperArrayDeclaration(ProgramElementName name, - FieldDeclaration length) { - super(new Modifier[0], - name, name, - new MemberDeclaration[]{length}, - false, false); - this.length = length; + + private SuperArrayDeclaration(ProgramElementName name, FieldDeclaration length) { + super(new Modifier[0], name, name, new MemberDeclaration[] { length }, false, false); + this.length = length; } - public SuperArrayDeclaration(FieldDeclaration length){ - this(new ProgramElementName("SuperArray"), length); + public SuperArrayDeclaration(FieldDeclaration length) { + this(new ProgramElementName("SuperArray"), length); } - public int getChildCount(){ - return 0; + public int getChildCount() { + return 0; } - public boolean isInterface(){ - return false; + public boolean isInterface() { + return false; } public FieldDeclaration length() { - return length; + return length; } - /** + /** * returns the local declared supertypes */ public ImmutableList getSupertypes() { - return ImmutableSLList.nil(); + return ImmutableSLList.nil(); } - public ProgramElement getChildAt(int i){ - return null; + public ProgramElement getChildAt(int i) { + return null; } - /** - * calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnSuperArrayDeclaration(this); + v.performActionOnSuperArrayDeclaration(this); } -} \ No newline at end of file +} 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 5293d3d5db4..676385ceda7 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -12,55 +15,55 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Throws. - * @author AutoDoc + * Throws. + * + * @author AutoDoc */ -public class Throws extends JavaNonTerminalProgramElement - implements TypeReferenceContainer { +public class Throws extends JavaNonTerminalProgramElement implements TypeReferenceContainer { /** - * Exceptions. + * Exceptions. */ protected final ImmutableArray exceptions; /** - * Throws. + * Throws. */ public Throws() { - this.exceptions=null; + this.exceptions = null; } /** - * Throws. - * @param exception a type reference. + * Throws. + * + * @param exception a type reference. */ public Throws(TypeReference exception) { - this.exceptions=new ImmutableArray(exception); + this.exceptions = 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.exceptions = 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 + * + * @param children the children of this AST element as KeY classes. 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)); } public SourceElement getLastElement() { @@ -71,22 +74,23 @@ 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 */ public int getChildCount() { int result = 0; - if (exceptions != null) result += exceptions.size(); + if (exceptions != null) + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (exceptions != null) { @@ -94,31 +98,35 @@ public ProgramElement getChildAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } - + /** - * Get exceptions. - * @return the type reference mutable list. + * Get exceptions. + * + * @return the type reference mutable list. */ 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. */ public int getTypeReferenceCount() { return (exceptions != null) ? exceptions.size() : 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. - */ + * 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. + */ public TypeReference getTypeReferenceAt(int index) { if (exceptions != null) { return exceptions.get(index); @@ -127,16 +135,18 @@ public TypeReference getTypeReferenceAt(int index) { } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnThrows(this); + v.performActionOnThrows(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printThrows(this); } -} \ No newline at end of file +} 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 96320406a67..458817b5191 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -23,12 +26,10 @@ import org.slf4j.LoggerFactory; /** - * Type declaration. - * taken from COMPOST and changed to achieve an immutable structure + * Type declaration. taken from COMPOST and changed to achieve an immutable structure */ -public abstract class TypeDeclaration extends JavaDeclaration - implements NamedProgramElement, MemberDeclaration, - TypeDeclarationContainer, ClassType, VariableScope, TypeScope { +public abstract class TypeDeclaration extends JavaDeclaration implements NamedProgramElement, + MemberDeclaration, TypeDeclarationContainer, ClassType, VariableScope, TypeScope { private static final Logger LOGGER = LoggerFactory.getLogger(TypeDeclaration.class); protected final ProgramElementName name; @@ -43,79 +44,62 @@ public abstract class TypeDeclaration extends JavaDeclaration public TypeDeclaration() { - this.name = null; - this.fullName = null; - this.members = null; - this.parentIsInterfaceDeclaration = false; - this.isLibrary = false; + this.name = null; + this.fullName = null; + this.members = null; + this.parentIsInterfaceDeclaration = false; + this.isLibrary = false; } /** * Type declaration. + * * @param mods a modifier array. * @param name ProgramElementName of the type - * @param members an array containing the memberdeclarations of - * this type + * @param members an array containing the memberdeclarations of this type */ - public TypeDeclaration(Modifier[] mods, - ProgramElementName name, - ProgramElementName fullName, - MemberDeclaration[] members, - boolean parentIsInterfaceDeclaration, - boolean isLibrary) { - super(mods); - this.name = name; - this.fullName = fullName; - this.members = new ImmutableArray<>(members); - this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; - this.isLibrary = isLibrary; + public TypeDeclaration(Modifier[] mods, ProgramElementName name, ProgramElementName fullName, + MemberDeclaration[] members, boolean parentIsInterfaceDeclaration, boolean isLibrary) { + super(mods); + this.name = name; + this.fullName = fullName; + this.members = new ImmutableArray<>(members); + this.parentIsInterfaceDeclaration = parentIsInterfaceDeclaration; + this.isLibrary = isLibrary; } /** * @param children an ExtList of children. - * @param name the ProgramElementName of the type - * May contain: - * several MemberDeclaration (as members of the type), - * a parentIsInterfaceDeclaration (indicating if parent is interface), - * several Modifier (as modifiers of the type decl), - * Comments + * @param name the ProgramElementName of the type May contain: several MemberDeclaration (as + * members of the type), a parentIsInterfaceDeclaration (indicating if parent is + * interface), several Modifier (as modifiers of the type decl), Comments */ - public TypeDeclaration(ExtList children, - ProgramElementName name, - ProgramElementName fullName, - boolean isLibrary) { - super(children); - this.name = name; - this.fullName = fullName; - this.members = new ImmutableArray<>(children.collect(MemberDeclaration.class)); - ParentIsInterfaceDeclaration piid=children.get(ParentIsInterfaceDeclaration.class); - if (piid!=null) { - this.parentIsInterfaceDeclaration =(piid).getValue(); - } else { - this.parentIsInterfaceDeclaration =false; - } - this.isLibrary = isLibrary; + public TypeDeclaration(ExtList children, ProgramElementName name, ProgramElementName fullName, + boolean isLibrary) { + super(children); + this.name = name; + this.fullName = fullName; + this.members = new ImmutableArray<>(children.collect(MemberDeclaration.class)); + ParentIsInterfaceDeclaration piid = children.get(ParentIsInterfaceDeclaration.class); + if (piid != null) { + this.parentIsInterfaceDeclaration = (piid).getValue(); + } else { + this.parentIsInterfaceDeclaration = false; + } + this.isLibrary = isLibrary; } /** - * @param children an ExtList of children. - * May contain: - * a ProgramElementName (as name), - * several MemberDeclaration (as members of the type), - * a parentIsInterfaceDeclaration (indicating if parent is interface), - * several Modifier (as modifiers of the type decl), - * Comments + * @param children an ExtList of children. May contain: a ProgramElementName (as name), several + * MemberDeclaration (as members of the type), a parentIsInterfaceDeclaration (indicating + * if parent is interface), several Modifier (as modifiers of the type decl), Comments */ - public TypeDeclaration(ExtList children, - ProgramElementName fullName, - boolean isLibrary) { - this(children, - children.get(ProgramElementName.class), - fullName, isLibrary); + public TypeDeclaration(ExtList children, ProgramElementName fullName, boolean isLibrary) { + this(children, children.get(ProgramElementName.class), fullName, isLibrary); } public SourceElement getFirstElement() { - if (modArray != null && (modArray.size()>0)) { + if (modArray != null && (modArray.size() > 0)) { return modArray.get(0); } else { return this; @@ -129,29 +113,29 @@ public SourceElement getLastElement() { /** * Get name. + * * @return the string. */ public final String getName() { - return (name == null) ? ((fullName == null) ? null : fullName.toString()) - : name.toString(); + return (name == null) ? ((fullName == null) ? null : fullName.toString()) : name.toString(); } public String getFullName() { - return (fullName == null) ? getName() : fullName.toString(); + return (fullName == null) ? getName() : fullName.toString(); } /** - * returns the default value of the given type - * according to JLS 4.5.5 - * @return the default value of the given type - * according to JLS 4.5.5 + * returns the default value of the given type according to JLS 4.5.5 + * + * @return the default value of the given type according to JLS 4.5.5 */ public Literal getDefaultValue() { - return NullLiteral.NULL; + return NullLiteral.NULL; } /** * Get ProgramElementName. + * * @return the ProgramElementName. */ public ProgramElementName getProgramElementName() { @@ -161,6 +145,7 @@ public ProgramElementName getProgramElementName() { /** * Get members. + * * @return the member declaration array. */ public ImmutableArray getMembers() { @@ -168,14 +153,15 @@ public ImmutableArray getMembers() { } public boolean isLibraryClass() { - return isLibrary; + return isLibrary; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public de.uka.ilkd.key.java.abstraction.Package getPackage(Services s) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } /** @@ -187,15 +173,15 @@ public de.uka.ilkd.key.java.abstraction.Package getPackage(Services s) { * TO BE IMPLEMENTED */ public ImmutableList getAllSupertypes(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } /** * TO BE IMPLEMENTED */ public ImmutableList getFields(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); + LOGGER.error("Method in class TypeDeclaration not implemented."); return null; } @@ -211,7 +197,8 @@ public ImmutableList getAllFields(Services services) { for (MemberDeclaration member : members) { if (member instanceof FieldDeclaration) { - for (FieldSpecification field : ((FieldDeclaration) member).getFieldSpecifications()) { + for (FieldSpecification field : ((FieldDeclaration) member) + .getFieldSpecifications()) { result = result.append(field); } } @@ -220,46 +207,52 @@ public ImmutableList getAllFields(Services services) { return result; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public ImmutableList getMethods(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public ImmutableList getAllMethods(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public ImmutableList getConstructors(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public ImmutableList getTypes(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } - /** TO BE IMPLEMENTED + /** + * TO BE IMPLEMENTED */ public ImmutableList getAllTypes(Services services) { - LOGGER.error("Method in class TypeDeclaration not implemented." ); - return null; + LOGGER.error("Method in class TypeDeclaration not implemented."); + return null; } /** - * 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; @@ -274,13 +267,15 @@ public int getTypeDeclarationCount() { } /* - Return the type declaration at the specified index in this node's - "virtual" type declaration array. - @param index an index for a type declaration. - @return the type declaration with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the type declaration at the specified index in this node's "virtual" type declaration + * array. + * + * @param index an index for a type declaration. + * + * @return the type declaration with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public TypeDeclaration getTypeDeclarationAt(int index) { if (members != null) { @@ -289,7 +284,7 @@ public TypeDeclaration getTypeDeclarationAt(int index) { MemberDeclaration md = members.get(i); if (md instanceof TypeDeclaration) { if (index == 0) { - return (TypeDeclaration)md; + return (TypeDeclaration) md; } index -= 1; } @@ -347,9 +342,10 @@ public boolean isAbstract() { return super.isAbstract(); } - public boolean equals(Object o){ - if (o instanceof TypeDeclaration){ - return ((TypeDeclaration)o).fullName.equals(fullName); - } else return false; + public boolean equals(Object o) { + if (o instanceof TypeDeclaration) { + return ((TypeDeclaration) o).fullName.equals(fullName); + } else + return false; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclarationContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclarationContainer.java index c4feeaa613d..eb8263ec1ce 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclarationContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/TypeDeclarationContainer.java @@ -1,27 +1,32 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import de.uka.ilkd.key.java.NonTerminalProgramElement; /** - * Type declaration container. - * taken from COMPOST and changed to achieve an immutable structure + * Type declaration container. taken from COMPOST and changed to achieve an immutable structure */ public interface TypeDeclarationContainer extends NonTerminalProgramElement { /** - * 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. */ int getTypeDeclarationCount(); /* - Return the type declaration at the specified index in this node's - "virtual" type declaration array. - @param index an index for a type declaration. - @return the type declaration with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the type declaration at the specified index in this node's "virtual" type declaration + * array. + * + * @param index an index for a type declaration. + * + * @return the type declaration with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ TypeDeclaration getTypeDeclarationAt(int index); -} \ No newline at end of file +} 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 720ee36e267..e4046dd0fd5 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import org.key_project.util.ExtList; @@ -10,79 +13,77 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Variable declaration. - * taken from COMPOST and changed to achieve an immutable structure + * 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 - * unable to walk the tree upwards to check this + /** + * 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. + * Variable declaration. */ public VariableDeclaration() { - typeReference=null; - parentIsInterfaceDeclaration=false; + typeReference = null; + parentIsInterfaceDeclaration = false; } /** * Variable declaration. + * * @param mods a modifier mutable list. * @param typeRef a type reference. - * @param parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff 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 parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * @param parentIsInterfaceDeclaration a boolean set true iff 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 parentIsInterfaceDeclaration a boolean set true iff - * the parent is an InterfaceDeclaration + * + * @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 */ - 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; } public SourceElement getFirstElement() { @@ -91,7 +92,7 @@ public SourceElement getFirstElement() { @Override public SourceElement getFirstElementIncludingBlocks() { - return getChildAt(0).getFirstElementIncludingBlocks(); + return getChildAt(0).getFirstElementIncludingBlocks(); } public SourceElement getLastElement() { @@ -99,8 +100,9 @@ public SourceElement 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() { @@ -108,13 +110,15 @@ public int getTypeReferenceCount() { } /* - 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. - */ + * 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. + */ public TypeReference getTypeReferenceAt(int index) { if (typeReference != null && index == 0) { @@ -124,8 +128,9 @@ public TypeReference getTypeReferenceAt(int index) { } /** - * Get type reference. - * @return the type reference. + * Get type reference. + * + * @return the type reference. */ public TypeReference getTypeReference() { @@ -133,8 +138,9 @@ public TypeReference getTypeReference() { } /** - * Get variables. - * @return the variable specification array wrapper + * Get variables. + * + * @return the variable specification array wrapper */ public abstract ImmutableArray getVariables(); @@ -147,22 +153,25 @@ public boolean isFinal() { return super.isFinal(); } - /** this field stores if parent is an InterfaceDeclaration because we will be - * unable to walk the tree upwards to check this + /** + * 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 - * perform some action/transformation on this element + /** + * 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 { p.printVariableDeclaration(this); } -} \ No newline at end of file +} 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 35b53a3155c..843380a894a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration; import de.uka.ilkd.key.java.*; @@ -15,11 +18,10 @@ /** * Variable specification that defines a variable name. This is a part of a - * {@link recoder.java.declaration.VariableDeclaration} and does not - * contain a type reference or own modifiers. Note that calls to modifiers - * are delegated to the enclosing variable declaration and are therefore - * discouraged. This was necessary to subtype Declaration as analyses are - * interested in the exact location of a variable name. + * {@link recoder.java.declaration.VariableDeclaration} and does not contain a type reference or own + * modifiers. Note that calls to modifiers are delegated to the enclosing variable declaration and + * are therefore discouraged. This was necessary to subtype Declaration as analyses are interested + * in the exact location of a variable name. * * @author AL */ @@ -58,18 +60,16 @@ public VariableSpecification(IProgramVariable var, Type type) { } - public VariableSpecification(IProgramVariable var, Expression init, - Type type) { + public VariableSpecification(IProgramVariable var, Expression init, Type type) { this(var, 0, init, type, null); } - public VariableSpecification(IProgramVariable var, int dim, - Expression init, Type type) { + public VariableSpecification(IProgramVariable var, int dim, Expression init, Type type) { this(var, dim, init, type, PositionInfo.UNDEFINED); } - public VariableSpecification(IProgramVariable var, int dim, - Expression init, Type type, PositionInfo pi) { + public VariableSpecification(IProgramVariable var, int dim, Expression init, Type type, + PositionInfo pi) { super(pi); this.var = var; this.initializer = init; @@ -81,14 +81,11 @@ public VariableSpecification(IProgramVariable var, int dim, /** * Constructor for the transformation of RECODER ASTs to KeY. * - * @param children the children of this AST element as KeY classes. - * May contain: - * an Expression (as initializer of the variable) - * a Comment - * @param dim the dimension of this type + * @param children the children of this AST element as KeY classes. May contain: an Expression + * (as initializer of the variable) a Comment + * @param dim the dimension of this type */ - public VariableSpecification(ExtList children, IProgramVariable var, - int dim, Type type) { + public VariableSpecification(ExtList children, IProgramVariable var, int dim, Type type) { super(children); this.var = var; initializer = children.get(Expression.class); @@ -104,23 +101,24 @@ public VariableSpecification(ExtList children, IProgramVariable var, */ public int getChildCount() { int result = 0; - if (var != null) result++; - if (initializer != null) result++; + if (var != null) + result++; + if (initializer != null) + result++; return result; } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @throws ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (var != null) { - if (index == 0) return var; + if (index == 0) + return var; index--; } if (initializer != null && index == 0) { @@ -131,7 +129,8 @@ public ProgramElement getChildAt(int index) { @Override protected int computeHashCode() { - return 37 * super.computeHashCode() + 31 * ((type == null) ? 0 : type.hashCode()) + dimensions; + return 37 * super.computeHashCode() + 31 * ((type == null) ? 0 : type.hashCode()) + + dimensions; } /** @@ -145,13 +144,14 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (initializer != null && index == 0) { return initializer; @@ -177,7 +177,7 @@ public ProgramElementName getProgramElementName() { if (var.name() instanceof ProgramElementName) { return (ProgramElementName) var.name(); } else { - return new ProgramElementName(var.name().toString()); //only with SVs + return new ProgramElementName(var.name().toString()); // only with SVs } } @@ -244,8 +244,8 @@ public SourceElement getLastElement() { } /** - * calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + * calls the corresponding method of a visitor in order to perform some action/transformation on + * this element * * @param v the Visitor */ @@ -259,9 +259,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } /** - * equals modulo renaming is described in the corresponding - * comment in class SourceElement. The variables declared in the - * local variable declaration have to be added to the + * equals modulo renaming is described in the corresponding comment in class SourceElement. The + * variables declared in the local variable declaration have to be added to the * NameAbstractionTable. */ @Override @@ -287,8 +286,7 @@ public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { return false; } for (int i = 0, cc = getChildCount(); i < cc; i++) { - if (!getChildAt(i).equalsModRenaming - (vs.getChildAt(i), nat)) { + if (!getChildAt(i).equalsModRenaming(vs.getChildAt(i), nat)) { return false; } } @@ -300,10 +298,10 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { final ProgramElement pe = source.getSource(); matchCond = super.match(source, matchCond); if (matchCond != null && getDimensions() != ((VariableSpecification) pe).getDimensions()) { - LOGGER.debug("Program match. Variables have different dimension " + - "(template {}, source {})", this, pe); + LOGGER.debug("Program match. Variables have different dimension " + + "(template {}, source {})", this, pe); return null; } return matchCond; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Abstract.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Abstract.java index 295ef7f6dbe..98478f8cfd8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Abstract.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Abstract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -5,33 +8,34 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Abstract. + * Abstract. */ public class Abstract extends Modifier { /** - * Abstract. + * Abstract. */ public Abstract() {} /** - * Abstract. + * Abstract. + * * @param children list of children. May contain: Comments */ public Abstract(ExtList children) { - super (children); + super(children); } - /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "abstract"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/AnnotationUseSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/AnnotationUseSpecification.java index 1705a2696b4..383279bbac4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/AnnotationUseSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/AnnotationUseSpecification.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import de.uka.ilkd.key.java.ProgramElement; @@ -5,21 +8,21 @@ import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; -public class AnnotationUseSpecification extends Modifier implements TypeReferenceContainer{ +public class AnnotationUseSpecification extends Modifier implements TypeReferenceContainer { protected final TypeReference tr; - - public AnnotationUseSpecification(TypeReference tr){ + + public AnnotationUseSpecification(TypeReference tr) { super(); this.tr = tr; } - - protected String getSymbol(){ - return "@"+tr.toString(); + + protected String getSymbol() { + return "@" + tr.toString(); } public TypeReference getTypeReferenceAt(int index) { - if(index==0){ + if (index == 0) { return tr; } throw new ArrayIndexOutOfBoundsException(); @@ -30,7 +33,7 @@ public int getTypeReferenceCount() { } public ProgramElement getChildAt(int index) { - if(index==0){ + if (index == 0) { return tr; } throw new ArrayIndexOutOfBoundsException(); @@ -40,4 +43,4 @@ public int getChildCount() { return 1; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Final.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Final.java index 333bcef27cb..3caf136ec85 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Final.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Final.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; @@ -6,31 +9,34 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Final. - * @author AutoDoc + * Final. + * + * @author AutoDoc */ public class Final extends Modifier { /** - * Final. + * Final. */ public Final() {} /** - * Abstract. + * Abstract. + * * @param children list of children. May contain: Comments */ public Final(ExtList children) { - super (children); + super(children); } - + /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "final"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Ghost.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Ghost.java index 059f964ae14..99928f70002 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Ghost.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Ghost.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,7 +9,7 @@ /** - * The JML modifier "ghost". + * The JML modifier "ghost". */ public class Ghost extends Modifier { @@ -14,11 +17,11 @@ public Ghost() {} public Ghost(ExtList children) { - super (children); + super(children); } protected String getSymbol() { return "ghost"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Model.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Model.java index 7414635ec97..d3386aa32c8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Model.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Model.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,7 +9,7 @@ /** - * The JML modifier "model". + * The JML modifier "model". */ public class Model extends Modifier { @@ -14,11 +17,11 @@ public Model() {} public Model(ExtList children) { - super (children); + super(children); } protected String getSymbol() { return "model"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Native.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Native.java index 1dc6809024b..dff356a8ad8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Native.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Native.java @@ -1,34 +1,41 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; + import org.key_project.util.ExtList; import de.uka.ilkd.key.java.declaration.Modifier; /** - * Native. - * @author AutoDoc + * Native. + * + * @author AutoDoc */ public class Native extends Modifier { /** - * Native. + * Native. */ public Native() {} - /** - * Native + /** + * Native + * * @param children list of children. May contain: Comments */ public Native(ExtList children) { - super (children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "native"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/NoState.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/NoState.java index b881ef07caf..7f8ba07cd96 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/NoState.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/NoState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,7 +9,7 @@ /** - * The JML modifier "no_state". + * The JML modifier "no_state". */ public class NoState extends Modifier { @@ -14,11 +17,11 @@ public NoState() {} public NoState(ExtList children) { - super (children); + super(children); } protected String getSymbol() { return "no_state"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Private.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Private.java index 8ab51baa498..2c813a1413b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Private.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Private.java @@ -1,33 +1,39 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; /** - * Private. - * @author AutoDoc + * Private. + * + * @author AutoDoc */ public class Private extends VisibilityModifier { /** - * Private. + * Private. */ public Private() {} /** - * Private + * Private + * * @param children list of children. May contain: Comments */ public Private(ExtList children) { - super (children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "private"; @@ -35,11 +41,15 @@ protected String getSymbol() { @Override public int compareTo(VisibilityModifier arg0) { - if (arg0 instanceof Private) return 0; - if (arg0 == null) return 1; - if (arg0 instanceof Protected) return 2; - if (arg0 instanceof Public) return 3; + if (arg0 instanceof Private) + return 0; + if (arg0 == null) + return 1; + if (arg0 instanceof Protected) + return 2; + if (arg0 instanceof Public) + return 3; assert false; return 0; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Protected.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Protected.java index 53526527bdf..02fce48dada 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Protected.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Protected.java @@ -1,46 +1,56 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; /** - * Protected. - * @author AutoDoc + * Protected. + * + * @author AutoDoc */ public class Protected extends VisibilityModifier { /** - * Protected. + * Protected. */ public Protected() {} /** - * Protected. + * Protected. + * * @param children list of children. May contain: Comments */ public Protected(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "protected"; } - + @Override public int compareTo(VisibilityModifier arg0) { - if (arg0 instanceof Private) return -2; - if (arg0 == null) return -1; - if (arg0 instanceof Protected) return 0; - if (arg0 instanceof Public) return 1; + if (arg0 instanceof Private) + return -2; + if (arg0 == null) + return -1; + if (arg0 instanceof Protected) + return 0; + if (arg0 instanceof Public) + return 1; assert false; return 0; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Public.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Public.java index 4c023ceb194..5da3ec996ff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Public.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Public.java @@ -1,11 +1,15 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; /** - * Public. - * @author AutoDoc + * Public. + * + * @author AutoDoc */ public class Public extends VisibilityModifier { @@ -15,33 +19,38 @@ public class Public extends VisibilityModifier { * Constructor for the transformation of COMPOST ASTs to KeY. */ public Public() { - super(); + super(); } /** * 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 Public(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "public"; } - + @Override public int compareTo(VisibilityModifier arg0) { - if (arg0 instanceof Private) return -3; - if (arg0 == null) return -2; - if (arg0 instanceof Protected) return -1; - if (arg0 instanceof Public) return 0; + if (arg0 instanceof Private) + return -3; + if (arg0 == null) + return -2; + if (arg0 instanceof Protected) + return -1; + if (arg0 instanceof Public) + return 0; assert false; return 0; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Static.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Static.java index f22f3492a02..f692672812f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Static.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Static.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -5,34 +8,36 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Static. - * @author AutoDoc + * Static. + * + * @author AutoDoc */ public class Static extends Modifier { /** - * Static. + * Static. */ public Static() {} /** - * Static - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Static + * + * @param children the children of this AST element as KeY classes. May contain: Comments */ public Static(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "static"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/StrictFp.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/StrictFp.java index fbabaca85a8..8597e4fe60e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/StrictFp.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/StrictFp.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,35 +9,37 @@ /** - * Strict fp. - * @author AutoDoc + * Strict fp. + * + * @author AutoDoc */ public class StrictFp extends Modifier { /** - * Strict fp. + * Strict fp. */ public StrictFp() {} /** - * Strict fp. - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Strict fp. + * + * @param children the children of this AST element as KeY classes. May contain: Comments */ public StrictFp(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "strictfp"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Synchronized.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Synchronized.java index e2f54097c58..3d64b4babad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Synchronized.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Synchronized.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -5,35 +8,37 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Synchronized. - * @author AutoDoc + * Synchronized. + * + * @author AutoDoc */ public class Synchronized extends Modifier { /** - * Synchronized. + * Synchronized. */ public Synchronized() {} /** - * Synchronized. - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Synchronized. + * + * @param children the children of this AST element as KeY classes. May contain: Comments */ public Synchronized(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "synchronized"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Transient.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Transient.java index 749e3545d21..04eaa2d0808 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Transient.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Transient.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -5,34 +8,36 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Transient. - * @author AutoDoc + * Transient. + * + * @author AutoDoc */ public class Transient extends Modifier { /** - * Transient. + * Transient. */ public Transient() {} /** - * Transient. - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Transient. + * + * @param children the children of this AST element as KeY classes. May contain: Comments */ public Transient(ExtList children) { - super(children); + super(children); } - + /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "transient"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/TwoState.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/TwoState.java index c75f43f3eda..cf07682033f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/TwoState.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/TwoState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,7 +9,7 @@ /** - * The JML modifier "two_state". + * The JML modifier "two_state". */ public class TwoState extends Modifier { @@ -14,11 +17,11 @@ public TwoState() {} public TwoState(ExtList children) { - super (children); + super(children); } protected String getSymbol() { return "two_state"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/VisibilityModifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/VisibilityModifier.java index 5dd2e006f64..2c58b80127d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/VisibilityModifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/VisibilityModifier.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -6,54 +9,55 @@ /** - * Visibility modifier. - * Public, protected, and private modifiers are represented by instances of respective subclasses. - * Beware: package-privacy is represented by null! - * For comparison of modifiers, please use the static methods of this class instead of instanceof. - * @author AutoDoc + * Visibility modifier. Public, protected, and private modifiers are represented by instances of + * respective subclasses. Beware: package-privacy is represented by null! For + * comparison of modifiers, please use the static methods of this class instead of + * instanceof. + * + * @author AutoDoc */ -public abstract class VisibilityModifier - extends Modifier implements Comparable{ +public abstract class VisibilityModifier extends Modifier + implements Comparable { - public VisibilityModifier() { - } + public VisibilityModifier() {} /** * 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 VisibilityModifier(ExtList children) { - super(children); + super(children); } /** Whether it represents a public modifier. */ - public static boolean isPublic (VisibilityModifier vm){ - assert sane(vm) : "Unknown visibility modifier: "+vm; + public static boolean isPublic(VisibilityModifier vm) { + assert sane(vm) : "Unknown visibility modifier: " + vm; return vm != null && vm instanceof Public; } - + /** Whether it represents at least a protected modifier. */ - public static boolean allowsInheritance (VisibilityModifier vm){ - assert sane(vm) : "Unknown visibility modifier: "+vm; + public static boolean allowsInheritance(VisibilityModifier vm) { + assert sane(vm) : "Unknown visibility modifier: " + vm; return vm != null && (vm instanceof Public || vm instanceof Protected); } - + /** Whether it represents at least default (package-private) visibility. */ - public static boolean isPackageVisible (VisibilityModifier vm){ - assert sane(vm) : "Unknown visibility modifier: "+vm; + public static boolean isPackageVisible(VisibilityModifier vm) { + assert sane(vm) : "Unknown visibility modifier: " + vm; return vm == null || vm instanceof Public || vm instanceof Protected; } - + /** Whether it represents a private modifier. */ - public static boolean isPrivate (VisibilityModifier vm){ - assert sane(vm) : "Unknown visibility modifier: "+vm; - return vm != null && vm instanceof Private; + public static boolean isPrivate(VisibilityModifier vm) { + assert sane(vm) : "Unknown visibility modifier: " + vm; + return vm != null && vm instanceof Private; } - - private static boolean sane (VisibilityModifier vm){ - return vm == null || vm instanceof Public || vm instanceof Protected || vm instanceof Private; + + private static boolean sane(VisibilityModifier vm) { + return vm == null || vm instanceof Public || vm instanceof Protected + || vm instanceof Private; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Volatile.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Volatile.java index 3e243daa78a..a32b82cb596 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Volatile.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/declaration/modifier/Volatile.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.declaration.modifier; import org.key_project.util.ExtList; @@ -5,34 +8,35 @@ import de.uka.ilkd.key.java.declaration.Modifier; /** - * Volatile. - * + * Volatile. + * */ public class Volatile extends Modifier { /** - * Volatile. + * Volatile. */ public Volatile() {} /** * 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 Volatile(ExtList children) { - super(children); + super(children); } /** - * Get symbol. - * @return the string. + * Get symbol. + * + * @return the string. */ protected String getSymbol() { return "volatile"; } -} \ No newline at end of file +} 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 c0143d3dc2c..5df20650fbf 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import org.key_project.util.ExtList; @@ -15,39 +18,36 @@ /** - * 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 { + implements Expression, ExpressionContainer { protected final ImmutableArray children; protected final KeYJavaType 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)); + super(list); + assert kjt != null; + 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) { @@ -56,7 +56,7 @@ public ArrayInitializer(Expression[] expressions, KeYJavaType kjt) { this.kjt = kjt; this.children = new ImmutableArray(expressions); } - + @Override public int getChildCount() { @@ -72,13 +72,13 @@ public ProgramElement getChildAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - + @Override public int getExpressionCount() { return (children != null) ? children.size() : 0; } - + @Override public Expression getExpressionAt(int index) { if (children != null) { @@ -87,29 +87,30 @@ public Expression getExpressionAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - + @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 bc04ffe57da..301ab84d618 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import org.key_project.util.ExtList; @@ -9,12 +12,11 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; -/** - * 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 { public Assignment() { @@ -22,41 +24,40 @@ public Assignment() { /** * 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 Assignment(ExtList children) { - super(children); + super(children); } /** - Unary Assignment (e.g. +=, ++). - @param lhs an expression. - */ + * Unary Assignment (e.g. +=, ++). + * + * @param lhs an expression. + */ public Assignment(Expression lhs) { super(lhs); } /** - Assignment. - @param lhs an expression. - @param rhs an expression. - */ + * Assignment. + * + * @param lhs an expression. + * @param rhs an expression. + */ public Assignment(Expression lhs, Expression rhs) { super(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() { @@ -66,30 +67,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 * @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/ExpressionStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ExpressionStatement.java index 14c3504d327..f73b3cf8cc6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ExpressionStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/ExpressionStatement.java @@ -1,16 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import de.uka.ilkd.key.java.Expression; import de.uka.ilkd.key.java.LoopInitializer; -/** - * An ExpressionStatement is a statement that may appear as an expression. - * There are three subclasses: MethodReference, Assignment, and New. - * Strictly speaking, Java would allow any expression as a statement; - * however, this does not make much sense (except backward compatibility to - * awkward C code) and is even forbidden in dialects (such as Generic Java). +/** + * An ExpressionStatement is a statement that may appear as an expression. There are three + * subclasses: MethodReference, Assignment, and New. Strictly speaking, Java would allow any + * expression as a statement; however, this does not make much sense (except backward compatibility + * to awkward C code) and is even forbidden in dialects (such as Generic Java). */ public interface ExpressionStatement extends Expression, LoopInitializer { -} \ 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 13a1601435b..715d2b62c13 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import org.key_project.util.ExtList; @@ -16,31 +19,34 @@ import de.uka.ilkd.key.util.Debug; /** - * Literal. - * @author AutoDoc + * Literal. + * + * @author AutoDoc */ -public abstract class Literal extends JavaProgramElement implements Expression, TerminalProgramElement { +public abstract class Literal extends JavaProgramElement + implements Expression, TerminalProgramElement { /** * 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 Literal(ExtList children) { - super(children); + super(children); } /** * Literal */ public Literal() { - + } /** * 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. */ @@ -50,31 +56,35 @@ 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 - * 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 + /** + * 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 * @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(); @@ -84,12 +94,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 9bae9e9f260..c17474d4f08 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import org.key_project.util.ExtList; @@ -13,22 +16,23 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; /** - * Operator base class. - * @author AL -*/ + * Operator base class. + * + * @author AL + */ public abstract class Operator extends JavaNonTerminalProgramElement - implements Expression, ExpressionContainer { + implements Expression, ExpressionContainer { /** - * Children. + * Children. */ protected final ImmutableArray children; /** - * Relative positioning of the operator. + * Relative positioning of the operator. */ public static final int PREFIX = 0; @@ -36,68 +40,66 @@ public abstract class Operator extends JavaNonTerminalProgramElement public static final int POSTFIX = 2; public Operator() { - this.children = null; + this.children = null; } /** - Operator. - @param lhs an expression. - @param rhs an expression. + * Operator. + * + * @param lhs an expression. + * @param rhs an expression. */ public Operator(Expression lhs, Expression rhs) { - this.children=new ImmutableArray(lhs, 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)); + 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(unaryChild); } /** * Operator. + * * @param arguments an array of expression. */ public Operator(Expression[] arguments) { - this.children = new ImmutableArray(arguments); + this.children = 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) { @@ -105,17 +107,16 @@ 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; @@ -134,14 +135,14 @@ public SourceElement getFirstElement() { @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; + } } public SourceElement getLastElement() { @@ -149,15 +150,16 @@ public SourceElement getLastElement() { case INFIX: case PREFIX: return children.get(getArity() - 1).getLastElement(); - case POSTFIX: + case POSTFIX: 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() { @@ -165,12 +167,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 + * 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 */ public ProgramElement getChildAt(int index) { if (children != null) { @@ -180,22 +181,24 @@ 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 (children != null) ? children.size() : 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (children != null) { @@ -206,22 +209,22 @@ public Expression getExpressionAt(int index) { /** 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 dd217de7639..7cb04e9eb5e 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 @@ -1,4 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; + import java.io.IOException; import org.key_project.util.ExtList; @@ -13,44 +17,43 @@ import de.uka.ilkd.key.java.reference.ReferencePrefix; import de.uka.ilkd.key.java.visitor.Visitor; -/** 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 { /** * 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 + * + * @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 */ public ParenthesizedExpression(ExtList children) { - super(children); + super(children); } public ParenthesizedExpression(Expression child) { - super(child); + super(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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (children != null) { @@ -60,28 +63,31 @@ 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;) */ } public SourceElement getFirstElement() { @@ -92,12 +98,14 @@ public SourceElement getLastElement() { return this; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { @@ -105,21 +113,21 @@ public void prettyPrint(PrettyPrinter w) throws IOException { } /** - * We do not have a prefix, so fake it! - * This way we implement ReferencePrefix + * 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); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/PassiveExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/PassiveExpression.java index 501fc020b66..62df30259bd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/PassiveExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/PassiveExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression; import java.io.IOException; @@ -9,37 +12,37 @@ import de.uka.ilkd.key.java.visitor.Visitor; -/** +/** * Marks an active statement as inactive. */ public class PassiveExpression extends ParenthesizedExpression { /** * 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 + * + * @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 */ public PassiveExpression(ExtList children) { - super(children); + super(children); } public PassiveExpression(Expression child) { - super(child); + super(child); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnPassiveExpression(this); + v.performActionOnPassiveExpression(this); } public void prettyPrint(PrettyPrinter w) throws IOException { w.printPassiveExpression(this); } -} \ No newline at end of file +} 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 60694e57b96..923bb471612 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -9,10 +12,11 @@ import de.uka.ilkd.key.logic.Name; /** - * 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. + * 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 { @@ -20,8 +24,7 @@ public abstract class AbstractIntegerLiteral extends Literal { /** * Empty default constructor. */ - protected AbstractIntegerLiteral() { - } + protected AbstractIntegerLiteral() {} /** * Constructor for Recoder2KeY transformation. @@ -55,7 +58,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 @@ -75,14 +78,15 @@ public Name getLDTName() { } /** - * Checks if the prefix of the given String indicates a decimal literal. - * 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 '-'). + * Checks if the prefix of the given String indicates a decimal literal. 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 - * decimal too. + * @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 decimal too. */ public static boolean representsDecLiteral(String literalStr) { if (literalStr.length() == 0) { @@ -93,22 +97,24 @@ public static boolean representsDecLiteral(String literalStr) { literalStr = literalStr.substring(1); } - /* we have to remove the char indicating a long literal as the length of the literal is - * used later on when checking for an octal prefix */ + /* + * we have to remove the char indicating a long literal as the length of the literal is used + * later on when checking for an octal prefix + */ if (literalStr.endsWith("l") || literalStr.endsWith("L")) { literalStr = literalStr.substring(0, literalStr.length() - 1); } int radix = 10; - if (literalStr.startsWith("0x") || literalStr.startsWith("0X")) { // hex + if (literalStr.startsWith("0x") || literalStr.startsWith("0X")) { // hex radix = 16; - //literalStr = literalStr.substring(2); // cut of '0x' + // literalStr = literalStr.substring(2); // cut of '0x' } else if (literalStr.startsWith("0b") || literalStr.startsWith("0B")) { // bin radix = 2; - //literalStr = literalStr.substring(2); // cut of '0b' - } else if (literalStr.startsWith("0") && literalStr.length() > 1) { // oct + // literalStr = literalStr.substring(2); // cut of '0b' + } else if (literalStr.startsWith("0") && literalStr.length() > 1) { // oct radix = 8; - //literalStr = literalStr.substring(1); // cut of leading '0' + // literalStr = literalStr.substring(1); // cut of leading '0' } return radix == 10; } 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 c626267b865..6a5b807b971 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -16,8 +19,9 @@ /** - * Boolean literal. - * @author AutoDoc + * Boolean literal. + * + * @author AutoDoc */ public class BooleanLiteral extends Literal { @@ -27,61 +31,66 @@ public class BooleanLiteral extends Literal { protected final boolean value; - + /** - * get boolean literal for the given value. This supports - * use of single literals, but we do not force it. + * get boolean literal for the given value. This supports 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.value = 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. */ 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 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() { @@ -89,40 +98,43 @@ 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 - * perform some action/transformation on this element + /** + * 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 { @@ -131,7 +143,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 6102c45fc9d..d2ee7b3a9b8 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -9,8 +12,9 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Char literal. - * @author Wolfram Pfeifer + * Char literal. + * + * @author Wolfram Pfeifer */ public class CharLiteral extends AbstractIntegerLiteral { @@ -21,6 +25,7 @@ public class CharLiteral extends AbstractIntegerLiteral { /** * Creates a new CharLiteral from the given char. + * * @param charVal a char value. */ public CharLiteral(char charVal) { @@ -28,11 +33,10 @@ public CharLiteral(char charVal) { } /** - * Creates a new CharLiteral from the given String. - * Char literals can be given as described in the Java 8 Language Specification: - * 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. + * Creates a new CharLiteral from the given String. Char literals can be given as described in + * the Java 8 Language Specification: 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. * @@ -47,6 +51,7 @@ 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) { @@ -55,6 +60,7 @@ public CharLiteral(String valueStr) { /** * Returns the decimal value of the char. + * * @return the decimal value of the char as a BigInteger */ public long getValue() { @@ -85,24 +91,24 @@ public String toString() { @Override public String getValueString() { // the char value as a decimal number (without single-quotes) - return "" + (int)charVal; + return "" + (int) charVal; } /** - * Parses the String and extracts the actual value of the literal. - * This method is able to parse char literals as described in the Java 8 Language Specification: - * 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. + * Parses the String and extracts the actual value of the literal. This method is able to parse + * char literals as described in the Java 8 Language Specification: 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) { if (sourceStr.charAt(0) != '\'' || sourceStr.charAt(sourceStr.length() - 1) != '\'') { @@ -112,10 +118,8 @@ protected char parseFromString(final String sourceStr) { String valStr = sourceStr.substring(1, sourceStr.length() - 1); /* - * There are three possible cases: - * 1. the char is written directly - * 2. Java escape like '\n' - * 3. octal Unicode escape like '\040' + * There are three possible cases: 1. the char is written directly 2. Java escape like '\n' + * 3. octal Unicode escape like '\040' */ if (valStr.charAt(0) == '\\') { switch (valStr.charAt(1)) { 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 ebff8e75292..b1ca9ba67c2 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -14,90 +17,96 @@ import de.uka.ilkd.key.logic.Name; /** - * Double literal. - * @author AutoDoc + * Double literal. + * + * @author AutoDoc */ public class DoubleLiteral extends Literal { /** - * Textual representation of the value. + * Textual representation of the value. */ protected final String value; /** - * Double literal. + * Double literal. */ public DoubleLiteral() { - this.value="0.0"; + this.value = "0.0"; } /** - * Double literal. - * @param value a double value. + * Double literal. + * + * @param value a double value. */ public DoubleLiteral(double value) { - this.value="" + value; + this.value = "" + 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.value = 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 - * perform some action/transformation on this element + /** + * 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 { @@ -105,7 +114,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/EmptyMapLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptyMapLiteral.java index b53f3ef360f..f7a94995ae4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptyMapLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptyMapLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import de.uka.ilkd.key.java.NameAbstractionTable; @@ -15,12 +18,10 @@ public class EmptyMapLiteral extends Literal { public static final EmptyMapLiteral INSTANCE = new EmptyMapLiteral(); - private EmptyMapLiteral() { - } + private EmptyMapLiteral() {} @Override - public boolean equalsModRenaming(SourceElement o, - NameAbstractionTable nat) { + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { return o == this; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySeqLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySeqLiteral.java index ebb3a65b758..f1940abd6a7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySeqLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySeqLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import de.uka.ilkd.key.java.NameAbstractionTable; @@ -16,19 +19,18 @@ public class EmptySeqLiteral extends Literal { public static final EmptySeqLiteral INSTANCE = new EmptySeqLiteral(); - - private EmptySeqLiteral() {} - - + + private EmptySeqLiteral() {} + + @Override - public boolean equalsModRenaming(SourceElement o, - NameAbstractionTable nat) { - return o == this; + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { + return o == this; } public void visit(Visitor v) { - v.performActionOnEmptySeqLiteral(this); + v.performActionOnEmptySeqLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -37,7 +39,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySetLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySetLiteral.java index f946d494fd1..7e3fe0fc810 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySetLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/EmptySetLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import de.uka.ilkd.key.java.NameAbstractionTable; @@ -16,17 +19,16 @@ public class EmptySetLiteral extends Literal { public static final EmptySetLiteral LOCSET = new EmptySetLiteral(); - - + + @Override - public boolean equalsModRenaming(SourceElement o, - NameAbstractionTable nat) { - return o == this; + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { + return o == this; } public void visit(Visitor v) { - v.performActionOnEmptySetLiteral(this); + v.performActionOnEmptySetLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -35,8 +37,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public KeYJavaType getKeYJavaType(Services javaServ) { - PrimitiveType type = PrimitiveType.JAVA_LOCSET; - return javaServ.getJavaInfo().getKeYJavaType(type); + PrimitiveType type = PrimitiveType.JAVA_LOCSET; + return javaServ.getJavaInfo().getKeYJavaType(type); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FloatLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FloatLiteral.java index 94d5e6bdd56..26c0ad1bf99 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FloatLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FloatLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -14,81 +17,88 @@ import de.uka.ilkd.key.logic.Name; /** - * Float literal. - * @author AutoDoc + * Float literal. + * + * @author AutoDoc */ public class FloatLiteral extends Literal { /** - * Textual representation of the value. + * Textual representation of the value. */ protected final String value; /** - * Float literal. - * @param value a float value. + * Float literal. + * + * @param value a float value. */ public FloatLiteral(float value) { - this.value="" + value; + this.value = "" + value; } /** - * Float literal. - * @param children an ExtList with all children(here:comments) - * @param value a string. + * Float literal. + * + * @param children an ExtList with all children(here:comments) + * @param value a string. */ - public FloatLiteral(ExtList children,String value) { - super(children); - this.value=value; + public FloatLiteral(ExtList children, String value) { + super(children); + this.value = value; } /** - * Float literal. - * @param value a string. + * Float literal. + * + * @param value a string. */ public FloatLiteral(String value) { - this.value=value; + this.value = value; } - /** tests if equals + /** + * tests if equals */ - public boolean equalsModRenaming( SourceElement o, - NameAbstractionTable nat){ - if (!(o instanceof FloatLiteral)) { - return false; - } - return ((FloatLiteral)o).getValue().equals(getValue()); + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { + if (!(o instanceof FloatLiteral)) { + return false; + } + return ((FloatLiteral) o).getValue().equals(getValue()); } - + @Override 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 - * perform some action/transformation on this element + /** + * 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.performActionOnFloatLiteral(this); + v.performActionOnFloatLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -96,7 +106,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_FLOAT); } @Override diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FreeLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FreeLiteral.java index 4f5580a310e..b1d6f86942c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FreeLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/FreeLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import de.uka.ilkd.key.java.Services; @@ -9,7 +12,7 @@ import de.uka.ilkd.key.logic.Name; public class FreeLiteral extends Literal { - + public final static FreeLiteral INSTANCE = new FreeLiteral(); @Override @@ -28,4 +31,4 @@ public Name getLDTName() { return FreeLDT.NAME; } -} \ No newline at end of file +} 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 5dcb6ff4341..89aea10e502 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -9,8 +12,9 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Int literal. - * @author AutoDoc + * Int literal. + * + * @author AutoDoc */ public class IntLiteral extends AbstractIntegerLiteral { @@ -33,6 +37,7 @@ public class IntLiteral extends AbstractIntegerLiteral { /** * Creates a new IntLiteral representing the given int. + * * @param value the int value represented by the literal */ public IntLiteral(int value) { @@ -48,9 +53,9 @@ 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); @@ -63,7 +68,7 @@ public IntLiteral(String valStr) { * @param children the children of this AST element as KeY classes, may contain: Comments * @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); @@ -97,20 +102,19 @@ public String getValueString() { } /** - * Parses the String and extracts the actual value of the literal. - * This method is able to parse literals as described in the Java 8 Language Specification: - * hexadecimal (beginning with '0x'), decimal, octal (beginning with '0'), and binary - * (beginning with '0b') literals. In addition, underscores are allowed as separators inside - * the literal. All values parsed by this method are checked for range correctly, particularly - * considering the asymmetric range of int. + * Parses the String and extracts the actual value of the literal. This method is able to parse + * literals as described in the Java 8 Language Specification: hexadecimal (beginning with + * '0x'), decimal, octal (beginning with '0'), and binary (beginning with '0b') literals. In + * addition, underscores are allowed as separators inside the literal. All values parsed by this + * method are checked for range correctly, particularly considering the asymmetric range of int. * Hexadecimal, octal and binary literals are converted using two's complement. * * @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 { @@ -131,15 +135,15 @@ protected int parseFromString(final String sourceStr) throws NumberFormatExcepti valStr = valStr.replace("_", ""); // remove prefix indicating the radix - if (valStr.startsWith("0x") || valStr.startsWith("0X")) { // hex + if (valStr.startsWith("0x") || valStr.startsWith("0X")) { // hex radix = 16; - valStr = valStr.substring(2); // cut of '0x' + valStr = valStr.substring(2); // cut of '0x' } else if (valStr.startsWith("0b") || valStr.startsWith("0B")) { // bin radix = 2; - valStr = valStr.substring(2); // cut of '0b' - } else if (valStr.startsWith("0") && valStr.length() > 1) { // oct + valStr = valStr.substring(2); // cut of '0b' + } else if (valStr.startsWith("0") && valStr.length() > 1) { // oct radix = 8; - valStr = valStr.substring(1); // cut of leading '0' + valStr = valStr.substring(1); // cut of leading '0' } // add minus sign again @@ -150,8 +154,9 @@ protected int parseFromString(final String sourceStr) throws NumberFormatExcepti /////////////////////////////////////////////////////////////////////////// /* range check and actual conversion: */ - /* the raw long converted from the input String without considering - * allowed value range or two's complement + /* + * the raw long converted from the input String without considering allowed value range or + * two's complement */ long val = 0; try { @@ -174,12 +179,14 @@ protected int parseFromString(final String sourceStr) throws NumberFormatExcepti // check if literal is in valid range if (val > maxValue || val < minValue) { - //raiseError("Number constant out of bounds: " + literalString, n); + // raiseError("Number constant out of bounds: " + literalString, n); throw new NumberFormatException("Number constant out of bounds: " + valStr); } - /* 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 + /* + * 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 } } 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 e221d17ca0d..7559eb17793 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import java.math.BigInteger; @@ -11,8 +14,9 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Long literal. - * @author AutoDoc + * Long literal. + * + * @author AutoDoc */ public class LongLiteral extends AbstractIntegerLiteral { @@ -29,8 +33,8 @@ public class LongLiteral extends AbstractIntegerLiteral { private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); /** - * A constant holding the maximum valid value as if a long was interpreted unsigned: - * : 264-1 + * A constant holding the maximum valid value as if a long was interpreted unsigned: : + * 264-1 */ private static final BigInteger MAX_ULONG = new BigInteger("ffffffffffffffff", 16); @@ -46,6 +50,7 @@ public class LongLiteral extends AbstractIntegerLiteral { /** * Creates a new LongLiteral representing the given long. + * * @param value the long value represented by the literal */ public LongLiteral(long value) { @@ -61,9 +66,9 @@ 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); @@ -76,7 +81,7 @@ public LongLiteral(String valStr) { * @param children the children of this AST element as KeY classes, may contain: Comments * @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); @@ -107,8 +112,8 @@ 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() { @@ -116,20 +121,19 @@ public String getValueString() { } /** - * Parses the String and extracts the actual value of the literal. - * This method is able to parse literals as described in the Java 8 Language Specification: - * hexadecimal (beginning with '0x'), decimal, octal (beginning with '0'), and binary - * (beginning with '0b') literals. In addition, underscores are allowed as separators inside - * the literal. All values parsed by this method are checked for range correctly, particularly - * considering the asymmetric range of long. - * Hexadecimal, octal and binary literals are converted using two's complement. + * Parses the String and extracts the actual value of the literal. This method is able to parse + * literals as described in the Java 8 Language Specification: hexadecimal (beginning with + * '0x'), decimal, octal (beginning with '0'), and binary (beginning with '0b') literals. In + * addition, underscores are allowed as separators inside the literal. All values parsed by this + * method are checked for range correctly, particularly considering the asymmetric range of + * long. Hexadecimal, octal and binary literals are converted using two's complement. * * @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) { @@ -153,15 +157,15 @@ protected long parseFromString(final String sourceStr) { valStr = valStr.substring(0, valStr.length() - 1); } - if (valStr.startsWith("0x") || valStr.startsWith("0X")) { // hex + if (valStr.startsWith("0x") || valStr.startsWith("0X")) { // hex radix = 16; - valStr = valStr.substring(2); // cut of '0x' + valStr = valStr.substring(2); // cut of '0x' } else if (valStr.startsWith("0b") || valStr.startsWith("0B")) { // bin radix = 2; - valStr = valStr.substring(2); // cut of '0b' - } else if (valStr.startsWith("0") && valStr.length() > 1) { // oct + valStr = valStr.substring(2); // cut of '0b' + } else if (valStr.startsWith("0") && valStr.length() > 1) { // oct radix = 8; - valStr = valStr.substring(1); // cut of leading '0' + valStr = valStr.substring(1); // cut of leading '0' } // add minus sign again @@ -172,8 +176,9 @@ protected long parseFromString(final String sourceStr) { /////////////////////////////////////////////////////////////////////////// /* range check and actual conversion: */ - /* the raw BigInteger converted from the input String without considering - * allowed value range or two's complement + /* + * the raw BigInteger converted from the input String without considering allowed value + * range or two's complement */ BigInteger val; try { @@ -196,12 +201,14 @@ protected long parseFromString(final String sourceStr) { // check if literal is in valid range if (val.compareTo(maxValue) > 0 || val.compareTo(minValue) < 0) { - //raiseError("Number constant out of bounds: " + literalString, n); + // raiseError("Number constant out of bounds: " + literalString, n); throw new NumberFormatException("Number constant out of bounds: " + sourceStr); } - /* 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 */ + /* + * 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 val.longValue(); // two's complement conversion } } 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 c86997533ff..1c519c29173 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import de.uka.ilkd.key.java.PrettyPrinter; @@ -8,8 +11,7 @@ import de.uka.ilkd.key.logic.Name; /** - * Null literal. - * Is used as singleton. + * Null literal. Is used as singleton. */ public class NullLiteral extends Literal { @@ -20,24 +22,26 @@ public class NullLiteral extends Literal { * Constructor for the transformation of COMPOST ASTs to KeY. */ private NullLiteral() { - super(); + super(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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/literal/RealLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/RealLiteral.java index bdab8d365ec..98d6b8bcd7b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/RealLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/RealLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -14,64 +17,67 @@ import de.uka.ilkd.key.logic.Name; /** - * JML \real literal. - * @author bruns + * JML \real literal. + * + * @author bruns */ public class RealLiteral extends Literal { /** - * Textual representation of the value. + * Textual representation of the value. */ protected final String value; /** - * Double literal. + * Double literal. */ public RealLiteral() { - this.value="0.0"; + this.value = "0.0"; } - public RealLiteral (int value){ - this(""+value+".0"); + public RealLiteral(int value) { + this("" + value + ".0"); } + public RealLiteral(double value) { - this.value="" + value; + this.value = "" + value; } public RealLiteral(java.math.BigDecimal value) { - this.value = ""+value; + this.value = "" + value; } public RealLiteral(ExtList children, String value) { - super(children); - this.value=value; + super(children); + this.value = value; } - public RealLiteral(ExtList children){ + public RealLiteral(ExtList children) { super(children); value = "0.0"; } /** - * Double literal. - * @param value a string. + * Double literal. + * + * @param value a string. */ public RealLiteral(String value) { - this.value=value; + this.value = value; } - /** tests if equals + /** + * tests if equals */ - public boolean equalsModRenaming( SourceElement o, - NameAbstractionTable nat) { - if (!(o instanceof RealLiteral)) { - return false; - } - return ((RealLiteral)o).getValue().equals(getValue()); + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { + if (!(o instanceof RealLiteral)) { + return false; + } + return ((RealLiteral) o).getValue().equals(getValue()); } @Override @@ -80,30 +86,33 @@ public int computeHashCode() { } /** - * 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 - * perform some action/transformation on this element + /** + * 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 { -// p.printDoubleLiteral(this); + // p.printDoubleLiteral(this); } public KeYJavaType getKeYJavaType(Services javaServ) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_REAL); + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_REAL); } - + @Override public Name getLDTName() { return RealLDT.NAME; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/StringLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/StringLiteral.java index 8529e84c42b..0230f65ea65 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/StringLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/literal/StringLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.literal; import org.key_project.util.ExtList; @@ -21,31 +24,32 @@ public class StringLiteral extends Literal implements ReferencePrefix { /** * String literal. + * * @param value a string. */ public StringLiteral(String value) { - this.value=value; + this.value = value; } /** * String literal. + * * @param children an ExtList with children(here:comments) * @param value a string. */ public StringLiteral(ExtList children, String value) { - super(children); - this.value=value; + super(children); + this.value = value; } - public boolean equalsModRenaming(SourceElement o, - NameAbstractionTable nat) { - if (!(o instanceof StringLiteral)) { - return false; - } - return ((StringLiteral)o).getValue().equals(getValue()); + public boolean equalsModRenaming(SourceElement o, NameAbstractionTable nat) { + if (!(o instanceof StringLiteral)) { + return false; + } + return ((StringLiteral) o).getValue().equals(getValue()); } - + @Override public int computeHashCode() { return 17 * super.computeHashCode() + getValue().hashCode(); @@ -55,12 +59,14 @@ public String getValue() { return value; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnStringLiteral(this); + v.performActionOnStringLiteral(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -69,20 +75,20 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { /** - * We do not have a prefix, so fake it! - * This way we implement ReferencePrefix + * 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) { - return javaServ.getJavaInfo().getKeYJavaType("java.lang.String"); + return javaServ.getJavaInfo().getKeYJavaType("java.lang.String"); } @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 39b5fc4eaa3..371c16e708d 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,16 +9,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary and. + * Binary and. */ public class BinaryAnd extends BinaryOperator { /** - * 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) { @@ -23,8 +26,9 @@ public BinaryAnd(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public final int getArity() { @@ -32,8 +36,9 @@ public final int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public final int getPrecedence() { @@ -41,20 +46,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 - * perform some action/transformation on this element + /** + * 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 { @@ -62,4 +70,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/BinaryAndAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryAndAssignment.java index 8af9ebd9e0c..1ee02c65528 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,17 +10,19 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary and assignment. - * @author AutoDoc + * Binary and assignment. + * + * @author AutoDoc */ public class BinaryAndAssignment extends Assignment { - /* 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); @@ -25,8 +30,9 @@ public BinaryAndAssignment(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -34,8 +40,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -43,24 +50,27 @@ 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 - * perform some action/transformation on this element + /** + * 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); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printBinaryAndAssignment(this); } -} \ No newline at end of file +} 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 a56afc3a7f1..cd32d42c83d 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,15 +15,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary not. - * @author AutoDoc + * Binary not. + * + * @author AutoDoc */ public class BinaryNot extends Operator { /** - * Binary not. - * @param children list withh all children + * Binary not. + * + * @param children list withh all children */ public BinaryNot(ExtList children) { @@ -29,8 +34,9 @@ public BinaryNot(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -38,8 +44,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -47,8 +54,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -56,10 +64,10 @@ 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() { @@ -67,12 +75,14 @@ public boolean isLeftAssociative() { } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { @@ -80,9 +90,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/BinaryOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/BinaryOperator.java index dc945c3c866..64b335a8d6c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -10,36 +13,38 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; /** - * 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(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; } 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 ccfcd82631d..762d3915d49 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,18 +9,19 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary or. - * @author AutoDoc + * Binary or. + * + * @author AutoDoc */ public class BinaryOr extends BinaryOperator { /** - * 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) { @@ -27,8 +31,9 @@ public BinaryOr(ExtList children) { /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -36,24 +41,27 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printBinaryOr(this); } -} \ No newline at end of file +} 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 ed704523deb..faed5b7f3f0 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,8 +10,9 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary or assignment. - * @author AutoDoc + * Binary or assignment. + * + * @author AutoDoc */ public class BinaryOrAssignment extends Assignment { @@ -16,10 +20,10 @@ 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) { @@ -28,8 +32,9 @@ public BinaryOrAssignment(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -37,8 +42,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -46,23 +52,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printBinaryOrAssignment(this); } -} \ No newline at end of file +} 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 87a14b4b0ac..5e619590c97 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,18 +9,19 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary X or. - * @author AutoDoc + * Binary X or. + * + * @author AutoDoc */ public class BinaryXOr extends BinaryOperator { /** - * 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) { @@ -26,8 +30,9 @@ public BinaryXOr(ExtList children) { /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -35,23 +40,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printBinaryXOr(this); } -} \ No newline at end of file +} 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 17dfa2ec237..064262436e5 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,18 +10,19 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Binary X or assignment. - * @author AutoDoc + * Binary X or assignment. + * + * @author AutoDoc */ public class BinaryXOrAssignment extends Assignment { /** - * 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) { @@ -26,8 +30,9 @@ public BinaryXOrAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -35,8 +40,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -44,23 +50,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printBinaryXOrAssignment(this); } -} \ No newline at end of file +} 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 5813671d88f..01a41764ed2 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,19 +10,21 @@ import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.java.expression.Operator; import de.uka.ilkd.key.java.reference.ExecutionContext; + /** - * Comparative operator. - * @author AutoDoc + * Comparative operator. + * + * @author AutoDoc */ public abstract class ComparativeOperator extends Operator { /** - * 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) { @@ -32,8 +37,9 @@ public ComparativeOperator(Expression lhs, Expression rhs) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -41,8 +47,9 @@ public int getArity() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -50,10 +57,11 @@ public int getNotation() { } 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 623cb86c764..878fffee3f4 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -17,19 +20,21 @@ public class Conditional extends Operator { /** - * 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() { @@ -37,8 +42,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -46,8 +52,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -55,22 +62,23 @@ 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 - * perform some action/transformation on this element + /** + * 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 { @@ -78,46 +86,39 @@ 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 ed12a53a847..a4a6365a6da 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,63 +11,71 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Copy assignment. - * @author AutoDoc + * Copy assignment. + * + * @author AutoDoc */ public class CopyAssignment extends Assignment { /** * 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 - * perform some action/transformation on this element + /** + * 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 { p.printCopyAssignment(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DLEmbeddedExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DLEmbeddedExpression.java index df0010e633d..5e889e2fca1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DLEmbeddedExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DLEmbeddedExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -36,11 +39,10 @@ public DLEmbeddedExpression(Function f, ExtList children) { } /** - * Arity of an embedded JavaDL Expression depends upon the number of - * arguments. - * - * Since the first argument may be implicitly given, we cannot use the arity - * of {@link #functionSymbol}. + * Arity of an embedded JavaDL Expression depends upon the number of arguments. + * + * Since the first argument may be implicitly given, we cannot use the arity of + * {@link #functionSymbol}. */ @Override public int getArity() { @@ -48,16 +50,19 @@ public int getArity() { return children.size(); } - /* (non-Javadoc) - * @see de.uka.ilkd.key.java.expression.Operator#getKeYJavaType(de.uka.ilkd.key.java.Services, de.uka.ilkd.key.java.reference.ExecutionContext) + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.java.expression.Operator#getKeYJavaType(de.uka.ilkd.key.java.Services, + * de.uka.ilkd.key.java.reference.ExecutionContext) */ @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - + Sort sort = functionSymbol.sort(); - + KeYJavaType kjt = getKeYJavaType(javaServ, sort); - if(kjt != null) { + if (kjt != null) { return kjt; } else { // FIXME FIXME FIXME Unknown types are mapped to int. @@ -79,56 +84,52 @@ public int getPrecedence() { public void visit(Visitor v) { v.performActionOnDLEmbeddedExpression(this); } - - @Override + + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printDLEmbeddedExpression(this); } - public void check(Services javaServ, - KeYJavaType containingClass) throws ConvertException { - - if(functionSymbol == null) + public void check(Services javaServ, KeYJavaType containingClass) throws ConvertException { + + if (functionSymbol == null) throw new ConvertException("null function symbol"); - + int expected = functionSymbol.arity(); int actual = children.size(); // if the first argument is the implicit heap argument, then shift everything // by one int implicitOffset = 0; - - if (actual == expected - 1 && - functionSymbol.argSort(0) == getHeapSort(javaServ)) { + + if (actual == expected - 1 && functionSymbol.argSort(0) == getHeapSort(javaServ)) { implicitOffset = 1; } - + if (expected != actual + implicitOffset) { - throw new ConvertException("Function symbol " + functionSymbol - + " requires " + expected + throw new ConvertException("Function symbol " + functionSymbol + " requires " + expected + " arguments, but received only " + actual); } - String name = containingClass.getSort().name().toString(); - String qualifier = name.lastIndexOf('.') != -1 ? name.substring(0, name.lastIndexOf('.')) : ""; - name = name.substring(name.lastIndexOf('.')+1); - TypeRef tr = - new TypeRef(new ProgramElementName(name, qualifier), 0, null, containingClass); + String name = containingClass.getSort().name().toString(); + String qualifier = + name.lastIndexOf('.') != -1 ? name.substring(0, name.lastIndexOf('.')) : ""; + name = name.substring(name.lastIndexOf('.') + 1); + TypeRef tr = new TypeRef(new ProgramElementName(name, qualifier), 0, null, containingClass); ExecutionContext ec = new ExecutionContext(tr, null, null); for (int i = 0; i < actual; i++) { Sort argSort = functionSymbol.argSort(i + implicitOffset); KeYJavaType kjtExpected = getKeYJavaType(javaServ, argSort); - + Expression child = children.get(i); KeYJavaType kjtActual = javaServ.getTypeConverter().getKeYJavaType(child, ec); - - if(kjtExpected != null && !kjtActual.getSort().extendsTrans(kjtExpected.getSort())) { - throw new ConvertException("Received " + child - + " as argument " + i + " for function " - + functionSymbol + ". Was expecting type " - + kjtExpected + ", but received " + kjtActual); + + if (kjtExpected != null && !kjtActual.getSort().extendsTrans(kjtExpected.getSort())) { + throw new ConvertException("Received " + child + " as argument " + i + + " for function " + functionSymbol + ". Was expecting type " + kjtExpected + + ", but received " + kjtActual); } } } @@ -143,7 +144,7 @@ private static KeYJavaType getKeYJavaType(Services javaServ, Sort argSort) { // other paths. JavaInfo javaInfo = javaServ.getJavaInfo(); KeYJavaType intType = javaInfo.getPrimitiveKeYJavaType("int"); - if(argSort == intType.getSort()) { + if (argSort == intType.getSort()) { return intType; } else { return javaInfo.getKeYJavaType(argSort); @@ -154,8 +155,8 @@ public Term makeTerm(LocationVariable heap, Term[] subs, Services services) { Function f = getFunctionSymbol(); // we silently assume that check has been called earlier - if(f.arity() == subs.length) { - return services.getTermFactory().createTerm(f, subs); + if (f.arity() == subs.length) { + return services.getTermFactory().createTerm(f, subs); } else { Term[] extSubs = new Term[subs.length + 1]; System.arraycopy(subs, 0, extSubs, 1, subs.length); @@ -163,4 +164,4 @@ public Term makeTerm(LocationVariable heap, Term[] subs, Services services) { return services.getTermFactory().createTerm(f, extSubs); } } -} \ No newline at end of file +} 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 04e49706737..58e468aedd3 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,16 +11,16 @@ /** - * Divide. + * Divide. */ public class Divide extends BinaryOperator { /** - * 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) { @@ -25,12 +28,13 @@ public Divide(ExtList 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() { @@ -38,20 +42,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 - * perform some action/transformation on this element + /** + * 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 { @@ -59,4 +66,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/DivideAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/DivideAssignment.java index c2b71201f7f..e008eb8218a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,8 +10,9 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Divide assignment. - * @author AutoDoc + * Divide assignment. + * + * @author AutoDoc */ public class DivideAssignment extends Assignment { @@ -16,10 +20,10 @@ public class DivideAssignment extends Assignment { /** - * 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) { @@ -27,8 +31,9 @@ public DivideAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -36,8 +41,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -45,23 +51,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printDivideAssignment(this); } -} \ No newline at end of file +} 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 7afdcb8c81a..3c3a7fb711c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,16 +10,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Equals. + * Equals. */ public class Equals extends ComparativeOperator { /** - * 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); @@ -24,31 +27,35 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printEquals(this); } -} \ No newline at end of file +} 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 663c32e8fe6..5f43c59cfff 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -10,18 +13,20 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Instanceof. - * @author AutoDoc + * Instanceof. + * + * @author AutoDoc */ public class ExactInstanceof extends TypeOperator { /** - * 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 ExactInstanceof(ExtList children) { @@ -34,14 +39,17 @@ public ExactInstanceof(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; - if (children != null) result += children.size(); - if (typeReference != null) result++; + if (children != null) + result += children.size(); + if (typeReference != null) + result++; return result; } @@ -50,13 +58,12 @@ public SourceElement getLastElement() { } /** - * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; @@ -68,14 +75,16 @@ public ProgramElement getChildAt(int index) { index -= len; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -83,8 +92,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -92,23 +102,26 @@ 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 - * perform some action/transformation on this element + /** + * 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.performActionOnExactInstanceof(this); + v.performActionOnExactInstanceof(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printExactInstanceof(this); } -} \ No newline at end of file +} 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 f5c52e1721b..54e728c540f 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,17 +9,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Greater or equals. + * Greater or equals. */ public class GreaterOrEquals extends ComparativeOperator { /** - * 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) { @@ -24,23 +27,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printGreaterOrEquals(this); } -} \ No newline at end of file +} 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 00b5e6c1310..e1a608abfa6 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,17 +10,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Greater than. + * Greater than. */ public class GreaterThan extends ComparativeOperator { /** - * 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) { @@ -26,6 +29,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 */ @@ -34,23 +38,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printGreaterThan(this); } -} \ No newline at end of file +} 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 09ad250622d..0b55892a339 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -14,18 +17,20 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Instanceof. - * @author AutoDoc + * Instanceof. + * + * @author AutoDoc */ public class Instanceof extends TypeOperator { /** - * 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) { @@ -40,14 +45,17 @@ 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; - if (children != null) result += children.size(); - if (typeReference != null) result++; + if (children != null) + result += children.size(); + if (typeReference != null) + result++; return result; } @@ -56,13 +64,12 @@ public SourceElement getLastElement() { } /** - * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; @@ -74,14 +81,16 @@ public ProgramElement getChildAt(int index) { index -= len; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -89,8 +98,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -98,20 +108,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 - * perform some action/transformation on this element + /** + * 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 { @@ -119,11 +132,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 329ce19c7c1..a4c9bcf947c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -23,12 +26,12 @@ 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); } -} \ No newline at end of file +} 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 9c9412d9fba..278742e5544 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,17 +10,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Less or equals. + * Less or equals. */ public class LessOrEquals extends ComparativeOperator { /** - * 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) { @@ -30,23 +33,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printLessOrEquals(this); } -} \ No newline at end of file +} 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 29830734bd3..7480fb625a2 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,17 +10,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Less than. + * Less than. */ public class LessThan extends ComparativeOperator { /** - * 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); @@ -25,6 +28,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 */ @@ -34,6 +38,7 @@ public LessThan(Expression lhs, Expression rhs) { /** * Get precedence. + * * @return the int value. */ @@ -41,15 +46,17 @@ public int getPrecedence() { return 5; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printLessThan(this); } -} \ No newline at end of file +} 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 8022c4f46a8..3660e971ae1 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -11,17 +14,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Logical and. + * Logical and. */ public class LogicalAnd extends Operator { /** - * 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) { @@ -29,21 +32,23 @@ public LogicalAnd(ExtList children) { } public LogicalAnd(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() { @@ -51,20 +56,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 - * perform some action/transformation on this element + /** + * 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 { @@ -72,7 +80,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 65dfd3579f4..b7b67bc63f6 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -10,17 +13,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Logical not. + * Logical not. */ public class LogicalNot extends Operator { /** - * 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) { @@ -29,8 +32,9 @@ public LogicalNot(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -38,8 +42,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -47,8 +52,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -56,22 +62,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { @@ -79,7 +87,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 38413e76e0e..f3a167d7f15 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,13 +15,13 @@ /** - * Logical or. + * Logical or. */ public class LogicalOr extends Operator { /** - * Logical or. + * Logical or. */ public LogicalOr(ExtList children) { @@ -27,13 +30,14 @@ public LogicalOr(ExtList children) { public LogicalOr(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() { @@ -41,8 +45,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -50,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 - * perform some action/transformation on this element + /** + * 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 { @@ -71,6 +79,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 31f8fca24d9..0b4f86a7a62 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,18 +10,19 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Minus. - * @author AutoDoc + * Minus. + * + * @author AutoDoc */ public class Minus extends BinaryOperator { /** - * 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) { @@ -26,13 +30,14 @@ public Minus(ExtList 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() { @@ -40,20 +45,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 - * perform some action/transformation on this element + /** + * 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 { @@ -62,4 +70,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 873270fd37c..a6c870fc9d7 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,16 +10,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Minus assignment. + * Minus assignment. */ public class MinusAssignment extends Assignment { /** - * Minus 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. + * Minus 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 MinusAssignment(ExtList children) { @@ -25,8 +28,9 @@ public MinusAssignment(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -34,8 +38,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -43,23 +48,26 @@ 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 - * perform some action/transformation on this element + /** + * 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.performActionOnMinusAssignment(this); + v.performActionOnMinusAssignment(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printMinusAssignment(this); } -} \ No newline at end of file +} 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 92ae2ee6323..6a50b59c563 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,13 +11,13 @@ /** - * Modulo. + * Modulo. */ public class Modulo extends BinaryOperator { /** - * Modulo. + * Modulo. */ public Modulo(ExtList children) { @@ -22,15 +25,15 @@ public Modulo(ExtList 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() { @@ -38,24 +41,27 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printModulo(this); } -} \ No newline at end of file +} 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 39c2408cf9a..bf94aa1c570 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,17 +10,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Modulo assignment. + * Modulo assignment. */ public class ModuloAssignment extends Assignment { /** - * 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) { @@ -25,8 +28,9 @@ public ModuloAssignment(ExtList children) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -34,8 +38,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -43,23 +48,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printModuloAssignment(this); } -} \ No newline at end of file +} 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 d446eeaea7b..d1fb155a96c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,16 +15,16 @@ /** - * Negative. + * Negative. */ public class Negative extends Operator { /** - * 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) { @@ -30,12 +33,13 @@ 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() { @@ -43,8 +47,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -52,8 +57,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -61,22 +67,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { @@ -84,8 +92,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 f54c7a4dd10..440d4174959 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -18,114 +21,105 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * The object allocation operator. - * There are two variants for New: - *

      - *
    1. Class constructor call - *
      new XYZ(a1, ..., an) - *
      if getType() instanceof UserType - *
    2. Anonymous Inner Class definition and construction - *
      new XYZ(a1, ..., an) - * { m1, ..., mk } - *
      if getType() instanceof UserType - * {@literal &&} getClassDeclaration() {@literal !=} null - *
    - * The access path is null in most cases, except when an inner class - * constructor is invoked from an outer instance. + * The object allocation operator. There are two variants for New: + *
      + *
    1. Class constructor call
      + * new XYZ(a1, ..., an)
      + * if getType() instanceof UserType + *
    2. Anonymous Inner Class definition and construction
      + * new XYZ(a1, ..., an) + * { m1, ..., mk }
      + * if getType() instanceof UserType {@literal &&} getClassDeclaration() {@literal !=} null + *
    + * The access path is null in most cases, except when an inner class constructor is invoked + * from an outer instance. */ -public class New extends TypeOperator - implements ConstructorReference, - ExpressionStatement, - ReferencePrefix, - ReferenceSuffix, - TypeDeclarationContainer { +public class New extends TypeOperator implements ConstructorReference, ExpressionStatement, + ReferencePrefix, ReferenceSuffix, TypeDeclarationContainer { - protected final ClassDeclaration anonymousClass; + protected final ClassDeclaration anonymousClass; protected final ReferencePrefix accessPath; - + /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * a ClassDeclaration (in case of an anonymous class decl) - * a TypeReference (the referred type) - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments; - * does NOT contain: a ReferencePrefix for the constructor - * as it might be mixed up with the TypeReference - * @param rp a ReferencePrefix as access path for the constructor + * + * @param children the children of this AST element as KeY classes. a ClassDeclaration (in case + * of an anonymous class decl) a TypeReference (the referred type) 2 of Expression (the + * first Expression as left hand side, the second as right hand side), Comments; does NOT + * contain: a ReferencePrefix for the constructor as it might be mixed up with the + * TypeReference + * @param rp a ReferencePrefix as access path for the constructor */ public New(ExtList children, ReferencePrefix rp) { - super(children); - anonymousClass = children.get(ClassDeclaration.class); - accessPath = rp; + super(children); + anonymousClass = children.get(ClassDeclaration.class); + accessPath = rp; } - + /** * Constructor for the transformation of COMPOST ASTs to KeY. - * @param children the children of this AST element as KeY classes. - * a ClassDeclaration (in case of an anonymous class decl) - * a TypeReference (the referred type) - * 2 of Expression (the first Expression as left hand - * side, the second as right hand side), - * Comments; - * does NOT contain: a ReferencePrefix for the constructor - * as it might be mixed up with the TypeReference - * @param rp a ReferencePrefix as access path for the constructor + * + * @param children the children of this AST element as KeY classes. a ClassDeclaration (in case + * of an anonymous class decl) a TypeReference (the referred type) 2 of Expression (the + * first Expression as left hand side, the second as right hand side), Comments; does NOT + * contain: a ReferencePrefix for the constructor as it might be mixed up with the + * TypeReference + * @param rp a ReferencePrefix as access path for the constructor */ public New(ExtList children, ReferencePrefix rp, PositionInfo pi) { - super(children, pi); - anonymousClass = children.get(ClassDeclaration.class); - accessPath = rp; + super(children, pi); + anonymousClass = children.get(ClassDeclaration.class); + accessPath = rp; } /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param type a TypeReference (the referred type) - * @param rp a ReferencePrefix as access path for the constructor + * @param rp a ReferencePrefix as access path for the constructor */ public New(Expression[] arguments, TypeReference type, ReferencePrefix rp) { - super(arguments, type); - anonymousClass = null; - accessPath = rp; + super(arguments, type); + anonymousClass = null; + accessPath = rp; } - - - @Override + + + @Override public SourceElement getFirstElement() { return (accessPath != null) ? accessPath.getFirstElement() : this; } @Override public SourceElement getFirstElementIncludingBlocks() { - return (accessPath != null) ? accessPath.getFirstElementIncludingBlocks() : this; + return (accessPath != null) ? accessPath.getFirstElementIncludingBlocks() : this; } - - @Override + + @Override public SourceElement getLastElement() { return getChildAt(getChildCount() - 1).getLastElement(); } - @Override + @Override public int getArity() { return 0; } - @Override + @Override public int getPrecedence() { return 0; } - - @Override + + @Override public int getNotation() { return PREFIX; } @@ -135,12 +129,12 @@ public ClassDeclaration getClassDeclaration() { return anonymousClass; } - + @Override public int getTypeDeclarationCount() { return (anonymousClass != null) ? 1 : 0; } - + @Override public TypeDeclaration getTypeDeclarationAt(int index) { @@ -150,27 +144,33 @@ public TypeDeclaration getTypeDeclarationAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - + @Override public int getChildCount() { int result = 0; - if (accessPath != null) result++; - if (typeReference != null) result++; - if (children != null) result += children.size(); - if (anonymousClass != null) result++; + if (accessPath != null) + result++; + if (typeReference != null) + result++; + if (children != null) + result += children.size(); + if (anonymousClass != null) + result++; return result; } - - @Override + + @Override public ProgramElement getChildAt(int index) { int len; if (accessPath != null) { - if (index == 0) return accessPath; + if (index == 0) + return accessPath; index--; } if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (children != null) { @@ -181,25 +181,27 @@ public ProgramElement getChildAt(int index) { index -= len; } if (anonymousClass != null) { - if (index == 0) return anonymousClass; + if (index == 0) + return anonymousClass; } throw new ArrayIndexOutOfBoundsException(); } - + /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ - @Override + @Override public ReferencePrefix getReferencePrefix() { return accessPath; } - - + + @Override public void visit(Visitor v) { - v.performActionOnNew(this); + v.performActionOnNew(this); } @@ -208,8 +210,8 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printNew(this); } - + public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } -} \ No newline at end of file +} 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 ff94c3f1b72..fb286c4e87a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -15,35 +18,31 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * The array allocation operator. - * There are two variants for NewArray: - *
      - *
    1. Ordinary array construction - *
      new XYZ[d1]...[dn] - *
    2. Initialized array construction - *
      new XYZ[]...[] { a1, ..., an } - *
    - * Contrary to an ordinary New, a NewArray is no ConstructorReference (since - * all ArrayType constructors are predefined) and is not used as a Statement - * (since there are no side-effects in the constructor). No access path is - * required for new, since there is no inner class problem. - *

    - * NewArray has either a list of dimension length expressions, or - * a single ArrayInitializer. + * The array allocation operator. There are two variants for NewArray: + *

      + *
    1. Ordinary array construction
      + * new XYZ[d1]...[dn] + *
    2. Initialized array construction
      + * new XYZ[]...[] { a1, ..., an } + *
    + * Contrary to an ordinary New, a NewArray is no ConstructorReference (since all ArrayType + * constructors are predefined) and is not used as a Statement (since there are no side-effects in + * the constructor). No access path is required for new, since there is no inner class problem. + *

    + * NewArray has either a list of dimension length expressions, or a single ArrayInitializer. */ -public class NewArray extends TypeOperator - implements Reference, ReferencePrefix { +public class NewArray extends TypeOperator implements Reference, ReferencePrefix { /** - * Dimensions. + * Dimensions. */ protected final int dimensions; - + /** - * Array initializer. + * Array initializer. */ protected final ArrayInitializer arrayInitializer; @@ -55,39 +54,39 @@ public class NewArray extends TypeOperator /** - * New array. - * @param children an ExtList with the children of this node - * (remove the ArrayInitializer out of the list). - * @param init the arrayInitializer + * New array. + * + * @param children an ExtList with the children of this node (remove the ArrayInitializer out of + * the list). + * @param init the arrayInitializer * @param dimensions an int value. */ - public NewArray(ExtList children, KeYJavaType keyJavaType, - ArrayInitializer init, int dimensions) { - super(children); - this.arrayInitializer = init; - this.dimensions = dimensions; - this.keyJavaType = keyJavaType; - assert dimensions > 0; + public NewArray(ExtList children, KeYJavaType keyJavaType, ArrayInitializer init, + int dimensions) { + super(children); + this.arrayInitializer = init; + this.dimensions = dimensions; + this.keyJavaType = keyJavaType; + assert dimensions > 0; } - - + + /** - * New array. - * @param arguments an array of expressions describing the - * dimensions + * New array. + * + * @param arguments an array of expressions describing the dimensions * @param typeRef a reference to the arraytype - * @param init the arrayInitializer + * @param init the arrayInitializer * @param dimensions an int value. */ - public NewArray(Expression[] arguments, TypeReference typeRef, - KeYJavaType keyJavaType, ArrayInitializer init, - int dimensions) { - super(arguments, typeRef); - this.arrayInitializer = init; - this.dimensions = dimensions; - this.keyJavaType = keyJavaType; - assert dimensions > 0; + public NewArray(Expression[] arguments, TypeReference typeRef, KeYJavaType keyJavaType, + ArrayInitializer init, int dimensions) { + super(arguments, typeRef); + this.arrayInitializer = init; + this.dimensions = dimensions; + this.keyJavaType = keyJavaType; + assert dimensions > 0; } public SourceElement getLastElement() { @@ -96,10 +95,11 @@ public SourceElement getLastElement() { } return this; } - + /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -107,8 +107,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -116,8 +117,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -126,8 +128,9 @@ public int getNotation() { /** - * Get dimensions. - * @return the int value. + * Get dimensions. + * + * @return the int value. */ public int getDimensions() { @@ -135,8 +138,9 @@ public int getDimensions() { } /** - * Get array initializer. - * @return the array initializer. + * Get array initializer. + * + * @return the array initializer. */ public ArrayInitializer getArrayInitializer() { @@ -144,31 +148,35 @@ public ArrayInitializer getArrayInitializer() { } /** - * 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 (typeReference != null) result++; - if (children != null) result += children.size(); - if (arrayInitializer != null) result++; + if (typeReference != null) + result++; + if (children != null) + result += children.size(); + if (arrayInitializer != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (children != null) { @@ -179,31 +187,36 @@ public ProgramElement getChildAt(int index) { index -= len; } if (arrayInitializer != null) { - if (index == 0) return arrayInitializer; + if (index == 0) + return arrayInitializer; } 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; - if (children != null) result += children.size(); - if (arrayInitializer != null) result++; + if (children != null) + result += children.size(); + if (arrayInitializer != null) + result++; return result; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { int len; @@ -215,17 +228,20 @@ public Expression getExpressionAt(int index) { index -= len; } if (arrayInitializer != null) { - if (index == 0) return arrayInitializer; + if (index == 0) + return arrayInitializer; } throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnNewArray(this); + v.performActionOnNewArray(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -233,23 +249,23 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } /** - * We do not have a prefix, so fake it! - * This way we implement ReferencePrefix + * We do not have a prefix, so fake it! This way we implement ReferencePrefix + * * @author VK */ public ReferencePrefix getReferencePrefix() { - return null; + return null; } /** * same as getKeYJavaType() */ public KeYJavaType getKeYJavaType(Services javaServ) { - return getKeYJavaType(); + return getKeYJavaType(); } public KeYJavaType getKeYJavaType() { - return keyJavaType; + return keyJavaType; } - -} \ No newline at end of file + +} 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 3355e3b7cab..d682d5d8859 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,17 +9,17 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Not equals. + * Not equals. */ public class NotEquals extends ComparativeOperator { /** - * 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) { @@ -25,23 +28,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printNotEquals(this); } -} \ No newline at end of file +} 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 7a121bd8ebc..9e23f3d713e 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,32 +10,32 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Addition or string concatenation operator "+". + * Addition or string concatenation operator "+". */ public class Plus extends BinaryOperator { /** - * 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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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() { @@ -40,23 +43,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPlus(this); } -} \ No newline at end of file +} 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 d30e6de164b..329ac037d93 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,27 +10,28 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Addition or string concatenation assignment "+=". + * Addition or string concatenation assignment "+=". */ public class PlusAssignment extends Assignment { /** - * 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() { @@ -35,8 +39,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -44,23 +49,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPlusAssignment(this); } -} \ No newline at end of file +} 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 c6de6f7c050..1997ec91fe0 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -11,31 +14,34 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Positive. + * Positive. */ public class Positive extends Operator { /** - * Positive. - * @param expr the Expression + * Positive. + * + * @param expr the Expression */ public Positive(Expression expr) { super(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() { @@ -43,8 +49,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -52,8 +59,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -61,22 +69,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { @@ -84,8 +94,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 7997e18b2ad..313d86e4ee8 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,15 +10,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Post decrement. + * Post decrement. */ public class PostDecrement extends Assignment { /** - * 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) { @@ -24,8 +28,9 @@ public PostDecrement(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -33,8 +38,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -42,23 +48,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPostDecrement(this); } -} \ No newline at end of file +} 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 855b6bae61f..4abefb02096 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,15 +11,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Post increment. + * Post increment. */ public class PostIncrement extends Assignment { /** - * 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) { @@ -25,8 +29,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) { @@ -35,8 +40,9 @@ public PostIncrement(ExtList children) { /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -44,8 +50,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -53,23 +60,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPostIncrement(this); } -} \ No newline at end of file +} 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 6793af5a143..4ad0da0fb48 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,24 +10,26 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Pre decrement. + * Pre decrement. */ public class PreDecrement extends Assignment { /** - * 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() { @@ -32,8 +37,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -41,23 +47,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPreDecrement(this); } -} \ No newline at end of file +} 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 fff26ae2c2a..128d2aaec19 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,15 +10,16 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Pre increment. + * Pre increment. */ public class PreIncrement extends Assignment { /** - * 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) { @@ -24,17 +28,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() { @@ -42,23 +48,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printPreIncrement(this); } -} \ No newline at end of file +} 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 45b426468ba..7d24a977248 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,43 +15,44 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Shift left. - * + * Shift left. + * */ public class ShiftLeft extends Operator { /** - * Shift left. + * Shift left. */ public ShiftLeft() {} /** - * 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); } /** - * 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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -56,8 +60,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -65,19 +70,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 - * perform some action/transformation on this element + /** + * 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 { @@ -86,8 +94,7 @@ 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 d0b41276f1b..89f705a607b 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,22 +11,23 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Shift left assignment. - * + * Shift left assignment. + * */ public class ShiftLeftAssignment extends Assignment { /** - * Shift left assignment. + * 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) { @@ -31,21 +35,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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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() { @@ -53,8 +57,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -62,23 +67,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printShiftLeftAssignment(this); } -} \ No newline at end of file +} 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 58cd9bf6158..9b81f3f9a60 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,41 +15,43 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Shift right. - * @author AutoDoc + * Shift right. + * + * @author AutoDoc */ public class ShiftRight extends Operator { /** - * Shift right. + * Shift right. */ public ShiftRight() {} /** - * 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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -54,8 +59,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -63,20 +69,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 - * perform some action/transformation on this element + /** + * 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 { @@ -85,8 +94,7 @@ 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 67d93ce3eeb..6cb7e9a7497 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -6,43 +9,46 @@ 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 + * Shift right assignment. + * + * @author AutoDoc */ public class ShiftRightAssignment extends Assignment { /** - * Shift right assignment. + * Shift right assignment. */ public ShiftRightAssignment() {} /** - * 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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + /** + * 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 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() { @@ -50,8 +56,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -59,23 +66,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printShiftRightAssignment(this); } -} \ No newline at end of file +} 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 39dfaea2ef7..75221c26e71 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -7,40 +10,42 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Times. - * @author AutoDoc + * Times. + * + * @author AutoDoc */ public class Times extends BinaryOperator { /** - * Times. - * @param lhs an expression. - * @param rhs an expression. + * Times. + * + * @param lhs an expression. + * @param rhs an expression. */ public Times(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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + + /** + * 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 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 Times(ExtList children) { - super(children); + super(children); } - + /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -48,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 - * perform some action/transformation on this element + /** + * 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.performActionOnTimes(this); + v.performActionOnTimes(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -69,4 +77,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/TimesAssignment.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TimesAssignment.java index f62eaa795c7..444c953d778 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,43 +11,45 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Times assignment. - * @author AutoDoc + * Times assignment. + * + * @author AutoDoc */ public class TimesAssignment extends Assignment { /** - * Times assignment. + * 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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + /** + * 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 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() { @@ -52,8 +57,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -61,23 +67,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printTimesAssignment(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeCast.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeCast.java index 07f51775fc9..51c56f9ed76 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeCast.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/TypeCast.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -10,23 +13,22 @@ /** - * Type cast. - * + * Type cast. + * */ public class TypeCast extends TypeOperator { /** - * Type cast. + * Type cast. */ public TypeCast() {} /** - * Note: The ordering of the arguments does not match the syntactical - * appearance of a Java type case, but the order in the superclass - * TypeOperator. However, getASTChildren yields them in the right - * order. + * Note: The ordering of the arguments does not match the syntactical appearance of a Java type + * case, but the order in the superclass TypeOperator. However, getASTChildren yields them in + * the right order. */ public TypeCast(Expression child, TypeReference typeref) { super(child, typeref); @@ -34,38 +36,42 @@ public TypeCast(Expression child, TypeReference typeref) { /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. */ public TypeCast(ExtList children) { - super(children); + super(children); } /** - * 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 (typeReference != null) result++; - if (children != null) result += children.size(); + if (typeReference != null) + result++; + if (children != null) + result += children.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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { int len; if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; index--; } if (children != null) { @@ -78,8 +84,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get arity. - * @return the int value. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -87,8 +94,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -96,8 +104,9 @@ public int getPrecedence() { } /** - * Get notation. - * @return the int value. + * Get notation. + * + * @return the int value. */ public int getNotation() { @@ -105,25 +114,26 @@ public int getNotation() { } /** - * Checks if this operator is left or right associative. Type casts - * are right associative. - * @return true, if the operator is left associative, - * false otherwise. + * Checks if this operator is left or right associative. Type casts 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 - * perform some action/transformation on this element + /** + * 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.performActionOnTypeCast(this); + v.performActionOnTypeCast(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printTypeCast(this); } -} \ No newline at end of file +} 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 f316335eb6c..cebe5a1d1ad 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -10,77 +13,78 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.java.reference.TypeReference; import de.uka.ilkd.key.java.reference.TypeReferenceContainer; + /** - * Type operator. - * @author AutoDoc + * Type operator. + * + * @author AutoDoc */ public abstract class TypeOperator extends Operator implements TypeReferenceContainer { /** - * Type reference. + * Type reference. */ protected final 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 + * + * @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 */ 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 + * + * @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 */ 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; } /* - 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. - */ + * 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. + */ public TypeReference getTypeReferenceAt(int index) { if (typeReference != null && index == 0) { @@ -90,22 +94,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 582d0faa5c5..235f40e2eaa 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -12,22 +15,23 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Unsigned shift right. - * + * Unsigned shift right. + * */ public class UnsignedShiftRight extends Operator { /** - * Unsigned shift right. + * Unsigned shift right. */ public UnsignedShiftRight() {} /** - * 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) { @@ -35,21 +39,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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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. + * Get arity. + * + * @return the int value. */ public int getArity() { @@ -57,8 +61,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -66,20 +71,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 - * perform some action/transformation on this element + /** + * 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 { @@ -88,8 +96,7 @@ 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 37824ff24eb..129f0a47159 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator; import org.key_project.util.ExtList; @@ -8,22 +11,23 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Unsigned shift right assignment. - * + * Unsigned shift right assignment. + * */ public class UnsignedShiftRightAssignment extends Assignment { /** - * Unsigned shift right assignment. + * 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) { @@ -32,20 +36,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 - * of the expression, the second occurrence is taken as the right hand - * side of the expression. + * 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 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() { @@ -53,8 +57,9 @@ public int getArity() { } /** - * Get precedence. - * @return the int value. + * Get precedence. + * + * @return the int value. */ public int getPrecedence() { @@ -62,23 +67,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printUnsignedShiftRightAssignment(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllFields.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllFields.java index 61191159360..f28bb88ef36 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllFields.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllFields.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -28,10 +31,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnAllFields(this); + v.performActionOnAllFields(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printAllFields(this); } @@ -41,6 +44,6 @@ public int getArity() { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); - } -} \ No newline at end of file + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllObjects.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllObjects.java index 738df23d4eb..9c71bacad22 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllObjects.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/AllObjects.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -28,10 +31,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnAllObjects(this); + v.performActionOnAllObjects(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printAllObjects(this); } @@ -41,6 +44,6 @@ public int getArity() { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); - } -} \ No newline at end of file + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); + } +} 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 6aca4cfda05..803824cfae3 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -30,12 +33,12 @@ 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); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqGet.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqGet.java index 5cefdbe4575..e724b60e2f4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqGet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqGet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -12,6 +15,7 @@ /** * Represents a sequence getter function. + * * @author bruns * @since 1.7.2120 * @@ -30,7 +34,7 @@ public int getPrecedence() { @Override public void visit(Visitor v) { - v.performActionOnSeqGet(this); + v.performActionOnSeqGet(this); } @Override @@ -56,4 +60,4 @@ public int getNotation() { return Operator.PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqIndexOf.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqIndexOf.java index e18f27ff46d..36bc0086a4f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqIndexOf.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqIndexOf.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -12,6 +15,7 @@ /** * Represents a function giving the index of some element in a sequence (if it exists). + * * @author bruns * */ @@ -29,7 +33,7 @@ public int getPrecedence() { @Override public void visit(Visitor v) { - v.performActionOnSeqIndexOf(this); + v.performActionOnSeqIndexOf(this); } @Override @@ -55,4 +59,4 @@ public int getNotation() { return Operator.PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqLength.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqLength.java index 661682d1dbb..b9c375439a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqLength.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqLength.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -11,7 +14,8 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Represents a function giving the length of a sequence. + * Represents a function giving the length of a sequence. + * * @author bruns * @since 1.7.2120 * @@ -30,7 +34,7 @@ public int getPrecedence() { @Override public void visit(Visitor v) { - v.performActionOnSeqLength(this); + v.performActionOnSeqLength(this); } @Override @@ -56,4 +60,4 @@ public int getNotation() { return Operator.PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqReverse.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqReverse.java index 78d3b69eaa4..eb106db82de 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqReverse.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqReverse.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -17,38 +20,38 @@ public SeqReverse(ExtList children) { } - @Override + @Override public int getPrecedence() { return 0; } - @Override + @Override public int getNotation() { return PREFIX; } - @Override + @Override public void visit(Visitor v) { - v.performActionOnSeqReverse(this); + v.performActionOnSeqReverse(this); } - @Override + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSeqReverse(this); } - - + + @Override public int getArity() { - return 1; + return 1; } - - + + @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); - } -} \ No newline at end of file + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSingleton.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSingleton.java index 836fac97e98..0efb6e0c9ea 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSingleton.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSingleton.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -16,7 +19,7 @@ public class SeqSingleton extends Operator { public SeqSingleton(ExtList children) { super(children); } - + public SeqSingleton(Expression child) { super(child); } @@ -33,10 +36,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnSeqSingleton(this); + v.performActionOnSeqSingleton(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSeqSingleton(this); } @@ -46,6 +49,6 @@ public int getArity() { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); - } -} \ No newline at end of file + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_SEQ); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSub.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSub.java index ffc22ecc7ba..3a32fd25e2b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSub.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/SeqSub.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -17,36 +20,36 @@ public SeqSub(ExtList children) { } - @Override + @Override public int getPrecedence() { return 0; } - @Override + @Override public int getNotation() { return PREFIX; } - @Override + @Override public void visit(Visitor v) { - v.performActionOnSeqSub(this); + v.performActionOnSeqSub(this); } - @Override + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSeqSub(this); } - - + + @Override public int getArity() { - return 3; + return 3; } - - + + @Override public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { // bugfix, this used to return the join for the the first two arguments' 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 67f6ec81b02..d9cbe3a4b7c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -24,12 +27,12 @@ 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); } -} \ No newline at end of file +} 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 088485263c1..a297b11e840 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -24,12 +27,12 @@ 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); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/Singleton.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/Singleton.java index a9784c3dafb..4bf23e84a9f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/Singleton.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/expression/operator/adt/Singleton.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.expression.operator.adt; import org.key_project.util.ExtList; @@ -28,10 +31,10 @@ public int getNotation() { public void visit(Visitor v) { - v.performActionOnSingleton(this); + v.performActionOnSingleton(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSingleton(this); } @@ -41,6 +44,6 @@ public int getArity() { } public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { - return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); - } -} \ No newline at end of file + return javaServ.getJavaInfo().getKeYJavaType(PrimitiveType.JAVA_LOCSET); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Bigint.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Bigint.java index 8c014ae2547..caa0483fcc1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Bigint.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Bigint.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.abstraction.PrimitiveType; @@ -5,6 +8,7 @@ /** * RecodeR extension for JML's \bigint type. + * * @author bruns * */ @@ -14,4 +18,4 @@ public Bigint(String name, ProgramModelInfo pmi) { super(name, pmi); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchAllStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchAllStatement.java index 58462018b16..c786606d69a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchAllStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchAllStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; @@ -12,12 +15,11 @@ import recoder.java.reference.VariableReference; import recoder.java.statement.JavaStatement; -public class CatchAllStatement extends JavaStatement - implements StatementContainer, - ExpressionContainer { +public class CatchAllStatement extends JavaStatement + implements StatementContainer, ExpressionContainer { /** - * + * */ private static final long serialVersionUID = -7826889550059322778L; @@ -25,111 +27,117 @@ public class CatchAllStatement extends JavaStatement protected StatementBlock body; protected VariableReference param; - - + + /** - * Construct a catch all statement - * @param r the VariableReference of the catch clause - * @param body the StatementBlock representing the catch clause's body - */ - public CatchAllStatement(VariableReference r, - StatementBlock body) { + * Construct a catch all statement + * + * @param r the VariableReference of the catch clause + * @param body the StatementBlock representing the catch clause's body + */ + public CatchAllStatement(VariableReference r, StatementBlock body) { this.body = body; - param = r; + param = r; makeParentRoleValid(); } public NonTerminalProgramElement getASTParent() { - return astParent; + return astParent; } - + public StatementContainer getStatementContainer() { - return astParent; + return astParent; } - + public int getStatementCount() { - return body == null ? 0 : 1; + return body == null ? 0 : 1; } - + public Statement getStatementAt(int i) { - return i == 0 ? body : null; + return i == 0 ? body : null; } - - + + public int getExpressionCount() { return (param != null) ? 1 : 0; } - + public Expression getExpressionAt(int index) { if (param != null && index == 0) { return param; } throw new ArrayIndexOutOfBoundsException(); } - - + + public VariableReference getVariable() { - return param; + return param; } public void setStatementContainer(StatementContainer parent) { - astParent = parent; + astParent = parent; } - + /** - * Finds the source element that occurs first in the source. - * @return the last source element in the syntactical representation of - * this element, may be equals to this element. + * Finds the source element that occurs first in the source. + * + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ public SourceElement getFirstElement() { return getChildAt(0).getFirstElement(); } - + /** - * 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. + * 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. */ 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 (param != null) result++; + if (body != null) + result++; + if (param != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (param != null) { - if (index == 0) return param; + if (index == 0) + return param; index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; index--; } throw new ArrayIndexOutOfBoundsException(); @@ -139,14 +147,14 @@ public ProgramElement getChildAt(int index) { @Override public boolean replaceChild(ProgramElement p, ProgramElement q) { if (param == p) { - VariableReference r = (VariableReference)q; + VariableReference r = (VariableReference) q; param = r; if (r != null) { r.setExpressionContainer(this); } return true; } else if (body == p) { - StatementBlock r = (StatementBlock)q; + StatementBlock r = (StatementBlock) q; body = r; if (r != null) { r.setStatementContainer(this); @@ -156,7 +164,7 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { return false; } - + /** * Ensures that each child has "this" as syntactical parent. */ @@ -164,43 +172,43 @@ public void makeParentRoleValid() { super.makeParentRoleValid(); if (param != null) { param.setExpressionContainer(this); - } + } if (body != null) { body.setStatementContainer(this); } } - + public int getChildPositionCode(ProgramElement child) { if (param == child) { return 0; - } + } if (body == child) { return 1; } return -1; } - - //don't think we need it + + // don't think we need it public void accept(SourceVisitor v) { - if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended)v).visitCatchAll(this); - } else { - throw new IllegalStateException("Method 'accept' not implemented in " - +"CatchAllStatement"); - } + if (v instanceof SourceVisitorExtended) { + ((SourceVisitorExtended) v).visitCatchAll(this); + } else { + throw new IllegalStateException( + "Method 'accept' not implemented in " + "CatchAllStatement"); + } } - - //don't think we need it + + // don't think we need it public CatchAllStatement deepClone() { - throw new IllegalStateException("Method 'deepClone' not implemented in " - +"CatchAllStatement"); - } + throw new IllegalStateException( + "Method 'deepClone' not implemented in " + "CatchAllStatement"); + } + - - public String getName() { - return "catchAll" + "(" + param + ") {" + body + " }"; + public String getName() { + return "catchAll" + "(" + param + ") {" + body + " }"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchSVWrapper.java index 55d21fa8002..42a9d2e27f7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CatchSVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; @@ -6,67 +9,66 @@ import recoder.java.statement.Catch; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class CatchSVWrapper extends Catch - implements KeYRecoderExtension, SVWrapper{ - +public class CatchSVWrapper extends Catch implements KeYRecoderExtension, SVWrapper { + /** - * + * */ private static final long serialVersionUID = 6288254708744002494L; protected SchemaVariable sv; public CatchSVWrapper(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * sets the schema variable of sort statement + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns a String name of this meta construct. */ public SchemaVariable getSV() { - return sv; + return sv; } public void accept(SourceVisitor v) { - v.visitIdentifier(new Identifier(sv.name().toString())); + v.visitIdentifier(new Identifier(sv.name().toString())); } - + public CatchSVWrapper deepClone() { - return new CatchSVWrapper(sv); + return new CatchSVWrapper(sv); } public int getChildCount() { - return 0; + return 0; } public ProgramElement getChildAt(int i) { - throw new ArrayIndexOutOfBoundsException(); + throw new ArrayIndexOutOfBoundsException(); } public int getChildPositionCode(recoder.java.ProgramElement pe) { - throw new ArrayIndexOutOfBoundsException(); + throw new ArrayIndexOutOfBoundsException(); } - public boolean replaceChild(recoder.java.ProgramElement p1, - recoder.java.ProgramElement p2) { - return false; + public boolean replaceChild(recoder.java.ProgramElement p1, recoder.java.ProgramElement p2) { + return false; } public int getStatementCount() { - return 0; + return 0; } - + public recoder.java.Statement getStatementAt(int s) { - throw new ArrayIndexOutOfBoundsException(); + throw new ArrayIndexOutOfBoundsException(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ccatch.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ccatch.java index 1bb62b7eef6..e2739ade7d8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ccatch.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ccatch.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.util.Collections; @@ -17,13 +20,11 @@ import recoder.util.Debug; /** - * A ccatch statement (branch of exec statement). Initial code copied from - * recoder's Catch. + * A ccatch statement (branch of exec statement). Initial code copied from recoder's Catch. * * @author Dominic Steinhöfel */ -public class Ccatch extends Branch - implements ParameterContainer, VariableScope { +public class Ccatch extends Branch implements ParameterContainer, VariableScope { /** * serialization id @@ -54,10 +55,8 @@ public Ccatch() { /** * 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(); @@ -70,13 +69,10 @@ public Ccatch(ParameterDeclaration e, StatementBlock 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) { + public Ccatch(CcatchNonstandardParameterDeclaration e, StatementBlock body) { super(); setBody(body); setNonStdParameterDeclaration(e); @@ -87,8 +83,7 @@ public Ccatch(CcatchNonstandardParameterDeclaration e, /** * Ccatch. * - * @param proto - * a Ccatch. + * @param proto a Ccatch. */ protected Ccatch(Ccatch proto) { super(proto); @@ -96,8 +91,7 @@ protected Ccatch(Ccatch proto) { parameter = Optional.ofNullable(proto.parameter.get().deepClone()); } if (proto.hasNonStdParameterDeclaration()) { - nonStdParameter = Optional - .ofNullable(proto.nonStdParameter.get().deepClone()); + nonStdParameter = Optional.ofNullable(proto.nonStdParameter.get().deepClone()); } if (proto.body != null) { body = proto.body.deepClone(); @@ -151,14 +145,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -197,27 +188,22 @@ public int getChildPositionCode(ProgramElement child) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. * - * @param p - * the old child. - * @param p - * the new child. + * @param p the old child. + * @param p the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ @Override public boolean replaceChild(ProgramElement p, ProgramElement q) { if (p == null) { throw new NullPointerException(); } - if (hasParameterDeclaration() - && parameter.map(param -> param == p).orElse(false)) { + if (hasParameterDeclaration() && parameter.map(param -> param == p).orElse(false)) { ParameterDeclaration r = (ParameterDeclaration) q; parameter = Optional.of(r); if (r != null) { @@ -256,10 +242,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. @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. @exception + * ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { @@ -280,11 +265,10 @@ 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. @return the parameter declaration with the given - * index. @exception ArrayIndexOutOfBoundsException if index is - * out of bounds. + * Return the parameter declaration at the specified index in this node's "virtual" parameter + * declaration array. @param index an index for a parameter declaration. @return the parameter + * declaration with the given index. @exception ArrayIndexOutOfBoundsException if index + * is out of bounds. */ @Override public ParameterDeclaration getParameterDeclarationAt(int index) { @@ -294,8 +278,7 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - public CcatchNonstandardParameterDeclaration getNonstandardParameterDeclarationAt( - int index) { + public CcatchNonstandardParameterDeclaration getNonstandardParameterDeclarationAt(int index) { if (hasNonStdParameterDeclaration() && index == 0) { return nonStdParameter.get(); } @@ -314,8 +297,7 @@ public Statement getBody() { /** * Set body. * - * @param statement - * a statement. + * @param statement a statement. */ public void setBody(Statement statement) { body = (StatementBlock) statement; @@ -324,8 +306,7 @@ public void setBody(Statement statement) { /** * Set parent. * - * @param parent - * a try. + * @param parent a try. */ public void setParent(Exec parent) { this.parent = parent; @@ -360,8 +341,7 @@ public CcatchNonstandardParameterDeclaration getNonStdParameterDeclaration() { /** * Set parameter declaration. * - * @param p - * a parameter declaration. + * @param p a parameter declaration. */ public void setParameterDeclaration(ParameterDeclaration p) { parameter = Optional.ofNullable(p); @@ -370,11 +350,9 @@ public void setParameterDeclaration(ParameterDeclaration p) { /** * Set parameter declaration. * - * @param p - * a parameter declaration. + * @param p a parameter declaration. */ - public void setNonStdParameterDeclaration( - CcatchNonstandardParameterDeclaration p) { + public void setNonStdParameterDeclaration(CcatchNonstandardParameterDeclaration p) { nonStdParameter = Optional.ofNullable(p); } @@ -391,13 +369,10 @@ public void setDefinedScope(boolean defined) { @Override public List getVariablesInScope() { if (hasParameterDeclaration()) { - return parameter.map(ParameterDeclaration::getVariables) - .orElse(null); - } else if (nonStdParameter - .map(p -> p instanceof CcatchReturnValParameterDeclaration) + return parameter.map(ParameterDeclaration::getVariables).orElse(null); + } else if (nonStdParameter.map(p -> p instanceof CcatchReturnValParameterDeclaration) .orElse(false)) { - return nonStdParameter - .map(CcatchReturnValParameterDeclaration.class::cast) + return nonStdParameter.map(CcatchReturnValParameterDeclaration.class::cast) .map(CcatchReturnValParameterDeclaration::getDelegate) .map(ParameterDeclaration::getVariables).orElse(null); } @@ -408,20 +383,17 @@ public List getVariablesInScope() { @Override public VariableSpecification getVariableInScope(String name) { if (hasParameterDeclaration()) { - VariableSpecification v = parameter - .map(ParameterDeclaration::getVariableSpecification) - .orElse(null); + VariableSpecification v = + parameter.map(ParameterDeclaration::getVariableSpecification).orElse(null); if (name.equals(v.getName())) { return v; } - } else if (nonStdParameter - .map(p -> p instanceof CcatchReturnValParameterDeclaration) + } else if (nonStdParameter.map(p -> p instanceof CcatchReturnValParameterDeclaration) .orElse(false)) { - VariableSpecification v = nonStdParameter - .map(CcatchReturnValParameterDeclaration.class::cast) - .map(CcatchReturnValParameterDeclaration::getDelegate) - .map(ParameterDeclaration::getVariableSpecification) - .orElse(null); + VariableSpecification v = + nonStdParameter.map(CcatchReturnValParameterDeclaration.class::cast) + .map(CcatchReturnValParameterDeclaration::getDelegate) + .map(ParameterDeclaration::getVariableSpecification).orElse(null); if (name.equals(v.getName())) { return v; } @@ -449,4 +421,4 @@ public void accept(SourceVisitor v) { // "Method 'accept' not implemented in Ccatch"); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakLabelParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakLabelParameterDeclaration.java index 2527c0db9eb..d63b2300385 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakLabelParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakLabelParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; @@ -9,8 +12,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakLabelParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakLabelParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; private Identifier label; @@ -43,14 +45,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override @@ -72,19 +71,15 @@ public int getChildPositionCode(ProgramElement child) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. * - * @param p - * the old child. - * @param p - * the new child. + * @param p the old child. + * @param p the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ @Override @@ -106,8 +101,7 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchBreakLabelParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchBreakLabelParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakParameterDeclaration.java index 427818cf9cb..8f6076eb6ae 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -7,8 +10,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; @Override @@ -35,8 +37,7 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchBreakParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchBreakParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakWildcardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakWildcardParameterDeclaration.java index 46f89cdf668..e5403877b2b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakWildcardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchBreakWildcardParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -7,8 +10,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchBreakWildcardParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchBreakWildcardParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; @Override @@ -35,8 +37,7 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchReturnWildcardParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchReturnWildcardParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueLabelParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueLabelParameterDeclaration.java index 54354be8b08..924e80f7cb3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueLabelParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueLabelParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; @@ -9,8 +12,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchContinueLabelParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchContinueLabelParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; private Identifier label; @@ -43,14 +45,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override @@ -72,19 +71,15 @@ public int getChildPositionCode(ProgramElement child) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. * - * @param p - * the old child. - * @param p - * the new child. + * @param p the old child. + * @param p the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ @Override @@ -106,8 +101,7 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchContinueLabelParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchContinueLabelParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueParameterDeclaration.java index 3e1323d4114..61b6fa0fcb0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -7,8 +10,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchContinueParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchContinueParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; @Override @@ -35,8 +37,7 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchContinueParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchContinueParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueWildcardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueWildcardParameterDeclaration.java index d9f48af9b79..fde81e590a2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueWildcardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchContinueWildcardParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -35,8 +38,7 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchContinueWildcardParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchContinueWildcardParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchNonstandardParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchNonstandardParameterDeclaration.java index a28f1e3a8a4..957f2caf199 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchNonstandardParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchNonstandardParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.JavaNonTerminalProgramElement; @@ -8,8 +11,7 @@ * * @author Dominic Steinhöfel */ -public abstract class CcatchNonstandardParameterDeclaration - extends JavaNonTerminalProgramElement { +public abstract class CcatchNonstandardParameterDeclaration extends JavaNonTerminalProgramElement { private static final long serialVersionUID = 1L; private ParameterContainer parent; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnParameterDeclaration.java index fbd50e8ea84..11dfce78b93 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -7,8 +10,7 @@ * * @author Dominic Steinhöfel */ -public class CcatchReturnParameterDeclaration - extends CcatchNonstandardParameterDeclaration { +public class CcatchReturnParameterDeclaration extends CcatchNonstandardParameterDeclaration { private static final long serialVersionUID = 1L; @Override @@ -35,8 +37,7 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchReturnParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchReturnParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnValParameterDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnValParameterDeclaration.java index 793e54a7989..eeeaca2a9d6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnValParameterDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchReturnValParameterDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.ParameterContainer; @@ -11,8 +14,8 @@ * * @author Dominic Steinhöfel */ -public class CcatchReturnValParameterDeclaration extends - CcatchNonstandardParameterDeclaration implements ParameterContainer { +public class CcatchReturnValParameterDeclaration extends CcatchNonstandardParameterDeclaration + implements ParameterContainer { private static final long serialVersionUID = 1L; /** @@ -34,11 +37,9 @@ public CcatchReturnValParameterDeclaration(ParameterDeclaration delegate) { /** * Parameter declaration. * - * @param proto - * a parameter declaration. + * @param proto a parameter declaration. */ - protected CcatchReturnValParameterDeclaration( - CcatchReturnValParameterDeclaration proto) { + protected CcatchReturnValParameterDeclaration(CcatchReturnValParameterDeclaration proto) { delegate = proto.delegate; makeParentRoleValid(); } @@ -84,14 +85,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -111,19 +109,15 @@ public int getChildPositionCode(ProgramElement child) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. * - * @param p - * the old child. - * @param p - * the new child. + * @param p the old child. + * @param p the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ @Override public boolean replaceChild(ProgramElement p, ProgramElement q) { @@ -150,8 +144,7 @@ public ParameterContainer getParameterContainer() { /** * Set parameter container. * - * @param c - * a parameter container. + * @param c a parameter container. */ @Override public void setParameterContainer(ParameterContainer c) { @@ -161,8 +154,7 @@ public void setParameterContainer(ParameterContainer c) { @Override public CcatchReturnValParameterDeclaration deepClone() { if (delegate != null) { - return new CcatchReturnValParameterDeclaration( - delegate.deepClone()); + return new CcatchReturnValParameterDeclaration(delegate.deepClone()); } else { return new CcatchReturnValParameterDeclaration(); } @@ -171,8 +163,7 @@ public CcatchReturnValParameterDeclaration deepClone() { @Override public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { - ((SourceVisitorExtended) v) - .visitCcatchReturnValParameterDeclaration(this); + ((SourceVisitorExtended) v).visitCcatchReturnValParameterDeclaration(this); } else { // throw new IllegalStateException( // "Method 'accept' not implemented in Ccatch"); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchSVWrapper.java index 4bde42d6143..f6523770c08 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CcatchSVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.logic.op.SchemaVariable; @@ -5,8 +8,7 @@ import recoder.java.ProgramElement; import recoder.java.SourceVisitor; -public class CcatchSVWrapper extends Ccatch - implements KeYRecoderExtension, SVWrapper { +public class CcatchSVWrapper extends Ccatch implements KeYRecoderExtension, SVWrapper { private static final long serialVersionUID = -1; protected SchemaVariable sv; @@ -17,8 +19,7 @@ public CcatchSVWrapper(SchemaVariable sv) { /** * sets the schema variable of sort statement * - * @param sv - * the SchemaVariable + * @param sv the SchemaVariable */ @Override public void setSV(SchemaVariable sv) { @@ -59,8 +60,7 @@ public int getChildPositionCode(recoder.java.ProgramElement pe) { } @Override - public boolean replaceChild(recoder.java.ProgramElement p1, - recoder.java.ProgramElement p2) { + public boolean replaceChild(recoder.java.ProgramElement p1, recoder.java.ProgramElement p2) { return false; } @@ -74,4 +74,4 @@ public recoder.java.Statement getStatementAt(int s) { throw new ArrayIndexOutOfBoundsException(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationBuilder.java index 1882808afe1..8dbba402a3a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.java.ConvertException; @@ -26,25 +29,24 @@ /** * Make a ClassDeclaration out of a class file. * - * Given a ClassFile read in via recoder create a corresponding ClassDeclaration - * to be registered in the system instead. This allows to rely on one - * mechanism of Recoder-KeY correspondance. + * Given a ClassFile read in via recoder create a corresponding ClassDeclaration to be registered in + * the system instead. This allows to rely on one mechanism of Recoder-KeY correspondance. * - * The information from the classfile are not retrieved via the various services - * but via direct queries. This makes sure that the classfile is not known to - * a classfile repository and saves space. + * The information from the classfile are not retrieved via the various services but via direct + * queries. This makes sure that the classfile is not known to a classfile repository and saves + * space. * - * Method bodies cannot be retrieved so that all methods/constructors have got a - * "null-body", the resulting declaration is a stub. + * Method bodies cannot be retrieved so that all methods/constructors have got a "null-body", the + * resulting declaration is a stub. * * The information is stored into a compilation unit within the appropriate package. * - * TODO Recoder does not allow to detect if an inner class is static or not because - * it discards the information about inner classes all to early. That is why all inner - * classes are non-static. Does this matter? Patch is on the way + * TODO Recoder does not allow to detect if an inner class is static or not because it discards the + * information about inner classes all to early. That is why all inner classes are non-static. Does + * this matter? Patch is on the way * - * TODO inner classes are not detected to be "private". A combination of private and - * static seems impossible with recoder + * TODO inner classes are not detected to be "private". A combination of private and static seems + * impossible with recoder * * TODO Possible improvement: Remove "synthetic" members (JVM spec chapter 4) * @@ -79,13 +81,13 @@ public class ClassFileDeclarationBuilder implements Comparable typeParameters; /** - * create a new ClassDeclaration builder. The builder can be used to create a - * ClassDeclaration for a single class file. + * create a new ClassDeclaration builder. The builder can be used to create a ClassDeclaration + * for a single class file. * * @param classFile class file to be investigated * @param manager the manager to which this builder belongs @@ -99,8 +101,7 @@ public ClassFileDeclarationBuilder(ClassFileDeclarationManager manager, ClassFil /** - * get the class name stored in the class file. May contain '$' for inner or - * anonymous classes + * get the class name stored in the class file. May contain '$' for inner or anonymous classes * * @return the physical name of the class in the class file */ @@ -110,9 +111,9 @@ public String getFullClassname() { /** - * get the class name of this class. If it is an inner class, it is only the - * part after $, or the complete short name otherwise. Anonymous classes are - * therefore referenced by "EnclosingClass$11" for instance. + * get the class name of this class. If it is an inner class, it is only the part after $, or + * the complete short name otherwise. Anonymous classes are therefore referenced by + * "EnclosingClass$11" for instance. * * @return the name of the class */ @@ -126,11 +127,10 @@ public String getClassName() { /** * retrieve the compilation unit for the class file under consideration. * - * The second and following calls will return the cached value of the initial - * calculation. + * The second and following calls will return the cached value of the initial calculation. * - * This method calls {@link #makeTypeDeclaration()} and embeds this type - * into a compilation unit. + * This method calls {@link #makeTypeDeclaration()} and embeds this type into a compilation + * unit. * * @return a compilation unit corresponding to the class file. */ @@ -149,21 +149,20 @@ public CompilationUnit makeCompilationUnit() { /** * retrieve a TypeDeclaration for the class file under consideration * - * The second and following calls will return the cached value of the - * initial calculation. + * The second and following calls will return the cached value of the initial calculation. * * @return a TypeDeclaration corresponding to the class file */ public TypeDeclaration makeTypeDeclaration() { - if(typeDecl == null) { + if (typeDecl == null) { createTypeDeclaration(); setNameAndMods(); setInheritance(); memberDecls = new ASTArrayList(); if (typeDecl instanceof EnumDeclaration) { for (FieldInfo field : classFile.getFieldInfos()) { - if(isEnumConstant(field)) + if (isEnumConstant(field)) addEnumConstant(field); } // create a default constructor for the enum constants @@ -173,7 +172,7 @@ public TypeDeclaration makeTypeDeclaration() { addConstructor(constr); } for (FieldInfo field : classFile.getFieldInfos()) { - if(!isEnumConstant(field)) + if (!isEnumConstant(field)) addField(field); } for (MethodInfo method : classFile.getMethodInfos()) { @@ -186,8 +185,7 @@ public TypeDeclaration makeTypeDeclaration() { } /** - * set the location to be stored in the compilation unit, mainly for - * error reporting. + * set the location to be stored in the compilation unit, mainly for error reporting. * * @param dataLocation the DataLocation to be set or null */ @@ -198,13 +196,13 @@ public void setDataLocation(DataLocation dataLocation) { /** * is the considered ClassFile the byte code of an inner class? * - * This is done checking the fully qualified class name. Does it contain a - * "$" and is this character not followed by a number + * This is done checking the fully qualified class name. Does it contain a "$" and is this + * character not followed by a number * * @return true iff the classFile under inspection is an inner class */ public boolean isInnerClass() { - if(physicalName.contains("$")) { + if (physicalName.contains("$")) { String trailing = physicalName.substring(physicalName.lastIndexOf('$') + 1); return !startsWithADigit(trailing); } @@ -212,15 +210,15 @@ public boolean isInnerClass() { } /** - * is the considered ClassFile the representation of an anymous class or a class - * declared within a program? + * is the considered ClassFile the representation of an anymous class or a class declared within + * a program? * * This is the case if the last $ is followed by a digit. * * @return true iff the classFile under inspection is an anon. or in-code-class */ public boolean isAnonymousClass() { - if(physicalName.contains("$")) { + if (physicalName.contains("$")) { String trailing = physicalName.substring(physicalName.lastIndexOf('$') + 1); return startsWithADigit(trailing); } @@ -228,16 +226,15 @@ public boolean isAnonymousClass() { } /** - * If this is a builder for an inner class, the declaration has to be - * attached to the enclosing class. This method adds the resulting - * declaration to an existing type declaration. A reference to the - * enclosing builder is stored to retrieve the type parameter - * information, e.g. + * If this is a builder for an inner class, the declaration has to be attached to the enclosing + * class. This method adds the resulting declaration to an existing type declaration. A + * reference to the enclosing builder is stored to retrieve the type parameter information, e.g. * */ public void attachToEnclosingDeclaration() { - if(!isInnerClass()) - throw new IllegalStateException("only inner classes can be attached to enclosing classes"); + if (!isInnerClass()) + throw new IllegalStateException( + "only inner classes can be attached to enclosing classes"); // this builder must not yet have built: assert typeDecl == null; @@ -253,10 +250,11 @@ public void attachToEnclosingDeclaration() { /** * get the fully qualified name of the enclosing class of an inner class + * * @return class name, not null */ public String getEnclosingName() { - if(!isInnerClass() && !isAnonymousClass()) + if (!isInnerClass() && !isAnonymousClass()) throw new IllegalStateException("only inner classes have an enclosing class"); return physicalName.substring(0, physicalName.lastIndexOf('$')); } @@ -264,35 +262,28 @@ public String getEnclosingName() { /** * make a stub class declaration for a fully qualified type reference. * - * If the type reference stands for an array, the trailing [] are - * discarded first. + * If the type reference stands for an array, the trailing [] are discarded first. * * - * @param programFactory - * factory to use as parser - * @param fullClassName - * the fully qualified type name - * @return a compilation unit that has not been added to a source repository - * yet - * @throws ParserException - * thrown by the parser - */ - public static CompilationUnit makeEmptyClassDeclaration( - ProgramFactory programFactory, - String fullClassName) - throws ParserException { - - while(fullClassName.endsWith("[]")) - fullClassName = fullClassName.substring(0, fullClassName.length()-2); + * @param programFactory factory to use as parser + * @param fullClassName the fully qualified type name + * @return a compilation unit that has not been added to a source repository yet + * @throws ParserException thrown by the parser + */ + public static CompilationUnit makeEmptyClassDeclaration(ProgramFactory programFactory, + String fullClassName) throws ParserException { + + while (fullClassName.endsWith("[]")) + fullClassName = fullClassName.substring(0, fullClassName.length() - 2); String cuString = ""; int lastdot = fullClassName.lastIndexOf('.'); - if(lastdot != -1) { + if (lastdot != -1) { // there is a package cuString = "package " + fullClassName.substring(0, lastdot) + "; "; } - cuString += "public class " + fullClassName.substring(lastdot+1) + " { }"; + cuString += "public class " + fullClassName.substring(lastdot + 1) + " { }"; LOGGER.debug("Parsing: " + cuString); @@ -301,7 +292,6 @@ public static CompilationUnit makeEmptyClassDeclaration( - // --------------------------------------- private stuff below this line (and main) @@ -314,11 +304,12 @@ private void createTypeDeclaration() { typeDecl = factory.createInterfaceDeclaration(); } else if (classFile.isOrdinaryClass()) { typeDecl = factory.createClassDeclaration(); - } else if (classFile.isEnumType()){ + } else if (classFile.isEnumType()) { // there is no factory.createEnumDeclaration() typeDecl = new EnumDeclaration(); } else { - throw new ConvertException("Only Interfaces, enums and classes are allowed as byte code files"); + throw new ConvertException( + "Only Interfaces, enums and classes are allowed as byte code files"); } } @@ -360,7 +351,7 @@ private void setNameAndMods() { private void setInheritance() { // do not inherit Object from itself! - if("java.lang.Object".equals(physicalName)) + if ("java.lang.Object".equals(physicalName)) return; String superClassName = classFile.getSuperClassName(); @@ -376,26 +367,26 @@ private void setInheritance() { for (String intf : interfaceNames) { implList.add(createTypeReference(intf)); } - if(implList.size() > 0) + if (implList.size() > 0) classDecl.setImplementedTypes(factory.createImplements(implList)); - } else if(typeDecl instanceof EnumDeclaration) { + } else if (typeDecl instanceof EnumDeclaration) { EnumDeclaration enDecl = (EnumDeclaration) typeDecl; ASTList implList = new ASTArrayList(); for (String intf : interfaceNames) { implList.add(createTypeReference(intf)); } - if(implList.size() > 0) + if (implList.size() > 0) enDecl.setImplementedTypes(factory.createImplements(implList)); - } else if(typeDecl instanceof InterfaceDeclaration){ + } else if (typeDecl instanceof InterfaceDeclaration) { InterfaceDeclaration intfDecl = (InterfaceDeclaration) typeDecl; ASTList implList = new ASTArrayList(); for (String intf : interfaceNames) { implList.add(createTypeReference(intf)); } - if(implList.size() > 0) + if (implList.size() > 0) intfDecl.setExtendedTypes(factory.createExtends(implList)); } else - throw new Error("unknown declaration type: " + typeDecl.getClass().getName()); + throw new Error("unknown declaration type: " + typeDecl.getClass().getName()); } @@ -416,8 +407,7 @@ private void setPackage() { /* - * create the modifier list for a field declaration - * TODO are these all the possible modifiers? + * create the modifier list for a field declaration TODO are these all the possible modifiers? */ private ASTList makeFieldSpecifiers(FieldInfo decl) { ASTList specs = new ASTArrayList(); @@ -435,23 +425,22 @@ private ASTList makeFieldSpecifiers(FieldInfo decl) { } /* - * This uses an undocumented(!) feature which is provided by the java - * compiler: Enum constants have set the bit 0x4000 in their access flags. - * TODO find a documented and transferable mean to express this + * This uses an undocumented(!) feature which is provided by the java compiler: Enum constants + * have set the bit 0x4000 in their access flags. TODO find a documented and transferable mean + * to express this */ private boolean isEnumConstant(FieldInfo field) { return ((field.getAccessFlags() & 0x4000) == 0x4000); } /* - * Add a field to the member list - * TODO compile time constants. + * Add a field to the member list TODO compile time constants. */ private void addField(FieldInfo field) { // ignore internal fields. String name = field.getName(); - if(isInternal(name)) + if (isInternal(name)) return; String typename = field.getTypeName(); @@ -466,23 +455,21 @@ private void addField(FieldInfo field) { } /* - * Add an enum constant to the member list. - * There is no factory.createEnum... () method + * Add an enum constant to the member list. There is no factory.createEnum... () method * - * TODO This maps all constants w/o arguments, i.e. - * such a constructor must be present. :( + * TODO This maps all constants w/o arguments, i.e. such a constructor must be present. :( */ private void addEnumConstant(FieldInfo field) { Identifier id = factory.createIdentifier(field.getName()); EnumConstructorReference ecr = new EnumConstructorReference(); EnumConstantSpecification ecs = new EnumConstantSpecification(id, ecr); - EnumConstantDeclaration ecd = new EnumConstantDeclaration(ecs, new ASTArrayList()); + EnumConstantDeclaration ecd = + new EnumConstantDeclaration(ecs, new ASTArrayList()); memberDecls.add(ecd); } /* - * create the modifier list for a method declaration - * TODO are these all the possiblie mods? + * create the modifier list for a method declaration TODO are these all the possiblie mods? */ private ASTList makeMethodSpecifiers(MethodInfo decl) { ASTList specs = new ASTArrayList(); @@ -512,7 +499,7 @@ private void addMethod(MethodInfo method) { // feature: ignore access functions which should not ne visible on // source code level String methodName = method.getName(); - if(isInternal(methodName)) + if (isInternal(methodName)) return; String returntype = method.getTypeName(); @@ -533,8 +520,8 @@ private void addMethod(MethodInfo method) { } // modify last argument to vararg if method is vararg (#1664) - if(method.isVarArgMethod()) { - ParameterDeclaration lastParam = params.get(params.size()-1); + if (method.isVarArgMethod()) { + ParameterDeclaration lastParam = params.get(params.size() - 1); lastParam.setVarArg(true); TypeReference tyref = lastParam.getTypeReference(); tyref.setDimensions(tyref.getDimensions() - 1); @@ -561,14 +548,14 @@ private void addMethod(MethodInfo method) { } /* - * add a default constructor - * this is used for enums, it is therefore made private + * add a default constructor this is used for enums, it is therefore made private */ private void addDefaultConstructor() { Identifier id = factory.createIdentifier(getClassName()); Private priv = factory.createPrivate(); ASTList params = new ASTArrayList(); - ConstructorDeclaration decl = factory.createConstructorDeclaration(priv, id, params, null, null); + ConstructorDeclaration decl = + factory.createConstructorDeclaration(priv, id, params, null, null); memberDecls.add(decl); } @@ -589,7 +576,7 @@ private void addConstructor(ConstructorInfo constr) { tys = resolveTypeVariable(tys, constr.getTypeParameters()); // filter out those constructors with a Classname$1 argument // that are only introduced for technical reasons - if(ClassFileDeclarationBuilder.isAnononymous(tys)) + if (ClassFileDeclarationBuilder.isAnononymous(tys)) return; type = createTypeReference(tys); String name = "arg" + (index++); @@ -617,8 +604,7 @@ private void addConstructor(ConstructorInfo constr) { /* - * Helper: - * see also recoder.kit,PackageKit + * Helper: see also recoder.kit,PackageKit */ private PackageReference makePackageReference(String name) { PackageReference result = null; @@ -633,19 +619,16 @@ private PackageReference makePackageReference(String name) { } /* - * in the presence of (generic) type parameters - * replace every type parameter by its first boundary. - * There are three sources for type parameters: - *

      - *
    1. type parameters in the classfile - *
    2. type parameters from the enclosing classfiles (gathered in getAllTypeParameters) - *
    3. additional parameters (from constr/methdo decl) - *
    + * in the presence of (generic) type parameters replace every type parameter by its first + * boundary. There are three sources for type parameters:
    1. type parameters in the + * classfile
    2. type parameters from the enclosing classfiles (gathered in + * getAllTypeParameters)
    3. additional parameters (from constr/methdo decl)
    */ - private String resolveTypeVariable(String typename, List additionalTypeParameters) { + private String resolveTypeVariable(String typename, + List additionalTypeParameters) { int dim = 0; - while(typename.endsWith("[]")) { + while (typename.endsWith("[]")) { typename = typename.substring(0, typename.length() - 2); dim++; } @@ -655,7 +638,7 @@ private String resolveTypeVariable(String typename, List getAllTypeParameters() { - if(typeParameters == null) { + if (typeParameters == null) { typeParameters = new ArrayList(0); typeParameters.addAll(classFile.getTypeParameters()); - if(isInnerClass() || isAnonymousClass()) { + if (isInnerClass() || isAnonymousClass()) { ClassFileDeclarationBuilder encl = manager.getBuilder(getEnclosingName()); typeParameters.addAll(encl.getAllTypeParameters()); } @@ -690,29 +672,27 @@ private List getAllTypeParameters() { /* - * Helper: create a type reference to an arbitrary type. - * $ are introduced instead of . if identifier are numbers or - * start with digits. - * This is not used at the moment - but might be interesting if - * anonymous classes are mapped, too. + * Helper: create a type reference to an arbitrary type. $ are introduced instead of . if + * identifier are numbers or start with digits. This is not used at the moment - but might be + * interesting if anonymous classes are mapped, too. */ private TypeReference createTypeReference(String typename) { int dimension = 0; - while(typename.endsWith("[]")) { - dimension ++; - typename = typename.substring(0, typename.length()-2); + while (typename.endsWith("[]")) { + dimension++; + typename = typename.substring(0, typename.length() - 2); } // rare occasion where an anonymous class is used as a marker. // happens only in methods not present in source code. // bugfix: treatment to the situations: - // CN.1.1 --> CN$1$1 - // CN.1.D --> CD$1.D etc. + // CN.1.1 --> CN$1$1 + // CN.1.D --> CD$1.D etc. String[] parts = typename.split("(\\.|\\$)"); typename = parts[0]; for (int i = 1; i < parts.length; i++) { - if(startsWithADigit(parts[i])) { + if (startsWithADigit(parts[i])) { typename += "$" + parts[i]; } else { typename += "." + parts[i]; @@ -726,16 +706,17 @@ private TypeReference createTypeReference(String typename) { /* - * is this a reference to an anonymous class? - * The argument must contain "." not "$" + * is this a reference to an anonymous class? The argument must contain "." not "$" */ private static boolean isAnononymous(String tys) { - return startsWithADigit(tys.substring(tys.lastIndexOf('.')+1)); + return startsWithADigit(tys.substring(tys.lastIndexOf('.') + 1)); } /* * check if a string starts with a decimal digit. + * * @param string to check + * * @return true iff string denotes a decimal number */ private static boolean startsWithADigit(String string) { @@ -756,8 +737,7 @@ public String toString() { } /** - * compare to class file declaration builders. - * comparison is performed upon the full classnames + * compare to class file declaration builders. comparison is performed upon the full classnames */ @Override public int compareTo(ClassFileDeclarationBuilder o) { @@ -766,14 +746,14 @@ public int compareTo(ClassFileDeclarationBuilder o) { @Override public boolean equals(Object o) { - if(! (o instanceof ClassFileDeclarationBuilder)) { - return false; - } - return compareTo((ClassFileDeclarationBuilder) o) == 0; + if (!(o instanceof ClassFileDeclarationBuilder)) { + return false; + } + return compareTo((ClassFileDeclarationBuilder) o) == 0; } @Override public int hashCode() { - return getFullClassname().hashCode(); + return getFullClassname().hashCode(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationManager.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationManager.java index 31bfa69c644..45d451fe7fb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationManager.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassFileDeclarationManager.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.io.File; @@ -27,22 +30,21 @@ import de.uka.ilkd.key.util.KeYRecoderExcHandler; /** - * This class provides an infrastructure to read in multiple class files and to - * manufacture ClassDeclarations out of them. - * - * If inner classes are present, more than one class file may be put into a - * class declaration. This manager uses {@link ClassFileDeclarationBuilder} - * objects to actually create source objects from classes and keeps track of the - * changes. - * + * This class provides an infrastructure to read in multiple class files and to manufacture + * ClassDeclarations out of them. + * + * If inner classes are present, more than one class file may be put into a class declaration. This + * manager uses {@link ClassFileDeclarationBuilder} objects to actually create source objects from + * classes and keeps track of the changes. + * * It allows to retrieve a collection of compilation units in the end. - * - * Only toplevel classes and their embedded classes are created. Anonymous - * classes and classes which are declared within the code are NOT translated. - * + * + * Only toplevel classes and their embedded classes are created. Anonymous classes and classes which + * are declared within the code are NOT translated. + * * @see ClassFileDeclarationBuilder * @author MU - * + * */ public class ClassFileDeclarationManager { private static final Logger LOGGER = LoggerFactory.getLogger(ClassFileDeclarationManager.class); @@ -54,9 +56,10 @@ public class ClassFileDeclarationManager { private ProgramFactory programFactory; private Map classBuilders = new LinkedHashMap<>(); - + /** * create a new ClassFileDeclarationManager + * * @param programFactory Factory to be used for the creation of the type declarations. */ public ClassFileDeclarationManager(ProgramFactory programFactory) { @@ -66,14 +69,13 @@ public ClassFileDeclarationManager(ProgramFactory programFactory) { /** * retrieve all stores compilation units. - * - * This method makes sure that prior to returning all known inner classses - * are appended as members to the corresponding enclosing classes - * + * + * This method makes sure that prior to returning all known inner classses are appended as + * members to the corresponding enclosing classes + * * @return a collection of compilation units - * @throws ConvertException - * if an inner class cannot be connected to the enclosing - * class, e.g. if this is not present + * @throws ConvertException if an inner class cannot be connected to the enclosing class, e.g. + * if this is not present */ public Collection getCompilationUnits() throws ConvertException { processBuilders(); @@ -82,37 +84,34 @@ public Collection getCompilationUnits() throws Conver /* * iterate the inner classes and add them to the according enclosing classes., - * - * The list of inner classes is sorted lexicographically so that any inner - * classes has been added before their (even more) inner classes appear. + * + * The list of inner classes is sorted lexicographically so that any inner classes has been + * added before their (even more) inner classes appear. */ private void processBuilders() throws ConvertException { - + Collections.sort(builderList); for (ClassFileDeclarationBuilder builder : builderList) { try { - if(builder.isInnerClass()) { + if (builder.isInnerClass()) { builder.attachToEnclosingDeclaration(); - } else if(!builder.isAnonymousClass()){ - compUnits.add(builder.makeCompilationUnit()); + } else if (!builder.isAnonymousClass()) { + compUnits.add(builder.makeCompilationUnit()); } } catch (Exception ex) { - throw new ConvertException("Error while processing: " + - builder.getFullClassname(), ex); + throw new ConvertException("Error while processing: " + builder.getFullClassname(), + ex); } } builderList.clear(); } /** - * add a class file which is to be transformed into a stub. Create a - * compilation unit if the class file is no inner class. Otherwise remember - * the builder to resolve it later. - * - * @param cf - * Classfile to add - * @param dataLocation - * location to be stored in the created stub. + * add a class file which is to be transformed into a stub. Create a compilation unit if the + * class file is no inner class. Otherwise remember the builder to resolve it later. + * + * @param cf Classfile to add + * @param dataLocation location to be stored in the created stub. */ public void addClassFile(ClassFile cf, DataLocation dataLocation) { ClassFileDeclarationBuilder builder = new ClassFileDeclarationBuilder(this, cf); @@ -120,9 +119,10 @@ public void addClassFile(ClassFile cf, DataLocation dataLocation) { classBuilders.put(builder.getFullClassname(), builder); builderList.add(builder); } - + /** * get the program factory associated with this manager + * * @return the program factory, not null */ public ProgramFactory getProgramFactory() { @@ -132,9 +132,8 @@ public ProgramFactory getProgramFactory() { /** * retrieve a specific builder from the database of builders. - * - * @param className - * class to get a builder for. + * + * @param className class to get a builder for. * @return a builder for the given className or null if no builder is stored */ public ClassFileDeclarationBuilder getBuilder(String className) { @@ -144,46 +143,46 @@ public ClassFileDeclarationBuilder getBuilder(String className) { /** * Test the class creation mechanism. - * - * Arguments: - * 1. Directory that contains .class files - * 2. Directory to write resulting .java files to - * - * The test procedure is to run this program on the JDK java.* packages - * There should be no error. - * + * + * Arguments: 1. Directory that contains .class files 2. Directory to write resulting .java + * files to + * + * The test procedure is to run this program on the JDK java.* packages There should be no + * error. + * * @throws Exception all kinds of exceptions */ public static void main(String[] args) throws Exception { - - ClassFileDeclarationManager manager = new ClassFileDeclarationManager(JavaProgramFactory.getInstance()); + + ClassFileDeclarationManager manager = + new ClassFileDeclarationManager(JavaProgramFactory.getInstance()); ByteCodeParser parser = new ByteCodeParser(); - + FileCollection fileColl = new DirectoryFileCollection(new File(args[0])); Walker walker = fileColl.createWalker(".class"); - - while(walker.step()) { + + while (walker.step()) { try { DataLocation currentDataLocation = walker.getCurrentDataLocation(); LOGGER.info("Now reading: {}", currentDataLocation); InputStream is = walker.openCurrent(); ClassFile cf; - try { + try { cf = parser.parseClassFile(is); } finally { is.close(); } manager.addClassFile(cf, currentDataLocation); - } catch(Exception ex) { + } catch (Exception ex) { throw new Exception("Error while loading: " + walker.getCurrentDataLocation(), ex); } } - - ServiceConfiguration sc = new KeYCrossReferenceServiceConfiguration( - new KeYRecoderExcHandler()); - KeYCrossReferenceSourceInfo sourceInfo = (KeYCrossReferenceSourceInfo)sc.getSourceInfo(); + + ServiceConfiguration sc = + new KeYCrossReferenceServiceConfiguration(new KeYRecoderExcHandler()); + KeYCrossReferenceSourceInfo sourceInfo = (KeYCrossReferenceSourceInfo) sc.getSourceInfo(); sourceInfo.setIgnoreUnresolvedClasses(true); - + for (CompilationUnit cu : manager.getCompilationUnits()) { sc.getChangeHistory().attached(cu); } @@ -193,14 +192,14 @@ public static void main(String[] args) throws Exception { sc.getChangeHistory().updateModel(); for (CompilationUnit cu : manager.getCompilationUnits()) { String name = cu.getPrimaryTypeDeclaration().getFullName(); - LOGGER.info("Generating {}",name); + LOGGER.info("Generating {}", name); FileWriter fw = new FileWriter(new File(args[1], name + ".jstub")); fw.write(cu.toSource()); fw.close(); } for (CompilationUnit cu : sourceInfo.getCreatedStubClasses()) { String name = cu.getPrimaryTypeDeclaration().getFullName(); - LOGGER.info("Generating empty stub {}", name); + LOGGER.info("Generating empty stub {}", name); FileWriter fw = new FileWriter(new File(args[1], name + ".jstub")); fw.write(cu.toSource()); fw.close(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassInitializeMethodBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassInitializeMethodBuilder.java index 83f4151a1be..c6d5b647e0a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassInitializeMethodBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassInitializeMethodBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.util.Debug; @@ -21,17 +24,13 @@ import java.util.Map; /** - * 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. + * 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 RecoderModelTransformer { +public class ClassInitializeMethodBuilder extends RecoderModelTransformer { - public static final String - CLASS_INITIALIZE_IDENTIFIER = ""; + public static final String CLASS_INITIALIZE_IDENTIFIER = ""; /** * maps a class to its static NON CONSTANT fields @@ -47,34 +46,31 @@ public class ClassInitializeMethodBuilder /** - * 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. + * 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 - * @param cache 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. + * @param services the CrossReferenceServiceConfiguration with the information about the recoder + * model + * @param cache 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. */ - public ClassInitializeMethodBuilder(CrossReferenceServiceConfiguration services, TransformerCache cache) { + public ClassInitializeMethodBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); class2initializers = new LinkedHashMap<>(10 * getUnits().size()); class2super = new LinkedHashMap<>(2 * getUnits().size()); } /** - * 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. + * 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(FieldSpecification spec) { boolean result = spec.isStatic() && spec.isFinal(); @@ -96,29 +92,25 @@ private boolean isConstantField(FieldSpecification spec) { * creates the package reference java.lang */ private PackageReference createJavaLangPackageReference() { - return new PackageReference - (new PackageReference(new Identifier("java")), - new Identifier("lang")); + return new PackageReference(new PackageReference(new Identifier("java")), + new Identifier("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. + * 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 ASTList - fieldInitializersToAssignments(FieldDeclaration fd) { + private ASTList fieldInitializersToAssignments(FieldDeclaration fd) { ASTList specs = fd.getFieldSpecifications(); - ASTList result = - new ASTArrayList<>(specs.size()); + ASTList result = new ASTArrayList<>(specs.size()); for (FieldSpecification fs : specs) { if (fs.isStatic() && fs.getInitializer() != null && !isConstantField(fs)) { - result.add( - assign(passiveFieldReference( - fs.getIdentifier().deepClone()), fs.getInitializer().deepClone())); + result.add(assign(passiveFieldReference(fs.getIdentifier().deepClone()), + fs.getInitializer().deepClone())); } } @@ -128,8 +120,8 @@ private PackageReference createJavaLangPackageReference() { /** - * retrieves all static non-constant fields and returns a list of - * copy assignment pre-initialising them with their default values + * 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 * @@ -138,16 +130,15 @@ private PackageReference createJavaLangPackageReference() { */ private ASTList getInitializers(TypeDeclaration typeDeclaration) { - ASTList result = new ASTArrayList<> - (typeDeclaration.getChildCount()); + ASTList result = new ASTArrayList<>(typeDeclaration.getChildCount()); for (int i = 0; i < typeDeclaration.getChildCount(); i++) { if (typeDeclaration.getChildAt(i) instanceof ClassInitializer) { - result.add(((ClassInitializer) typeDeclaration. - getChildAt(i)).getBody().deepClone()); + result.add( + ((ClassInitializer) typeDeclaration.getChildAt(i)).getBody().deepClone()); } else if (typeDeclaration.getChildAt(i) instanceof FieldDeclaration) { - result.addAll(fieldInitializersToAssignments - ((FieldDeclaration) typeDeclaration.getChildAt(i))); + result.addAll(fieldInitializersToAssignments( + (FieldDeclaration) typeDeclaration.getChildAt(i))); } } return result; @@ -166,9 +157,8 @@ public ProblemReport analyze() { if (cd.getExtendedTypes() != null) { superType = cd.getExtendedTypes().getTypeReferenceAt(0).deepClone(); } else { - superType = - new TypeReference(createJavaLangPackageReference(), - new Identifier("Object")); + superType = new TypeReference(createJavaLangPackageReference(), + new Identifier("Object")); } class2super.put(cd, superType); } @@ -208,8 +198,7 @@ protected CopyAssignment assign(Expression left, Expression right) { /** - * creates the following catch clause - * + * creates the following catch clause * catch (caughtType caughtParam) { * <classInitializationInProgress>=false; * <classClassErroneous>=true; @@ -217,28 +206,23 @@ protected CopyAssignment assign(Expression left, Expression right) { * } * */ - private Catch createCatchClause - (String caughtType, String caughtParam, Throw t) { + private Catch createCatchClause(String caughtType, String caughtParam, Throw t) { ASTList catcher = new ASTArrayList<>(3); - CopyAssignment resetInitInProgress = - assign(passiveFieldReference - (new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS)), - new BooleanLiteral(false)); + CopyAssignment resetInitInProgress = assign( + passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS)), + new BooleanLiteral(false)); - CopyAssignment markErroneous = - assign(passiveFieldReference - (new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_ERRONEOUS)), - new BooleanLiteral(true)); + CopyAssignment markErroneous = assign( + passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_ERRONEOUS)), + new BooleanLiteral(true)); - ParameterDeclaration param = - new ParameterDeclaration - (new TypeReference(createJavaLangPackageReference(), - new Identifier(caughtType)), - new Identifier(caughtParam)); + ParameterDeclaration param = new ParameterDeclaration( + new TypeReference(createJavaLangPackageReference(), new Identifier(caughtType)), + new Identifier(caughtParam)); catcher.add(resetInitInProgress.deepClone()); @@ -251,9 +235,8 @@ protected CopyAssignment assign(Expression left, Expression right) { /** - * around the initializers there is a try block that catches - * eventually thrown errors or exceptions and handles them in a - * special way + * around the initializers there is a try block that catches eventually thrown errors or + * exceptions and handles them in a special way */ private Try createInitializerExecutionTryBlock(TypeDeclaration td) { @@ -267,12 +250,10 @@ private Try createInitializerExecutionTryBlock(TypeDeclaration td) { if (td instanceof ClassDeclaration && td != javaLangObject) { ClassDeclaration cd = (ClassDeclaration) td; - initializerExecutionBody.add - (0, new PassiveExpression - (new MethodReference - (class2super.get(cd).deepClone(), - new ImplicitIdentifier - (ClassInitializeMethodBuilder.CLASS_INITIALIZE_IDENTIFIER)))); + initializerExecutionBody.add(0, + new PassiveExpression(new MethodReference(class2super.get(cd).deepClone(), + new ImplicitIdentifier( + ClassInitializeMethodBuilder.CLASS_INITIALIZE_IDENTIFIER)))); } // catch clauses @@ -280,27 +261,20 @@ private Try createInitializerExecutionTryBlock(TypeDeclaration td) { ASTList catchClauses = new ASTArrayList<>(2); - catchClauses.add - (createCatchClause - ("Error", "err", - new Throw(new VariableReference(new Identifier("err"))))); + catchClauses.add(createCatchClause("Error", "err", + new Throw(new VariableReference(new Identifier("err"))))); - ASTList exceptionInInitializerArguments = - new ASTArrayList<>(1); - exceptionInInitializerArguments.add - (new VariableReference(new Identifier("twa"))); + ASTList exceptionInInitializerArguments = new ASTArrayList<>(1); + exceptionInInitializerArguments.add(new VariableReference(new Identifier("twa"))); - Throw t = new Throw - (new New(null, - new TypeReference - (createJavaLangPackageReference(), - new Identifier("ExceptionInInitializerError")), - exceptionInInitializerArguments)); + Throw t = new Throw(new New(null, + new TypeReference(createJavaLangPackageReference(), + new Identifier("ExceptionInInitializerError")), + exceptionInInitializerArguments)); catchClauses.add(createCatchClause("Throwable", "twa", t)); - return new Try(new StatementBlock(initializerExecutionBody), - catchClauses); + return new Try(new StatementBlock(initializerExecutionBody), catchClauses); } @@ -314,81 +288,64 @@ private StatementBlock createInitializeMethodBody(TypeDeclaration td) { ASTList clInitNotInProgressBody = new ASTArrayList<>(20); ASTList clNotPreparedBody = new ASTArrayList<>(1); - clNotPreparedBody.add - (new PassiveExpression - (new MethodReference - (new ImplicitIdentifier - (ClassPreparationMethodBuilder.CLASS_PREPARE_IDENTIFIER)))); + clNotPreparedBody.add(new PassiveExpression(new MethodReference( + new ImplicitIdentifier(ClassPreparationMethodBuilder.CLASS_PREPARE_IDENTIFIER)))); - If isClassPrepared = new If - (new LogicalNot(passiveFieldReference - (new ImplicitIdentifier(ImplicitFieldAdder. - IMPLICIT_CLASS_PREPARED))), - new Then(new StatementBlock(clNotPreparedBody))); + If isClassPrepared = new If( + new LogicalNot(passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_PREPARED))), + new Then(new StatementBlock(clNotPreparedBody))); clInitNotInProgressBody.add(isClassPrepared); ASTList clErroneousBody = new ASTArrayList<>(1); - clErroneousBody.add - (new Throw(new New(null, - new TypeReference - (createJavaLangPackageReference(), - new Identifier("NoClassDefFoundError")), - null))); - If isClassErroneous = new If - (passiveFieldReference - (new ImplicitIdentifier(ImplicitFieldAdder. - IMPLICIT_CLASS_ERRONEOUS)), - new Then(new StatementBlock(clErroneousBody))); + clErroneousBody + .add(new Throw(new New(null, new TypeReference(createJavaLangPackageReference(), + new Identifier("NoClassDefFoundError")), null))); + If isClassErroneous = new If( + passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_ERRONEOUS)), + new Then(new StatementBlock(clErroneousBody))); clInitNotInProgressBody.add(isClassErroneous); // @(CLASS_INIT_IN_PROGRESS) = true - clInitNotInProgressBody.add - (assign(passiveFieldReference - (new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS)), - new BooleanLiteral(true))); + clInitNotInProgressBody.add(assign( + passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS)), + new BooleanLiteral(true))); // create try block in initialize method clInitNotInProgressBody.add(createInitializerExecutionTryBlock(td)); - clInitNotInProgressBody.add - (assign - (passiveFieldReference((new ImplicitIdentifier - (ImplicitFieldAdder. - IMPLICIT_CLASS_INIT_IN_PROGRESS))), - new BooleanLiteral(false))); - clInitNotInProgressBody.add - (assign - (passiveFieldReference((new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_ERRONEOUS))), - new BooleanLiteral(false))); - clInitNotInProgressBody.add - (assign - (passiveFieldReference((new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_INITIALIZED))), - new BooleanLiteral(true))); - - - If isClassInitializationInProgress = new If - (new LogicalNot - (passiveFieldReference - (new ImplicitIdentifier(ImplicitFieldAdder. - IMPLICIT_CLASS_INIT_IN_PROGRESS))), - new Then(new StatementBlock(clInitNotInProgressBody))); + clInitNotInProgressBody.add(assign(passiveFieldReference( + (new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS))), + new BooleanLiteral(false))); + clInitNotInProgressBody.add(assign( + passiveFieldReference( + (new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_ERRONEOUS))), + new BooleanLiteral(false))); + clInitNotInProgressBody.add(assign( + passiveFieldReference( + (new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_INITIALIZED))), + new BooleanLiteral(true))); + + + If isClassInitializationInProgress = new If( + new LogicalNot(passiveFieldReference(new ImplicitIdentifier( + ImplicitFieldAdder.IMPLICIT_CLASS_INIT_IN_PROGRESS))), + new Then(new StatementBlock(clInitNotInProgressBody))); clInitializeBody.add(isClassInitializationInProgress); - If isClassInitialized = new If - (new LogicalNot(passiveFieldReference - (new ImplicitIdentifier(ImplicitFieldAdder. - IMPLICIT_CLASS_INITIALIZED))), - new Then(new StatementBlock(clInitializeBody))); + If isClassInitialized = new If( + new LogicalNot(passiveFieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_INITIALIZED))), + new Then(new StatementBlock(clInitializeBody))); methodBody.add(isClassInitialized); @@ -397,23 +354,19 @@ private StatementBlock createInitializeMethodBody(TypeDeclaration td) { /** - * creates the static method <clprepare> for the - * given type declaration + * creates the static method <clprepare> for the given type declaration * - * @param td the TypeDeclaration to which the new created method - * will be attached + * @param td the TypeDeclaration to which the new created method will be attached * @return the created class preparation method */ private MethodDeclaration createInitializeMethod(TypeDeclaration td) { ASTList modifiers = new ASTArrayList<>(2); modifiers.add(new Static()); modifiers.add(new Public()); - return new MethodDeclaration(modifiers, - null, // return type is void - new ImplicitIdentifier - (CLASS_INITIALIZE_IDENTIFIER), - new ASTArrayList<>(0), - null, // no declared throws + return new MethodDeclaration(modifiers, null, // return type is void + new ImplicitIdentifier(CLASS_INITIALIZE_IDENTIFIER), new ASTArrayList<>(0), null, // no + // declared + // throws createInitializeMethodBody(td)); } @@ -428,4 +381,4 @@ protected void makeExplicit(TypeDeclaration td) { } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassPreparationMethodBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassPreparationMethodBuilder.java index a0b3354a18c..634fe508040 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassPreparationMethodBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ClassPreparationMethodBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import org.slf4j.Logger; @@ -22,17 +25,15 @@ import java.util.Map; /** - * 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. + * 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 RecoderModelTransformer { - private static final Logger LOGGER = LoggerFactory.getLogger(ClassPreparationMethodBuilder.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ClassPreparationMethodBuilder.class); - public static final String - CLASS_PREPARE_IDENTIFIER = ""; + public static final String CLASS_PREPARE_IDENTIFIER = ""; /** * maps a class to its static NON CONSTANT fields @@ -40,35 +41,30 @@ public class ClassPreparationMethodBuilder extends RecoderModelTransformer { private final Map> 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. + * 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 - * @param cache 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. + * @param services the CrossReferenceServiceConfiguration with the information about the recoder + * model + * @param cache 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. */ - public ClassPreparationMethodBuilder - (CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public ClassPreparationMethodBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); class2staticFields = new LinkedHashMap<>(10 * getUnits().size()); } /** - * 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. + * 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(FieldSpecification spec) { boolean result = spec.isStatic() && spec.isFinal(); @@ -88,8 +84,8 @@ private boolean isConstantField(FieldSpecification spec) { /** - * retrieves all static non-constant fields and returns a list of - * copy assignment pre-initialising them with their default values + * 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 * @@ -105,19 +101,16 @@ private ASTList prepareFields(TypeDeclaration typeDeclaration) { for (FieldSpecification spec : fields) { if (spec.isStatic() && !isConstantField(spec)) { Identifier ident = spec.getIdentifier(); - result.add(new CopyAssignment - (new PassiveExpression - (new FieldReference(ident.deepClone())), - getDefaultValue(spec.getType()))); + result.add(new CopyAssignment( + new PassiveExpression(new FieldReference(ident.deepClone())), + getDefaultValue(spec.getType()))); } } - result.add - (new CopyAssignment - (new PassiveExpression(new FieldReference - (new ImplicitIdentifier - (ImplicitFieldAdder.IMPLICIT_CLASS_PREPARED))), - new BooleanLiteral(true))); + result.add(new CopyAssignment( + new PassiveExpression(new FieldReference( + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_CLASS_PREPARED))), + new BooleanLiteral(true))); return result; } @@ -130,9 +123,8 @@ public ProblemReport analyze() { if (cu.getTypeDeclarationAt(i) instanceof ClassDeclaration) { ClassDeclaration cd = (ClassDeclaration) cu.getTypeDeclarationAt(i); if (cd.getTypeDeclarationCount() > 0) { - LOGGER.debug - ("clPrepBuilder: Inner Class detected. " + - "Reject building class initialisation methods."); + LOGGER.debug("clPrepBuilder: Inner Class detected. " + + "Reject building class initialisation methods."); } // collect initializers for transformation phase @@ -145,22 +137,18 @@ public ProblemReport analyze() { } /** - * creates the static method <clprepare> for the - * given type declaration + * creates the static method <clprepare> for the given type declaration * - * @param td the TypeDeclaration to which the new created method - * will be attached + * @param td the TypeDeclaration to which the new created method will be attached * @return the created class preparation method */ private MethodDeclaration createPrepareMethod(TypeDeclaration td) { ASTList modifiers = new ASTArrayList<>(2); modifiers.add(new Static()); modifiers.add(new Private()); - return new MethodDeclaration(modifiers, - null, // return type is void - new ImplicitIdentifier(CLASS_PREPARE_IDENTIFIER), - new ASTArrayList<>(0), - null, // no throws + return new MethodDeclaration(modifiers, null, // return type is void + new ImplicitIdentifier(CLASS_PREPARE_IDENTIFIER), new ASTArrayList<>(0), null, // no + // throws new StatementBlock(class2staticFields.get(td))); } @@ -173,4 +161,4 @@ private MethodDeclaration createPrepareMethod(TypeDeclaration td) { protected void makeExplicit(TypeDeclaration td) { attach(createPrepareMethod(td), td, 0); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstantStringExpressionEvaluator.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstantStringExpressionEvaluator.java index 39a71e2a6c3..502c85b7141 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstantStringExpressionEvaluator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstantStringExpressionEvaluator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.CrossReferenceServiceConfiguration; @@ -12,46 +15,45 @@ public class ConstantStringExpressionEvaluator extends RecoderModelTransformer { - public ConstantStringExpressionEvaluator( - CrossReferenceServiceConfiguration services, TransformerCache cache) { - super(services, cache); + public ConstantStringExpressionEvaluator(CrossReferenceServiceConfiguration services, + TransformerCache cache) { + super(services, cache); } private void evaluateConstantStringExpressions(NonTerminalProgramElement td) { - for (int i = 0; i < td.getChildCount(); i++) { - ProgramElement pe = td.getChildAt(i); - - if (pe instanceof Expression) { - ConstantEvaluator cee = services.getConstantEvaluator(); - - ConstantEvaluator.EvaluationResult res = new ConstantEvaluator.EvaluationResult(); - - Type expType = services.getSourceInfo().getType((Expression) pe); - - if (!(pe instanceof NullLiteral) && expType != null - && expType.getFullName().equals("java.lang.String")) { - boolean isCTC = false; - try { - isCTC = cee.isCompileTimeConstant((Expression) pe, res); - } catch (java.lang.ArithmeticException t) { - // - } - if (isCTC && res.getTypeCode() == ConstantEvaluator.STRING_TYPE) { - replace(pe, new StringLiteral("\"" + res.getString() - + "\"")); - continue; - } - } - } - - if (pe instanceof NonTerminalProgramElement) { - evaluateConstantStringExpressions((NonTerminalProgramElement) pe); - } - } + for (int i = 0; i < td.getChildCount(); i++) { + ProgramElement pe = td.getChildAt(i); + + if (pe instanceof Expression) { + ConstantEvaluator cee = services.getConstantEvaluator(); + + ConstantEvaluator.EvaluationResult res = new ConstantEvaluator.EvaluationResult(); + + Type expType = services.getSourceInfo().getType((Expression) pe); + + if (!(pe instanceof NullLiteral) && expType != null + && expType.getFullName().equals("java.lang.String")) { + boolean isCTC = false; + try { + isCTC = cee.isCompileTimeConstant((Expression) pe, res); + } catch (java.lang.ArithmeticException t) { + // + } + if (isCTC && res.getTypeCode() == ConstantEvaluator.STRING_TYPE) { + replace(pe, new StringLiteral("\"" + res.getString() + "\"")); + continue; + } + } + } + + if (pe instanceof NonTerminalProgramElement) { + evaluateConstantStringExpressions((NonTerminalProgramElement) pe); + } + } } @Override protected void makeExplicit(TypeDeclaration td) { - evaluateConstantStringExpressions(td); + evaluateConstantStringExpressions(td); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstructorNormalformBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstructorNormalformBuilder.java index a3f74c0aae4..674d0f5abd0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstructorNormalformBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ConstructorNormalformBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.util.Debug; @@ -17,19 +20,15 @@ import java.util.*; /** - * 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. + * 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 RecoderModelTransformer { +public class ConstructorNormalformBuilder extends RecoderModelTransformer { - public static final String - CONSTRUCTOR_NORMALFORM_IDENTIFIER = ""; + public static final String CONSTRUCTOR_NORMALFORM_IDENTIFIER = ""; - public static final String - OBJECT_INITIALIZER_IDENTIFIER = ""; + public static final String OBJECT_INITIALIZER_IDENTIFIER = ""; private final Map> class2constructors; private final Map class2enclosingThis; @@ -45,9 +44,8 @@ public class ConstructorNormalformBuilder /** * creates the constructor normalform builder */ - public ConstructorNormalformBuilder - (CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public ConstructorNormalformBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); List units = getUnits(); class2constructors = new LinkedHashMap<>(4 * units.size()); @@ -62,10 +60,9 @@ public class ConstructorNormalformBuilder /** - * 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 + * 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 @@ -79,63 +76,50 @@ public class ConstructorNormalformBuilder *

    * public C () {} ... * } - * the following list of size two is returned - * + * the following list of size two is returned * [ i = 0;, <objectInitializer>0(); ] - * - * where + * where * private <objectInitializer>0() { * int j = 3; * i = j + 5; * } * * - * @param cd the ClassDeclaration of which the initilizers have to - * be collected - * @return the list of copy assignments and method references - * realising the initializers. + * @param cd the ClassDeclaration of which the initilizers have to be collected + * @return the list of copy assignments and method references realising the initializers. */ private ASTList collectInitializers(ClassDeclaration cd) { ASTList result = new ASTArrayList<>(20); ASTList mdl = new ASTArrayList<>(5); int childCount = cd.getChildCount(); for (int i = 0; i < childCount; i++) { - if (cd.getChildAt(i) instanceof ClassInitializer && - !((ClassInitializer) cd.getChildAt(i)).isStatic()) { + if (cd.getChildAt(i) instanceof ClassInitializer + && !((ClassInitializer) cd.getChildAt(i)).isStatic()) { ASTList mods = new ASTArrayList<>(1); mods.add(new Private()); String name = OBJECT_INITIALIZER_IDENTIFIER + mdl.size(); - MethodDeclaration initializerMethod = - new MethodDeclaration - (mods, - null, //return type is void - new ImplicitIdentifier(name), - new ASTArrayList<>(0), - null, - ((ClassInitializer) cd.getChildAt(i)).getBody().deepClone()); + MethodDeclaration initializerMethod = new MethodDeclaration(mods, null, // return + // type is + // void + new ImplicitIdentifier(name), new ASTArrayList<>(0), null, + ((ClassInitializer) cd.getChildAt(i)).getBody().deepClone()); initializerMethod.makeAllParentRolesValid(); mdl.add(initializerMethod); - result.add(new MethodReference - (null, - new ImplicitIdentifier(name))); - } else if (cd.getChildAt(i) instanceof FieldDeclaration && - !((FieldDeclaration) cd.getChildAt(i)).isStatic()) { + result.add(new MethodReference(null, new ImplicitIdentifier(name))); + } else if (cd.getChildAt(i) instanceof FieldDeclaration + && !((FieldDeclaration) cd.getChildAt(i)).isStatic()) { ASTList specs = ((FieldDeclaration) cd.getChildAt(i)).getFieldSpecifications(); - for (FieldSpecification spec : specs) { - Expression fieldInit; - if ((fieldInit = spec. - getInitializer()) != null) { - CopyAssignment fieldCopy = - new CopyAssignment - (new FieldReference - (new ThisReference(), - spec.getIdentifier()), - fieldInit.deepClone()); - result.add(fieldCopy); - } - } + for (FieldSpecification spec : specs) { + Expression fieldInit; + if ((fieldInit = spec.getInitializer()) != null) { + CopyAssignment fieldCopy = new CopyAssignment( + new FieldReference(new ThisReference(), spec.getIdentifier()), + fieldInit.deepClone()); + result.add(fieldCopy); + } + } } } class2methodDeclaration.put(cd, mdl); @@ -143,16 +127,14 @@ private ASTList collectInitializers(ClassDeclaration cd) { } /** - * Two-pass transformation have to be strictly divided up into two - * parts. the first part analyzes the model and collects all - * necessary information. In this case all class declarations are - * examined and initializers as well as constructors are collected. - * All actions, which may cause a recoder model update have to be - * done here. + * Two-pass transformation have to be strictly divided up into two parts. the first part + * analyzes the model and collects all necessary information. In this case all class + * declarations are examined and initializers as well as constructors are collected. All + * actions, which may cause a recoder model update have to be done here. * * @return status report if analyze encountered problems or not */ - @Override + @Override public ProblemReport analyze() { javaLangObject = services.getNameInfo().getJavaLangObject(); if (!(javaLangObject instanceof ClassDeclaration)) { @@ -165,8 +147,8 @@ public ProblemReport analyze() { // collect constructors for transformation phase List constructors = new ArrayList<>(10); constructors.addAll(services.getSourceInfo().getConstructors(cd)); - if (constructors.isEmpty() && (cd.getContainingClassType() != null && !cd.isStatic() || - cd.getName() == null || cd.getStatementContainer() != null)) { + if (constructors.isEmpty() && (cd.getContainingClassType() != null && !cd.isStatic() + || cd.getName() == null || cd.getStatementContainer() != null)) { constructors.add(new DefaultConstructor(cd)); } class2constructors.put(cd, constructors); @@ -175,7 +157,8 @@ public ProblemReport analyze() { class2enclosingThis.put(cd, getImplicitEnclosingThis(cd)); - if (cd.getAllSupertypes().size() > 1 && (cd.getStatementContainer() != null || cd.getName() == null)) { + if (cd.getAllSupertypes().size() > 1 + && (cd.getStatementContainer() != null || cd.getName() == null)) { class2superContainer.put(cd, cd.getAllSupertypes().get(1).getContainingClassType()); } @@ -186,9 +169,8 @@ public ProblemReport analyze() { } } - if (cd.getName() == null || - cd.getStatementContainer() != null || - cd.getContainingClassType() != null && !cd.isStatic()) { + if (cd.getName() == null || cd.getStatementContainer() != null + || cd.getContainingClassType() != null && !cd.isStatic()) { class2enclosingClass.put(cd, containingClass(cd)); } @@ -198,7 +180,7 @@ public ProblemReport analyze() { setProblemReport(NO_PROBLEM); return NO_PROBLEM; } - + protected Field getImplicitEnclosingThis(ClassDeclaration cd) { for (final Field f : cd.getAllFields()) { if (f.getName().equals(ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS)) { @@ -218,35 +200,28 @@ private void attachDefaultConstructor(ClassDeclaration cd) { recThrows = null; body = new StatementBlock(); body.setBody(new ASTArrayList<>()); - attach(new MethodReference - (new SuperReference(), new ImplicitIdentifier - (CONSTRUCTOR_NORMALFORM_IDENTIFIER)), body, 0); + attach(new MethodReference(new SuperReference(), + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER)), body, 0); final Iterator initializers = class2initializers.get(cd).iterator(); for (int i = 0; initializers.hasNext(); i++) { - attach(initializers.next().deepClone(), - body, i + 1); + attach(initializers.next().deepClone(), body, i + 1); } - MethodDeclaration def = new MethodDeclaration(mods, - null, // return type is void - new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), - parameters, - recThrows, + MethodDeclaration def = new MethodDeclaration(mods, null, // return type is void + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), parameters, recThrows, body); def.makeAllParentRolesValid(); attach(def, cd, 0); } /** - * 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. + * 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 ClassDeclaration where the cons is declared + * @param cd the ClassDeclaration where the cons is declared * @param cons the Constructor to be transformed * @return the constructor normalform */ - private MethodDeclaration normalform(ClassDeclaration cd, - Constructor cons) { + private MethodDeclaration normalform(ClassDeclaration cd, Constructor cons) { ASTList mods = new ASTArrayList<>(5); ASTList parameters; @@ -256,15 +231,16 @@ private MethodDeclaration normalform(ClassDeclaration cd, TypeDeclaration td = class2enclosingClass.get(cd); final List outerVars = getLocalClass2FinalVar().get(cd); int j = et == null ? 0 : 1; - if (outerVars != null) j += outerVars.size(); + if (outerVars != null) + j += outerVars.size(); ParameterDeclaration pd = null; CopyAssignment ca = null; String etId = "_ENCLOSING_THIS"; if (et != null) { - pd = new ParameterDeclaration( - new TypeReference(td.getIdentifier().deepClone()), + pd = new ParameterDeclaration(new TypeReference(td.getIdentifier().deepClone()), new Identifier(etId)); - ca = new CopyAssignment(new FieldReference(new ThisReference(), new ImplicitIdentifier(et.getName())), + ca = new CopyAssignment( + new FieldReference(new ThisReference(), new ImplicitIdentifier(et.getName())), new VariableReference(new Identifier(etId))); } @@ -276,7 +252,7 @@ private MethodDeclaration normalform(ClassDeclaration cd, } else { ConstructorDeclaration consDecl = (ConstructorDeclaration) cons; mods = (consDecl.getDeclarationSpecifiers() == null ? null - : consDecl.getDeclarationSpecifiers().deepClone()); + : consDecl.getDeclarationSpecifiers().deepClone()); parameters = consDecl.getParameters().deepClone(); recThrows = consDecl.getThrown() == null ? null : consDecl.getThrown().deepClone(); @@ -308,39 +284,37 @@ private MethodDeclaration normalform(ClassDeclaration cd, if (cd != javaLangObject && body != null) { // remember original first statement - Statement first = body.getStatementCount() > 0 ? - body.getStatementAt(0) : null; + Statement first = body.getStatementCount() > 0 ? body.getStatementAt(0) : null; // first statement has to be a this or super constructor call if (!(first instanceof SpecialConstructorReference)) { if (body.getBody() == null) { body.setBody(new ASTArrayList<>()); } - attach(new MethodReference - (new SuperReference(), new ImplicitIdentifier - (CONSTRUCTOR_NORMALFORM_IDENTIFIER)), body, 0); + attach(new MethodReference(new SuperReference(), + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER)), body, 0); } else { body.getBody().remove(0); if (first instanceof ThisConstructorReference) { - attach(new MethodReference - (new ThisReference(), new ImplicitIdentifier - (CONSTRUCTOR_NORMALFORM_IDENTIFIER), - ((SpecialConstructorReference) first).getArguments()), body, 0); + attach(new MethodReference(new ThisReference(), + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), + ((SpecialConstructorReference) first).getArguments()), body, 0); } else { - ReferencePrefix referencePrefix = ((SuperConstructorReference) first).getReferencePrefix(); + ReferencePrefix referencePrefix = + ((SuperConstructorReference) first).getReferencePrefix(); ASTList args = ((SpecialConstructorReference) first).getArguments(); if (referencePrefix instanceof Expression) { - if (args == null) args = new ASTArrayList<>(1); + if (args == null) + args = new ASTArrayList<>(1); args.add((Expression) referencePrefix); } else if (class2superContainer.get(cd) != null) { - if (args == null) args = new ASTArrayList<>(1); + if (args == null) + args = new ASTArrayList<>(1); args.add(new VariableReference(new Identifier(etId))); } - attach(new MethodReference - (new SuperReference(), new ImplicitIdentifier - (CONSTRUCTOR_NORMALFORM_IDENTIFIER), - args), - body, 0); + attach(new MethodReference(new SuperReference(), + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), args), body, + 0); } } // if the first statement is not a this constructor reference @@ -352,11 +326,12 @@ private MethodDeclaration normalform(ClassDeclaration cd, attach(ca, body, 0); } for (int i = 0; outerVars != null && i < outerVars.size(); i++) { - attach(new CopyAssignment(new FieldReference(new ThisReference(), - new ImplicitIdentifier(ImplicitFieldAdder.FINAL_VAR_PREFIX + - (outerVars.get(i)).getName())), - new VariableReference(new Identifier(outerVars.get(i).getName()))), body, - i + (ca != null ? 1 : 0)); + attach(new CopyAssignment( + new FieldReference(new ThisReference(), + new ImplicitIdentifier(ImplicitFieldAdder.FINAL_VAR_PREFIX + + (outerVars.get(i)).getName())), + new VariableReference(new Identifier(outerVars.get(i).getName()))), + body, i + (ca != null ? 1 : 0)); } for (int i = 0; i < initializers.size(); i++) { attach(initializers.get(i).deepClone(), body, i + 1 + j); @@ -366,13 +341,9 @@ private MethodDeclaration normalform(ClassDeclaration cd, } - MethodDeclaration nf = new MethodDeclaration - (mods, - null, // return type is void - new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), - parameters, - recThrows, - body); + MethodDeclaration nf = new MethodDeclaration(mods, null, // return type is void + new ImplicitIdentifier(CONSTRUCTOR_NORMALFORM_IDENTIFIER), parameters, recThrows, + body); nf.makeAllParentRolesValid(); return nf; } @@ -380,13 +351,15 @@ private MethodDeclaration normalform(ClassDeclaration cd, private ConstructorDeclaration attachConstructorDecl(TypeDeclaration td) { if (td.getASTParent() instanceof New) { New n = (New) td.getASTParent(); - if (n.getArguments() == null || n.getArguments().isEmpty()) return null; - ConstructorDeclaration constr = services.getCrossReferenceSourceInfo().getConstructorDeclaration( - services.getCrossReferenceSourceInfo().getConstructor(n)); + if (n.getArguments() == null || n.getArguments().isEmpty()) + return null; + ConstructorDeclaration constr = + services.getCrossReferenceSourceInfo().getConstructorDeclaration( + services.getCrossReferenceSourceInfo().getConstructor(n)); constr = constr.deepClone(); SuperConstructorReference sr = new SuperConstructorReference( - n.getArguments() != null ? n.getArguments().deepClone() : - new ASTArrayList<>(0)); + n.getArguments() != null ? n.getArguments().deepClone() + : new ASTArrayList<>(0)); constr.setBody(new StatementBlock(new ASTArrayList<>(sr))); constr.makeAllParentRolesValid(); attach(constr, td, 0); @@ -407,17 +380,16 @@ protected void makeExplicit(TypeDeclaration td) { if (td.getName() == null) { anonConstr = attachConstructorDecl(td); } - if (anonConstr != null) constructors.add(anonConstr); - for (Constructor constructor : constructors) { - attach(normalform - ((ClassDeclaration) td, - constructor), td, 0); - } + if (anonConstr != null) + constructors.add(anonConstr); + for (Constructor constructor : constructors) { + attach(normalform((ClassDeclaration) td, constructor), td, 0); + } ASTList mdl = class2methodDeclaration.get(td); - for (MethodDeclaration methodDeclaration : mdl) { - attach(methodDeclaration, td, 0); - } + for (MethodDeclaration methodDeclaration : mdl) { + attach(methodDeclaration, td, 0); + } } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ContextStatementBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ContextStatementBlock.java index 048ca320b32..091471d20c4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ContextStatementBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ContextStatementBlock.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is taken from the RECODER library, which is protected by the LGPL, // and modified. @@ -6,61 +9,62 @@ import recoder.java.StatementBlock; /** - Statement block. - @author AL - @author AutoDoc + * Statement block. + * + * @author AL + * @author AutoDoc */ -public class ContextStatementBlock - extends StatementBlock implements KeYRecoderExtension{ +public class ContextStatementBlock extends StatementBlock implements KeYRecoderExtension { /** - * + * */ private static final long serialVersionUID = -7812560435975572578L; private ExecutionContext ec; - + /** - Statement block. + * Statement block. */ - public ContextStatementBlock() { - } + public ContextStatementBlock() {} /** - Statement block. + * Statement block. */ - public ContextStatementBlock(TypeSVWrapper tr, MethodSignatureSVWrapper pm, ExpressionSVWrapper runtime) { - this(tr != null ? new ExecutionContext(tr, pm, runtime) : null); + public ContextStatementBlock(TypeSVWrapper tr, MethodSignatureSVWrapper pm, + ExpressionSVWrapper runtime) { + this(tr != null ? new ExecutionContext(tr, pm, runtime) : null); } /** - Statement block. + * Statement block. */ public ContextStatementBlock(ExecutionContext ec) { - this.ec = ec; + this.ec = ec; } /** - Statement block. - @param proto a statement block. + * Statement block. + * + * @param proto a statement block. */ protected ContextStatementBlock(ContextStatementBlock proto) { super(proto); - this.ec = proto.getExecutionContext(); + this.ec = proto.getExecutionContext(); } public TypeSVWrapper getClassContext() { - return (TypeSVWrapper)ec.getTypeReference(); + return (TypeSVWrapper) ec.getTypeReference(); } public ExpressionSVWrapper getRuntimeInstance() { - return (ExpressionSVWrapper)ec.getRuntimeInstance(); + return (ExpressionSVWrapper) ec.getRuntimeInstance(); } public ExecutionContext getExecutionContext() { - return ec; + return ec; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateBuilder.java index 7a19e96d544..6fed7f14018 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.CrossReferenceServiceConfiguration; @@ -14,33 +17,29 @@ import recoder.list.generic.ASTList; /** - * 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. + * 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 RecoderModelTransformer { public static final String IMPLICIT_CREATE = ""; - public CreateBuilder( - CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public CreateBuilder(CrossReferenceServiceConfiguration services, TransformerCache cache) { super(services, cache); } /** - * Creates the body of the static <createObject> - * method. + * Creates the body of the static <createObject> method. */ private StatementBlock createBody() { ASTList result = new ASTArrayList<>(10); result.add(assign( - attribute(new ThisReference(), new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_INITIALIZED)), + attribute(new ThisReference(), + new ImplicitIdentifier(ImplicitFieldAdder.IMPLICIT_INITIALIZED)), new BooleanLiteral(false))); result.add(new MethodReference(null, @@ -53,23 +52,18 @@ private StatementBlock createBody() { /** - * creates the implicit static <createObject> - * method that takes the object to be created out of the pool + * 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 + * @param type the TypeDeclaration for which the <prepare> is created * @return the implicit <prepare> method */ public MethodDeclaration createMethod(ClassDeclaration type) { ASTList modifiers = new ASTArrayList<>(2); modifiers.add(new Public()); - MethodDeclaration md = new MethodDeclaration(modifiers, - new TypeReference(getId(type)), - new ImplicitIdentifier(IMPLICIT_CREATE), - new ASTArrayList<>(0), - null, - createBody()); + MethodDeclaration md = new MethodDeclaration(modifiers, new TypeReference(getId(type)), + new ImplicitIdentifier(IMPLICIT_CREATE), new ASTArrayList<>(0), null, createBody()); md.makeAllParentRolesValid(); return md; } @@ -82,8 +76,7 @@ public MethodDeclaration createMethod(ClassDeclaration type) { */ protected void makeExplicit(TypeDeclaration td) { if (td instanceof ClassDeclaration) { - attach(createMethod((ClassDeclaration) td), - td, td.getMembers().size()); + attach(createMethod((ClassDeclaration) td), td, td.getMembers().size()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateObjectBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateObjectBuilder.java index 925d522030d..ad838ff19e9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateObjectBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/CreateObjectBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.CrossReferenceServiceConfiguration; @@ -21,14 +24,12 @@ import java.util.Map; /** - * 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. + * 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 RecoderModelTransformer { @@ -37,42 +38,36 @@ public class CreateObjectBuilder extends RecoderModelTransformer { private final Map class2identifier; - public CreateObjectBuilder - (CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public CreateObjectBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); class2identifier = new LinkedHashMap<>(); } /** - * Creates the body of the static <createObject> - * method. + * Creates the body of the static <createObject> method. */ private StatementBlock createBody(ClassDeclaration recoderClass) { ASTList result = new ASTArrayList<>(10); - LocalVariableDeclaration local = declare(NEW_OBJECT_VAR_NAME, class2identifier.get(recoderClass)); + LocalVariableDeclaration local = + declare(NEW_OBJECT_VAR_NAME, class2identifier.get(recoderClass)); result.add(local); final ASTList arguments = new ASTArrayList<>(0); - result.add - (assign(new VariableReference - (new Identifier(NEW_OBJECT_VAR_NAME)), - new MethodReference(new TypeReference - (class2identifier.get(recoderClass)), - new ImplicitIdentifier - (InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), - arguments))); + result.add(assign(new VariableReference(new Identifier(NEW_OBJECT_VAR_NAME)), + new MethodReference(new TypeReference(class2identifier.get(recoderClass)), + new ImplicitIdentifier( + InstanceAllocationMethodBuilder.IMPLICIT_INSTANCE_ALLOCATE), + arguments))); MethodReference createRef = - (new MethodReference(new VariableReference - (new Identifier(NEW_OBJECT_VAR_NAME)), - new ImplicitIdentifier - (CreateBuilder.IMPLICIT_CREATE))); + (new MethodReference(new VariableReference(new Identifier(NEW_OBJECT_VAR_NAME)), + new ImplicitIdentifier(CreateBuilder.IMPLICIT_CREATE))); // July 08 - mulbrich: wraps createRef into a method body statement to // avoid unnecessary dynamic dispatch. @@ -80,11 +75,9 @@ private StatementBlock createBody(ClassDeclaration recoderClass) { // Use a method call there if (recoderClass.getIdentifier() == null) { // anonymous - result.add - (new MethodReference(new VariableReference - (new Identifier(NEW_OBJECT_VAR_NAME)), - new ImplicitIdentifier - (CreateBuilder.IMPLICIT_CREATE))); + result.add( + new MethodReference(new VariableReference(new Identifier(NEW_OBJECT_VAR_NAME)), + new ImplicitIdentifier(CreateBuilder.IMPLICIT_CREATE))); } else { TypeReference tyref; tyref = makeTyRef(recoderClass); @@ -99,8 +92,8 @@ private StatementBlock createBody(ClassDeclaration recoderClass) { } /* - * make a type reference. There are special classes which need to be handled - * differently. ( for instance) + * make a type reference. There are special classes which need to be handled differently. + * ( for instance) */ private TypeReference makeTyRef(ClassDeclaration recoderClass) { Identifier id = recoderClass.getIdentifier(); @@ -112,11 +105,10 @@ private TypeReference makeTyRef(ClassDeclaration recoderClass) { /** - * creates the implicit static <createObject> - * method that takes the object to be created out of the pool + * 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 + * @param type the TypeDeclaration for which the <prepare> is created * @return the implicit <prepare> method */ public MethodDeclaration createMethod(ClassDeclaration type) { @@ -124,18 +116,15 @@ public MethodDeclaration createMethod(ClassDeclaration type) { modifiers.add(new Public()); modifiers.add(new Static()); - MethodDeclaration md = new MethodDeclaration - (modifiers, - new TypeReference(class2identifier.get(type)), - new ImplicitIdentifier(IMPLICIT_OBJECT_CREATE), - new ASTArrayList<>(0), - null, + MethodDeclaration md = + new MethodDeclaration(modifiers, new TypeReference(class2identifier.get(type)), + new ImplicitIdentifier(IMPLICIT_OBJECT_CREATE), new ASTArrayList<>(0), null, createBody(type)); md.makeAllParentRolesValid(); return md; } - @Override + @Override public ProblemReport analyze() { for (final ClassDeclaration cd : classDeclarations()) { class2identifier.put(cd, getId(cd)); @@ -151,8 +140,7 @@ public ProblemReport analyze() { */ protected void makeExplicit(TypeDeclaration td) { if (td instanceof ClassDeclaration) { - attach(createMethod((ClassDeclaration) td), td, - td.getMembers().size()); + attach(createMethod((ClassDeclaration) td), td, td.getMembers().size()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/DLEmbeddedExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/DLEmbeddedExpression.java index 1aa360e12b3..2bc294c39cd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/DLEmbeddedExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/DLEmbeddedExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.util.List; @@ -6,10 +9,10 @@ import de.uka.ilkd.key.util.MiscTools; /** - * This class is used to parse function applications with JavaDL escapes within - * set statements or similar situations. - * - * + * This class is used to parse function applications with JavaDL escapes within set statements or + * similar situations. + * + * * @author Mattias Ulbrich */ public class DLEmbeddedExpression extends EscapeExpression { @@ -24,10 +27,10 @@ public DLEmbeddedExpression(String functionName, List arguments) { public Expression deepClone() { return new DLEmbeddedExpression(functionName, children); } - + @Override public String toSource() { return "\\dl_" + functionName + "(" + MiscTools.join(children, ",") + ")"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassBuilder.java index fe0d71f726b..60d9c646fb5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.util.LinkedHashMap; @@ -27,10 +30,10 @@ import de.uka.ilkd.key.util.Debug; /** - * - * This transformation is made to transform any found {@link EnumDeclaration} - * into a corresponding {@link EnumClassDeclaration}. - * + * + * This transformation is made to transform any found {@link EnumDeclaration} into a corresponding + * {@link EnumClassDeclaration}. + * * @author mulbrich * @since 2006-11-20 * @version 2006-11-21 @@ -39,19 +42,15 @@ public class EnumClassBuilder extends RecoderModelTransformer { private static final Logger LOGGER = LoggerFactory.getLogger(EnumClassBuilder.class); /** - * create a new instance that uses the given service configuration and works - * on the given list of compilation units - * - * @param services - * the cross referencing service configuration to be used - * @param cache - * 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. + * create a new instance that uses the given service configuration and works on the given list + * of compilation units + * + * @param services the cross referencing service configuration to be used + * @param cache 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. */ - public EnumClassBuilder(CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public EnumClassBuilder(CrossReferenceServiceConfiguration services, TransformerCache cache) { super(services, cache); } @@ -59,19 +58,18 @@ public EnumClassBuilder(CrossReferenceServiceConfiguration services, * a mapping of enums to the newly created class declarations. */ Map substitutes = new LinkedHashMap<>(); - + /** - * a mapping of constant references in switch-statements and their - * substitutes. + * a mapping of constant references in switch-statements and their substitutes. */ Map caseSubstitutes = new LinkedHashMap<>(); /** - * find all enum declarations and make their substitutes. - * find all case usages of enum constants and make their substitutes. - * + * find all enum declarations and make their substitutes. find all case usages of enum constants + * and make their substitutes. + * * we may not the cache which buffers classes only not enums! - * + * * @see recoder.kit.TwoPassTransformation#analyze() */ @Override @@ -88,8 +86,7 @@ public ProblemReport analyze() { substitutes.put(ed, ecd); if (Debug.ENABLE_DEBUG) { for (MemberDeclaration m : ecd.getMembers()) { - LOGGER.debug("Member of " - + ecd.getIdentifier().getText() + ": " + LOGGER.debug("Member of " + ecd.getIdentifier().getText() + ": " + m.toSource()); } } @@ -101,76 +98,75 @@ public ProblemReport analyze() { /** * find enumconstants in case statements and mark them for substitution. - * - * Use the cross reference property and find all case usages of enum constants - * replace them by their fully qualified name, if they are not qualified. - * + * + * Use the cross reference property and find all case usages of enum constants replace them by + * their fully qualified name, if they are not qualified. + * * @param ed the EnumDeclaration to search for. */ private void addCases(EnumDeclaration ed) { - - for(EnumConstantDeclaration ecd : ed.getConstants()) { + + for (EnumConstantDeclaration ecd : ed.getConstants()) { EnumConstantSpecification ecs = ecd.getEnumConstantSpecification(); - + List references = getCrossReferenceSourceInfo().getReferences(ecs); - + for (FieldReference fr : references) { if (fr.getASTParent() instanceof Case) { TypeReference tyRef = - TypeKit.createTypeReference( - JavaProgramFactory.getInstance(), ed); - UncollatedReferenceQualifier newCase = - new UncollatedReferenceQualifier(tyRef, - ecs.getIdentifier().deepClone()); - + TypeKit.createTypeReference(JavaProgramFactory.getInstance(), ed); + UncollatedReferenceQualifier newCase = new UncollatedReferenceQualifier(tyRef, + ecs.getIdentifier().deepClone()); + caseSubstitutes.put(fr, newCase); } } - + } } /** * substitute EnumDeclarations by EnumClassDeclarations. - * + * * @see de.uka.ilkd.key.java.recoderext.RecoderModelTransformer#makeExplicit(recoder.java.declaration.TypeDeclaration) - * @deprecated THIS DOES NOT WORK ANY MORE, SINCE THE CACHE ONLY CONSIDERS CLASSE TYPES, NOT ENUMS! + * @deprecated THIS DOES NOT WORK ANY MORE, SINCE THE CACHE ONLY CONSIDERS CLASSE TYPES, NOT + * ENUMS! */ @Deprecated - protected void makeExplicit(TypeDeclaration td) { } - + protected void makeExplicit(TypeDeclaration td) {} + /** * substitute all case statements that have been recorded earlier. - * + * * call super class to invoke "makeExplicit". - * + * * @see de.uka.ilkd.key.java.recoderext.RecoderModelTransformer#transform() */ @Override public void transform() { - + super.transform(); - + for (EnumDeclaration ed : substitutes.keySet()) { EnumClassDeclaration ecd = substitutes.get(ed); if (ecd == null) { - LOGGER.debug("There is no enum->class substitute for " - + ed.getFullName()); + LOGGER.debug("There is no enum->class substitute for " + ed.getFullName()); } else { replace(ed, ecd); - assert ecd.getASTParent() != null : "No parent for " - + ecd.getIdentifier().getText(); + assert ecd.getASTParent() != null + : "No parent for " + ecd.getIdentifier().getText(); } } - - for (Entry entry : caseSubstitutes.entrySet()) { + + for (Entry entry : caseSubstitutes + .entrySet()) { replace(entry.getKey(), entry.getValue()); } - + getChangeHistory().updateModel(); cache.invalidateClasses(); } - - + + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassDeclaration.java index b910cd9a1cb..255e6c98a60 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EnumClassDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.util.List; @@ -21,11 +24,10 @@ import recoder.list.generic.ASTList; /** - * This class is used to describe an enum type by its equivalent class - * declaration. - * - * The transformation {@link EnumClassBuilder} transform an - * {@link EnumDeclaration} to an EnumClassDeclaration by + * This class is used to describe an enum type by its equivalent class declaration. + * + * The transformation {@link EnumClassBuilder} transform an {@link EnumDeclaration} to an + * EnumClassDeclaration by *

      *
    • adding static fields for the enum constants *
    • adding statements in constructors @@ -33,18 +35,18 @@ *
    • adding the methods as specified in the JLS 8.9 *
    • adding "extends Enum" to the ClassDeclaration *
    - * + * *

    - * Currently anonymous implementations for constants are not supported as they - * are anonymous inner classes which are not supported by KeY. - * + * Currently anonymous implementations for constants are not supported as they are anonymous inner + * classes which are not supported by KeY. + * *

    - * The additional methods are constructed as follows (E is the name of the enum, - * (e1, ..., en) its constants): - * + * The additional methods are constructed as follows (E is the name of the enum, (e1, ..., en) its + * constants): + * *

      *            public static E[] values() { return new E[] { e1,..., en } };
    - *            
    + *
      *            public static E valueOf(java.lang.String string) {
      *               for(E e : values()) {
      *                  if(e.name().equals(string))
    @@ -52,22 +54,22 @@
      *               }
      *               throw new IllegalArgumentException();
      *            }
    - *            
    + *
      *            public java.lang.String name() { return ENUM_NAMES[ordinal()]; }
      * 
    - * + * *

    * Additionally the fields that are enum constants are remembered. - * + * * @author mulbrich * @since 2006-11-18 * @version 2006-12-05 */ public class EnumClassDeclaration extends ClassDeclaration { - + /** - * + * */ private static final long serialVersionUID = -7075041929429297548L; @@ -81,13 +83,11 @@ public class EnumClassDeclaration extends ClassDeclaration { private static final String VALUES_PROTO = "public static $E[] values() { return new $E[] { $consts }; }"; private static final String NAME_PROTO = - "public java.lang.String name() { return " + ENUM_NAMES - + "[ordinal()]; }"; + "public java.lang.String name() { return " + ENUM_NAMES + "[ordinal()]; }"; /** - * store the EnumConstantDeclarations here. - * NB: The AST-parent cannot be set to this because - * it is not a EnumDeclaration. + * store the EnumConstantDeclarations here. NB: The AST-parent cannot be set to this + * because it is not a EnumDeclaration. */ private List enumConstants; @@ -97,11 +97,10 @@ public EnumClassDeclaration() { } /** - * make a new wrapping class declaration upon a given enum declaration. Deep - * copy all things instead of relinking them! - * - * Anonymous inner classes are not supported --> no need for an abstract - * keyword. + * make a new wrapping class declaration upon a given enum declaration. Deep copy all things + * instead of relinking them! + * + * Anonymous inner classes are not supported --> no need for an abstract keyword. */ public EnumClassDeclaration(EnumDeclaration ed) { @@ -133,8 +132,7 @@ public EnumClassDeclaration(EnumDeclaration ed) { // // Extends - setExtendedTypes(f.createExtends(TypeKit.createTypeReference(f, - "java.lang.Enum"))); + setExtendedTypes(f.createExtends(TypeKit.createTypeReference(f, "java.lang.Enum"))); // // Implements @@ -146,15 +144,14 @@ public EnumClassDeclaration(EnumDeclaration ed) { // Members // - Make internal fields // - Change constructors, create fields from constants, copy the rest - ASTList members = - new ASTArrayList(); + ASTList members = new ASTArrayList(); setMembers(members); for (MemberDeclaration mem : ed.getMembers()) { if (mem instanceof EnumConstantDeclaration) { members.add(makeConstantField((EnumConstantDeclaration) mem, ed)); enumConstants.add((EnumConstantDeclaration) mem.deepClone()); - } else - members.add((MemberDeclaration)mem.deepClone()); + } else + members.add((MemberDeclaration) mem.deepClone()); } @@ -169,12 +166,11 @@ public EnumClassDeclaration(EnumDeclaration ed) { // // set parent roles makeAllParentRolesValid(); - + } /* - * there are three methods that are to be implemented: - values() - - * valueof(String) - name() + * there are three methods that are to be implemented: - values() - valueof(String) - name() */ private void addImplicitMethods() { @@ -186,16 +182,14 @@ private void addImplicitMethods() { sb.append(", "); sb.append(ecd.getEnumConstantSpecification().getIdentifier().getText()); } - String valuesString = - VALUES_PROTO.replace("$E", getIdentifier().getText()); + String valuesString = VALUES_PROTO.replace("$E", getIdentifier().getText()); valuesString = valuesString.replace("$consts", sb.toString()); MethodDeclaration values = parseMethodDeclaration(valuesString); // // valueOf MethodDeclaration valueOf = - parseMethodDeclaration(VALUE_OF_PROTO.replace("$E", - getIdentifier().getText())); + parseMethodDeclaration(VALUE_OF_PROTO.replace("$E", getIdentifier().getText())); // // name @@ -208,13 +202,12 @@ private void addImplicitMethods() { } /* - * parse a method declaration given as a string. use the - * ProofJavaProgramFactory to be able to make implicit identifiers. + * parse a method declaration given as a string. use the ProofJavaProgramFactory to be able to + * make implicit identifiers. */ private MethodDeclaration parseMethodDeclaration(String string) { try { - return ProofJavaProgramFactory.getInstance().parseMethodDeclaration( - string); + return ProofJavaProgramFactory.getInstance().parseMethodDeclaration(string); } catch (Exception ex) { throw new RuntimeException(ex); } @@ -227,45 +220,41 @@ private void addInternalFields() { ProgramFactory f = getFactory(); - ASTArrayList dsml = - new ASTArrayList(); + ASTArrayList dsml = new ASTArrayList(); dsml.add(f.createPrivate()); dsml.add(f.createStatic()); - - // - // ENUM_NAMES + + // + // ENUM_NAMES dsml = dsml.deepClone(); dsml.add(f.createFinal()); - + Expression init; /* - // use this, once Strings are supported - ASTList nameList = new ASTArrayList(); - for (EnumConstantDeclaration edc : getEnumConstantDeclarations()) { - nameList.add(f.createStringLiteral('"' + edc.getEnumConstantSpecification().getIdentifier().getText() + '"')); - } - - init = f.createArrayInitializer(nameList); - */ + * // use this, once Strings are supported ASTList nameList = new + * ASTArrayList(); for (EnumConstantDeclaration edc : + * getEnumConstantDeclarations()) { nameList.add(f.createStringLiteral( + * '"' + edc.getEnumConstantSpecification().getIdentifier().getText() + '"')); } + * + * init = f.createArrayInitializer(nameList); + */ // String literals are not supported at the moment init = f.createNullLiteral(); - TypeReference stringArrayType = - f.createTypeReference(f.createIdentifier("String"), 1); - + TypeReference stringArrayType = f.createTypeReference(f.createIdentifier("String"), 1); - FieldDeclaration enumNames = - f.createFieldDeclaration(dsml.deepClone(), stringArrayType, - createIdentifier(ENUM_NAMES), init); + + FieldDeclaration enumNames = f.createFieldDeclaration(dsml.deepClone(), stringArrayType, + createIdentifier(ENUM_NAMES), init); getMembers().add(enumNames); } /* - * depending on whether there is a < in the beginning construct a new - * ImplicitIdentifier or a normal Identifier + * depending on whether there is a < in the beginning construct a new ImplicitIdentifier or a + * normal Identifier */ private static Identifier createIdentifier(String string) { if (string.startsWith("<")) @@ -275,9 +264,8 @@ private static Identifier createIdentifier(String string) { } /** - * get all declared enum constants for this enum. - * return them as a list. - * + * get all declared enum constants for this enum. return them as a list. + * * @return a list of the enum constants, not null */ public List getEnumConstantDeclarations() { @@ -285,25 +273,20 @@ public List getEnumConstantDeclarations() { } /* - * make a constantField out of a EnumConstantDeclaration enum A {a1(args)} - * ==> ... public static A a1 = new A(args); ... - * + * make a constantField out of a EnumConstantDeclaration enum A {a1(args)} ==> ... public static + * A a1 = new A(args); ... + * */ - private MemberDeclaration makeConstantField(EnumConstantDeclaration ecd, - EnumDeclaration ed) { + private MemberDeclaration makeConstantField(EnumConstantDeclaration ecd, EnumDeclaration ed) { ProgramFactory f = getFactory(); EnumConstantSpecification ecs = ecd.getEnumConstantSpecification(); ASTList args = ecs.getConstructorReference().getArguments(); - ASTArrayList dsml = - new ASTArrayList(); + ASTArrayList dsml = new ASTArrayList(); // // Make Constructorref - New constrref = - f.createNew(null, - f.createTypeReference(getIdentifier().deepClone()), - args); + New constrref = f.createNew(null, f.createTypeReference(getIdentifier().deepClone()), args); // // make field @@ -311,11 +294,10 @@ private MemberDeclaration makeConstantField(EnumConstantDeclaration ecd, dsml.add(f.createStatic()); dsml.add(f.createFinal()); FieldDeclaration fd = - f.createFieldDeclaration(dsml, - f.createTypeReference(getIdentifier().deepClone()), + f.createFieldDeclaration(dsml, f.createTypeReference(getIdentifier().deepClone()), ecs.getIdentifier().deepClone(), constrref); return fd; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EscapeExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EscapeExpression.java index 8a2a8884ba0..8da367419d7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EscapeExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/EscapeExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.speclang.njml.JmlIO; @@ -11,9 +14,9 @@ /** * Handles JML expressions that begin with an escape character '\'. *

    - * Escaped identifiers in JML code are usually (always?) function symbols. - * JML function symbols begin with an escape character, to distinguish them - * from Java function symbols that might occur in an annotated source code. + * Escaped identifiers in JML code are usually (always?) function symbols. JML function symbols + * begin with an escape character, to distinguish them from Java function symbols that might occur + * in an annotated source code. * * @author Kai Wallisch */ @@ -38,7 +41,8 @@ protected EscapeExpression(String functionName, List arguments) { children = new ASTArrayList(arguments); } - public static EscapeExpression getEscapeExpression(String functionName, List arguments) { + public static EscapeExpression getEscapeExpression(String functionName, + List arguments) { if (functionName.startsWith("\\dl_")) { return new DLEmbeddedExpression(functionName.substring(4), arguments); } else if (JmlIO.isKnownFunction(functionName)) { @@ -48,8 +52,7 @@ public static EscapeExpression getEscapeExpression(String functionName, List branches) { setBranchList(branches); @@ -80,8 +79,7 @@ public Exec(StatementBlock body, ASTList branches) { /** * Exec. * - * @param proto - * a Exec. + * @param proto a Exec. */ protected Exec(Exec proto) { super(proto); @@ -145,20 +143,16 @@ public int getChildCount() { result++; if (branches != null) result += branches.size(); - result += variableDeclarations == null ? 0 - : variableDeclarations.size(); + result += variableDeclarations == null ? 0 : variableDeclarations.size(); return result; } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -202,19 +196,15 @@ public int getChildPositionCode(ProgramElement child) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. * - * @param p - * the old child. - * @param p - * the new child. + * @param p the old child. + * @param p the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ @Override public boolean replaceChild(ProgramElement p, ProgramElement q) { @@ -222,8 +212,7 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { if (p == null) { throw new NullPointerException(); } - count = (variableDeclarations == null) ? 0 - : variableDeclarations.size(); + count = (variableDeclarations == null) ? 0 : variableDeclarations.size(); for (int i = 0; i < count; i++) { if (variableDeclarations.get(i) == p) { if (q == null) { @@ -270,8 +259,7 @@ public StatementBlock getBody() { /** * Set body. * - * @param body - * a statement block. + * @param body a statement block. */ public void setBody(StatementBlock body) { @@ -289,10 +277,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. @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. @exception + * ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override @@ -316,8 +303,7 @@ public ASTList getBranchList() { /** * Set branch list. * - * @param branches - * a branch mutable list. + * @param branches a branch mutable list. */ public void setBranchList(ASTList branches) { this.branches = branches; @@ -335,10 +321,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. @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. @exception + * ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Branch getBranchAt(int index) { @@ -353,8 +338,8 @@ public void accept(SourceVisitor v) { if (v instanceof SourceVisitorExtended) { ((SourceVisitorExtended) v).visitExec(this); } else { -// throw new IllegalStateException( -// "Method 'accept' not implemented in Exec"); + // throw new IllegalStateException( + // "Method 'accept' not implemented in Exec"); } } @@ -372,8 +357,7 @@ public ASTList getVariableDeclarations() { return variableDeclarations; } - public void setVariableDeclarations( - ASTList variableDeclarations) { + public void setVariableDeclarations(ASTList variableDeclarations) { this.variableDeclarations = variableDeclarations; } @@ -408,4 +392,4 @@ public void removeVariableFromScope(String name) { Debug.assertNonnull(name); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecCtxtSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecCtxtSVWrapper.java index b3d6452eb8c..2a0537b145e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecCtxtSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecCtxtSVWrapper.java @@ -1,49 +1,51 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceElement; import recoder.java.SourceVisitor; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class ExecCtxtSVWrapper extends ExecutionContext - implements KeYRecoderExtension, SVWrapper{ +public class ExecCtxtSVWrapper extends ExecutionContext implements KeYRecoderExtension, SVWrapper { /** - * + * */ private static final long serialVersionUID = 2299515454738715766L; - SchemaVariable sv=null; + SchemaVariable sv = null; + - public ExecCtxtSVWrapper(SchemaVariable sv) { this.sv = sv; } /** * sets the schema variable of sort label + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns the schema variable of this type sv wrapper */ public SchemaVariable getSV() { - return sv; + return sv; } public SourceElement getFirstElement() { - return this; + return this; } public ExecutionContext deepClone() { - return new ExecCtxtSVWrapper(sv); + return new ExecCtxtSVWrapper(sv); } - //don't think we need it - public void accept(SourceVisitor v) { - } + // don't think we need it + public void accept(SourceVisitor v) {} -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecutionContext.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecutionContext.java index d636724cbce..015eab6c458 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecutionContext.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExecutionContext.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; @@ -13,13 +16,11 @@ import recoder.java.reference.TypeReferenceContainer; import de.uka.ilkd.key.java.recoderext.adt.MethodSignature; -public class ExecutionContext - extends JavaNonTerminalProgramElement - implements Reference, TypeReferenceContainer, - ExpressionContainer { - +public class ExecutionContext extends JavaNonTerminalProgramElement + implements Reference, TypeReferenceContainer, ExpressionContainer { + /** - * + * */ private static final long serialVersionUID = 2460904042433100490L; @@ -29,188 +30,197 @@ public class ExecutionContext private NonTerminalProgramElement astParent; /** - * the class context + * the class context */ private TypeReference classContext; - + /** * the method signature of the currently active method */ private MethodSignature methodContext; - + /** * the reference to the active object */ private ReferencePrefix runtimeInstance; - + protected ExecutionContext() {} /** * creates an execution context reference - * @param classContext the TypeReference referring to the next enclosing - * class + * + * @param classContext the TypeReference referring to the next enclosing class * @param methodContext the method signature representing the currently active method - * @param runtimeInstance a ReferencePrefix to the object that - * is currently active/executed + * @param runtimeInstance a ReferencePrefix to the object that is currently active/executed */ - public ExecutionContext(TypeReference classContext, - MethodSignature methodContext, - ReferencePrefix runtimeInstance) { - this.classContext = classContext; - this.methodContext = methodContext; - this.runtimeInstance = runtimeInstance; - makeParentRoleValid(); - } - + public ExecutionContext(TypeReference classContext, MethodSignature methodContext, + ReferencePrefix runtimeInstance) { + this.classContext = classContext; + this.methodContext = methodContext; + this.runtimeInstance = runtimeInstance; + makeParentRoleValid(); + } + /** * 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 (runtimeInstance != null) count++; - if (classContext != null) count++; - if (methodContext != null) count++; - return count; + int count = 0; + if (runtimeInstance != null) + count++; + if (classContext != null) + count++; + if (methodContext != null) + count++; + return count; } /** - * Returns the child at the specified index in this node's "virtual" - * child array. + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { - if (classContext != null) { - if (index == 0) return classContext; - index--; - } - if (methodContext != null) { - if (index == 0) return methodContext; - index--; - } - if (runtimeInstance != null) { - if (index == 0) return runtimeInstance; - index--; - } - throw new ArrayIndexOutOfBoundsException(); + if (classContext != null) { + if (index == 0) + return classContext; + index--; + } + if (methodContext != null) { + if (index == 0) + return methodContext; + index--; + } + if (runtimeInstance != null) { + if (index == 0) + return runtimeInstance; + index--; + } + throw new ArrayIndexOutOfBoundsException(); } /** * Returns the positional code of the given child + * * @param child the exact child to look for. * @return the positional code of the given child, or -1. */ public int getChildPositionCode(ProgramElement child) { - int idx = 0; - if (classContext != null) { - if (child == classContext) return idx; - idx ++; - } - if (methodContext != null) { - if (child == methodContext) return idx; - idx ++; - } - if (runtimeInstance != null) { - if (child == runtimeInstance) return idx; - } - return -1; + int idx = 0; + if (classContext != null) { + if (child == classContext) + return idx; + idx++; + } + if (methodContext != null) { + if (child == methodContext) + return idx; + idx++; + } + if (runtimeInstance != null) { + if (child == runtimeInstance) + return idx; + } + return -1; } - public void accept(SourceVisitor visitor) { - } + public void accept(SourceVisitor visitor) {} public ExecutionContext deepClone() { - return new ExecutionContext(classContext, methodContext, runtimeInstance); + return new ExecutionContext(classContext, methodContext, runtimeInstance); } public NonTerminalProgramElement getASTParent() { - return astParent; + return astParent; } public void setParent(NonTerminalProgramElement parent) { - astParent = parent; - } - - public boolean replaceChild(recoder.java.ProgramElement child, - recoder.java.ProgramElement newChild) { - if (child == classContext) { - classContext = (TypeReference) newChild; - } else if (child == runtimeInstance) { - runtimeInstance = (ReferencePrefix)newChild; - } else { - return false; - } - makeParentRoleValid(); - return true; - } - + astParent = parent; + } + + public boolean replaceChild(recoder.java.ProgramElement child, + recoder.java.ProgramElement newChild) { + if (child == classContext) { + classContext = (TypeReference) newChild; + } else if (child == runtimeInstance) { + runtimeInstance = (ReferencePrefix) newChild; + } else { + return false; + } + makeParentRoleValid(); + return true; + } + /** - * Ensures that each child has "this" as syntactical parent. + * Ensures that each child has "this" as syntactical parent. */ public void makeParentRoleValid() { super.makeParentRoleValid(); if (classContext != null) { - classContext.setParent(this); + classContext.setParent(this); } if (runtimeInstance != null) { - ((Expression)runtimeInstance).setExpressionContainer(this); + ((Expression) runtimeInstance).setExpressionContainer(this); } } - - + + public TypeReference getTypeReferenceAt(int index) { - if (classContext != null && index == 0) { - return classContext; - } - throw new ArrayIndexOutOfBoundsException(); + if (classContext != null && index == 0) { + return classContext; + } + throw new ArrayIndexOutOfBoundsException(); } public int getTypeReferenceCount() { - return classContext == null ? 0 : 1; + return classContext == null ? 0 : 1; } public Expression getExpressionAt(int index) { - if (runtimeInstance != null && index == 0) { - return (Expression) runtimeInstance; - } - throw new ArrayIndexOutOfBoundsException(); + if (runtimeInstance != null && index == 0) { + return (Expression) runtimeInstance; + } + throw new ArrayIndexOutOfBoundsException(); } public int getExpressionCount() { - return runtimeInstance == null ? 0 : 1; + return runtimeInstance == null ? 0 : 1; } /** * returns the type reference to the next enclosing class + * * @return the type reference to the next enclosing class */ public TypeReference getTypeReference() { - return classContext; + return classContext; } /** * returns the method signature of the currently active method + * * @return the method signature of the currently active method */ public MethodSignature getMethodContext() { - return methodContext; + return methodContext; } - + /** * returns the runtime instance object + * * @return the runtime instance object */ public ReferencePrefix getRuntimeInstance() { - return runtimeInstance; + return runtimeInstance; } - public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - } -} \ No newline at end of file + public void prettyPrint(PrettyPrinter p) throws java.io.IOException {} +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExpressionSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExpressionSVWrapper.java index cb0939b675c..d0654b2d90b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExpressionSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExpressionSVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; @@ -11,118 +14,123 @@ import recoder.java.reference.ReferenceSuffix; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class ExpressionSVWrapper extends Literal implements Expression, - LoopInitializer, KeYRecoderExtension, SVWrapper, ReferencePrefix { - +public class ExpressionSVWrapper extends Literal + implements Expression, LoopInitializer, KeYRecoderExtension, SVWrapper, ReferencePrefix { + /** - * + * */ private static final long serialVersionUID = 7659491655661716390L; protected SchemaVariable sv; protected ReferenceSuffix suff; - - protected StatementContainer statementParent=null; + + protected StatementContainer statementParent = null; protected ExpressionSVWrapper(ExpressionSVWrapper proto) { super(proto); - expressionParent = null; + expressionParent = null; } public ExpressionSVWrapper() { - expressionParent = null; + expressionParent = null; } public ExpressionSVWrapper(SchemaVariable sv) { - this.sv = sv; - expressionParent = null; + this.sv = sv; + expressionParent = null; } /** - Make parent role valid. + * Make parent role valid. */ - public void makeParentRoleValid() { - } - + public void makeParentRoleValid() {} + /** - Get AST parent. - @return the non terminal program element. + * Get AST parent. + * + * @return the non terminal program element. */ - public NonTerminalProgramElement getASTParent() { - return expressionParent; + public NonTerminalProgramElement getASTParent() { + return expressionParent; } - + /** * sets the schema variable of sort statement + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } public SchemaVariable getSV() { - return sv; + return sv; } - /** - Get expression container. - @return the expression container. + /** + * Get expression container. + * + * @return the expression container. */ public ExpressionContainer getExpressionContainer() { return expressionParent; - } + } /** - Set expression container. - @param c an expression container. + * Set expression container. + * + * @param c an expression container. */ public void setExpressionContainer(ExpressionContainer c) { expressionParent = c; } - //don't think we need it - public void accept(SourceVisitor v) { - } - + // don't think we need it + public void accept(SourceVisitor v) {} + public ExpressionSVWrapper deepClone() { - return new ExpressionSVWrapper(sv); + return new ExpressionSVWrapper(sv); } /** - Get statement container. - @return the statement container. + * Get statement container. + * + * @return the statement container. */ public StatementContainer getStatementContainer() { - return statementParent; + return statementParent; } /** - Set statement container. - @param c a statement container. + * Set statement container. + * + * @param c a statement container. */ public void setStatementContainer(StatementContainer c) { - statementParent = c; + statementParent = c; } public ReferenceSuffix getReferenceSuffix() { - return suff; + return suff; } /** - Set reference suffix. - @param path a reference suffix. + * Set reference suffix. + * + * @param path a reference suffix. */ public void setReferenceSuffix(ReferenceSuffix path) { - suff = path; + suff = path; } - + @Override public Object getEquivalentJavaType() { - throw new Error("mulbrich: what to do here?!"); + throw new Error("mulbrich: what to do here?!"); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExtendedIdentifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExtendedIdentifier.java index 52e6e6695b5..ea157722c28 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExtendedIdentifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ExtendedIdentifier.java @@ -1,8 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; -/** - * an extended identifier that accepts hash symbols in its name - * but not as first character +/** + * an extended identifier that accepts hash symbols in its name but not as first character */ public class ExtendedIdentifier extends recoder.java.Identifier { /** @@ -15,18 +17,16 @@ public ExtendedIdentifier(String arg0) { } public void setText(String text) { - if (text.charAt(0)=='#') { - throw new IllegalArgumentException - ("No hash symbol allowed as first element in variable" + - "identifiers"); - } else if (text.charAt(0)=='<') { - throw new IllegalArgumentException - (text + " is no valid extended identifier."); + if (text.charAt(0) == '#') { + throw new IllegalArgumentException( + "No hash symbol allowed as first element in variable" + "identifiers"); + } else if (text.charAt(0) == '<') { + throw new IllegalArgumentException(text + " is no valid extended identifier."); } - id=text.intern(); + id = text.intern(); } - + public ExtendedIdentifier deepClone() { return new ExtendedIdentifier(id); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ghost.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ghost.java index 132d2a1dee7..b868a1be9c7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ghost.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Ghost.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -5,27 +8,25 @@ public class Ghost extends Modifier { - + /** - * + * */ private static final long serialVersionUID = -4883937081008486072L; - public Ghost() { - } - + public Ghost() {} + protected Ghost(Ghost proto) { super(proto); } - + public Ghost deepClone() { return new Ghost(this); } - - public void accept(SourceVisitor v) { - } - } \ No newline at end of file + + public void accept(SourceVisitor v) {} +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitFieldAdder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitFieldAdder.java index eb162ba4536..10b731a9795 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitFieldAdder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitFieldAdder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.util.Debug; @@ -22,15 +25,13 @@ /** - * 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. + * 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 RecoderModelTransformer { @@ -57,40 +58,34 @@ public class ImplicitFieldAdder extends RecoderModelTransformer { private ClassType javaLangObject; /** - * creates a transformation that adds all implicit fields, - * for example <created>, - * <initialized> and + * creates a transformation that adds all implicit fields, for example + * <created>, <initialized> and * <nextToCreate> etc. * - * @param services the CrossReferenceServiceConfiguration to access - * model information - * @param cache 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. + * @param services the CrossReferenceServiceConfiguration to access model information + * @param cache 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. */ - public ImplicitFieldAdder(CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public ImplicitFieldAdder(CrossReferenceServiceConfiguration services, TransformerCache cache) { super(services, cache); } /** * creates an implicit field of the given type and name * - * @param typeName the name of the type of the new field to create + * @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 + * @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 - (String typeName, String fieldName, - boolean isStatic, boolean isPrivate) { + public static FieldDeclaration createImplicitRecoderField(String typeName, String fieldName, + boolean isStatic, boolean isPrivate) { return createImplicitRecoderField(typeName, fieldName, isStatic, isPrivate, false); } - public static FieldDeclaration createImplicitRecoderField - (String typeName, String fieldName, - boolean isStatic, boolean isPrivate, boolean isFinal) { + public static FieldDeclaration createImplicitRecoderField(String typeName, String fieldName, + boolean isStatic, boolean isPrivate, boolean isFinal) { final int modCount = 1 + (isStatic ? 1 : 0) + (isFinal ? 1 : 0); ASTList modifiers = new ASTArrayList<>(modCount); @@ -111,12 +106,12 @@ public ImplicitFieldAdder(CrossReferenceServiceConfiguration services, int idx = typeName.indexOf('['); final String baseType = (idx == -1 ? typeName : typeName.substring(0, idx)); - final Identifier id = typeName.charAt(0) == '<' ? - new ImplicitIdentifier(baseType) : new Identifier(baseType); + final Identifier id = typeName.charAt(0) == '<' ? new ImplicitIdentifier(baseType) + : new Identifier(baseType); - FieldDeclaration fd = new FieldDeclaration - (modifiers, new TypeReference(id, idx == -1 ? 0 : (typeName.length() - baseType.length()) / 2), - new ImplicitIdentifier(fieldName), null); + FieldDeclaration fd = new FieldDeclaration(modifiers, + new TypeReference(id, idx == -1 ? 0 : (typeName.length() - baseType.length()) / 2), + new ImplicitIdentifier(fieldName), null); fd.makeAllParentRolesValid(); @@ -125,54 +120,56 @@ public ImplicitFieldAdder(CrossReferenceServiceConfiguration services, /** - * 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. + * 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 attach(createImplicitRecoderField("boolean", IMPLICIT_INITIALIZED, false, false), td, 0); attach(createImplicitRecoderField("boolean", IMPLICIT_CREATED, false, false), td, 0); attach(createImplicitRecoderField("int", IMPLICIT_TRANSIENT, false, false), td, 0); - attach(createImplicitRecoderField("boolean", IMPLICIT_TRANSACTION_UPDATED, false, false), td, 0); + attach(createImplicitRecoderField("boolean", IMPLICIT_TRANSACTION_UPDATED, false, false), + td, 0); } /** * adds implicit fields to the given type declaration * - * @param td the recoder.java.TypeDeclaration to be enriched with - * implicit fields + * @param td the recoder.java.TypeDeclaration to be enriched with implicit fields */ private void addImplicitRecoderFields(recoder.java.declaration.TypeDeclaration td) { - attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true), td, 0); + attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true), + td, 0); attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_ERRONEOUS, true, true), td, 0); - attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INITIALIZED, true, true), td, 0); + attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INITIALIZED, true, true), td, + 0); attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_PREPARED, true, true), td, 0); - if (td instanceof ClassDeclaration && - (td.getName() == null || - ((ClassDeclaration) td).getStatementContainer() != null || - td.getContainingClassType() != null) && - (containingMethod(td) == null || !containingMethod(td).isStatic()) && - !td.isStatic()) { + if (td instanceof ClassDeclaration + && (td.getName() == null || ((ClassDeclaration) td).getStatementContainer() != null + || td.getContainingClassType() != null) + && (containingMethod(td) == null || !containingMethod(td).isStatic()) + && !td.isStatic()) { ClassDeclaration container = containingClass(td); ASTList modifiers = new ASTArrayList<>(1); modifiers.add(new Private()); Identifier id = getId(container); - FieldDeclaration fd = new FieldDeclaration - (modifiers, new TypeReference(id), - new ImplicitIdentifier(IMPLICIT_ENCLOSING_THIS), null); + FieldDeclaration fd = new FieldDeclaration(modifiers, new TypeReference(id), + new ImplicitIdentifier(IMPLICIT_ENCLOSING_THIS), null); fd.makeAllParentRolesValid(); attach(fd, td, 0); } } protected void addClassInitializerStatusFields(recoder.java.declaration.TypeDeclaration td) { - attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true), td, 0); + attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INIT_IN_PROGRESS, true, true), + td, 0); attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_ERRONEOUS, true, true), td, 0); - attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INITIALIZED, true, true), td, 0); + attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_INITIALIZED, true, true), td, + 0); attach(createImplicitRecoderField("boolean", IMPLICIT_CLASS_PREPARED, true, true), td, 0); } @@ -180,7 +177,8 @@ private void addFieldsForFinalVars(TypeDeclaration td) { final List vars = getLocalClass2FinalVar().get(td); if (vars != null) { - // not sure why, but doing it separated in two loops is much faster (for large programs) then just in one + // 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... FieldDeclaration[] newFields = new FieldDeclaration[vars.size()]; @@ -203,8 +201,7 @@ public ProblemReport analyze() { Debug.fail("Could not find class java.lang.Object or only as bytecode"); } for (final ClassDeclaration cd : classDeclarations()) { - if (cd != null && - (cd.getName() == null || cd.getStatementContainer() != null)) { + if (cd != null && (cd.getName() == null || cd.getStatementContainer() != null)) { (new FinalOuterVarsCollector()).walk(cd); } } @@ -224,4 +221,4 @@ protected void makeExplicit(TypeDeclaration td) { td.makeAllParentRolesValid(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitIdentifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitIdentifier.java index b68c0a16522..469fd79490f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitIdentifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ImplicitIdentifier.java @@ -1,34 +1,37 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; /** - * subclasses the recoder Identifier in order to allow fields with special - * characters. For example, these are used to distinct between implicit and - * customary class fields. + * subclasses the recoder Identifier in order to allow fields with special characters. For example, + * these are used to distinct between implicit and customary class fields. */ public class ImplicitIdentifier extends Identifier { - + /** - * + * */ private static final long serialVersionUID = -4226362019731704838L; public ImplicitIdentifier(String id) { - super(id); + super(id); } protected void setText(String text) { - id = text.intern(); + id = text.intern(); } - + /** * Deep clone. + * * @return the object. */ - + public ImplicitIdentifier deepClone() { return new ImplicitIdentifier(id); } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/InstanceAllocationMethodBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/InstanceAllocationMethodBuilder.java index b1c0db3af25..1fc76acc1e3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/InstanceAllocationMethodBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/InstanceAllocationMethodBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.CrossReferenceServiceConfiguration; @@ -16,30 +19,26 @@ public class InstanceAllocationMethodBuilder extends RecoderModelTransformer { public static final String IMPLICIT_INSTANCE_ALLOCATE = ""; - public InstanceAllocationMethodBuilder( - CrossReferenceServiceConfiguration services, TransformerCache cache) { + public InstanceAllocationMethodBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); } /** - * 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 + * 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 */ private MethodDeclaration createAllocateMethod(ClassDeclaration type) { ASTList modifiers = new ASTArrayList<>(2); modifiers.add(new Public()); - modifiers.add(new Static()); - + modifiers.add(new Static()); + ASTArrayList pdal = new ASTArrayList<>(1); - - MethodDeclaration md = new MethodDeclaration - (modifiers, - new TypeReference(getId(type)), - new ImplicitIdentifier(IMPLICIT_INSTANCE_ALLOCATE), - pdal, - null, null); + + MethodDeclaration md = new MethodDeclaration(modifiers, new TypeReference(getId(type)), + new ImplicitIdentifier(IMPLICIT_INSTANCE_ALLOCATE), pdal, null, null); md.makeAllParentRolesValid(); return md; } @@ -47,9 +46,8 @@ private MethodDeclaration createAllocateMethod(ClassDeclaration type) { protected void makeExplicit(TypeDeclaration td) { if (td instanceof ClassDeclaration) { - attach(createAllocateMethod((ClassDeclaration)td), td, - td.getMembers().size()); + attach(createAllocateMethod((ClassDeclaration) td), td, td.getMembers().size()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JMLTransformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JMLTransformer.java index 561b4c7e2a7..58c72a4567e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JMLTransformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JMLTransformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.settings.ProofIndependentSettings; @@ -31,11 +34,10 @@ 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. + * 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 RecoderModelTransformer { @@ -45,9 +47,8 @@ public final class JMLTransformer extends RecoderModelTransformer { private static final String JML = "/*@"; private static final String JMR = "@*/"; - public static final ImmutableList javaMods = ImmutableSLList - .nil().prepend("abstract", "final", "private", "protected", - "public", "static"); + public static final ImmutableList javaMods = ImmutableSLList.nil() + .prepend("abstract", "final", "private", "protected", "public", "static"); private static ImmutableList warnings = ImmutableSLList.nil(); @@ -56,18 +57,15 @@ public final class JMLTransformer extends RecoderModelTransformer { private final HashMap> typeDeclaration2Constructores; /** - * Creates a transformation that adds JML specific elements, for example - * ghost fields and model method declarations. + * Creates a transformation that adds JML specific elements, for example ghost fields and model + * method declarations. * - * @param services the CrossReferenceServiceConfiguration to access model - * information - * @param cache 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. + * @param services the CrossReferenceServiceConfiguration to access model information + * @param cache 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. */ - public JMLTransformer(CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public JMLTransformer(CrossReferenceServiceConfiguration services, TransformerCache cache) { super(services, cache); warnings = ImmutableSLList.nil(); typeDeclaration2Constructores = new LinkedHashMap<>(); @@ -103,9 +101,9 @@ private String concatenate(Comment[] comments) { } /** - * 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). + * 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(); @@ -122,22 +120,22 @@ private PositionedString convertToString(ImmutableList mods, ParserRuleC 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); + 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); } public static String getFullText(ParserRuleContext context) { - if (context.start == null || context.stop == null - || context.start.getStartIndex() < 0 || context.stop.getStopIndex() < 0) + 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())); + return context.start.getInputStream() + .getText(Interval.of(context.start.getStartIndex(), context.stop.getStopIndex())); } /** - * Puts the JML modifiers from the passed list into a string enclosed in JML - * markers. + * 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); @@ -153,18 +151,15 @@ private String getJMLModString(ImmutableList mods) { } /** - * Recursively adds the passed position to the starting positions of the - * passed program element and its children. + * Recursively adds the passed position to the starting positions of the passed program element + * and its children. */ - private void updatePositionInformation(ProgramElement pe, - de.uka.ilkd.key.java.Position pos) { + private void updatePositionInformation(ProgramElement pe, de.uka.ilkd.key.java.Position pos) { // set start pos Position oldPos = pe.getStartPosition(); int line = Math.max(0, pos.getLine() + oldPos.getLine() - 1); int column = Math.max(0, pos.getColumn() + oldPos.getColumn() - 1); - Position newPos = new Position( - line, - column); + Position newPos = new Position(line, column); pe.setStartPosition(newPos); // recurse to children @@ -215,8 +210,8 @@ private Comment[] getCommentsAndSetParent(ProgramElement pe) { // private transformation methods // ------------------------------------------------------------------------- - private void transformFieldDecl(TextualJMLFieldDecl decl, - Comment[] originalComments) throws SLTranslationException { + private void transformFieldDecl(TextualJMLFieldDecl decl, Comment[] originalComments) + throws SLTranslationException { assert originalComments.length > 0; // prepend Java modifiers @@ -232,8 +227,7 @@ private void transformFieldDecl(TextualJMLFieldDecl decl, isModel = true; if (isGhost) { throw new SLTranslationException( - "JML field declaration cannot be" - + " both ghost and model!", + "JML field declaration cannot be" + " both ghost and model!", declWithMods.fileName, declWithMods.pos); } } @@ -242,28 +236,23 @@ private void transformFieldDecl(TextualJMLFieldDecl decl, s = s.substring(0, s.indexOf(' ')); throw new SLTranslationException( "Could not translate JML specification. " - + "You have either tried to use an unsupported keyword (" - + s + ") " + + "You have either tried to use an unsupported keyword (" + s + ") " + "or a JML field declaration without a ghost or model modifier.", declWithMods.fileName, declWithMods.pos); } // determine parent, child index - NonTerminalProgramElement astParent = originalComments[0].getParent() - .getASTParent(); - int childIndex = astParent - .getIndexOfChild(originalComments[0].getParent()); + NonTerminalProgramElement astParent = originalComments[0].getParent().getASTParent(); + int childIndex = astParent.getIndexOfChild(originalComments[0].getParent()); // parse declaration, attach to AST Declaration fieldDecl; try { if (astParent instanceof TypeDeclaration) { - fieldDecl = services.getProgramFactory() - .parseFieldDeclaration(declWithMods.text); + fieldDecl = services.getProgramFactory().parseFieldDeclaration(declWithMods.text); if (decl.getMods().contains("instance")) { - fieldDecl = new FieldDeclaration( - (FieldDeclaration) fieldDecl) { + fieldDecl = new FieldDeclaration((FieldDeclaration) fieldDecl) { /** * */ @@ -280,15 +269,13 @@ public boolean isStatic() { // set comments: the original list of comments with the // declaration, // and the JML modifiers - ASTList newComments = new ASTArrayList<>( - Arrays.asList(originalComments)); - Comment jmlComment = new Comment( - getJMLModString(decl.getMods())); + ASTList newComments = new ASTArrayList<>(Arrays.asList(originalComments)); + Comment jmlComment = new Comment(getJMLModString(decl.getMods())); jmlComment.setParent(fieldDecl); newComments.add(jmlComment); fieldDecl.setComments(newComments); - attach((FieldDeclaration) fieldDecl, - (TypeDeclaration) astParent, 0); // No matter what the + attach((FieldDeclaration) fieldDecl, (TypeDeclaration) astParent, 0); // No matter + // what the // javadoc for attach() // may say, // this value is *not* @@ -308,17 +295,16 @@ public boolean isStatic() { assert astParent instanceof StatementBlock; if (isModel) { throw new SLTranslationException( - "JML model fields cannot be declared" - + " within a method!", + "JML model fields cannot be declared" + " within a method!", declWithMods.fileName, declWithMods.pos); } - List declStatement = services.getProgramFactory() - .parseStatements(declWithMods.text); + List declStatement = + services.getProgramFactory().parseStatements(declWithMods.text); assert declStatement.size() == 1; fieldDecl = (LocalVariableDeclaration) declStatement.get(0); updatePositionInformation(fieldDecl, declWithMods.pos); - attach((LocalVariableDeclaration) fieldDecl, - (StatementBlock) astParent, childIndex); // Unlike + attach((LocalVariableDeclaration) fieldDecl, (StatementBlock) astParent, + childIndex); // Unlike // above, here // the value is // really a @@ -329,14 +315,12 @@ public boolean isStatic() { // matters. } } catch (Throwable e) { - throw new SLTranslationException( - e.getMessage() + " (" + e.getClass().getName() + ")", + throw new SLTranslationException(e.getMessage() + " (" + e.getClass().getName() + ")", declWithMods.fileName, declWithMods.pos, e); } // add ghost or model modifier - ASTList mods = fieldDecl - .getDeclarationSpecifiers(); + ASTList mods = fieldDecl.getDeclarationSpecifiers(); if (mods == null) { mods = new ASTArrayList<>(); } @@ -344,30 +328,27 @@ public boolean isStatic() { fieldDecl.setDeclarationSpecifiers(mods); } - private void transformMethodDecl(TextualJMLMethodDecl decl, - Comment[] originalComments) throws SLTranslationException { + private void transformMethodDecl(TextualJMLMethodDecl decl, Comment[] originalComments) + throws SLTranslationException { assert originalComments.length > 0; // prepend Java modifiers - PositionedString declWithMods = - new PositionedString(decl.getParsableDeclaration()); + 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!", + throw new SLTranslationException("JML method declaration has to be model!", declWithMods.fileName, declWithMods.pos); } // determine parent - TypeDeclaration astParent = (TypeDeclaration) originalComments[0] - .getParent().getASTParent(); + TypeDeclaration astParent = + (TypeDeclaration) originalComments[0].getParent().getASTParent(); // parse declaration, attach to AST MethodDeclaration methodDecl; try { - methodDecl = services.getProgramFactory() - .parseMethodDeclaration(declWithMods.text); + methodDecl = services.getProgramFactory().parseMethodDeclaration(declWithMods.text); updatePositionInformation(methodDecl, declWithMods.pos); attach(methodDecl, astParent, 0); // about the 0 see the comment in // transformFieldDecl() above @@ -378,8 +359,7 @@ private void transformMethodDecl(TextualJMLMethodDecl decl, } // add model modifier - ASTList mods = methodDecl - .getDeclarationSpecifiers(); + ASTList mods = methodDecl.getDeclarationSpecifiers(); mods.add(new Model()); if (decl.getMods().contains("two_state")) { mods.add(new TwoState()); @@ -391,8 +371,7 @@ private void transformMethodDecl(TextualJMLMethodDecl decl, // set comments: the original list of comments with the declaration, // and the JML modifiers - ASTList newComments = new ASTArrayList<>( - Arrays.asList(originalComments)); + ASTList newComments = new ASTArrayList<>(Arrays.asList(originalComments)); Comment jmlComment = new Comment(getJMLModString(decl.getMods())); jmlComment.setParent(methodDecl); newComments.add(jmlComment); @@ -400,19 +379,17 @@ private void transformMethodDecl(TextualJMLMethodDecl decl, } private void transformAssertStatement(TextualJMLAssertStatement stat, - Comment[] originalComments) throws SLTranslationException { - if (originalComments.length <= 0) throw new IllegalArgumentException(); + Comment[] originalComments) throws SLTranslationException { + if (originalComments.length <= 0) + throw new IllegalArgumentException(); // determine parent, child index - StatementBlock astParent = (StatementBlock) originalComments[0] - .getParent().getASTParent(); - int childIndex = astParent - .getIndexOfChild(originalComments[0].getParent()); + StatementBlock astParent = (StatementBlock) originalComments[0].getParent().getASTParent(); + int childIndex = astParent.getIndexOfChild(originalComments[0].getParent()); ParserRuleContext ctx = stat.getContext().first; - de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( - ctx.start.getLine(), + de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position(ctx.start.getLine(), ctx.start.getCharPositionInLine()); final Kind kind = stat.getKind(); JmlAssert jmlAssert = new JmlAssert(kind, stat.getContext()); @@ -426,67 +403,58 @@ private void transformAssertStatement(TextualJMLAssertStatement stat, } } - private void transformSetStatement(TextualJMLSetStatement stat, - Comment[] originalComments) throws SLTranslationException { + private void transformSetStatement(TextualJMLSetStatement stat, Comment[] originalComments) + throws SLTranslationException { assert originalComments.length > 0; // determine parent, child index - StatementBlock astParent = (StatementBlock) originalComments[0] - .getParent().getASTParent(); - int childIndex = astParent - .getIndexOfChild(originalComments[0].getParent()); + StatementBlock astParent = (StatementBlock) originalComments[0].getParent().getASTParent(); + int childIndex = astParent.getIndexOfChild(originalComments[0].getParent()); // 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()); + 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); List stmtList = services.getProgramFactory().parseStatements(assignment); assert stmtList.size() == 1; CopyAssignment assignStmt = (CopyAssignment) stmtList.get(0); - updatePositionInformation(assignStmt, - pos); + updatePositionInformation(assignStmt, pos); doAttach(assignStmt, astParent, childIndex); } catch (Throwable e) { - throw new SLTranslationException( - e.getMessage() + " (" + e.getClass().getName() + ")", + throw new SLTranslationException(e.getMessage() + " (" + e.getClass().getName() + ")", stat.getAssignment().start.getTokenSource().getSourceName(), pos, e); } } - private void transformMergePointDecl(TextualJMLMergePointDecl stat, - Comment[] originalComments) throws SLTranslationException { + private void transformMergePointDecl(TextualJMLMergePointDecl stat, Comment[] originalComments) + throws SLTranslationException { assert originalComments.length > 0; // determine parent, child index - StatementBlock astParent = (StatementBlock) originalComments[0] - .getParent().getASTParent(); - int childIndex = astParent - .getIndexOfChild(originalComments[0].getParent()); + StatementBlock astParent = (StatementBlock) originalComments[0].getParent().getASTParent(); + int childIndex = astParent.getIndexOfChild(originalComments[0].getParent()); // create MPS, attach to AST try { MergePointStatement mps = new MergePointStatement(stat.getMergeProc()); - mps.setComments( - new ASTArrayList<>(Arrays.asList(originalComments))); + mps.setComments(new ASTArrayList<>(Arrays.asList(originalComments))); - Position startPosition = astParent.getChildAt(childIndex) - .getStartPosition(); + Position startPosition = astParent.getChildAt(childIndex).getStartPosition(); // Note (DS): I don't really know what I do here (concerning the // position information), but it seems to work... updatePositionInformation(mps, new de.uka.ilkd.key.java.Position( startPosition.getLine(), startPosition.getColumn())); doAttach(mps, astParent, childIndex); } catch (Throwable e) { - throw new SLTranslationException( - e.getMessage() + " (" + e.getClass().getName() + ")", + throw new SLTranslationException(e.getMessage() + " (" + e.getClass().getName() + ")", stat.getSourceFileName(), stat.getApproxPosition(), e); } } - private void transformClasslevelComments(TypeDeclaration td, - String fileName) throws SLTranslationException { + private void transformClasslevelComments(TypeDeclaration td, String fileName) + throws SLTranslationException { // iterate over all pre-existing children ProgramElement[] children = getChildren(td); for (int i = 0; i <= children.length; i++) { @@ -511,13 +479,13 @@ private void transformClasslevelComments(TypeDeclaration td, // concatenate comments of child, determine position String concatenatedComment = concatenate(comments); Position recoderPos = comments[0].getStartPosition(); - de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( - recoderPos.getLine(), recoderPos.getColumn()); + de.uka.ilkd.key.java.Position pos = + new de.uka.ilkd.key.java.Position(recoderPos.getLine(), recoderPos.getColumn()); // call preparser JmlIO io = new JmlIO(); - ImmutableList constructs - = io.parseClassLevel(concatenatedComment, fileName, pos); + ImmutableList constructs = + io.parseClassLevel(concatenatedComment, fileName, pos); warnings = warnings.append(io.getWarnings()); // handle model and ghost declarations in textual constructs @@ -529,27 +497,25 @@ private void transformClasslevelComments(TypeDeclaration td, } else if (c instanceof TextualJMLMethodDecl) { transformMethodDecl((TextualJMLMethodDecl) c, comments); } else if (c instanceof TextualJMLSetStatement) { - if (i == 0 || !(children[i - - 1] instanceof MethodDeclaration)) { + if (i == 0 || !(children[i - 1] instanceof MethodDeclaration)) { throw new SLTranslationException( - "A set assignment only allowed inside of a method body.", - fileName, pos); + "A set assignment only allowed inside of a method body.", fileName, + pos); } Statement emptyStmt = new EmptyStatement(); Comment emptyStmtComment = new Comment(); emptyStmtComment.setParent(emptyStmt); - StatementBlock methodBody = ((MethodDeclaration) children[i - - 1]).getBody(); + StatementBlock methodBody = ((MethodDeclaration) children[i - 1]).getBody(); attach(emptyStmt, methodBody, methodBody.getChildCount()); transformSetStatement((TextualJMLSetStatement) c, - new Comment[]{emptyStmtComment}); + new Comment[] { emptyStmtComment }); } } } } - private void transformMethodlevelCommentsHelper(ProgramElement pe, - String fileName) throws SLTranslationException { + private void transformMethodlevelCommentsHelper(ProgramElement pe, String fileName) + throws SLTranslationException { // recurse to all pre-existing children ProgramElement[] children = getChildren(pe); for (ProgramElement aChildren : children) { @@ -568,13 +534,13 @@ private void transformMethodlevelCommentsHelper(ProgramElement pe, // concatenate comments, determine position String concatenatedComment = concatenate(comments); Position recoderPos = comments[0].getStartPosition(); - de.uka.ilkd.key.java.Position pos = new de.uka.ilkd.key.java.Position( - recoderPos.getLine(), recoderPos.getColumn()); + de.uka.ilkd.key.java.Position pos = + new de.uka.ilkd.key.java.Position(recoderPos.getLine(), recoderPos.getColumn()); // call preparser JmlIO io = new JmlIO(); - ImmutableList constructs - = io.parseMethodLevel(concatenatedComment, fileName, pos); + ImmutableList constructs = + io.parseMethodLevel(concatenatedComment, fileName, pos); warnings = warnings.append(io.getWarnings()); // handle ghost declarations and set assignments in textual constructs @@ -591,8 +557,8 @@ private void transformMethodlevelCommentsHelper(ProgramElement pe, } } - private void transformMethodlevelComments(MethodDeclaration md, - String fileName) throws SLTranslationException { + private void transformMethodlevelComments(MethodDeclaration md, String fileName) + throws SLTranslationException { StatementBlock body = md.getBody(); if (body != null) { transformMethodlevelCommentsHelper(body, fileName); @@ -638,8 +604,7 @@ public ProblemReport analyze() { // the invariant will appear as a comment of the unit. We move it // to B here.) if (unit.getTypeDeclarationCount() > 0) { - TypeDeclaration td = unit.getTypeDeclarationAt( - unit.getTypeDeclarationCount() - 1); + TypeDeclaration td = unit.getTypeDeclarationAt(unit.getTypeDeclarationCount() - 1); ASTList tdComments = new ASTArrayList<>(); if (unit.getComments() != null) { tdComments.addAll(unit.getComments().deepClone()); @@ -653,8 +618,7 @@ public ProblemReport analyze() { Set typeDeclarations = tdc.result(); for (TypeDeclaration td : typeDeclarations) { // collect pre-existing operations - List constructorList = td - .getConstructors(); + List constructorList = td.getConstructors(); List methodList = td.getMethods(); typeDeclaration2Constructores.put(td, constructorList); @@ -670,8 +634,7 @@ public ProblemReport analyze() { public void makeExplicit() { // abort if JML is disabled // if(!ProofSettings.DEFAULT_SETTINGS.getGeneralSettings().useJML()) { - if (!ProofIndependentSettings.DEFAULT_INSTANCE.getGeneralSettings() - .useJML()) { + if (!ProofIndependentSettings.DEFAULT_INSTANCE.getGeneralSettings().useJML()) { return; } @@ -686,18 +649,20 @@ public void makeExplicit() { Set typeDeclarations = tdc.result(); for (TypeDeclaration td : typeDeclarations) { // collect pre-existing operations - List constructorList = typeDeclaration2Constructores - .get(td); + List constructorList = + typeDeclaration2Constructores.get(td); List methodList = typeDeclaration2Methods.get(td); // 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 = dl == null ? "UNKNOWN:unknown" - : MiscTools.extractURI(dl).toString(); + /* + * 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 = + dl == null ? "UNKNOWN:unknown" : MiscTools.extractURI(dl).toString(); transformClasslevelComments(td, resource); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JmlAssert.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JmlAssert.java index 57d4e79fc43..435d36b7493 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JmlAssert.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JmlAssert.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.speclang.jml.pretranslation.TextualJMLAssertStatement; @@ -19,11 +22,10 @@ public class JmlAssert extends JavaStatement { */ private final TextualJMLAssertStatement.Kind kind; - /* condition should be an Expression, - but as KeY doesn't support some jml Expressions as Expression Objects - e.g. \forall - keep this as the parse tree for now - (blockcontracts seem to handle this similar) + /* + * condition should be an Expression, but as KeY doesn't support some jml Expressions as + * Expression Objects e.g. \forall keep this as the parse tree for now (blockcontracts seem to + * handle this similar) */ /** * The condition of this statement in parse tree form diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JumpLabelSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JumpLabelSVWrapper.java index 95099a9dc51..fe6da7ca063 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JumpLabelSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/JumpLabelSVWrapper.java @@ -1,25 +1,28 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.logic.op.SchemaVariable; public class JumpLabelSVWrapper implements SVWrapper { - private SchemaVariable label; - + private SchemaVariable label; + public JumpLabelSVWrapper(SchemaVariable l) { label = l; } - - public SchemaVariable getSV() { + + public SchemaVariable getSV() { return label; } public void setSV(SchemaVariable sv) { - label = sv; + label = sv; } - + public String toString() { - return ""+label; + return "" + label; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYAnnotationUseSpecification.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYAnnotationUseSpecification.java index 406b17bca01..af63cde25f5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYAnnotationUseSpecification.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYAnnotationUseSpecification.java @@ -1,27 +1,30 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.declaration.AnnotationUseSpecification; import recoder.java.reference.TypeReference; -//HACK: This class is declared due to a bug in recoder causing a stack overflow when -//deepClone@AnnotationUseSpecification is called +// HACK: This class is declared due to a bug in recoder causing a stack overflow when +// deepClone@AnnotationUseSpecification is called public class KeYAnnotationUseSpecification extends AnnotationUseSpecification { /** - * + * */ private static final long serialVersionUID = 2163251956161988258L; - public KeYAnnotationUseSpecification(){ + public KeYAnnotationUseSpecification() { super(); } - - public KeYAnnotationUseSpecification(TypeReference tr){ + + public KeYAnnotationUseSpecification(TypeReference tr) { super(tr); } - - public KeYAnnotationUseSpecification deepClone(){ + + public KeYAnnotationUseSpecification deepClone() { return new KeYAnnotationUseSpecification(getTypeReference()); } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceNameInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceNameInfo.java index 8d50c58d304..4be22cae4dd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceNameInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceNameInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.java.ConvertException; @@ -16,74 +19,72 @@ /** - * This is a specialisation of the NameInfo interface which allows KeY to detect - * multiple declaration of types. It stores all defined type (w/o possible some - * array types which do not matter) in a hash table to look up. - * - * If it records an attempt to register a declaration type twice, a verbose - * conversion exception is thrown. - * - * It also reports a missing "java.lang.Object" definition in a - * {@link ConvertException}. Recoder itself usually fails at a random point - * with a {@link NullPointerException}. - * - * An instance of this class is created in - * {@link KeYCrossReferenceServiceConfiguration}. - * + * This is a specialisation of the NameInfo interface which allows KeY to detect multiple + * declaration of types. It stores all defined type (w/o possible some array types which do not + * matter) in a hash table to look up. + * + * If it records an attempt to register a declaration type twice, a verbose conversion exception is + * thrown. + * + * It also reports a missing "java.lang.Object" definition in a {@link ConvertException}. Recoder + * itself usually fails at a random point with a {@link NullPointerException}. + * + * An instance of this class is created in {@link KeYCrossReferenceServiceConfiguration}. + * * @author MU - * + * */ public class KeYCrossReferenceNameInfo extends DefaultNameInfo { private static final Logger LOGGER = LoggerFactory.getLogger(KeYCrossReferenceNameInfo.class); // this somewhat doubles name2type in DefaultNameInfo to which we have no access private final HashMap classtypes = new LinkedHashMap<>(); - + public KeYCrossReferenceNameInfo(ServiceConfiguration config) { super(config); } - + /** * register a class type. - * - * @param ct - * class type to register - * @throws ConvertException - * if there was already a different type registered for the - * same name + * + * @param ct class type to register + * @throws ConvertException if there was already a different type registered for the same name */ @Override public void register(ClassType ct) { - + String name = ct.getFullName(); ClassType old = classtypes.get(name); - if(old != null && ct != old) { + if (old != null && ct != old) { String d1, d2; if (ct instanceof TypeDeclaration) { - d1 = UnitKit.getCompilationUnit((TypeDeclaration) ct).getOriginalDataLocation().toString(); + d1 = UnitKit.getCompilationUnit((TypeDeclaration) ct).getOriginalDataLocation() + .toString(); } else { d1 = ct.toString(); } if (old instanceof TypeDeclaration) { - d2 = UnitKit.getCompilationUnit((TypeDeclaration) old).getOriginalDataLocation().toString(); + d2 = UnitKit.getCompilationUnit((TypeDeclaration) old).getOriginalDataLocation() + .toString(); } else { d2 = old.toString(); } - LOGGER.warn("Datatype {} declared twice: Once in {} and once in {}, Keeping one from {}", name, d1, d2, d2); + LOGGER.warn( + "Datatype {} declared twice: Once in {} and once in {}, Keeping one from {}", + name, d1, d2, d2); return; } - + super.register(ct); classtypes.put(name, ct); } /** - * unregister a class type. This happens for instance when removing an - * EnumDeclaration and inserting an EnumClassDeclaration instead - * - * @param fullname - * name of the type to be unregistered + * unregister a class type. This happens for instance when removing an EnumDeclaration and + * inserting an EnumClassDeclaration instead + * + * @param fullname name of the type to be unregistered */ @Override public void unregisterClassType(String fullname) { @@ -97,27 +98,24 @@ public void unregisterClassType(String fullname) { @Override public Type getType(String name) { Type t = super.getType(name); - if(t instanceof ClassType) - classtypes.put(name, (ClassType)t); + if (t instanceof ClassType) + classtypes.put(name, (ClassType) t); return t; } - + /** * {@inheritDoc} - * - * This implementation checks whether an implementation is available and - * fails if not. - * - * @throws ConvertException - * if no implementation of java.lang.Object is available - * presently. + * + * This implementation checks whether an implementation is available and fails if not. + * + * @throws ConvertException if no implementation of java.lang.Object is available presently. */ - @Override + @Override public ClassType getJavaLangObject() throws ConvertException { ClassType result = super.getJavaLangObject(); - if(result == null) + if (result == null) throw new ConvertException("Class type 'java.lang.Object' cannot be found"); return result; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceServiceConfiguration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceServiceConfiguration.java index a274377c0d1..bc8432c2e98 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceServiceConfiguration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceServiceConfiguration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.CrossReferenceServiceConfiguration; @@ -9,22 +12,21 @@ import de.uka.ilkd.key.java.KeYProgModelInfo; import de.uka.ilkd.key.util.KeYRecoderExcHandler; -public class KeYCrossReferenceServiceConfiguration - extends CrossReferenceServiceConfiguration{ +public class KeYCrossReferenceServiceConfiguration extends CrossReferenceServiceConfiguration { protected KeYProgModelInfo kpmi = null; - public KeYCrossReferenceServiceConfiguration(KeYRecoderExcHandler keh ) { - super(); // initialises servConf - // better not: it might add to the input path of recoder - // getProjectSettings().ensureSystemClassesAreInPath(); - assert keh != null : "The exception handler must not be null"; + public KeYCrossReferenceServiceConfiguration(KeYRecoderExcHandler keh) { + super(); // initialises servConf + // better not: it might add to the input path of recoder + // getProjectSettings().ensureSystemClassesAreInPath(); + assert keh != null : "The exception handler must not be null"; getProjectSettings().setErrorHandler(keh); } public KeYCrossReferenceServiceConfiguration(KeYProgModelInfo kpmi) { - this(kpmi.getExceptionHandler()); - this.kpmi = kpmi; + this(kpmi.getExceptionHandler()); + this.kpmi = kpmi; } protected ProgramFactory makeProgramFactory() { @@ -32,22 +34,22 @@ protected ProgramFactory makeProgramFactory() { } /** - The cross reference source info is a subclass of the source info, - so this class simply overrides the source info factory method. + * The cross reference source info is a subclass of the source info, so this class simply + * overrides the source info factory method. */ protected SourceInfo makeSourceInfo() { - return new KeYCrossReferenceSourceInfo(this); + return new KeYCrossReferenceSourceInfo(this); } - + protected SourceFileRepository makeSourceFileRepository() { return new KeYCrossReferenceSourceFileRepository(this); } protected NameInfo makeNameInfo() { - return new KeYCrossReferenceNameInfo(this); + return new KeYCrossReferenceNameInfo(this); } - public KeYProgModelInfo getKeYProgModelInfo(){ - return kpmi; + public KeYProgModelInfo getKeYProgModelInfo() { + return kpmi; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceSourceFileRepository.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceSourceFileRepository.java index 71ddb044d72..5229b463429 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceSourceFileRepository.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYCrossReferenceSourceFileRepository.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.ServiceConfiguration; @@ -8,35 +11,30 @@ /** * This class is used to handle source files within recoder. - * + * * It does only overwrite one method: createDataLocation. - * - * The original method in {@link DefaultSourceFileRepository} creates references - * to possibly non-existing files which we do not want. Thus, we leave the location - * already present. - * + * + * The original method in {@link DefaultSourceFileRepository} creates references to possibly + * non-existing files which we do not want. Thus, we leave the location already present. + * * @author MU - * + * */ -public class KeYCrossReferenceSourceFileRepository extends - DefaultSourceFileRepository { +public class KeYCrossReferenceSourceFileRepository extends DefaultSourceFileRepository { public KeYCrossReferenceSourceFileRepository(ServiceConfiguration config) { super(config); } /** - * return the data location that is already stored in the compilation unit. - * If there is no location stored so far, create a temporary invalid one. - * - * The super class would have created a location that does not represent the - * existing sources. - * - * @param cu - * Compilation unit to create the location for. - * @return location(cu) == null ? {@link SpecDataLocation#UNKNOWN_LOCATION} : - * location(cu) + * return the data location that is already stored in the compilation unit. If there is no + * location stored so far, create a temporary invalid one. + * + * The super class would have created a location that does not represent the existing sources. + * + * @param cu Compilation unit to create the location for. + * @return location(cu) == null ? {@link SpecDataLocation#UNKNOWN_LOCATION} : location(cu) */ protected DataLocation createDataLocation(CompilationUnit cu) { DataLocation dataLocation = cu.getDataLocation(); @@ -45,4 +43,4 @@ protected DataLocation createDataLocation(CompilationUnit cu) { return dataLocation; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYRecoderExtension.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYRecoderExtension.java index 3ebc33b959d..8be9e3d665a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYRecoderExtension.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/KeYRecoderExtension.java @@ -1,7 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; public interface KeYRecoderExtension { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LabelSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LabelSVWrapper.java index 92d427d77b9..8334a2a6114 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LabelSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LabelSVWrapper.java @@ -1,19 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class LabelSVWrapper extends Identifier - implements KeYRecoderExtension, SVWrapper{ +public class LabelSVWrapper extends Identifier implements KeYRecoderExtension, SVWrapper { /** - * + * */ private static final long serialVersionUID = 5338442155201858492L; - SchemaVariable sv=null; + SchemaVariable sv = null; public LabelSVWrapper(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } protected LabelSVWrapper(LabelSVWrapper proto) { @@ -23,18 +25,19 @@ protected LabelSVWrapper(LabelSVWrapper proto) { /** * sets the schema variable of sort label + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns the schema variable of this label sv wrapper */ public SchemaVariable getSV() { - return sv; + return sv; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LocalClassTransformation.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LocalClassTransformation.java index 05940ba9771..b8e1e250fc2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LocalClassTransformation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LocalClassTransformation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.util.List; @@ -14,45 +17,43 @@ import recoder.service.CrossReferenceSourceInfo; /** - * 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. - * + * 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 RecoderModelTransformer { - - public LocalClassTransformation( - CrossReferenceServiceConfiguration services, TransformerCache cache) { + + public LocalClassTransformation(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); } public ProblemReport analyze() { - for (final ClassDeclaration cd : classDeclarations()) { - if(cd.getName() == null || cd.getStatementContainer() !=null){ - (new FinalOuterVarsCollector()).walk(cd); - } - } - return super.analyze(); + for (final ClassDeclaration cd : classDeclarations()) { + if (cd.getName() == null || cd.getStatementContainer() != null) { + (new FinalOuterVarsCollector()).walk(cd); + } + } + return super.analyze(); } - + protected void makeExplicit(TypeDeclaration td) { List outerVars = getLocalClass2FinalVar().get(td); CrossReferenceSourceInfo si = services.getCrossReferenceSourceInfo(); - - if(outerVars!=null){ + + if (outerVars != null) { for (final Variable v : outerVars) { - for (final VariableReference vr : si.getReferences(v)){ - if (si.getContainingClassType(vr) != - si.getContainingClassType((ProgramElement) v)){ - FieldReference fr = new FieldReference(new ThisReference(), - new ImplicitIdentifier(ImplicitFieldAdder.FINAL_VAR_PREFIX+ - v.getName())); + for (final VariableReference vr : si.getReferences(v)) { + if (si.getContainingClassType(vr) != si + .getContainingClassType((ProgramElement) v)) { + FieldReference fr = + new FieldReference(new ThisReference(), new ImplicitIdentifier( + ImplicitFieldAdder.FINAL_VAR_PREFIX + v.getName())); vr.getASTParent().replaceChild(vr, fr); td.makeAllParentRolesValid(); } @@ -61,4 +62,4 @@ protected void makeExplicit(TypeDeclaration td) { } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LoopScopeBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LoopScopeBlock.java index d94acb31138..64e7c8b7f4e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LoopScopeBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/LoopScopeBlock.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; @@ -23,9 +26,8 @@ public class LoopScopeBlock extends JavaStatement protected Statement body; /** - * This constructor should only be used in the SchemaJavaParser! Make sure - * to call {@link #setBody(Statement)} and - * {@link #setIndexPV(Expression)} afterward. + * This constructor should only be used in the SchemaJavaParser! Make sure to call + * {@link #setBody(Statement)} and {@link #setIndexPV(Expression)} afterward. */ public LoopScopeBlock() { this.indexPV = null; @@ -33,7 +35,7 @@ public LoopScopeBlock() { } /** - * + * * @param resultVar * @param body */ @@ -64,9 +66,8 @@ public Expression getIndexPV() { /** * Set body. - * - * @param body - * the Statement + * + * @param body the Statement */ public void setBody(Statement body) { this.body = body; @@ -74,7 +75,7 @@ public void setBody(Statement body) { /** * Get body. - * + * * @return the Statement */ public Statement getBody() { @@ -82,11 +83,11 @@ public Statement getBody() { } /** - * Finds the source element that occurs first in the source. Returns the - * first element of the first child. - * - * @return the last source element in the syntactical representation of this - * element, may be equals to this element. + * Finds the source element that occurs first in the source. Returns the first element of the + * first child. + * + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ public SourceElement getFirstElement() { @@ -94,11 +95,11 @@ public SourceElement getFirstElement() { } /** - * Finds the source element that occurs last in the source. Returns the last - * element of the body. - * - * @return the last source element in the syntactical representation of this - * element, may be equals to this element. + * Finds the source element that occurs last in the source. Returns the last element of the + * body. + * + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ public SourceElement getLastElement() { @@ -107,7 +108,7 @@ public SourceElement getLastElement() { /** * Returns the number of children of this node. - * + * * @return an int giving the number of children of this node */ @@ -121,14 +122,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 + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { @@ -160,7 +158,7 @@ public int getChildPositionCode(ProgramElement child) { /** * Get the number of statements in this container. - * + * * @return the number of statements. */ public int getStatementCount() { @@ -169,14 +167,11 @@ public int getStatementCount() { } /** - * Return the statement at the specified index in this node's "virtual" - * statement array. - * - * @param index - * an index for a statement. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -187,7 +182,7 @@ public Statement getStatementAt(int index) { /** * Get the number of expressions in this container. - * + * * @return the number of expressions. */ public int getExpressionCount() { @@ -195,14 +190,11 @@ public int getExpressionCount() { } /** - * Return the expression at the specified index in this node's "virtual" - * expression array. - * - * @param index - * an index for a expression. + * Return the expression at the specified index in this node's "virtual" expression array. + * + * @param index an index for a expression. * @return the expression with the given index. - * @exception ArrayIndexOutOfBoundsException - * if index is out of bounds. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { @@ -213,19 +205,15 @@ public Expression getExpressionAt(int index) { } /** - * Replace a single child in the current node. The child to replace is - * matched by identity and hence must be known exactly. The replacement - * element can be null - in that case, the child is effectively removed. The - * parent role of the new child is validated, while the parent link of the - * replaced child is left untouched. - * - * @param p - * the old child. - * @param q - * the new child. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * + * @param p the old child. + * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException - * if the new child cannot take over the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { if (indexPV == p) { @@ -260,16 +248,15 @@ public void makeParentRoleValid() { } // don't think we need it - public void accept(SourceVisitor v) { - } + public void accept(SourceVisitor v) {} /** * Deep clone. - * + * * @return the object */ public LoopScopeBlock deepClone() { return new LoopScopeBlock(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MergePointStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MergePointStatement.java index b1912338fda..9b9d496dc42 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MergePointStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MergePointStatement.java @@ -1,11 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import org.antlr.v4.runtime.ParserRuleContext; import recoder.java.*; import recoder.java.statement.JavaStatement; -public class MergePointStatement extends JavaStatement - implements ExpressionContainer { +public class MergePointStatement extends JavaStatement implements ExpressionContainer { private static final long serialVersionUID = 8513553210611636414L; private StatementContainer astParent; @@ -58,8 +60,8 @@ public void setIndexPV(Expression indexPV) { /** * Finds the source element that occurs first in the source. * - * @return the last source element in the syntactical representation of this - * element, may be equals to this element. + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ @Override public SourceElement getFirstElement() { @@ -69,8 +71,8 @@ public SourceElement getFirstElement() { /** * 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. + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ @Override public SourceElement getLastElement() { @@ -88,8 +90,7 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodBodyStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodBodyStatement.java index c238e7560b4..0d906ca1cc1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodBodyStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodBodyStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; @@ -19,13 +22,13 @@ /** - * A shortcut-statement for a method body. + * A shortcut-statement for a method body. */ -public class MethodBodyStatement extends JavaStatement implements - TypeReferenceContainer, ExpressionContainer, NamedProgramElement, ReferenceSuffix { - +public class MethodBodyStatement extends JavaStatement implements TypeReferenceContainer, + ExpressionContainer, NamedProgramElement, ReferenceSuffix { + /** - * + * */ private static final long serialVersionUID = 3576016842584950841L; @@ -35,158 +38,173 @@ public class MethodBodyStatement extends JavaStatement implements private StatementContainer astParent; protected TypeReference bodySource; - protected Expression resultVar; + protected Expression resultVar; private Identifier methodName; private ReferencePrefix methodReferencePrefix; private ASTList arguments; - + /** - * Construct a method body shortcut - * @param bodySource exact class where the body is declared - * @param resultVar the Expression naming the variable to which - * the result of the mthod is assigned - * @param methRef MethodReference that represents the call + * Construct a method body shortcut + * + * @param bodySource exact class where the body is declared + * @param resultVar the Expression naming the variable to which the result of the mthod is + * assigned + * @param methRef MethodReference that represents the call */ - - public MethodBodyStatement(TypeReference bodySource, - Expression resultVar, - MethodReference methRef) { + + public MethodBodyStatement(TypeReference bodySource, Expression resultVar, + MethodReference methRef) { setBodySource(bodySource); - this.resultVar = resultVar; - setMethodReference(methRef); - makeParentRoleValid(); + this.resultVar = resultVar; + setMethodReference(methRef); + makeParentRoleValid(); } - + /** - * Set the exact Class the denoted method body is from. + * Set the exact Class the denoted method body is from. */ - + public void setBodySource(TypeReference bodySource) { - this.bodySource = bodySource; + this.bodySource = bodySource; } /** - * Get the exact Class the denoted method body is from. - * @returns the TypeReference + * Get the exact Class the denoted method body is from. + * + * @returns the TypeReference */ - + public TypeReference getBodySource() { - return bodySource; + return bodySource; } /** - * Set the result variable. - * @param resultVar the Expression used as result variable + * Set the result variable. + * + * @param resultVar the Expression used as result variable */ - + public void setResultVariable(Expression resultVar) { - this.resultVar = resultVar; + this.resultVar = resultVar; } /** - * Get the result variable. - * @return the VariableReference + * Get the result variable. + * + * @return the VariableReference */ - + public Expression getResultVariable() { - return resultVar; + return resultVar; } /** - * Set the MethodReference that caused this call. + * Set the MethodReference that caused this call. */ - public void setMethodReference(MethodReference methRef) { + public void setMethodReference(MethodReference methRef) { this.methodName = methRef.getIdentifier(); this.methodReferencePrefix = methRef.getReferencePrefix(); this.arguments = methRef.getArguments(); } public NonTerminalProgramElement getASTParent() { - return astParent; + return astParent; } public StatementContainer getStatementContainer() { - return astParent; + return astParent; } public void setStatementContainer(StatementContainer parent) { - astParent = parent; + astParent = parent; } /** - * Finds the source element that occurs first in the source. - * @return the last source element in the syntactical representation of - * this element, may be equals to this element. + * Finds the source element that occurs first in the source. + * + * @return the last source element in the syntactical representation of this element, may be + * equals to this element. */ - + public SourceElement getFirstElement() { return getChildAt(0).getFirstElement(); } /** - * 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. + * 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. */ - + 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 (bodySource != null) result++; - if (resultVar != null) result++; - if (methodReferencePrefix != null) result++; - if (methodName != null) result++; - if (arguments != null) result += arguments.size(); + if (bodySource != null) + result++; + if (resultVar != null) + result++; + if (methodReferencePrefix != null) + result++; + if (methodName != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ - + public ProgramElement getChildAt(int index) { if (bodySource != null) { - if (index == 0) return bodySource; + if (index == 0) + return bodySource; index--; } if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; } if (methodReferencePrefix != null) { - if (index == 0) return methodReferencePrefix; + if (index == 0) + return methodReferencePrefix; index--; } if (methodName != null) { - if (index == 0) return methodName; + if (index == 0) + return methodName; 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 statements. + * Get the number of type references in this container. + * + * @return the number of statements. */ public int getTypeReferenceCount() { @@ -194,12 +212,11 @@ public int getTypeReferenceCount() { } /** - * Return the type reference at the specified index in this node's - * "virtual" statement 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. + * Return the type reference at the specified index in this node's "virtual" statement 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. */ public TypeReference getTypeReferenceAt(int index) { @@ -208,18 +225,19 @@ public TypeReference getTypeReferenceAt(int index) { } 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; if (resultVar != null) { result++; - } + } if (arguments != null) { result += arguments.size(); } @@ -227,70 +245,68 @@ public int getExpressionCount() { } /** - * Return the expression at the specified index in this node's - * "virtual" expression array. - * @param index an index for a 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 a expression. + * @return the expression with the given index. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; - } + } if (arguments != null) { return arguments.get(index); - } + } throw new ArrayIndexOutOfBoundsException(); } /** - * Replace a single child in the current node. - * The child to replace is matched by identity and hence must be known - * exactly. The replacement element can be null - in that case, the child - * is effectively removed. - * The parent role of the new child is validated, while the - * parent link of the replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * * @param p the old child. * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException if the new child cannot take over - * the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { - if (p == null) throw new NullPointerException(); + if (p == null) + throw new NullPointerException(); if (bodySource == p) { - TypeReference r = (TypeReference)q; + TypeReference r = (TypeReference) q; bodySource = r; if (r != null) { r.setParent(this); } return true; - } - else if (resultVar == p) { - Expression r = (Expression)q; + } else if (resultVar == p) { + Expression r = (Expression) q; resultVar = r; if (r != null) { r.setExpressionContainer(this); } return true; - } else if (methodReferencePrefix == p) { + } else if (methodReferencePrefix == p) { ReferencePrefix rp = (ReferencePrefix) q; methodReferencePrefix = rp; return true; } else if (methodName == p) { - Identifier id = (Identifier)q; - methodName = id; + Identifier id = (Identifier) q; + methodName = id; return true; - } else { + } else { for (int i = 0; i < arguments.size(); i++) { if (arguments.get(i) == p) { if (q == null) { arguments.remove(i); } else { - Expression r = (Expression)q; + Expression r = (Expression) q; arguments.set(i, r); r.setExpressionContainer(this); } @@ -298,16 +314,16 @@ else if (resultVar == p) { } } } - + return false; } - + /** - * Ensures that each child has "this" as syntactical parent. + * Ensures that each child has "this" as syntactical parent. */ public void makeParentRoleValid() { - //TODO weigl makes no sense super.makeParentRoleValid(); + // TODO weigl makes no sense super.makeParentRoleValid(); // super.... is abstract if (bodySource != null) { @@ -317,32 +333,32 @@ public void makeParentRoleValid() { if (resultVar != null) { resultVar.setExpressionContainer(this); } - + if (methodName != null) { methodName.setParent(this); } - + if (methodReferencePrefix != null) { methodReferencePrefix.setReferenceSuffix(this); } - + if (arguments != null) { - for (int i = 0, sz = arguments.size(); iindex 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ - + public ProgramElement getChildAt(int index) { if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; } if (ec != null) { - if (index == 0) return ec; + if (index == 0) + return ec; index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; index--; } throw new ArrayIndexOutOfBoundsException(); @@ -193,8 +208,9 @@ public int getChildPositionCode(ProgramElement child) { } /** - * 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() { @@ -203,12 +219,11 @@ public int getStatementCount() { } /** - * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Statement getStatementAt(int index) { @@ -217,11 +232,12 @@ public Statement getStatementAt(int index) { } 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() { @@ -229,12 +245,11 @@ public int getExpressionCount() { } /** - * Return the expression at the specified index in this node's - * "virtual" expression array. - * @param index an index for a 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 a expression. + * @return the expression with the given index. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { @@ -245,38 +260,33 @@ public Expression getExpressionAt(int index) { } /** - * Replace a single child in the current node. - * The child to replace is matched by identity and hence must be known - * exactly. The replacement element can be null - in that case, the child - * is effectively removed. - * The parent role of the new child is validated, while the - * parent link of the replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * * @param p the old child. * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException if the new child cannot take over - * the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { - if (resultVar == p) - { - Expression r = (Expression)q; + if (resultVar == p) { + Expression r = (Expression) q; resultVar = r; if (r != null) { r.setExpressionContainer(this); } return true; - } - else if (ec == p) { - ec = (ExecutionContext)q; + } else if (ec == p) { + ec = (ExecutionContext) q; if (ec != null) { ec.setParent(this); } return true; - } - else if (body == p) { - Statement r = (Statement)q; + } else if (body == p) { + Statement r = (Statement) q; body = r; if (r != null) { r.setStatementContainer(this); @@ -285,12 +295,12 @@ else if (body == p) { } return false; } - + /** - * Ensures that each child has "this" as syntactical parent. + * Ensures that each child has "this" as syntactical parent. */ public void makeParentRoleValid() { - //TODO weigl: makes no sense: super.makeParentRoleValid(); + // TODO weigl: makes no sense: super.makeParentRoleValid(); if (resultVar != null) { resultVar.setExpressionContainer(this); } @@ -298,20 +308,20 @@ public void makeParentRoleValid() { ec.setParent(this); } if (body != null) { - body.setStatementContainer(this); + body.setStatementContainer(this); } } - //don't think we need it - public void accept(SourceVisitor v) { - } - + // don't think we need it + public void accept(SourceVisitor v) {} + /** * Deep clone. + * * @return the object */ public MethodCallStatement deepClone() { - return new MethodCallStatement(this); + return new MethodCallStatement(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodSignatureSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodSignatureSVWrapper.java index 602df7f88dd..77744305fa5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodSignatureSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/MethodSignatureSVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.java.recoderext.adt.MethodSignature; @@ -6,22 +9,22 @@ public class MethodSignatureSVWrapper extends MethodSignature implements SVWrapper { private static final long serialVersionUID = -4381850332826267659L; - private SchemaVariable method; - + private SchemaVariable method; + public MethodSignatureSVWrapper(SchemaVariable l) { - super(null, null); - method = l; + super(null, null); + method = l; } - - public SchemaVariable getSV() { + + public SchemaVariable getSV() { return method; } public void setSV(SchemaVariable sv) { - method = sv; + method = sv; } public String toString() { - return ""+method; + return "" + method; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Model.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Model.java index f9682671b76..6f012fbbc73 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Model.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Model.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -5,27 +8,25 @@ public class Model extends Modifier { - + /** - * + * */ private static final long serialVersionUID = -1997772798461795576L; - public Model() { - } - + public Model() {} + protected Model(Model proto) { super(proto); } - + public Model deepClone() { return new Model(this); } - - public void accept(SourceVisitor v) { - } - } \ No newline at end of file + + public void accept(SourceVisitor v) {} +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewArrayWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewArrayWrapper.java index 48ec2b893a5..b03cd6c55af 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewArrayWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewArrayWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; @@ -6,22 +9,22 @@ public class NewArrayWrapper extends NewArray { /** - * + * */ private static final long serialVersionUID = -3838799869300845065L; private Identifier scope; - - public NewArrayWrapper(NewArray proto, Identifier scope){ + + public NewArrayWrapper(NewArray proto, Identifier scope) { super(proto); this.scope = scope; } - - public NewArrayWrapper deepClone(){ - return new NewArrayWrapper(super.deepClone(), scope==null ? null : scope.deepClone()); + + public NewArrayWrapper deepClone() { + return new NewArrayWrapper(super.deepClone(), scope == null ? null : scope.deepClone()); } - - public Identifier getScope(){ + + public Identifier getScope() { return scope; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewWrapper.java index 895e616cdb4..72f00974191 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NewWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; @@ -6,22 +9,22 @@ public class NewWrapper extends New { /** - * + * */ private static final long serialVersionUID = -2814303467813768233L; private Identifier scope; - - public NewWrapper(New proto, Identifier scope){ + + public NewWrapper(New proto, Identifier scope) { super(proto); this.scope = scope; } - - public NewWrapper deepClone(){ - return new NewWrapper(super.deepClone(), scope==null ? null : scope.deepClone()); + + public NewWrapper deepClone() { + return new NewWrapper(super.deepClone(), scope == null ? null : scope.deepClone()); } - - public Identifier getScope(){ + + public Identifier getScope() { return scope; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NoState.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NoState.java index fd47515b34a..6363d95779d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NoState.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/NoState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -8,8 +11,7 @@ public class NoState extends Modifier { private static final long serialVersionUID = 2717863742463891263L; - public NoState() { - } + public NoState() {} protected NoState(NoState proto) { @@ -20,7 +22,6 @@ public NoState deepClone() { return new NoState(this); } - public void accept(SourceVisitor v) { - } + public void accept(SourceVisitor v) {} } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ObjectTypeIdentifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ObjectTypeIdentifier.java index 5a6ef7f0098..f9e2f39027c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ObjectTypeIdentifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ObjectTypeIdentifier.java @@ -1,11 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; public class ObjectTypeIdentifier extends Identifier { - + /** - * + * */ private static final long serialVersionUID = -2181868786991278019L; @@ -13,17 +16,18 @@ public ObjectTypeIdentifier(String id) { super(id); } - //protected void setText(String text) { - //id = text.intern(); - //} - + // protected void setText(String text) { + // id = text.intern(); + // } + /** * Deep clone. + * * @return the object. */ - + public ObjectTypeIdentifier deepClone() { return new ObjectTypeIdentifier(id); } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PassiveExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PassiveExpression.java index c447834364a..f4c63554128 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PassiveExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PassiveExpression.java @@ -1,15 +1,17 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Expression; import recoder.java.expression.ParenthesizedExpression; -public class PassiveExpression - extends ParenthesizedExpression { +public class PassiveExpression extends ParenthesizedExpression { + - /** - * + * */ private static final long serialVersionUID = 4916068787633267648L; @@ -17,21 +19,21 @@ public class PassiveExpression * creates a newly generated passive expression */ public PassiveExpression() { - super(); + super(); } /** * creates a newly generated passive expression */ public PassiveExpression(Expression e) { - super(e); + super(e); } public PassiveExpression(PassiveExpression proto) { - super(proto); + super(proto); } - + public PassiveExpression deepClone() { - return new PassiveExpression(this); + return new PassiveExpression(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PrepareObjectBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PrepareObjectBuilder.java index 21b3187f640..c555dc5e75e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PrepareObjectBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/PrepareObjectBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.util.Debug; @@ -24,40 +27,33 @@ import java.util.List; /** - * Creates the preparation method for pre-initilizing the object fields - * with their default settings. + * Creates the preparation method for pre-initilizing the object fields with their default settings. */ -public class PrepareObjectBuilder - extends RecoderModelTransformer { +public class PrepareObjectBuilder extends RecoderModelTransformer { - public static final String - IMPLICIT_OBJECT_PREPARE = ""; + public static final String IMPLICIT_OBJECT_PREPARE = ""; - public static final String - IMPLICIT_OBJECT_PREPARE_ENTER = ""; + public static final String IMPLICIT_OBJECT_PREPARE_ENTER = ""; private final HashMap> class2fields; private ClassType javaLangObject; - public PrepareObjectBuilder - (CrossReferenceServiceConfiguration services, - TransformerCache cache) { + public PrepareObjectBuilder(CrossReferenceServiceConfiguration services, + TransformerCache cache) { super(services, cache); class2fields = new LinkedHashMap<>(getUnits().size()); } /** - * 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. + * 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(ClassDeclaration cd) { List result = new ArrayList<>(cd.getChildCount()); - outer: - for (int i = 0; i < cd.getChildCount(); i++) { + outer: for (int i = 0; i < cd.getChildCount(); i++) { if (cd.getChildAt(i) instanceof FieldDeclaration) { final FieldDeclaration fd = (FieldDeclaration) cd.getChildAt(i); for (Modifier mod : fd.getModifiers()) { @@ -65,26 +61,23 @@ private List getFields(ClassDeclaration cd) { continue outer; } } - final ASTList fields - = fd.getFieldSpecifications(); - result.addAll(fields); + final ASTList fields = fd.getFieldSpecifications(); + result.addAll(fields); } } return result; } /** - * Two-pass transformation have to be strictly divided up into two - * parts. the first part analyzes the model and collects all - * necessary information. In this case all class declarations are - * examined and for each found field a copy assignment to its - * default value is added to the map "class2fields". - * All actions, which may cause a recoder model update have to be - * done here. + * Two-pass transformation have to be strictly divided up into two parts. the first part + * analyzes the model and collects all necessary information. In this case all class + * declarations are examined and for each found field a copy assignment to its default value is + * added to the map "class2fields". All actions, which may cause a recoder model update have to + * be done here. * * @return status report if analyze encountered problems or not */ - @Override + @Override public ProblemReport analyze() { javaLangObject = services.getNameInfo().getJavaLangObject(); if (!(javaLangObject instanceof ClassDeclaration)) { @@ -98,8 +91,8 @@ public ProblemReport analyze() { } /** - * creates the assignments of the field variables to their default values - * and inserts them to the given body list + * 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 */ @@ -114,11 +107,8 @@ private ASTList defaultSettings(List fields) { Identifier fieldId; if (field.getName().charAt(0) != '<') { fieldId = new Identifier(field.getName()); - result.add - (assign((attribute(new ThisReference(), fieldId)), - getDefaultValue - (services. - getCrossReferenceSourceInfo().getType(field)))); + result.add(assign((attribute(new ThisReference(), fieldId)), getDefaultValue( + services.getCrossReferenceSourceInfo().getType(field)))); } } } @@ -127,62 +117,51 @@ private ASTList defaultSettings(List fields) { } /** - * creates an implicit method called 'prepare', that sets all - * attributes to their default values + * creates an implicit method called 'prepare', that sets all attributes to their default values */ protected StatementBlock createPrepareBody(ReferencePrefix prefix, TypeDeclaration classType) { ASTList body = new ASTArrayList<>(15); if (classType != javaLangObject) { // we can access the implementation - body.add((new MethodReference( - new SuperReference(), new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE)))); + body.add((new MethodReference(new SuperReference(), + new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE)))); body.addAll(class2fields.get(classType)); } return new StatementBlock(body); } /** - * creates the implicit <prepare> method that - * sets the fields of the given type to its default values + * 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 + * @param type the TypeDeclaration for which the <prepare> is created * @return the implicit <prepare> method */ public MethodDeclaration createMethod(TypeDeclaration type) { ASTList modifiers = new ASTArrayList<>(1); modifiers.add(new Protected()); - MethodDeclaration md = new MethodDeclaration - (modifiers, - null, - new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE), - new ASTArrayList<>(0), - null, - createPrepareBody(new ThisReference(), type)); + MethodDeclaration md = new MethodDeclaration(modifiers, null, + new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE), new ASTArrayList<>(0), null, + createPrepareBody(new ThisReference(), type)); md.makeAllParentRolesValid(); return md; } /** - * creates the implicit <prepareEnter> method that - * sets the fields of the given type to its default values + * 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 + * @param type the TypeDeclaration for which the <prepare> is created * @return the implicit <prepare> method */ public MethodDeclaration createMethodPrepareEnter(TypeDeclaration type) { ASTList modifiers = new ASTArrayList<>(1); modifiers.add(new Private()); - MethodDeclaration md = new MethodDeclaration - (modifiers, - null, - new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE_ENTER), - new ASTArrayList<>(0), - null, - createPrepareBody(new ThisReference(), type)); + MethodDeclaration md = new MethodDeclaration(modifiers, null, + new ImplicitIdentifier(IMPLICIT_OBJECT_PREPARE_ENTER), new ASTArrayList<>(0), null, + createPrepareBody(new ThisReference(), type)); md.makeAllParentRolesValid(); return md; } @@ -200,4 +179,4 @@ protected void makeExplicit(TypeDeclaration td) { } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProgramVariableSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProgramVariableSVWrapper.java index bb139a3627c..0b098a47700 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProgramVariableSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProgramVariableSVWrapper.java @@ -1,19 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.Identifier; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class ProgramVariableSVWrapper extends Identifier - implements KeYRecoderExtension, SVWrapper{ +public class ProgramVariableSVWrapper extends Identifier implements KeYRecoderExtension, SVWrapper { /** - * + * */ private static final long serialVersionUID = 8398356228769806560L; - SchemaVariable sv=null; + SchemaVariable sv = null; public ProgramVariableSVWrapper(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } protected ProgramVariableSVWrapper(ProgramVariableSVWrapper proto) { @@ -22,19 +24,20 @@ protected ProgramVariableSVWrapper(ProgramVariableSVWrapper proto) { /** * sets the schema variable of sort label - * @param sv the SchemaVariable + * + * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns the schema variable of this type sv wrapper */ public SchemaVariable getSV() { - return sv; + return sv; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofCrossReferenceServiceConfiguration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofCrossReferenceServiceConfiguration.java index 6c53f90fe84..bd557a43932 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofCrossReferenceServiceConfiguration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofCrossReferenceServiceConfiguration.java @@ -1,19 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is part of the RECODER library and protected by the LGPL. package de.uka.ilkd.key.java.recoderext; import recoder.ProgramFactory; import de.uka.ilkd.key.util.KeYRecoderExcHandler; -public class ProofCrossReferenceServiceConfiguration - extends KeYCrossReferenceServiceConfiguration { +public class ProofCrossReferenceServiceConfiguration extends KeYCrossReferenceServiceConfiguration { public ProofCrossReferenceServiceConfiguration(KeYRecoderExcHandler keh) { - super(keh); + super(keh); } /** we need another factory for some new program elements */ protected ProgramFactory makeProgramFactory() { - return ProofJavaProgramFactory.getInstance(); + return ProofJavaProgramFactory.getInstance(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofJavaProgramFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofJavaProgramFactory.java index 5b35b0d6e8e..442e9bfcccd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofJavaProgramFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/ProofJavaProgramFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is partially taken from the RECODER library, which is protected by // the LGPL, and modified. @@ -35,18 +38,17 @@ public class ProofJavaProgramFactory extends JavaProgramFactory { /** - Protected constructor - use {@link #getInstance} instead. + * Protected constructor - use {@link #getInstance} instead. */ protected ProofJavaProgramFactory() {} /** - The singleton instance of the program factory. + * The singleton instance of the program factory. */ - private static ProofJavaProgramFactory theFactory - = new ProofJavaProgramFactory(); + private static ProofJavaProgramFactory theFactory = new ProofJavaProgramFactory(); /** - Returns the single instance of this class. + * Returns the single instance of this class. */ public static JavaProgramFactory getInstance() { return theFactory; @@ -55,22 +57,22 @@ public static JavaProgramFactory getInstance() { @Override public void initialize(ServiceConfiguration cfg) { - super.initialize(cfg); - ProjectSettings settings = cfg.getProjectSettings(); - /*// that is the original recoder code: - ProofJavaParser.setAwareOfAssert(StringUtils.parseBooleanProperty(settings.getProperties().getProperty( - PropertyNames.JDK1_4))); - ProofJavaParser.setJava5(ALLOW_JAVA5); - */ - ProofJavaParser.setJava5(StringUtils.parseBooleanProperty(settings.getProperties().getProperty( - PropertyNames.JAVA_5))); - ProofJavaParser.setAwareOfAssert(true); + super.initialize(cfg); + ProjectSettings settings = cfg.getProjectSettings(); + /* + * // that is the original recoder code: + * ProofJavaParser.setAwareOfAssert(StringUtils.parseBooleanProperty(settings.getProperties( + * ).getProperty( PropertyNames.JDK1_4))); ProofJavaParser.setJava5(ALLOW_JAVA5); + */ + ProofJavaParser.setJava5(StringUtils + .parseBooleanProperty(settings.getProperties().getProperty(PropertyNames.JAVA_5))); + ProofJavaParser.setAwareOfAssert(true); - } + } /** - For internal reuse and synchronization. + * For internal reuse and synchronization. */ private static final ProofJavaParser parser = new ProofJavaParser(System.in); @@ -84,14 +86,15 @@ private static void attachComment(Comment c, ProgramElement pe) { NonTerminalProgramElement ppe = dest.getASTParent(); int i = 0; if (ppe != null) { - for (; ppe.getChildAt(i) != dest; i++) {} + for (; ppe.getChildAt(i) != dest; i++) { + } } if (i == 0) { // before syntactical parent - c.setPrefixed(true); + c.setPrefixed(true); } else { dest = ppe.getChildAt(i - 1); while (dest instanceof NonTerminalProgramElement) { - ppe = (NonTerminalProgramElement)dest; + ppe = (NonTerminalProgramElement) dest; i = ppe.getChildCount(); if (i == 0) { break; @@ -115,10 +118,8 @@ private static void attachComment(Comment c, ProgramElement pe) { } // appends all comments with pos < endPos to the end of the last a block - private static int appendComments(ProgramElement last, - List comments, - int commentIndex, - Position endPos) { + private static int appendComments(ProgramElement last, List comments, int commentIndex, + Position endPos) { int commentCount = comments.size(); while (commentIndex < commentCount) { @@ -129,12 +130,12 @@ private static int appendComments(ProgramElement last, return commentIndex; } - if ( ! current.getText().contains("@")) { + if (!current.getText().contains("@")) { // "pure" comment without @ (we only need JML annotations) // place it somewhere, doesn't matter current.setPrefixed(true); attachComment(current, last); - commentIndex +=1; + commentIndex += 1; continue; } @@ -198,14 +199,13 @@ private static void makeParentRolesValid(ProgramElement programElem) { while (tw.next()) { ProgramElement pe = tw.getProgramElement(); if (pe instanceof NonTerminalProgramElement) { - ((NonTerminalProgramElement)pe).makeParentRoleValid(); + ((NonTerminalProgramElement) pe).makeParentRoleValid(); } } } /** - Perform post work on the created element. Creates parent links - and assigns comments. + * Perform post work on the created element. Creates parent links and assigns comments. */ private static void postWork(ProgramElement programElem) { makeParentRolesValid(programElem); @@ -280,182 +280,184 @@ private static void postWork(ProgramElement programElem) { } /** - Parse a {@link CompilationUnit} from the given reader. + * Parse a {@link CompilationUnit} from the given reader. */ @Override public CompilationUnit parseCompilationUnit(Reader in) throws IOException, ParserException { - synchronized(parser) { - try { - ProofJavaParser.initialize(in); - CompilationUnit res = ProofJavaParser.CompilationUnit(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + CompilationUnit res = ProofJavaParser.CompilationUnit(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link TypeDeclaration} from the given reader. + * Parse a {@link TypeDeclaration} from the given reader. */ @Override public TypeDeclaration parseTypeDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - TypeDeclaration res = ProofJavaParser.TypeDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + TypeDeclaration res = ProofJavaParser.TypeDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link FieldDeclaration} from the given reader. + * Parse a {@link FieldDeclaration} from the given reader. */ @Override public FieldDeclaration parseFieldDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - FieldDeclaration res = ProofJavaParser.FieldDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + FieldDeclaration res = ProofJavaParser.FieldDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link MethodDeclaration} from the given reader. + * Parse a {@link MethodDeclaration} from the given reader. */ @Override public MethodDeclaration parseMethodDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - MethodDeclaration res = ProofJavaParser.MethodDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + MethodDeclaration res = ProofJavaParser.MethodDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link MemberDeclaration} from the given reader. + * Parse a {@link MemberDeclaration} from the given reader. */ @Override public MemberDeclaration parseMemberDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - MemberDeclaration res = ProofJavaParser.ClassBodyDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + MemberDeclaration res = ProofJavaParser.ClassBodyDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link ParameterDeclaration} from the given reader. + * Parse a {@link ParameterDeclaration} from the given reader. */ @Override - public ParameterDeclaration parseParameterDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - ParameterDeclaration res = ProofJavaParser.FormalParameter(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + public ParameterDeclaration parseParameterDeclaration(Reader in) + throws IOException, ParserException { + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + ParameterDeclaration res = ProofJavaParser.FormalParameter(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link ConstructorDeclaration} from the given reader. + * Parse a {@link ConstructorDeclaration} from the given reader. */ @Override - public ConstructorDeclaration parseConstructorDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - ConstructorDeclaration res = ProofJavaParser.ConstructorDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + public ConstructorDeclaration parseConstructorDeclaration(Reader in) + throws IOException, ParserException { + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + ConstructorDeclaration res = ProofJavaParser.ConstructorDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse a {@link TypeReference} from the given reader. + * Parse a {@link TypeReference} from the given reader. */ @Override public TypeReference parseTypeReference(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - TypeReference res = ProofJavaParser.ResultType(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + TypeReference res = ProofJavaParser.ResultType(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse an {@link Expression} from the given reader. + * Parse an {@link Expression} from the given reader. */ @Override public Expression parseExpression(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - Expression res = ProofJavaParser.Expression(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + Expression res = ProofJavaParser.Expression(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } /** - Parse some {@link Statement}s from the given reader. + * Parse some {@link Statement}s from the given reader. */ @Override public ASTList parseStatements(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - ASTList res = ProofJavaParser.GeneralizedStatements(); - for (int i = 0; i < res.size(); i += 1) { - postWork(res.get(i)); - } - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + ASTList res = ProofJavaParser.GeneralizedStatements(); + for (int i = 0; i < res.size(); i += 1) { + postWork(res.get(i)); + } + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } @@ -464,17 +466,16 @@ public ASTList parseStatements(Reader in) throws IOException, ParserE * Parse a {@link StatementBlock} from the given string. */ @Override - public StatementBlock parseStatementBlock(Reader in) - throws IOException, ParserException { - synchronized(parser) { - try{ - ProofJavaParser.initialize(in); - StatementBlock res = ProofJavaParser.StartBlock(); - postWork(res); - return res; - } catch (ParseException e) { - throw (ParserException) (new ParserException(e.getMessage())).initCause(e); - } + public StatementBlock parseStatementBlock(Reader in) throws IOException, ParserException { + synchronized (parser) { + try { + ProofJavaParser.initialize(in); + StatementBlock res = ProofJavaParser.StartBlock(); + postWork(res); + return res; + } catch (ParseException e) { + throw (ParserException) (new ParserException(e.getMessage())).initCause(e); + } } } @@ -483,31 +484,30 @@ public StatementBlock parseStatementBlock(Reader in) * Create a {@link PassiveExpression}. */ public PassiveExpression createPassiveExpression(Expression e) { - return new PassiveExpression(e); + return new PassiveExpression(e); } /** * Create a {@link PassiveExpression}. */ public PassiveExpression createPassiveExpression() { - return new PassiveExpression(); + return new PassiveExpression(); } /** * Create a {@link MethodSignature}. */ public MethodSignature createMethodSignature(Identifier methodName, - ASTList paramTypes) { - return new MethodSignature(methodName, paramTypes); + ASTList paramTypes) { + return new MethodSignature(methodName, paramTypes); } /** * Create a {@link MethodCallStatement}. */ - public MethodCallStatement createMethodCallStatement(Expression resVar, - ExecutionContext ec, - StatementBlock block) { - return new MethodCallStatement(resVar, ec, block); + public MethodCallStatement createMethodCallStatement(Expression resVar, ExecutionContext ec, + StatementBlock block) { + return new MethodCallStatement(resVar, ec, block); } public LoopScopeBlock createLoopScopeBlock() { @@ -526,21 +526,20 @@ public MergePointStatement createMergePointStatement(Expression expr) { * Create a {@link MethodBodyStatement}. */ public MethodBodyStatement createMethodBodyStatement(TypeReference bodySource, - Expression resVar, - MethodReference methRef) { - return new MethodBodyStatement(bodySource, resVar, methRef); + Expression resVar, MethodReference methRef) { + return new MethodBodyStatement(bodySource, resVar, methRef); } /** * Create a {@link CatchAllStatement}. */ - public Statement createCatchAllStatement(VariableReference param, - StatementBlock body) { - return new CatchAllStatement(param, body); + public Statement createCatchAllStatement(VariableReference param, StatementBlock body) { + return new CatchAllStatement(param, body); } /** * Create a comment. + * * @param text comment text */ @Override @@ -550,6 +549,7 @@ public Comment createComment(String text) { /** * Create a comment. + * * @param text comment text */ @Override @@ -607,7 +607,8 @@ public CcatchBreakParameterDeclaration createCcatchBreakParameterDeclaration() { return new CcatchBreakParameterDeclaration(); } - public CcatchBreakLabelParameterDeclaration createCcatchBreakLabelParameterDeclaration(Identifier label) { + public CcatchBreakLabelParameterDeclaration createCcatchBreakLabelParameterDeclaration( + Identifier label) { return new CcatchBreakLabelParameterDeclaration(label); } @@ -619,7 +620,8 @@ public CcatchContinueParameterDeclaration createCcatchContinueParameterDeclarati return new CcatchContinueParameterDeclaration(); } - public CcatchContinueLabelParameterDeclaration createCcatchContinueLabelParameterDeclaration(Identifier label) { + public CcatchContinueLabelParameterDeclaration createCcatchContinueLabelParameterDeclaration( + Identifier label) { return new CcatchContinueLabelParameterDeclaration(label); } @@ -627,7 +629,8 @@ public CcatchContinueWildcardParameterDeclaration createCcatchContinueWildcardPa return new CcatchContinueWildcardParameterDeclaration(); } - public CcatchNonstandardParameterDeclaration createCcatchReturnValParameterDeclaration(ParameterDeclaration e) { + public CcatchNonstandardParameterDeclaration createCcatchReturnValParameterDeclaration( + ParameterDeclaration e) { return new CcatchReturnValParameterDeclaration(e); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstruct.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstruct.java index 318bb1b945f..957aaeba9b6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstruct.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstruct.java @@ -1,8 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is taken from the RECODER library, which is protected by the LGPL, // and modified. -/** This class is part of the AST RECODER builds when it parses and resolves Java - * programs with meta constructs and schema variables. It is transformed by Recoder2KeY - * to a subclass of ...rule.metaconstruct.ProgramMetaConstruct. +/** + * This class is part of the AST RECODER builds when it parses and resolves Java programs with meta + * constructs and schema variables. It is transformed by Recoder2KeY to a subclass of + * ...rule.metaconstruct.ProgramMetaConstruct. */ package de.uka.ilkd.key.java.recoderext; @@ -19,26 +23,27 @@ import recoder.java.statement.JavaStatement; import de.uka.ilkd.key.logic.op.ProgramSV; -public class RKeYMetaConstruct extends JavaStatement - implements StatementContainer, KeYRecoderExtension { +public class RKeYMetaConstruct extends JavaStatement + implements StatementContainer, KeYRecoderExtension { /** - * + * */ private static final long serialVersionUID = -2616618524631193660L; /** - Child + * Child */ - protected Statement child=null; - protected String name=""; + protected Statement child = null; + protected String name = ""; /** schemavariable needed by meta construct */ - private List sv = new Vector(); //of ProgramVariableSVWrapper + private List sv = new Vector(); // of ProgramVariableSVWrapper /** - Loop statement. - @param proto a loop statement. + * Loop statement. + * + * @param proto a loop statement. */ protected RKeYMetaConstruct(RKeYMetaConstruct proto) { @@ -48,11 +53,10 @@ protected RKeYMetaConstruct(RKeYMetaConstruct proto) { } } - public RKeYMetaConstruct() { - } + public RKeYMetaConstruct() {} /** - Make parent role valid. + * Make parent role valid. */ public void makeParentRoleValid() { super.makeParentRoleValid(); @@ -62,26 +66,28 @@ public void makeParentRoleValid() { } /** - 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 (child != null) result++; + if (child != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (child != null) { - if (index == 0) return child; + if (index == 0) + return child; } throw new ArrayIndexOutOfBoundsException(); } @@ -97,22 +103,20 @@ public int getChildPositionCode(ProgramElement child0) { /** - * Replace a single child in the current node. - * The child to replace is matched by identity and hence must be known - * exactly. The replacement element can be null - in that case, the child - * is effectively removed. - * The parent role of the new child is validated, while the - * parent link of the replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * * @param p the old child. * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException if the new child cannot take over - * the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { if (child == p) { - Statement r = (Statement)q; + Statement r = (Statement) q; child = r; if (r != null) { r.setStatementContainer(this); @@ -125,23 +129,25 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { /** * sets a String name of this meta construct like 'unwind-loop' + * * @param s the String */ public void setName(String s) { - name=s; + name = s; } /** * returns a String name of this meta construct. */ public String getName() { - return name; + return name; } /** - Get child. - @return the statement. + * Get child. + * + * @return the statement. */ public Statement getChild() { @@ -149,8 +155,9 @@ public Statement getChild() { } /** - Set child. - @param statement a statement. + * Set child. + * + * @param statement a statement. */ public void setChild(Statement statement) { @@ -159,19 +166,21 @@ public void setChild(Statement statement) { /** * first schemavariable needed by the metaconstruct + * * @param sv an SVWrapper containing the first Schemavariable */ public void setSV(SVWrapper sv) { - this.sv.add(0,sv); + this.sv.add(0, sv); } public void addSV(SVWrapper svw) { - this.sv.add(svw); + this.sv.add(svw); } /** * first schemavariable needed by the metaconstruct + * * @return first schemavariable needed by the metaconstruct */ public SVWrapper getFirstSV() { @@ -179,18 +188,19 @@ public SVWrapper getFirstSV() { } public ProgramSV[] getSV() { - ProgramSV[] res = new ProgramSV[sv.size()]; - Iterator it = sv.iterator(); - int i=0; - while (it.hasNext()) { - res[i++]=(ProgramSV)it.next().getSV(); - } - return res; + ProgramSV[] res = new ProgramSV[sv.size()]; + Iterator it = sv.iterator(); + int i = 0; + while (it.hasNext()) { + res[i++] = (ProgramSV) it.next().getSV(); + } + return res; } /** - 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() { @@ -198,13 +208,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (child != null && index == 0) { @@ -213,14 +224,13 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - //don't think we need it - public void accept(SourceVisitor v) { - } - - //??? + // don't think we need it + public void accept(SourceVisitor v) {} + + // ??? public JavaStatement deepClone() { - return null; + return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructExpression.java index ad794719619..efc78ae3fd6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructExpression.java @@ -1,8 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is taken from the RECODER library, which is protected by the LGPL, // and modified. -/** This class is part of the AST RECODER builds when it parses and resolves Java - * programs with meta constructs and schema variables. It is transformed by Recoder2KeY - * to a subclass of ...rule.metaconstruct.ProgramMetaConstruct. +/** + * This class is part of the AST RECODER builds when it parses and resolves Java programs with meta + * constructs and schema variables. It is transformed by Recoder2KeY to a subclass of + * ...rule.metaconstruct.ProgramMetaConstruct. */ package de.uka.ilkd.key.java.recoderext; @@ -18,18 +22,18 @@ public class RKeYMetaConstructExpression extends Literal - implements ExpressionContainer, KeYRecoderExtension { + implements ExpressionContainer, KeYRecoderExtension { /** - * + * */ private static final long serialVersionUID = -145731902618445018L; /** - Child + * Child */ - protected Expression child=null; - protected String name=""; + protected Expression child = null; + protected String name = ""; protected RKeYMetaConstructExpression(RKeYMetaConstructExpression proto) { super(proto); @@ -38,11 +42,10 @@ protected RKeYMetaConstructExpression(RKeYMetaConstructExpression proto) { } } - public RKeYMetaConstructExpression() { - } + public RKeYMetaConstructExpression() {} /** - Make parent role valid. + * Make parent role valid. */ public void makeParentRoleValid() { if (child != null) { @@ -51,26 +54,28 @@ public void makeParentRoleValid() { } /** - 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 (child != null) result++; + if (child != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (child != null) { - if (index == 0) return child; + if (index == 0) + return child; } throw new ArrayIndexOutOfBoundsException(); } @@ -85,35 +90,36 @@ public int getChildPositionCode(ProgramElement child0) { } public int getIndexOfChild(ProgramElement pe) { - if (pe==child) { - return 0; - } - return -1; + if (pe == child) { + return 0; + } + return -1; } @Deprecated public int getIndexOfChild(int posCode) { - if (posCode==getChildPositionCode(child)) { - return 0; - } - return -1; + if (posCode == getChildPositionCode(child)) { + return 0; + } + return -1; } public int getRoleOfChild(int i) { - if (i==0) return getChildPositionCode(child); - return -1; + if (i == 0) + return getChildPositionCode(child); + return -1; } public void makeAllParentRolesValid() { - TreeWalker tw = new TreeWalker(this); + TreeWalker tw = new TreeWalker(this); while (tw.next(NonTerminalProgramElement.class)) { - ((NonTerminalProgramElement)tw.getProgramElement()).makeParentRoleValid(); + ((NonTerminalProgramElement) tw.getProgramElement()).makeParentRoleValid(); } } public boolean replaceChild(ProgramElement p, ProgramElement q) { if (child == p) { - Expression r = (Expression)q; + Expression r = (Expression) q; child = r; if (r != null) { r.setExpressionContainer(this); @@ -127,23 +133,25 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { /** * sets a String name of this meta construct like 'unwind-loop' + * * @param s the String */ public void setName(String s) { - name=s; + name = s; } /** * returns a String name of this meta construct. */ public String getName() { - return name; + return name; } /** - Get child. - @return the expression. + * Get child. + * + * @return the expression. */ public Expression getChild() { @@ -151,8 +159,9 @@ public Expression getChild() { } /** - Set child. - @param expression a expression. + * Set child. + * + * @param expression a expression. */ public void setChild(Expression expression) { @@ -160,8 +169,9 @@ public void setChild(Expression expression) { } /** - Get the number of expression in this container. - @return the number of expressions. + * Get the number of expression in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { @@ -169,13 +179,14 @@ public int getExpressionCount() { } /* - Return the expression at the specified index in this node's - "virtual" expression array. - @param index an index for a 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 a expression. + * + * @return the expression with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (child != null && index == 0) { @@ -184,25 +195,24 @@ public Expression getExpressionAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - //don't think we need it - public void accept(SourceVisitor v) { - } - - //??? + // don't think we need it + public void accept(SourceVisitor v) {} + + // ??? public Literal deepClone() { - return null; + return null; } - public void validateAll() throws ModelException { - // TODO Auto-generated method stub - throw new Error("mulbrich: Don't know what to do - yet"); - } + public void validateAll() throws ModelException { + // TODO Auto-generated method stub + throw new Error("mulbrich: Don't know what to do - yet"); + } - @Override - public Object getEquivalentJavaType() { - // TODO Auto-generated method stub - throw new Error("mulbrich: Don't know what to do - yet"); - } + @Override + public Object getEquivalentJavaType() { + // TODO Auto-generated method stub + throw new Error("mulbrich: Don't know what to do - yet"); + } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructType.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructType.java index 9942d681a33..43911739916 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RKeYMetaConstructType.java @@ -1,9 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is taken from the RECODER library, which is protected by the LGPL, // and modified. -/** This class is part of the AST RECODER builds when it parses and resolves Java - * programs with meta constructs and schema variables. It is transformed by - * SchemaRecoder2KeY - * to a subclass of ...rule.metaconstruct.ProgramMetaConstruct. +/** + * This class is part of the AST RECODER builds when it parses and resolves Java programs with meta + * constructs and schema variables. It is transformed by SchemaRecoder2KeY to a subclass of + * ...rule.metaconstruct.ProgramMetaConstruct. */ package de.uka.ilkd.key.java.recoderext; @@ -13,19 +16,18 @@ import recoder.java.SourceVisitor; import recoder.java.reference.TypeReference; -public class RKeYMetaConstructType extends TypeReference - implements KeYRecoderExtension { +public class RKeYMetaConstructType extends TypeReference implements KeYRecoderExtension { /** - * + * */ private static final long serialVersionUID = -8028793181207056503L; /** - Child + * Child */ - protected Expression child=null; - protected String myname=""; + protected Expression child = null; + protected String myname = ""; protected RKeYMetaConstructType(RKeYMetaConstructType proto) { super(proto); @@ -34,31 +36,32 @@ protected RKeYMetaConstructType(RKeYMetaConstructType proto) { } } - public RKeYMetaConstructType() { - } + public RKeYMetaConstructType() {} /** - 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 (child != null) result++; + if (child != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (child != null) { - if (index == 0) return child; + if (index == 0) + return child; } throw new ArrayIndexOutOfBoundsException(); } @@ -73,41 +76,44 @@ public int getChildPositionCode(ProgramElement child0) { } public int getIndexOfChild(ProgramElement pe) { - if (pe==child) { - return 0; - } - return -1; + if (pe == child) { + return 0; + } + return -1; } @Deprecated public int getIndexOfChild(int posCode) { - if (posCode==getChildPositionCode(child)) { - return 0; - } - return -1; + if (posCode == getChildPositionCode(child)) { + return 0; + } + return -1; } public int getRoleOfChild(int i) { - if (i==0) return getChildPositionCode(child); - return -1; + if (i == 0) + return getChildPositionCode(child); + return -1; } /** * sets a String myname of this meta construct like 'unwind-loop' + * * @param s the String */ public void setName(String s) { - myname=s; + myname = s; } public String getName0() { - return myname; + return myname; } /** - Get child. - @return the expression. + * Get child. + * + * @return the expression. */ public Expression getChild() { @@ -115,8 +121,9 @@ public Expression getChild() { } /** - Set child. - @param expression a expression. + * Set child. + * + * @param expression a expression. */ public void setChild(Expression expression) { @@ -124,8 +131,9 @@ public void setChild(Expression expression) { } /** - Get the number of expression in this container. - @return the number of expressions. + * Get the number of expression in this container. + * + * @return the number of expressions. */ public int getExpressionCount() { @@ -133,13 +141,14 @@ public int getExpressionCount() { } /* - Return the expression at the specified index in this node's - "virtual" expression array. - @param index an index for a 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 a expression. + * + * @return the expression with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (child != null && index == 0) { @@ -148,14 +157,13 @@ public Expression getExpressionAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - //don't think we need it - public void accept(SourceVisitor v) { - } - - //??? + // don't think we need it + public void accept(SourceVisitor v) {} + + // ??? public TypeReference deepClone() { - return null; + return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RMethodBodyStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RMethodBodyStatement.java index 0ff9a511a23..a42a062d7ac 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RMethodBodyStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RMethodBodyStatement.java @@ -1,8 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is taken from the RECODER library, which is protected by the LGPL, // and modified. -/** This class is part of the AST RECODER builds when it parses and resolves Java - * programs with meta constructs and schema variables. It is transformed by Recoder2KeY - * to a subclass of ...rule.metaconstruct.ProgramMetaConstruct. +/** + * This class is part of the AST RECODER builds when it parses and resolves Java programs with meta + * constructs and schema variables. It is transformed by Recoder2KeY to a subclass of + * ...rule.metaconstruct.ProgramMetaConstruct. */ package de.uka.ilkd.key.java.recoderext; @@ -21,34 +25,30 @@ import recoder.list.generic.ASTList; -public class RMethodBodyStatement extends JavaStatement - implements KeYRecoderExtension, TypeReferenceContainer, - ExpressionContainer, NamedProgramElement { +public class RMethodBodyStatement extends JavaStatement implements KeYRecoderExtension, + TypeReferenceContainer, ExpressionContainer, NamedProgramElement { /** - * + * */ private static final long serialVersionUID = -8427953809480454933L; - private TypeReference bodySource; + private TypeReference bodySource; private ProgramVariableSVWrapper resultVar; - + private ReferencePrefix methodReferencePrefix; - private Identifier methodName; + private Identifier methodName; private ASTList arguments; - public RMethodBodyStatement(TypeReference typeRef, - ProgramVariableSVWrapper resVar, - MethodReference mr) { + public RMethodBodyStatement(TypeReference typeRef, ProgramVariableSVWrapper resVar, + MethodReference mr) { this.bodySource = typeRef; this.resultVar = resVar; setMethodReference(mr); makeParentRoleValid(); } - public RMethodBodyStatement(TypeReference typeRef, - ProgramVariableSVWrapper resVar, - ReferencePrefix prefix, Identifier methodName, - ASTList arguments) { + public RMethodBodyStatement(TypeReference typeRef, ProgramVariableSVWrapper resVar, + ReferencePrefix prefix, Identifier methodName, ASTList arguments) { this.bodySource = typeRef; this.resultVar = resVar; this.methodReferencePrefix = prefix; @@ -57,76 +57,82 @@ public RMethodBodyStatement(TypeReference typeRef, makeParentRoleValid(); } - - public void accept(SourceVisitor visitor) { - } + + public void accept(SourceVisitor visitor) {} public RMethodBodyStatement deepClone() { - return new RMethodBodyStatement - (bodySource.deepClone(), - (ProgramVariableSVWrapper)resultVar.deepClone(), - (ReferencePrefix)methodReferencePrefix.deepClone(), - methodName.deepClone(), - arguments.deepClone()); + return new RMethodBodyStatement(bodySource.deepClone(), + (ProgramVariableSVWrapper) resultVar.deepClone(), + (ReferencePrefix) methodReferencePrefix.deepClone(), methodName.deepClone(), + arguments.deepClone()); } - + /** - * Set the MethodReference that caused this call. + * Set the MethodReference that caused this call. */ - public void setMethodReference(MethodReference methRef) { + public void setMethodReference(MethodReference methRef) { this.methodName = methRef.getIdentifier(); this.methodReferencePrefix = methRef.getReferencePrefix(); this.arguments = methRef.getArguments(); } - + /** - * 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 (bodySource != null) result++; - if (resultVar != null) result++; - if (methodReferencePrefix != null) result++; - if (methodName != null) result++; - if (arguments != null) result += arguments.size(); + if (bodySource != null) + result++; + if (resultVar != null) + result++; + if (methodReferencePrefix != null) + result++; + if (methodName != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ - + public ProgramElement getChildAt(int index) { if (bodySource != null) { - if (index == 0) return bodySource; + if (index == 0) + return bodySource; index--; } if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; } if (methodReferencePrefix != null) { - if (index == 0) return methodReferencePrefix; + if (index == 0) + return methodReferencePrefix; index--; } if (methodName != null) { - if (index == 0) return methodName; + if (index == 0) + return methodName; index--; } if (arguments != null) { - return arguments.get(index); + return arguments.get(index); } throw new ArrayIndexOutOfBoundsException(); } - + public int getChildPositionCode(ProgramElement child) { // role 0: bodySource // role 1: resultVar @@ -144,19 +150,19 @@ public int getChildPositionCode(ProgramElement child) { if (methodName == child) { return 3; } - - for (int i = 0, sz = arguments.size(); iindex 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; } if (ecsvw != null) { - if (index == 0) return ecsvw; + if (index == 0) + return ecsvw; index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; index--; } throw new ArrayIndexOutOfBoundsException(); @@ -102,7 +110,7 @@ public int getChildPositionCode(ProgramElement child) { return 0; } if (ecsvw == child) { - return 1; + return 1; } if (body == child) { return 2; @@ -111,8 +119,9 @@ public int getChildPositionCode(ProgramElement child) { } /** - * 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() { @@ -120,22 +129,20 @@ public int getStatementCount() { } /** - * Replace a single child in the current node. - * The child to replace is matched by identity and hence must be known - * exactly. The replacement element can be null - in that case, the child - * is effectively removed. - * The parent role of the new child is validated, while the - * parent link of the replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * * @param p the old child. * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException if the new child cannot take over - * the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { if (body == p) { - Statement r = (Statement)q; + Statement r = (Statement) q; body = r; if (r != null) { r.setStatementContainer(this); @@ -145,36 +152,38 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { return false; } - /** - Get child. - @return the statement. - */ + /** + * Get child. + * + * @return the statement. + */ - public Statement getChild() { - return body; - } + public Statement getChild() { + return body; + } - /** - Get body. - @return the statement. - */ + /** + * Get body. + * + * @return the statement. + */ - public Statement getBody() { - return body; - } + public Statement getBody() { + return body; + } -// /** -// Set child. -// @param statement a statement. -// */ + // /** + // Set child. + // @param statement a statement. + // */ -// public void setChild(Statement statement) { -// child = statement; -// } + // public void setChild(Statement statement) { + // child = statement; + // } /** - * schemavariable needed by the metaconstruct (needed by method-call) + * schemavariable needed by the metaconstruct (needed by method-call) */ public void setVariableSV(ProgramVariableSVWrapper sv) { this.resultVar = sv; @@ -184,21 +193,22 @@ public void setVariableSV(ProgramVariableSVWrapper sv) { public ProgramVariableSVWrapper getVariableSV() { return resultVar; } - + public ExecutionContext getExecutionContext() { - return ecsvw; + return ecsvw; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -207,14 +217,13 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - //don't think we need it - public void accept(SourceVisitor v) { - } - - //??? + // don't think we need it + public void accept(SourceVisitor v) {} + + // ??? public JavaStatement deepClone() { - return null; + return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Real.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Real.java index 8414f46b27a..ae9fc6c3834 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Real.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/Real.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.abstraction.PrimitiveType; @@ -5,6 +8,7 @@ /** * recoder extension for JML's \real type. + * * @author bruns * */ @@ -14,4 +18,4 @@ public Real(String name, ProgramModelInfo pmi) { super(name, pmi); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RecoderModelTransformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RecoderModelTransformer.java index 12035b38415..e94e6716c5d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RecoderModelTransformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RecoderModelTransformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.java.recoderext.adt.EmptyMapLiteral; @@ -21,22 +24,18 @@ import java.util.*; /** - * 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}
    • - *
    + * 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. + * 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 RecoderModelTransformer extends TwoPassTransformation { protected CrossReferenceServiceConfiguration services; @@ -45,14 +44,13 @@ public abstract class RecoderModelTransformer extends TwoPassTransformation { /** * creates a transormder for the recoder model * - * @param services the CrossReferenceServiceConfiguration to access - * model information - * @param cache 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. + * @param services the CrossReferenceServiceConfiguration to access model information + * @param cache 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. */ public RecoderModelTransformer(CrossReferenceServiceConfiguration services, - TransformerCache cache) { + TransformerCache cache) { super(services); this.services = services; this.cache = Objects.requireNonNull(cache); @@ -60,50 +58,50 @@ public RecoderModelTransformer(CrossReferenceServiceConfiguration services, } /** - * returns the default value of the given type - * according to JLS Sect. 4.5.5 + * 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 + * @return the default value of the given type according to JLS Sect. 4.5.5 */ public Expression getDefaultValue(Type type) { if (type instanceof ClassType || type instanceof ArrayType) { return new NullLiteral(); } else if (type instanceof PrimitiveType) { switch (type.getName()) { - case "boolean": - return new BooleanLiteral(false); - case "byte": - case "short": - case "int": - case "\\bigint": - return new IntLiteral(0); - case "long": - return new LongLiteral(0); - case "\\real": - return new RealLiteral(); - case "char": - return new CharLiteral((char) 0); - case "float": - return new FloatLiteral(0.0F); - case "double": - return new DoubleLiteral(0.0D); - case "\\locset": - return EmptySetLiteral.INSTANCE; - case "\\seq": - return EmptySeqLiteral.INSTANCE; - case "\\set": - return new DLEmbeddedExpression("emptySet", Collections.emptyList()); - case "\\free": - return new DLEmbeddedExpression("atom", Collections.emptyList()); - case "\\map": - return EmptyMapLiteral.INSTANCE; - default: - if (type.getName().startsWith("\\dl_")) { - //The default value of a type is resolved later, then we know the Sort of the type - return new DLEmbeddedExpression("\\dl_DEFAULT_VALUE_"+type.getName().substring(4), - Collections.emptyList()); - } + case "boolean": + return new BooleanLiteral(false); + case "byte": + case "short": + case "int": + case "\\bigint": + return new IntLiteral(0); + case "long": + return new LongLiteral(0); + case "\\real": + return new RealLiteral(); + case "char": + return new CharLiteral((char) 0); + case "float": + return new FloatLiteral(0.0F); + case "double": + return new DoubleLiteral(0.0D); + case "\\locset": + return EmptySetLiteral.INSTANCE; + case "\\seq": + return EmptySeqLiteral.INSTANCE; + case "\\set": + return new DLEmbeddedExpression("emptySet", Collections.emptyList()); + case "\\free": + return new DLEmbeddedExpression("atom", Collections.emptyList()); + case "\\map": + return EmptyMapLiteral.INSTANCE; + default: + if (type.getName().startsWith("\\dl_")) { + // The default value of a type is resolved later, then we know the Sort of the + // type + return new DLEmbeddedExpression( + "\\dl_DEFAULT_VALUE_" + type.getName().substring(4), + Collections.emptyList()); + } } } Debug.fail("makeImplicitMembersExplicit: unknown primitive type" + type); @@ -111,16 +109,13 @@ public Expression getDefaultValue(Type type) { } /** - * attaches a method declaration to the declaration of type td at - * position idx + * attaches a method declaration to the declaration of type td at position idx * - * @param md the MethodDeclaration to insert - * @param td the TypeDeclaration that becomes parent of the new - * method + * @param md the MethodDeclaration to insert + * @param td the TypeDeclaration that becomes parent of the new method * @param idx the position where to add the method */ - public void attach(MethodDeclaration md, TypeDeclaration td, - int idx) { + public void attach(MethodDeclaration md, TypeDeclaration td, int idx) { super.attach(md, td, idx); } @@ -135,17 +130,15 @@ public boolean isVisible() { } /** - * 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. + * 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. */ protected abstract void makeExplicit(TypeDeclaration td); // Java construction helper methods for recoder data structures - protected FieldReference attribute - (ReferencePrefix prefix, Identifier attributeName) { + protected FieldReference attribute(ReferencePrefix prefix, Identifier attributeName) { return new FieldReference(prefix, attributeName); } @@ -154,18 +147,13 @@ protected CopyAssignment assign(Expression lhs, Expression rhs) { return new CopyAssignment(lhs, rhs); } - protected LocalVariableDeclaration declare - (String name, ClassType type) { - return new LocalVariableDeclaration - (new TypeReference(new Identifier(type.getName())), - new Identifier(name)); + protected LocalVariableDeclaration declare(String name, ClassType type) { + return new LocalVariableDeclaration(new TypeReference(new Identifier(type.getName())), + new Identifier(name)); } - protected LocalVariableDeclaration declare - (String name, Identifier type) { - return new LocalVariableDeclaration - (new TypeReference(type), - new Identifier(name)); + protected LocalVariableDeclaration declare(String name, Identifier type) { + return new LocalVariableDeclaration(new TypeReference(type), new Identifier(name)); } protected Identifier getId(TypeDeclaration td) { @@ -174,9 +162,9 @@ protected Identifier getId(TypeDeclaration td) { } final ClassType firstActualSupertype = getAllSupertypes(td).get(1); - return firstActualSupertype instanceof TypeDeclaration ? - getId((TypeDeclaration) firstActualSupertype) : - new Identifier(firstActualSupertype.getName()); + return firstActualSupertype instanceof TypeDeclaration + ? getId((TypeDeclaration) firstActualSupertype) + : new Identifier(firstActualSupertype.getName()); } @@ -200,8 +188,8 @@ protected MethodDeclaration containingMethod(TypeDeclaration td) { } /** - * invokes model transformation for each top level type declaration - * in any compilation unit. Not for inner classes. + * invokes model transformation for each top level type declaration in any compilation unit. + * Not for inner classes. */ public void makeExplicit() { Set s = classDeclarations(); @@ -238,11 +226,9 @@ public void transform() { } /** - * 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. + * 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. * @@ -327,13 +313,15 @@ public void walk(SourceElement s) { } public void visitVariableReference(VariableReference vr) { - final DefaultCrossReferenceSourceInfo si = (DefaultCrossReferenceSourceInfo) services.getSourceInfo(); + final DefaultCrossReferenceSourceInfo si = + (DefaultCrossReferenceSourceInfo) services.getSourceInfo(); final Variable v = si.getVariable(vr.getName(), vr); - final ClassType containingClassTypeOfProgVarV = si.getContainingClassType((ProgramElement) v); + final ClassType containingClassTypeOfProgVarV = + si.getContainingClassType((ProgramElement) v); ClassType ct = si.getContainingClassType(vr); - if (containingClassTypeOfProgVarV != ct && - v instanceof VariableSpecification && !(v instanceof FieldSpecification)) { + if (containingClassTypeOfProgVarV != ct && v instanceof VariableSpecification + && !(v instanceof FieldSpecification)) { while (ct instanceof ClassDeclaration && ct != containingClassTypeOfProgVarV) { List vars = lc2fv.get(ct); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RegisteredEscapeExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RegisteredEscapeExpression.java index ff5520474e7..f7be52bb21a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RegisteredEscapeExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/RegisteredEscapeExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.speclang.njml.JmlTermFactory; @@ -7,10 +10,10 @@ import java.util.List; /** - * This class handles all escape expressions in set-statements, that are registered - * in JMLTranslator.jml2jdl - * - * + * This class handles all escape expressions in set-statements, that are registered in + * JMLTranslator.jml2jdl + * + * * @author Kai Wallisch */ public class RegisteredEscapeExpression extends EscapeExpression { @@ -19,7 +22,7 @@ public class RegisteredEscapeExpression extends EscapeExpression { * generated UID */ private static final long serialVersionUID = 5400879603292633806L; - + private final String mapEscape; RegisteredEscapeExpression(String mapEscape, List arguments) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SVWrapper.java index 9febc17b76c..66110cd557f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import de.uka.ilkd.key.logic.op.SchemaVariable; @@ -6,6 +9,7 @@ public interface SVWrapper { /** * sets the schema variable of sort statement + * * @param sv the SchemaVariable to wrap */ void setSV(SchemaVariable sv); @@ -16,4 +20,4 @@ public interface SVWrapper { SchemaVariable getSV(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceServiceConfiguration.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceServiceConfiguration.java index 700f8456d5d..9ae6abadb3a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceServiceConfiguration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceServiceConfiguration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is part of the RECODER library and protected by the LGPL. package de.uka.ilkd.key.java.recoderext; @@ -6,24 +9,24 @@ import de.uka.ilkd.key.util.KeYRecoderExcHandler; public class SchemaCrossReferenceServiceConfiguration - extends KeYCrossReferenceServiceConfiguration { - + extends KeYCrossReferenceServiceConfiguration { + public SchemaCrossReferenceServiceConfiguration(KeYRecoderExcHandler keh) { - super(keh); + super(keh); } /** we need another factory for some new program elements */ protected ProgramFactory makeProgramFactory() { - return SchemaJavaProgramFactory.getInstance(); + return SchemaJavaProgramFactory.getInstance(); } /** - The cross reference source info is a subclass of the source info, - so this class simply overrides the source info factory method. + * The cross reference source info is a subclass of the source info, so this class simply + * overrides the source info factory method. */ protected SourceInfo makeSourceInfo() { - return new SchemaCrossReferenceSourceInfo(this); - } - + return new SchemaCrossReferenceSourceInfo(this); + } + -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceSourceInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceSourceInfo.java index 25f0f7d3e72..384a5a8e6d8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceSourceInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaCrossReferenceSourceInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.ServiceConfiguration; @@ -10,42 +13,42 @@ import recoder.service.KeYCrossReferenceSourceInfo; public class SchemaCrossReferenceSourceInfo extends KeYCrossReferenceSourceInfo { - + protected final PrimitiveType recoderTypeSVType; public SchemaCrossReferenceSourceInfo(ServiceConfiguration config) { - super(config); - recoderTypeSVType - = new PrimitiveType("TypeSV", this); - } + super(config); + recoderTypeSVType = new PrimitiveType("TypeSV", this); + } public void initialize(ServiceConfiguration cfg) { - super.initialize(cfg); - cfg.getChangeHistory().removeChangeHistoryListener(this); + super.initialize(cfg); + cfg.getChangeHistory().removeChangeHistoryListener(this); } public Type getType(TypeReference tr) { - if (tr instanceof TypeSVWrapper) { - return recoderTypeSVType; - } else { - return super.getType(tr); - } + if (tr instanceof TypeSVWrapper) { + return recoderTypeSVType; + } else { + return super.getType(tr); + } } public Type getType(VariableSpecification vs) { - if (vs.getExpressionCount()>0 - && vs.getExpressionAt(0) instanceof ProgramVariableSVWrapper) { - return recoderTypeSVType; - } else { - return super.getType(vs); - } + if (vs.getExpressionCount() > 0 + && vs.getExpressionAt(0) instanceof ProgramVariableSVWrapper) { + return recoderTypeSVType; + } else { + return super.getType(vs); + } } - /** does not resolve the urq, just returns the argument + /** + * does not resolve the urq, just returns the argument */ - public Reference resolveURQ(UncollatedReferenceQualifier urq){ - return urq; + public Reference resolveURQ(UncollatedReferenceQualifier urq) { + return urq; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaJavaProgramFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaJavaProgramFactory.java index 9b9fe66b872..22ca78456f8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaJavaProgramFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SchemaJavaProgramFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ // This file is partially taken from the RECODER library, which is protected by // the LGPL, and modified. @@ -36,18 +39,17 @@ public class SchemaJavaProgramFactory extends JavaProgramFactory { protected Namespace svns; /** - Protected constructor - use {@link #getInstance} instead. + * Protected constructor - use {@link #getInstance} instead. */ protected SchemaJavaProgramFactory() {} /** - The singleton instance of the program factory. + * The singleton instance of the program factory. */ - private static SchemaJavaProgramFactory theFactory - = new SchemaJavaProgramFactory(); + private static SchemaJavaProgramFactory theFactory = new SchemaJavaProgramFactory(); /** - Returns the single instance of this class. + * Returns the single instance of this class. */ public static JavaProgramFactory getInstance() { return theFactory; @@ -61,20 +63,17 @@ public ImplicitIdentifier createImplicitIdentifier(String text) { } @Override - public Identifier createIdentifier (String text){ + public Identifier createIdentifier(String text) { return new ExtendedIdentifier(text); } - public SpecialReferenceWrapper createThisReference(TypeReference typeRef, - Expression var) { - return new SpecialReferenceWrapper - (typeRef, (ReferencePrefix) var); + public SpecialReferenceWrapper createThisReference(TypeReference typeRef, Expression var) { + return new SpecialReferenceWrapper(typeRef, (ReferencePrefix) var); } public RMethodCallStatement createRMethodCallStatement(ProgramVariableSVWrapper resVar, - ExecutionContext esvw, - Statement st) { - return new RMethodCallStatement(resVar, esvw, st); + ExecutionContext esvw, Statement st) { + return new RMethodCallStatement(resVar, esvw, st); } public LoopScopeBlock createLoopScopeBlock() { @@ -82,41 +81,38 @@ public LoopScopeBlock createLoopScopeBlock() { } - public RMethodBodyStatement createRMethodBodyStatement - (TypeReference typeRef, - ProgramVariableSVWrapper resVar, - MethodReference mr) { + public RMethodBodyStatement createRMethodBodyStatement(TypeReference typeRef, + ProgramVariableSVWrapper resVar, MethodReference mr) { return new RMethodBodyStatement(typeRef, resVar, mr); } public RKeYMetaConstruct createRKeYMetaConstruct() { - return new RKeYMetaConstruct(); + return new RKeYMetaConstruct(); } public RKeYMetaConstructExpression createRKeYMetaConstructExpression() { - return new RKeYMetaConstructExpression(); + return new RKeYMetaConstructExpression(); } public RKeYMetaConstructType createRKeYMetaConstructType() { - return new RKeYMetaConstructType(); + return new RKeYMetaConstructType(); } public ContextStatementBlock createContextStatementBlock(TypeSVWrapper typeRef, - MethodSignatureSVWrapper pm, - ExpressionSVWrapper var) { - return new ContextStatementBlock(typeRef, pm, var); + MethodSignatureSVWrapper pm, ExpressionSVWrapper var) { + return new ContextStatementBlock(typeRef, pm, var); } public ContextStatementBlock createContextStatementBlock(ExecCtxtSVWrapper ec) { - return new ContextStatementBlock(ec); + return new ContextStatementBlock(ec); } /** * Create a {@link PassiveExpression}. */ public PassiveExpression createPassiveExpression(Expression e) { - return new PassiveExpression(e); + return new PassiveExpression(e); } public MergePointStatement createMergePointStatement() { @@ -131,115 +127,110 @@ public MergePointStatement createMergePointStatement(Expression e) { * Create a {@link PassiveExpression}. */ public PassiveExpression createPassiveExpression() { - return new PassiveExpression(); + return new PassiveExpression(); } - public static void throwSortInvalid(SchemaVariable sv, String s) - throws ParseException { - throw new ParseException("Sort of declared schema variable " - +sv.name().toString()+" " - +sv.sort().name().toString() - +" does not comply with expected type "+s - +" in Java program."); + public static void throwSortInvalid(SchemaVariable sv, String s) throws ParseException { + throw new ParseException("Sort of declared schema variable " + sv.name().toString() + " " + + sv.sort().name().toString() + " does not comply with expected type " + s + + " in Java program."); } public boolean lookupSchemaVariableType(String s, ProgramSVSort sort) { - if (svns==null) return false; - Named n=svns.lookup(new Name(s)); - if (n!=null && n instanceof SchemaVariable) { - return ((SchemaVariable) n).sort()==sort; - } - return false; + if (svns == null) + return false; + Named n = svns.lookup(new Name(s)); + if (n != null && n instanceof SchemaVariable) { + return ((SchemaVariable) n).sort() == sort; + } + return false; } public SchemaVariable lookupSchemaVariable(String s) throws ParseException { - SchemaVariable sv=null; - Named n=svns.lookup(new Name(s)); - if (n!=null && n instanceof SchemaVariable) { - sv=(SchemaVariable) n; - } else { - throw new ParseException("Schema variable not declared: "+s); - } - return sv; + SchemaVariable sv = null; + Named n = svns.lookup(new Name(s)); + if (n != null && n instanceof SchemaVariable) { + sv = (SchemaVariable) n; + } else { + throw new ParseException("Schema variable not declared: " + s); + } + return sv; } public StatementSVWrapper getStatementSV(String s) throws ParseException { - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Statement"); - } + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Statement"); + } - return new StatementSVWrapper(sv); + return new StatementSVWrapper(sv); } public ExpressionSVWrapper getExpressionSV(String s) throws ParseException { - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Expression"); - } - return new ExpressionSVWrapper(sv); + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Expression"); + } + return new ExpressionSVWrapper(sv); } - public LabelSVWrapper getLabelSV(String s) throws ParseException{ - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Label"); - } - return new LabelSVWrapper(sv); + public LabelSVWrapper getLabelSV(String s) throws ParseException { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Label"); + } + return new LabelSVWrapper(sv); } - public MethodSignatureSVWrapper getMethodSignatureSVWrapper(String s) throws ParseException{ - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "MethodSignature"); - } - return new MethodSignatureSVWrapper(sv); + public MethodSignatureSVWrapper getMethodSignatureSVWrapper(String s) throws ParseException { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "MethodSignature"); } + return new MethodSignatureSVWrapper(sv); + } public JumpLabelSVWrapper getJumpLabelSV(String s) throws ParseException { - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV) || - sv.sort()!=ProgramSVSort.LABEL) { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV) || sv.sort() != ProgramSVSort.LABEL) { throwSortInvalid(sv, "Label"); } return new JumpLabelSVWrapper(sv); } - public TypeSVWrapper getTypeSV(String s) throws ParseException{ - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Type"); - } - return new TypeSVWrapper(sv); + public TypeSVWrapper getTypeSV(String s) throws ParseException { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Type"); + } + return new TypeSVWrapper(sv); } public ExecCtxtSVWrapper getExecutionContextSV(String s) throws ParseException { - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Type"); - } - return new ExecCtxtSVWrapper(sv); + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Type"); + } + return new ExecCtxtSVWrapper(sv); } - public ProgramVariableSVWrapper getProgramVariableSV(String s) - throws ParseException{ - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Program Variable"); - } - return new ProgramVariableSVWrapper(sv); + public ProgramVariableSVWrapper getProgramVariableSV(String s) throws ParseException { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Program Variable"); + } + return new ProgramVariableSVWrapper(sv); } - public CatchSVWrapper getCatchSV(String s) - throws ParseException { - SchemaVariable sv=lookupSchemaVariable(s); - if (!(sv instanceof ProgramSV)) { - throwSortInvalid(sv, "Catch"); - } - return new CatchSVWrapper(sv); + public CatchSVWrapper getCatchSV(String s) throws ParseException { + SchemaVariable sv = lookupSchemaVariable(s); + if (!(sv instanceof ProgramSV)) { + throwSortInvalid(sv, "Catch"); + } + return new CatchSVWrapper(sv); } public CcatchSVWrapper getCcatchSV(String s) throws ParseException { @@ -251,7 +242,7 @@ public CcatchSVWrapper getCcatchSV(String s) throws ParseException { } /** - For internal reuse and synchronization. + * For internal reuse and synchronization. */ private static final SchemaJavaParser parser = new SchemaJavaParser(System.in); @@ -263,14 +254,15 @@ private static void attachComment(Comment c, ProgramElement pe) { NonTerminalProgramElement ppe = dest.getASTParent(); int i = 0; if (ppe != null) { - for (; ppe.getChildAt(i) != dest; i++){} + for (; ppe.getChildAt(i) != dest; i++) { + } } if (i == 0) { // before syntactical parent - c.setPrefixed(true); + c.setPrefixed(true); } else { dest = ppe.getChildAt(i - 1); while (dest instanceof NonTerminalProgramElement) { - ppe = (NonTerminalProgramElement)dest; + ppe = (NonTerminalProgramElement) dest; i = ppe.getChildCount(); if (i == 0) { break; @@ -294,8 +286,7 @@ private static void attachComment(Comment c, ProgramElement pe) { } /** - Perform post work on the created element. Creates parent links - and assigns comments. + * Perform post work on the created element. Creates parent links and assigns comments. */ private static void postWork(ProgramElement pe) { List comments = SchemaJavaParser.getComments(); @@ -311,19 +302,18 @@ private static void postWork(ProgramElement pe) { while (tw.next()) { pe = tw.getProgramElement(); if (pe instanceof NonTerminalProgramElement) { - ((NonTerminalProgramElement)pe).makeParentRoleValid(); + ((NonTerminalProgramElement) pe).makeParentRoleValid(); } - if (pe.getFirstElement()!=null) { - Position pos = pe.getFirstElement().getStartPosition(); - while ((commentIndex < commentCount) - && pos.compareTo(cpos) > 0) { - attachComment(current, pe); - commentIndex += 1; - if (commentIndex < commentCount) { - current = comments.get(commentIndex); - cpos = current.getFirstElement().getStartPosition(); - } - } + if (pe.getFirstElement() != null) { + Position pos = pe.getFirstElement().getStartPosition(); + while ((commentIndex < commentCount) && pos.compareTo(cpos) > 0) { + attachComment(current, pe); + commentIndex += 1; + if (commentIndex < commentCount) { + current = comments.get(commentIndex); + cpos = current.getFirstElement().getStartPosition(); + } + } } } if (commentIndex < commentCount) { @@ -344,202 +334,204 @@ private static void postWork(ProgramElement pe) { } /** - Parse a {@link CompilationUnit} from the given reader. + * Parse a {@link CompilationUnit} from the given reader. */ @Override public CompilationUnit parseCompilationUnit(Reader in) throws IOException, ParserException { - synchronized(parser) { - try { - SchemaJavaParser.initialize(in); - CompilationUnit res = SchemaJavaParser.CompilationUnit(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); - pe.initCause(e); - throw pe; - } + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + CompilationUnit res = SchemaJavaParser.CompilationUnit(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); + pe.initCause(e); + throw pe; + } } } /** - Parse a {@link TypeDeclaration} from the given reader. + * Parse a {@link TypeDeclaration} from the given reader. */ @Override public TypeDeclaration parseTypeDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - TypeDeclaration res = SchemaJavaParser.TypeDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + TypeDeclaration res = SchemaJavaParser.TypeDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link FieldDeclaration} from the given reader. + * Parse a {@link FieldDeclaration} from the given reader. */ @Override public FieldDeclaration parseFieldDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - FieldDeclaration res = SchemaJavaParser.FieldDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + FieldDeclaration res = SchemaJavaParser.FieldDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link MethodDeclaration} from the given reader. + * Parse a {@link MethodDeclaration} from the given reader. */ @Override public MethodDeclaration parseMethodDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - MethodDeclaration res = SchemaJavaParser.MethodDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + MethodDeclaration res = SchemaJavaParser.MethodDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link MemberDeclaration} from the given reader. + * Parse a {@link MemberDeclaration} from the given reader. */ @Override public MemberDeclaration parseMemberDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - MemberDeclaration res = SchemaJavaParser.ClassBodyDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + MemberDeclaration res = SchemaJavaParser.ClassBodyDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link ParameterDeclaration} from the given reader. + * Parse a {@link ParameterDeclaration} from the given reader. */ @Override - public ParameterDeclaration parseParameterDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - ParameterDeclaration res = SchemaJavaParser.FormalParameter(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + public ParameterDeclaration parseParameterDeclaration(Reader in) + throws IOException, ParserException { + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + ParameterDeclaration res = SchemaJavaParser.FormalParameter(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link ConstructorDeclaration} from the given reader. + * Parse a {@link ConstructorDeclaration} from the given reader. */ @Override - public ConstructorDeclaration parseConstructorDeclaration(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - ConstructorDeclaration res = SchemaJavaParser.ConstructorDeclaration(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + public ConstructorDeclaration parseConstructorDeclaration(Reader in) + throws IOException, ParserException { + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + ConstructorDeclaration res = SchemaJavaParser.ConstructorDeclaration(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse a {@link TypeReference} from the given reader. + * Parse a {@link TypeReference} from the given reader. */ @Override public TypeReference parseTypeReference(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - TypeReference res = SchemaJavaParser.ResultType(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + TypeReference res = SchemaJavaParser.ResultType(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse an {@link Expression} from the given reader. + * Parse an {@link Expression} from the given reader. */ @Override public Expression parseExpression(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - Expression res = SchemaJavaParser.Expression(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + Expression res = SchemaJavaParser.Expression(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } /** - Parse some {@link Statement}s from the given reader. + * Parse some {@link Statement}s from the given reader. */ @Override public ASTList parseStatements(Reader in) throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - ASTList res = SchemaJavaParser.GeneralizedStatements(); - for (int i = 0; i < res.size(); i += 1) { - postWork(res.get(i)); - } - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(); + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + ASTList res = SchemaJavaParser.GeneralizedStatements(); + for (int i = 0; i < res.size(); i += 1) { + postWork(res.get(i)); + } + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(); pe.initCause(e); throw pe; - } + } } } @@ -548,19 +540,18 @@ public ASTList parseStatements(Reader in) throws IOException, ParserE * Parse a {@link StatementBlock} from the given string. */ @Override - public StatementBlock parseStatementBlock(Reader in) - throws IOException, ParserException { - synchronized(parser) { - try{ - SchemaJavaParser.initialize(in); - StatementBlock res = SchemaJavaParser.StartBlock(); - postWork(res); - return res; - } catch (ParseException e) { - ParserException pe = new ParserException(e.getMessage()); + public StatementBlock parseStatementBlock(Reader in) throws IOException, ParserException { + synchronized (parser) { + try { + SchemaJavaParser.initialize(in); + StatementBlock res = SchemaJavaParser.StartBlock(); + postWork(res); + return res; + } catch (ParseException e) { + ParserException pe = new ParserException(e.getMessage()); pe.initCause(e); throw pe; - } + } } } @@ -568,14 +559,15 @@ public StatementBlock parseStatementBlock(Reader in) public void setSVNamespace(Namespace ns) { - svns=ns; + svns = ns; } public CcatchReturnParameterDeclaration createCcatchReturnParameterDeclaration() { return new CcatchReturnParameterDeclaration(); } - public CcatchReturnValParameterDeclaration createCcatchReturnValParameterDeclaration(ParameterDeclaration p) { + public CcatchReturnValParameterDeclaration createCcatchReturnValParameterDeclaration( + ParameterDeclaration p) { return new CcatchReturnValParameterDeclaration(p); } @@ -583,7 +575,8 @@ public CcatchBreakParameterDeclaration createCcatchBreakParameterDeclaration() { return new CcatchBreakParameterDeclaration(); } - public CcatchBreakLabelParameterDeclaration createCcatchBreakLabelParameterDeclaration(Identifier label) { + public CcatchBreakLabelParameterDeclaration createCcatchBreakLabelParameterDeclaration( + Identifier label) { return new CcatchBreakLabelParameterDeclaration(label); } @@ -595,7 +588,8 @@ public CcatchContinueParameterDeclaration createCcatchContinueParameterDeclarati return new CcatchContinueParameterDeclaration(); } - public CcatchContinueLabelParameterDeclaration createCcatchContinueLabelParameterDeclaration(Identifier label) { + public CcatchContinueLabelParameterDeclaration createCcatchContinueLabelParameterDeclaration( + Identifier label) { return new CcatchContinueLabelParameterDeclaration(label); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SourceVisitorExtended.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SourceVisitorExtended.java index c18319147e4..1f339cfcbb5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SourceVisitorExtended.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SourceVisitorExtended.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -62,4 +65,4 @@ public void visitCcatchReturnWildcardParameterDeclaration( // default do nothing } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SpecialReferenceWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SpecialReferenceWrapper.java index 56a5842104f..39dbcb87399 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SpecialReferenceWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/SpecialReferenceWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.*; @@ -23,8 +26,7 @@ public SpecialReferenceWrapper() { } - public SpecialReferenceWrapper(TypeReference typeRef, - ReferencePrefix myprefix) { + public SpecialReferenceWrapper(TypeReference typeRef, ReferencePrefix myprefix) { this.typeRef = typeRef; this.myprefix = myprefix; expressionParent = null; @@ -39,8 +41,7 @@ protected SpecialReferenceWrapper(SpecialReferenceWrapper proto) { /** * Make parent role valid. */ - public void makeParentRoleValid() { - } + public void makeParentRoleValid() {} /** * Get AST parent. @@ -70,9 +71,8 @@ public void setExpressionContainer(ExpressionContainer c) { expressionParent = c; } - //don't think we need it - public void accept(SourceVisitor v) { - } + // don't think we need it + public void accept(SourceVisitor v) {} public SpecialReferenceWrapper deepClone() { return new SpecialReferenceWrapper(typeRef, myprefix); @@ -119,4 +119,4 @@ public ReferencePrefix getReferencePrefix() { public void setReferencePrefix(ReferencePrefix myprefix) { this.myprefix = myprefix; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/StatementSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/StatementSVWrapper.java index b5180cccc5e..11b2b8ec805 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/StatementSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/StatementSVWrapper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.ProgramElement; @@ -6,11 +9,10 @@ import recoder.java.statement.JavaStatement; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class StatementSVWrapper extends JavaStatement - implements KeYRecoderExtension, SVWrapper{ - +public class StatementSVWrapper extends JavaStatement implements KeYRecoderExtension, SVWrapper { + /** - * + * */ private static final long serialVersionUID = -4062276649575988872L; protected SchemaVariable sv; @@ -19,37 +21,36 @@ protected StatementSVWrapper(StatementSVWrapper proto) { super(proto); } - public StatementSVWrapper() { - } + public StatementSVWrapper() {} public StatementSVWrapper(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** - Make parent role valid. + * Make parent role valid. */ public void makeParentRoleValid() { super.makeParentRoleValid(); } /** - 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; 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { throw new ArrayIndexOutOfBoundsException(); } @@ -61,17 +62,15 @@ public int getChildPositionCode(ProgramElement child0) { /** - * Replace a single child in the current node. - * The child to replace is matched by identity and hence must be known - * exactly. The replacement element can be null - in that case, the child - * is effectively removed. - * The parent role of the new child is validated, while the - * parent link of the replaced child is left untouched. + * Replace a single child in the current node. The child to replace is matched by identity and + * hence must be known exactly. The replacement element can be null - in that case, the child is + * effectively removed. The parent role of the new child is validated, while the parent link of + * the replaced child is left untouched. + * * @param p the old child. * @param q the new child. * @return true if a replacement has occured, false otherwise. - * @exception ClassCastException if the new child cannot take over - * the role of the old one. + * @exception ClassCastException if the new child cannot take over the role of the old one. */ public boolean replaceChild(ProgramElement p, ProgramElement q) { @@ -81,23 +80,25 @@ public boolean replaceChild(ProgramElement p, ProgramElement q) { /** * sets the schema variable of sort statement + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns a String name of this meta construct. */ public SchemaVariable getSV() { - return sv; + return sv; } /** - 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() { @@ -105,24 +106,24 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - //don't think we need it - public void accept(SourceVisitor v) { - } - + // don't think we need it + public void accept(SourceVisitor v) {} + public StatementSVWrapper deepClone() { - return new StatementSVWrapper(sv); + return new StatementSVWrapper(sv); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TransactionStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TransactionStatement.java index 154d23408ee..b0bb8966a23 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TransactionStatement.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TransactionStatement.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -8,22 +11,22 @@ public class TransactionStatement extends JavaStatement { private static final long serialVersionUID = -4470827742145010769L; - public static final int BEGIN = 1; - public static final int COMMIT = 2; - public static final int FINISH = 3; + public static final int BEGIN = 1; + public static final int COMMIT = 2; + public static final int FINISH = 3; public static final int ABORT = 4; - + private int type; - + public TransactionStatement(int type) { super(); - if(type != BEGIN && type != COMMIT && type != FINISH && type != ABORT) { - throw new IllegalArgumentException("Wrong transaction statement type "+type); + if (type != BEGIN && type != COMMIT && type != FINISH && type != ABORT) { + throw new IllegalArgumentException("Wrong transaction statement type " + type); } this.type = type; makeParentRoleValid(); } - + protected TransactionStatement(TransactionStatement proto) { this(proto.type); } @@ -31,7 +34,7 @@ protected TransactionStatement(TransactionStatement proto) { public int getType() { return type; } - + public recoder.java.ProgramElement getChildAt(int index) { return null; } @@ -41,10 +44,9 @@ public recoder.java.ProgramElement getChildAt(int index) { public Statement deepClone() { return new TransactionStatement(this); } - + @Override - public void accept(SourceVisitor sourceVisitor) { - } + public void accept(SourceVisitor sourceVisitor) {} @Override @@ -63,14 +65,14 @@ public boolean replaceChild(recoder.java.ProgramElement arg0, recoder.java.ProgramElement arg1) { return false; } - + 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 int hashCode() { return type; } @@ -79,4 +81,4 @@ public String toString() { return de.uka.ilkd.key.java.statement.TransactionStatement.names[type - 1]; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TwoState.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TwoState.java index 128a2285c08..896d4cae461 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TwoState.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TwoState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceVisitor; @@ -8,8 +11,7 @@ public class TwoState extends Modifier { private static final long serialVersionUID = 1408979308814683681L; - public TwoState() { - } + public TwoState() {} protected TwoState(TwoState proto) { super(proto); @@ -19,7 +21,6 @@ public TwoState deepClone() { return new TwoState(this); } - public void accept(SourceVisitor v) { - } + public void accept(SourceVisitor v) {} } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TypeSVWrapper.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TypeSVWrapper.java index 04a5a0bb86c..ffc6658ce86 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TypeSVWrapper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/TypeSVWrapper.java @@ -1,20 +1,22 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import recoder.java.SourceElement; import recoder.java.reference.TypeReference; import de.uka.ilkd.key.logic.op.SchemaVariable; -public class TypeSVWrapper extends TypeReference - implements KeYRecoderExtension, SVWrapper{ +public class TypeSVWrapper extends TypeReference implements KeYRecoderExtension, SVWrapper { /** - * + * */ private static final long serialVersionUID = 2694567717981292433L; - SchemaVariable sv=null; + SchemaVariable sv = null; public TypeSVWrapper(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } protected TypeSVWrapper(TypeSVWrapper proto) { @@ -23,22 +25,23 @@ protected TypeSVWrapper(TypeSVWrapper proto) { /** * sets the schema variable of sort label + * * @param sv the SchemaVariable */ public void setSV(SchemaVariable sv) { - this.sv=sv; + this.sv = sv; } /** * returns the schema variable of this type sv wrapper */ public SchemaVariable getSV() { - return sv; + return sv; } public SourceElement getFirstElement() { - return this; + return this; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/URLDataLocation.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/URLDataLocation.java index c5b8e0253b7..7d153ce0470 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/URLDataLocation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/URLDataLocation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext; import java.io.IOException; @@ -11,24 +14,25 @@ import recoder.io.DataLocation; /** - * This class implements a data location, that describes an arbitrary URL. It is read-only - * and uses the URL's own stream for reading - * + * This class implements a data location, that describes an arbitrary URL. It is read-only and uses + * the URL's own stream for reading + * * @author mulbrich * @since 2006-11-02 */ public class URLDataLocation implements DataLocation { private URL url; - + public static final String LOCATION_TYPE_FILE = "URL"; public URLDataLocation(URL url) { this.url = url; } - /** + /** * return the URL's input stream + * * @see recoder.io.DataLocation#getInputStream() */ public InputStream getInputStream() throws IOException { @@ -42,9 +46,9 @@ public InputStream getInputStream() throws IOException { public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException("Output is not supported for URLDataLocation"); } - + /** - * @throws UnsupportedOperationException always + * @throws UnsupportedOperationException always * @see recoder.io.DataLocation#getWriter() */ public Writer getWriter() throws IOException { @@ -61,6 +65,7 @@ public String getType() { /** * Getter for url. + * * @return the url of this data location */ public URL getUrl() { @@ -76,23 +81,19 @@ public boolean hasReaderSupport() { } public boolean hasWriterSupport() { - return false; + return false; } - + public boolean isWritable() { return false; } - public void inputStreamClosed() { - } + public void inputStreamClosed() {} - public void outputStreamClosed() { - } + public void outputStreamClosed() {} - public void readerClosed() { - } + public void readerClosed() {} - public void writerClosed() { - } + public void writerClosed() {} -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/ADTPrefixConstruct.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/ADTPrefixConstruct.java index c913952a51d..d7cc22e1b29 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/ADTPrefixConstruct.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/ADTPrefixConstruct.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -7,26 +10,26 @@ import recoder.java.reference.ReferenceSuffix; public abstract class ADTPrefixConstruct extends Operator implements ReferencePrefix { - + /** - * + * */ private static final long serialVersionUID = 2903025447315816147L; private ReferenceSuffix suffix; - - public ADTPrefixConstruct(){ + + public ADTPrefixConstruct() { super(); } - - public ADTPrefixConstruct(Expression unary){ + + public ADTPrefixConstruct(Expression unary) { super(unary); } - - public ADTPrefixConstruct(Expression lhs, Expression rhs){ - super(lhs,rhs); + + public ADTPrefixConstruct(Expression lhs, Expression rhs) { + super(lhs, rhs); } - - protected ADTPrefixConstruct(ADTPrefixConstruct proto){ + + protected ADTPrefixConstruct(ADTPrefixConstruct proto) { super(proto); } @@ -45,15 +48,15 @@ public void accept(SourceVisitor arg0) { // SourceVisitors in RecodeR currently are only used to perform the toSource() operation. // One of them needs to be implemented in order for source code to be reproduced. } - + @Override - public int getPrecedence(){ + public int getPrecedence() { return 0; // TODO remove from subclasses } - + @Override - public String toString(){ + public String toString() { return toSource(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllFields.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllFields.java index 59877fe9278..37da0dc4b1d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllFields.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllFields.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,38 +9,38 @@ public class AllFields extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 3940415948467563540L; public AllFields(Expression lhs) { - super(lhs); - makeParentRoleValid(); + super(lhs); + makeParentRoleValid(); } protected AllFields(AllFields proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public AllFields deepClone() { - return new AllFields(this); + return new AllFields(this); } - @Override + @Override public int getArity() { - return 1; + return 1; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllObjects.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllObjects.java index d5dd69d8751..d4bc6cea078 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllObjects.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/AllObjects.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,38 +9,38 @@ public class AllObjects extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 3940415948467542340L; public AllObjects(Expression lhs) { - super(lhs); - makeParentRoleValid(); + super(lhs); + makeParentRoleValid(); } protected AllObjects(AllObjects proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public AllObjects deepClone() { - return new AllObjects(this); + return new AllObjects(this); } - @Override + @Override public int getArity() { - return 1; + return 1; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptyMapLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptyMapLiteral.java index 5dd72a1637d..2156774d1b8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptyMapLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptyMapLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -10,7 +13,7 @@ public final class EmptyMapLiteral extends Literal { * generated UID */ private static final long serialVersionUID = -4665241238978552904L; - + public static final EmptyMapLiteral INSTANCE = new EmptyMapLiteral(); @Override @@ -19,8 +22,7 @@ public Expression deepClone() { } @Override - public void accept(SourceVisitor v) { - } + public void accept(SourceVisitor v) {} @Override public Object getEquivalentJavaType() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySeqLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySeqLiteral.java index beede5a03c7..35157adb681 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySeqLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySeqLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,30 +9,29 @@ public final class EmptySeqLiteral extends Literal { - + /** - * + * */ private static final long serialVersionUID = 7272271426600775146L; public static final EmptySeqLiteral INSTANCE = new EmptySeqLiteral(); - + @Override public Expression deepClone() { - return this; + return this; } - @Override - public void accept(SourceVisitor v) { - } + @Override + public void accept(SourceVisitor v) {} + - @Override public Object getEquivalentJavaType() { - return null; + return null; } - + @Override - public String toSource(){ + public String toSource() { return "\\seq_empty"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySetLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySetLiteral.java index 307682b7bde..896a3844d29 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySetLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/EmptySetLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,25 +9,24 @@ public final class EmptySetLiteral extends Literal { - + /** - * + * */ private static final long serialVersionUID = 262935836224837458L; public static final EmptySetLiteral INSTANCE = new EmptySetLiteral(); - + @Override public Expression deepClone() { - return this; + return this; } - @Override - public void accept(SourceVisitor v) { - } + @Override + public void accept(SourceVisitor v) {} + - @Override public Object getEquivalentJavaType() { - return null; + return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Intersect.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Intersect.java index cd812ed8753..d6b2443b7ec 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Intersect.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Intersect.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,43 +9,43 @@ public class Intersect extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 8777658515734186914L; public Intersect(Expression lhs, Expression rhs) { - super(lhs, rhs); - makeParentRoleValid(); + super(lhs, rhs); + makeParentRoleValid(); } protected Intersect(Intersect proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public Intersect deepClone() { - return new Intersect(this); + return new Intersect(this); } - @Override + @Override public int getArity() { - return 2; + return 2; } - - @Override + + @Override public int getPrecedence() { - return 0; + return 0; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/MethodSignature.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/MethodSignature.java index bbf8561c53f..8b30fdd5d0c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/MethodSignature.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/MethodSignature.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Identifier; @@ -14,7 +17,7 @@ public class MethodSignature extends JavaNonTerminalProgramElement { private static final long serialVersionUID = 6966957683489654730L; private Identifier methodName; private ASTList paramTypes; - + public MethodSignature(Identifier methodName, ASTList paramTypes) { super(); this.methodName = methodName; @@ -23,9 +26,10 @@ public MethodSignature(Identifier methodName, ASTList paramTypes) @Override public ProgramElement getChildAt(int i) { - if (i == 0) return methodName; + if (i == 0) + return methodName; i--; - if (i>=0 && i= 0 && i < paramTypes.size()) { return paramTypes.get(i); } return null; @@ -33,7 +37,7 @@ public ProgramElement getChildAt(int i) { @Override public int getChildCount() { - return 1+paramTypes.size(); + return 1 + paramTypes.size(); } @Override @@ -56,13 +60,11 @@ public NonTerminalProgramElement getASTParent() { } @Override - public void accept(SourceVisitor arg0) { - } + public void accept(SourceVisitor arg0) {} @Override public SourceElement deepClone() { - throw new IllegalStateException("Not implemented in " - +"MethodSignature"); + throw new IllegalStateException("Not implemented in " + "MethodSignature"); } @@ -73,4 +75,4 @@ public Identifier getMethodName() { public ASTList getParamTypes() { return paramTypes; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/RangeExpression.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/RangeExpression.java index bcb24a47eea..8e33186c7c8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/RangeExpression.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/RangeExpression.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,21 +9,26 @@ /** - * Represents the range suffix for subsequences written in suffix notation, e.g.,

    seq[from..to]
    + * Represents the range suffix for subsequences written in suffix notation, e.g., + * + *
    + * seq[from..to]
    + * 
    + * * @since 1.7.2119 * @author bruns * */ public class RangeExpression extends Operator implements Expression { - - + + /** - * + * */ private static final long serialVersionUID = 6404478656913511767L; - public RangeExpression (Expression fromIdx, Expression toIdx){ + public RangeExpression(Expression fromIdx, Expression toIdx) { super(fromIdx, toIdx); makeParentRoleValid(); } @@ -32,17 +40,17 @@ public RangeExpression(RangeExpression rangeExpression) { @Override public void accept(SourceVisitor arg0) { // TODO Auto-generated method stub - + } @Override public RangeExpression deepClone() { return new RangeExpression(this); } - + @Override - public String toSource(){ - return "["+children.get(0)+".."+children.get(1)+"]"; + public String toSource() { + return "[" + children.get(0) + ".." + children.get(1) + "]"; } @@ -62,5 +70,5 @@ public int getNotation() { public int getPrecedence() { return 1; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqConcat.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqConcat.java index dc96869cfaf..4dc567c782c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqConcat.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqConcat.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,41 +9,42 @@ public class SeqConcat extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = -5950638934821692317L; public SeqConcat(Expression lhs, Expression rhs) { - super(lhs, rhs); - makeParentRoleValid(); + super(lhs, rhs); + makeParentRoleValid(); } protected SeqConcat(SeqConcat proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SeqConcat deepClone() { - return new SeqConcat(this); + return new SeqConcat(this); } - @Override + @Override public int getArity() { - return 2; + return 2; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - + @Override - public String toSource(){ - return "\\seq_concat("+children.get(0).toSource()+","+children.get(1).toSource()+")"; + public String toSource() { + return "\\seq_concat(" + children.get(0).toSource() + "," + children.get(1).toSource() + + ")"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqGet.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqGet.java index df646d95fd1..1f159d2ed38 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqGet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqGet.java @@ -1,21 +1,26 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; /** * Sequence getter operation. + * * @author bruns * @since 1.7.2119 */ public class SeqGet extends ADTPrefixConstruct { - + /** - * + * */ private static final long serialVersionUID = -421447886220796576L; /** * Creates a sequence getter operator. + * * @param seq Sequence to operate on * @param idx Index position (from 0 to length-1) */ @@ -31,25 +36,25 @@ protected SeqGet(SeqGet proto) { } - @Override + @Override public SeqGet deepClone() { return new SeqGet(this); } - @Override + @Override public int getArity() { return 2; } - @Override + @Override public int getNotation() { return POSTFIX; } - + @Override - public String toSource(){ - return children.get(0).toSource()+"["+children.get(1).toSource()+"]"; + public String toSource() { + return children.get(0).toSource() + "[" + children.get(1).toSource() + "]"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqIndexOf.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqIndexOf.java index c8120268399..f3a8b9e4178 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqIndexOf.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqIndexOf.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -12,6 +15,7 @@ public class SeqIndexOf extends Operator { /** * Creates an "index of" operator. + * * @param seq Sequence to operate on * @param elem The element to look for in the sequence */ @@ -27,37 +31,37 @@ protected SeqIndexOf(SeqIndexOf proto) { } - @Override + @Override public SeqIndexOf deepClone() { return new SeqIndexOf(this); } - @Override + @Override public int getArity() { return 2; } - @Override + @Override public int getPrecedence() { return 0; } - @Override + @Override public int getNotation() { return PREFIX; } - @Override + @Override public void accept(SourceVisitor v) { } - + @Override - public String toSource(){ - return "\\indexOf("+children.get(0).toSource()+","+children.get(1).toSource()+")"; + public String toSource() { + return "\\indexOf(" + children.get(0).toSource() + "," + children.get(1).toSource() + ")"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqLength.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqLength.java index 77333912b5e..73605faa7e5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqLength.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqLength.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -26,37 +29,37 @@ protected SeqLength(SeqLength proto) { } - @Override + @Override public SeqLength deepClone() { return new SeqLength(this); } - @Override + @Override public int getArity() { return 1; } - @Override + @Override public int getPrecedence() { return 0; } - @Override + @Override public int getNotation() { return POSTFIX; } - @Override + @Override public void accept(SourceVisitor v) { } - - public String toSource(){ - return children.get(0).toSource()+".length"; + + public String toSource() { + return children.get(0).toSource() + ".length"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqReverse.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqReverse.java index 8b9eea42b6d..064c5c09125 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqReverse.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqReverse.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -7,42 +10,42 @@ public class SeqReverse extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = -4836079248155746383L; public SeqReverse(Expression e) { - children = new ASTArrayList(getArity()); - children.add(e); - makeParentRoleValid(); + children = new ASTArrayList(getArity()); + children.add(e); + makeParentRoleValid(); } protected SeqReverse(SeqReverse proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SeqReverse deepClone() { - return new SeqReverse(this); + return new SeqReverse(this); } - @Override + @Override public int getArity() { - return 1; + return 1; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - + @Override - public String toSource(){ - return "\\seq_reverse("+children.get(0).toSource()+")"; + public String toSource() { + return "\\seq_reverse(" + children.get(0).toSource() + ")"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSingleton.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSingleton.java index 3990dacf71e..1cece61df0d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSingleton.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSingleton.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,41 +9,41 @@ public class SeqSingleton extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 940102046205262465L; public SeqSingleton(Expression lhs) { - super(lhs); - makeParentRoleValid(); + super(lhs); + makeParentRoleValid(); } protected SeqSingleton(SeqSingleton proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SeqSingleton deepClone() { - return new SeqSingleton(this); + return new SeqSingleton(this); } - @Override + @Override public int getArity() { - return 1; + return 1; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - + @Override - public String toSource(){ - return "\\seq_singleton("+children.get(0)+")"; + public String toSource() { + return "\\seq_singleton(" + children.get(0) + ")"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSub.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSub.java index f0ce3cab4cb..690b86f79f0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSub.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SeqSub.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -7,50 +10,50 @@ public class SeqSub extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 9034359926577584988L; public SeqSub(Expression e1, Expression e2, Expression e3) { - children = new ASTArrayList(getArity()); - children.add(e1); - children.add(e2); - children.add(e3); - makeParentRoleValid(); + children = new ASTArrayList(getArity()); + children.add(e1); + children.add(e2); + children.add(e3); + makeParentRoleValid(); } - - public SeqSub(ADTPrefixConstruct seq, RangeExpression range){ + + public SeqSub(ADTPrefixConstruct seq, RangeExpression range) { this(seq, (Expression) range.getChildAt(0), (Expression) range.getChildAt(1)); } protected SeqSub(SeqSub proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SeqSub deepClone() { - return new SeqSub(this); + return new SeqSub(this); } - @Override + @Override public int getArity() { - return 3; + return 3; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } - + @Override - public String toSource(){ - return children.get(0).toSource()+"["+children.get(1)+".."+children.get(2)+"]"; + public String toSource() { + return children.get(0).toSource() + "[" + children.get(1) + ".." + children.get(2) + "]"; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetMinus.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetMinus.java index 5e24c5b459c..f5aa9d43ec7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetMinus.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetMinus.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,37 +9,37 @@ public class SetMinus extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = -1824229344478712816L; public SetMinus(Expression lhs, Expression rhs) { - super(lhs, rhs); - makeParentRoleValid(); + super(lhs, rhs); + makeParentRoleValid(); } protected SetMinus(SetMinus proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SetMinus deepClone() { - return new SetMinus(this); + return new SetMinus(this); } - @Override + @Override public int getArity() { - return 2; + return 2; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetUnion.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetUnion.java index 1f3670ae7c0..9c3fee43fbc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetUnion.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/SetUnion.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,37 +9,37 @@ public class SetUnion extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = -8425018389934762589L; public SetUnion(Expression lhs, Expression rhs) { - super(lhs, rhs); - makeParentRoleValid(); + super(lhs, rhs); + makeParentRoleValid(); } protected SetUnion(SetUnion proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public SetUnion deepClone() { - return new SetUnion(this); + return new SetUnion(this); } - @Override + @Override public int getArity() { - return 2; + return 2; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Singleton.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Singleton.java index fdc4149101e..b9593d3552c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Singleton.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/adt/Singleton.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.adt; import recoder.java.Expression; @@ -6,37 +9,37 @@ public class Singleton extends ADTPrefixConstruct { /** - * + * */ private static final long serialVersionUID = 5549648259903299451L; public Singleton(Expression lhs) { - super(lhs); - makeParentRoleValid(); + super(lhs); + makeParentRoleValid(); } protected Singleton(Singleton proto) { - super(proto); - makeParentRoleValid(); + super(proto); + makeParentRoleValid(); } - - @Override + + @Override public Singleton deepClone() { - return new Singleton(this); + return new Singleton(this); } - @Override + @Override public int getArity() { - return 1; + return 1; } - - @Override + + @Override public int getNotation() { - return PREFIX; + return PREFIX; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/expression/literal/RealLiteral.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/expression/literal/RealLiteral.java index 851d4171e01..dd96ed2c350 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/expression/literal/RealLiteral.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/recoderext/expression/literal/RealLiteral.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.recoderext.expression.literal; import java.math.BigDecimal; @@ -13,6 +16,7 @@ /** * Literal for JML \real type; + * * @author bruns * */ @@ -22,19 +26,19 @@ public final class RealLiteral extends Literal implements KeYRecoderExtension { private static final Logger LOGGER = LoggerFactory.getLogger(RealLiteral.class); private final String value; - public RealLiteral (int value){ - this(""+value+".0"); + public RealLiteral(int value) { + this("" + value + ".0"); } - public RealLiteral(String value){ + public RealLiteral(String value) { this.value = value.intern(); } - public RealLiteral(BigDecimal value){ + public RealLiteral(BigDecimal value) { this(value.toString()); } - public RealLiteral(){ + public RealLiteral() { this("0.0"); } @@ -58,17 +62,17 @@ public void accept(SourceVisitor arg0) { } - public String getValue(){ + public String getValue() { return value; } - public String toString(){ + public String toString() { return value; } - public boolean equals(Object o){ + public boolean equals(Object o) { if (o instanceof RealLiteral) - return value.equals(((RealLiteral)o).getValue()); + return value.equals(((RealLiteral) o).getValue()); else return false; } @@ -85,4 +89,4 @@ public int hashCode() { } -} \ No newline at end of file +} 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 113f8e3d9c9..11fb2a50769 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -15,75 +18,73 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * 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. */ 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. + * Array length reference. */ public ArrayLengthReference() { - prefix = null; + prefix = null; } /** * 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 - */ + * + * @param children the children of this AST element as KeY classes. 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 */ 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { - if (prefix != null && index == 0) return prefix; + 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); + 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; @@ -95,19 +96,21 @@ public SourceElement 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 - * perform some action/transformation on this element + /** + * 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.performActionOnArrayLengthReference(this); + v.performActionOnArrayLengthReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printArrayLengthReference(this); } -} \ No newline at end of file +} 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 055c193b34c..66809499eb8 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -17,123 +20,125 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Array reference. - * @author AutoDoc + * Array reference. + * + * @author AutoDoc */ -public class ArrayReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, ReferenceSuffix, - ExpressionContainer, TypeReferenceContainer { +public class ArrayReference extends JavaNonTerminalProgramElement implements Reference, Expression, + ReferencePrefix, ReferenceSuffix, ExpressionContainer, TypeReferenceContainer { /** - * Access path. + * Access path. */ protected final ReferencePrefix prefix; - + /** - Inits. + * Inits. */ - protected final ImmutableArray inits; + protected final ImmutableArray inits; + - /** - * Array reference. + * Array reference. */ public ArrayReference() { - prefix = null; - this.inits=null; + prefix = null; + this.inits = null; } /** - * 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) { + public ArrayReference(ReferencePrefix accessPath, Expression[] initializers) { this.prefix = accessPath; - this.inits = new ImmutableArray(initializers); + this.inits = 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); - } + 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. */ public int getExpressionCount() { int c = 0; - if (prefix instanceof Expression) c += 1; - if (inits != null) c += inits.size(); + if (prefix instanceof Expression) + c += 1; + if (inits != null) + c += inits.size(); return c; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ 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) { @@ -143,32 +148,36 @@ 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. */ public int getTypeReferenceCount() { return (prefix 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. - */ + * 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. + */ 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. */ public ReferencePrefix getReferencePrefix() { @@ -176,27 +185,30 @@ public ReferencePrefix getReferencePrefix() { } /** - * 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 (inits != null) result += inits.size(); + if (prefix != null) + result++; + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; index--; } if (inits != null) { @@ -206,8 +218,9 @@ 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; @@ -219,15 +232,17 @@ public SourceElement 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 - * perform some action/transformation on this element + /** + * 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.performActionOnArrayReference(this); + v.performActionOnArrayReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -235,13 +250,12 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } 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/ConstructorReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ConstructorReference.java index 75361a2f3b2..98b1c8c89ff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ConstructorReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ConstructorReference.java @@ -1,12 +1,15 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; /** - * Constructor reference. - * @author AutoDoc + * Constructor reference. + * + * @author AutoDoc */ -public interface ConstructorReference extends MethodOrConstructorReference, - MemberReference { +public interface ConstructorReference extends MethodOrConstructorReference, MemberReference { -} \ 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 462d0b06012..761fbad8d1a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -9,12 +12,11 @@ import de.uka.ilkd.key.java.visitor.Visitor; import de.uka.ilkd.key.logic.op.IProgramMethod; -public class ExecutionContext -extends JavaNonTerminalProgramElement -implements IExecutionContext, Reference { +public class ExecutionContext extends JavaNonTerminalProgramElement + implements IExecutionContext, Reference { /** - * the class context + * the class context */ protected final TypeReference classContext; @@ -30,14 +32,13 @@ public class ExecutionContext /** * creates an execution context reference - * @param classContext the TypeReference referring to the next enclosing - * class + * + * @param classContext the TypeReference referring to the next enclosing class * @param methodContext the IProgramMethod referring to the currently active method - * @param runtimeInstance a ReferencePrefix to the object that - * is currently active/executed + * @param runtimeInstance a ReferencePrefix to the object that is currently active/executed */ - public ExecutionContext(TypeReference classContext, - IProgramMethod methodContext, ReferencePrefix runtimeInstance) { + public ExecutionContext(TypeReference classContext, IProgramMethod methodContext, + ReferencePrefix runtimeInstance) { this.classContext = classContext; this.methodContext = methodContext; this.runtimeInstance = runtimeInstance; @@ -45,11 +46,11 @@ public ExecutionContext(TypeReference classContext, /** * creates an execution context reference - * @param children an ExtList with the required children of the execution - * context + * + * @param children an ExtList with the required children of the execution context */ public ExecutionContext(ExtList children) { - this.classContext = children.get(TypeReference.class); + this.classContext = children.get(TypeReference.class); children.remove(this.classContext); this.methodContext = children.get(IProgramMethod.class); this.runtimeInstance = children.get(ReferencePrefix.class); @@ -59,37 +60,43 @@ public ExecutionContext(ExtList children) { /** * 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 (classContext != null) count++; - if (methodContext != null) count++; - if (runtimeInstance != null) count++; + if (classContext != null) + count++; + if (methodContext != null) + count++; + if (runtimeInstance != null) + count++; return count; } /** - * Returns the child at the specified index in this node's "virtual" - * child array. + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { if (classContext != null) { - if (index == 0) return classContext; + if (index == 0) + return classContext; index--; } if (methodContext != null) { - if (index == 0) return methodContext; + if (index == 0) + return methodContext; index--; } if (runtimeInstance != null) { - if (index == 0) return runtimeInstance; + if (index == 0) + return runtimeInstance; index--; } throw new ArrayIndexOutOfBoundsException(); @@ -119,8 +126,10 @@ public ReferencePrefix getRuntimeInstance() { return runtimeInstance; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * calls the corresponding method of a visitor in order to perform some action/transformation on + * this element + * * @param v the Visitor */ @Override @@ -135,7 +144,7 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @Override public String toString() { - return "Context: "+classContext+ "#" + methodContext + " Instance: "+runtimeInstance; + return "Context: " + classContext + "#" + methodContext + " Instance: " + runtimeInstance; } -} \ No newline at end of file +} 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 aa3c931d39f..5b11bb6fe5a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; @@ -13,15 +16,14 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; -public class FieldReference extends VariableReference - implements MemberReference, ReferenceSuffix, - TypeReferenceContainer, ExpressionContainer { +public class FieldReference extends VariableReference + implements MemberReference, ReferenceSuffix, TypeReferenceContainer, ExpressionContainer { /** - * Reference prefix. + * Reference prefix. */ protected ReferencePrefix prefix; - + protected FieldReference() { prefix = null; @@ -53,65 +55,72 @@ public FieldReference(ProgramVariable pv, ReferencePrefix prefix, PositionInfo p } /** - * 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 (prefix != null) + result++; + if (variable != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; index--; } if (variable != null) { - if (index == 0) return variable; + if (index == 0) + return variable; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ public ReferencePrefix getReferencePrefix() { return prefix; } /* - * returns true if the reference prefix is an explicit or implicit - * this reference this field reference does not refer to a static field + * 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(); + return (prefix == null || prefix instanceof ThisReference) + && !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(variable, 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() { @@ -119,39 +128,43 @@ public int getTypeReferenceCount() { } /* - 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. - */ + * 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. + */ 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; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + return (Expression) prefix; } throw new ArrayIndexOutOfBoundsException(); } @@ -162,7 +175,7 @@ public SourceElement getFirstElement() { @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? variable : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? variable : prefix.getFirstElementIncludingBlocks(); } /** pretty print */ @@ -172,17 +185,19 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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? */ 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/IExecutionContext.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/IExecutionContext.java index 5c216b013cd..55258c15b4c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/IExecutionContext.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/IExecutionContext.java @@ -1,28 +1,33 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.Reference; import de.uka.ilkd.key.logic.op.IProgramMethod; /** - * extracted interface to allow schema variabes to stand for an - * execution context + * extracted interface to allow schema variabes to stand for an execution context */ public interface IExecutionContext extends Reference { - /** - * returns the type reference to the next enclosing class - * @return the type reference to the next enclosing class - */ - public TypeReference getTypeReference(); - - /** - * returns the program method which is currently active - * @return the currently active method - */ - public IProgramMethod getMethodContext(); - - /** - * returns the runtime instance object - * @return the runtime instance object - */ - public ReferencePrefix getRuntimeInstance(); -} \ No newline at end of file + /** + * returns the type reference to the next enclosing class + * + * @return the type reference to the next enclosing class + */ + public TypeReference getTypeReference(); + + /** + * returns the program method which is currently active + * + * @return the currently active method + */ + public IProgramMethod getMethodContext(); + + /** + * returns the runtime instance object + * + * @return the runtime instance object + */ + public ReferencePrefix getRuntimeInstance(); +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MemberReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MemberReference.java index 687c3cadd6d..c56bf4723d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MemberReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MemberReference.java @@ -1,11 +1,16 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.ExpressionContainer; import de.uka.ilkd.key.java.Reference; + /** - * Member reference. - * @author AutoDoc + * Member reference. + * + * @author AutoDoc */ public interface MemberReference extends Reference, ExpressionContainer { -} \ 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 3433636d672..c654a33fb29 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -13,93 +16,97 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Meta class reference. - * + * Meta class reference. + * */ public class MetaClassReference extends JavaNonTerminalProgramElement - implements Reference, Expression, ReferencePrefix, ReferenceSuffix, - TypeReferenceContainer { + implements Reference, Expression, ReferencePrefix, ReferenceSuffix, TypeReferenceContainer { /** - * Type reference. + * Type reference. */ protected final TypeReference typeReference; /** - * Meta class reference. + * Meta class reference. */ public MetaClassReference() { - typeReference=null; + typeReference = null; } /** - * Meta class reference. - * @param reference a type reference. + * Meta class reference. + * + * @param reference a type reference. */ public MetaClassReference(TypeReference reference) { - typeReference=reference; + typeReference = 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 - */ + * + * @param children the children of this AST element as KeY classes. 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 */ 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (typeReference != null) { - if (index == 0) return typeReference; + if (index == 0) + return typeReference; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ 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. */ public int getTypeReferenceCount() { return (typeReference != null) ? 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. - */ + * 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. + */ public TypeReference getTypeReferenceAt(int index) { if (typeReference != null && index == 0) { @@ -109,8 +116,9 @@ public TypeReference getTypeReferenceAt(int index) { } /** - * Get type reference. - * @return the type reference. + * Get type reference. + * + * @return the type reference. */ public TypeReference getTypeReference() { return typeReference; @@ -122,15 +130,17 @@ public SourceElement 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 - * perform some action/transformation on this element + /** + * 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.performActionOnMetaClassReference(this); + v.performActionOnMetaClassReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -138,14 +148,13 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } 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/MethodName.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodName.java index dc935ef4a80..ce5c99ba13b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodName.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodName.java @@ -1,11 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; /** - * Method name. + * Method name. */ -public interface MethodName extends de.uka.ilkd.key.java.TerminalProgramElement{ +public interface MethodName extends de.uka.ilkd.key.java.TerminalProgramElement { - - -} \ No newline at end of file + + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodOrConstructorReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodOrConstructorReference.java index 2432027119c..178de45d473 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodOrConstructorReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/MethodOrConstructorReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.collection.ImmutableArray; @@ -5,12 +8,10 @@ import de.uka.ilkd.key.java.Expression; import de.uka.ilkd.key.java.Statement; -public interface MethodOrConstructorReference extends MemberReference, - ReferencePrefix, - Statement { +public interface MethodOrConstructorReference extends MemberReference, ReferencePrefix, Statement { /** * @return the array wrapper of the argument expressions . */ ImmutableArray getArguments(); -} \ 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 8fa6be0c9a8..be4aa0e73b3 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -25,164 +28,174 @@ import de.uka.ilkd.key.util.Debug; /** - * Method reference. - * @author AutoDoc + * Method reference. + * + * @author AutoDoc */ public class MethodReference extends JavaNonTerminalProgramElement - implements MethodOrConstructorReference, - MemberReference, ReferencePrefix, - ReferenceSuffix, ExpressionStatement, - TypeReferenceContainer, NameReference { - + implements MethodOrConstructorReference, MemberReference, ReferencePrefix, ReferenceSuffix, + ExpressionStatement, TypeReferenceContainer, NameReference { + /** - Access path. - */ + * Access path. + */ protected final ReferencePrefix prefix; - + /** - * Name. + * Name. */ protected final MethodName name; - + /** - * Arguments. + * Arguments. */ protected final ImmutableArray arguments; - - public MethodReference(ExtList args, MethodName n, - ReferencePrefix p, PositionInfo pos) { + + 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, + + public MethodReference(ImmutableArray args, MethodName n, ReferencePrefix p) { this.prefix = p; name = n; Debug.assertTrue(name != null, "Tried to reference unnamed method."); - this.arguments = args; - checkArguments(); + 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(); + + 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(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(); + } } - + public SourceElement getFirstElement() { return (prefix == null) ? getChildAt(0).getFirstElement() : prefix.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? getChildAt(0).getFirstElement() : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? getChildAt(0).getFirstElement() + : prefix.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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; index--; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; 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 - "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. - */ + * 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. + */ 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; - if (prefix instanceof Expression) result += 1; + if (prefix instanceof Expression) + result += 1; if (arguments != null) { result += arguments.size(); } @@ -190,17 +203,18 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (prefix instanceof Expression) { if (index == 0) { - return (Expression)prefix; + return (Expression) prefix; } index -= 1; } @@ -211,28 +225,32 @@ 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() { @@ -240,8 +258,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) { @@ -251,120 +270,108 @@ public Expression getArgumentAt(int index) { } /** - * determines the arguments types and constructs a signature of the current - * method + * determines the arguments types and constructs a signature of the current method */ - public ImmutableList getMethodSignature(Services services, - ExecutionContext ec) { - ImmutableList signature = ImmutableSLList.nil(); - if (arguments != null) { + public ImmutableList getMethodSignature(Services services, ExecutionContext ec) { + ImmutableList signature = ImmutableSLList.nil(); + if (arguments != null) { final TypeConverter typeConverter = services.getTypeConverter(); - for (int i = arguments.size()-1; i>=0; i--) { - signature = signature.prepend - (typeConverter.getKeYJavaType(getArgumentAt(i), ec)); - } - } - return signature; + for (int i = arguments.size() - 1; i >= 0; i--) { + signature = signature.prepend(typeConverter.getKeYJavaType(getArgumentAt(i), ec)); + } + } + return signature; } - + /** * returns the static KeYJavaType of the methods prefix */ - public KeYJavaType determineStaticPrefixType(Services services, - ExecutionContext ec) { - KeYJavaType prefixType; + public KeYJavaType determineStaticPrefixType(Services services, ExecutionContext ec) { + 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, - getMethodSignature(services, ec), + 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, - getMethodSignature(services, ec), - classType); - if(pm!=null){ + pm = method(services, classType, getMethodSignature(services, ec), classType); + if (pm != null) { return pm; } - inst = services.getJavaInfo().getAttribute( - ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS, classType); + inst = services.getJavaInfo().getAttribute(ImplicitFieldAdder.IMPLICIT_ENCLOSING_THIS, + classType); } 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, - methodName, signature, context); - return pm; + public IProgramMethod method(Services services, KeYJavaType classType, + ImmutableList signature, KeYJavaType context) { + final String methodName = name.toString(); + IProgramMethod pm = + services.getJavaInfo().getProgramMethod(classType, methodName, signature, context); + 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 - * perform some action/transformation on this element + /** + * 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/NameReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/NameReference.java index d180fde5885..40a6fdd3346 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/NameReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/NameReference.java @@ -1,11 +1,15 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; + import de.uka.ilkd.key.java.NamedProgramElement; import de.uka.ilkd.key.java.Reference; /** - * A NameReference references an entity by its explicite name. + * A NameReference references an entity by its explicite name. */ public interface NameReference extends NamedProgramElement, Reference { -} \ 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 e1a7f23d718..c8339c307dd 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -10,42 +13,41 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * Package reference. - * @author AutoDoc + * Package reference. + * + * @author AutoDoc */ public class PackageReference extends JavaNonTerminalProgramElement - implements TypeReferenceInfix, PackageReferenceContainer { + implements TypeReferenceInfix, PackageReferenceContainer { /** - * Prefix. + * Prefix. */ protected final ReferencePrefix prefix; /** - * Name. + * Name. */ 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. + * + * @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. */ public PackageReference(ExtList children) { - prefix=children.get(PackageReference.class); - name=children.get(ProgramElementName.class); - assert name != null; + prefix = children.get(PackageReference.class); + name = children.get(ProgramElementName.class); + assert name != null; } - public PackageReference(ProgramElementName name, - ReferencePrefix prefix) { - this.prefix = prefix; - this.name = name; - assert name != null; + public PackageReference(ProgramElementName name, ReferencePrefix prefix) { + this.prefix = prefix; + this.name = name; + assert name != null; } public SourceElement getFirstElement() { @@ -58,75 +60,84 @@ 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 */ public int getChildCount() { int result = 0; - if (prefix != null) result++; - if (name != null) result++; + if (prefix != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + 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. */ public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Get the package reference. - * @return the package reference. + * Get the package reference. + * + * @return the package reference. */ 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. */ public final String getName() { return (name == null) ? null : name.toString(); } /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public ProgramElementName getProgramElementName() { return name; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnPackageReference(this); + v.performActionOnPackageReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -134,23 +145,20 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + 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)); } public String toString() { return (prefix != null ? prefix.toString() + "." : "") + getName(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReferenceContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReferenceContainer.java index 7da185bf120..682b418e9cc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReferenceContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/PackageReferenceContainer.java @@ -1,16 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.NonTerminalProgramElement; /** - * Element that contains a PackageReference. - * @author AL + * Element that contains a PackageReference. + * + * @author AL */ public interface PackageReferenceContainer extends NonTerminalProgramElement { /** - * Get the package reference. - * @return the package reference. + * Get the package reference. + * + * @return the package reference. */ PackageReference getPackageReference(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferencePrefix.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferencePrefix.java index 80c60ff40c0..667e5580769 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferencePrefix.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferencePrefix.java @@ -1,13 +1,17 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.ProgramElement; /** - * Reference prefix. - * @author AutoDoc + * Reference prefix. + * + * @author AutoDoc */ public interface ReferencePrefix extends ProgramElement { ReferencePrefix getReferencePrefix(); - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferenceSuffix.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferenceSuffix.java index 125c5051bf7..8f551776d5c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferenceSuffix.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ReferenceSuffix.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.ModelElement; @@ -6,18 +9,16 @@ import de.uka.ilkd.key.java.SourceElement; /** - * Reference suffix. There are only few pure suffices, e.g. - * {@link SuperConstructorReference}. - * This interface does not extend {@link Reference}, as - * {@link recoder.java.expression.ParenthesizedExpression} is a qualifier - * but not a reference per se. + * Reference suffix. There are only few pure suffices, e.g. {@link SuperConstructorReference}. This + * interface does not extend {@link Reference}, as + * {@link recoder.java.expression.ParenthesizedExpression} is a qualifier but not a reference per + * se. */ -public interface ReferenceSuffix extends ModelElement, - ProgramElement, SourceElement { +public interface ReferenceSuffix extends ModelElement, ProgramElement, SourceElement { /** - * @return the prefix in the access path, or null if there is none. + * @return the prefix in the access path, or null if there is none. */ -// ReferencePrefix getReferencePrefix(); -} \ No newline at end of file + // ReferencePrefix getReferencePrefix(); +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchemaTypeReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchemaTypeReference.java index 2e14e867539..81a2ff65fa8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchemaTypeReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/SchemaTypeReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.PrettyPrinter; @@ -11,34 +14,32 @@ import de.uka.ilkd.key.rule.MatchConditions; -public class SchemaTypeReference extends TypeReferenceImp - implements AbstractProgramElement { +public class SchemaTypeReference extends TypeReferenceImp implements AbstractProgramElement { private final String fullName; - public SchemaTypeReference(ProgramElementName name, - int dimension, - ReferencePrefix prefix) { - super(name, dimension, prefix); - final StringBuffer sb = new StringBuffer(""); + public SchemaTypeReference(ProgramElementName name, int dimension, ReferencePrefix prefix) { + super(name, dimension, prefix); + final StringBuffer sb = new StringBuffer(""); - // as no inner classes prefix must be package reference - PackageReference rp = (PackageReference)prefix; - while (rp != null) { - sb.insert(0, rp.getName() + "."); - rp = (PackageReference) rp.getReferencePrefix(); - } - sb.append(name.toString()); - fullName = sb.toString(); + // as no inner classes prefix must be package reference + PackageReference rp = (PackageReference) prefix; + while (rp != null) { + sb.insert(0, rp.getName() + "."); + rp = (PackageReference) rp.getReferencePrefix(); + } + sb.append(name.toString()); + fullName = sb.toString(); } public KeYJavaType getKeYJavaType() { - return null; + return null; } public KeYJavaType getKeYJavaType(Services services) { - KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(fullName); - assert kjt != null : "KeYJavaType is null for SchemaTypeReference " + this + " - " + fullName; + KeYJavaType kjt = services.getJavaInfo().getKeYJavaType(fullName); + assert kjt != null + : "KeYJavaType is null for SchemaTypeReference " + this + " - " + fullName; return kjt; } @@ -49,25 +50,27 @@ public ProgramElement getConcreteProgramElement(Services services) { public MatchConditions match(SourceData source, MatchConditions matchCond) { ProgramElement t = source.getSource(); if (t instanceof TypeReference) { - if (getName().equals(((TypeReference)t).getName()) && - ((TypeReference)t).getDimensions() == getDimensions()) { - source.next(); + if (getName().equals(((TypeReference) t).getName()) + && ((TypeReference) t).getDimensions() == getDimensions()) { + source.next(); return matchCond; - } - } + } + } return null; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnAbstractProgramElement(this); + v.performActionOnAbstractProgramElement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSchemaTypeReference(this); } -} \ No newline at end of file +} 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 eb788ab7667..b4d2d796a53 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -16,63 +19,68 @@ import de.uka.ilkd.key.util.Debug; /** - * Field reference. - * @author AutoDoc + * 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(SchemaVariable pe, ReferencePrefix prefix) { - this.schemaVariable = pe; - this.prefix = prefix; + this.schemaVariable = pe; + this.prefix = prefix; } public SchematicFieldReference(ExtList children, ReferencePrefix prefix) { - this.schemaVariable = children.get(SchemaVariable.class); - this.prefix = prefix; + this.schemaVariable = children.get(SchemaVariable.class); + this.prefix = prefix; } /** * 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 (schemaVariable != null) result++; + if (prefix != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; 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() { @@ -81,25 +89,28 @@ public ReferencePrefix getReferencePrefix() { /** * 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() { @@ -107,22 +118,23 @@ public int getTypeReferenceCount() { } /** - * Return the type reference at the specified index in this node's - * "virtual" type reference array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ 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. */ public int getExpressionCount() { @@ -130,67 +142,68 @@ public int getExpressionCount() { } /** - * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { if (prefix instanceof Expression && index == 0) { - return (Expression)prefix; + return (Expression) prefix; } throw new ArrayIndexOutOfBoundsException(); } public SourceElement getFirstElement() { - return (prefix == null) ? (ProgramSV)schemaVariable : prefix.getFirstElement(); + return (prefix == null) ? (ProgramSV) schemaVariable : prefix.getFirstElement(); } @Override public SourceElement getFirstElementIncludingBlocks() { - return (prefix == null) ? (ProgramSV)schemaVariable : prefix.getFirstElementIncludingBlocks(); + return (prefix == null) ? (ProgramSV) schemaVariable + : prefix.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 + /** + * 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); } 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); + LOGGER.debug("Program match failed. SchematicFieldReferences matches " + + "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 e8b8fd4ecdd..1a059130070 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -9,84 +12,81 @@ import de.uka.ilkd.key.java.ProgramElement; /** - * 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 { +public abstract class SpecialConstructorReference extends JavaNonTerminalProgramElement + implements ConstructorReference { + - protected final ImmutableArray arguments; - + public SpecialConstructorReference() { - this.arguments = null; + this.arguments = null; } /** * Special constructor reference. + * * @param arguments an expression mutable list. */ public SpecialConstructorReference(Expression[] arguments) { - this.arguments = new ImmutableArray(arguments); + this.arguments = new ImmutableArray(arguments); } /** * Special constructor reference. + * * @param arguments an expression mutable list. */ public SpecialConstructorReference(ImmutableArray arguments) { - this.arguments = arguments; + this.arguments = 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 - */ + * + * @param children the children of this AST element as KeY classes. 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 - */ + * + * @param children the children of this AST element as KeY classes. 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (arguments != null) { @@ -94,10 +94,11 @@ public ProgramElement getChildAt(int index) { } 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() { @@ -105,13 +106,14 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (arguments != null) { return arguments.get(index); @@ -120,10 +122,11 @@ public Expression getExpressionAt(int index) { } /** - * Get arguments. - * @return the expression mutable list. + * Get arguments. + * + * @return the expression mutable list. */ public ImmutableArray getArguments() { return arguments; } -} \ No newline at end of file +} 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 67b77a06f76..cdc205b8d8c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -10,54 +13,55 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Super constructor reference. + * Super constructor reference. */ public class SuperConstructorReference extends SpecialConstructorReference - implements ReferenceSuffix { + implements ReferenceSuffix { + - /** - * Access path to enclosing class. - * As KeY normalises inner classes this should be always null and may be - * removed in future + * Access path to enclosing class. As KeY normalises inner classes this should be always null + * and may be removed in future */ protected final ReferencePrefix prefix; - + public SuperConstructorReference() { - prefix = null; + prefix = null; } /** - * Super constructor reference. - * @param arguments an expression mutable list. + * Super constructor reference. + * + * @param arguments an expression mutable list. */ public SuperConstructorReference(Expression[] arguments) { super(arguments); - this.prefix = null; + this.prefix = null; } /** - * Super constructor reference. - * @param accessPath a reference prefix. - * @param arguments an expression mutable list. + * Super constructor reference. + * + * @param accessPath a reference prefix. + * @param arguments an expression mutable list. */ - public SuperConstructorReference(ReferencePrefix accessPath, - Expression[] arguments) { + public SuperConstructorReference(ReferencePrefix accessPath, Expression[] arguments) { super(arguments); this.prefix = accessPath; } /** - * Super constructor reference. - * @param accessPath a reference prefix. - * @param arguments an expression mutable list. + * Super constructor reference. + * + * @param accessPath a reference prefix. + * @param arguments an expression mutable list. */ public SuperConstructorReference(ReferencePrefix accessPath, - ImmutableArray arguments) { + ImmutableArray arguments) { super(arguments); this.prefix = accessPath; } @@ -66,40 +70,32 @@ public SuperConstructorReference(ReferencePrefix accessPath, /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * @param accessPath a ReferencePrefix of the array reference. - * May contain: - * several of Expression (as initializers of the array), - * Comments. - * Must contain: - * execution context - * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because - * Expression and ReferencePrefix might not be disjunct. - */ - public SuperConstructorReference(ExtList children, - ReferencePrefix accessPath, - PositionInfo pi) { - super(children, pi); - this.prefix = accessPath; + * @param accessPath a ReferencePrefix of the array reference. May contain: several of + * Expression (as initializers of the array), Comments. Must contain: execution context + * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because Expression and + * ReferencePrefix might not be disjunct. + */ + public SuperConstructorReference(ExtList children, ReferencePrefix accessPath, + PositionInfo pi) { + super(children, pi); + this.prefix = accessPath; } - + /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - * @param accessPath a ReferencePrefix of the array reference. - * May contain: - * several of Expression (as initializers of the array), - * Comments. - * Must contain: - * execution context - * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because - * Expression and ReferencePrefix might not be disjunct. - */ - public SuperConstructorReference(ExtList children, - ReferencePrefix accessPath) { - super(children); - this.prefix = accessPath; + * @param accessPath a ReferencePrefix of the array reference. May contain: several of + * Expression (as initializers of the array), Comments. Must contain: execution context + * MUST NOT CONTAIN: the ReferencePrefix for the accessPath because Expression and + * ReferencePrefix might not be disjunct. + */ + public SuperConstructorReference(ExtList children, ReferencePrefix accessPath) { + super(children); + this.prefix = accessPath; } @@ -108,8 +104,8 @@ public ReferencePrefix getReferencePrefix() { return prefix; } - - @Override + + @Override public SourceElement getFirstElement() { return (prefix == null) ? this : prefix.getFirstElement(); } @@ -118,16 +114,16 @@ public SourceElement getFirstElement() { public SourceElement getFirstElementIncludingBlocks() { return (prefix == null) ? this : prefix.getFirstElementIncludingBlocks(); } - + @Override public void visit(Visitor v) { - v.performActionOnSuperConstructorReference(this); + v.performActionOnSuperConstructorReference(this); } - - @Override + + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printSuperConstructorReference(this); } -} \ No newline at end of file +} 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 1ff6069f774..61ce1ab905b 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -14,31 +17,30 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Super reference. - * + * Super reference. + * */ -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. */ private final ReferencePrefix prefix; /** - * Super reference. + * Super reference. */ public SuperReference() { prefix = null; } /** - * Super reference. - * @param accessPath a reference expression. + * Super reference. + * + * @param accessPath a reference expression. */ public SuperReference(ReferencePrefix accessPath) { this.prefix = accessPath; @@ -46,10 +48,11 @@ public SuperReference(ReferencePrefix 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); + prefix = children.get(ReferencePrefix.class); } @@ -63,8 +66,9 @@ public SourceElement getFirstElementIncludingBlocks() { } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ public ReferencePrefix getReferencePrefix() { @@ -72,33 +76,36 @@ public ReferencePrefix getReferencePrefix() { } /** - * 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 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; - } + 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. */ public int getExpressionCount() { @@ -106,52 +113,58 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ 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. */ public int getTypeReferenceCount() { return (prefix 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. - */ + * 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. + */ 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 - * perform some action/transformation on this element + /** + * 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.performActionOnSuperReference(this); + v.performActionOnSuperReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -159,15 +172,14 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; + return this; } /** - * returns the KeYJavaType + * returns the KeYJavaType */ 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/ThisConstructorReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisConstructorReference.java index 65dabb5080e..e2b8ad55910 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisConstructorReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/ThisConstructorReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -9,21 +12,22 @@ /** - * This constructor reference. + * This constructor reference. */ public class ThisConstructorReference extends SpecialConstructorReference { /** - * This constructor reference. + * This constructor reference. */ public ThisConstructorReference() { - super(); + super(); } - + /** - * This constructor reference. - * @param arguments an expression mutable list. + * This constructor reference. + * + * @param arguments an expression mutable list. */ public ThisConstructorReference(Expression[] arguments) { super(arguments); @@ -32,45 +36,45 @@ public ThisConstructorReference(Expression[] arguments) { /** * This constructor reference. + * * @param arguments an expression mutable list. */ public ThisConstructorReference(ImmutableArray arguments) { super(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 - * Must contain: - * execution context - */ + * + * @param children the children of this AST element as KeY classes. May contain: several of + * Expression (as initializers of the array), Comments Must contain: execution context + */ public ThisConstructorReference(ExtList children) { - super(children); + super(children); } - - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + + /** + * calls the corresponding method of a visitor in order to perform some action/transformation on + * this element + * * @param v the Visitor */ - @Override + @Override public void visit(Visitor v) { - v.performActionOnThisConstructorReference(this); + v.performActionOnThisConstructorReference(this); } - + @Override public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printThisConstructorReference(this); } - - + + @Override public ReferencePrefix getReferencePrefix() { return null; } -} \ 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 a0e371c7811..88581d122a4 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -13,47 +16,45 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * 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 { - +public class ThisReference extends JavaNonTerminalProgramElement + implements Reference, Expression, ReferencePrefix, ReferenceSuffix, TypeReferenceContainer { + /** - * Prefix. + * Prefix. */ private final ReferencePrefix prefix; /** - * This reference. + * This reference. */ public ThisReference() { - prefix = null; + prefix = null; } /** - * This reference. - * @param outer a type reference. + * This reference. + * + * @param outer a type reference. */ public ThisReference(TypeReference outer) { - prefix = outer; + prefix = 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 - */ + * + * @param children the children of this AST element as KeY classes. 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); } @@ -67,68 +68,76 @@ 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 */ 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get reference prefix. - * @return the reference prefix. + * Get reference prefix. + * + * @return the reference prefix. */ 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. */ public int getTypeReferenceCount() { return (prefix != null) ? 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. - */ + * 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. + */ 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 - * perform some action/transformation on this element + /** + * 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.performActionOnThisReference(this); + v.performActionOnThisReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -136,12 +145,11 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { } public ReferencePrefix setReferencePrefix(ReferencePrefix r) { - return this; - } + return this; + } - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return ec.getTypeReference().getKeYJavaType(); + 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/TypeRef.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeRef.java index 9d2ead26c24..9213179c30a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeRef.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeRef.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -9,44 +12,41 @@ public class TypeRef extends TypeReferenceImp { private KeYJavaType kjt = null; - /** creates a type reference for the given KeYJavaType with - * dimension 0 and creates a suitable package reference prefix - * from the KeYJavaType. If this is not desired use the - * constructor TypeRef(ProgramElementName, int, ReferencePrefix, - * KeYJavaType) and take null as last argument. + /** + * creates a type reference for the given KeYJavaType with dimension 0 and creates a suitable + * package reference prefix from the KeYJavaType. If this is not desired use the constructor + * TypeRef(ProgramElementName, int, ReferencePrefix, KeYJavaType) and take null as last + * argument. */ public TypeRef(KeYJavaType kjt) { - this(kjt, 0); + this(kjt, 0); } - /** creates a type reference for the given KeYJavaType and the - * given dimension and creates a suitable package reference prefix - * from the KeYJavaType. If this is not desired use the constructor - * TypeRef(ProgramElementName, int, ReferencePrefix, KeYJavaType) - * and take null as last argument. + /** + * creates a type reference for the given KeYJavaType and the given dimension and creates a + * suitable package reference prefix from the KeYJavaType. If this is not desired use the + * constructor TypeRef(ProgramElementName, int, ReferencePrefix, KeYJavaType) and take null as + * last argument. */ public TypeRef(KeYJavaType kjt, int dim) { - super(new ProgramElementName(kjt.getName()), - dim, kjt.createPackagePrefix()); - this.kjt = kjt; + super(new ProgramElementName(kjt.getName()), dim, kjt.createPackagePrefix()); + this.kjt = kjt; } public TypeRef(ExtList children, KeYJavaType kjt, int dim) { - super(children, dim); - this.kjt = kjt; + super(children, dim); + this.kjt = kjt; } - public TypeRef(ProgramElementName name, - int dimension, - ReferencePrefix prefix, - KeYJavaType kjt) { - super(name, dimension, prefix); - this.kjt = kjt; + public TypeRef(ProgramElementName name, int dimension, ReferencePrefix prefix, + KeYJavaType kjt) { + super(name, dimension, prefix); + this.kjt = kjt; } public KeYJavaType getKeYJavaType() { - return kjt; + return kjt; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReference.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReference.java index d7960bdd3eb..66b280a2c30 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReference.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReference.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.NonTerminalProgramElement; @@ -6,16 +9,14 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * 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}. + * 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 interface TypeReference - extends TypeReferenceInfix, TypeReferenceContainer, PackageReferenceContainer, MemberReference, NonTerminalProgramElement, SourceElement { +public interface TypeReference extends TypeReferenceInfix, TypeReferenceContainer, + PackageReferenceContainer, MemberReference, NonTerminalProgramElement, SourceElement { String getName(); @@ -26,4 +27,4 @@ public interface TypeReference int getDimensions(); KeYJavaType getKeYJavaType(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceContainer.java index 24ad69be651..66070c5444a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceContainer.java @@ -1,27 +1,33 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import de.uka.ilkd.key.java.NonTerminalProgramElement; /** - * Type reference container. - * + * Type reference container. + * */ public interface TypeReferenceContainer extends NonTerminalProgramElement { /** - * 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. */ int getTypeReferenceCount(); /* - 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. - */ + * 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. + */ TypeReference getTypeReferenceAt(int index); -} \ 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 174f2719dfa..fb41dea427e 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -12,64 +15,59 @@ 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}. + * 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 { +public abstract class TypeReferenceImp extends JavaNonTerminalProgramElement + implements TypeReference { /** - * Prefix. + * Prefix. */ protected ReferencePrefix prefix; /** - * Dimensions. + * Dimensions. */ protected int dimensions; /** - * Name. + * Name. */ protected ProgramElementName 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 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 */ 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.name = name; + this.dimensions = dimension; + this.prefix = prefix; } @@ -83,109 +81,121 @@ 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 */ public int getChildCount() { int result = 0; - if (prefix != null) result++; - if (name != null) result++; + if (prefix != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (prefix != null) { - if (index == 0) return prefix; + if (index == 0) + return prefix; index--; } if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; } 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 - "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. - */ + * 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. + */ 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; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ 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. */ public ReferencePrefix getReferencePrefix() { return prefix; } /** - * Get the package reference. - * @return the package reference. + * Get the package reference. + * + * @return the package reference. */ 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. */ public int getDimensions() { return dimensions; } /** - * Get name. - * @return the string. + * Get name. + * + * @return the string. */ public final String getName() { return (name == null) ? null : name.toString(); @@ -194,21 +204,24 @@ public final String getName() { public abstract KeYJavaType getKeYJavaType(); /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public ProgramElementName getProgramElementName() { return name; } - - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + + /** + * 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.performActionOnTypeReference(this); + v.performActionOnTypeReference(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { @@ -217,11 +230,12 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { 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/TypeReferenceInfix.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceInfix.java index 5b5de59c294..a9081b82e88 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceInfix.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/reference/TypeReferenceInfix.java @@ -1,9 +1,11 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; /** - * ReferencePrefix and -suffix that is admissible for outer type references. + * ReferencePrefix and -suffix that is admissible for outer type references. */ -public interface TypeReferenceInfix - extends ReferencePrefix, ReferenceSuffix, NameReference { +public interface TypeReferenceInfix extends ReferencePrefix, ReferenceSuffix, NameReference { -} \ 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 529cfd32f54..82ce9ea4b88 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.reference; import org.key_project.util.ExtList; @@ -17,8 +20,7 @@ public class VariableReference extends JavaNonTerminalProgramElement - implements NameReference, Expression, - ReferencePrefix { + implements NameReference, Expression, ReferencePrefix { protected final ProgramVariable variable; @@ -32,17 +34,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() { @@ -50,12 +52,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (variable != null) { @@ -66,8 +67,8 @@ public ProgramElement getChildAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - public ProgramElementName getIdentifier(){ - return (ProgramElementName) variable.name(); + public ProgramElementName getIdentifier() { + return (ProgramElementName) variable.name(); } @@ -85,29 +86,30 @@ public SourceElement getFirstElement() { } 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 + * 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 + * 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; } /** @@ -117,16 +119,15 @@ public ReferencePrefix setReferencePrefix(ReferencePrefix r) { * @param ec the execution context * @return the KeY java type */ - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { + public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { return getKeYJavaType(); } 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/Assert.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Assert.java index d7484fb47bf..c00e783ab57 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Assert.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Assert.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import de.uka.ilkd.key.java.Expression; @@ -17,28 +20,32 @@ public Assert(Expression condition, Expression message, PositionInfo pos) { super(pos); assert condition != null; this.condition = condition; - this.message = message; + this.message = message; } - + public Expression getExpressionAt(int index) { - if (index == 0) { return condition; } + if (index == 0) { + return condition; + } index--; - if (index == 0) { - if (message != null) { return message; } + if (index == 0) { + if (message != null) { + return message; + } } throw new IndexOutOfBoundsException(); } - public int getExpressionCount() { + public int getExpressionCount() { return message == null ? 1 : 2; } - public ProgramElement getChildAt(int index) { + public ProgramElement getChildAt(int index) { return getExpressionAt(index); } - public int getChildCount() { + public int getChildCount() { return getExpressionCount(); } @@ -49,12 +56,12 @@ public void visit(Visitor v) { public Expression getCondition() { return condition; } - + public Expression getMessage() { return message; } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printAssert(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Branch.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Branch.java index 85a42a57c2a..14b56596bdf 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Branch.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Branch.java @@ -1,14 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import de.uka.ilkd.key.java.StatementContainer; /** - * Branch. - * @author AutoDoc + * Branch. + * + * @author AutoDoc */ public interface Branch extends StatementContainer { -} \ 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 f38c62abc40..d213650875e 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -6,25 +9,25 @@ import de.uka.ilkd.key.java.PositionInfo; /** - * Branch. - * @author AutoDoc + * Branch. + * + * @author AutoDoc */ -public abstract class BranchImp - extends JavaNonTerminalProgramElement implements Branch { +public abstract class BranchImp extends JavaNonTerminalProgramElement implements Branch { /** * 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); + super(children); } public BranchImp() { - super(); + super(); } @@ -33,4 +36,4 @@ public BranchImp(ExtList children, PositionInfo 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 c58b00ef977..586f24b7670 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -5,42 +8,45 @@ import de.uka.ilkd.key.java.NonTerminalProgramElement; /** - * Branch statement. - * @author AL - * @author AutoDoc + * Branch statement. + * + * @author AL + * @author AutoDoc */ public abstract class BranchStatement extends JavaStatement implements NonTerminalProgramElement { public BranchStatement() { - + } /** * 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 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(); /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public abstract Branch getBranchAt(int index); -} \ No newline at end of file +} 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 548d48efe84..252e60bb629 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -7,23 +10,24 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Break. - * + * Break. + * */ public class Break extends LabelJumpStatement { /** - * Break. + * Break. */ public Break() { - super(); + super(); } /** - * Break. - * @param label a name for the label. + * Break. + * + * @param label a name for the label. */ public Break(Label label) { super(label); @@ -31,24 +35,26 @@ public Break(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) - */ + * + * @param children the children of this AST element as KeY classes. 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); + // label=(ProgramElementName)children.get(ProgramElementName.class); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printBreak(this); } -} \ No newline at end of file +} 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 3808e10e3af..446f4bf5c19 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -10,90 +13,95 @@ import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.Statement; import de.uka.ilkd.key.java.visitor.Visitor; + /** - * Case. - * + * Case. + * */ public class Case extends BranchImp implements ExpressionContainer { /** - * Expression. + * Expression. */ protected final Expression expression; /** - * Body. + * Body. */ protected final ImmutableArray body; /** - * Case. + * Case. */ public Case() { - this.expression=null; - this.body=null; + this.expression = null; + this.body = null; } /** - * Case. - * @param e an expression. + * Case. + * + * @param e an expression. */ public Case(Expression e) { - this.expression=e; - this.body=null; + this.expression = e; + this.body = null; } /** - * 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.body = new ImmutableArray(body); + this.expression = e; } /** * 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 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 - */ + */ 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 (expression != null) + result++; + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; if (expression != null) { - if (index == 0) return expression; + if (index == 0) + return expression; index--; } if (body != null) { @@ -106,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() { @@ -115,13 +124,14 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (expression != null && index == 0) { return expression; @@ -130,21 +140,23 @@ 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; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null) { return body.get(index); @@ -153,30 +165,33 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printCase(this); } -} \ No newline at end of file +} 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 216613cae1b..20573775a22 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -11,57 +14,57 @@ import de.uka.ilkd.key.java.VariableScope; import de.uka.ilkd.key.java.declaration.ParameterDeclaration; import de.uka.ilkd.key.java.visitor.Visitor; + /** - * Catch. - * + * Catch. + * */ -public class Catch extends BranchImp implements ParameterContainer, - VariableScope { +public class Catch extends BranchImp implements ParameterContainer, VariableScope { /** - * Parameter. + * Parameter. */ protected final ParameterDeclaration parameter; /** - * Body. + * Body. */ protected final StatementBlock body; /** - * Catch. + * Catch. */ public Catch() { - super(); - parameter=null; - body=null; + super(); + parameter = null; + body = null; } /** - * 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; + this.body = body; + parameter = e; } /** * 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 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); } public SourceElement getLastElement() { @@ -69,52 +72,58 @@ 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 */ public int getChildCount() { int result = 0; - if (parameter != null) result++; - if (body != null) result++; + if (parameter != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (parameter != null) { - if (index == 0) return parameter; + if (index == 0) + return parameter; index--; } if (body != null) { - if (index == 0) return body; + 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 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { return body; @@ -123,21 +132,24 @@ 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; } /* - Return the parameter declaration at the specified index in this node's - "virtual" parameter declaration array. - @param index an index for a parameter declaration. - @return the parameter declaration with the given index. - @exception ArrayIndexOutOfBoundsException if index is out - of bounds. - */ + * Return the parameter declaration at the specified index in this node's "virtual" parameter + * declaration array. + * + * @param index an index for a parameter declaration. + * + * @return the parameter declaration with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public ParameterDeclaration getParameterDeclarationAt(int index) { if (parameter != null && index == 0) { return parameter; @@ -146,30 +158,34 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printCatch(this); } -} \ No newline at end of file +} 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 ac6a9d6dcc0..3b406cd1b6f 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -15,109 +18,112 @@ public class CatchAllStatement extends JavaNonTerminalProgramElement - implements Statement, - NonTerminalProgramElement, -// Desugarable, - StatementContainer { + implements Statement, NonTerminalProgramElement, + // Desugarable, + StatementContainer { private StatementBlock body; private LocationVariable param; public CatchAllStatement(StatementBlock body, LocationVariable param) { - this.body = body; - this.param = param; + this.body = body; + this.param = 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 */ 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; } - + public Statement getStatementAt(int i) { return body; } - - + + 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ 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 - * perform some action/transformation on this element + + + /** + * 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.performActionOnCatchAllStatement(this); + v.performActionOnCatchAllStatement(this); } - + public void prettyPrint(PrettyPrinter p) throws java.io.IOException { - p.printCatchAllStatement(this); + p.printCatchAllStatement(this); } - - -// public Object desugar() { -// IProgramVariable pv = getParameterDeclaration() -// .getVariableSpecification().getProgramVariable(); -// LocalVariableDeclaration lvd = new LocalVariableDeclaration -// (new TypeRef(pv.getKeYJavaType()), -// new VariableSpecification(pv, 0, NullLiteral.NULL, -// pv.getKeYJavaType())); -// ProgramVariable paramExc = new LocationVariable -// (new ProgramElementName("e"), -// pv.getKeYJavaType()); -// CopyAssignment ass = new CopyAssignment((Expression)pv, paramExc); -// ParameterDeclaration parDecl -// = new ParameterDeclaration(new Modifier[0], -// new TypeRef(pv.getKeYJavaType()), -// new VariableSpecification(paramExc), -// false); -// Catch catchBranch = new Catch(parDecl, new StatementBlock(ass)); -// Try tryBlock = new Try(body, new Branch[]{catchBranch}); -// return new StatementBlock(new Statement[]{lvd, tryBlock}); -// } -} \ No newline at end of file + + + // public Object desugar() { + // IProgramVariable pv = getParameterDeclaration() + // .getVariableSpecification().getProgramVariable(); + // LocalVariableDeclaration lvd = new LocalVariableDeclaration + // (new TypeRef(pv.getKeYJavaType()), + // new VariableSpecification(pv, 0, NullLiteral.NULL, + // pv.getKeYJavaType())); + // ProgramVariable paramExc = new LocationVariable + // (new ProgramElementName("e"), + // pv.getKeYJavaType()); + // CopyAssignment ass = new CopyAssignment((Expression)pv, paramExc); + // ParameterDeclaration parDecl + // = new ParameterDeclaration(new Modifier[0], + // new TypeRef(pv.getKeYJavaType()), + // new VariableSpecification(paramExc), + // false); + // Catch catchBranch = new Catch(parDecl, new StatementBlock(ass)); + // Try tryBlock = new Try(body, new Branch[]{catchBranch}); + // return new StatementBlock(new Statement[]{lvd, tryBlock}); + // } +} 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 9f8a2fb91f8..5be8dcd98e0 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import java.util.Optional; @@ -19,8 +22,7 @@ * Ccatch. * */ -public class Ccatch extends BranchImp - implements ParameterContainer, VariableScope { +public class Ccatch extends BranchImp implements ParameterContainer, VariableScope { /** * Parameter. @@ -46,10 +48,8 @@ public Ccatch() { /** * 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(); @@ -61,13 +61,10 @@ public Ccatch(ParameterDeclaration e, StatementBlock 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) { + public Ccatch(CcatchNonstandardParameterDeclaration e, StatementBlock body) { super(); this.body = body; parameter = Optional.empty(); @@ -77,18 +74,15 @@ public Ccatch(CcatchNonstandardParameterDeclaration e, /** * 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 = Optional.ofNullable(children.get(ParameterDeclaration.class)); + nonStdParameter = + Optional.ofNullable(children.get(CcatchNonstandardParameterDeclaration.class)); body = children.get(StatementBlock.class); } @@ -123,14 +117,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -163,15 +154,13 @@ public int getStatementCount() { } /* - * Return the statement at the specified index in this node's "virtual" - * statement array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { @@ -192,16 +181,14 @@ public int getParameterDeclarationCount() { } /** - * Return the parameter declaration at the specified index in this node's - * "virtual" parameter declaration array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public ParameterDeclaration getParameterDeclarationAt(int index) { @@ -212,19 +199,16 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { } /** - * Return the non-standard parameter declaration at the specified index in - * this node's "virtual" parameter declaration array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ - public CcatchNonstandardParameterDeclaration getNonStdParameterDeclarationAt( - int index) { + public CcatchNonstandardParameterDeclaration getNonStdParameterDeclarationAt(int index) { if (hasNonStdParameterDeclaration() && index == 0) { return nonStdParameter.get(); } @@ -259,11 +243,10 @@ public CcatchNonstandardParameterDeclaration getNonStdParameterDeclaration() { } /** - * calls the corresponding method of a visitor in order to perform some - * action/transformation on this element + * 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) { @@ -274,4 +257,4 @@ public void visit(Visitor v) { public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printCcatch(this); } -} \ No newline at end of file +} 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 766eb975965..daddfe4da41 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -7,21 +10,22 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Continue. - * + * Continue. + * */ public class Continue extends LabelJumpStatement { /** - * Continue. + * Continue. */ public Continue() { - super(); + super(); } /** - * Continue. - * @param label an identifier. + * Continue. + * + * @param label an identifier. */ public Continue(Label label) { super(label); @@ -29,23 +33,25 @@ 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) - */ + * + * @param children the children of this AST element as KeY classes. 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 - * perform some action/transformation on this element + /** + * 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 { p.printContinue(this); } -} \ No newline at end of file +} 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 2de59556073..873ed21092a 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -7,61 +10,64 @@ import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.Statement; import de.uka.ilkd.key.java.visitor.Visitor; + /** - * Default. - * + * Default. + * */ public class Default extends BranchImp { /** - * Body. + * Body. */ protected final ImmutableArray body; /** - * Default. + * Default. */ public Default() { - this.body=null; + this.body = null; } /** - * Default. - * @param body a statement array. + * Default. + * + * @param body a statement array. */ public Default(Statement[] body) { - this.body=new ImmutableArray(body); + this.body = 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; - 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { int len; @@ -75,21 +81,23 @@ 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; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null) { return body.get(index); @@ -98,22 +106,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printDefault(this); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Desugarable.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Desugarable.java index 1066105e1f1..53353e603c7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Desugarable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/Desugarable.java @@ -1,7 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; public interface Desugarable { Object desugar(); -} \ No newline at end of file +} 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 a935d361f1c..3808ab48f43 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -10,42 +13,45 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Do. - * + * Do. + * */ public class Do extends LoopStatement { /** - * Do. + * Do. */ public Do() { - super(); + super(); } /** - * 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); } public SourceElement getLastElement() { @@ -53,19 +59,22 @@ public SourceElement getLastElement() { } /** - * 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 - * perform some action/transformation on this element + /** + * 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 edd28dc79fc..3eaa5fde442 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -9,36 +12,37 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Else. + * Else. */ public class Else extends BranchImp { /** - * Body. + * Body. */ protected Statement 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 - */ + * + * @param children the children of this AST element as KeY classes. 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; + this.body = body; } @@ -47,44 +51,47 @@ 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 */ public int getChildCount() { return (body != 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 + * @exception 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 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { return body; @@ -93,22 +100,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printElse(this); } -} \ No newline at end of file +} 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 a9b6d185ed9..8499564ad8d 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -11,38 +14,41 @@ /** - * Empty statement. - * @author AutoDoc + * Empty statement. + * + * @author AutoDoc */ public class EmptyStatement extends JavaProgramElement - implements Statement, TerminalProgramElement { + implements Statement, TerminalProgramElement { /** * Constructor for the transformation of COMPOST ASTs to KeY. + * * @param children the children of this AST element as KeY classes. - */ + */ public EmptyStatement(ExtList children) { - super(children); + super(children); } /** - * Constructor for the transformation of COMPOST ASTs to KeY. - * May contain: Comments - */ + * Constructor for the transformation of COMPOST ASTs to KeY. May contain: Comments + */ public EmptyStatement() { - super(); + super(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 1cd3cc77454..ff58e3a14ad 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -13,12 +16,12 @@ /** * The new enhanced form of a for-loop. - * + * * for(Type var : exp) Statement - * - * LoopStatement.inits is initialized with "Type var" LoopStatement.guard is - * initialized with "exp" LoopStatement.body with "statement" - * + * + * LoopStatement.inits is initialized with "Type var" LoopStatement.guard is initialized with "exp" + * LoopStatement.body with "statement" + * * @author mulbrich */ public class EnhancedFor extends LoopStatement implements VariableScope { @@ -26,25 +29,19 @@ public class EnhancedFor extends LoopStatement implements VariableScope { /** * create empty for loop. */ - public EnhancedFor() { - } + public EnhancedFor() {} /** * Used for the Recoder2KeY transformation. - * - * @param init - * the initializers - here a single VariableDeclaration. may not be null. - * @param guard - * a guard - here an expression of type Iterable. may not be null. - * @param statement - * the statement of the loop - * @param comments - * collected comments - * @param info - * position + * + * @param init the initializers - here a single VariableDeclaration. may not be null. + * @param guard a guard - here an expression of type Iterable. may not be null. + * @param statement the statement of the loop + * @param comments collected comments + * @param info position */ - public EnhancedFor(LoopInit init, Guard guard, Statement statement, - ExtList comments, PositionInfo info) { + public EnhancedFor(LoopInit init, Guard guard, Statement statement, ExtList comments, + PositionInfo info) { super(init, guard, null, statement, comments, info); assert init != null; assert guard != null; @@ -52,13 +49,12 @@ public EnhancedFor(LoopInit init, Guard guard, Statement statement, /** * Used by the {@link CreatingASTVisitor}. - * + * * @param children a list of parameters */ public EnhancedFor(ExtList children) { - super(children.get(ILoopInit.class), children - .get(IGuard.class), null, children - .get(Statement.class), children); + super(children.get(ILoopInit.class), children.get(IGuard.class), null, + children.get(Statement.class), children); } /** @@ -85,14 +81,15 @@ public void visit(Visitor v) { public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printEnhancedFor(this); } - + /** - * get the local variable declaration of the enhanced for-loop - * for(type var : exp) gives type var. + * get the local variable declaration of the enhanced for-loop for(type var : exp) + * gives type var. + * * @return the local variable declaration. */ public LocalVariableDeclaration getVariableDeclaration() { - return (LocalVariableDeclaration)getInitializers().get(0); + return (LocalVariableDeclaration) getInitializers().get(0); } -} \ No newline at end of file +} 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 eb562f46b91..f45d8e37a13 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -19,8 +22,7 @@ * * @author AutoDoc */ -public class Exec extends BranchStatement - implements StatementContainer, ProgramPrefix { +public class Exec extends BranchStatement implements StatementContainer, ProgramPrefix { /** * Body. @@ -39,14 +41,12 @@ public class Exec extends BranchStatement /** * Exec. * - * @param body - * a statement block. + * @param body a statement block. */ public Exec(StatementBlock body) { this.body = body; this.branches = null; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); } @@ -54,16 +54,13 @@ 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) { this.body = body; this.branches = new ImmutableArray(branches); - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -72,16 +69,13 @@ 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) { this.body = body; this.branches = branches; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -90,16 +84,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)); - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + this.branches = new ImmutableArray(children.collect(Branch.class)); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -107,8 +98,7 @@ public Exec(ExtList children) { @Override public boolean hasNextPrefixElement() { - return !body.isEmpty() - && body.getStatementAt(0) instanceof ProgramPrefix; + return !body.isEmpty() && body.getStatementAt(0) instanceof ProgramPrefix; } @Override @@ -116,16 +106,13 @@ public ProgramPrefix getNextPrefixElement() { if (hasNextPrefixElement()) { return (ProgramPrefix) body.getStatementAt(0); } else { - throw new IndexOutOfBoundsException( - "No next prefix element " + this); + throw new IndexOutOfBoundsException("No next prefix element " + this); } } @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() - ? getNextPrefixElement().getLastPrefixElement() - : this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : this; } @Override @@ -169,14 +156,11 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" child - * array + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -212,16 +196,13 @@ public int getStatementCount() { } /** - * Return the statement at the specified index in this node's "virtual" - * statement array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { @@ -242,14 +223,11 @@ public int getBranchCount() { } /** - * Return the branch at the specified index in this node's "virtual" branch - * array. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Branch getBranchAt(int index) { @@ -269,11 +247,10 @@ public ImmutableArray getBranchList() { } /** - * calls the corresponding method of a visitor in order to perform some - * action/transformation on this element + * 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) { @@ -289,4 +266,4 @@ public void prettyPrint(PrettyPrinter p) throws java.io.IOException { public PosInProgram getFirstActiveChildPos() { 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/ExpressionJumpStatement.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ExpressionJumpStatement.java index 2a9bf663af2..330bca37af1 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -5,61 +8,62 @@ import de.uka.ilkd.key.java.Expression; import de.uka.ilkd.key.java.ExpressionContainer; import de.uka.ilkd.key.java.ProgramElement; + /** - * Expression jump statement. - * @author AutoDoc + * Expression jump statement. + * + * @author AutoDoc */ public abstract class ExpressionJumpStatement extends JumpStatement implements ExpressionContainer { /** - * Expression. + * Expression. */ protected final Expression expression; /** - * Expression jump statement. - * May contain: an Expression (as expression of the - * ExpressionJumpStatement), - * Comments + * Expression jump statement. May contain: an Expression (as expression of the + * 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. */ public ExpressionJumpStatement() { - expression=null; + expression = 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; + expression = 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (expression != null && index == 0) { return expression; @@ -68,33 +72,35 @@ 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; } /** - * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (expression != null) { - if (index == 0) return expression; + if (index == 0) + return expression; } throw new ArrayIndexOutOfBoundsException(); } -} \ No newline at end of file +} 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 d391724a0fc..3faf23d4ba2 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -10,26 +13,27 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Finally. - * + * Finally. + * */ public class Finally extends BranchImp { /** - * Body. + * Body. */ protected StatementBlock body; /** - * Finally. + * Finally. */ public Finally() { - body=null; + body = null; } /** - * Finally. - * @param body a statement. + * Finally. + * + * @param body a statement. */ public Finally(StatementBlock body) { this.body = body; @@ -38,56 +42,61 @@ public Finally(StatementBlock 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 - */ + * + * @param children the children of this AST element as KeY classes. 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++; + 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 + * @exception 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 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { return body; @@ -96,8 +105,9 @@ public Statement getStatementAt(int index) { } /** - * Get body. - * @return the statement. + * Get body. + * + * @return the statement. */ public Statement getBody() { return body; @@ -107,15 +117,17 @@ public SourceElement getLastElement() { return body; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printFinally(this); } -} \ No newline at end of file +} 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 77898bf3ae0..4cae4c61367 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -15,54 +18,49 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * For. - * + * For. + * */ public class For extends LoopStatement implements VariableScope { - private static final ImmutableArray EMPTY_VARSPECS= + private static final ImmutableArray EMPTY_VARSPECS = new ImmutableArray(new VariableSpecification[0]); /** - * For. + * For. */ public For() {} /** - * For. Used for the Recoder2KeY transformation - * @param inits a loop initializer mutable list. - * @param guard an expression. - * @param updates an expression mutable list. - * @param body a statement. + * For. Used for the Recoder2KeY transformation + * + * @param inits a loop initializer mutable list. + * @param guard an expression. + * @param updates an expression mutable list. + * @param body a statement. */ - public For(LoopInitializer[] inits, Expression guard, - Expression[] updates, Statement body) { + public For(LoopInitializer[] inits, Expression guard, Expression[] updates, Statement body) { super(inits, guard, updates, body); } - public For(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body, ExtList comments) { + public For(ILoopInit inits, IGuard guard, IForUpdates updates, Statement body, + ExtList comments) { super(inits, guard, updates, body, comments); } - public For(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body, - ExtList comments, PositionInfo pos) { + public For(ILoopInit inits, IGuard guard, IForUpdates updates, Statement body, ExtList comments, + PositionInfo pos) { super(inits, guard, updates, body, comments, pos); } - public For(ILoopInit inits, IGuard guard, - IForUpdates updates, Statement body) { + public For(ILoopInit inits, IGuard guard, IForUpdates updates, Statement body) { super(inits, guard, updates, body); } public For(ExtList children) { - super(children.get(ILoopInit.class), - children.get(IGuard.class), - children.get(IForUpdates.class), - children.get(Statement.class), - children); + super(children.get(ILoopInit.class), children.get(IGuard.class), + children.get(IForUpdates.class), children.get(Statement.class), children); } public SourceElement getLastElement() { @@ -70,8 +68,9 @@ public SourceElement getLastElement() { } /** - * Is checked before iteration. - * @return the boolean value. + * Is checked before iteration. + * + * @return the boolean value. */ public boolean isCheckedBeforeIteration() { @@ -86,7 +85,7 @@ public ImmutableArray getVariablesInScope() { if (inits != null) { LoopInitializer li = inits.getInits().get(0); if (li instanceof LocalVariableDeclaration) { - return ((LocalVariableDeclaration)li).getVariables(); + return ((LocalVariableDeclaration) li).getVariables(); } } return EMPTY_VARSPECS; @@ -97,7 +96,7 @@ public VariableSpecification getVariableInScope(String name) { LoopInitializer li = inits.getInits().get(0); if (li instanceof LocalVariableDeclaration) { ImmutableArray vars = - ((LocalVariableDeclaration)li).getVariables(); + ((LocalVariableDeclaration) li).getVariables(); for (int i = 0, s = vars.size(); i < s; i += 1) { VariableSpecification v = vars.get(i); if (name.equals(v.getName())) { @@ -109,15 +108,17 @@ public VariableSpecification getVariableInScope(String name) { return null; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnFor(this); + v.performActionOnFor(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printFor(this); } -} \ No newline at end of file +} 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 d64931b58c6..a0b41562f85 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 @@ -1,7 +1,6 @@ -/** - * This class encapsulates updates of a for loop - */ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -15,62 +14,64 @@ import de.uka.ilkd.key.java.visitor.Visitor; public class ForUpdates extends JavaNonTerminalProgramElement - implements ExpressionContainer, IForUpdates{ + implements ExpressionContainer, IForUpdates { ImmutableArray updates; public ForUpdates(ImmutableArray exprarr) { - updates = exprarr; + updates = 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(); } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out 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 cd52f063f26..3f78d5e37b3 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 @@ -1,7 +1,6 @@ -/** - * This class encapsulates a guard for a loop - */ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -11,37 +10,37 @@ import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.visitor.Visitor; -public class Guard extends JavaNonTerminalProgramElement - implements IGuard { +public class Guard extends JavaNonTerminalProgramElement implements IGuard { Expression expr; public Guard(Expression expression) { - expr=expression; + expr = expression; } public Guard(ExtList children) { - expr=children.get(Expression.class); + 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 (expr != null) ? 1 : 0; } 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/IForUpdates.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IForUpdates.java index c49d943f800..a9c86320e8a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IForUpdates.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IForUpdates.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.collection.ImmutableArray; @@ -12,4 +15,4 @@ public interface IForUpdates extends de.uka.ilkd.key.java.TerminalProgramElement ImmutableArray getUpdates(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IGuard.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IGuard.java index 33cdb9a6e79..fb2c6c181cd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IGuard.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/IGuard.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import de.uka.ilkd.key.java.NonTerminalProgramElement; @@ -5,4 +8,4 @@ public interface IGuard extends NonTerminalProgramElement { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ILoopInit.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ILoopInit.java index 85f7de24579..aba3f4e9632 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ILoopInit.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/ILoopInit.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.collection.ImmutableArray; @@ -11,4 +14,4 @@ public interface ILoopInit extends TerminalProgramElement { ImmutableArray getInits(); -} \ 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 1aabc6cf96a..9374032d4cd 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -10,34 +13,36 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * If. - * @author AutoDoc + * If. + * + * @author AutoDoc */ public class If extends BranchStatement implements ExpressionContainer { /** - * Then branch. + * Then branch. */ protected Then thenBranch; /** - * Else branch. + * Else branch. */ protected Else elseBranch; /** - * Expression. + * Expression. */ protected Expression expression; /** * 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) - */ + * + * @param children the children of this AST element as KeY classes. May contain: Comments, a + * Then, an Else, an Expression (as condition of If) + */ public If(ExtList children) { super(children); thenBranch = children.get(Then.class); @@ -53,14 +58,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) { @@ -68,20 +74,21 @@ 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.thenBranch = thenBranch; + this.elseBranch = elseBranch; checkValidity(); } /** - * + * * @return */ public SourceElement getLastElement() { @@ -89,9 +96,10 @@ 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 + */ public int getChildCount() { if (elseBranch != null) { @@ -101,44 +109,48 @@ 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 + * @exception 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; + if (index == 0) + return expression; index--; } if (thenBranch != null) { - if (index == 0) return thenBranch; + if (index == 0) + return thenBranch; index--; } if (elseBranch != null) { - if (index == 0) return elseBranch; + if (index == 0) + return elseBranch; } 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 1; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (index == 0) { return expression; @@ -147,48 +159,54 @@ 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; - if (elseBranch != null) result += 1; + if (elseBranch != null) + result += 1; return result; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Branch getBranchAt(int index) { if (index == 0) { return thenBranch; @@ -199,15 +217,17 @@ public Branch getBranchAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printIf(this); } -} \ No newline at end of file +} 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 815fba96917..5977ae9ee9c 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -7,36 +10,34 @@ import de.uka.ilkd.key.java.Statement; /** - * Default implementation for non-terminal Java statements. - * @author AutoDoc + * Default implementation for non-terminal Java statements. + * + * @author AutoDoc */ -public abstract class JavaStatement - extends JavaNonTerminalProgramElement - implements Statement { +public abstract class JavaStatement extends JavaNonTerminalProgramElement implements Statement { - /** - * Java statement. + /** + * Java statement. */ - public JavaStatement() { - } + public JavaStatement() {} /** - * Java statement. - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Java statement. + * + * @param children the children of this AST element as KeY classes. 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) { super(pos); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JmlAssert.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JmlAssert.java index a251891c350..8ab3ab7fd8c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JmlAssert.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/statement/JmlAssert.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import de.uka.ilkd.key.java.PositionInfo; @@ -56,10 +59,8 @@ public class JmlAssert extends JavaStatement { * @param positionInfo the position information for this statement * @param services needed for pretty printing (not pretty when null) */ - public JmlAssert(TextualJMLAssertStatement.Kind kind, - LabeledParserRuleContext condition, - PositionInfo positionInfo, - Services services) { + public JmlAssert(TextualJMLAssertStatement.Kind kind, LabeledParserRuleContext condition, + PositionInfo positionInfo, Services services) { super(positionInfo); this.kind = kind; this.condition = condition; @@ -128,8 +129,8 @@ public Term getCond(final Term self, final Services services) { replacementMap.replaceRemembranceLocalVariables(vars.atPreVars, vars.atPres, services); replacementMap.replaceRemembranceLocalVariables(vars.atBeforeVars, vars.atBefores, services); - final OpReplacer replacer = new OpReplacer( - replacementMap, termFactory, services.getProof()); + final OpReplacer replacer = + new OpReplacer(replacementMap, termFactory, services.getProof()); return replacer.replace(cond); } @@ -148,12 +149,8 @@ public void translateCondition(final JmlIO jmlIo, final ProgramVariableCollectio throw new IllegalStateException("condition can only be set once"); } this.vars = pv; - jmlIo.selfVar(pv.selfVar) - .parameters(pv.paramVars) - .resultVariable(pv.resultVar) - .exceptionVariable(pv.excVar) - .atPres(pv.atPres) - .atBefore(pv.atBefores); + jmlIo.selfVar(pv.selfVar).parameters(pv.paramVars).resultVariable(pv.resultVar) + .exceptionVariable(pv.excVar).atPres(pv.atPres).atBefore(pv.atBefores); this.cond = jmlIo.translateTermAsFormula(condition); condition = null; } @@ -166,11 +163,10 @@ public boolean equals(final Object o) { if (!super.equals(o)) { return false; } - //super.equals() check classes + // super.equals() check classes final JmlAssert jmlAssert = (JmlAssert) o; - return kind == jmlAssert.kind && - Objects.equals(condition, jmlAssert.condition) && - Objects.equals(cond, jmlAssert.cond); + return kind == jmlAssert.kind && Objects.equals(condition, jmlAssert.condition) + && Objects.equals(cond, jmlAssert.cond); } // hashCode() caches the result of computeHashCode() @@ -206,6 +202,7 @@ public ProgramVariableCollection getVars() { /** * updates this statement with prestate renaming + * * @param atPres prestate renaming * @param services services */ @@ -213,8 +210,8 @@ public void updateVars(final Map atPres, final Services final TermFactory termFactory = services.getTermFactory(); final TermReplacementMap replacementMap = new TermReplacementMap(termFactory); replacementMap.replaceRemembranceLocalVariables(vars.atPreVars, atPres, services); - final OpReplacer replacer = new OpReplacer( - replacementMap, termFactory, services.getProof()); + final OpReplacer replacer = + new OpReplacer(replacementMap, termFactory, services.getProof()); cond = replacer.replace(cond); vars.atPres = atPres; 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 33592848315..b5d12436be7 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 @@ -1,27 +1,30 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; /** - * Jump statement. - * @author AutoDoc + * Jump statement. + * + * @author AutoDoc */ public abstract class JumpStatement extends JavaStatement { /** - * Jump statement. - * @param children the children of this AST element as KeY classes. - * May contain: Comments + * Jump statement. + * + * @param children the children of this AST element as KeY classes. May contain: Comments */ public JumpStatement(ExtList children) { - super(children); + super(children); } /** - * Jump statement. + * Jump statement. */ - public JumpStatement() { - } + public JumpStatement() {} -} \ 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 6db43e6eb89..1703b843bdf 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; @@ -7,60 +10,65 @@ import de.uka.ilkd.key.java.ProgramElement; import de.uka.ilkd.key.java.reference.NameReference; import de.uka.ilkd.key.logic.ProgramElementName; + /** - * Label jump statement. - * + * Label jump statement. + * */ public abstract class LabelJumpStatement extends JumpStatement implements NameReference { /** - * Name. + * Name. */ protected final Label name; /** - * Label jump statement. + * Label jump statement. */ public LabelJumpStatement() { - name=null; + name = null; } /** - * Label jump statement. + * Label jump statement. + * * @param label the Label of this jump statement */ public LabelJumpStatement(Label label) { - super(); - name=label; + super(); + name = 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() { @@ -69,38 +77,40 @@ 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; } throw new ArrayIndexOutOfBoundsException(); } -} \ No newline at end of file +} 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 f675cfe970f..ed2cb21af4e 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -21,47 +24,44 @@ import de.uka.ilkd.key.util.Debug; /** - * Labeled statement. + * Labeled statement. */ -public class LabeledStatement extends JavaStatement - implements StatementContainer, - NamedProgramElement, - ProgramPrefix { +public class LabeledStatement extends JavaStatement + implements StatementContainer, NamedProgramElement, ProgramPrefix { /** - * Name. + * Name. */ protected final Label name; /** - * Body. + * Body. */ protected final Statement body; - + private final PosInProgram firstActiveChildPos; private final int prefixLength; private final MethodFrame 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 + * + * @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 */ 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 : - PosInProgram.ONE_ZERO : PosInProgram.ONE; + body = children.get(Statement.class); + firstActiveChildPos = body instanceof StatementBlock + ? ((StatementBlock) body).isEmpty() ? PosInProgram.TOP : PosInProgram.ONE_ZERO + : PosInProgram.ONE; // otherwise it will crash later assert body != null; @@ -73,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(); + 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(); @@ -110,8 +112,8 @@ public LabeledStatement(Label id, Statement statement, PositionInfo pos) { public boolean hasNextPrefixElement() { if (body instanceof ProgramPrefix) { if (body instanceof StatementBlock) { - return !((StatementBlock) body).isEmpty() && - ((StatementBlock)body).getStatementAt(0) instanceof ProgramPrefix; + return !((StatementBlock) body).isEmpty() + && ((StatementBlock) body).getStatementAt(0) instanceof ProgramPrefix; } return true; } @@ -121,65 +123,60 @@ public boolean hasNextPrefixElement() { @Override public ProgramPrefix getNextPrefixElement() { if (hasNextPrefixElement()) { - return (ProgramPrefix) - (body instanceof StatementBlock ? ((StatementBlock) body).getStatementAt(0) : body); + 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); + return StatementBlock.computePrefixElements(((StatementBlock) body).getBody(), this); } else if (body instanceof ProgramPrefix) { - return StatementBlock. - computePrefixElements(new ImmutableArray(body), - this); - } + return StatementBlock.computePrefixElements(new ImmutableArray(body), this); + } return new ImmutableArray(this); } 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; + } } 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() { @@ -187,8 +184,9 @@ public final String getName() { } /** - * Get identifier. - * @return the identifier. + * Get identifier. + * + * @return the identifier. */ public Label getLabel() { @@ -197,61 +195,68 @@ 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; - } - 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 */ public int getChildCount() { int result = 0; - if (name != null) result++; - if (body != null) result++; + if (name != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (name != null) { - if (index == 0) return name; + if (index == 0) + return name; index--; } if (body != null) { - if (index == 0) return body; + 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() { @@ -259,12 +264,11 @@ public int getStatementCount() { } /** - * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Statement getStatementAt(int index) { @@ -274,34 +278,35 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnLabeledStatement(this); + v.performActionOnLabeledStatement(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printLabeledStatement(this); } - /** 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. + /** + * 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); + 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); } - + public PosInProgram getFirstActiveChildPos() { return firstActiveChildPos; } @@ -315,5 +320,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 bdfc1179178..ef0ba272d8e 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 @@ -1,7 +1,6 @@ -/** - * This class encapsulates initializers of a for loop - */ - +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -16,66 +15,68 @@ import de.uka.ilkd.key.java.visitor.Visitor; public class LoopInit extends JavaNonTerminalProgramElement - implements StatementContainer, ILoopInit{ + implements StatementContainer, ILoopInit { ImmutableArray inits; public LoopInit(ImmutableArray exprarr) { - inits = exprarr; + inits = exprarr; } public LoopInit(LoopInitializer[] exprarr) { - inits = new ImmutableArray(exprarr); + inits = 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(); } /* - Return the statement at the specified index in this node's - "virtual" statement array. - @param index an index for an 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 an statement. + * + * @return the statement with the given index. + * + * @exception ArrayIndexOutOfBoundsException if index is out 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 2814ad31543..334304f834e 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -33,29 +36,27 @@ public class LoopScopeBlock extends JavaStatement /** * TODO - * + * * @param body */ public LoopScopeBlock(StatementBlock body) { this.body = body; this.indexPV = null; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); } /** * TODO - * + * * @param e * @param body */ public LoopScopeBlock(IProgramVariable iProgramVariable, StatementBlock body) { this.indexPV = iProgramVariable; this.body = body; - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -63,16 +64,14 @@ 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); indexPV = children.get(IProgramVariable.class); body = children.get(StatementBlock.class); - ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil - .computeEssentials(this); + ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -80,8 +79,7 @@ public LoopScopeBlock(ExtList children) { @Override public boolean hasNextPrefixElement() { - return !body.isEmpty() - && body.getStatementAt(0) instanceof ProgramPrefix; + return !body.isEmpty() && body.getStatementAt(0) instanceof ProgramPrefix; } @Override @@ -89,15 +87,13 @@ public ProgramPrefix getNextPrefixElement() { if (hasNextPrefixElement()) { return (ProgramPrefix) body.getStatementAt(0); } else { - throw new IndexOutOfBoundsException( - "No next prefix element " + this); + throw new IndexOutOfBoundsException("No next prefix element " + this); } } @Override public ProgramPrefix getLastPrefixElement() { - return hasNextPrefixElement() - ? getNextPrefixElement().getLastPrefixElement() : this; + return hasNextPrefixElement() ? getNextPrefixElement().getLastPrefixElement() : this; } @Override @@ -123,7 +119,7 @@ public PosInProgram getFirstActiveChildPos() { /** * Get the number of expressions in this container. - * + * * @return the number of expressions. */ @Override @@ -132,26 +128,23 @@ public int getExpressionCount() { } /** - * Return the expression at the specified index in this node's "virtual" - * expression array. - * - * @param index - * an index for an expression. + * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Expression getExpressionAt(int index) { if (indexPV != null && index == 0) { - return (ProgramVariable) indexPV; //XXX This cast may fail... + return (ProgramVariable) indexPV; // XXX This cast may fail... } throw new ArrayIndexOutOfBoundsException(); } /** * Get expression. - * + * * @return the expression. */ public IProgramVariable getIndexPV() { @@ -160,7 +153,7 @@ public IProgramVariable getIndexPV() { /** * Returns the number of children of this node. - * + * * @return an int giving the number of children of this node */ @Override @@ -174,14 +167,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 + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ @Override public ProgramElement getChildAt(int index) { @@ -199,7 +189,7 @@ public ProgramElement getChildAt(int index) { /** * Get body. - * + * * @return the statement block. */ public StatementBlock getBody() { @@ -208,7 +198,7 @@ public StatementBlock getBody() { /** * Get the number of statements in this container. - * + * * @return the number of statements. */ @Override @@ -217,16 +207,13 @@ public int getStatementCount() { } /** - * Return the statement at the specified index in this node's "virtual" - * statement array. - * - * @param index - * an index for a statement. - * + * 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ @Override public Statement getStatementAt(int index) { @@ -242,11 +229,10 @@ public SourceElement getFirstElement() { } /** - * Calls the corresponding method of a visitor in order to perform some - * action/transformation on this element - * - * @param v - * the Visitor + * 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) { @@ -257,4 +243,4 @@ public void visit(Visitor v) { public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printLoopScopeBlock(this); } -} \ No newline at end of file +} 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 69355e7e5e7..3461d5bef80 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -13,250 +16,256 @@ import de.uka.ilkd.key.java.StatementContainer; /** - * 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; /** - * Loop statement. + * Loop statement. */ public LoopStatement() { - this.body=null; - this.updates=null; - this.inits=null; - this.guard=null; + this.body = null; + this.updates = null; + this.inits = null; + this.guard = 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.body = body; + this.updates = null; + this.inits = null; + this.guard = null; } - /** - * 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.body = null; + 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, 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.body = body; + this.updates = null; + this.inits = null; + this.guard = new Guard(guard); } - public LoopStatement(Expression guard, Statement body, - PositionInfo pos) { - super(pos); - this.body = body; - this.updates = null; - this.inits = null; - this.guard = new Guard(guard); + public LoopStatement(Expression guard, Statement body, PositionInfo pos) { + 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) { 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); + 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); } - /** - * 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. + * 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 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; + 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; } - static private ExtList add(ExtList e, Object o){ - e.add(o); - return e; + static private 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 (updates != null) result++; - if (body != null) result++; + if (inits != null) + result++; + if (guard != null) + result++; + if (updates != 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 + * @exception 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--; } if (isCheckedBeforeIteration()) { if (guard != null) { - if (index == 0) return guard; + if (index == 0) + return guard; index--; } } if (updates != null) { - if (index==0) { + if (index == 0) { return updates; } index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; index--; } if (!isCheckedBeforeIteration()) { if (guard != null) { - if (index == 0) return guard; + if (index == 0) + return guard; index--; } } @@ -264,14 +273,16 @@ 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 (guard != null) + result += 1; if (inits != null) { - result +=1; + result += 1; } if (updates != null) { result += updates.size(); @@ -280,17 +291,18 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (guard != null) { if (index == 0) { - return (Expression)guard.getChildAt(0); + return (Expression) guard.getChildAt(0); } index -= 1; } @@ -300,7 +312,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; } @@ -313,45 +325,50 @@ 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; } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { return body; @@ -360,47 +377,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(); @@ -410,11 +432,10 @@ public boolean equals(Object o) { return false; } - LoopStatement cmp = (LoopStatement)o; - return super.equals(cmp) - && (this.getStartPosition().equals(Position.UNDEFINED) || - cmp.getStartPosition().equals(Position.UNDEFINED) || - this.getStartPosition().getLine() == cmp.getStartPosition().getLine()); + LoopStatement cmp = (LoopStatement) o; + return super.equals(cmp) && (this.getStartPosition().equals(Position.UNDEFINED) + || 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 be73e2696fd..6bbd2516149 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -16,8 +19,7 @@ * * @author Dominic Scheurer */ -public class MergePointStatement extends JavaStatement - implements ExpressionContainer { +public class MergePointStatement extends JavaStatement implements ExpressionContainer { // Those are used for JML to JavaDL conversions protected final IProgramVariable identifier; @@ -47,7 +49,7 @@ public Comment[] getComments() { /** * Get the number of expressions in this container. - * + * * @return the number of expressions. */ public int getExpressionCount() { @@ -55,16 +57,13 @@ public int getExpressionCount() { } /** - * Return the expression at the specified index in this node's "virtual" - * expression array. - * - * @param index - * an index for an expression. - * + * 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Expression getExpressionAt(int index) { if (identifier != null && index == 0) { @@ -75,7 +74,7 @@ public Expression getExpressionAt(int index) { /** * Get expression. - * + * * @return the expression. */ public Expression getExpression() { @@ -84,7 +83,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() { @@ -95,14 +94,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 + * 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (identifier != null) { @@ -114,11 +110,10 @@ 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 + * 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.performActionOnMergePointStatement(this); @@ -127,4 +122,4 @@ public void visit(Visitor v) { public void prettyPrint(PrettyPrinter p) throws java.io.IOException { p.printMergePointStatementBlock(this); } -} \ No newline at end of file +} 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 8b0529989f6..230bc04bda6 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -24,210 +27,199 @@ /** - * 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 - * variable or field, this value is null. + + /** + * the variable the result of the method execution is assigned to 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. + * This type reference determines the class where the represented method has to be implemented. */ private final TypeReference bodySource; - /** + /** * the reference describing the method signature */ private final MethodReference methodReference; - + /** cache resolved method */ private IProgramMethod method; - /** indicates whether this stands for the specification of - * a method rather than the concrete body*/ + /** + * indicates whether this stands for the specification of a method rather than the concrete body + */ private boolean useSpecification; - + /** - * 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.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) { 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){ + 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, boolean useSpecification, + ProgramElement scope) { 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"); + throw new IllegalArgumentException( + "The invocation target of a method body" + "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) { + public MethodBodyStatement(IProgramMethod method, ReferencePrefix newContext, + IProgramVariable res, ImmutableArray args) { this(method, newContext, res, args, false); } - - public MethodBodyStatement(IProgramMethod method, - ReferencePrefix newContext, - IProgramVariable res, - ImmutableArray args, - ProgramElement scope) { + + 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++; - if (resultVar != null) i++; - if (methodReference != null) i++; - return i; + int i = 0; + if (bodySource != null) + i++; + if (resultVar != null) + i++; + if (methodReference != null) + 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 + * @exception 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); @@ -236,31 +228,33 @@ public boolean isStatic(Services services) { } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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); @@ -269,26 +263,23 @@ public IProgramMethod getProgramMethod(Services services) { } private void resolveMethod(Services services) { - method = services.getJavaInfo(). - getProgramMethod(getBodySource(), - methodReference.getName(), - services.getJavaInfo(). - createSignature(methodReference.getArguments()), - getBodySource()); + method = services.getJavaInfo().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 608926fb226..4a5d47a8b99 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.collection.ImmutableArray; @@ -19,10 +22,10 @@ import de.uka.ilkd.key.util.Debug; /** - * 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 { +public class MethodFrame extends JavaStatement + implements Statement, StatementContainer, ProgramPrefix { /** * result @@ -30,76 +33,67 @@ public class MethodFrame extends JavaStatement implements private final IProgramVariable resultVar; /** - * Body. + * Body. */ private final StatementBlock body; - + private final IExecutionContext execContext; - + private final PosInProgram firstActiveChildPos; private final int prefixLength; private final MethodFrame 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) { + this.resultVar = resultVar; + this.body = body; this.execContext = execContext; - - 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(); + + 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(); } - + /** - * 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, - PositionInfo pos) { + 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 = - 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(); + + 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(); } @@ -116,13 +110,12 @@ 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; @@ -136,14 +129,14 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } - - public PosInProgram getFirstActiveChildPos() { + } + + public PosInProgram getFirstActiveChildPos() { return firstActiveChildPos; } - + public SourceElement getFirstElement() { -// return getChildAt(0).getFirstElement(); -VK + // return getChildAt(0).getFirstElement(); -VK return body.getFirstElement(); } @@ -152,38 +145,40 @@ public SourceElement getFirstElementIncludingBlocks() { return body; } - public SourceElement getLastElement() { + 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; } /** - * returns the execution context for the elements in the method - * frame's body + * returns the execution context for the elements in the method frame's body */ public IExecutionContext getExecutionContext() { - return execContext; + return execContext; } /** - * Get body. - * @return the Statement + * Get body. + * + * @return the Statement */ public StatementBlock getBody() { return body; } - - + + /** - * Get method. - * @return the method + * Get method. + * + * @return the method */ public IProgramMethod getProgramMethod() { return getExecutionContext().getMethodContext(); @@ -192,46 +187,53 @@ public IProgramMethod getProgramMethod() { /** - * 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++; + if (resultVar != null) + result++; + if (execContext != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds */ public ProgramElement getChildAt(int index) { if (resultVar != null) { - if (index == 0) return resultVar; + if (index == 0) + return resultVar; index--; } if (execContext != null) { - if (index == 0) return execContext; + if (index == 0) + return execContext; index--; } if (body != null) { - if (index == 0) return body; + 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() { @@ -239,12 +241,11 @@ public int getStatementCount() { } /** - * 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. */ public Statement getStatementAt(int index) { @@ -254,15 +255,17 @@ public Statement getStatementAt(int index) { throw new ArrayIndexOutOfBoundsException(); } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 d7fd63c4943..dcf8805f955 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 @@ -1,12 +1,17 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ 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.PrettyPrinter; import de.uka.ilkd.key.java.visitor.Visitor; + /** - * Return. - * + * Return. + * */ public class Return extends ExpressionJumpStatement { @@ -14,32 +19,34 @@ public class Return extends ExpressionJumpStatement { /** * Expression jump statement. - * @param expr an Expression used to jump + * + * @param expr an Expression used to jump */ public Return(Expression expr) { - super(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 - */ + * + * @param children the children of this AST element as KeY classes. 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 - * perform some action/transformation on this element + /** + * 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 { p.printReturn(this); } -} \ No newline at end of file +} 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 5b515a906ce..c07aacbb573 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -12,21 +15,20 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Switch. + * Switch. */ public class Switch extends BranchStatement - implements ExpressionContainer, - VariableScope, TypeScope { + implements ExpressionContainer, VariableScope, TypeScope { /** - * Branches. + * Branches. */ protected final ImmutableArray branches; /** - * Expression. + * Expression. */ protected final Expression expression; @@ -34,71 +36,77 @@ public class Switch extends BranchStatement /** - * Switch. + * Switch. */ public Switch() { - this.branches=null; - this.expression=null; + this.branches = null; + this.expression = null; } /** - * Switch. - * @param e an expression. + * Switch. + * + * @param e an expression. */ public Switch(Expression e) { - this.branches=null; - this.expression=e; + this.branches = null; + this.expression = e; } /** - * 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.branches = new ImmutableArray(branches); + this.expression = e; } /** - * 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 (expression != 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 + * @exception ArrayIndexOutOfBoundsException if index is out of bounds + */ public ProgramElement getChildAt(int index) { if (expression != null) { - if (index == 0) return expression; + if (index == 0) + return expression; index--; } if (branches != null) { @@ -108,8 +116,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() { @@ -117,13 +126,14 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (expression != null && index == 0) { @@ -133,8 +143,9 @@ public Expression getExpressionAt(int index) { } /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { @@ -143,8 +154,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() { @@ -152,13 +164,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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Branch getBranchAt(int index) { if (branches != null) { @@ -168,22 +181,26 @@ public Branch getBranchAt(int index) { } - /* 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 - * perform some action/transformation on this element + /** + * 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 { p.printSwitch(this); } -} \ No newline at end of file +} 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 de02bd66572..43b5dcdb3ae 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -21,20 +24,20 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; /** - * Synchronized block. + * Synchronized block. */ -public class SynchronizedBlock extends JavaStatement - implements StatementContainer, ExpressionContainer, ProgramPrefix { +public class SynchronizedBlock extends JavaStatement + implements StatementContainer, ExpressionContainer, ProgramPrefix { /** - * Expression. + * Expression. */ protected final Expression expression; /** - * Body. + * Body. */ protected final StatementBlock body; @@ -42,32 +45,34 @@ public class SynchronizedBlock extends JavaStatement private final MethodFrame innerMostMethodFrame; private final int 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(); + 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; + expression = e; + this.body = body; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -75,17 +80,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(); } @@ -102,13 +108,12 @@ 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; @@ -122,31 +127,31 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } + } /** - * The method checks whether the expression in the synchronized - * prefix is either a local variable or a meta class reference - * (as local variables of this type are not supported by KeY, - * see return value for - * {@link MetaClassReference#getKeYJavaType(Services, ExecutionContext)}. + * The method checks whether the expression in the synchronized prefix is either a local + * variable or a meta class reference (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()) + return (expression instanceof ProgramVariable && !((ProgramVariable) expression).isMember()) || (expression instanceof MetaClassReference); } public PosInProgram getFirstActiveChildPos() { - return getStatementCount() == 0 ? - PosInProgram.TOP : (expressionWithoutSideffects() ? - PosInProgram.TOP.down(getChildCount()-1).down(0) : PosInProgram.ONE); + return getStatementCount() == 0 ? PosInProgram.TOP + : (expressionWithoutSideffects() + ? 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() { @@ -154,13 +159,14 @@ public int getExpressionCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Expression getExpressionAt(int index) { if (expression != null && index == 0) { @@ -171,8 +177,9 @@ public Expression getExpressionAt(int index) { /** - * Get expression. - * @return the expression. + * Get expression. + * + * @return the expression. */ public Expression getExpression() { @@ -180,40 +187,45 @@ 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 (expression != 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 - */ - - public ProgramElement getChildAt(int index) { + * 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 + */ + + public ProgramElement getChildAt(int index) { if (expression != null) { - if (index == 0) return expression; + if (index == 0) + return expression; index--; } if (body != null) { - if (index == 0) return body; + if (index == 0) + return body; } throw new ArrayIndexOutOfBoundsException(); } /** - * Get body. - * @return the statement block. + * Get body. + * + * @return the statement block. */ public StatementBlock getBody() { @@ -222,8 +234,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() { @@ -231,13 +244,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -245,7 +259,7 @@ public Statement getStatementAt(int index) { } throw new ArrayIndexOutOfBoundsException(); } - + public SourceElement getFirstElement() { @@ -253,15 +267,17 @@ public SourceElement getFirstElement() { } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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 { p.printSynchronizedBlock(this); } -} \ No newline at end of file +} 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 d92167ccdbd..f3bc8885f7a 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 @@ -1,4 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; + import org.key_project.util.ExtList; import de.uka.ilkd.key.java.PrettyPrinter; @@ -8,14 +12,15 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Then. - * @author AutoDoc + * Then. + * + * @author AutoDoc */ public class Then extends BranchImp { /** - * Body. + * Body. */ protected Statement body; @@ -23,19 +28,21 @@ public class Then extends BranchImp { /** * 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; + this.body = stmnt; } @@ -54,8 +61,9 @@ 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 */ public int getChildCount() { @@ -63,24 +71,25 @@ public int getChildCount() { } /** - * Returns the child at the specified index in this node's "virtual" - * child array + * 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 + * @exception 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() { @@ -88,13 +97,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -104,22 +114,24 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printThen(this); } -} \ No newline at end of file +} 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 8193525cbe9..638408e2c93 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -7,20 +10,21 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * Throw. + * Throw. */ public class Throw extends ExpressionJumpStatement { /** - * Throw. + * Throw. */ public Throw() {} /** - * Throw. - * @param expr an expression. + * Throw. + * + * @param expr an expression. */ public Throw(Expression expr) { @@ -31,23 +35,26 @@ 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 - * perform some action/transformation on this element + /** + * 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 { p.printThrow(this); } -} \ No newline at end of file +} 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 0eabfd73cc7..c13a8bb1718 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import de.uka.ilkd.key.java.NameAbstractionTable; @@ -9,17 +12,19 @@ public class TransactionStatement extends JavaStatement { - public static final String[] names = { - "#beginJavaCardTransaction", "#commitJavaCardTransaction", "#finishJavaCardTransaction", "#abortJavaCardTransaction" - }; + 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); + 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); } this.type = type; } @@ -42,34 +47,34 @@ 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); } -} \ No newline at end of file +} 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 20080545e3b..aeb3b8de003 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -15,12 +18,12 @@ import de.uka.ilkd.key.logic.ProgramPrefix; /** - * Try. - * @author AutoDoc + * Try. + * + * @author AutoDoc */ -public class Try extends BranchStatement - implements StatementContainer, ProgramPrefix { - +public class Try extends BranchStatement implements StatementContainer, ProgramPrefix { + /** * Body. */ @@ -28,7 +31,7 @@ public class Try extends BranchStatement private final StatementBlock body; /** - * Branches. + * Branches. */ private final ImmutableArray branches; @@ -36,29 +39,31 @@ public class Try extends BranchStatement private final MethodFrame innerMostMethodFrame; private final int prefixLength; - + /** - * Try. - * @param body a statement block. + * Try. + * + * @param body a statement block. */ public Try(StatementBlock body) { - this.body = body; - this.branches = 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); + this.body = body; + this.branches = new ImmutableArray(branches); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -66,13 +71,14 @@ 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; + this.body = body; this.branches = branches; ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); @@ -81,15 +87,15 @@ public Try(StatementBlock body, ImmutableArray branches) { } /** - * 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 - ImmutableArray(children.collect(Branch.class)); + this.branches = new ImmutableArray(children.collect(Branch.class)); ProgramPrefixUtil.ProgramPrefixInfo info = ProgramPrefixUtil.computeEssentials(this); prefixLength = info.getLength(); innerMostMethodFrame = info.getInnerMostMethodFrame(); @@ -109,13 +115,12 @@ 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; @@ -129,9 +134,9 @@ public MethodFrame getInnerMostMethodFrame() { @Override public ImmutableArray getPrefixElements() { return StatementBlock.computePrefixElements(body.getBody(), this); - } + } + - public SourceElement getFirstElement() { return body.getFirstElement(); } @@ -142,29 +147,32 @@ 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 + */ public int getChildCount() { int result = 0; - if (body != null) result++; - if (branches != null) result += branches.size(); + 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 + * @exception 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; index--; } if (branches != null) { @@ -174,8 +182,9 @@ public ProgramElement getChildAt(int index) { } /** - * Get body. - * @return the statement block. + * Get body. + * + * @return the statement block. */ public StatementBlock getBody() { @@ -183,8 +192,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() { @@ -192,13 +202,14 @@ public int getStatementCount() { } /* - 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. + * + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Statement getStatementAt(int index) { if (body != null && index == 0) { @@ -208,8 +219,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() { @@ -217,13 +229,12 @@ 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. + * @exception ArrayIndexOutOfBoundsException if index is out of bounds. + */ public Branch getBranchAt(int index) { if (branches != null) { @@ -232,19 +243,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 - * perform some action/transformation on this element + /** + * 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 { @@ -252,6 +267,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 fd322aec1b0..8e9cd6719fe 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.statement; import org.key_project.util.ExtList; @@ -10,31 +13,32 @@ import de.uka.ilkd.key.java.visitor.Visitor; /** - * While. + * While. */ public class While extends LoopStatement { /** - * While. + * While. */ public While() {} /** - * While. - * @param guard an expression. - * @param body a statement. - * @param pos a PositionInformation. + * While. + * + * @param guard an expression. + * @param body a statement. + * @param pos a PositionInformation. */ - public While(Expression guard, Statement body, PositionInfo pos, - ExtList comments){ - super(guard,body,comments,pos); + public While(Expression guard, Statement body, PositionInfo pos, ExtList comments) { + super(guard, body, comments, pos); } - + /** * create a new While statement with no position info and no comments but guard and body set + * * @param guard an expression. * @param body a statement. */ @@ -43,15 +47,16 @@ public While(Expression guard, Statement body) { super(guard, body, new ExtList()); } - /** - * While. - * @param guard an expression. - * @param body a statement. - * @param pos a PositionInformation. + /** + * While. + * + * @param guard an expression. + * @param body a statement. + * @param pos a PositionInformation. */ - public While(Expression guard, Statement body, PositionInfo pos){ - super(guard, body, pos); + public While(Expression guard, Statement body, PositionInfo pos) { + super(guard, body, pos); } public SourceElement getLastElement() { @@ -59,20 +64,23 @@ public SourceElement getLastElement() { } /** - * Is checked before iteration. - * @return the boolean value. + * Is checked before iteration. + * + * @return the boolean value. */ public boolean isCheckedBeforeIteration() { return true; } - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + /** + * 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.performActionOnWhile(this); + v.performActionOnWhile(this); } public void prettyPrint(PrettyPrinter p) throws java.io.IOException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/ContainsStatementVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/ContainsStatementVisitor.java index e709689aa55..0940488bd5b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/ContainsStatementVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/ContainsStatementVisitor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import org.key_project.util.java.ObjectUtil; @@ -12,7 +15,7 @@ /** * Utilits class used by * {@link SymbolicExecutionUtil#containsStatement(MethodFrame, ProgramElement, Services)}. - * + * * @author Martin Hentschel */ public class ContainsStatementVisitor extends JavaASTVisitor { @@ -28,13 +31,10 @@ public class ContainsStatementVisitor extends JavaASTVisitor { /** * Constructor. - * - * @param root - * The {@link ProgramElement} to start search in. - * @param toSearch - * The {@link SourceElement} to search. - * @param services - * The {@link Services} to use. + * + * @param root The {@link ProgramElement} to start search in. + * @param toSearch The {@link SourceElement} to search. + * @param services The {@link Services} to use. */ public ContainsStatementVisitor(ProgramElement root, SourceElement toSearch, Services services) { @@ -55,7 +55,7 @@ protected void doDefaultAction(SourceElement se) { /** * Returns the result. - * + * * @return {@code true} contained, {@code false} not contained. */ public boolean isContained() { @@ -63,41 +63,35 @@ public boolean isContained() { } /** - * Compares the given {@link SourceElement}s including their - * {@link PositionInfo}s. + * Compares the given {@link SourceElement}s including their {@link PositionInfo}s. *

    * NOTE: (DS) This is a copy of - * SymbolicExecutionUtil#equalsWithPosition(SourceElement, SourceElement) - * which has been copied here since it's not possible to create a dependency - * to its original container project. - * - * @param first - * The first {@link SourceElement}. - * @param second - * The second {@link SourceElement}. - * @return {@code true} both are equal and at the same {@link PositionInfo}, - * {@code false} otherwise. + * SymbolicExecutionUtil#equalsWithPosition(SourceElement, SourceElement) which has been copied + * here since it's not possible to create a dependency to its original container project. + * + * @param first The first {@link SourceElement}. + * @param second The second {@link SourceElement}. + * @return {@code true} both are equal and at the same {@link PositionInfo}, {@code false} + * otherwise. */ - public static boolean equalsWithPosition(SourceElement first, - SourceElement second) { + public static boolean equalsWithPosition(SourceElement first, SourceElement second) { if (first != null && second != null) { if (first instanceof While) { if (second instanceof While) { // Special treatment for while because its position info is // lost during prove, but maintained in its guard. - return first.equals(second) - && equalsWithPosition(((While) first).getGuard(), - ((While) second).getGuard()); + return first.equals(second) && equalsWithPosition(((While) first).getGuard(), + ((While) second).getGuard()); } else { return false; } } else { // Compare all source elements including ints position info - return first.equals(second) && ObjectUtil.equals( - first.getPositionInfo(), second.getPositionInfo()); + return first.equals(second) + && ObjectUtil.equals(first.getPositionInfo(), second.getPositionInfo()); } } else { return first == null && second == null; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/CreatingASTVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/CreatingASTVisitor.java index 6e68131673c..26fcad4fc23 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/CreatingASTVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/CreatingASTVisitor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import java.util.ArrayDeque; @@ -45,15 +48,11 @@ public abstract class CreatingASTVisitor extends JavaASTVisitor { /** * create the CreatingASTVisitor * - * @param root - * the ProgramElement where to begin - * @param preservesPos - * whether the position should be preserved - * @param services - * the services instance + * @param root the ProgramElement where to begin + * @param preservesPos whether the position should be preserved + * @param services the services instance */ - public CreatingASTVisitor(ProgramElement root, boolean preservesPos, - Services services) { + public CreatingASTVisitor(ProgramElement root, boolean preservesPos, Services services) { super(root, services); this.preservesPositionInfo = preservesPos; } @@ -77,6 +76,7 @@ public String toString() { /** * called if the program element x is unchanged + * * @param x The {@link SourceElement}. */ @Override @@ -89,15 +89,12 @@ public void performActionOnAssert(Assert x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pos = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pos = PositionInfo.UNDEFINED; } - Expression condition = changeList - .removeFirstOccurrence(Expression.class); - Expression message = changeList - .removeFirstOccurrence(Expression.class); + Expression condition = changeList.removeFirstOccurrence(Expression.class); + Expression message = changeList.removeFirstOccurrence(Expression.class); addChild(new Assert(condition, message, pos)); @@ -150,8 +147,7 @@ protected void performActionOnMergeContract(MergePointStatement oldLoop, // do nothing } - protected void performActionOnLoopInvariant(LoopStatement oldLoop, - LoopStatement newLoop) { + protected void performActionOnLoopInvariant(LoopStatement oldLoop, LoopStatement newLoop) { // do nothing } @@ -161,8 +157,7 @@ public void performActionOnWhile(While x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pos = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pos = PositionInfo.UNDEFINED; } @@ -190,8 +185,7 @@ public void performActionOnFor(final For x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pos = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pos = PositionInfo.UNDEFINED; } @@ -218,8 +212,7 @@ public void performActionOnDo(Do x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pos = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pos = PositionInfo.UNDEFINED; } @@ -268,8 +261,7 @@ public void performActionOnVariableSpecification(VariableSpecification x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; @@ -279,8 +271,8 @@ public void performActionOnVariableSpecification(VariableSpecification x) { expr = (Expression) changeList.get(1); } IProgramVariable pv = (IProgramVariable) changeList.get(0); - addChild(new VariableSpecification(pv, x.getDimensions(), expr, - pv.getKeYJavaType(), pi)); + addChild(new VariableSpecification(pv, x.getDimensions(), expr, pv.getKeYJavaType(), + pi)); changed(); } else { doDefaultAction(x); @@ -295,8 +287,7 @@ public void performActionOnFieldReference(FieldReference x) { if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; @@ -308,13 +299,11 @@ public void performActionOnFieldReference(FieldReference x) { addChild(new FieldReference((ProgramVariable) field, (ReferencePrefix) changeList.get(0), pi)); } else { - addChild(new FieldReference( - ((FieldReference) field).getProgramVariable(), + addChild(new FieldReference(((FieldReference) field).getProgramVariable(), (ReferencePrefix) changeList.get(0), pi)); } } else { - addChild(new FieldReference((ProgramVariable) changeList.get(0), - null, pi)); + addChild(new FieldReference((ProgramVariable) changeList.get(0), null, pi)); } changed(); } else { @@ -324,8 +313,7 @@ public void performActionOnFieldReference(FieldReference x) { } @Override - public void performActionOnSchematicFieldReference( - SchematicFieldReference sfr) { + public void performActionOnSchematicFieldReference(SchematicFieldReference sfr) { performActionOnFieldReference(sfr); } @@ -336,8 +324,7 @@ public void performActionOnMethodReference(MethodReference x) { if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; @@ -362,8 +349,7 @@ public void performActionOnTypeReference(final TypeReference x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { - return new TypeRef(changeList, x.getKeYJavaType(), - x.getDimensions()); + return new TypeRef(changeList, x.getKeYJavaType(), x.getDimensions()); } }; def.doAction(x); @@ -387,8 +373,7 @@ public void performActionOnCase(Case x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; } @@ -534,8 +519,7 @@ public void performActionOnLabeledStatement(LabeledStatement x) { ExtList changeList = stack.peek(); if (changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; } @@ -559,11 +543,10 @@ public void performActionOnMethodFrame(MethodFrame x) { ExtList changeList = stack.peek(); if (!changeList.isEmpty() && changeList.getFirst() == CHANGED) { changeList.removeFirst(); - PositionInfo pi = changeList - .removeFirstOccurrence(PositionInfo.class); // Methodframe - // cannot occur - // in original - // program + PositionInfo pi = changeList.removeFirstOccurrence(PositionInfo.class); // Methodframe + // cannot occur + // in original + // program if (!preservesPositionInfo()) { pi = PositionInfo.UNDEFINED; @@ -571,16 +554,14 @@ public void performActionOnMethodFrame(MethodFrame x) { if (x.getChildCount() == 3) { addChild(new MethodFrame((IProgramVariable) changeList.get(0), - (IExecutionContext) changeList.get(1), - (StatementBlock) changeList.get(2), pi)); + (IExecutionContext) changeList.get(1), (StatementBlock) changeList.get(2), + pi)); } else if (x.getChildCount() == 2) { - addChild(new MethodFrame(null, - (IExecutionContext) changeList.get(0), + addChild(new MethodFrame(null, (IExecutionContext) changeList.get(0), (StatementBlock) changeList.get(1), pi)); } else { - throw new IllegalStateException( - "Methodframe has not allowed number of children."); + throw new IllegalStateException("Methodframe has not allowed number of children."); } changed(); } else { @@ -589,8 +570,7 @@ public void performActionOnMethodFrame(MethodFrame x) { } @Override - public void performActionOnMethodBodyStatement( - final MethodBodyStatement x) { + public void performActionOnMethodBodyStatement(final MethodBodyStatement x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { @@ -733,8 +713,7 @@ ProgramElement createNewElement(ExtList changeList) { } @Override - public void performActionOnParenthesizedExpression( - ParenthesizedExpression x) { + public void performActionOnParenthesizedExpression(ParenthesizedExpression x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { @@ -965,8 +944,7 @@ ProgramElement createNewElement(ExtList changeList) { } @Override - public void performActionOnUnsignedShiftRightAssignment( - UnsignedShiftRightAssignment x) { + public void performActionOnUnsignedShiftRightAssignment(UnsignedShiftRightAssignment x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { @@ -996,8 +974,7 @@ public void performActionOnNewArray(NewArray x) { ProgramElement createNewElement(ExtList children) { ArrayInitializer arrInit = children.get(ArrayInitializer.class); children.remove(arrInit); - return new NewArray(children, y.getKeYJavaType(), arrInit, - y.getDimensions()); + return new NewArray(children, y.getKeYJavaType(), arrInit, y.getDimensions()); } }; def.doAction(x); @@ -1009,8 +986,7 @@ public void performActionOnNew(New x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList children) { - PositionInfo pi = children - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pi = children.removeFirstOccurrence(PositionInfo.class); if (!preservesPositionInfo) { pi = PositionInfo.UNDEFINED; } @@ -1132,8 +1108,7 @@ public void performActionOnArrayReference(ArrayReference x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList children) { - PositionInfo pos = children - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = children.removeFirstOccurrence(PositionInfo.class); ArrayReference y = (ArrayReference) pe; ReferencePrefix prefix = null; int prefixPos = getPosition(y, y.getReferencePrefix()); @@ -1163,13 +1138,11 @@ ProgramElement createNewElement(ExtList changeList) { // ppp @Override - public void performActionOnSuperConstructorReference( - SuperConstructorReference x) { + public void performActionOnSuperConstructorReference(SuperConstructorReference x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList children) { - PositionInfo pos = children - .removeFirstOccurrence(PositionInfo.class); + PositionInfo pos = children.removeFirstOccurrence(PositionInfo.class); SuperConstructorReference y = (SuperConstructorReference) pe; ReferencePrefix prefix = null; int prefixPos = getPosition(y, y.getReferencePrefix()); @@ -1189,8 +1162,7 @@ ProgramElement createNewElement(ExtList children) { } @Override - public void performActionOnThisConstructorReference( - ThisConstructorReference x) { + public void performActionOnThisConstructorReference(ThisConstructorReference x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { @@ -1271,8 +1243,7 @@ public void performActionOnArrayInitializer(final ArrayInitializer x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { - return new ArrayInitializer(changeList, - x.getKeYJavaType(services, null)); + return new ArrayInitializer(changeList, x.getKeYJavaType(services, null)); } }; def.doAction(x); @@ -1323,8 +1294,7 @@ ProgramElement createNewElement(ExtList changeList) { } @Override - public void performActionOnLocalVariableDeclaration( - LocalVariableDeclaration x) { + public void performActionOnLocalVariableDeclaration(LocalVariableDeclaration x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { @@ -1350,8 +1320,8 @@ private class ParameterDeclarationAction extends DefaultAction { @Override ProgramElement createNewElement(ExtList changeList) { - return new ParameterDeclaration(changeList, - x.parentIsInterfaceDeclaration(), x.isVarArg()); + return new ParameterDeclaration(changeList, x.parentIsInterfaceDeclaration(), + x.isVarArg()); } } @@ -1490,13 +1460,11 @@ ProgramElement createNewElement(ExtList changeList) { } @Override - public void performActionOnDLEmbeddedExpression( - final DLEmbeddedExpression x) { + public void performActionOnDLEmbeddedExpression(final DLEmbeddedExpression x) { DefaultAction def = new DefaultAction(x) { @Override ProgramElement createNewElement(ExtList changeList) { - return new DLEmbeddedExpression(x.getFunctionSymbol(), - changeList); + return new DLEmbeddedExpression(x.getFunctionSymbol(), changeList); } }; def.doAction(x); @@ -1531,7 +1499,7 @@ public void performActionOnJmlAssert(JmlAssert x) { ProgramElement createNewElement(ExtList changeList) { changeList.add(x.getKind()); changeList.add(x.getVars()); - return new JmlAssert(changeList,services); + return new JmlAssert(changeList, services); } }; def.doAction(x); @@ -1546,12 +1514,12 @@ public void performActionOnJmlAssertCondition(final Term cond) { /** * returns the position of pe2 in the virtual child array of pe1 + * * @param pe1 A {@link NonTerminalProgramElement} * @param pe2 A {@link ProgramElement} * @return pe2's position in pe1 */ - protected static int getPosition(NonTerminalProgramElement pe1, - ProgramElement pe2) { + protected static int getPosition(NonTerminalProgramElement pe1, ProgramElement pe2) { int n = pe1.getChildCount(); int i = 0; while ((i < n) && (pe1.getChildAt(i) != pe2)) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/DeclarationProgramVariableCollector.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/DeclarationProgramVariableCollector.java index 80803a1fb1c..779016c3097 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/DeclarationProgramVariableCollector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/DeclarationProgramVariableCollector.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; @@ -14,14 +17,12 @@ import de.uka.ilkd.key.logic.op.LocationVariable; import de.uka.ilkd.key.logic.op.ProgramConstant; -/** - * The DeclarationProgramVariableCollector collects all top level - * declared program variables relative to the given block to be - * visited, for example starting with +/** + * The DeclarationProgramVariableCollector collects all top level declared program variables + * relative to the given block to be visited, for example starting with * { int j; { int i; } { int h; } for (int k; ...) {} int h; } - * - * the collector will return a set containg j, h the - * h because of the second occurrence of h + * the collector will return a set containg j, h the h because of + * the second occurrence of h */ public class DeclarationProgramVariableCollector extends JavaASTVisitor { @@ -29,54 +30,52 @@ public class DeclarationProgramVariableCollector extends JavaASTVisitor { /** creates a new declaration visitor */ - public DeclarationProgramVariableCollector(ProgramElement root, - Services services) { - super(root, services); + public DeclarationProgramVariableCollector(ProgramElement root, Services services) { + super(root, services); } - - /** starts the walker*/ - public void start() { - walk(root()); + + /** starts the walker */ + public void start() { + walk(root()); } public Set result() { - return result; - } + return result; + } public String toString() { - return result.toString(); + return result.toString(); } - + /** * adds the given variable if we are currently at top level */ protected void addVariable(IProgramVariable var) { - if (depth() == 1) { - result.add(var); - } + if (depth() == 1) { + result.add(var); + } } - protected void doDefaultAction(SourceElement x) { - } + protected void doDefaultAction(SourceElement x) {} public void performActionOnVariableSpecification(VariableSpecification x) { - addVariable(x.getProgramVariable()); + addVariable(x.getProgramVariable()); } - + public void performActionOnFieldSpecification(FieldSpecification x) { - addVariable(x.getProgramVariable()); + addVariable(x.getProgramVariable()); } public void performActionOnImplicitFieldSpecification(ImplicitFieldSpecification x) { - addVariable(x.getProgramVariable()); + addVariable(x.getProgramVariable()); } public void performActionOnLocationVariable(LocationVariable x) { - performActionOnProgramVariable(x); + performActionOnProgramVariable(x); } public void performActionOnProgramConstant(ProgramConstant x) { performActionOnProgramVariable(x); } - + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FieldReplaceVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FieldReplaceVisitor.java index 857583f8a84..cfe28c9d604 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FieldReplaceVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FieldReplaceVisitor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import org.key_project.util.ExtList; @@ -15,8 +18,7 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; /** - * Replaces field references o.a by methodcalls o._a(). This is needed for unit - * test generation. + * Replaces field references o.a by methodcalls o._a(). This is needed for unit test generation. */ public class FieldReplaceVisitor extends CreatingASTVisitor { @@ -25,62 +27,58 @@ public class FieldReplaceVisitor extends CreatingASTVisitor { // private KeYJavaType containingKJT=null public FieldReplaceVisitor(final ProgramElement pe, final Services services) { - super(pe, true, services); + super(pe, true, services); } /** starts the walker */ @Override public void start() { - stack.push(new ExtList()); - walk(root()); - final ExtList el = stack.peek(); - int i = 0; - while (!(el.get(i) instanceof ProgramElement)) { - i++; - } - result = (ProgramElement) stack.peek().get(i); + stack.push(new ExtList()); + walk(root()); + final ExtList el = stack.peek(); + int i = 0; + while (!(el.get(i) instanceof ProgramElement)) { + i++; + } + result = (ProgramElement) stack.peek().get(i); } public ProgramElement result() { - return result; + return result; } @Override public void performActionOnFieldReference(final FieldReference x) { - final ExtList changeList = stack.peek(); - if (changeList.getFirst() == CHANGED) { - changeList.removeFirst(); - } - changeList.removeFirstOccurrence(PositionInfo.class); - if (x.getReferencePrefix() != null) { - final Expression field = (Expression) changeList.get(1); - if (field instanceof ProgramVariable) { - final String shortName = ((ProgramVariable) field) - .getProgramElementName().getProgramName(); - if ("length".equals(shortName)) { - final ExtList l = new ExtList(); - l.add(changeList.get(0)); - addChild(new ArrayLengthReference(l)); - } else { - String typeName = ((ProgramVariable) x.getChildAt(1)) - .getKeYJavaType().getName(); - typeName = PrettyPrinter - .getTypeNameForAccessMethods(typeName); - addChild(new MethodReference(new ExtList(), - new ProgramElementName("_" + shortName + typeName), - (ReferencePrefix) changeList.get(0))); - } - } - } else { - String typeName = ((ProgramVariable) x.getChildAt(0)) - .getKeYJavaType().getName(); - typeName = PrettyPrinter.getTypeNameForAccessMethods(typeName); - addChild(new MethodReference(new ExtList(), new ProgramElementName( - "_" - + ((ProgramVariable) changeList.get(0)) - .getProgramElementName().getProgramName() - + typeName), null)); - } - changed(); + final ExtList changeList = stack.peek(); + if (changeList.getFirst() == CHANGED) { + changeList.removeFirst(); + } + changeList.removeFirstOccurrence(PositionInfo.class); + if (x.getReferencePrefix() != null) { + final Expression field = (Expression) changeList.get(1); + if (field instanceof ProgramVariable) { + final String shortName = + ((ProgramVariable) field).getProgramElementName().getProgramName(); + if ("length".equals(shortName)) { + final ExtList l = new ExtList(); + l.add(changeList.get(0)); + addChild(new ArrayLengthReference(l)); + } else { + String typeName = + ((ProgramVariable) x.getChildAt(1)).getKeYJavaType().getName(); + typeName = PrettyPrinter.getTypeNameForAccessMethods(typeName); + addChild(new MethodReference(new ExtList(), + new ProgramElementName("_" + shortName + typeName), + (ReferencePrefix) changeList.get(0))); + } + } + } else { + String typeName = ((ProgramVariable) x.getChildAt(0)).getKeYJavaType().getName(); + typeName = PrettyPrinter.getTypeNameForAccessMethods(typeName); + addChild(new MethodReference(new ExtList(), new ProgramElementName("_" + + ((ProgramVariable) changeList.get(0)).getProgramElementName().getProgramName() + + typeName), null)); + } + changed(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FreeLabelFinder.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FreeLabelFinder.java index e6197b23511..209726c0908 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FreeLabelFinder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/FreeLabelFinder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import de.uka.ilkd.key.java.Label; @@ -10,22 +13,20 @@ */ public class FreeLabelFinder { - public FreeLabelFinder() { - } + public FreeLabelFinder() {} - public boolean findLabel(Label label, ProgramElement node) { - if (!(node instanceof LabeledStatement && - ((LabeledStatement)node).getLabel().equals(label))) { + public boolean findLabel(Label label, ProgramElement node) { + if (!(node instanceof LabeledStatement + && ((LabeledStatement) node).getLabel().equals(label))) { if (node instanceof NonTerminalProgramElement) { - final NonTerminalProgramElement nonTerminalNode = - (NonTerminalProgramElement) node; - for (int i = 0; i loopLabels, final Label breakLabel, final Label continueLabel, @@ -448,4 +446,4 @@ public void doAction(final ProgramElement x) { } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTCollector.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTCollector.java index 5168995b824..e68a442f599 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTCollector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTCollector.java @@ -1,12 +1,16 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; import de.uka.ilkd.key.java.ProgramElement; -/** Walks through a java AST in depth-left-fist-order. - * You can set the type of nodes you want to collect and then start the - * walker. The found nodes of the given type are returned as a + +/** + * Walks through a java AST in depth-left-fist-order. You can set the type of nodes you want to + * collect and then start the walker. The found nodes of the given type are returned as a * IList */ public class JavaASTCollector extends JavaASTWalker { @@ -14,33 +18,35 @@ public class JavaASTCollector extends JavaASTWalker { /** the type of nodes to be collected */ private Class type; /** the list of found elements */ - private ImmutableList resultList = - ImmutableSLList.nil(); + private ImmutableList resultList = ImmutableSLList.nil(); - /** create the JavaASTWalker + /** + * create the JavaASTWalker + * * @param root the ProgramElement where to begin - * @param type the Class representing the type of nodes that have - * to be collected + * @param type the Class representing the type of nodes that have to be collected */ public JavaASTCollector(ProgramElement root, Class type) { - super(root); - this.type = type; + super(root); + this.type = type; } - /** the action that is performed just before leaving the node the - * last time + /** + * the action that is performed just before leaving the node the last time */ protected void doAction(ProgramElement node) { - if (type.isInstance(node)) { - resultList = resultList.prepend(node); - } + if (type.isInstance(node)) { + resultList = resultList.prepend(node); + } } - /** returns the found nodes of the specified type + /** + * returns the found nodes of the specified type + * * @return the found nodes of the specified type as list */ public ImmutableList getNodes() { - return resultList; + return resultList; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTVisitor.java index 3de6b0858b3..79136467aed 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTVisitor.java @@ -1,4 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; + import de.uka.ilkd.key.logic.Term; import org.key_project.util.collection.ImmutableSet; @@ -28,17 +32,18 @@ import de.uka.ilkd.key.speclang.MergeContract; /** - * Extends the JavaASTWalker to use the visitor mechanism. The - * methods inherited by the Visitor interface are all implemented that - * they call the method doDefaultAction(ProgramElement) . + * Extends the JavaASTWalker to use the visitor mechanism. The methods inherited by the Visitor + * interface are all implemented that they call the method + * doDefaultAction(ProgramElement) . */ -public abstract class JavaASTVisitor extends JavaASTWalker - implements Visitor { +public abstract class JavaASTVisitor extends JavaASTWalker implements Visitor { protected final Services services; - /** create the JavaASTVisitor + /** + * create the JavaASTVisitor + * * @param root the ProgramElement where to begin * @param services the Services object */ @@ -54,29 +59,26 @@ protected void walk(ProgramElement node) { performActionOnJmlAssertCondition(((JmlAssert) node).getCond()); } super.walk(node); - if(node instanceof LoopStatement && services != null) { - LoopSpecification li = services.getSpecificationRepository() - .getLoopSpec((LoopStatement) node); - if(li != null) { + if (node instanceof LoopStatement && services != null) { + LoopSpecification li = + services.getSpecificationRepository().getLoopSpec((LoopStatement) node); + if (li != null) { performActionOnLoopInvariant(li); } } else if (node instanceof StatementBlock && services != null) { ImmutableSet bcs = - services.getSpecificationRepository() - .getBlockContracts((StatementBlock) node); + services.getSpecificationRepository().getBlockContracts((StatementBlock) node); for (BlockContract bc : bcs) { performActionOnBlockContract(bc); } ImmutableSet lcs = - services.getSpecificationRepository() - .getLoopContracts((StatementBlock) node); + services.getSpecificationRepository().getLoopContracts((StatementBlock) node); for (LoopContract lc : lcs) { performActionOnLoopContract(lc); } } else if (node instanceof MergePointStatement && services != null) { - ImmutableSet mcs = services - .getSpecificationRepository() + ImmutableSet mcs = services.getSpecificationRepository() .getMergeContracts((MergePointStatement) node); mcs.forEach(mc -> performActionOnMergeContract(mc)); } @@ -91,8 +93,9 @@ protected void doAction(ProgramElement node) { } - /** the action that is performed just before leaving the node the - * last time + /** + * the action that is performed just before leaving the node the last time + * * @param node the node described above */ protected abstract void doDefaultAction(SourceElement node); @@ -487,7 +490,7 @@ public void performActionOnLocalVariableDeclaration(LocalVariableDeclaration x) public void performActionOnLocationVariable(LocationVariable x) { // TODO: uncomment line below after KeY 1.0 and remove the call // to performActionOnProgramVariable - //doDefaultAction(x); + // doDefaultAction(x); performActionOnProgramVariable(x); } @@ -660,7 +663,7 @@ public void performActionOnPreIncrement(PreIncrement x) { public void performActionOnProgramConstant(ProgramConstant x) { // TODO: uncomment line below after KeY 1.0 and remove the call // to performActionOnProgramVariable - //doDefaultAction(x); + // doDefaultAction(x); performActionOnProgramVariable(x); } @@ -701,7 +704,7 @@ public void performActionOnSchematicFieldReference(SchematicFieldReference x) { @Override public void performActionOnSchemaVariable(SchemaVariable x) { - doDefaultAction((ProgramSV)x); + doDefaultAction((ProgramSV) x); } @Override @@ -851,7 +854,7 @@ public void performActionOnMergePointStatement(MergePointStatement x) { @Override public void performActionOnLoopInvariant(LoopSpecification x) { - //do nothing + // do nothing } @Override @@ -866,25 +869,25 @@ public void performActionOnLoopContract(LoopContract x) { @Override public void performActionOnBlockContract(final StatementBlock oldBlock, - final StatementBlock newBlock) { + final StatementBlock newBlock) { // do nothing } @Override public void performActionOnLoopContract(final StatementBlock oldBlock, - final StatementBlock newBlock) { + final StatementBlock newBlock) { // do nothing } @Override public void performActionOnLoopContract(final LoopStatement oldLoop, - final LoopStatement newLoop) { + final LoopStatement newLoop) { // do nothing } @Override public void performActionOnMergeContract(MergeContract x) { - //do nothing + // do nothing } @Override @@ -920,8 +923,7 @@ public void performActionOnCcatchReturnValParameterDeclaration( } @Override - public void performActionOnCcatchBreakParameterDeclaration( - CcatchBreakParameterDeclaration x) { + public void performActionOnCcatchBreakParameterDeclaration(CcatchBreakParameterDeclaration x) { doDefaultAction(x); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTWalker.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTWalker.java index 5cf4b076fb5..dfa2e627958 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTWalker.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/JavaASTWalker.java @@ -1,12 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import de.uka.ilkd.key.java.NonTerminalProgramElement; import de.uka.ilkd.key.java.ProgramElement; /** - * walks through a java AST in depth-left-fist-order at default. - * Implementing method doAction specifies its behaviour at the - * different Nodes. The depth-left-fist behaviour can be changed by + * walks through a java AST in depth-left-fist-order at default. Implementing method doAction + * specifies its behaviour at the different Nodes. The depth-left-fist behaviour can be changed by * overwriting the method walk(ProgramElement) . */ public abstract class JavaASTWalker { @@ -61,8 +63,7 @@ public int depth() { protected void walk(ProgramElement node) { if (node instanceof NonTerminalProgramElement) { depth++; - NonTerminalProgramElement nonTerminalNode = - (NonTerminalProgramElement) node; + NonTerminalProgramElement nonTerminalNode = (NonTerminalProgramElement) node; for (int i = 0; i < nonTerminalNode.getChildCount(); i++) { if (nonTerminalNode.getChildAt(i) != null) { walk(nonTerminalNode.getChildAt(i)); @@ -75,8 +76,7 @@ protected void walk(ProgramElement node) { } /** - * the action that is performed just before leaving the node the - * last time + * the action that is performed just before leaving the node the last time */ protected abstract void doAction(ProgramElement node); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/LabelCollector.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/LabelCollector.java index e679711ca5c..c74f8e850cd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/LabelCollector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/LabelCollector.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import java.util.HashSet; @@ -14,27 +17,26 @@ public class LabelCollector extends JavaASTVisitor { private HashSet

    - * This class is a specialization of {@link ProgramVariableCollector} which - * returns as result ({@link #result()}) used {@link LocationVariable} which - * are undeclared, but used in the given {@link ProgramElement. + * This class is a specialization of {@link ProgramVariableCollector} which returns as result + * ({@link #result()}) used {@link LocationVariable} which are undeclared, but used in the given + * {@link ProgramElement. *

    *

    * Declared {@link LocationVariable}s are: *

      - *
    • Local variables in blocks and methods
    • - *
    • Self variable of an {@link ExecutionContext}
    • - *
    • Result variable of a {@link MethodFrame}
    • + *
    • Local variables in blocks and methods
    • + *
    • Self variable of an {@link ExecutionContext}
    • + *
    • Result variable of a {@link MethodFrame}
    • *
    *

    + * * @author Martin Hentschel */ public class UndeclaredProgramVariableCollector extends ProgramVariableCollector { - /** - * Contains the found declared {@link IProgramVariable}s. - */ - private LinkedHashSet declaredVariables = new LinkedHashSet(); + /** + * Contains the found declared {@link IProgramVariable}s. + */ + private LinkedHashSet declaredVariables = + new LinkedHashSet(); - /** - * Contains the super result. - */ - private LinkedHashSet allVariables; - - /** - * Contains the undeclared variables as result. - */ - private LinkedHashSet undeclaredVariables; - - /** - * Constructor. - * @param root The {@link ProgramElement} to collect undeclared variables in. - * @param services The {@link Services} to use. - */ - public UndeclaredProgramVariableCollector(ProgramElement root, Services services) { - super(root, services); - } + /** + * Contains the super result. + */ + private LinkedHashSet allVariables; - /** - * {@inheritDoc} - */ - @Override - protected void collectHeapVariables() { - // Ignore heap - } + /** + * Contains the undeclared variables as result. + */ + private LinkedHashSet undeclaredVariables; - /** - * {@inheritDoc} - */ - @Override - public void performActionOnLocalVariableDeclaration(LocalVariableDeclaration x) { - ImmutableArray varSpecs = x.getVariableSpecifications(); - for (VariableSpecification spec : varSpecs) { - IProgramVariable var = spec.getProgramVariable(); - if (var != null) { - declaredVariables.add(var); - } - } - } + /** + * Constructor. + * + * @param root The {@link ProgramElement} to collect undeclared variables in. + * @param services The {@link Services} to use. + */ + public UndeclaredProgramVariableCollector(ProgramElement root, Services services) { + super(root, services); + } - /** - * {@inheritDoc} - */ - @Override - public void performActionOnMethodFrame(MethodFrame x) { - IProgramVariable resultVar = x.getProgramVariable(); - if (resultVar != null) { - declaredVariables.add(resultVar); - } - } + /** + * {@inheritDoc} + */ + @Override + protected void collectHeapVariables() { + // Ignore heap + } - /** - * {@inheritDoc} - */ - @Override - public void performActionOnExecutionContext(ExecutionContext x) { - if (x.getRuntimeInstance() instanceof IProgramVariable) { - declaredVariables.add((IProgramVariable)x.getRuntimeInstance()); - } - } + /** + * {@inheritDoc} + */ + @Override + public void performActionOnLocalVariableDeclaration(LocalVariableDeclaration x) { + ImmutableArray varSpecs = x.getVariableSpecifications(); + for (VariableSpecification spec : varSpecs) { + IProgramVariable var = spec.getProgramVariable(); + if (var != null) { + declaredVariables.add(var); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void performActionOnMethodFrame(MethodFrame x) { + IProgramVariable resultVar = x.getProgramVariable(); + if (resultVar != null) { + declaredVariables.add(resultVar); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void performActionOnExecutionContext(ExecutionContext x) { + if (x.getRuntimeInstance() instanceof IProgramVariable) { + declaredVariables.add((IProgramVariable) x.getRuntimeInstance()); + } + } + + /** + * Returns the found declared variables. + * + * @return The found declared variables. + */ + public Set getDeclaredVariables() { + return declaredVariables; + } - /** - * Returns the found declared variables. - * @return The found declared variables. - */ - public Set getDeclaredVariables() { - return declaredVariables; - } - - /** - * Returns all used variables. - * @return All used variables. - */ - public LinkedHashSet getAllVariables() { - if (allVariables == null) { - allVariables = super.result(); - } - return allVariables; - } + /** + * Returns all used variables. + * + * @return All used variables. + */ + public LinkedHashSet getAllVariables() { + if (allVariables == null) { + allVariables = super.result(); + } + return allVariables; + } - /** - * Returns the undeclared variables as result. - * @return The undeclared variables. - */ - @Override - public LinkedHashSet result() { - if (undeclaredVariables == null) { - // Create result Set - undeclaredVariables = new LinkedHashSet(); - // Add all found variables - undeclaredVariables.addAll(getAllVariables()); - // Remove all declared variables - undeclaredVariables.removeAll(getDeclaredVariables()); - // Remove all fields (members) - Iterator iter = undeclaredVariables.iterator(); - while (iter.hasNext()) { - LocationVariable next = iter.next(); - if (next.isMember()) { - iter.remove(); + /** + * Returns the undeclared variables as result. + * + * @return The undeclared variables. + */ + @Override + public LinkedHashSet result() { + if (undeclaredVariables == null) { + // Create result Set + undeclaredVariables = new LinkedHashSet(); + // Add all found variables + undeclaredVariables.addAll(getAllVariables()); + // Remove all declared variables + undeclaredVariables.removeAll(getDeclaredVariables()); + // Remove all fields (members) + Iterator iter = undeclaredVariables.iterator(); + while (iter.hasNext()) { + LocationVariable next = iter.next(); + if (next.isMember()) { + iter.remove(); + } } - } - } - return undeclaredVariables; - } -} \ No newline at end of file + } + return undeclaredVariables; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/Visitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/Visitor.java index 0c37801f6a2..8f75ccb3dbb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/Visitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/java/visitor/Visitor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.java.visitor; import de.uka.ilkd.key.java.*; @@ -26,10 +29,8 @@ import de.uka.ilkd.key.speclang.MergeContract; /** - * This class is implemented by visitors/walkers. - * Each AST node implements a visit(Visitor) method that - * calls the doActionAt method. Similar to the pretty print - * mechanism. + * This class is implemented by visitors/walkers. Each AST node implements a visit(Visitor) method + * that calls the doActionAt method. Similar to the pretty print mechanism. */ public interface Visitor { @@ -171,8 +172,7 @@ public interface Visitor { void performActionOnFieldSpecification(FieldSpecification x); - void performActionOnImplicitFieldSpecification - (ImplicitFieldSpecification x); + void performActionOnImplicitFieldSpecification(ImplicitFieldSpecification x); void performActionOnBinaryAnd(BinaryAnd x); @@ -206,8 +206,7 @@ public interface Visitor { void performActionOnTimesAssignment(TimesAssignment x); - void performActionOnUnsignedShiftRightAssignment( - UnsignedShiftRightAssignment x); + void performActionOnUnsignedShiftRightAssignment(UnsignedShiftRightAssignment x); void performActionOnBinaryNot(BinaryNot x); @@ -336,34 +335,28 @@ void performActionOnUnsignedShiftRightAssignment( void performActionOnLoopContract(LoopContract x); /** - * Adds block contract for new statement block to block contract - * of old block statement. + * Adds block contract for new statement block to block contract of old block statement. * * @param oldBlock the old block * @param newBlock the new block */ - void performActionOnBlockContract(final StatementBlock oldBlock, - final StatementBlock newBlock); + void performActionOnBlockContract(final StatementBlock oldBlock, final StatementBlock newBlock); /** - * Adds block contract for new statement block to block contract - * of old block statement. + * Adds block contract for new statement block to block contract of old block statement. * * @param oldBlock the old block * @param newBlock the new block */ - void performActionOnLoopContract(final StatementBlock oldBlock, - final StatementBlock newBlock); + void performActionOnLoopContract(final StatementBlock oldBlock, final StatementBlock newBlock); /** - * Adds loop contract for new loop statement to loop contract - * of old loop statement. + * Adds loop contract for new loop statement to loop contract of old loop statement. * * @param oldLoop the old loop statement * @param newLoop the new loop statement */ - void performActionOnLoopContract(final LoopStatement oldLoop, - final LoopStatement newLoop); + void performActionOnLoopContract(final LoopStatement oldLoop, final LoopStatement newLoop); void performActionOnMergeContract(MergeContract x); @@ -416,8 +409,8 @@ void performActionOnCcatchBreakWildcardParameterDeclaration( * Note: if you don't extend JavaASTVisitor or something else that calls this methode for you, * you have to call it yourself, e.g. in {@link #performActionOnJmlAssert} if needed. * - * @param cond the condition to perform an action on - * (may be {@code null} if the JML assert wasn't finished) + * @param cond the condition to perform an action on (may be {@code null} if the JML assert + * wasn't finished) */ void performActionOnJmlAssertCondition(final Term cond); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/BooleanLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/BooleanLDT.java index 46ade63ac0c..d272f07f816 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/BooleanLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/BooleanLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -16,49 +19,49 @@ import de.uka.ilkd.key.util.Debug; -/** - * This class inherits from LDT and implements all method that are - * necessary to handle the primitive type boolean. +/** + * This class inherits from LDT and implements all method that are necessary to handle the primitive + * type boolean. */ public final class BooleanLDT extends LDT { - + public static final Name NAME = new Name("boolean"); - + /** the boolean literals as function symbols and terms */ private final Function bool_true; private final Term term_bool_true; private final Function bool_false; private final Term term_bool_false; - - - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + + + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- public BooleanLDT(TermServices services) { super(NAME, services); - - bool_true = addFunction(services, "TRUE"); - term_bool_true = services.getTermBuilder().func(bool_true); - bool_false = addFunction(services, "FALSE"); - term_bool_false = services.getTermBuilder().func(bool_false); + + bool_true = addFunction(services, "TRUE"); + term_bool_true = services.getTermBuilder().func(bool_true); + bool_false = addFunction(services, "FALSE"); + term_bool_false = services.getTermBuilder().func(bool_false); } - - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- - + + + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- + public Term getFalseTerm() { return term_bool_false; } - + public Term getTrueTerm() { return term_bool_true; } - + /** * returns the function representing the boolean value FALSE */ @@ -66,7 +69,7 @@ public Function getFalseConst() { return bool_false; } - + /** * returns the function representing the boolean value TRUE */ @@ -74,81 +77,78 @@ public Function getTrueConst() { return bool_true; } - + @Override - public boolean isResponsible - (de.uka.ilkd.key.java.expression.Operator op, Term[] subs, - Services services, ExecutionContext ec) { - if (subs.length == 1) { - return isResponsible(op, subs[0], services, ec); - } else if (subs.length == 2) { - return isResponsible(op, subs[0], subs[1], services, ec); - } - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + if (subs.length == 1) { + return isResponsible(op, subs[0], services, ec); + } else if (subs.length == 2) { + return isResponsible(op, subs[0], subs[1], services, ec); + } + return false; } - + @Override - public boolean isResponsible - (de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, Services services, ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible - (de.uka.ilkd.key.java.expression.Operator op, Term sub, TermServices services, ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return false; } - - @Override + + @Override public Term translateLiteral(Literal lit, Services services) { - if (lit instanceof BooleanLiteral) { - return (((BooleanLiteral)lit).getValue() ? - term_bool_true : term_bool_false); - } - Debug.fail("booleanLDT: Wrong literal", lit); - return null; + if (lit instanceof BooleanLiteral) { + return (((BooleanLiteral) lit).getValue() ? term_bool_true : term_bool_false); + } + Debug.fail("booleanLDT: Wrong literal", lit); + return null; } - + @Override - public Function getFunctionFor - (de.uka.ilkd.key.java.expression.Operator op, Services services, - ExecutionContext ec) { - assert false; - return null; - } + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services services, + ExecutionContext ec) { + assert false; + return null; + } @Override public boolean hasLiteralFunction(Function f) { - return containsFunction(f) && f.arity()==0; + return containsFunction(f) && f.arity() == 0; } - + @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if(t.op() == bool_true) { - return BooleanLiteral.TRUE; - } else if(t.op() == bool_false) { - return BooleanLiteral.FALSE; - } else { - assert false : "BooleanLDT: Cannot convert term to program: " + t; - return null; - } + if (t.op() == bool_true) { + return BooleanLiteral.TRUE; + } else if (t.op() == bool_false) { + return BooleanLiteral.FALSE; + } else { + assert false : "BooleanLDT: Cannot convert term to program: " + t; + return null; + } } - - + + @Override public final Type getType(Term t) { - if(t.sort() == targetSort()) { - return PrimitiveType.JAVA_BOOLEAN; - } else { - assert false : "BooleanLDT: Cannot get Java type for term: " + t; - return null; - } + if (t.sort() == targetSort()) { + return PrimitiveType.JAVA_BOOLEAN; + } else { + assert false : "BooleanLDT: Cannot get Java type for term: " + t; + return null; + } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java index 64b8a908542..90b9a01efa9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/CharListLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -21,17 +24,17 @@ public final class CharListLDT extends LDT { - + public static final Name NAME = new Name("CharList"); - + public static final Name STRINGPOOL_NAME = new Name("strPool"); public static final Name STRINGCONTENT_NAME = new Name("strContent"); - - - //Warning: Some names of char list functions are hardcoded into - // LexPathOrdering and into CharListNotation! - - //functions + + + // Warning: Some names of char list functions are hardcoded into + // LexPathOrdering and into CharListNotation! + + // functions private final Function clIndexOfChar; private final Function clIndexOfCl; private final Function clLastIndexOfChar; @@ -41,220 +44,212 @@ public final class CharListLDT extends LDT { private final Function clRemoveZeros; private final Function clHashCode; - //predicates + // predicates private final Function clStartsWith; private final Function clEndsWith; private final Function clContains; - - - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- - + + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- + public CharListLDT(TermServices services) { - super(NAME, (Sort) services.getNamespaces().sorts().lookup(SeqLDT.NAME), services); - clIndexOfChar = addFunction(services, "clIndexOfChar"); - clIndexOfCl = addFunction(services, "clIndexOfCl"); - clLastIndexOfChar = addFunction(services, "clLastIndexOfChar"); - clLastIndexOfCl = addFunction(services, "clLastIndexOfCl"); - clReplace = addFunction(services, "clReplace"); - clTranslateInt = addFunction(services, "clTranslateInt"); - clRemoveZeros = addFunction(services, "clRemoveZeros"); - clHashCode = addFunction(services, "clHashCode"); - - clStartsWith = addFunction(services, "clStartsWith"); - clEndsWith = addFunction(services, "clEndsWith"); - clContains = addFunction(services, "clContains"); + super(NAME, (Sort) services.getNamespaces().sorts().lookup(SeqLDT.NAME), services); + clIndexOfChar = addFunction(services, "clIndexOfChar"); + clIndexOfCl = addFunction(services, "clIndexOfCl"); + clLastIndexOfChar = addFunction(services, "clLastIndexOfChar"); + clLastIndexOfCl = addFunction(services, "clLastIndexOfCl"); + clReplace = addFunction(services, "clReplace"); + clTranslateInt = addFunction(services, "clTranslateInt"); + clRemoveZeros = addFunction(services, "clRemoveZeros"); + clHashCode = addFunction(services, "clHashCode"); + + clStartsWith = addFunction(services, "clStartsWith"); + clEndsWith = addFunction(services, "clEndsWith"); + clContains = addFunction(services, "clContains"); } - - - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- - + + + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- + private String translateCharTerm(Term t) { - char charVal = 0; - int intVal = 0; - String result = printlastfirst(t.sub(0)).toString(); - try { - intVal = Integer.parseInt(result); - charVal = (char) intVal; - if (intVal - charVal != 0) - throw new NumberFormatException(); // overflow! - - } catch (NumberFormatException ex) { - throw new ConvertException(result + " is not of type char"); - } - return ""+charVal; + char charVal = 0; + int intVal = 0; + String result = printlastfirst(t.sub(0)).toString(); + try { + intVal = Integer.parseInt(result); + charVal = (char) intVal; + if (intVal - charVal != 0) + throw new NumberFormatException(); // overflow! + + } catch (NumberFormatException ex) { + throw new ConvertException(result + " is not of type char"); + } + return "" + charVal; } - + private StringBuffer printlastfirst(Term t) { - if (t.op().arity() == 0) { - return new StringBuffer(); - } else { - return printlastfirst(t.sub(0)).append(t.op().name().toString()); - } + if (t.op().arity() == 0) { + return new StringBuffer(); + } else { + return printlastfirst(t.sub(0)).append(t.op().name().toString()); + } } - - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- - - + + + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- + + public Function getClIndexOfChar() { - return clIndexOfChar; + return clIndexOfChar; } - - + + public Function getClIndexOfCl() { - return clIndexOfCl; + return clIndexOfCl; } - - + + public Function getClLastIndexOfChar() { - return clLastIndexOfChar; + return clLastIndexOfChar; } - - + + public Function getClLastIndexOfCl() { - return clLastIndexOfCl; + return clLastIndexOfCl; } - - + + public Function getClReplace() { - return clReplace; + return clReplace; } - - + + public Function getClTranslateInt() { - return clTranslateInt; + return clTranslateInt; } - - + + public Function getClRemoveZeros() { - return clRemoveZeros; + return clRemoveZeros; } - - + + public Function getClHashCode() { - return clHashCode; + return clHashCode; } - + public Function getClStartsWith() { - return clStartsWith; + return clStartsWith; } - - + + public Function getClEndsWith() { - return clEndsWith; + return clEndsWith; } - - + + public Function getClContains() { - return clContains; + return clContains; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return false; } @Override public Term translateLiteral(Literal lit, Services services) { - final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); - final TermBuilder tb = services.getTermBuilder(); - final Term term_empty = tb.func(seqLDT.getSeqEmpty()); - - char[] charArray; - Term result = term_empty; - - if (lit instanceof StringLiteral) { - charArray = ((StringLiteral) lit).getValue().toCharArray(); - } else { - return null; - } - - IntegerLDT intLDT = services.getTypeConverter().getIntegerLDT(); - if (intLDT == null) { - throw new IllegalArgumentException( - "IntegerLDT is needed for StringLiteral translation"); - } - - for (int i = charArray.length - 2; i >= 1; i--) { - Term singleton = tb.seqSingleton(intLDT.translateLiteral(new CharLiteral(charArray[i]), services)); - result = tb.seqConcat(singleton, result); - } - - return result; + final SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); + final TermBuilder tb = services.getTermBuilder(); + final Term term_empty = tb.func(seqLDT.getSeqEmpty()); + + char[] charArray; + Term result = term_empty; + + if (lit instanceof StringLiteral) { + charArray = ((StringLiteral) lit).getValue().toCharArray(); + } else { + return null; + } + + IntegerLDT intLDT = services.getTypeConverter().getIntegerLDT(); + if (intLDT == null) { + throw new IllegalArgumentException( + "IntegerLDT is needed for StringLiteral translation"); + } + + for (int i = charArray.length - 2; i >= 1; i--) { + Term singleton = tb + .seqSingleton(intLDT.translateLiteral(new CharLiteral(charArray[i]), services)); + result = tb.seqConcat(singleton, result); + } + + return result; } - + @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services serv, - ExecutionContext ec) { - assert false; - return null; + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services serv, + ExecutionContext ec) { + assert false; + return null; } - + @Override public boolean hasLiteralFunction(Function f) { - return false; + return false; } - + @Override public Expression translateTerm(Term t, ExtList children, Services services) { - final StringBuffer result = new StringBuffer(""); - Term term = t; - while (term.op().arity() != 0) { - result.append(translateCharTerm(term.sub(0))); - term = term.sub(1); - } - return new StringLiteral("\"" + result + "\""); + final StringBuffer result = new StringBuffer(""); + Term term = t; + while (term.op().arity() != 0) { + result.append(translateCharTerm(term.sub(0))); + term = term.sub(1); + } + return new StringLiteral("\"" + result + "\""); } - - + + @Override public final Type getType(Term t) { - assert false; - return null; + assert false; + return null; } - @Nullable - @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - return services.getTypeConverter().getSeqLDT().getFunctionFor(operatorSymbol, services); - } -} \ No newline at end of file + @Nullable + @Override + public Function getFunctionFor(String operatorSymbol, Services services) { + return services.getTypeConverter().getSeqLDT().getFunctionFor(operatorSymbol, services); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java index e4c2bad6fe6..353532343da 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/DoubleLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import de.uka.ilkd.key.java.expression.literal.FloatLiteral; @@ -72,55 +75,53 @@ public final class DoubleLDT extends LDT implements FloatingPointLDT { public DoubleLDT(TermServices services) { super(NAME, services); - doubleLit = addFunction(services, DOUBLELIT_NAME.toString()); - javaUnaryMinusDouble = addFunction(services, NEGATIVE_LITERAL.toString()); - lessThan = addFunction(services, "ltDouble"); - greaterThan = addFunction(services, "gtDouble"); - lessOrEquals = addFunction(services, "leqDouble"); - greaterOrEquals = addFunction(services, "geqDouble"); - eqDouble = addFunction(services, "eqDouble"); - - javaAddDouble = addFunction(services, "javaAddDouble"); - javaSubDouble = addFunction(services, "javaSubDouble"); - javaMulDouble = addFunction(services, "javaMulDouble"); - javaDivDouble = addFunction(services, "javaDivDouble"); - javaModDouble = addFunction(services, "javaModDouble"); - javaMaxDouble = addFunction(services, "javaMaxDouble"); - javaMinDouble = addFunction(services, "javaMinDouble"); - - addDouble = addFunction(services, "addDouble"); - subDouble = addFunction(services, "subDouble"); - mulDouble = addFunction(services, "mulDouble"); - divDouble = addFunction(services, "divDouble"); - doubleAbs = addFunction(services, "absDouble"); - negDouble = addFunction(services, "negDouble"); - - isNormal = addFunction(services, "doubleIsNormal"); - isSubnormal = addFunction(services, "doubleIsSubnormal"); - isNaN = addFunction(services, "doubleIsNaN"); - isZero = addFunction(services, "doubleIsZero"); - isNice = addFunction(services, "doubleIsNice"); - isInfinite = addFunction(services, "doubleIsInfinite"); - isPositive = addFunction(services, "doubleIsPositive"); - isNegative = addFunction(services, "doubleIsNegative"); - - sinDouble = addFunction(services, "sinDouble"); - cosDouble = addFunction(services, "cosDouble"); - acosDouble = addFunction(services, "acosDouble"); - asinDouble = addFunction(services, "asinDouble"); - tanDouble = addFunction(services, "tanDouble"); - atan2Double = addFunction(services, "atan2Double"); - sqrtDouble = addFunction(services, "sqrtDouble"); - powDouble = addFunction(services, "powDouble"); - expDouble = addFunction(services, "expDouble"); - atanDouble = addFunction(services, "atanDouble"); + doubleLit = addFunction(services, DOUBLELIT_NAME.toString()); + javaUnaryMinusDouble = addFunction(services, NEGATIVE_LITERAL.toString()); + lessThan = addFunction(services, "ltDouble"); + greaterThan = addFunction(services, "gtDouble"); + lessOrEquals = addFunction(services, "leqDouble"); + greaterOrEquals = addFunction(services, "geqDouble"); + eqDouble = addFunction(services, "eqDouble"); + + javaAddDouble = addFunction(services, "javaAddDouble"); + javaSubDouble = addFunction(services, "javaSubDouble"); + javaMulDouble = addFunction(services, "javaMulDouble"); + javaDivDouble = addFunction(services, "javaDivDouble"); + javaModDouble = addFunction(services, "javaModDouble"); + javaMaxDouble = addFunction(services, "javaMaxDouble"); + javaMinDouble = addFunction(services, "javaMinDouble"); + + addDouble = addFunction(services, "addDouble"); + subDouble = addFunction(services, "subDouble"); + mulDouble = addFunction(services, "mulDouble"); + divDouble = addFunction(services, "divDouble"); + doubleAbs = addFunction(services, "absDouble"); + negDouble = addFunction(services, "negDouble"); + + isNormal = addFunction(services, "doubleIsNormal"); + isSubnormal = addFunction(services, "doubleIsSubnormal"); + isNaN = addFunction(services, "doubleIsNaN"); + isZero = addFunction(services, "doubleIsZero"); + isNice = addFunction(services, "doubleIsNice"); + isInfinite = addFunction(services, "doubleIsInfinite"); + isPositive = addFunction(services, "doubleIsPositive"); + isNegative = addFunction(services, "doubleIsNegative"); + + sinDouble = addFunction(services, "sinDouble"); + cosDouble = addFunction(services, "cosDouble"); + acosDouble = addFunction(services, "acosDouble"); + asinDouble = addFunction(services, "asinDouble"); + tanDouble = addFunction(services, "tanDouble"); + atan2Double = addFunction(services, "atan2Double"); + sqrtDouble = addFunction(services, "sqrtDouble"); + powDouble = addFunction(services, "powDouble"); + expDouble = addFunction(services, "expDouble"); + atanDouble = addFunction(services, "atanDouble"); } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { if (subs.length == 1) { return isResponsible(op, subs[0], services, ec); } else if (subs.length == 2) { @@ -130,14 +131,9 @@ public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - if(left != null - && left.sort().extendsTrans(targetSort()) - && right != null + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + if (left != null && left.sort().extendsTrans(targetSort()) && right != null && right.sort().extendsTrans(targetSort())) { return getFunctionFor(op, services, ec) != null; } @@ -145,11 +141,9 @@ public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - if(sub != null && sub.sort().extendsTrans(targetSort())) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + if (sub != null && sub.sort().extendsTrans(targetSort())) { return op instanceof Negative; } return false; @@ -158,33 +152,25 @@ public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, @Override public Term translateLiteral(Literal lit, Services services) { - assert lit instanceof DoubleLiteral : "Literal '"+lit+"' is not a double literal."; - String s = ((DoubleLiteral)lit).getValue(); + assert lit instanceof DoubleLiteral : "Literal '" + lit + "' is not a double literal."; + String s = ((DoubleLiteral) lit).getValue(); double doubleVal = Double.parseDouble(s); return services.getTermBuilder().dfpTerm(doubleVal); } -/* @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - // Floating point extensions with "\fp_" - case "nan": return getIsNaN(); - case "zero": return getIsZero(); - case "infinite": return getIsInfinite(); - case "nice": return getIsNice(); - case "abs": return getAbs(); - case "negative": return getIsNegative(); - case "positive": return getIsPositive(); - case "subnormal": return getIsSubnormal(); - case "normal": return getIsNormal(); - } - return null; - }*/ + /* + * @Override public Function getFunctionFor(String operatorSymbol, Services services) { // + * Floating point extensions with "\fp_" case "nan": return getIsNaN(); case "zero": return + * getIsZero(); case "infinite": return getIsInfinite(); case "nice": return getIsNice(); case + * "abs": return getAbs(); case "negative": return getIsNegative(); case "positive": return + * getIsPositive(); case "subnormal": return getIsSubnormal(); case "normal": return + * getIsNormal(); } return null; } + */ @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services services, - ExecutionContext ec) { + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services services, + ExecutionContext ec) { if (op instanceof Negative) { return getJavaUnaryMinus(); } else { @@ -194,15 +180,15 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, @Override public boolean hasLiteralFunction(Function f) { - return containsFunction(f) && (f.arity()==0); + return containsFunction(f) && (f.arity() == 0); } @Override public DoubleLiteral translateTerm(Term t, ExtList children, Services services) { - Function f = (Function)t.op(); + Function f = (Function) t.op(); IntegerLDT intLDT = services.getTypeConverter().getIntegerLDT(); - if(f == doubleLit) { + if (f == doubleLit) { // Use IntegerLDT to translate to literals String digits = intLDT.toNumberString(t.sub(0)); long bits = Long.parseUnsignedLong(digits); @@ -217,7 +203,7 @@ public DoubleLiteral translateTerm(Term t, ExtList children, Services services) @Override public Type getType(Term t) { - if(t.sort() == targetSort()) { + if (t.sort() == targetSort()) { return PrimitiveType.JAVA_DOUBLE; } else { return null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java index 64d04ae1240..e2845e1e5a8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -68,44 +71,42 @@ public final class FloatLDT extends LDT implements FloatingPointLDT { public FloatLDT(TermServices services) { super(NAME, services); - floatLit = addFunction(services, FLOATLIT_NAME.toString()); + floatLit = addFunction(services, FLOATLIT_NAME.toString()); javaUnaryMinusFloat = addFunction(services, NEGATIVE_LITERAL.toString()); - lessThan = addFunction(services, "ltFloat"); - greaterThan = addFunction(services, "gtFloat"); - lessOrEquals = addFunction(services, "leqFloat"); - greaterOrEquals = addFunction(services, "geqFloat"); - eqFloat = addFunction(services, "eqFloat"); - - javaAddFloat = addFunction(services, "javaAddFloat"); - javaSubFloat = addFunction(services, "javaSubFloat"); - javaMulFloat = addFunction(services, "javaMulFloat"); - javaDivFloat = addFunction(services, "javaDivFloat"); - javaModFloat = addFunction(services, "javaModFloat"); - javaMaxFloat = addFunction(services, "javaMaxFloat"); - javaMinFloat = addFunction(services, "javaMinFloat"); - - addFloatIEEE = addFunction(services, "addFloat"); - subFloatIEEE = addFunction(services, "subFloat"); - mulFloatIEEE = addFunction(services, "mulFloat"); - divFloatIEEE = addFunction(services, "divFloat"); - absFloat = addFunction(services, "absFloat"); - negFloat = addFunction(services, "negFloat"); - - isNormal = addFunction(services, "floatIsNormal"); - isSubnormal = addFunction(services, "floatIsSubnormal"); - isNaN = addFunction(services, "floatIsNaN"); - isZero = addFunction(services, "floatIsZero"); - isNice = addFunction(services, "floatIsNice"); - isInfinite = addFunction(services, "floatIsInfinite"); - isPositive = addFunction(services, "floatIsPositive"); - isNegative = addFunction(services, "floatIsNegative"); + lessThan = addFunction(services, "ltFloat"); + greaterThan = addFunction(services, "gtFloat"); + lessOrEquals = addFunction(services, "leqFloat"); + greaterOrEquals = addFunction(services, "geqFloat"); + eqFloat = addFunction(services, "eqFloat"); + + javaAddFloat = addFunction(services, "javaAddFloat"); + javaSubFloat = addFunction(services, "javaSubFloat"); + javaMulFloat = addFunction(services, "javaMulFloat"); + javaDivFloat = addFunction(services, "javaDivFloat"); + javaModFloat = addFunction(services, "javaModFloat"); + javaMaxFloat = addFunction(services, "javaMaxFloat"); + javaMinFloat = addFunction(services, "javaMinFloat"); + + addFloatIEEE = addFunction(services, "addFloat"); + subFloatIEEE = addFunction(services, "subFloat"); + mulFloatIEEE = addFunction(services, "mulFloat"); + divFloatIEEE = addFunction(services, "divFloat"); + absFloat = addFunction(services, "absFloat"); + negFloat = addFunction(services, "negFloat"); + + isNormal = addFunction(services, "floatIsNormal"); + isSubnormal = addFunction(services, "floatIsSubnormal"); + isNaN = addFunction(services, "floatIsNaN"); + isZero = addFunction(services, "floatIsZero"); + isNice = addFunction(services, "floatIsNice"); + isInfinite = addFunction(services, "floatIsInfinite"); + isPositive = addFunction(services, "floatIsPositive"); + isNegative = addFunction(services, "floatIsNegative"); } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { if (subs.length == 1) { return isResponsible(op, subs[0], services, ec); } else if (subs.length == 2) { @@ -115,40 +116,30 @@ public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return left != null - && left.sort().extendsTrans(targetSort()) - && right != null + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return left != null && left.sort().extendsTrans(targetSort()) && right != null && right.sort().extendsTrans(targetSort()) && getFunctionFor(op, services, ec) != null; } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return sub != null - && sub.sort().extendsTrans(targetSort()) - && op instanceof Negative; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return sub != null && sub.sort().extendsTrans(targetSort()) && op instanceof Negative; } @Override public Term translateLiteral(Literal lit, Services services) { - assert lit instanceof FloatLiteral : "Literal '"+lit+"' is not a float literal."; - String s = ((FloatLiteral)lit).getValue(); + assert lit instanceof FloatLiteral : "Literal '" + lit + "' is not a float literal."; + String s = ((FloatLiteral) lit).getValue(); Float flValue = Float.parseFloat(s); return services.getTermBuilder().fpTerm(flValue); } @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services services, - ExecutionContext ec) { + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services services, + ExecutionContext ec) { if (op instanceof GreaterThan) { return getGreaterThan(); } else if (op instanceof LessThan) { @@ -174,53 +165,47 @@ public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, } } -/* @Override - public Function getFunctionFor(String operatorSymbol, Services services) { - case "nan": return getIsNaN(); - case "zero": return getIsZero(); - case "infinite": return getIsInfinite(); - case "nice": return getIsNice(); - case "abs": return getAbs(); - case "negative": return getIsNegative(); - case "positive": return getIsPositive(); - case "subnormal": return getIsSubnormal(); - - case "normal": return getIsNormal(); - - } - return null; - } - */ + /* + * @Override public Function getFunctionFor(String operatorSymbol, Services services) { case + * "nan": return getIsNaN(); case "zero": return getIsZero(); case "infinite": return + * getIsInfinite(); case "nice": return getIsNice(); case "abs": return getAbs(); case + * "negative": return getIsNegative(); case "positive": return getIsPositive(); case + * "subnormal": return getIsSubnormal(); + * + * case "normal": return getIsNormal(); + * + * } return null; } + */ @Override public boolean hasLiteralFunction(Function f) { - return containsFunction(f) && (f.arity()==0); + return containsFunction(f) && (f.arity() == 0); } @Override public FloatLiteral translateTerm(Term t, ExtList children, Services services) { - if(!containsFunction((Function) t.op())) { + if (!containsFunction((Function) t.op())) { return null; } - Function f = (Function)t.op(); + Function f = (Function) t.op(); IntegerLDT intLDT = services.getTypeConverter().getIntegerLDT(); - if(f == floatLit) { + if (f == floatLit) { // Use IntegerLDT to translate to literals String digits = intLDT.toNumberString(t.sub(0)); int bits = Integer.parseUnsignedInt(digits); float f1 = Float.intBitsToFloat(bits); return new FloatLiteral(Float.toString(f1)); } - throw new RuntimeException("FloatLDT: Cannot convert term to program: "+t); + throw new RuntimeException("FloatLDT: Cannot convert term to program: " + t); } @Override public final Type getType(Term t) { - if(t.sort() == targetSort()) { + if (t.sort() == targetSort()) { return PrimitiveType.JAVA_FLOAT; } else { return null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatingPointLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatingPointLDT.java index 03542b8dadc..35256c36533 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatingPointLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FloatingPointLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import de.uka.ilkd.key.logic.op.Function; @@ -5,29 +8,54 @@ public interface FloatingPointLDT { public Function getLessThan(); + public Function getGreaterThan(); + public Function getLessOrEquals(); + public Function getGreaterOrEquals(); + public Function getEquals(); + public Function getJavaUnaryMinus(); + public Function getJavaAdd(); + public Function getJavaSub(); + public Function getJavaMul(); + public Function getJavaDiv(); + public Function getJavaMod(); + public Function getJavaMin(); + public Function getJavaMax(); + public Function getIsNormal(); + public Function getIsSubnormal(); + public Function getIsNaN(); + public Function getIsZero(); + public Function getIsNice(); + public Function getIsInfinite(); + public Function getIsPositive(); + public Function getIsNegative(); + public Function getAdd(); + public Function getSub(); + public Function getMul(); + public Function getDiv(); + public Function getAbs(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FreeLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FreeLDT.java index 3f8d2af5caf..79b63b3f812 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FreeLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/FreeLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -14,34 +17,34 @@ import de.uka.ilkd.key.logic.TermServices; import de.uka.ilkd.key.logic.op.Function; -/** Generic data type, which has no predefined theory. - * It is meant as a basis to implement an additional abstract data type, - * e.g., binary trees, stacks, etc. in .key files. +/** + * Generic data type, which has no predefined theory. It is meant as a basis to implement an + * additional abstract data type, e.g., binary trees, stacks, etc. in .key files. + * * @author daniel * */ public final class FreeLDT extends LDT { public static final Name NAME = new Name("Free"); - + // neutral element, the only pre-defined function private Function atom; public FreeLDT(TermServices services) { super(NAME, services); - atom = addFunction(services, "atom"); + atom = addFunction(services, "atom"); } @Override - public boolean isResponsible(Operator op, Term[] subs, Services services, - ExecutionContext ec) { + public boolean isResponsible(Operator op, Term[] subs, Services services, ExecutionContext ec) { // TODO Auto-generated method stub return false; } @Override - public boolean isResponsible(Operator op, Term left, Term right, - Services services, ExecutionContext ec) { + public boolean isResponsible(Operator op, Term left, Term right, Services services, + ExecutionContext ec) { // TODO Auto-generated method stub return false; } @@ -59,8 +62,7 @@ public Term translateLiteral(Literal lit, Services services) { } @Override - public Function getFunctionFor(Operator op, Services services, - ExecutionContext ec) { + public Function getFunctionFor(Operator op, Services services, ExecutionContext ec) { // TODO Auto-generated method stub assert false; return null; @@ -73,7 +75,7 @@ public boolean hasLiteralFunction(Function f) { @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if(t.op() instanceof Function && hasLiteralFunction((Function)t.op())) { + if (t.op() instanceof Function && hasLiteralFunction((Function) t.op())) { return FreeLiteral.INSTANCE; } assert false; @@ -85,9 +87,9 @@ public Type getType(Term t) { assert false; return null; } - - public Function getAtom(){ + + public Function getAtom() { return atom; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/HeapLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/HeapLDT.java index 70215e63e94..04411d88349 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/HeapLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/HeapLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -32,34 +35,35 @@ /** - * LDT responsible for the "Heap" sort, and the associated "Field" sort. Besides - * offering the usual LDT functionality, this class is also responsible for - * creating and managing the constant symbols representing fields. + * LDT responsible for the "Heap" sort, and the associated "Field" sort. Besides offering the usual + * LDT functionality, this class is also responsible for creating and managing the constant symbols + * representing fields. */ public final class HeapLDT extends LDT { - - public static final Name NAME = new Name("Heap"); - + + public static final Name NAME = new Name("Heap"); + public static final Name SELECT_NAME = new Name("select"); public static final Name STORE_NAME = new Name("store"); public static final Name BASE_HEAP_NAME = new Name("heap"); public static final Name SAVED_HEAP_NAME = new Name("savedHeap"); public static final Name PERMISSION_HEAP_NAME = new Name("permissions"); - public static final Name[] VALID_HEAP_NAMES = { BASE_HEAP_NAME, SAVED_HEAP_NAME, PERMISSION_HEAP_NAME }; + public static final Name[] VALID_HEAP_NAMES = + { BASE_HEAP_NAME, SAVED_HEAP_NAME, PERMISSION_HEAP_NAME }; + + + // additional sorts + private final Sort fieldSort; - - //additional sorts - private final Sort fieldSort; - - //select/store + // select/store private final SortDependingFunction select; private final Function store; private final Function create; private final Function anon; private final Function memset; - - //fields + + // fields private final Function arr; private final Function created; private final Function initialized; @@ -67,147 +71,144 @@ public final class HeapLDT extends LDT { private final SortDependingFunction classInitialized; private final SortDependingFunction classInitializationInProgress; private final SortDependingFunction classErroneous; - - //length + + // length private final Function length; - - //null + + // null private final Function nullFunc; - - //predicates - private final Function wellFormed; + + // predicates + private final Function wellFormed; private final Function acc; private final Function reach; private final Function prec; - - //heap pv + + // heap pv private ImmutableList heaps; - - - - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- - + + + + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- + public HeapLDT(TermServices services) { - super(NAME, services); - final Namespace sorts = services.getNamespaces().sorts(); - final Namespace progVars = services.getNamespaces().programVariables(); - - fieldSort = (Sort) sorts.lookup(new Name("Field")); - select = addSortDependingFunction(services, SELECT_NAME.toString()); - store = addFunction(services, "store"); - create = addFunction(services, "create"); - anon = addFunction(services, "anon"); - memset = addFunction(services, "memset"); - arr = addFunction(services, "arr"); - created = addFunction(services, "java.lang.Object::"); - initialized = addFunction(services, "java.lang.Object::"); - classPrepared = addSortDependingFunction(services, ""); - classInitialized = addSortDependingFunction(services, ""); - classInitializationInProgress - = addSortDependingFunction(services, ""); - classErroneous = addSortDependingFunction(services, ""); - length = addFunction(services, "length"); - nullFunc = addFunction(services, "null"); - acc = addFunction(services, "acc"); - reach = addFunction(services, "reach"); - prec = addFunction(services, "prec"); + super(NAME, services); + final Namespace sorts = services.getNamespaces().sorts(); + final Namespace progVars = services.getNamespaces().programVariables(); + + fieldSort = (Sort) sorts.lookup(new Name("Field")); + select = addSortDependingFunction(services, SELECT_NAME.toString()); + store = addFunction(services, "store"); + create = addFunction(services, "create"); + anon = addFunction(services, "anon"); + memset = addFunction(services, "memset"); + arr = addFunction(services, "arr"); + created = addFunction(services, "java.lang.Object::"); + initialized = addFunction(services, "java.lang.Object::"); + classPrepared = addSortDependingFunction(services, ""); + classInitialized = addSortDependingFunction(services, ""); + classInitializationInProgress = + addSortDependingFunction(services, ""); + classErroneous = addSortDependingFunction(services, ""); + length = addFunction(services, "length"); + nullFunc = addFunction(services, "null"); + acc = addFunction(services, "acc"); + reach = addFunction(services, "reach"); + prec = addFunction(services, "prec"); heaps = ImmutableSLList.nil() - .append((LocationVariable) progVars.lookup(BASE_HEAP_NAME)) - .append((LocationVariable) progVars.lookup(SAVED_HEAP_NAME)); - if(services instanceof Services) { - Services s = (Services)services; - if(s.getProfile() instanceof JavaProfile) { - if(((JavaProfile)s.getProfile()).withPermissions()) { + .append((LocationVariable) progVars.lookup(BASE_HEAP_NAME)) + .append((LocationVariable) progVars.lookup(SAVED_HEAP_NAME)); + if (services instanceof Services) { + Services s = (Services) services; + if (s.getProfile() instanceof JavaProfile) { + if (((JavaProfile) s.getProfile()).withPermissions()) { heaps = heaps.append((LocationVariable) progVars.lookup(PERMISSION_HEAP_NAME)); } } } wellFormed = addFunction(services, "wellFormed"); } - - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- - + + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- + private String getFieldSymbolName(LocationVariable fieldPV) { - if(fieldPV.isImplicit()) { - return fieldPV.name().toString(); - } else { - String fieldPVName = fieldPV.name().toString(); - int index = fieldPV.toString().indexOf("::"); - assert index > 0; - return fieldPVName.substring(0, index) - + "::$" - + fieldPVName.substring(index + 2); - } - } - - - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- - + if (fieldPV.isImplicit()) { + return fieldPV.name().toString(); + } else { + String fieldPVName = fieldPV.name().toString(); + int index = fieldPV.toString().indexOf("::"); + assert index > 0; + return fieldPVName.substring(0, index) + "::$" + fieldPVName.substring(index + 2); + } + } + + + + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- + /** - * Given a constant symbol representing a field, this method returns a - * simplified name of the constant symbol to be used for pretty printing. + * Given a constant symbol representing a field, this method returns a simplified name of the + * constant symbol to be used for pretty printing. */ public static String getPrettyFieldName(Named fieldSymbol) { - String name = fieldSymbol.name().toString(); - int index = name.indexOf("::"); - if(index == -1) { - return name; - } else { - String result = name.substring(index + 2); - if(result.charAt(0) == '$') { - result = result.substring(1); - } - return result; - } - } - - + String name = fieldSymbol.name().toString(); + int index = name.indexOf("::"); + if (index == -1) { + return name; + } else { + String result = name.substring(index + 2); + if (result.charAt(0) == '$') { + result = result.substring(1); + } + return result; + } + } + + /** - * Extracts the name of the enclosing class from the name of a constant - * symbol representing a field. + * Extracts the name of the enclosing class from the name of a constant symbol representing a + * field. */ public static String getClassName(Function fieldSymbol) { - String name = fieldSymbol.name().toString(); - int index = name.indexOf("::"); - if(index == -1) { - return null; - } else { - return name.substring(0, index); - } - } - - + String name = fieldSymbol.name().toString(); + int index = name.indexOf("::"); + if (index == -1) { + return null; + } else { + return name.substring(0, index); + } + } + + /** * Returns the sort "Field". */ public Sort getFieldSort() { - return fieldSort; + return fieldSort; } - - + + /** * Returns the select function for the given sort. */ public SortDependingFunction getSelect(Sort instanceSort, TermServices services) { - return select.getInstanceFor(instanceSort, services); + return select.getInstanceFor(instanceSort, services); } - - + + /** - * If the passed operator is an instance of "select", this method returns - * the sort of the function (identical to its return type); otherwise, - * returns null. + * If the passed operator is an instance of "select", this method returns the sort of the + * function (identical to its return type); otherwise, returns null. */ public Sort getSortOfSelect(Operator op) { - if(isSelectOp(op)) { - return ((SortDependingFunction)op).getSortDependingOn(); + if (isSelectOp(op)) { + return ((SortDependingFunction) op).getSortDependingOn(); } else { return null; } @@ -215,105 +216,103 @@ public Sort getSortOfSelect(Operator op) { public boolean isSelectOp(Operator op) { return op instanceof SortDependingFunction - && ((SortDependingFunction)op).isSimilar(select); + && ((SortDependingFunction) op).isSimilar(select); } public Function getStore() { - return store; + return store; } public Function getCreate() { - return create; + return create; } - + public Function getAnon() { - return anon; - } - - + return anon; + } + + public Function getMemset() { - return memset; - } - - + return memset; + } + + public Function getArr() { - return arr; + return arr; } - - + + public Function getCreated() { - return created; + return created; } - - + + public Function getInitialized() { - return initialized; + return initialized; } - - + + public Function getClassPrepared(Sort instanceSort, TermServices services) { - return classPrepared.getInstanceFor(instanceSort, services); + return classPrepared.getInstanceFor(instanceSort, services); } - - + + public Function getClassInitialized(Sort instanceSort, TermServices services) { - return classInitialized.getInstanceFor(instanceSort, services); + return classInitialized.getInstanceFor(instanceSort, services); } - - - public Function getClassInitializationInProgress(Sort instanceSort, - TermServices services) { - return classInitializationInProgress.getInstanceFor(instanceSort, - services); + + + public Function getClassInitializationInProgress(Sort instanceSort, TermServices services) { + return classInitializationInProgress.getInstanceFor(instanceSort, services); } - - + + public Function getClassErroneous(Sort instanceSort, TermServices services) { - return classErroneous.getInstanceFor(instanceSort, services); + return classErroneous.getInstanceFor(instanceSort, services); } - - + + public Function getLength() { - return length; - } - - + return length; + } + + public Function getNull() { - return nullFunc; + return nullFunc; } - - + + public Function getWellFormed() { - return wellFormed; + return wellFormed; } - - + + public Function getAcc() { - return acc; + return acc; } - - + + public Function getReach() { - return reach; + return reach; } - + public Function getPrec() { - return prec; + return prec; } - + public LocationVariable getHeap() { - return heaps.head(); + return heaps.head(); } - + public LocationVariable getSavedHeap() { return heaps.tail().head(); } - + public ImmutableList getAllHeaps() { return heaps; } @@ -328,166 +327,144 @@ public LocationVariable getHeapForName(Name name) { } public LocationVariable getPermissionHeap() { - return heaps.size() > 2 ? heaps.tail().tail().head() : null; + return heaps.size() > 2 ? heaps.tail().tail().head() : null; } /** - * Given a "program variable" representing a field or a model field, - * returns the function symbol representing the same field. For - * normal fields (Java or ghost fields), this function symbol is a - * constant symbol of type "Field". For model fields, it is an observer - * function symbol. If the appropriate symbol does not yet exist in the - * namespace, this method creates and adds it to the namespace as a - * side effect. + * Given a "program variable" representing a field or a model field, returns the function symbol + * representing the same field. For normal fields (Java or ghost fields), this function symbol + * is a constant symbol of type "Field". For model fields, it is an observer function symbol. If + * the appropriate symbol does not yet exist in the namespace, this method creates and adds it + * to the namespace as a side effect. */ - public Function getFieldSymbolForPV(LocationVariable fieldPV, - Services services) { - assert fieldPV.isMember(); - assert fieldPV != services.getJavaInfo().getArrayLength(); - - final Name name = new Name(getFieldSymbolName(fieldPV)); - Function result = (Function) services.getNamespaces() - .functions() - .lookup(name); - if(result == null) { - int index = name.toString().indexOf("::"); - assert index > 0; - final Name kind = new Name(name.toString().substring(index + 2)); - - SortDependingFunction firstInstance - = SortDependingFunction.getFirstInstance(kind, services); - if(firstInstance != null) { - Sort sortDependingOn = fieldPV.getContainerType().getSort(); - result = firstInstance.getInstanceFor(sortDependingOn, services); - } else { - if(fieldPV.isModel()) { - int heapCount = 0; - for(LocationVariable heap : getAllHeaps()) { - if(heap == getSavedHeap()) { - continue; - } - heapCount++; - } - result = new ObserverFunction( - kind.toString(), - fieldPV.sort(), - fieldPV.getKeYJavaType(), - targetSort(), - fieldPV.getContainerType(), - fieldPV.isStatic(), - new ImmutableArray(), - heapCount, - 1); - } else { - result = new Function(name, - fieldSort, - new Sort[0], - null, - true); - } - services.getNamespaces().functions().addSafely(result); - } - } - - //sanity check - if(fieldPV.isModel()) { - assert result instanceof ObserverFunction; - } else { - assert !(result instanceof ObserverFunction); - assert result.isUnique() - : "field symbol is not unique: " + result; - } - + public Function getFieldSymbolForPV(LocationVariable fieldPV, Services services) { + assert fieldPV.isMember(); + assert fieldPV != services.getJavaInfo().getArrayLength(); + + final Name name = new Name(getFieldSymbolName(fieldPV)); + Function result = (Function) services.getNamespaces().functions().lookup(name); + if (result == null) { + int index = name.toString().indexOf("::"); + assert index > 0; + final Name kind = new Name(name.toString().substring(index + 2)); + + SortDependingFunction firstInstance = + SortDependingFunction.getFirstInstance(kind, services); + if (firstInstance != null) { + Sort sortDependingOn = fieldPV.getContainerType().getSort(); + result = firstInstance.getInstanceFor(sortDependingOn, services); + } else { + if (fieldPV.isModel()) { + int heapCount = 0; + for (LocationVariable heap : getAllHeaps()) { + if (heap == getSavedHeap()) { + continue; + } + heapCount++; + } + result = new ObserverFunction(kind.toString(), fieldPV.sort(), + fieldPV.getKeYJavaType(), targetSort(), fieldPV.getContainerType(), + fieldPV.isStatic(), new ImmutableArray(), heapCount, 1); + } else { + result = new Function(name, fieldSort, new Sort[0], null, true); + } + services.getNamespaces().functions().addSafely(result); + } + } + + // sanity check + if (fieldPV.isModel()) { + assert result instanceof ObserverFunction; + } else { + assert !(result instanceof ObserverFunction); + assert result.isUnique() : "field symbol is not unique: " + result; + } + return result; } @Override public final boolean containsFunction(Function op) { - if (super.containsFunction(op)) { - return true; - } - if (op instanceof SortDependingFunction) { - return ((SortDependingFunction) op).isSimilar(select); - } - return op.isUnique() && op.sort() == getFieldSort(); - } - + if (super.containsFunction(op)) { + return true; + } + if (op instanceof SortDependingFunction) { + return ((SortDependingFunction) op).isSimilar(select); + } + return op.isUnique() && op.sort() == getFieldSort(); + } + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return false; } @Override public Term translateLiteral(Literal lit, Services services) { - assert false; - return null; + assert false; + return null; } - + @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services serv, - ExecutionContext ec) { - assert false; - return null; + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services serv, + ExecutionContext ec) { + assert false; + return null; } - + @Override public boolean hasLiteralFunction(Function f) { - return false; + return false; } - + @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if (t.op() instanceof SortDependingFunction && - ((SortDependingFunction)t.op()).isSimilar(select)) { - ProgramVariable heap = (ProgramVariable) children.remove(0); - if (heap != getHeap()) { - throw new IllegalArgumentException("Can only translate field access to base heap."); - } - ReferencePrefix prefix = (ReferencePrefix) children.remove(0); - ProgramVariable field = (ProgramVariable) children.remove(0); - - if (prefix instanceof NullLiteral) { - return new FieldReference(field, null); - } - return new FieldReference(field, prefix); - } else if (t.sort() == getFieldSort() && t.op() instanceof Function && ((Function) t.op()).isUnique()) { - return services.getJavaInfo().getAttribute(getPrettyFieldName(t.op()), getClassName((Function) t.op())); - } - throw new IllegalArgumentException("Could not translate " + ProofSaver.printTerm(t, null) + " to program."); - } - - + if (t.op() instanceof SortDependingFunction + && ((SortDependingFunction) t.op()).isSimilar(select)) { + ProgramVariable heap = (ProgramVariable) children.remove(0); + if (heap != getHeap()) { + throw new IllegalArgumentException("Can only translate field access to base heap."); + } + ReferencePrefix prefix = (ReferencePrefix) children.remove(0); + ProgramVariable field = (ProgramVariable) children.remove(0); + + if (prefix instanceof NullLiteral) { + return new FieldReference(field, null); + } + return new FieldReference(field, prefix); + } else if (t.sort() == getFieldSort() && t.op() instanceof Function + && ((Function) t.op()).isUnique()) { + return services.getJavaInfo().getAttribute(getPrettyFieldName(t.op()), + getClassName((Function) t.op())); + } + throw new IllegalArgumentException( + "Could not translate " + ProofSaver.printTerm(t, null) + " to program."); + } + + @Override public final Type getType(Term t) { - assert false; - return null; + assert false; + return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java index 0e09a1433a5..99f7f803518 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/IntegerLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -42,28 +45,27 @@ import javax.annotation.Nullable; -/** - * This class inherits from LDT and implements all method that are - * necessary to handle integers, shorts and bytes. It caches the symbols - * declared in integerHeader.key and offers methods to convert java - * number types to their logic counterpart. +/** + * This class inherits from LDT and implements all method that are necessary to handle integers, + * shorts and bytes. It caches the symbols declared in integerHeader.key and offers methods to + * convert java number types to their logic counterpart. */ @SuppressWarnings("unused") public final class IntegerLDT extends LDT { private static final Logger LOGGER = LoggerFactory.getLogger(IntegerLDT.class); - public static final Name NAME = new Name("int"); - - //public name constants + public static final Name NAME = new Name("int"); + + // public name constants public static final String NEGATIVE_LITERAL_STRING = "neglit"; public static final Name NUMBERS_NAME = new Name("Z"); - public static final Name CHAR_ID_NAME = new Name("C"); + public static final Name CHAR_ID_NAME = new Name("C"); - //the following fields cache the symbols from integerHeader.key. - //(explanations see there) + // the following fields cache the symbols from integerHeader.key. + // (explanations see there) private final Function sharp; private final Function numberSymbol[] = new Function[10]; - private final Function neglit; + private final Function neglit; private final Function numbers; private final Function charID; private final Function add; @@ -75,8 +77,8 @@ public final class IntegerLDT extends LDT { private final Function pow; private final Function bsum; private final Function bprod; -// private final Function min; // handled by the \ifEx operator -// private final Function max; + // private final Function min; // handled by the \ifEx operator + // private final Function max; private final Function jdiv; private final Function jmod; private final Function unaryMinusJint; @@ -91,7 +93,7 @@ public final class IntegerLDT extends LDT { private final Function modJlong; private final Function divJint; private final Function divJlong; - + private final Function shiftright; private final Function shiftleft; private final Function shiftrightJint; @@ -121,7 +123,7 @@ public final class IntegerLDT extends LDT { private final Function javaAddLong; private final Function javaSubInt; private final Function javaSubLong; - private final Function javaMulInt; + private final Function javaMulInt; private final Function javaMulLong; private final Function javaMod; private final Function javaDivInt; @@ -142,9 +144,9 @@ public final class IntegerLDT extends LDT { private final Function javaCastShort; private final Function javaCastInt; private final Function javaCastLong; - private final Function javaCastChar; + private final Function javaCastChar; private final Function lessThan; - private final Function greaterThan; + private final Function greaterThan; private final Function greaterOrEquals; private final Function lessOrEquals; private final Function inByte; @@ -156,127 +158,123 @@ public final class IntegerLDT extends LDT { private final Term one; private final Term zero; - - - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + + + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- public IntegerLDT(Services services) { - super(NAME, services); + super(NAME, services); - //initialise caches for function symbols from integerHeader.key - sharp = addFunction(services, "#"); - for(int i = 0; i < 10; i++) { + // initialise caches for function symbols from integerHeader.key + sharp = addFunction(services, "#"); + for (int i = 0; i < 10; i++) { numberSymbol[i] = addFunction(services, "" + i); } - neglit = addFunction(services, NEGATIVE_LITERAL_STRING); - numbers = addFunction(services, NUMBERS_NAME.toString()); + neglit = addFunction(services, NEGATIVE_LITERAL_STRING); + numbers = addFunction(services, NUMBERS_NAME.toString()); assert sharp.sort() == numbers.argSort(0); - charID = addFunction(services, CHAR_ID_NAME.toString()); - add = addFunction(services, "add"); - neg = addFunction(services, "neg"); - sub = addFunction(services, "sub"); - mul = addFunction(services, "mul"); - div = addFunction(services, "div"); - mod = addFunction(services, "mod"); - bsum = addFunction(services, "bsum"); - bprod = addFunction(services, "bprod"); - jdiv = addFunction(services, "jdiv"); - jmod = addFunction(services, "jmod"); - pow = addFunction(services, "pow"); - unaryMinusJint = addFunction(services, "unaryMinusJint"); - unaryMinusJlong = addFunction(services, "unaryMinusJlong"); - addJint = addFunction(services, "addJint"); - addJlong = addFunction(services, "addJlong"); - subJint = addFunction(services, "subJint"); - subJlong = addFunction(services, "subJlong"); - mulJint = addFunction(services, "mulJint"); - mulJlong = addFunction(services, "mulJlong"); - modJint = addFunction(services, "modJint"); - modJlong = addFunction(services, "modJlong"); - divJint = addFunction(services, "divJint"); - divJlong = addFunction(services, "divJlong"); - - shiftright = addFunction(services, "shiftright"); - shiftleft = addFunction(services, "shiftleft"); - shiftrightJint = addFunction(services, "shiftrightJint"); - shiftrightJlong = addFunction(services, "shiftrightJlong"); - shiftleftJint = addFunction(services, "shiftleftJint"); - shiftleftJlong = addFunction(services, "shiftleftJlong"); - unsignedshiftrightJint - = addFunction(services, "unsignedshiftrightJint"); - unsignedshiftrightJlong - = addFunction(services, "unsignedshiftrightJlong"); - binaryOr = addFunction(services, "binaryOr"); - binaryAnd = addFunction(services, "binaryAnd"); - binaryXOr = addFunction(services, "binaryXOr"); - orJint = addFunction(services, "orJint"); - orJlong = addFunction(services, "orJlong"); - andJint = addFunction(services, "andJint"); - andJlong = addFunction(services, "andJlong"); - xorJint = addFunction(services, "xorJint"); - xorJlong = addFunction(services, "xorJlong"); - moduloByte = addFunction(services, "moduloByte"); - moduloShort = addFunction(services, "moduloShort"); - moduloInt = addFunction(services, "moduloInt"); - moduloLong = addFunction(services, "moduloLong"); - moduloChar = addFunction(services, "moduloChar"); - javaUnaryMinusInt = addFunction(services, "javaUnaryMinusInt"); - javaUnaryMinusLong = addFunction(services, "javaUnaryMinusLong"); + charID = addFunction(services, CHAR_ID_NAME.toString()); + add = addFunction(services, "add"); + neg = addFunction(services, "neg"); + sub = addFunction(services, "sub"); + mul = addFunction(services, "mul"); + div = addFunction(services, "div"); + mod = addFunction(services, "mod"); + bsum = addFunction(services, "bsum"); + bprod = addFunction(services, "bprod"); + jdiv = addFunction(services, "jdiv"); + jmod = addFunction(services, "jmod"); + pow = addFunction(services, "pow"); + unaryMinusJint = addFunction(services, "unaryMinusJint"); + unaryMinusJlong = addFunction(services, "unaryMinusJlong"); + addJint = addFunction(services, "addJint"); + addJlong = addFunction(services, "addJlong"); + subJint = addFunction(services, "subJint"); + subJlong = addFunction(services, "subJlong"); + mulJint = addFunction(services, "mulJint"); + mulJlong = addFunction(services, "mulJlong"); + modJint = addFunction(services, "modJint"); + modJlong = addFunction(services, "modJlong"); + divJint = addFunction(services, "divJint"); + divJlong = addFunction(services, "divJlong"); + + shiftright = addFunction(services, "shiftright"); + shiftleft = addFunction(services, "shiftleft"); + shiftrightJint = addFunction(services, "shiftrightJint"); + shiftrightJlong = addFunction(services, "shiftrightJlong"); + shiftleftJint = addFunction(services, "shiftleftJint"); + shiftleftJlong = addFunction(services, "shiftleftJlong"); + unsignedshiftrightJint = addFunction(services, "unsignedshiftrightJint"); + unsignedshiftrightJlong = addFunction(services, "unsignedshiftrightJlong"); + binaryOr = addFunction(services, "binaryOr"); + binaryAnd = addFunction(services, "binaryAnd"); + binaryXOr = addFunction(services, "binaryXOr"); + orJint = addFunction(services, "orJint"); + orJlong = addFunction(services, "orJlong"); + andJint = addFunction(services, "andJint"); + andJlong = addFunction(services, "andJlong"); + xorJint = addFunction(services, "xorJint"); + xorJlong = addFunction(services, "xorJlong"); + moduloByte = addFunction(services, "moduloByte"); + moduloShort = addFunction(services, "moduloShort"); + moduloInt = addFunction(services, "moduloInt"); + moduloLong = addFunction(services, "moduloLong"); + moduloChar = addFunction(services, "moduloChar"); + javaUnaryMinusInt = addFunction(services, "javaUnaryMinusInt"); + javaUnaryMinusLong = addFunction(services, "javaUnaryMinusLong"); javaBitwiseNegation = addFunction(services, "javaBitwiseNegation"); - javaAddInt = addFunction(services, "javaAddInt"); - javaAddLong = addFunction(services, "javaAddLong"); - javaSubInt = addFunction(services, "javaSubInt"); - javaSubLong = addFunction(services, "javaSubLong"); - javaMulInt = addFunction(services, "javaMulInt"); - javaMulLong = addFunction(services, "javaMulLong"); - javaMod = addFunction(services, "javaMod"); - javaDivInt = addFunction(services, "javaDivInt"); - javaDivLong = addFunction(services, "javaDivLong"); - javaShiftRightInt = addFunction(services, "javaShiftRightInt"); - javaShiftRightLong = addFunction(services, "javaShiftRightLong"); - javaShiftLeftInt = addFunction(services, "javaShiftLeftInt"); - javaShiftLeftLong = addFunction(services, "javaShiftLeftLong"); - javaUnsignedShiftRightInt - = addFunction(services, "javaUnsignedShiftRightInt"); - javaUnsignedShiftRightLong - = addFunction(services, "javaUnsignedShiftRightLong"); - javaBitwiseOrInt = addFunction(services, "javaBitwiseOrInt"); - javaBitwiseOrLong = addFunction(services, "javaBitwiseOrLong"); - javaBitwiseAndInt = addFunction(services, "javaBitwiseAndInt"); - javaBitwiseAndLong = addFunction(services, "javaBitwiseAndLong"); - javaBitwiseXOrInt = addFunction(services, "javaBitwiseXOrInt"); - javaBitwiseXOrLong = addFunction(services, "javaBitwiseXOrLong"); - javaCastByte = addFunction(services, "javaCastByte"); - javaCastShort = addFunction(services, "javaCastShort"); - javaCastInt = addFunction(services, "javaCastInt"); - javaCastLong = addFunction(services, "javaCastLong"); - javaCastChar = addFunction(services, "javaCastChar"); - lessThan = addFunction(services, "lt"); - greaterThan = addFunction(services, "gt"); - greaterOrEquals = addFunction(services, "geq"); - lessOrEquals = addFunction(services, "leq"); - inByte = addFunction(services, "inByte"); - inShort = addFunction(services, "inShort"); - inInt = addFunction(services, "inInt"); - inLong = addFunction(services, "inLong"); - inChar = addFunction(services, "inChar"); - index = addFunction(services, "index"); - - //cache often used constants + javaAddInt = addFunction(services, "javaAddInt"); + javaAddLong = addFunction(services, "javaAddLong"); + javaSubInt = addFunction(services, "javaSubInt"); + javaSubLong = addFunction(services, "javaSubLong"); + javaMulInt = addFunction(services, "javaMulInt"); + javaMulLong = addFunction(services, "javaMulLong"); + javaMod = addFunction(services, "javaMod"); + javaDivInt = addFunction(services, "javaDivInt"); + javaDivLong = addFunction(services, "javaDivLong"); + javaShiftRightInt = addFunction(services, "javaShiftRightInt"); + javaShiftRightLong = addFunction(services, "javaShiftRightLong"); + javaShiftLeftInt = addFunction(services, "javaShiftLeftInt"); + javaShiftLeftLong = addFunction(services, "javaShiftLeftLong"); + javaUnsignedShiftRightInt = addFunction(services, "javaUnsignedShiftRightInt"); + javaUnsignedShiftRightLong = addFunction(services, "javaUnsignedShiftRightLong"); + javaBitwiseOrInt = addFunction(services, "javaBitwiseOrInt"); + javaBitwiseOrLong = addFunction(services, "javaBitwiseOrLong"); + javaBitwiseAndInt = addFunction(services, "javaBitwiseAndInt"); + javaBitwiseAndLong = addFunction(services, "javaBitwiseAndLong"); + javaBitwiseXOrInt = addFunction(services, "javaBitwiseXOrInt"); + javaBitwiseXOrLong = addFunction(services, "javaBitwiseXOrLong"); + javaCastByte = addFunction(services, "javaCastByte"); + javaCastShort = addFunction(services, "javaCastShort"); + javaCastInt = addFunction(services, "javaCastInt"); + javaCastLong = addFunction(services, "javaCastLong"); + javaCastChar = addFunction(services, "javaCastChar"); + lessThan = addFunction(services, "lt"); + greaterThan = addFunction(services, "gt"); + greaterOrEquals = addFunction(services, "geq"); + lessOrEquals = addFunction(services, "leq"); + inByte = addFunction(services, "inByte"); + inShort = addFunction(services, "inShort"); + inInt = addFunction(services, "inInt"); + inLong = addFunction(services, "inLong"); + inChar = addFunction(services, "inChar"); + index = addFunction(services, "index"); + + // cache often used constants zero = makeDigit(0, services.getTermBuilder()); one = makeDigit(1, services.getTermBuilder()); } - - - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- + + + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- private boolean isNumberLiteral(Operator f) { String n = f.name().toString(); - if(n.length() == 1) { + if (n.length() == 1) { char c = n.charAt(0); return '0' <= c && c <= '9'; } @@ -284,162 +282,164 @@ private boolean isNumberLiteral(Operator f) { } private Term makeDigit(int digit, TermBuilder tb) { - return tb.func(getNumberSymbol(), tb.func(getNumberLiteralFor(digit), - tb.func(getNumberTerminator()))); - } - - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- - + return tb.func(getNumberSymbol(), + tb.func(getNumberLiteralFor(digit), tb.func(getNumberTerminator()))); + } + + + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- + public Function getNumberTerminator() { return sharp; } - - + + public Function getNumberLiteralFor(int number) { if (number < 0 || number > 9) { - throw new IllegalArgumentException - ("Number literal symbols range from 0 to 9. Requested was:" + number); + throw new IllegalArgumentException( + "Number literal symbols range from 0 to 9. Requested was:" + number); } - + return numberSymbol[number]; } - - + + public Function getNegativeNumberSign() { return neglit; - } - - + } + + public Function getNumberSymbol() { return numbers; } - - + + public Function getCharSymbol() { return charID; } - - + + public Function getAdd() { return add; } - - + + public Function getNeg() { return neg; - } - - + } + + public Function getSub() { return sub; } - - + + public Function getMul() { return mul; } - - + + public Function getDiv() { return div; } - - + + public Function getMod() { return mod; } - - + + public Function getPow() { - return pow; + return pow; } - - + + public Function getBsum() { - return bsum; - } - + return bsum; + } + public Function getBprod() { - return bprod; + return bprod; } - + public Function getLessThan() { return lessThan; } - - + + public Function getGreaterThan() { return greaterThan; } - - + + public Function getGreaterOrEquals() { return greaterOrEquals; } - - + + public Function getLessOrEquals() { return lessOrEquals; - } - - /** Placeholder for the loop index variable in an enhanced for loop over arrays. - * Follows the proposal by David Cok to adapt JML to Java5. + } + + /** + * Placeholder for the loop index variable in an enhanced for loop over arrays. Follows the + * proposal by David Cok to adapt JML to Java5. + * * @return */ - public Function getIndex(){ - return index; + public Function getIndex() { + return index; } - - + + public Function getInBounds(Type t) { - if(t == PrimitiveType.JAVA_BYTE) { - return inByte; - } else if(t == PrimitiveType.JAVA_CHAR) { - return inChar; - } else if(t == PrimitiveType.JAVA_INT) { - return inInt; - } else if(t == PrimitiveType.JAVA_LONG) { - return inLong; - } else if(t == PrimitiveType.JAVA_SHORT) { - return inShort; - } else { - return null; - } - } - - + if (t == PrimitiveType.JAVA_BYTE) { + return inByte; + } else if (t == PrimitiveType.JAVA_CHAR) { + return inChar; + } else if (t == PrimitiveType.JAVA_INT) { + return inInt; + } else if (t == PrimitiveType.JAVA_LONG) { + return inLong; + } else if (t == PrimitiveType.JAVA_SHORT) { + return inShort; + } else { + return null; + } + } + + public Function getJavaCast(Type t) { - if(t == PrimitiveType.JAVA_BYTE) { - return javaCastByte; - } else if(t == PrimitiveType.JAVA_CHAR) { - return javaCastChar; - } else if(t == PrimitiveType.JAVA_INT) { - return javaCastInt; - } else if(t == PrimitiveType.JAVA_LONG) { - return javaCastLong; - } else if(t == PrimitiveType.JAVA_SHORT) { - return javaCastShort; - } else { - return null; - } - } - - - - /** returns the function symbol for the given operation - * null if no function is found for the given operator - * @return the function symbol for the given operation - */ + if (t == PrimitiveType.JAVA_BYTE) { + return javaCastByte; + } else if (t == PrimitiveType.JAVA_CHAR) { + return javaCastChar; + } else if (t == PrimitiveType.JAVA_INT) { + return javaCastInt; + } else if (t == PrimitiveType.JAVA_LONG) { + return javaCastLong; + } else if (t == PrimitiveType.JAVA_SHORT) { + return javaCastShort; + } else { + return null; + } + } + + + + /** + * returns the function symbol for the given operation null if no function is found for the + * given operator + * + * @return the function symbol for the given operation + */ @Override - public Function getFunctionFor( - de.uka.ilkd.key.java.expression.Operator op, - Services serv, - ExecutionContext ec) { + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services serv, + ExecutionContext ec) { final Type opReturnType = op.getKeYJavaType(serv, ec).getJavaType(); - final boolean isLong = opReturnType == PrimitiveType.JAVA_LONG; + final boolean isLong = opReturnType == PrimitiveType.JAVA_LONG; final boolean isBigint = opReturnType == PrimitiveType.JAVA_BIGINT; if (op instanceof GreaterThan) { @@ -464,9 +464,8 @@ public Function getFunctionFor( return isLong ? getJavaShiftLeftLong() : getJavaShiftLeftInt(); } else if (op instanceof ShiftRight) { return isLong ? getJavaShiftRightLong() : getJavaShiftRightInt(); - } else if (op instanceof UnsignedShiftRight) { - return isLong ? getJavaUnsignedShiftRightLong() - : getJavaUnsignedShiftRightInt(); + } else if (op instanceof UnsignedShiftRight) { + return isLong ? getJavaUnsignedShiftRightLong() : getJavaUnsignedShiftRightInt(); } else if (op instanceof BinaryAnd) { return isLong ? getJavaBitwiseAndLong() : getJavaBitwiseAndInt(); } else if (op instanceof BinaryNot) { @@ -476,7 +475,8 @@ public Function getFunctionFor( } else if (op instanceof BinaryXOr) { return isLong ? getJavaBitwiseOrLong() : getJavaBitwiseXOrInt(); } else if (op instanceof Negative) { - return isLong ? getJavaUnaryMinusLong() : (isBigint ? getNegativeNumberSign() : getJavaUnaryMinusInt()); + return isLong ? getJavaUnaryMinusLong() + : (isBigint ? getNegativeNumberSign() : getJavaUnaryMinusInt()); } else if (op instanceof TypeCast) { return getJavaCast(opReturnType); } else { @@ -486,45 +486,36 @@ public Function getFunctionFor( @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { if (subs.length == 1) { return isResponsible(op, subs[0], services, ec); } else if (subs.length == 2) { - return isResponsible(op, subs[0], subs[1], services, ec); + return isResponsible(op, subs[0], subs[1], services, ec); } - return false; + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - if(left != null - && left.sort().extendsTrans(targetSort()) - && right != null - && right.sort().extendsTrans(targetSort())) { - if(getFunctionFor(op, services, ec) != null) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + if (left != null && left.sort().extendsTrans(targetSort()) && right != null + && right.sort().extendsTrans(targetSort())) { + if (getFunctionFor(op, services, ec) != null) { return true; } } return false; } - - + + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - if(sub != null && sub.sort().extendsTrans(targetSort())) { - if(op instanceof Negative) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + if (sub != null && sub.sort().extendsTrans(targetSort())) { + if (op instanceof Negative) { return true; } } @@ -534,7 +525,7 @@ public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, @Override public Term translateLiteral(Literal lit, Services services) { Debug.assertTrue(lit instanceof AbstractIntegerLiteral, - "Literal '" + lit + "' is not an integer literal."); + "Literal '" + lit + "' is not an integer literal."); Term result; if (lit instanceof CharLiteral) { @@ -549,7 +540,7 @@ public Term translateLiteral(Literal lit, Services services) { @Override public boolean hasLiteralFunction(Function f) { - return containsFunction(f) && (f.arity()==0 || isNumberLiteral(f)); + return containsFunction(f) && (f.arity() == 0 || isNumberLiteral(f)); } public String toNumberString(Term t) { @@ -562,8 +553,7 @@ public String toNumberString(Term t) { } if (f != sharp) { - throw new RuntimeException( - "IntegerLDT: This is not a numeral literal: " + t); + throw new RuntimeException("IntegerLDT: This is not a numeral literal: " + t); } return sb.toString(); @@ -571,105 +561,93 @@ public String toNumberString(Term t) { @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if(!containsFunction((Function) t.op())) { + if (!containsFunction((Function) t.op())) { return null; } - Function f = (Function)t.op(); - if(isNumberLiteral(f) || f == numbers || f == charID) { + Function f = (Function) t.op(); + if (isNumberLiteral(f) || f == numbers || f == charID) { Term it = t; if (f == charID || f == numbers) { - it = it.sub(0); + it = it.sub(0); } - return new IntLiteral(toNumberString(it)); // TODO: what if number too large for int? + return new IntLiteral(toNumberString(it)); // TODO: what if number too large for int? } - throw new RuntimeException("IntegerLDT: Cannot convert term to program: " - +t); + throw new RuntimeException("IntegerLDT: Cannot convert term to program: " + t); } - - + + @Override public final Type getType(Term t) { - Operator op = t.op(); - if(op == javaUnaryMinusInt - || op == javaAddInt - || op == javaSubInt - || op == javaMulInt - || op == javaDivInt - || op == javaShiftRightInt - || op == javaShiftLeftInt - || op == javaUnsignedShiftRightInt - || op == javaBitwiseOrInt - || op == javaBitwiseAndInt - || op == javaBitwiseXOrInt) { - return PrimitiveType.JAVA_INT; - } else if(op == javaUnaryMinusLong - || op == javaAddLong - || op == javaSubLong - || op == javaMulLong - || op == javaDivLong - || op == javaShiftRightLong - || op == javaShiftLeftLong - || op == javaUnsignedShiftRightLong - || op == javaBitwiseOrLong - || op == javaBitwiseAndLong - || op == javaBitwiseXOrLong) { - return PrimitiveType.JAVA_LONG; - } else if(op == javaBitwiseNegation || op == javaMod) { - return getType(t.sub(0)); - } else if(op == javaCastByte) { - return PrimitiveType.JAVA_BYTE; - } else if(op == javaCastShort) { - return PrimitiveType.JAVA_SHORT; - } else if(op == javaCastInt) { - return PrimitiveType.JAVA_INT; - } else if(op == javaCastLong) { - return PrimitiveType.JAVA_LONG; - } else if(op == javaCastChar) { - return PrimitiveType.JAVA_CHAR; - } else { - assert false : "IntegerLDT: Cannot get Java type for term: " + t; - return null; - } - } - - - - /** - * returns the function symbol used to represent java-like division of - * the arithmetical integers + Operator op = t.op(); + if (op == javaUnaryMinusInt || op == javaAddInt || op == javaSubInt || op == javaMulInt + || op == javaDivInt || op == javaShiftRightInt || op == javaShiftLeftInt + || op == javaUnsignedShiftRightInt || op == javaBitwiseOrInt + || op == javaBitwiseAndInt || op == javaBitwiseXOrInt) { + return PrimitiveType.JAVA_INT; + } else if (op == javaUnaryMinusLong || op == javaAddLong || op == javaSubLong + || op == javaMulLong || op == javaDivLong || op == javaShiftRightLong + || op == javaShiftLeftLong || op == javaUnsignedShiftRightLong + || op == javaBitwiseOrLong || op == javaBitwiseAndLong + || op == javaBitwiseXOrLong) { + return PrimitiveType.JAVA_LONG; + } else if (op == javaBitwiseNegation || op == javaMod) { + return getType(t.sub(0)); + } else if (op == javaCastByte) { + return PrimitiveType.JAVA_BYTE; + } else if (op == javaCastShort) { + return PrimitiveType.JAVA_SHORT; + } else if (op == javaCastInt) { + return PrimitiveType.JAVA_INT; + } else if (op == javaCastLong) { + return PrimitiveType.JAVA_LONG; + } else if (op == javaCastChar) { + return PrimitiveType.JAVA_CHAR; + } else { + assert false : "IntegerLDT: Cannot get Java type for term: " + t; + return null; + } + } + + + + /** + * returns the function symbol used to represent java-like division of the arithmetical integers + * * @return the function symbol used to represent integer division */ public Function getJDivision() { return jdiv; } - + /** - * returns the function symbol used to represent the modulo operation of - * the arithmetical integers - * @return the function symbol used to represent the integer modulo operation + * returns the function symbol used to represent the modulo operation of the arithmetical + * integers + * + * @return the function symbol used to represent the integer modulo operation */ - public Function getArithModulo() { + public Function getArithModulo() { return mod; } /** - * returns the function symbol used to represent the java-like modulo operation of - * the arithmetical integers - * @return the function symbol used to represent the integer modulo operation + * returns the function symbol used to represent the java-like modulo operation of the + * arithmetical integers + * + * @return the function symbol used to represent the integer modulo operation */ - public Function getJModulo() { + public Function getJModulo() { return jmod; } - /** returns a function mapping an arithmetic integer to its Java long representation */ - public Function getModuloLong() { + /** returns a function mapping an arithmetic integer to its Java long representation */ + public Function getModuloLong() { return modJlong; } /** maps an integer back into long range */ - public Function getArithModuloLong() { + public Function getArithModuloLong() { return modJlong; } @@ -694,33 +672,33 @@ public Function getArithModuloChar() { } /** - * returns the function symbol interpreted as the Java addition on - * int (or promotabel to int) operators, i.e. this addition performs a modulo - * operation wrt. to the range of type int. This function is independent - * of the chosen integer semantics. - * - * In case you want to represent the Java addition on operands promotable to int - * which shall be interpreted by the chosen integer semantics use + * returns the function symbol interpreted as the Java addition on int (or promotabel to int) + * operators, i.e. this addition performs a modulo operation wrt. to the range of type + * int. This function is independent of the chosen integer semantics. + * + * In case you want to represent the Java addition on operands promotable to int + * which shall be interpreted by the chosen integer semantics use * {@link IntegerLDT#getJavaAddInt()} instead - * - * @return mathematical interpreted function realising the Java addition on operands of or promotable - * to type int + * + * @return mathematical interpreted function realising the Java addition on operands of or + * promotable to type int */ - public Function getArithJavaIntAddition() { + public Function getArithJavaIntAddition() { return addJint; } - - - /** + + + /** * returns the function symbol representing the bitwise-or for Java int */ public Function getBitwiseOrJavaInt() { return orJint; } - + /** - * the function representing the Java operator when one of the - * operators is an or can be promoted to an int + * the function representing the Java operator when one of the operators is an or can be + * promoted to an int + * * @return function representing the generic Java operator function */ public Function getJavaAddInt() { @@ -729,8 +707,8 @@ public Function getJavaAddInt() { /** - * the function representing the Java operator when one of the - * operators is of type long + * the function representing the Java operator when one of the operators is of type long + * * @return function representing the generic Java operator function */ public Function getJavaAddLong() { @@ -738,8 +716,9 @@ public Function getJavaAddLong() { } /** - * the function representing the Java operator when one of the - * operators is an or can be promoted to int + * the function representing the Java operator when one of the operators is an or can be + * promoted to int + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseAndInt() { @@ -747,8 +726,8 @@ public Function getJavaBitwiseAndInt() { } /** - * the function representing the Java operator when one of the - * operators is of type long + * the function representing the Java operator when one of the operators is of type long + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseAndLong() { @@ -757,6 +736,7 @@ public Function getJavaBitwiseAndLong() { /** * the function representing the Java operator ~ + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseNegation() { @@ -764,18 +744,20 @@ public Function getJavaBitwiseNegation() { } /** - * the function representing the Java operator | - * when one of the operands is an or can be promoted to int + * the function representing the Java operator | when one of the operands is an or + * can be promoted to int + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseOrInt() { return javaBitwiseOrInt; } - + /** - * the function representing the Java operator | - * when one of the operands is of type long + * the function representing the Java operator | when one of the operands is of + * type long + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseOrLong() { @@ -783,8 +765,9 @@ public Function getJavaBitwiseOrLong() { } /** - * the function representing the Java operator ^ - * when one of the operands is an or can be promoted to int + * the function representing the Java operator ^ when one of the operands is an or + * can be promoted to int + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseXOrInt() { @@ -793,8 +776,9 @@ public Function getJavaBitwiseXOrInt() { /** - * the function representing the Java operator ^ - * when one of the operands is exact of type long + * the function representing the Java operator ^ when one of the operands is exact + * of type long + * * @return function representing the generic Java operator function */ public Function getJavaBitwiseXOrLong() { @@ -802,7 +786,8 @@ public Function getJavaBitwiseXOrLong() { } /** - * the function representing the Java operator (byte) + * the function representing the Java operator (byte) + * * @return function representing the generic Java operator function */ public Function getJavaCastByte() { @@ -810,7 +795,8 @@ public Function getJavaCastByte() { } /** - * the function representing the Java operator (char) + * the function representing the Java operator (char) + * * @return function representing the generic Java operator function */ public Function getJavaCastChar() { @@ -819,7 +805,8 @@ public Function getJavaCastChar() { /** - * the function representing the Java operator (int) + * the function representing the Java operator (int) + * * @return function representing the generic Java operator function */ public Function getJavaCastInt() { @@ -827,7 +814,8 @@ public Function getJavaCastInt() { } /** - * the function representing the Java operator (long) + * the function representing the Java operator (long) + * * @return function representing the generic Java operator function */ public Function getJavaCastLong() { @@ -835,7 +823,8 @@ public Function getJavaCastLong() { } /** - * the function representing the Java operator (short) + * the function representing the Java operator (short) + * * @return function representing the generic Java operator function */ public Function getJavaCastShort() { @@ -843,8 +832,9 @@ public Function getJavaCastShort() { } /** - * the function representing the Java operator / - * when one of the operands is an or a subtype of int + * the function representing the Java operator / when one of the operands is an or + * a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaDivInt() { @@ -852,8 +842,9 @@ public Function getJavaDivInt() { } /** - * the function representing the Java operator / - * when one of the operands is exact of type long + * the function representing the Java operator / when one of the operands is exact + * of type long + * * @return function representing the generic Java operator function */ public Function getJavaDivLong() { @@ -862,8 +853,9 @@ public Function getJavaDivLong() { /** - * the function representing the Java operator % - * when one of the operands is an or a subtype of int + * the function representing the Java operator % when one of the operands is an or + * a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaMod() { @@ -872,8 +864,9 @@ public Function getJavaMod() { /** - * the function representing the Java operator * - * when one of the operands is an or a subtype of int + * the function representing the Java operator * when one of the operands is an or + * a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaMulInt() { @@ -882,8 +875,9 @@ public Function getJavaMulInt() { /** - * the function representing the Java operator * - * when one of the operands is exact of type long + * the function representing the Java operator * when one of the operands is exact + * of type long + * * @return function representing the generic Java operator function */ public Function getJavaMulLong() { @@ -892,8 +886,9 @@ public Function getJavaMulLong() { /** - * the function representing the Java operator << - * when one of the operands is an or a subtype of int + * the function representing the Java operator << when one of the operands is + * an or a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaShiftLeftInt() { @@ -902,8 +897,9 @@ public Function getJavaShiftLeftInt() { /** - * the function representing the Java operator << - * when one of the operands is exact of type long + * the function representing the Java operator << when one of the operands is + * exact of type long + * * @return function representing the generic Java operator function */ public Function getJavaShiftLeftLong() { @@ -912,8 +908,9 @@ public Function getJavaShiftLeftLong() { /** - * the function representing the Java operator >> - * when one of the operands is an or a subtype of int + * the function representing the Java operator >> when one of the operands is + * an or a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaShiftRightInt() { @@ -921,8 +918,9 @@ public Function getJavaShiftRightInt() { } /** - * the function representing the Java operator >> - * when one of the operands is exact of type long + * the function representing the Java operator >> when one of the operands is + * exact of type long + * * @return function representing the generic Java operator function */ public Function getJavaShiftRightLong() { @@ -930,8 +928,9 @@ public Function getJavaShiftRightLong() { } /** - * the function representing the Java operator - - * when one of the operands is an or a subtype of int + * the function representing the Java operator - when one of the operands is an or + * a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaSubInt() { @@ -939,8 +938,9 @@ public Function getJavaSubInt() { } /** - * the function representing the Java operator - - * when one of the operands is exact of type long + * the function representing the Java operator - when one of the operands is exact + * of type long + * * @return function representing the generic Java operator function */ public Function getJavaSubLong() { @@ -949,8 +949,9 @@ public Function getJavaSubLong() { /** - * the function representing the Java operator -expr - * when one of the operands is an or a subtype of int + * the function representing the Java operator -expr when one of the operands is an + * or a subtype of int + * * @return function representing the generic Java operator function */ public Function getJavaUnaryMinusInt() { @@ -958,8 +959,9 @@ public Function getJavaUnaryMinusInt() { } /** - * the function representing the Java operator -exprLong - * when one of the operands is exact of type long + * the function representing the Java operator -exprLong when one of the operands + * is exact of type long + * * @return function representing the generic Java operator function */ public Function getJavaUnaryMinusLong() { @@ -968,29 +970,31 @@ public Function getJavaUnaryMinusLong() { /** - * the function representing the Java operator >>> - * when one of the operands is an or a subtype of int + * the function representing the Java operator >>> when one of the + * operands is an or a subtype of int + * * @return function representing the generic Java operator function - */ + */ public Function getJavaUnsignedShiftRightInt() { return javaUnsignedShiftRightInt; } /** - * the function representing the Java operator >>> - * when one of the operands is exact of type long + * the function representing the Java operator >>> when one of the + * operands is exact of type long + * * @return function representing the generic Java operator function - */ + */ public Function getJavaUnsignedShiftRightLong() { return javaUnsignedShiftRightLong; } - - public Term zero() { - return zero; + + public Term zero() { + return zero; } - public Term one() { - return one; + public Term one() { + return one; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java index dcd33387b16..63c2054002e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import java.util.Collection; @@ -25,103 +28,104 @@ import javax.annotation.Nullable; /** - * An "LDT" or "language data type" class corresponds to a standard rule file - * shipped with KeY. Usually, this rule file declares a sort (such as "int") - * and a number of operators. The LDT class provides a programming interface to - * access these entities, and it assists the type converter in handling them. + * An "LDT" or "language data type" class corresponds to a standard rule file shipped with KeY. + * Usually, this rule file declares a sort (such as "int") and a number of operators. The LDT class + * provides a programming interface to access these entities, and it assists the type converter in + * handling them. */ public abstract class LDT implements Named { - + private final Name name; - + /** the main sort associated with the LDT */ - private final Sort sort; - + private final Sort sort; + /** the namespace of functions this LDT feels responsible for */ private final Namespace functions = new Namespace<>(); - - //------------------------------------------------------------------------- + + // ------------------------------------------------------------------------- // constructors - //------------------------------------------------------------------------- - + // ------------------------------------------------------------------------- + protected LDT(Name name, TermServices services) { sort = (Sort) services.getNamespaces().sorts().lookup(name); - if (sort == null) - throw new RuntimeException("LDT "+name+" not found.\n"+ - "It seems that there are definitions missing from the .key files."); + if (sort == null) + throw new RuntimeException("LDT " + name + " not found.\n" + + "It seems that there are definitions missing from the .key files."); this.name = name; } - + protected LDT(Name name, Sort targetSort, TermServices services) { sort = targetSort; if (sort == null) - throw new RuntimeException("LDT "+name+" not found.\n"+ - "It seems that there are definitions missing from the .key files."); + throw new RuntimeException("LDT " + name + " not found.\n" + + "It seems that there are definitions missing from the .key files."); this.name = name; } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- // protected methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** - * adds a function to the LDT + * adds a function to the LDT + * * @return the added function (for convenience reasons) */ protected final Function addFunction(Function f) { - functions.addSafely(f); - return f; + functions.addSafely(f); + return f; } - + /** - * looks up a function in the namespace and adds it to the LDT + * looks up a function in the namespace and adds it to the LDT + * * @param funcName the String with the name of the function to look up * @return the added function (for convenience reasons) */ protected final Function addFunction(TermServices services, String funcName) { - final Namespace funcNS = services.getNamespaces().functions(); - final Function f = (Function)funcNS.lookup(new Name(funcName)); + final Namespace funcNS = services.getNamespaces().functions(); + final Function f = (Function) funcNS.lookup(new Name(funcName)); if (f == null) - throw new RuntimeException("LDT: Function " + funcName + " not found.\n" + - "It seems that there are definitions missing from the .key files."); + throw new RuntimeException("LDT: Function " + funcName + " not found.\n" + + "It seems that there are definitions missing from the .key files."); return addFunction(f); } - - protected final SortDependingFunction addSortDependingFunction( - TermServices services, - String kind) { - final SortDependingFunction f - = SortDependingFunction.getFirstInstance(new Name(kind), - services); - assert f != null : "LDT: Sort depending function " - + kind + " not found"; - addFunction(f); - return f; + + protected final SortDependingFunction addSortDependingFunction(TermServices services, + String kind) { + final SortDependingFunction f = + SortDependingFunction.getFirstInstance(new Name(kind), services); + assert f != null : "LDT: Sort depending function " + kind + " not found"; + addFunction(f); + return f; } - /** returns the basic functions of the model + /** + * returns the basic functions of the model + * * @return the basic functions of the model */ protected final Namespace functions() { - return functions; + return functions; } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- // public methods - //------------------------------------------------------------------------- - + // ------------------------------------------------------------------------- + /* - * Use this method to instantiate all LDTs. It returns a map that takes - * as input the name of an LDT and returns an instance of the corresponding LDT. - * + * Use this method to instantiate all LDTs. It returns a map that takes as input the name of an + * LDT and returns an instance of the corresponding LDT. + * * Is it possible to implement LDTs as singletons? (Kai Wallisch 04/2014) */ public static Map getNewLDTInstances(Services s) { - + // TreeMap ensures the map is sorted according to the natural order of its keys. Map ret = new TreeMap(); - + ret.put(IntegerLDT.NAME, new IntegerLDT(s)); ret.put(BooleanLDT.NAME, new BooleanLDT(s)); ret.put(LocSetLDT.NAME, new LocSetLDT(s)); @@ -134,129 +138,118 @@ public static Map getNewLDTInstances(Services s) { ret.put(DoubleLDT.NAME, new DoubleLDT(s)); ret.put(RealLDT.NAME, new RealLDT(s)); ret.put(CharListLDT.NAME, new CharListLDT(s)); - + return ret; } @Override public final Name name() { - return name; + return name; } @Override public final String toString() { - return "LDT "+name()+" ("+targetSort() + ")"; + return "LDT " + name() + " (" + targetSort() + ")"; } - - /** + + /** * Returns the sort associated with the LDT. */ public final Sort targetSort() { - return sort; + return sort; } - + public boolean containsFunction(Function op) { - Named n=functions.lookup(op.name()); - return (n==op); + Named n = functions.lookup(op.name()); + return (n == op); } - - //------------------------------------------------------------------------- + + // ------------------------------------------------------------------------- // abstract methods - //------------------------------------------------------------------------- - - /** returns true if the LDT offers an operation for the given java - * operator and the logic subterms - * @param op the de.uka.ilkd.key.java.expression.Operator to - * translate + // ------------------------------------------------------------------------- + + /** + * returns true if the LDT offers an operation for the given java operator and the logic + * subterms + * + * @param op the de.uka.ilkd.key.java.expression.Operator to translate * @param subs the logic subterms of the java operator * @param services the Services * @param ec the ExecutionContext in which the expression is evaluated - * @return true if the LDT offers an operation for the given java - * operator and the subterms + * @return true if the LDT offers an operation for the given java operator and the subterms */ - public abstract boolean isResponsible( - de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec); - - - /** returns true if the LDT offers an operation for the given - * binary java operator and the logic subterms - * @param op the de.uka.ilkd.key.java.expression.Operator to - * translate + public abstract boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec); + + + /** + * returns true if the LDT offers an operation for the given binary java operator and the logic + * subterms + * + * @param op the de.uka.ilkd.key.java.expression.Operator to translate * @param left the left subterm of the java operator * @param right the right subterm of the java operator * @param services the Services * @param ec the ExecutionContext in which the expression is evaluated - * @return true if the LDT offers an operation for the given java - * operator and the subterms + * @return true if the LDT offers an operation for the given java operator and the subterms */ - public abstract boolean isResponsible( - de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, ExecutionContext ec); - - - /** returns true if the LDT offers an operation for the given - * unary java operator and the logic subterms - * @param op the de.uka.ilkd.key.java.expression.Operator to - * translate + public abstract boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, + Term right, Services services, ExecutionContext ec); + + + /** + * returns true if the LDT offers an operation for the given unary java operator and the logic + * subterms + * + * @param op the de.uka.ilkd.key.java.expression.Operator to translate * @param sub the logic subterms of the java operator - * @param services the Services - * @param ec the ExecutionContext in which the expression is evaluated - * @return true if the LDT offers an operation for the given java - * operator and the subterm + * @param services the Services + * @param ec the ExecutionContext in which the expression is evaluated + * @return true if the LDT offers an operation for the given java operator and the subterm */ - public abstract boolean isResponsible( - de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec); + public abstract boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec); - /** translates a given literal to its logic counterpart + /** + * translates a given literal to its logic counterpart + * * @param lit the Literal to be translated - * @return the Term that represents the given literal in its logic - * form - */ + * @return the Term that represents the given literal in its logic form + */ public abstract Term translateLiteral(Literal lit, Services services); /** * returns the function symbol for the given Java operator. * - * @return the function symbol for the given operation, null if - * not supported in general or not supported for this particular - * operator. + * @return the function symbol for the given operation, null if not supported in general or not + * supported for this particular operator. */ - public abstract Function getFunctionFor( - de.uka.ilkd.key.java.expression.Operator op, - Services services, - ExecutionContext ec); + public abstract Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, + Services services, ExecutionContext ec); /** - * get the function in this LDT for an operation identified by generic - * operatorSymbol. If the LDT does not support this named function, it should - * return null. + * get the function in this LDT for an operation identified by generic operatorSymbol. If the + * LDT does not support this named function, it should return null. * * This is used to resolve overloaded symbols. * - * For example: "+" may map to "add" for integers, and to "addFloat" for - * floats. + * For example: "+" may map to "add" for integers, and to "addFloat" for floats. * * @param operatorSymbol non-null operatorSymbol for a generic function - * @param services services to use - * @return reference to the respective LDT-specific function for the - * operation, null if not available + * @param services services to use + * @return reference to the respective LDT-specific function for the operation, null if not + * available */ public @Nullable Function getFunctionFor(String operatorSymbol, Services services) { return getFunctionFor(operatorSymbol, MixFitInfo.Kind.INFIX, services); } - public @Nullable Function getFunctionFor(String operatorSymbol, MixFitInfo.Kind kind, Services services) { + + public @Nullable Function getFunctionFor(String operatorSymbol, MixFitInfo.Kind kind, + Services services) { for (Operator operator : functions.allElements()) { - if(operator instanceof Function) { + if (operator instanceof Function) { var op = (Function) operator; if (op.getMixFitInfo() != null) { var mfi = op.getMixFitInfo(); @@ -273,7 +266,7 @@ public abstract Function getFunctionFor( /** Is called whenever hasLiteralFunction() returns true. */ public abstract Expression translateTerm(Term t, ExtList children, Services services); - + public abstract Type getType(Term t); public Collection getFunctions() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java index a342c59e464..05a1c0caa5a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/LocSetLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -22,9 +25,9 @@ public final class LocSetLDT extends LDT { - - public static final Name NAME = new Name("LocSet"); - + + public static final Name NAME = new Name("LocSet"); + private final Function empty; private final Function allLocs; private final Function singleton; @@ -35,186 +38,175 @@ public final class LocSetLDT extends LDT { private final Function allFields; private final Function allObjects; private final Function arrayRange; - private final Function freshLocs; + private final Function freshLocs; private final Function elementOf; private final Function subset; - private final Function disjoint; - private final Function createdInHeap; - - + private final Function disjoint; + private final Function createdInHeap; + + public LocSetLDT(TermServices services) { - super(NAME, services); - empty = addFunction(services, "empty"); - allLocs = addFunction(services, "allLocs"); - singleton = addFunction(services, "singleton"); - union = addFunction(services, "union"); - intersect = addFunction(services, "intersect"); - setMinus = addFunction(services, "setMinus"); - infiniteUnion = addFunction(services, "infiniteUnion"); - allFields = addFunction(services, "allFields"); - allObjects = addFunction(services, "allObjects"); - arrayRange = addFunction(services, "arrayRange"); - freshLocs = addFunction(services, "freshLocs"); - elementOf = addFunction(services, "elementOf"); - subset = addFunction(services, "subset"); - disjoint = addFunction(services, "disjoint"); - createdInHeap = addFunction(services, "createdInHeap"); - } - - + super(NAME, services); + empty = addFunction(services, "empty"); + allLocs = addFunction(services, "allLocs"); + singleton = addFunction(services, "singleton"); + union = addFunction(services, "union"); + intersect = addFunction(services, "intersect"); + setMinus = addFunction(services, "setMinus"); + infiniteUnion = addFunction(services, "infiniteUnion"); + allFields = addFunction(services, "allFields"); + allObjects = addFunction(services, "allObjects"); + arrayRange = addFunction(services, "arrayRange"); + freshLocs = addFunction(services, "freshLocs"); + elementOf = addFunction(services, "elementOf"); + subset = addFunction(services, "subset"); + disjoint = addFunction(services, "disjoint"); + createdInHeap = addFunction(services, "createdInHeap"); + } + + public Function getEmpty() { - return empty; + return empty; } - - + + public Function getAllLocs() { - return allLocs; + return allLocs; } - - + + public Function getSingleton() { - return singleton; + return singleton; } - - + + public Function getUnion() { - return union; + return union; } - - + + public Function getIntersect() { - return intersect; + return intersect; } - - + + public Function getSetMinus() { - return setMinus; + return setMinus; } - - + + public Function getInfiniteUnion() { - return infiniteUnion; + return infiniteUnion; } - - + + public Function getAllFields() { - return allFields; + return allFields; } - - + + public Function getAllObjects() { - return allObjects; - } + return allObjects; + } + - public Function getArrayRange() { - return arrayRange; - } - - + return arrayRange; + } + + public Function getFreshLocs() { - return freshLocs; + return freshLocs; } - - + + public Function getElementOf() { - return elementOf; + return elementOf; } - - + + public Function getSubset() { - return subset; + return subset; } - - + + public Function getDisjoint() { - return disjoint; + return disjoint; } - - + + public Function getCreatedInHeap() { - return createdInHeap; - } - - + return createdInHeap; + } + + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { - return isResponsible(op, (Term)null, services, ec); + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + return isResponsible(op, (Term) null, services, ec); } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return op instanceof Singleton - || op instanceof SetUnion - || op instanceof Intersect - || op instanceof SetMinus - || op instanceof AllFields; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return op instanceof Singleton || op instanceof SetUnion || op instanceof Intersect + || op instanceof SetMinus || op instanceof AllFields; } @Override public Term translateLiteral(Literal lit, Services services) { - assert lit instanceof EmptySetLiteral; - return services.getTermBuilder().func(empty); + assert lit instanceof EmptySetLiteral; + return services.getTermBuilder().func(empty); } - + @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services serv, - ExecutionContext ec) { - if(op instanceof Singleton) { - return singleton; - } else if(op instanceof SetUnion) { - return union; - } else if(op instanceof Intersect) { - return intersect; - } else if(op instanceof SetMinus) { - return setMinus; - } else if(op instanceof AllFields) { - return allFields; - } - assert false; - return null; - } - - + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services serv, + ExecutionContext ec) { + if (op instanceof Singleton) { + return singleton; + } else if (op instanceof SetUnion) { + return union; + } else if (op instanceof Intersect) { + return intersect; + } else if (op instanceof SetMinus) { + return setMinus; + } else if (op instanceof AllFields) { + return allFields; + } + assert false; + return null; + } + + @Override public boolean hasLiteralFunction(Function f) { - return f.equals(empty); + return f.equals(empty); } - + @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if(t.op().equals(empty)) { - return EmptySetLiteral.LOCSET; - } - assert false; - return null; - } - - + if (t.op().equals(empty)) { + return EmptySetLiteral.LOCSET; + } + assert false; + return null; + } + + @Override public final Type getType(Term t) { - assert false; - return null; + assert false; + return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/MapLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/MapLDT.java index 92bfd7d5915..8e6cf519f29 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/MapLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/MapLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -31,26 +34,19 @@ public MapLDT(TermServices services) { } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { return isResponsible(op, (Term) null, services, ec); } @Override - public boolean isResponsible(Operator op, - Term left, - Term right, - Services services, + public boolean isResponsible(Operator op, Term left, Term right, Services services, ExecutionContext ec) { return false; } @Override - public boolean isResponsible(Operator op, - Term sub, - TermServices services, + public boolean isResponsible(Operator op, Term sub, TermServices services, ExecutionContext ec) { return false; } @@ -62,9 +58,7 @@ public Term translateLiteral(Literal lit, Services services) { } @Override - public Function getFunctionFor(Operator op, - Services serv, - ExecutionContext ec) { + public Function getFunctionFor(Operator op, Services serv, ExecutionContext ec) { assert false; return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/PermissionLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/PermissionLDT.java index 2178e787c4e..fcd09a9eff2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/PermissionLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/PermissionLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -28,17 +31,20 @@ public Function getPermissionsFor() { } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, Services services, ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { // TODO Auto-generated method stub return false; } - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, Services services, ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { return false; } - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, de.uka.ilkd.key.logic.TermServices services, ExecutionContext ec) { + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + de.uka.ilkd.key.logic.TermServices services, ExecutionContext ec) { return false; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/RealLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/RealLDT.java index 4957056cf6b..cc37e21ef5c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/RealLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/RealLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -17,6 +20,7 @@ * Complete this class if you want to add support for the JML \real type. * * At the moment this class contains only stubs. + * * @author bruns */ public final class RealLDT extends LDT { @@ -25,87 +29,79 @@ public final class RealLDT extends LDT { public RealLDT(TermServices services) { - super(NAME, services); + super(NAME, services); } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + return false; } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return false; } @Override public Term translateLiteral(Literal lit, Services services) { // return skolem term - final Function sk = new Function(new Name(""+NAME+lit),targetSort()); + final Function sk = new Function(new Name("" + NAME + lit), targetSort()); return services.getTermBuilder().func(sk); } -// @Override -// public Function getFunctionFor(String op, Services services) { -// switch (op) { -// case "gt": return getGreaterThan(); -// case "geq": return getGreaterOrEquals(); -// case "lt": return getLessThan(); -// case "leq": return getLessOrEquals(); -// case "div": return getDivIEEE(); -// case "mul": return getMulIEEE(); -// case "add": return getAddIEEE(); -// case "sub": return getSubIEEE(); -// } -// return null; -// } + // @Override + // public Function getFunctionFor(String op, Services services) { + // switch (op) { + // case "gt": return getGreaterThan(); + // case "geq": return getGreaterOrEquals(); + // case "lt": return getLessThan(); + // case "leq": return getLessOrEquals(); + // case "div": return getDivIEEE(); + // case "mul": return getMulIEEE(); + // case "add": return getAddIEEE(); + // case "sub": return getSubIEEE(); + // } + // return null; + // } @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services services, - ExecutionContext ec) { - assert false; - return null; + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services services, + ExecutionContext ec) { + assert false; + return null; } @Override public boolean hasLiteralFunction(Function f) { - return false; + return false; } @Override public Expression translateTerm(Term t, ExtList children, Services services) { - return null; + return null; } @Override public final Type getType(Term t) { - if(t.sort() == targetSort()) { - return PrimitiveType.JAVA_REAL; - } else { - return null; + if (t.sort() == targetSort()) { + return PrimitiveType.JAVA_REAL; + } else { + return null; } } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java index e5d85014823..43580c3300c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/ldt/SeqLDT.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.ldt; import org.key_project.util.ExtList; @@ -26,175 +29,165 @@ public final class SeqLDT extends LDT { - + public static final Name NAME = new Name("Seq"); public static final Name SEQGET_NAME = new Name("seqGet"); - //getters + // getters private final SortDependingFunction seqGet; private final Function seqLen; - private final Function seqIndexOf; - - //constructors + private final Function seqIndexOf; + + // constructors private final Function seqEmpty; private final Function seqSingleton; private final Function seqConcat; private final Function seqSub; - private final Function seqReverse; + private final Function seqReverse; private final Function seqDef; private final Function values; - + public SeqLDT(TermServices services) { - super(NAME, services); - seqGet = addSortDependingFunction(services, "seqGet"); - seqLen = addFunction(services, "seqLen"); - seqEmpty = addFunction(services, "seqEmpty"); - seqSingleton = addFunction(services, "seqSingleton"); - seqConcat = addFunction(services, "seqConcat"); - seqSub = addFunction(services, "seqSub"); - seqReverse = addFunction(services, "seqReverse"); - seqIndexOf = addFunction(services, "seqIndexOf"); - seqDef = addFunction(services, "seqDef"); - values = addFunction(services, "values"); - } - - + super(NAME, services); + seqGet = addSortDependingFunction(services, "seqGet"); + seqLen = addFunction(services, "seqLen"); + seqEmpty = addFunction(services, "seqEmpty"); + seqSingleton = addFunction(services, "seqSingleton"); + seqConcat = addFunction(services, "seqConcat"); + seqSub = addFunction(services, "seqSub"); + seqReverse = addFunction(services, "seqReverse"); + seqIndexOf = addFunction(services, "seqIndexOf"); + seqDef = addFunction(services, "seqDef"); + values = addFunction(services, "values"); + } + + public SortDependingFunction getSeqGet(Sort instanceSort, TermServices services) { - return seqGet.getInstanceFor(instanceSort, services); + return seqGet.getInstanceFor(instanceSort, services); } - - + + public Function getSeqLen() { - return seqLen; - } - - + return seqLen; + } + + public Function getSeqEmpty() { - return seqEmpty; + return seqEmpty; } - - + + public Function getSeqSingleton() { - return seqSingleton; + return seqSingleton; } - + public Function getSeqConcat() { - return seqConcat; + return seqConcat; } - + public Function getSeqSub() { - return seqSub; + return seqSub; } - - + + public Function getSeqReverse() { - return seqReverse; + return seqReverse; } - + public Function getSeqDef() { - return seqDef; + return seqDef; } - - /** Placeholder for the sequence of values observed through the execution of an enhanced for loop. - * Follows David Cok's proposal to adapt JML to Java5. + + /** + * Placeholder for the sequence of values observed through the execution of an enhanced for + * loop. Follows David Cok's proposal to adapt JML to Java5. + * * @return */ - public Function getValues(){ - return values; + public Function getValues() { + return values; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term[] subs, - Services services, - ExecutionContext ec) { - return isResponsible(op, (Term)null, services, ec); + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term[] subs, + Services services, ExecutionContext ec) { + return isResponsible(op, (Term) null, services, ec); } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term left, - Term right, - Services services, - ExecutionContext ec) { - return false; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term left, Term right, + Services services, ExecutionContext ec) { + return false; } - + @Override - public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, - Term sub, - TermServices services, - ExecutionContext ec) { - return op instanceof SeqSingleton - || op instanceof SeqConcat - || op instanceof SeqSub - || op instanceof SeqReverse - || op instanceof SeqIndexOf - || op instanceof SeqGet - || op instanceof SeqLength; + public boolean isResponsible(de.uka.ilkd.key.java.expression.Operator op, Term sub, + TermServices services, ExecutionContext ec) { + return op instanceof SeqSingleton || op instanceof SeqConcat || op instanceof SeqSub + || op instanceof SeqReverse || op instanceof SeqIndexOf || op instanceof SeqGet + || op instanceof SeqLength; } @Override public Term translateLiteral(Literal lit, Services services) { - assert lit instanceof EmptySeqLiteral; - return services.getTermBuilder().func(seqEmpty); + assert lit instanceof EmptySeqLiteral; + return services.getTermBuilder().func(seqEmpty); } - + @Override - public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, - Services serv, - ExecutionContext ec) { - if(op instanceof SeqSingleton) { - return seqSingleton; - } else if(op instanceof SeqConcat) { - return seqConcat; - } else if(op instanceof SeqSub) { - return seqSub; - } else if(op instanceof SeqReverse) { - return seqReverse; - } else if(op instanceof SeqIndexOf) { - return seqIndexOf; - } else if(op instanceof SeqGet){ - return seqGet; - } else if(op instanceof SeqLength){ - return seqLen; - } - assert false; - return null; + public Function getFunctionFor(de.uka.ilkd.key.java.expression.Operator op, Services serv, + ExecutionContext ec) { + if (op instanceof SeqSingleton) { + return seqSingleton; + } else if (op instanceof SeqConcat) { + return seqConcat; + } else if (op instanceof SeqSub) { + return seqSub; + } else if (op instanceof SeqReverse) { + return seqReverse; + } else if (op instanceof SeqIndexOf) { + return seqIndexOf; + } else if (op instanceof SeqGet) { + return seqGet; + } else if (op instanceof SeqLength) { + return seqLen; + } + assert false; + return null; } @Override public boolean hasLiteralFunction(Function f) { - return f.equals(seqEmpty); + return f.equals(seqEmpty); } - + @Override public Expression translateTerm(Term t, ExtList children, Services services) { - if(t.op().equals(seqEmpty)) { - return EmptySeqLiteral.INSTANCE; - } - assert false; - return null; - } - - + if (t.op().equals(seqEmpty)) { + return EmptySeqLiteral.INSTANCE; + } + assert false; + return null; + } + + @Override public final Type getType(Term t) { - assert false; - return null; + assert false; + return null; } public Function getSeqIndexOf() { - return seqIndexOf; - } -} \ No newline at end of file + return seqIndexOf; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BooleanContainer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BooleanContainer.java index d7fc3c70a35..1b35298096e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BooleanContainer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BooleanContainer.java @@ -1,18 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** BooleanContainer wraps primitive bool */ public final class BooleanContainer { private boolean bool; - + public BooleanContainer() { - bool = false; + bool = false; } - + public final boolean val() { - return bool; + return bool; } - + public final void setVal(boolean b) { - bool = b; + bool = b; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVariableTools.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVariableTools.java index bb58fd9933c..45deb6ae83b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVariableTools.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVariableTools.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.LinkedHashMap; @@ -15,196 +18,172 @@ * Some generally useful tools for dealing with arrays of bound variables */ public class BoundVariableTools { - - public final static BoundVariableTools DEFAULT = new BoundVariableTools (); - - private BoundVariableTools () {} - + + public final static BoundVariableTools DEFAULT = new BoundVariableTools(); + + private BoundVariableTools() {} + /** - * Compare the arrays oldBoundVars and - * newBoundVars component-wise, and in case of differences - * substitute variables from the former array with the ones of the latter - * array (in originalTerm) - * @param services the Services + * Compare the arrays oldBoundVars and newBoundVars component-wise, + * and in case of differences substitute variables from the former array with the ones of the + * latter array (in originalTerm) + * + * @param services the Services */ - public Term renameVariables (Term originalTerm, - ImmutableArray oldBoundVars, - ImmutableArray newBoundVars, - TermServices services) { + public Term renameVariables(Term originalTerm, + ImmutableArray oldBoundVars, + ImmutableArray newBoundVars, TermServices services) { Term res = originalTerm; for (int i = 0; i != oldBoundVars.size(); ++i) { - if ( oldBoundVars.get ( i ) - != newBoundVars.get ( i ) ) { - final Term newVarTerm = - services.getTermFactory().createTerm( newBoundVars.get ( i ) ); - final ClashFreeSubst subst = - new ClashFreeSubst ( oldBoundVars.get ( i ), - newVarTerm, services.getTermBuilder() ); - res = subst.apply ( res ); + if (oldBoundVars.get(i) != newBoundVars.get(i)) { + final Term newVarTerm = services.getTermFactory().createTerm(newBoundVars.get(i)); + final ClashFreeSubst subst = new ClashFreeSubst(oldBoundVars.get(i), newVarTerm, + services.getTermBuilder()); + res = subst.apply(res); } } - + return res; } - public Term[] renameVariables (Term[] originalTerms, - ImmutableArray oldBoundVars, - ImmutableArray newBoundVars, - TermServices services) { - final Term[] res = new Term [originalTerms.length]; - for ( int i = 0; i != res.length; ++i ) - res[i] = renameVariables ( originalTerms[i], - oldBoundVars, - newBoundVars, services ); + public Term[] renameVariables(Term[] originalTerms, + ImmutableArray oldBoundVars, + ImmutableArray newBoundVars, TermServices services) { + final Term[] res = new Term[originalTerms.length]; + for (int i = 0; i != res.length; ++i) + res[i] = renameVariables(originalTerms[i], oldBoundVars, newBoundVars, services); return res; } - - + + /** - * Replace all variables of oldVars that also turn up in - * criticalPairs with new variables (currently just with the - * same name). - * - * @param oldVars - * variables to be checked - * @param newVars - * array in which either the original variables (if a variable is - * not an element of criticalVars) or newly - * created variables are stored - * @param criticalVars - * variables that must not turn up in the resulting array - * newVars - * @return true iff it was necessary to create at least one - * new variable + * Replace all variables of oldVars that also turn up in criticalPairs + * with new variables (currently just with the same name). + * + * @param oldVars variables to be checked + * @param newVars array in which either the original variables (if a variable is not an element + * of criticalVars) or newly created variables are stored + * @param criticalVars variables that must not turn up in the resulting array + * newVars + * @return true iff it was necessary to create at least one new variable */ - public boolean resolveCollisions (ImmutableArray oldVars, - QuantifiableVariable[] newVars, - ImmutableSet criticalVars) { + public boolean resolveCollisions(ImmutableArray oldVars, + QuantifiableVariable[] newVars, ImmutableSet criticalVars) { boolean changedVar = false; - for ( int i = 0; i != newVars.length; ++i ) { - final QuantifiableVariable oldVar = oldVars.get ( i ); - if ( criticalVars.contains ( oldVar ) ) { + for (int i = 0; i != newVars.length; ++i) { + final QuantifiableVariable oldVar = oldVars.get(i); + if (criticalVars.contains(oldVar)) { // rename the bound variable - newVars[i] = new LogicVariable ( oldVar.name (), oldVar.sort () ); + newVars[i] = new LogicVariable(oldVar.name(), oldVar.sort()); changedVar = true; } else { newVars[i] = oldVar; } } - + return changedVar; } /** - * Ensure that none of the variables criticalVars is bound by - * the top-level operator of t (by bound renaming) + * Ensure that none of the variables criticalVars is bound by the top-level + * operator of t (by bound renaming) */ -// public Term resolveCollisions (Term t, -// ImmutableSet criticalVars) { -// final ImmutableArray[] newBoundVars = -// new ImmutableArray [t.arity ()]; -// final Term[] newSubs = new Term [t.arity ()]; -// -// if ( !resolveCollisions ( t, criticalVars, newBoundVars, newSubs ) ) -// return t; -// -// return tf.createTerm ( t.op (), newSubs, newBoundVars, t.javaBlock ()); -// } + // public Term resolveCollisions (Term t, + // ImmutableSet criticalVars) { + // final ImmutableArray[] newBoundVars = + // new ImmutableArray [t.arity ()]; + // final Term[] newSubs = new Term [t.arity ()]; + // + // if ( !resolveCollisions ( t, criticalVars, newBoundVars, newSubs ) ) + // return t; + // + // return tf.createTerm ( t.op (), newSubs, newBoundVars, t.javaBlock ()); + // } /** - * Ensure that none of the variables criticalVars is bound by - * the top-level operator of t (by bound renaming). The - * resulting subterms and arrays of bound variables are stored in - * newSubs and newBoundVars (resp.) - * @param services TODO - * - * @return true if it was necessary to rename a variable, - * i.e. to changed anything in the term originalTerm + * Ensure that none of the variables criticalVars is bound by the top-level + * operator of t (by bound renaming). The resulting subterms and arrays of bound + * variables are stored in newSubs and newBoundVars (resp.) + * + * @param services TODO + * + * @return true if it was necessary to rename a variable, i.e. to changed anything + * in the term originalTerm */ - public boolean resolveCollisions (Term originalTerm, - ImmutableSet criticalVars, - ImmutableArray[] newBoundVars, - Term[] newSubs, TermServices services) { + public boolean resolveCollisions(Term originalTerm, + ImmutableSet criticalVars, + ImmutableArray[] newBoundVars, Term[] newSubs, + TermServices services) { boolean changed = false; - for ( int i = 0; i != originalTerm.arity (); ++i ) { - final ImmutableArray oldVars = - originalTerm.varsBoundHere ( i ); + for (int i = 0; i != originalTerm.arity(); ++i) { + final ImmutableArray oldVars = originalTerm.varsBoundHere(i); - final QuantifiableVariable[] newVars = - new QuantifiableVariable [oldVars.size ()]; - if ( resolveCollisions ( oldVars, newVars, criticalVars ) ) { + final QuantifiableVariable[] newVars = new QuantifiableVariable[oldVars.size()]; + if (resolveCollisions(oldVars, newVars, criticalVars)) { changed = true; - newBoundVars[i] = new ImmutableArray ( newVars ); - newSubs[i] = renameVariables ( originalTerm.sub ( i ), - oldVars, - newBoundVars[i], services ); + newBoundVars[i] = new ImmutableArray(newVars); + newSubs[i] = + renameVariables(originalTerm.sub(i), oldVars, newBoundVars[i], services); } else { newBoundVars[i] = oldVars; - newSubs[i] = originalTerm.sub ( i ); + newSubs[i] = originalTerm.sub(i); } } - + return changed; } - + /** * Ensure that for the subterms with indexes [subtermsBegin, - * subtermsEnd) the same variables are bound. In case of - * differences bound renaming is applied (existing variables are renamed to - * new ones) - * + * subtermsEnd) the same variables are bound. In case of differences bound renaming + * is applied (existing variables are renamed to new ones) + * * @param boundVarsPerSub bound variables per subterms - * @param subs subterms (in which variables are renamed if necessary) - * @param subtermsBegin first subterm that is supposed to be considered - * @param subtermsEnd subterm after the last subterm to be consider - * - * PRE: subtermsEnd {@literal >} subtermsBegin - * @param services TODO + * @param subs subterms (in which variables are renamed if necessary) + * @param subtermsBegin first subterm that is supposed to be considered + * @param subtermsEnd subterm after the last subterm to be consider + * + * PRE: subtermsEnd {@literal >} subtermsBegin + * @param services TODO */ - public ImmutableArray - unifyBoundVariables (ImmutableArray[] boundVarsPerSub, - Term[] subs, - int subtermsBegin, - int subtermsEnd, TermServices services) { + public ImmutableArray unifyBoundVariables( + ImmutableArray[] boundVarsPerSub, Term[] subs, int subtermsBegin, + int subtermsEnd, TermServices services) { // at least one subterms belongs to the entry (value) ImmutableArray unifiedVariable = boundVarsPerSub[subtermsBegin]; - final Map variableRenamings = - new LinkedHashMap (); - for ( int i = subtermsBegin + 1; i < subtermsEnd; ++i ) { + final Map variableRenamings = + new LinkedHashMap(); + for (int i = subtermsBegin + 1; i < subtermsEnd; ++i) { // check that numbers and sorts of the quantified variables are // consistent - Debug.assertTrue ( consistentVariableArrays ( unifiedVariable, - boundVarsPerSub[i] ), - "Inconsistent bound variables" ); + Debug.assertTrue(consistentVariableArrays(unifiedVariable, boundVarsPerSub[i]), + "Inconsistent bound variables"); - unifiedVariable = unifyVariableArrays ( unifiedVariable, - boundVarsPerSub[i], - variableRenamings ); + unifiedVariable = + unifyVariableArrays(unifiedVariable, boundVarsPerSub[i], variableRenamings); } // substitute variables where necessary - for ( int i = subtermsBegin; i < subtermsEnd; ++i ) - subs[i] = renameVariables ( subs[i], - boundVarsPerSub[i], - unifiedVariable, services ); - + for (int i = subtermsBegin; i < subtermsEnd; ++i) + subs[i] = renameVariables(subs[i], boundVarsPerSub[i], unifiedVariable, services); + return unifiedVariable; } - + /** - * @return true iff the two given arrays have the same size - * and the contained variables have the same sorts + * @return true iff the two given arrays have the same size and the contained + * variables have the same sorts */ - public boolean consistentVariableArrays (ImmutableArray ar0, - ImmutableArray ar1) { - if ( ar0.size () != ar1.size () ) return false; - for ( int i = 0; i != ar0.size (); ++i ) { - if ( ar0.get ( i ).sort () - != ar1.get ( i ).sort () ) + public boolean consistentVariableArrays(ImmutableArray ar0, + ImmutableArray ar1) { + if (ar0.size() != ar1.size()) + return false; + for (int i = 0; i != ar0.size(); ++i) { + if (ar0.get(i).sort() != ar1.get(i).sort()) return false; } return true; @@ -212,60 +191,56 @@ public boolean consistentVariableArrays (ImmutableArray ar /** * @param services TODO - * @return true iff the two arrays of variables are - * compatible (compatibleVariableArrays()) and the - * two given terms are equal modulo renaming after unification of - * the two arrays (of variables occurring free in the terms) + * @return true iff the two arrays of variables are compatible + * (compatibleVariableArrays()) and the two given terms are equal modulo + * renaming after unification of the two arrays (of variables occurring free in the + * terms) */ - public boolean equalsModRenaming (ImmutableArray vars0, - Term term0, - ImmutableArray vars1, - Term term1, TermServices services) { - if ( !consistentVariableArrays ( vars0, vars1 ) ) return false; - if ( vars0.size () == 0 ) return term0.equalsModRenaming ( term1 ); - - final ImmutableArray unifiedVars = - unifyVariableArrays ( vars0, vars1, - new LinkedHashMap () ); - - final Term renamedTerm0 = renameVariables ( term0, vars0, unifiedVars, services ); - final Term renamedTerm1 = renameVariables ( term1, vars1, unifiedVars, services ); - - return renamedTerm0.equalsModRenaming ( renamedTerm1 ); + public boolean equalsModRenaming(ImmutableArray vars0, Term term0, + ImmutableArray vars1, Term term1, TermServices services) { + if (!consistentVariableArrays(vars0, vars1)) + return false; + if (vars0.size() == 0) + return term0.equalsModRenaming(term1); + + final ImmutableArray unifiedVars = unifyVariableArrays(vars0, vars1, + new LinkedHashMap()); + + final Term renamedTerm0 = renameVariables(term0, vars0, unifiedVars, services); + final Term renamedTerm1 = renameVariables(term1, vars1, unifiedVars, services); + + return renamedTerm0.equalsModRenaming(renamedTerm1); } - + /** - * Unify the given arrays be replacing variables with new ones, return the - * unifier + * Unify the given arrays be replacing variables with new ones, return the unifier */ - private ImmutableArray - unifyVariableArrays (ImmutableArray ar0, - ImmutableArray ar1, - Map variableRenaming) { - final QuantifiableVariable[] res = new QuantifiableVariable [ar0.size()]; - for ( int i = 0; i != ar0.size (); ++i ) { - QuantifiableVariable pv0 = ar0.get ( i ); - if ( variableRenaming.containsKey ( pv0 ) ) - pv0 = variableRenaming.get ( pv0 ); - - QuantifiableVariable pv1 = ar1.get ( i ); - if ( variableRenaming.containsKey ( pv1 ) ) - pv1 = variableRenaming.get ( pv1 ); - - if ( pv0 != pv1 ) { + private ImmutableArray unifyVariableArrays( + ImmutableArray ar0, ImmutableArray ar1, + Map variableRenaming) { + final QuantifiableVariable[] res = new QuantifiableVariable[ar0.size()]; + for (int i = 0; i != ar0.size(); ++i) { + QuantifiableVariable pv0 = ar0.get(i); + if (variableRenaming.containsKey(pv0)) + pv0 = variableRenaming.get(pv0); + + QuantifiableVariable pv1 = ar1.get(i); + if (variableRenaming.containsKey(pv1)) + pv1 = variableRenaming.get(pv1); + + if (pv0 != pv1) { // introduce a new variable - final QuantifiableVariable newVar = - new LogicVariable ( pv0.name (), pv0.sort () ); - variableRenaming.put ( ar0.get ( i ), newVar ); - variableRenaming.put ( ar1.get ( i ), newVar ); - variableRenaming.put ( pv0, newVar ); - variableRenaming.put ( pv1, newVar ); + final QuantifiableVariable newVar = new LogicVariable(pv0.name(), pv0.sort()); + variableRenaming.put(ar0.get(i), newVar); + variableRenaming.put(ar1.get(i), newVar); + variableRenaming.put(pv0, newVar); + variableRenaming.put(pv1, newVar); res[i] = newVar; } else { res[i] = pv0; } } - - return new ImmutableArray ( res ); + + return new ImmutableArray(res); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVarsVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVarsVisitor.java index dc6e9a36d67..4250196c919 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVarsVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/BoundVarsVisitor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.DefaultImmutableSet; @@ -5,36 +8,34 @@ import de.uka.ilkd.key.logic.op.QuantifiableVariable; -/** - * Visitor traversing a term and collecting all variables that occur bound. - * The visitor implements also a continuation on sequents, traversing all of - * the formulas occuring in the sequent. +/** + * Visitor traversing a term and collecting all variables that occur bound. The visitor implements + * also a continuation on sequents, traversing all of the formulas occuring in the sequent. */ -public class BoundVarsVisitor extends DefaultVisitor{ - +public class BoundVarsVisitor extends DefaultVisitor { + private ImmutableSet bdVars = - DefaultImmutableSet.nil(); + DefaultImmutableSet.nil(); + - /** - * creates a Visitor that collects all bound variables for the subterms - * of the term it is called from. + * creates a Visitor that collects all bound variables for the subterms of the term it is called + * from. */ - public BoundVarsVisitor() { - } + public BoundVarsVisitor() {} /** * only called by execPostOrder in Term. */ - public void visit(Term visited) { - for (int i = 0, ar = visited.arity(); i getBoundVariables(){ - return bdVars; + public ImmutableSet getBoundVariables() { + return bdVars; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Choice.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Choice.java index dfb57d59488..17c3da6c480 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Choice.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Choice.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; @@ -43,8 +46,10 @@ public Choice(@Nonnull Name name, @Nonnull String category) { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; Choice choice = (Choice) o; return name.equals(choice.name); } @@ -58,4 +63,4 @@ public int hashCode() { public String toString() { return name.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ClashFreeSubst.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ClashFreeSubst.java index cccc0525878..9439a8af506 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ClashFreeSubst.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ClashFreeSubst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.DefaultImmutableSet; @@ -20,49 +23,49 @@ public ClashFreeSubst(QuantifiableVariable v, Term s, TermBuilder tb) { svars = s.freeVars(); } - protected QuantifiableVariable getVariable () { + protected QuantifiableVariable getVariable() { return v; } - protected Term getSubstitutedTerm () { + protected Term getSubstitutedTerm() { return s; } - /** substitute s for v in t, - * avoiding collisions by replacing bound variables in - * t if necessary. + /** + * substitute s for v in t, avoiding collisions by + * replacing bound variables in t if necessary. */ public Term apply(Term t) { - if ( ! t.freeVars().contains(v) ) { + if (!t.freeVars().contains(v)) { return t; } else { - return apply1 ( t ); + return apply1(t); } } - /** substitute s for v in - * t, avoiding collisions by replacing bound - * variables in t if necessary. It is - * assumed, that t contains a free occurrence of - * v. */ + /** + * substitute s for v in t, avoiding collisions by + * replacing bound variables in t if necessary. It is assumed, that t + * contains a free occurrence of v. + */ protected Term apply1(Term t) { - if ( t.op() == v ) { + if (t.op() == v) { return s; } else { return applyOnSubterms(t); } } - //XXX - protected static ImmutableArray - getSingleArray(ImmutableArray[] bv) { + // XXX + protected static ImmutableArray getSingleArray( + ImmutableArray[] bv) { if (bv == null) { return null; } ImmutableArray result = null; - for(ImmutableArray arr : bv) { - if(arr != null && !arr.isEmpty()) { - if(result == null) { + for (ImmutableArray arr : bv) { + if (arr != null && !arr.isEmpty()) { + if (result == null) { result = arr; } else { assert arr.equals(result) : "expected: " + result + "\nfound: " + arr; @@ -72,73 +75,61 @@ protected Term apply1(Term t) { return result; } - /** substitute s for v in - * every subterm of t, and build a new term. - * It is assumed, that one of the subterms contains a free occurrence - * of v, and that the case v==t is already - * handled. */ + /** + * substitute s for v in every subterm of t, and build a + * new term. It is assumed, that one of the subterms contains a free occurrence of + * v, and that the case v==t is already handled. + */ private Term applyOnSubterms(Term t) { final int arity = t.arity(); final Term[] newSubterms = new Term[arity]; @SuppressWarnings("unchecked") - final ImmutableArray[] newBoundVars = - new ImmutableArray[arity]; - for ( int i=0; i[] newBoundVars = new ImmutableArray[arity]; + for (int i = 0; i < arity; i++) { + applyOnSubterm(t, i, newSubterms, newBoundVars); } - return tb.tf().createTerm(t.op(), newSubterms, getSingleArray(newBoundVars), t.javaBlock(), t.getLabels()); + return tb.tf().createTerm(t.op(), newSubterms, getSingleArray(newBoundVars), t.javaBlock(), + t.getLabels()); } /** - * Apply the substitution of the subterm subtermIndex of - * term/formula completeTerm. The result is stored in - * newSubterms and newBoundVars (at index - * subtermIndex) + * Apply the substitution of the subterm subtermIndex of term/formula + * completeTerm. The result is stored in newSubterms and + * newBoundVars (at index subtermIndex) */ - protected void applyOnSubterm (Term completeTerm, - int subtermIndex, - Term[] newSubterms, + protected void applyOnSubterm(Term completeTerm, int subtermIndex, Term[] newSubterms, ImmutableArray[] newBoundVars) { - if ( subTermChanges ( completeTerm.varsBoundHere ( subtermIndex ), - completeTerm.sub ( subtermIndex ) ) ) { + if (subTermChanges(completeTerm.varsBoundHere(subtermIndex), + completeTerm.sub(subtermIndex))) { final QuantifiableVariable[] nbv = - new QuantifiableVariable [completeTerm.varsBoundHere ( subtermIndex ).size ()]; - applyOnSubterm ( 0, - completeTerm.varsBoundHere ( subtermIndex ), - nbv, - subtermIndex, - completeTerm.sub ( subtermIndex ), - newSubterms ); - newBoundVars[subtermIndex] = new ImmutableArray ( nbv ); + new QuantifiableVariable[completeTerm.varsBoundHere(subtermIndex).size()]; + applyOnSubterm(0, completeTerm.varsBoundHere(subtermIndex), nbv, subtermIndex, + completeTerm.sub(subtermIndex), newSubterms); + newBoundVars[subtermIndex] = new ImmutableArray(nbv); } else { - newBoundVars[subtermIndex] = completeTerm.varsBoundHere ( subtermIndex ); - newSubterms[subtermIndex] = completeTerm.sub ( subtermIndex ); + newBoundVars[subtermIndex] = completeTerm.varsBoundHere(subtermIndex); + newSubterms[subtermIndex] = completeTerm.sub(subtermIndex); } } - /** Perform the substitution on subTerm bound by the - * variables in boundVars, starting with the variable - * at index varInd. Put the resulting bound - * variables (which might be new) into newBoundVars, - * starting from position varInd, and the resulting - * subTerm into newSubterms[subInd]. - *

    It is assumed that v occurrs free in - * in this quantified subterm, i.e. it occurrs free in - * subTerm, but does not occurr in - * boundVars from varInd upwards.. + /** + * Perform the substitution on subTerm bound by the variables in + * boundVars, starting with the variable at index varInd. Put the + * resulting bound variables (which might be new) into newBoundVars, starting from + * position varInd, and the resulting subTerm into + * newSubterms[subInd]. + *

    + * It is assumed that v occurrs free in in this quantified subterm, i.e. it occurrs + * free in subTerm, but does not occurr in boundVars from + * varInd upwards.. */ - private void applyOnSubterm(int varInd, - ImmutableArray boundVars, - QuantifiableVariable[] newBoundVars, - int subInd, - Term subTerm, - Term[] newSubterms - ) { - if ( varInd >= boundVars.size() ) { + private void applyOnSubterm(int varInd, ImmutableArray boundVars, + QuantifiableVariable[] newBoundVars, int subInd, Term subTerm, Term[] newSubterms) { + if (varInd >= boundVars.size()) { newSubterms[subInd] = apply1(subTerm); } else { QuantifiableVariable qv = boundVars.get(varInd); - if ( svars.contains(qv) ) { + if (svars.contains(qv)) { /* Here is the clash case all this is about! Hurrah! */ // Determine Variable names to avoid @@ -147,73 +138,62 @@ private void applyOnSubterm(int varInd, subTerm.execPostOrder(vcv); usedVars = svars; usedVars = usedVars.union(vcv.vars()); - for ( int i = varInd+1; i < boundVars.size(); i++ ) { - usedVars = - usedVars.add(boundVars.get(i)); + for (int i = varInd + 1; i < boundVars.size(); i++) { + usedVars = usedVars.add(boundVars.get(i)); } // Get a new variable with a fitting name. - QuantifiableVariable qv1 = newVarFor(qv,usedVars); + QuantifiableVariable qv1 = newVarFor(qv, usedVars); // Substitute that for the old one. newBoundVars[varInd] = qv1; - new ClashFreeSubst(qv, tb.var(qv1), tb) - .applyOnSubterm1(varInd+1, boundVars, newBoundVars, - subInd,subTerm,newSubterms); + new ClashFreeSubst(qv, tb.var(qv1), tb).applyOnSubterm1(varInd + 1, boundVars, + newBoundVars, subInd, subTerm, newSubterms); // then continue recursively, on the result. - applyOnSubterm(varInd+1, - new ImmutableArray(newBoundVars), - newBoundVars, - subInd,newSubterms[subInd],newSubterms); + applyOnSubterm(varInd + 1, new ImmutableArray(newBoundVars), + newBoundVars, subInd, newSubterms[subInd], newSubterms); } else { newBoundVars[varInd] = qv; - applyOnSubterm(varInd+1, boundVars, newBoundVars, - subInd, subTerm, newSubterms); + applyOnSubterm(varInd + 1, boundVars, newBoundVars, subInd, subTerm, newSubterms); } } } - /** Same as applyOnSubterm, but v doesn't have to occurr free in the - * considered quantified subterm. It is however assumed that no more - * clash can occurr. */ - private void applyOnSubterm1(int varInd, - ImmutableArray boundVars, - QuantifiableVariable[] newBoundVars, - int subInd, - Term subTerm, - Term[] newSubterms - ) { - if ( varInd >= boundVars.size() ) { + /** + * Same as applyOnSubterm, but v doesn't have to occurr free in the considered quantified + * subterm. It is however assumed that no more clash can occurr. + */ + private void applyOnSubterm1(int varInd, ImmutableArray boundVars, + QuantifiableVariable[] newBoundVars, int subInd, Term subTerm, Term[] newSubterms) { + if (varInd >= boundVars.size()) { newSubterms[subInd] = apply(subTerm); } else { QuantifiableVariable qv = boundVars.get(varInd); newBoundVars[varInd] = qv; - if ( qv == v ) { + if (qv == v) { newSubterms[subInd] = subTerm; - for( int i = varInd; isubTerm bound by - * boundVars would change under application of this - * substitution. This is the case, if v occurrs free - * in subTerm, but does not occurr in boundVars. - * @returns true if subTerm bound by - * boundVars would change under application of this - * substitution + /** + * returns true if subTerm bound by boundVars would change under + * application of this substitution. This is the case, if v occurrs free in + * subTerm, but does not occurr in boundVars. + * + * @returns true if subTerm bound by boundVars would change under + * application of this substitution */ - protected boolean subTermChanges(ImmutableArray boundVars, - Term subTerm) { - if ( !subTerm.freeVars().contains(v) ) { + protected boolean subTermChanges(ImmutableArray boundVars, Term subTerm) { + if (!subTerm.freeVars().contains(v)) { return false; } else { - for( int i = 0; i boundVars, return true; } - /** returns a new variable that has a name derived from that of - * var, that is different from any of the names of - * variables in usedVars. - *

    Assumes that var is a @link{LogicVariable}. */ + /** + * returns a new variable that has a name derived from that of var, that is + * different from any of the names of variables in usedVars. + *

    + * Assumes that var is a @link{LogicVariable}. + */ protected QuantifiableVariable newVarFor(QuantifiableVariable var, ImmutableSet usedVars) { LogicVariable lv = (LogicVariable) var; String stem = var.name().toString(); int i = 1; - while ( ! nameNewInSet( (stem + i), usedVars ) ) { + while (!nameNewInSet((stem + i), usedVars)) { i++; } - return new LogicVariable( new Name(stem+i), lv.sort() ); + return new LogicVariable(new Name(stem + i), lv.sort()); } - /** returns true if there is no object named n in the - * set s */ + /** + * returns true if there is no object named n in the set s + */ private boolean nameNewInSet(String n, ImmutableSet qvars) { for (QuantifiableVariable qvar : qvars) { if (qvar.name().toString().equals(n)) { @@ -249,8 +232,9 @@ private boolean nameNewInSet(String n, ImmutableSet qvars) // This helper is used in other places as well. Perhaps make it toplevel one // day. - /** A Visitor class to collect all (not just the free) variables - * occurring in a term. */ + /** + * A Visitor class to collect all (not just the free) variables occurring in a term. + */ public static class VariableCollectVisitor extends DefaultVisitor { /** the collected variables */ private ImmutableSet vars; @@ -263,21 +247,21 @@ public VariableCollectVisitor() { @Override public void visit(Term t) { if (t.op() instanceof QuantifiableVariable) { - vars=vars.add((QuantifiableVariable)t.op()); + vars = vars.add((QuantifiableVariable) t.op()); } else { - for ( int i = 0; i vbh = t.varsBoundHere(i); - for ( int j = 0; j vars() { return vars; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/DefaultVisitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/DefaultVisitor.java index bcb365c9ab0..6800e16bdd9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/DefaultVisitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/DefaultVisitor.java @@ -1,19 +1,20 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** * This abstract Vistor class declares the interface for a common term visitor. */ -public abstract class DefaultVisitor implements Visitor { +public abstract class DefaultVisitor implements Visitor { @Override public boolean visitSubtree(Term visited) { return true; } @Override - public void subtreeEntered(Term subtreeRoot){ - } + public void subtreeEntered(Term subtreeRoot) {} @Override - public void subtreeLeft(Term subtreeRoot){ - } -} \ No newline at end of file + public void subtreeLeft(Term subtreeRoot) {} +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/FormulaChangeInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/FormulaChangeInfo.java index e0a3f22344e..9cc3bc62974 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/FormulaChangeInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/FormulaChangeInfo.java @@ -1,39 +1,40 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** * This class is used to hold information about modified formulas. + * * @see SequentChangeInfo */ public class FormulaChangeInfo { /** position within the original formula */ - private final PosInOccurrence positionOfModification; + private final PosInOccurrence positionOfModification; /** modified formula */ private final SequentFormula newFormula; - public FormulaChangeInfo(PosInOccurrence positionOfModification, - SequentFormula newFormula) { - this.newFormula = newFormula; - this.positionOfModification = positionOfModification; + public FormulaChangeInfo(PosInOccurrence positionOfModification, SequentFormula newFormula) { + this.newFormula = newFormula; + this.positionOfModification = positionOfModification; } public SequentFormula getNewFormula() { - return newFormula; + return newFormula; } public SequentFormula getOriginalFormula() { - return getPositionOfModification ().sequentFormula (); + return getPositionOfModification().sequentFormula(); } /** * @return position within the original formula */ public PosInOccurrence getPositionOfModification() { - return positionOfModification; + return positionOfModification; } - public String toString () { - return - "Replaced " + positionOfModification + - " with " + newFormula; + public String toString() { + return "Replaced " + positionOfModification + " with " + newFormula; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/GenericTermReplacer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/GenericTermReplacer.java index 71032d17658..2966ffe9755 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/GenericTermReplacer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/GenericTermReplacer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.function.Function; @@ -7,8 +10,8 @@ import de.uka.ilkd.key.java.Services; /** - * A generic {@link Term} replace visitor based on a filter predicate and a - * replacement function for the filtered subterms. + * A generic {@link Term} replace visitor based on a filter predicate and a replacement function for + * the filtered subterms. * * @author Dominic Steinhoefel */ @@ -20,12 +23,12 @@ public static Term replace(final Term t, final Predicate filter, newTopLevelTerm = replacer.apply(t); } - final Term[] newSubs = newTopLevelTerm.subs().stream() - .map(sub -> replace(sub, filter, replacer, services)).collect(Collectors.toList()) - .toArray(new Term[0]); + final Term[] newSubs = + newTopLevelTerm.subs().stream().map(sub -> replace(sub, filter, replacer, services)) + .collect(Collectors.toList()).toArray(new Term[0]); return services.getTermFactory().createTerm(newTopLevelTerm.op(), newSubs, newTopLevelTerm.boundVars(), newTopLevelTerm.javaBlock(), newTopLevelTerm.getLabels()); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/InnerVariableNamer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/InnerVariableNamer.java index 5800dcf9102..0f1ab1894e5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/InnerVariableNamer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/InnerVariableNamer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.java.ProgramElement; @@ -8,41 +11,35 @@ /** - * Implements "inner renaming", i.e. renaming - if a new variable entering the - * globals causes a name clash - this "inner" variable, and leaving the clashing - * "outer" one untouched. + * Implements "inner renaming", i.e. renaming - if a new variable entering the globals causes a name + * clash - this "inner" variable, and leaving the clashing "outer" one untouched. */ public class InnerVariableNamer extends VariableNamer { public InnerVariableNamer(Services services) { - super(services); + super(services); } /** - * returns the maximum counter for the passed basename in the passed globals - * and the passed program + * returns the maximum counter for the passed basename in the passed globals and the passed + * program */ private int getMaxCounterInGlobalsAndProgram(String basename, - Iterable globals, - ProgramElement program, - PosInProgram posOfDeclaration) { - int maxInGlobals = getMaxCounterInGlobals(basename, globals); - int maxInProgram = getMaxCounterInProgram(basename, - program, - posOfDeclaration); + Iterable globals, ProgramElement program, + PosInProgram posOfDeclaration) { + int maxInGlobals = getMaxCounterInGlobals(basename, globals); + int maxInProgram = getMaxCounterInProgram(basename, program, posOfDeclaration); - return (maxInGlobals > maxInProgram ? maxInGlobals : maxInProgram); + return (maxInGlobals > maxInProgram ? maxInGlobals : maxInProgram); } - public ProgramVariable rename(ProgramVariable var, - Goal goal, - PosInOccurrence posOfFind) { + public ProgramVariable rename(ProgramVariable var, Goal goal, PosInOccurrence posOfFind) { ProgramElementName name = var.getProgramElementName(); BasenameAndIndex bai = getBasenameAndIndex(name); Iterable globals = wrapGlobals(goal.node().getLocalProgVars()); map.clear(); - //prepare renaming of inner var + // prepare renaming of inner var final NameCreationInfo nci = MethodStackInfo.create(getProgramFromPIO(posOfFind)); ProgramElementName newname = null; // ProgramElementName branchUniqueName = null; @@ -54,14 +51,10 @@ public ProgramVariable rename(ProgramVariable var, newname = new ProgramElementName(proposal.toString(), nci); } if (newname == null || !isUniqueInGlobals(newname.toString(), globals) - || services.getNamespaces() - .lookupLogicSymbol(newname) != null) { + || services.getNamespaces().lookupLogicSymbol(newname) != null) { newname = createName(bai.basename, bai.index, nci); - int newcounter = getMaxCounterInGlobalsAndProgram( - bai.basename, - globals, - getProgramFromPIO(posOfFind), - null); + int newcounter = getMaxCounterInGlobalsAndProgram(bai.basename, globals, + getProgramFromPIO(posOfFind), null); final NamespaceSet namespaces = services.getNamespaces(); while (!isUniqueInGlobals(newname.toString(), globals) @@ -80,8 +73,8 @@ public ProgramVariable rename(ProgramVariable var, assert newvar != null; assert isUniqueInGlobals(newvar.name().toString(), globals); - assert services.getNamespaces().lookupLogicSymbol(newvar.name())==null; + assert services.getNamespaces().lookupLogicSymbol(newvar.name()) == null; return newvar; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/IntIterator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/IntIterator.java index 7eee52840a0..742404b1715 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/IntIterator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/IntIterator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; @@ -10,4 +13,4 @@ public interface IntIterator { /** @return boolean true iff collection has more unseen elements */ boolean hasNext(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/JavaBlock.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/JavaBlock.java index f2619a3789e..b98e11fc4b2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/JavaBlock.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/JavaBlock.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.io.IOException; @@ -14,120 +17,125 @@ public class JavaBlock { private static final Logger LOGGER = LoggerFactory.getLogger(JavaBlock.class); /** - * Attention using the JavaBlock below means no program not the empty program. - * It is used as a realization of the sentinel design pattern to mark terms with operators - * that are incapable of containing a program like predicate symbols. - * - * If you want to have an empty program, create a new JavaBlock instance with an - * empty statement block. - * + * Attention using the JavaBlock below means no program not the empty program. It is used as a + * realization of the sentinel design pattern to mark terms with operators that are incapable of + * containing a program like predicate symbols. + * + * If you want to have an empty program, create a new JavaBlock instance with an empty statement + * block. + * */ public static final JavaBlock EMPTY_JAVABLOCK = new JavaBlock(new StatementBlock()); private final JavaProgramElement prg; - /** create a new JavaBlock + /** + * create a new JavaBlock + * * @param prg the root JavaProgramElement for this JavaBlock */ private JavaBlock(JavaProgramElement prg) { - this.prg=prg; + this.prg = prg; } - /** create a new JavaBlock - * @param prg the root StatementBlock for this JavaBlock. - * TacletIndex relies on prg being indeed a StatementBlock. + /** + * create a new JavaBlock + * + * @param prg the root StatementBlock for this JavaBlock. TacletIndex relies on prg + * being indeed a StatementBlock. */ public static JavaBlock createJavaBlock(StatementBlock prg) { - assert prg != null; - /*if (prg.isEmpty() && ! ) { - return EMPTY_JAVABLOCK; - } */ - return new JavaBlock(prg); + assert prg != null; + /* + * if (prg.isEmpty() && ! ) { return EMPTY_JAVABLOCK; } + */ + return new JavaBlock(prg); } - + public boolean isEmpty() { - if ((program() instanceof StatementBlock)) { - return ((StatementBlock)program()).isEmpty(); - } - return this == EMPTY_JAVABLOCK; + if ((program() instanceof StatementBlock)) { + return ((StatementBlock) program()).isEmpty(); + } + return this == EMPTY_JAVABLOCK; } - + public int size() { - if ((program() instanceof StatementBlock)) { - return ((StatementBlock)program()).getChildCount(); - } - return 0; + if ((program() instanceof StatementBlock)) { + return ((StatementBlock) program()).getChildCount(); + } + return 0; } - + /** returns the hashCode */ - public int hashCode() { - return 17 + ((program()==null) ? 0 : program().hashCode()); + public int hashCode() { + return 17 + ((program() == null) ? 0 : program().hashCode()); } /** returns true iff the program elements are equal */ public boolean equals(Object o) { - if ( o == this ) { + if (o == this) { return true; } else if (!(o instanceof JavaBlock)) { return false; } else { - JavaBlock block = (JavaBlock)o; - - if(block.program() == null){ - return program()==null; - } - else{ - return block.program().equals(program()); + JavaBlock block = (JavaBlock) o; + + if (block.program() == null) { + return program() == null; + } else { + return block.program().equals(program()); } - } + } } - /** returns true if the given ProgramElement is equal to the - * one of the JavaBlock modulo renaming (see comment in SourceElement) - */ - public boolean equalsModRenaming(Object o, - NameAbstractionTable nat) { + /** + * returns true if the given ProgramElement is equal to the one of the JavaBlock modulo renaming + * (see comment in SourceElement) + */ + public boolean equalsModRenaming(Object o, NameAbstractionTable nat) { if (!(o instanceof JavaBlock)) { return false; - } - return equalsModRenaming(((JavaBlock)o).program(), nat); + } + return equalsModRenaming(((JavaBlock) o).program(), nat); } - /** returns true if the given ProgramElement is equal to the - * one of the JavaBlock modulo renaming (see comment in SourceElement) - */ - private boolean equalsModRenaming(JavaProgramElement pe, - NameAbstractionTable nat) { - if (pe == null && program() == null) { - return true; - } else if (pe != null && program() != null) { - return program().equalsModRenaming(pe, nat); - } + /** + * returns true if the given ProgramElement is equal to the one of the JavaBlock modulo renaming + * (see comment in SourceElement) + */ + private boolean equalsModRenaming(JavaProgramElement pe, NameAbstractionTable nat) { + if (pe == null && program() == null) { + return true; + } else if (pe != null && program() != null) { + return program().equalsModRenaming(pe, nat); + } return false; } - /** returns the java program + /** + * returns the java program + * * @return the stored JavaProgramElement */ public JavaProgramElement program() { - return prg; + return prg; } /** toString */ public String toString() { - //if (this==EMPTY_JAVABLOCK) return ""; - StringWriter sw=new StringWriter(); - try { - PrettyPrinter pp=new PrettyPrinter(sw, true); - pp.setIndentationLevel(0); - prg.prettyPrint(pp); - } catch (IOException e) { - LOGGER.warn("toString of JavaBlock failed",e); - } - return sw.toString(); + // if (this==EMPTY_JAVABLOCK) return ""; + StringWriter sw = new StringWriter(); + try { + PrettyPrinter pp = new PrettyPrinter(sw, true); + pp.setIndentationLevel(0); + prg.prettyPrint(pp); + } catch (IOException e) { + LOGGER.warn("toString of JavaBlock failed", e); + } + return sw.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/LabeledTermImpl.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/LabeledTermImpl.java index bc7dcdca9c1..3e0a7302f00 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/LabeledTermImpl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/LabeledTermImpl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.stream.Collectors; @@ -31,15 +34,14 @@ class LabeledTermImpl extends TermImpl { /** * creates an instance of a labeled term. * - * @param op the top level operator - * @param subs the Term that are the subterms of this term + * @param op the top level operator + * @param subs the Term that are the subterms of this term * @param boundVars logic variables bound by the operator * @param javaBlock contains the program part of the term (if any) - * @param labels the terms labels (must not be null or empty) + * @param labels the terms labels (must not be null or empty) */ public LabeledTermImpl(Operator op, ImmutableArray subs, - ImmutableArray boundVars, - JavaBlock javaBlock, + ImmutableArray boundVars, JavaBlock javaBlock, ImmutableArray labels) { super(op, subs, boundVars, javaBlock); assert labels != null : "Term labels must not be null"; @@ -123,9 +125,8 @@ public String toString() { StringBuilder result = new StringBuilder(super.toString()); String labelsStr = labels.stream() - //.filter(TermLabel::isProofRelevant) - .map(TermLabel::toString) - .collect(Collectors.joining(", ")); + // .filter(TermLabel::isProofRelevant) + .map(TermLabel::toString).collect(Collectors.joining(", ")); if (!labelsStr.isEmpty()) { result.append("<<"); @@ -135,4 +136,4 @@ public String toString() { return result.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/LexPathOrdering.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/LexPathOrdering.java index 51784fd6000..ff486edfd6f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/LexPathOrdering.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/LexPathOrdering.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.math.BigInteger; @@ -23,11 +26,11 @@ */ public class LexPathOrdering implements TermOrdering { - public int compare (Term p_a, Term p_b) { - final CompRes res = compareHelp ( p_a, p_b ); - if ( res.lt () ) + public int compare(Term p_a, Term p_b) { + final CompRes res = compareHelp(p_a, p_b); + if (res.lt()) return -1; - else if ( res.gt () ) + else if (res.gt()) return 1; else return 0; @@ -37,88 +40,120 @@ private abstract static class CompRes { // used in anonymous classes inheriting from CompRes @SuppressWarnings("unused") - public boolean uncomparable () { return false; } - public boolean eq () { return false; } - public boolean gt () { return false; } - public boolean lt () { return false; } - public boolean geq() { return gt() || eq(); } + public boolean uncomparable() { + return false; + } + + public boolean eq() { + return false; + } + + public boolean gt() { + return false; + } + + public boolean lt() { + return false; + } + + public boolean geq() { + return gt() || eq(); + } + // kept for symmetry reasons @SuppressWarnings("unused") - public boolean leq () { return lt() || eq(); } + public boolean leq() { + return lt() || eq(); + } } - private final static CompRes UNCOMPARABLE = new CompRes () { - public boolean uncomparable() { return true; } + private final static CompRes UNCOMPARABLE = new CompRes() { + public boolean uncomparable() { + return true; + } }; - private final static CompRes EQUALS = new CompRes () { - public boolean eq() { return true; } + private final static CompRes EQUALS = new CompRes() { + public boolean eq() { + return true; + } }; - private final static CompRes GREATER = new CompRes () { - public boolean gt() { return true; } + private final static CompRes GREATER = new CompRes() { + public boolean gt() { + return true; + } }; - private final static CompRes LESS = new CompRes () { - public boolean lt() { return true; } + private final static CompRes LESS = new CompRes() { + public boolean lt() { + return true; + } }; - - + + private final static class CacheKey { public final Term left; public final Term right; - - public CacheKey (final Term left, final Term right) { + + public CacheKey(final Term left, final Term right) { this.left = left; this.right = right; } - - public boolean equals (Object arg0) { - if ( !( arg0 instanceof CacheKey ) ) return false; - final CacheKey key0 = (CacheKey)arg0; - return left.equals ( key0.left ) && right.equals ( key0.right ); + + public boolean equals(Object arg0) { + if (!(arg0 instanceof CacheKey)) + return false; + final CacheKey key0 = (CacheKey) arg0; + return left.equals(key0.left) && right.equals(key0.right); } - - public int hashCode () { - return left.hashCode () + 2 * right.hashCode (); + + public int hashCode() { + return left.hashCode() + 2 * right.hashCode(); } } - - - private final HashMap cache = - new LinkedHashMap (); - - - private CompRes compareHelp (Term p_a, Term p_b) { - final CacheKey key = new CacheKey ( p_a, p_b ); - CompRes res = cache.get ( key ); - if ( res == null ) { - res = compareHelp2 ( p_a, p_b ); - if ( cache.size () > 100000 ) cache.clear (); - cache.put ( key, res ); + + + private final HashMap cache = new LinkedHashMap(); + + + private CompRes compareHelp(Term p_a, Term p_b) { + final CacheKey key = new CacheKey(p_a, p_b); + CompRes res = cache.get(key); + if (res == null) { + res = compareHelp2(p_a, p_b); + if (cache.size() > 100000) + cache.clear(); + cache.put(key, res); } return res; } - private CompRes compareHelp2 (Term p_a, Term p_b) { - - if ( oneSubGeq ( p_a, p_b ) ) return GREATER; - if ( oneSubGeq ( p_b, p_a ) ) return LESS; - - final int opComp = compare ( p_a.op (), p_a.sort (), p_a.getLabels (), - p_b.op (), p_b.sort (), p_b.getLabels () ); - if ( opComp == 0 ) { - final CompRes lexComp = compareSubsLex ( p_a, p_b ); - if ( lexComp.eq () ) { + private CompRes compareHelp2(Term p_a, Term p_b) { + + if (oneSubGeq(p_a, p_b)) + return GREATER; + if (oneSubGeq(p_b, p_a)) + return LESS; + + final int opComp = compare(p_a.op(), p_a.sort(), p_a.getLabels(), p_b.op(), p_b.sort(), + p_b.getLabels()); + if (opComp == 0) { + final CompRes lexComp = compareSubsLex(p_a, p_b); + if (lexComp.eq()) { return EQUALS; - } else if ( lexComp.gt () ) { - if ( greaterThanSubs ( p_a, p_b, 1 ) ) return GREATER; - } else if ( lexComp.lt () ) { - if ( greaterThanSubs ( p_b, p_a, 1 ) ) return LESS; + } else if (lexComp.gt()) { + if (greaterThanSubs(p_a, p_b, 1)) + return GREATER; + } else if (lexComp.lt()) { + if (greaterThanSubs(p_b, p_a, 1)) + return LESS; } } - - if ( opComp > 0 ) { - if ( greaterThanSubs ( p_a, p_b, 0 ) ) return GREATER; + + if (opComp > 0) { + if (greaterThanSubs(p_a, p_b, 0)) + return GREATER; } else { - if ( greaterThanSubs ( p_b, p_a, 0 ) ) return LESS; + if (greaterThanSubs(p_b, p_a, 0)) + return LESS; } return UNCOMPARABLE; @@ -127,85 +162,94 @@ private CompRes compareHelp2 (Term p_a, Term p_b) { private CompRes compareSubsLex(Term p_a, Term p_b) { int i = 0; - while ( true ) { - if ( i >= p_a.arity () ) { - if ( i >= p_b.arity () ) + while (true) { + if (i >= p_a.arity()) { + if (i >= p_b.arity()) return EQUALS; else return LESS; } - if ( i >= p_b.arity () ) return GREATER; + if (i >= p_b.arity()) + return GREATER; - final CompRes subRes = compareHelp ( p_a.sub ( i ), p_b.sub ( i ) ); - if ( !subRes.eq () ) return subRes; + final CompRes subRes = compareHelp(p_a.sub(i), p_b.sub(i)); + if (!subRes.eq()) + return subRes; ++i; } } - - private boolean greaterThanSubs (Term p_a, Term p_b, int firstSub) { - for ( int i = firstSub; i < p_b.arity (); ++i ) { - if ( !compareHelp ( p_a, p_b.sub ( i ) ).gt () ) return false; + + private boolean greaterThanSubs(Term p_a, Term p_b, int firstSub) { + for (int i = firstSub; i < p_b.arity(); ++i) { + if (!compareHelp(p_a, p_b.sub(i)).gt()) + return false; } return true; } - private boolean oneSubGeq (Term p_a, Term p_b) { - for ( int i = 0; i != p_a.arity (); ++i ) { - if ( compareHelp ( p_a.sub ( i ), p_b ).geq () ) return true; + private boolean oneSubGeq(Term p_a, Term p_b) { + for (int i = 0; i != p_a.arity(); ++i) { + if (compareHelp(p_a.sub(i), p_b).geq()) + return true; } return false; } - + /** * Compare the two given symbols - * - * @return a number negative, zero or a number positive if p_a - * is less than, equal, or greater than p_b + * + * @return a number negative, zero or a number positive if p_a is less than, equal, + * or greater than p_b */ - private int compare (Operator aOp, - Sort aSort, - ImmutableArray aLabels, - Operator bOp, - Sort bSort, - ImmutableArray bLabels) { - if ( aOp == bOp ) return 0; + private int compare(Operator aOp, Sort aSort, ImmutableArray aLabels, Operator bOp, + Sort bSort, ImmutableArray bLabels) { + if (aOp == bOp) + return 0; // Search for literals - int v = literalWeighter.compareWeights ( aOp, bOp ); - if ( v != 0 ) return v; + int v = literalWeighter.compareWeights(aOp, bOp); + if (v != 0) + return v; - if ( isVar ( aOp ) ) { - if ( !isVar ( bOp ) ) return 1; + if (isVar(aOp)) { + if (!isVar(bOp)) + return 1; } else { - if ( isVar ( bOp ) ) return -1; + if (isVar(bOp)) + return -1; } - + // compare the sorts of the symbols: more specific sorts are smaller - v = getSortDepth ( bSort ) - getSortDepth ( aSort ); - if ( v != 0 ) return v; + v = getSortDepth(bSort) - getSortDepth(aSort); + if (v != 0) + return v; // Search for special function symbols - v = functionWeighter.compareWeights ( aOp, bOp ); - if ( v != 0 ) return v; + v = functionWeighter.compareWeights(aOp, bOp); + if (v != 0) + return v; // smaller arity is smaller - v = aOp.arity () - bOp.arity (); - if ( v != 0 ) return v; + v = aOp.arity() - bOp.arity(); + if (v != 0) + return v; // compare anonHeap labels: if only one term has an anonHeap label, // then this is smaller v = (aLabels.contains(ParameterlessTermLabel.ANON_HEAP_LABEL) ? -1 : 0); v += (bLabels.contains(ParameterlessTermLabel.ANON_HEAP_LABEL) ? 1 : 0); - if ( v != 0 ) return v; + if (v != 0) + return v; // use the names of the symbols - v = aOp.name ().compareTo ( bOp.name () ); - if ( v != 0 ) return v; + v = aOp.name().compareTo(bOp.name()); + if (v != 0) + return v; // HACK: compare the hash values of the two symbols - //return sign ( bOp.hashCode () - aOp.hashCode () ); + // return sign ( bOp.hashCode () - aOp.hashCode () ); // The two functions have the same name, consider them // equal for the sake of this comparison. // Otherwise the proof is indeterministic as the hash @@ -213,86 +257,85 @@ private int compare (Operator aOp, return 0; } - + /** - * Hashmap from Sort to Integer, storing the - * lengths of maximal paths from a sort to the top element of the sort - * lattice. + * Hashmap from Sort to Integer, storing the lengths of maximal paths + * from a sort to the top element of the sort lattice. */ - private final WeakHashMap sortDepthCache = - new WeakHashMap (); - + private final WeakHashMap sortDepthCache = new WeakHashMap(); + /** - * @return the length of the longest path from s to the top - * element of the sort lattice. Probably this length is not computed - * correctly here, because the representation of sorts in key is - * completely messed up, but you get the idea + * @return the length of the longest path from s to the top element of the sort + * lattice. Probably this length is not computed correctly here, because the + * representation of sorts in key is completely messed up, but you get the idea */ private int getSortDepth(Sort s) { - Integer res = sortDepthCache.get ( s ); - if ( res == null ) { - res = Integer.valueOf ( getSortDepthHelp ( s ) ); - sortDepthCache.put ( s, res ); + Integer res = sortDepthCache.get(s); + if (res == null) { + res = Integer.valueOf(getSortDepthHelp(s)); + sortDepthCache.put(s, res); } - return res.intValue (); + return res.intValue(); } - + private int getSortDepthHelp(Sort s) { int res = -1; // HACKish: ensure that object sorts are bigger than primitive sorts - final String sName = s.name ().toString (); - if ( "int".equals ( sName ) ) res = 10000; - if ( "boolean".equals ( sName ) ) res = 20000; - if ( s instanceof NullSort ) return 30000; + final String sName = s.name().toString(); + if ("int".equals(sName)) + res = 10000; + if ("boolean".equals(sName)) + res = 20000; + if (s instanceof NullSort) + return 30000; - for (Sort sort : s.extendsSorts()) res = Math.max(res, getSortDepth(sort)); + for (Sort sort : s.extendsSorts()) + res = Math.max(res, getSortDepth(sort)); return res + 1; } - + //////////////////////////////////////////////////////////////////////////// - + /** * Base class for metrics on symbols that are used to construct an ordering */ private static abstract class Weighter { - + /** - * Compare the weights of two symbols using the function - * getWeight. - * - * @return a number negative, zero or a number positive if the weight of - * p_a is less than, equal, or greater than the - * weight of p_b + * Compare the weights of two symbols using the function getWeight. + * + * @return a number negative, zero or a number positive if the weight of p_a is + * less than, equal, or greater than the weight of p_b */ public int compareWeights(Operator p_a, Operator p_b) { - final Integer aWeight = getWeight ( p_a ); - final Integer bWeight = getWeight ( p_b ); - - if ( aWeight == null ) { - if ( bWeight == null ) + final Integer aWeight = getWeight(p_a); + final Integer bWeight = getWeight(p_b); + + if (aWeight == null) { + if (bWeight == null) return 0; else return 1; } else { - if ( bWeight == null ) + if (bWeight == null) return -1; else - return aWeight.intValue () - bWeight.intValue (); + return aWeight.intValue() - bWeight.intValue(); } } - + protected abstract Integer getWeight(Operator p_op); } - + /** - * Explicit ordering of literals (symbols assigned a weight by this - * class are regarded as smaller than all other symbols) + * Explicit ordering of literals (symbols assigned a weight by this class are regarded as + * smaller than all other symbols) */ private static class LiteralWeighter extends Weighter { - private final Set intFunctionNames = new LinkedHashSet (); + private final Set intFunctionNames = new LinkedHashSet(); { intFunctionNames.add("#"); intFunctionNames.add("0"); @@ -309,28 +352,28 @@ private static class LiteralWeighter extends Weighter { intFunctionNames.add("neglit"); } - private final Set theoryFunctionNames = new LinkedHashSet (); + private final Set theoryFunctionNames = new LinkedHashSet(); { theoryFunctionNames.add("C"); theoryFunctionNames.add("seqEmpty"); theoryFunctionNames.add("empty"); - theoryFunctionNames.add("strPool"); + theoryFunctionNames.add("strPool"); } - + protected Integer getWeight(Operator p_op) { - final String opStr = p_op.name ().toString (); + final String opStr = p_op.name().toString(); + + if (intFunctionNames.contains(opStr) || theoryFunctionNames.contains(opStr)) + return Integer.valueOf(0); - if (intFunctionNames.contains ( opStr ) || theoryFunctionNames.contains ( opStr )) - return Integer.valueOf ( 0 ); - if (opStr.equals("allLocs")) { return Integer.valueOf(1); } else if (opStr.equals("allObjects")) { - return Integer.valueOf(2); + return Integer.valueOf(2); } else if (opStr.equals("allFields")) { return Integer.valueOf(3); } else if (opStr.equals("singleton")) { @@ -338,119 +381,130 @@ protected Integer getWeight(Operator p_op) { } else if (opStr.equals("freshLocs")) { return Integer.valueOf(5); } - - if ( opStr.equals ( "neg" ) ) return Integer.valueOf ( 1 ); - - if ( p_op.name ().equals ( IntegerLDT.CHAR_ID_NAME ) ) - return Integer.valueOf ( 1 ); - if ( p_op instanceof Function - && ( (Function)p_op ).sort () instanceof NullSort ) - return Integer.valueOf ( 2 ); - if ( p_op instanceof Function - && ( opStr.equals ( "TRUE" ) || opStr.equals ( "FALSE" ) ) ) - return Integer.valueOf ( 3 ); - - if ( opStr.equals ( "add" ) ) return Integer.valueOf ( 6 ); - if ( opStr.equals ( "mul" ) ) return Integer.valueOf ( 7 ); - if ( opStr.equals ( "div" ) ) return Integer.valueOf ( 8 ); - if ( opStr.equals ( "jdiv" ) ) return Integer.valueOf ( 9 ); - - - if ( opStr.equals ("intersect")) return Integer.valueOf ( 6 ); - if ( opStr.equals ("union")) return Integer.valueOf ( 7 ); - if ( opStr.equals ("infiniteUnion")) return Integer.valueOf ( 8 ); - if ( opStr.equals ("setMinus")) return Integer.valueOf ( 9 ); - - - if ( opStr.equals ("seqSingleton")) return Integer.valueOf ( 6 ); - if ( opStr.equals ("seqConcat")) return Integer.valueOf ( 7 ); + + if (opStr.equals("neg")) + return Integer.valueOf(1); + + if (p_op.name().equals(IntegerLDT.CHAR_ID_NAME)) + return Integer.valueOf(1); + if (p_op instanceof Function && ((Function) p_op).sort() instanceof NullSort) + return Integer.valueOf(2); + if (p_op instanceof Function && (opStr.equals("TRUE") || opStr.equals("FALSE"))) + return Integer.valueOf(3); + + if (opStr.equals("add")) + return Integer.valueOf(6); + if (opStr.equals("mul")) + return Integer.valueOf(7); + if (opStr.equals("div")) + return Integer.valueOf(8); + if (opStr.equals("jdiv")) + return Integer.valueOf(9); + + + if (opStr.equals("intersect")) + return Integer.valueOf(6); + if (opStr.equals("union")) + return Integer.valueOf(7); + if (opStr.equals("infiniteUnion")) + return Integer.valueOf(8); + if (opStr.equals("setMinus")) + return Integer.valueOf(9); + + + if (opStr.equals("seqSingleton")) + return Integer.valueOf(6); + if (opStr.equals("seqConcat")) + return Integer.valueOf(7); return null; } } /** - * Explicit ordering for different kinds of function symbols; symbols like - * C:: or C. should be smaller than other symbols + * Explicit ordering for different kinds of function symbols; symbols like C:: or + * C. should be smaller than other symbols */ private static class FunctionWeighter extends Weighter { protected Integer getWeight(Operator p_op) { - final String opStr = p_op.name ().toString (); + final String opStr = p_op.name().toString(); - if ( opStr.equals("heap")) return Integer.valueOf(0); - if ( p_op instanceof Function && ((Function)p_op).isUnique()) return Integer.valueOf(5); - if ( opStr.equals("pair")) return Integer.valueOf(10); - - -/* if ( p_op instanceof SortDependingSymbol ) return new Integer ( 10 ); + if (opStr.equals("heap")) + return Integer.valueOf(0); + if (p_op instanceof Function && ((Function) p_op).isUnique()) + return Integer.valueOf(5); + if (opStr.equals("pair")) + return Integer.valueOf(10); - if ( p_op instanceof AttributeOp ) return new Integer ( 20 ); - if ( p_op instanceof ProgramVariable ) { - final ProgramVariable var = (ProgramVariable)p_op; - if ( var.isStatic () ) return new Integer ( 30 ); - if ( var.isMember () ) return new Integer ( 31 ); - return new Integer ( 32 ); - } */ + /* + * if ( p_op instanceof SortDependingSymbol ) return new Integer ( 10 ); + * + * if ( p_op instanceof AttributeOp ) return new Integer ( 20 ); + * + * if ( p_op instanceof ProgramVariable ) { final ProgramVariable var = + * (ProgramVariable)p_op; if ( var.isStatic () ) return new Integer ( 30 ); if ( + * var.isMember () ) return new Integer ( 31 ); return new Integer ( 32 ); } + */ - return null; + return null; } } - - private final Weighter literalWeighter = new LiteralWeighter (); - private final Weighter functionWeighter = new FunctionWeighter (); - + + private final Weighter literalWeighter = new LiteralWeighter(); + private final Weighter functionWeighter = new FunctionWeighter(); + //////////////////////////////////////////////////////////////////////////// - + /** * @return true iff op is a logic variable */ - private boolean isVar (Operator op) { + private boolean isVar(Operator op) { return op instanceof QuantifiableVariable; } /** * TODO: this should also be used when comparing terms - * - * The reduction ordering on integers that is described in "A - * critical-pair/completion algorithm for finitely generated ideals in - * rings", with the difference that positive numbers are here considered as - * smaller than negative numbers (with the same absolute value) - * - * @return a negative number, zero, or a positive number, if a - * is smaller, equal to or greater than b + * + * The reduction ordering on integers that is described in "A critical-pair/completion algorithm + * for finitely generated ideals in rings", with the difference that positive numbers are here + * considered as smaller than negative numbers (with the same absolute value) + * + * @return a negative number, zero, or a positive number, if a is smaller, equal to + * or greater than b */ public static int compare(BigInteger a, BigInteger b) { - final int c = a.abs ().compareTo ( b.abs () ); - if ( c != 0 ) return c; - return b.signum () - a.signum (); + final int c = a.abs().compareTo(b.abs()); + if (c != 0) + return c; + return b.signum() - a.signum(); } - + /** - * @return the result of dividing a by c, - * such that the remainder becomes minimal in the reduction ordering - * LexPathOrdering.compare on integers + * @return the result of dividing a by c, such that the remainder + * becomes minimal in the reduction ordering LexPathOrdering.compare on + * integers */ public static BigInteger divide(BigInteger a, BigInteger c) { - final BigInteger[] divRem = a.divideAndRemainder ( c ); - while ( true ) { + final BigInteger[] divRem = a.divideAndRemainder(c); + while (true) { // could be done more efficiently. but apparently the rounding // behaviour of BigInteger.divide for negative numbers is not // properly specified. or everything becomes very tedious ... - - final BigInteger newRem1 = divRem[1].subtract ( c ); - if ( compare ( newRem1, divRem[1] ) < 0 ) { - divRem[0] = divRem[0].add ( BigInteger.ONE ); + + final BigInteger newRem1 = divRem[1].subtract(c); + if (compare(newRem1, divRem[1]) < 0) { + divRem[0] = divRem[0].add(BigInteger.ONE); divRem[1] = newRem1; continue; } - final BigInteger newRem2 = divRem[1].add ( c ); - if ( compare ( newRem2, divRem[1] ) < 0 ) { - divRem[0] = divRem[0].subtract ( BigInteger.ONE ); + final BigInteger newRem2 = divRem[1].add(c); + if (compare(newRem2, divRem[1]) < 0) { + divRem[0] = divRem[0].subtract(BigInteger.ONE); divRem[1] = newRem2; continue; } - + return divRem[0]; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/MethodStackInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/MethodStackInfo.java index fb1f7562684..3dc47eac6ce 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/MethodStackInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/MethodStackInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableArray; @@ -15,24 +18,25 @@ public static NameCreationInfo create(ProgramElement program) { } private final ProgramElement element; - - + + public MethodStackInfo(ProgramElement element) { this.element = element; } - + /** - * returns the method call stack + * returns the method call stack */ public ImmutableList getMethodStack() { - ImmutableList list = ImmutableSLList.nil(); + ImmutableList list = ImmutableSLList.nil(); if (element instanceof ProgramPrefix) { - final ImmutableArray prefix = ((ProgramPrefix) element).getPrefixElements(); - for (int i = prefix.size() - 1; i>=0; i--) { - if(prefix.get(i) instanceof MethodFrame) { - final MethodFrame frame = (MethodFrame)prefix.get(i); + final ImmutableArray prefix = + ((ProgramPrefix) element).getPrefixElements(); + for (int i = prefix.size() - 1; i >= 0; i--) { + if (prefix.get(i) instanceof MethodFrame) { + final MethodFrame frame = (MethodFrame) prefix.get(i); IProgramMethod method = frame.getProgramMethod(); - if(method != null) { + if (method != null) { list = list.prepend(method); } } @@ -41,7 +45,7 @@ public ImmutableList getMethodStack() { return list; } - + public String infoAsString() { String result = "Method stack:\n"; @@ -49,7 +53,8 @@ public String infoAsString() { result += "- " + method.getProgramElementName().toString() + "\n"; } - if(result.length() < 1) return ""; + if (result.length() < 1) + return ""; result = result.substring(0, result.length() - 1); @@ -58,4 +63,4 @@ public String infoAsString() { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/MultiRenamingTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/MultiRenamingTable.java index 4190324649c..6b5642829ed 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/MultiRenamingTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/MultiRenamingTable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashMap; @@ -7,28 +10,28 @@ -public class MultiRenamingTable extends RenamingTable{ +public class MultiRenamingTable extends RenamingTable { private final HashMap hmap; - public MultiRenamingTable(HashMap hmap){ - this.hmap = hmap; + public MultiRenamingTable(HashMap hmap) { + this.hmap = hmap; } - public SourceElement getRenaming(SourceElement se){ - return hmap.get(se); + public SourceElement getRenaming(SourceElement se) { + return hmap.get(se); } - public Iterator getRenamingIterator(){ - return hmap.keySet().iterator(); + public Iterator getRenamingIterator() { + return hmap.keySet().iterator(); } - - public String toString(){ - return ("MultiRenamingTable: "+hmap); + + public String toString() { + return ("MultiRenamingTable: " + hmap); } - - public HashMap getHashMap(){ + + public HashMap getHashMap() { return hmap; } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Name.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Name.java index b7f24bd3ad7..39792bef25d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Name.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Name.java @@ -1,50 +1,53 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** - * A Name object is created to represent the name of an object which usually - * implements the interface {@link Named}. - * + * A Name object is created to represent the name of an object which usually implements the + * interface {@link Named}. + * *

    - * It wraps a string object. To save memory and to speed up equality checks, the - * wrapped strings are stored in their {@linkplain String#intern() interned} - * representation. + * It wraps a string object. To save memory and to speed up equality checks, the wrapped strings are + * stored in their {@linkplain String#intern() interned} representation. */ public class Name implements Comparable { private static final String NONAME = "_noname_"; - private final /** Interned */ String nameString; - + private final /** Interned */ + String nameString; + /** * creates a name object */ public Name(String n) { - nameString = (n == null ? NONAME : n).intern(); + nameString = (n == null ? NONAME : n).intern(); } @Override public String toString() { - return nameString; + return nameString; } @Override public boolean equals(Object o) { - if (!(o instanceof Name)) { - return false; - } - // since ALL nameStrings are interned, equality can be safely reduced to - // identity in THIS case: - return nameString == ((Name) o).nameString; + if (!(o instanceof Name)) { + return false; + } + // since ALL nameStrings are interned, equality can be safely reduced to + // identity in THIS case: + return nameString == ((Name) o).nameString; } @Override public int compareTo(Name o) { - return nameString.compareTo(o.nameString); + return nameString.compareTo(o.nameString); } - + @Override public int hashCode() { - return nameString.hashCode(); + return nameString.hashCode(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/NameCreationInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/NameCreationInfo.java index 3520711fbba..adbdd01b456 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/NameCreationInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/NameCreationInfo.java @@ -1,5 +1,8 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; public interface NameCreationInfo { String infoAsString(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Named.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Named.java index dc0d3f651cf..df92436c19f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Named.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Named.java @@ -1,15 +1,19 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** - * This interface has to be implemented by all logic signature elements, which - * are identified by their name. + * This interface has to be implemented by all logic signature elements, which are identified by + * their name. */ public interface Named { /** * returns the name of this element + * * @return the name of the element */ Name name(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Namespace.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Namespace.java index 4ff0052a936..f08f41c6848 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Namespace.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Namespace.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.ArrayList; @@ -13,10 +16,9 @@ import javax.annotation.Nullable; /** - * A Namespace keeps track of already used {@link Name}s and the objects - * carrying these names. These objects have to implement the interface - * {@link Named}. It is possible to have nested namespaces in order to - * represent different visibility scopes. + * A Namespace keeps track of already used {@link Name}s and the objects carrying these names. These + * objects have to implement the interface {@link Named}. It is possible to have nested namespaces + * in order to represent different visibility scopes. */ public class Namespace implements java.io.Serializable { @@ -29,14 +31,13 @@ public class Namespace implements java.io.Serializable { private Namespace parent; /** - * The map that maps a name to a symbols of that name if it is defined in - * this Namespace. + * The map that maps a name to a symbols of that name if it is defined in this Namespace. */ private Map symbols; /** - * A namespace can be made immutable, this is called "sealing". This flag - * indicates whether this namespace has been sealed or not. + * A namespace can be made immutable, this is called "sealing". This flag indicates whether this + * namespace has been sealed or not. */ private boolean sealed; @@ -48,42 +49,41 @@ public Namespace() { } /** - * Construct a Namespace that uses parent as a fallback - * for finding symbols not defined in this one. + * Construct a Namespace that uses parent as a fallback for finding symbols not + * defined in this one. */ public Namespace(Namespace parent) { this.parent = parent; } /** - * Adds the object sym to this Namespace. - * If an object with the same name is already there, it is quietly - * replaced by sym. Use addSafely() instead if possible. + * Adds the object sym to this Namespace. If an object with the same name is + * already there, it is quietly replaced by sym. Use addSafely() instead if + * possible. * - * TODO:The problem of saving to localSym, symbols, and symbolRefs is not solved yet. - * (This is no longer self-explanatory. mu 2016) + * TODO:The problem of saving to localSym, symbols, and symbolRefs is not solved yet. (This is + * no longer self-explanatory. mu 2016) * - * If the local table is empty, then the new symbol is added as - * "singleton map". This has been adapted from an earlier - * implementation, done for memory efficiency reasons: Many namespaces - * only contain a single element; no need to allocate a hash map. - * The hash map is only created when the 2nd element is added. + * If the local table is empty, then the new symbol is added as "singleton map". This has been + * adapted from an earlier implementation, done for memory efficiency reasons: Many namespaces + * only contain a single element; no need to allocate a hash map. The hash map is only created + * when the 2nd element is added. * * This is not threadsafe. */ public void add(E sym) { - if(sealed) { + if (sealed) { LOGGER.warn("Namespace is SEALED"); - throw new IllegalStateException("This namespace has been sealed; addition is not possible."); + throw new IllegalStateException( + "This namespace has been sealed; addition is not possible."); } - /* TODO ulbrich: Investigate in a future version - Named old = lookup(sym.name()); - if(old != null && old != sym) { - LOGGER.warn("Clash! Name already used: " + sym.name().toString()); - } - */ + /* + * TODO ulbrich: Investigate in a future version Named old = lookup(sym.name()); if(old != + * null && old != sym) { LOGGER.warn("Clash! Name already used: " + sym.name().toString()); + * } + */ if (symbols == null) { symbols = Collections.singletonMap(sym.name(), sym); @@ -107,15 +107,13 @@ public void add(Iterable list) { } /** - * Adds the object sym to this namespace. - * Throws a runtime exception if an object with the same name is - * already there. + * Adds the object sym to this namespace. Throws a runtime exception if an object + * with the same name is already there. */ public void addSafely(E sym) { Named old = lookup(sym.name()); - if(old != null && old != sym) { - throw new RuntimeException("Name already in namespace: " - + sym.name()); + if (old != null && old != sym) { + throw new RuntimeException("Name already in namespace: " + sym.name()); } add(sym); @@ -134,13 +132,13 @@ public void addSafely(Iterable names) { * * @param name non-null name whose symbol is to be removed. */ - public void remove(Name name){ - if(symbols != null){ + public void remove(Name name) { + if (symbols != null) { symbols.remove(name); } } - protected E lookupLocally(Name name){ + protected E lookupLocally(Name name) { if (symbols != null) { return symbols.get(name); } else { @@ -149,8 +147,9 @@ protected E lookupLocally(Name name){ } - /** creates a new Namespace that has this as parent, and contains - * an entry for sym. + /** + * creates a new Namespace that has this as parent, and contains an entry for sym. + * * @return the new Namespace */ public Namespace extended(E sym) { @@ -163,13 +162,12 @@ public Namespace extended(Iterable ext) { return result; } - /** - * looks if a registered object is declared in this namespace, if - * negative it asks its parent - * @param name a Name representing the name of the symbol to look for - * @return Object with name "name" or null if no such an object - * has been found - */ + /** + * looks if a registered object is declared in this namespace, if negative it asks its parent + * + * @param name a Name representing the name of the symbol to look for + * @return Object with name "name" or null if no such an object has been found + */ public @Nullable E lookup(Name name) { E symbol = lookupLocally(name); if (symbol != null) { @@ -184,49 +182,53 @@ public Namespace extended(Iterable ext) { } /** Convenience method to look up. */ - public E lookup(String name){ + public E lookup(String name) { return lookup(new Name(name)); } - /** returns list of the elements (not the keys) in this - * namespace (not about the one of the parent) + /** + * returns list of the elements (not the keys) in this namespace (not about the one of the + * parent) + * * @return the list of the named objects */ public Collection elements() { - if(symbols == null) { + if (symbols == null) { return Collections.emptyList(); } else { - return Collections.unmodifiableCollection(symbols.values()); - } + return Collections.unmodifiableCollection(symbols.values()); + } } public Collection allElements() { - if (parent==null) { - return new ArrayList<>(elements()); - } else { - Collection result = parent().allElements(); - result.addAll(elements()); - return result; - } + if (parent == null) { + return new ArrayList<>(elements()); + } else { + Collection result = parent().allElements(); + result.addAll(elements()); + return result; + } } - /** returns the fall-back Namespace of this Namespace, i.e. the one - * where symbols are looked up that are not found in this one. + /** + * returns the fall-back Namespace of this Namespace, i.e. the one where symbols are looked up + * that are not found in this one. */ public Namespace parent() { - return parent; + return parent; } public String toString() { - String res="Namespace: [local:" + symbols; - if (parent!=null) res=res+"; parent:"+parent; - return res+"]"; + String res = "Namespace: [local:" + symbols; + if (parent != null) + res = res + "; parent:" + parent; + return res + "]"; } public Namespace copy() { Namespace copy = new Namespace<>(parent); - if(symbols != null) + if (symbols != null) copy.add(symbols.values()); return copy; @@ -281,7 +283,7 @@ public void flushToParent() { for (E element : elements()) { parent.add(element); } -// all symbols are contained in parent now ... we are empty again. + // all symbols are contained in parent now ... we are empty again. symbols = null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/NamespaceSet.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/NamespaceSet.java index d6b08d570b8..d94d51d5894 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/NamespaceSet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/NamespaceSet.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.logic.op.Function; @@ -15,149 +18,122 @@ public class NamespaceSet { private Namespace sortNS = new Namespace(); private Namespace choiceNS = new Namespace(); - public NamespaceSet() { - } + public NamespaceSet() {} - public NamespaceSet(Namespace varNS, - Namespace funcNS, - Namespace sortNS, - Namespace ruleSetNS, - Namespace choiceNS, - Namespace programVarNS) { - this.varNS = varNS; - this.progVarNS = programVarNS; - this.funcNS = funcNS; - this.sortNS = sortNS; - this.ruleSetNS = ruleSetNS; - this.choiceNS = choiceNS; + public NamespaceSet(Namespace varNS, Namespace funcNS, + Namespace sortNS, Namespace ruleSetNS, Namespace choiceNS, + Namespace programVarNS) { + this.varNS = varNS; + this.progVarNS = programVarNS; + this.funcNS = funcNS; + this.sortNS = sortNS; + this.ruleSetNS = ruleSetNS; + this.choiceNS = choiceNS; } public NamespaceSet copy() { - return new NamespaceSet( - variables().copy(), - functions().copy(), - sorts().copy(), - ruleSets().copy(), - choices().copy(), - programVariables().copy()); + return new NamespaceSet(variables().copy(), functions().copy(), sorts().copy(), + ruleSets().copy(), choices().copy(), programVariables().copy()); } public NamespaceSet shallowCopy() { - return new NamespaceSet( - variables(), - functions(), - sorts(), - ruleSets(), - choices(), + return new NamespaceSet(variables(), functions(), sorts(), ruleSets(), choices(), programVariables()); } // TODO MU: Rename into sth with wrap or similar public NamespaceSet copyWithParent() { - return new NamespaceSet( - new Namespace(variables()), - new Namespace(functions()), - new Namespace(sorts()), - new Namespace(ruleSets()), - new Namespace(choices()), - new Namespace(programVariables()) - ); + return new NamespaceSet(new Namespace(variables()), + new Namespace(functions()), new Namespace(sorts()), + new Namespace(ruleSets()), new Namespace(choices()), + new Namespace(programVariables())); } public Namespace variables() { - return varNS; + return varNS; } public void setVariables(Namespace varNS) { - this.varNS = varNS; + this.varNS = varNS; } public Namespace programVariables() { - return progVarNS; + return progVarNS; } public void setProgramVariables(Namespace progVarNS) { - this.progVarNS = progVarNS; + this.progVarNS = progVarNS; } public Namespace functions() { - return funcNS; + return funcNS; } public void setFunctions(Namespace funcNS) { - this.funcNS = funcNS; + this.funcNS = funcNS; } public Namespace ruleSets() { - return ruleSetNS; + return ruleSetNS; } public void setRuleSets(Namespace ruleSetNS) { - this.ruleSetNS = ruleSetNS; + this.ruleSetNS = ruleSetNS; } public Namespace sorts() { - return sortNS; + return sortNS; } public void setSorts(Namespace sortNS) { - this.sortNS = sortNS; + this.sortNS = sortNS; } public Namespace choices() { - return choiceNS; + return choiceNS; } public void setChoices(Namespace choiceNS) { - this.choiceNS = choiceNS; + this.choiceNS = choiceNS; } public void add(NamespaceSet ns) { - variables().add(ns.variables()); - programVariables().add(ns.programVariables()); - sorts().add(ns.sorts()); - ruleSets().add(ns.ruleSets()); - functions().add(ns.functions()); - choices().add(ns.choices()); + variables().add(ns.variables()); + programVariables().add(ns.programVariables()); + sorts().add(ns.sorts()); + ruleSets().add(ns.ruleSets()); + functions().add(ns.functions()); + choices().add(ns.choices()); } /** * returns all namespaces in an array */ private Namespace[] asArray() { - return new Namespace[]{variables(), - programVariables(), - sorts(), - ruleSets(), - functions(), - choices() - }; + return new Namespace[] { variables(), programVariables(), sorts(), ruleSets(), functions(), + choices() }; } /** - * returns all namespaces with symbols that may occur - * in a real sequent (this means all namespaces without - * variables, choices and ruleSets) + * returns all namespaces with symbols that may occur in a real sequent (this means all + * namespaces without variables, choices and ruleSets) */ private Namespace[] logicAsArray() { - return new Namespace[]{ - programVariables(), sorts(), functions() - }; + return new Namespace[] { programVariables(), sorts(), functions() }; } /** - * looks up if the given name is found in one of the namespaces - * and returns the named object or null if no object with the same name - * has been found + * looks up if the given name is found in one of the namespaces and returns the named object or + * null if no object with the same name has been found */ public Named lookup(Name name) { - final Namespace[] spaces = asArray(); - return lookup(name, spaces); + final Namespace[] spaces = asArray(); + return lookup(name, spaces); } /** - * looks up for the symbol in the namespaces sort, functions and - * programVariables + * looks up for the symbol in the namespaces sort, functions and programVariables + * * @param name the Name to look up * @return the element of the given name or null */ @@ -168,13 +144,14 @@ public Named lookupLogicSymbol(Name name) { /** * @param name * @param spaces - * @return the element with the given name if found in the - * given namespaces, otherwise null + * @return the element with the given name if found in the given namespaces, otherwise + * null */ private Named lookup(Name name, final Namespace[] spaces) { for (Namespace space : spaces) { final Named n = space.lookup(name); - if (n != null) return n; + if (n != null) + return n; } return null; } @@ -182,12 +159,9 @@ private Named lookup(Name name, final Namespace[] spaces) { @Override public String toString() { - return "Sorts: " + sorts() + "\n" + - "Functions: " + functions() + "\n" + - "Variables: " + variables() + "\n" + - "ProgramVariables: " + programVariables() + "\n" + - "Heuristics: " + ruleSets() + "\n" + - "Taclet Options: " + choices() + "\n"; + return "Sorts: " + sorts() + "\n" + "Functions: " + functions() + "\n" + "Variables: " + + variables() + "\n" + "ProgramVariables: " + programVariables() + "\n" + + "Heuristics: " + ruleSets() + "\n" + "Taclet Options: " + choices() + "\n"; } @@ -210,32 +184,20 @@ public void seal() { } public boolean isEmpty() { - return varNS.isEmpty() && - programVariables().isEmpty() && - funcNS.isEmpty() && - ruleSetNS.isEmpty() && - sortNS.isEmpty() && - choiceNS.isEmpty(); + return varNS.isEmpty() && programVariables().isEmpty() && funcNS.isEmpty() + && ruleSetNS.isEmpty() && sortNS.isEmpty() && choiceNS.isEmpty(); } // create a namespace public NamespaceSet simplify() { - return new NamespaceSet(varNS.simplify(), - funcNS.simplify(), - sortNS.simplify(), - ruleSetNS.simplify(), - choiceNS.simplify(), - progVarNS.simplify()); + return new NamespaceSet(varNS.simplify(), funcNS.simplify(), sortNS.simplify(), + ruleSetNS.simplify(), choiceNS.simplify(), progVarNS.simplify()); } public NamespaceSet getCompression() { - return new NamespaceSet(varNS.compress(), - funcNS.compress(), - sortNS.compress(), - ruleSetNS.compress(), - choiceNS.compress(), - progVarNS.compress()); + return new NamespaceSet(varNS.compress(), funcNS.compress(), sortNS.compress(), + ruleSetNS.compress(), choiceNS.compress(), progVarNS.compress()); } public void flushToParent() { @@ -245,12 +207,8 @@ public void flushToParent() { } public NamespaceSet getParent() { - return new NamespaceSet(varNS.parent(), - funcNS.parent(), - sortNS.parent(), - ruleSetNS.parent(), - choiceNS.parent(), - progVarNS.parent()); + return new NamespaceSet(varNS.parent(), funcNS.parent(), sortNS.parent(), + ruleSetNS.parent(), choiceNS.parent(), progVarNS.parent()); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/OpCollector.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/OpCollector.java index d34d4197071..9edfb2f0bff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/OpCollector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/OpCollector.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashSet; @@ -16,21 +19,21 @@ public class OpCollector extends DefaultVisitor { /** creates the Op collector */ public OpCollector() { - ops = new LinkedHashSet(); + ops = new LinkedHashSet(); } - public void visit(Term t) { + public void visit(Term t) { ops.add(t.op()); - if(t.op() instanceof ElementaryUpdate) { - ops.add(((ElementaryUpdate)t.op()).lhs()); + if (t.op() instanceof ElementaryUpdate) { + ops.add(((ElementaryUpdate) t.op()).lhs()); } } public boolean contains(Operator op) { - return ops.contains(op); + return ops.contains(op); } - + public Set ops() { - return ops; + return ops; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PIOPathIterator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PIOPathIterator.java index fa5c177a089..6c95b004da9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PIOPathIterator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PIOPathIterator.java @@ -1,40 +1,41 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** - * This interface represents an iterator, iterating the nodes on the - * path between the root of a term and a position within the term, - * given by a PosInOccurrence-object + * This interface represents an iterator, iterating the nodes on the path between the root of a term + * and a position within the term, given by a PosInOccurrence-object */ public interface PIOPathIterator extends IntIterator { /** - * @return the number of the next child on the path, or - * -1 if no further child exists + * @return the number of the next child on the path, or -1 if no further child + * exists */ - int next (); + int next(); // The following methods may only be called after having called // next() at least once /** - * @return the current position within the term - * (i.e. corresponding to the latest next()-call) + * @return the current position within the term (i.e. corresponding to the latest + * next()-call) */ - PosInOccurrence getPosInOccurrence (); + PosInOccurrence getPosInOccurrence(); /** - * @return the current subterm this object points to - * (i.e. corresponding to the latest next()-call); - * this method satisfies - * getPosInOccurrence().subTerm()==getSubTerm() + * @return the current subterm this object points to (i.e. corresponding to the latest + * next()-call); this method satisfies + * getPosInOccurrence().subTerm()==getSubTerm() */ - Term getSubTerm (); + Term getSubTerm(); /** - * @return the number of the next child on the path, or - * -1 if no further child exists (this is the number - * that was also returned by the last call of next()) + * @return the number of the next child on the path, or -1 if no further child + * exists (this is the number that was also returned by the last call of + * next()) */ - int getChild (); + int getChild(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInOccurrence.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInOccurrence.java index 687b88ff1d1..1f78da49f35 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInOccurrence.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInOccurrence.java @@ -1,19 +1,19 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** - * This class describes a position in an occurrence of a term. A - * SequentFormula and a PosInTerm determine an object of this - * class exactly. + * This class describes a position in an occurrence of a term. A SequentFormula and a PosInTerm + * determine an object of this class exactly. */ public final class PosInOccurrence { - public static PosInOccurrence findInSequent(Sequent seq, - int formulaNumber, - PosInTerm pos) { - return new PosInOccurrence(seq.getFormulabyNr(formulaNumber), - pos, seq.numberInAntec(formulaNumber)); + public static PosInOccurrence findInSequent(Sequent seq, int formulaNumber, PosInTerm pos) { + return new PosInOccurrence(seq.getFormulabyNr(formulaNumber), pos, + seq.numberInAntec(formulaNumber)); } - + /** * the constrained formula the pos in occurrence describes */ @@ -22,9 +22,9 @@ public static PosInOccurrence findInSequent(Sequent seq, // saves 8 bytes (due to alignment issues) per instance if we use a // short here instead of an int private final short hashCode; - + /** - * is true iff the position is in the antecedent of a sequent. + * is true iff the position is in the antecedent of a sequent. */ private final boolean inAntec; @@ -36,185 +36,174 @@ public static PosInOccurrence findInSequent(Sequent seq, */ private volatile Term subTermCache = null; - public PosInOccurrence(SequentFormula sequentFormula, - PosInTerm posInTerm, - boolean inAntec) { + public PosInOccurrence(SequentFormula sequentFormula, PosInTerm posInTerm, boolean inAntec) { assert posInTerm != null; assert sequentFormula != null; - this.inAntec = inAntec; - this.sequentFormula = sequentFormula; - this.posInTerm = posInTerm; - this.hashCode = (short) (sequentFormula.hashCode() * 13 + posInTerm.hashCode()); + this.inAntec = inAntec; + this.sequentFormula = sequentFormula; + this.posInTerm = posInTerm; + this.hashCode = (short) (sequentFormula.hashCode() * 13 + posInTerm.hashCode()); } - + /** - * returns the SequentFormula that determines the occurrence of - * this PosInOccurrence + * returns the SequentFormula that determines the occurrence of this PosInOccurrence */ public SequentFormula sequentFormula() { - return sequentFormula; + return sequentFormula; } /** - * @return Depth of the represented position within a formula; top-level - * positions (isTopLevel() have depth zero + * @return Depth of the represented position within a formula; top-level positions + * (isTopLevel() have depth zero */ - public int depth () { - return posInTerm ().depth (); + public int depth() { + return posInTerm().depth(); } /** - * creates a new PosInOccurrence that has exactly the same state as this - * object except the PosInTerm is new and walked down the specified - * subterm, as specified in method down of + * creates a new PosInOccurrence that has exactly the same state as this object except the + * PosInTerm is new and walked down the specified subterm, as specified in method down of * {@link de.uka.ilkd.key.logic.PosInTerm}. */ public PosInOccurrence down(int i) { - return new PosInOccurrence(sequentFormula, posInTerm.down(i), inAntec); + return new PosInOccurrence(sequentFormula, posInTerm.down(i), inAntec); } - - /** - * compares this PosInOccurrence with another PosInOccurrence - * and returns true if both describe the same occurrence + + /** + * compares this PosInOccurrence with another PosInOccurrence and returns true if both describe + * the same occurrence */ public boolean eqEquals(Object obj) { - if (!(obj instanceof PosInOccurrence)) { - return false; - } - final PosInOccurrence cmp = (PosInOccurrence)obj; + if (!(obj instanceof PosInOccurrence)) { + return false; + } + final PosInOccurrence cmp = (PosInOccurrence) obj; - if ( !sequentFormula.equals ( cmp.sequentFormula ) ) { - return false; + if (!sequentFormula.equals(cmp.sequentFormula)) { + return false; } - - return equalsHelp ( cmp ); - } + + return equalsHelp(cmp); + } /** - * Contrary to eqEquals, this method returns true only for pio - * objects that point to the same (identical) formula + * Contrary to eqEquals, this method returns true only for pio objects that point + * to the same (identical) formula + * * @param obj * @return true if both objects are equal */ - public boolean equals (Object obj) { - if (!(obj instanceof PosInOccurrence)) { - return false; - } - final PosInOccurrence cmp = (PosInOccurrence)obj; - - // NB: the class NonDuplicateAppFeature depends on the usage - // of != in this condition - if ( sequentFormula() != cmp.sequentFormula() ) { - return false; - } - - return equalsHelp ( cmp ); + public boolean equals(Object obj) { + if (!(obj instanceof PosInOccurrence)) { + return false; + } + final PosInOccurrence cmp = (PosInOccurrence) obj; + + // NB: the class NonDuplicateAppFeature depends on the usage + // of != in this condition + if (sequentFormula() != cmp.sequentFormula()) { + return false; + } + + return equalsHelp(cmp); } - private boolean equalsHelp (final PosInOccurrence cmp) { - if ( inAntec == cmp.inAntec ) { - return posInTerm .equals ( cmp.posInTerm ); - } + private boolean equalsHelp(final PosInOccurrence cmp) { + if (inAntec == cmp.inAntec) { + return posInTerm.equals(cmp.posInTerm); + } return false; } /** - * @return the number/index of the deepest subterm that this - * PosInOccurrence points to. If the position is - * top-level, the result will be -1 + * @return the number/index of the deepest subterm that this PosInOccurrence points + * to. If the position is top-level, the result will be -1 */ public int getIndex() { - return posInTerm.getIndex (); + return posInTerm.getIndex(); } - public int hashCode () { - return hashCode; - } + public int hashCode() { + return hashCode; + } /** - * returns true iff the occurrence is in the - * antecedent of a sequent. + * returns true iff the occurrence is in the antecedent of a sequent. */ - public boolean isInAntec() { - return inAntec; + public boolean isInAntec() { + return inAntec; } - public boolean isTopLevel () { - return posInTerm == PosInTerm.getTopLevel(); + public boolean isTopLevel() { + return posInTerm == PosInTerm.getTopLevel(); } /** - * List all subterms between the root and the position this - * objects points to; the first term is the whole term - * constrainedFormula().formula(), the last one + * List all subterms between the root and the position this objects points to; the first term is + * the whole term constrainedFormula().formula(), the last one * subTerm() - * @return an iterator that walks from the root of the term to the - * position this PosInOccurrence-object points to + * + * @return an iterator that walks from the root of the term to the position this + * PosInOccurrence-object points to */ - public PIOPathIterator iterator () { - return new PIOPathIteratorImpl (); + public PIOPathIterator iterator() { + return new PIOPathIteratorImpl(); } /** - * The usage of this method is strongly discouraged, use - * {@link PosInOccurrence#iterator} instead. - * describes the exact occurrence of the referred term inside - * {@link SequentFormula#formula()} - * @returns the position in the formula of the SequentFormula of - * this PosInOccurrence. + * The usage of this method is strongly discouraged, use {@link PosInOccurrence#iterator} + * instead. describes the exact occurrence of the referred term inside + * {@link SequentFormula#formula()} + * + * @returns the position in the formula of the SequentFormula of this PosInOccurrence. */ public PosInTerm posInTerm() { - return posInTerm; + return posInTerm; } /** * Replace the formula this object points to with the new formula given - * - * @param p_newFormula - * the new formula - * @return a PosInOccurrence object that points to the same - * position within the formula p_newFormula as this - * object does within the formula constrainedFormula(). - * It is not tested whether this position exists within p_newFormula + * + * @param p_newFormula the new formula + * @return a PosInOccurrence object that points to the same position within the + * formula p_newFormula as this object does within the formula + * constrainedFormula(). It is not tested whether this position exists + * within p_newFormula */ - public PosInOccurrence replaceConstrainedFormula (SequentFormula p_newFormula) { + public PosInOccurrence replaceConstrainedFormula(SequentFormula p_newFormula) { assert p_newFormula != null; if (p_newFormula == sequentFormula) { return this; } - return new PosInOccurrence ( p_newFormula, - posInTerm, - inAntec); + return new PosInOccurrence(p_newFormula, posInTerm, inAntec); } /** * returns the subterm this object points to */ - public Term subTerm () { - if ( subTermCache == null ) { + public Term subTerm() { + if (subTermCache == null) { subTermCache = posInTerm.getSubTerm(sequentFormula.formula()); } return subTermCache; } /** - * Ascend to the top node of the formula this object points to + * Ascend to the top node of the formula this object points to */ - public PosInOccurrence topLevel () { + public PosInOccurrence topLevel() { if (isTopLevel()) { return this; } - return new PosInOccurrence(sequentFormula, PosInTerm.getTopLevel(), - inAntec); + return new PosInOccurrence(sequentFormula, PosInTerm.getTopLevel(), inAntec); } /** toString */ public String toString() { - String res = "Term "+ - posInTerm()+" of "+ sequentFormula(); - - return res; + String res = "Term " + posInTerm() + " of " + sequentFormula(); + + return res; } @@ -224,87 +213,83 @@ public String toString() { * Ascend to the parent node */ public PosInOccurrence up() { - assert !isTopLevel() : "not possible to go up from top level position"; + assert !isTopLevel() : "not possible to go up from top level position"; - return new PosInOccurrence(sequentFormula, posInTerm.up(), - inAntec); + return new PosInOccurrence(sequentFormula, posInTerm.up(), inAntec); } - - private final class PIOPathIteratorImpl implements PIOPathIterator { - int child; - int count = 0; - IntIterator currentPathIt; - Term currentSubTerm = null; - - private PIOPathIteratorImpl () { - currentPathIt = posInTerm ().iterator (); - } - - /** - * @return the number of the next child on the path, or - * -1 if no further child exists (this is the number - * that was also returned by the last call of next()) - */ - public int getChild () { - return child; - } - - /** - * @return the current position within the term - * (i.e. corresponding to the latest next()-call) - */ - public PosInOccurrence getPosInOccurrence () { - // the object is created only now to make the method - // next() faster - - final PosInOccurrence pio; - pio = new PosInOccurrence ( sequentFormula, - posInTerm.firstN(count - 1), - inAntec ); - - - return pio; - } - - /** - * @return the current subterm this object points to - * (i.e. corresponding to the latest next()-call); - * this method satisfies - * getPosInOccurrence().subTerm()==getSubTerm() - */ - public Term getSubTerm () { - return currentSubTerm; - } - - public boolean hasNext () { - return currentPathIt != null; - } - - /** - * @return the number of the next child on the path, or - * -1 if no further child exists - */ - public int next () { - int res; - - if ( currentSubTerm == null ) - currentSubTerm = sequentFormula.formula (); - else - currentSubTerm = currentSubTerm.sub ( child ); - - if ( currentPathIt.hasNext () ) - res = currentPathIt.next (); - else { - res = -1 ; - currentPathIt = null; - } - - child = res; - ++count; - return res; - } + + private final class PIOPathIteratorImpl implements PIOPathIterator { + int child; + int count = 0; + IntIterator currentPathIt; + Term currentSubTerm = null; + + private PIOPathIteratorImpl() { + currentPathIt = posInTerm().iterator(); + } + + /** + * @return the number of the next child on the path, or -1 if no further child + * exists (this is the number that was also returned by the last call of + * next()) + */ + public int getChild() { + return child; + } + + /** + * @return the current position within the term (i.e. corresponding to the latest + * next()-call) + */ + public PosInOccurrence getPosInOccurrence() { + // the object is created only now to make the method + // next() faster + + final PosInOccurrence pio; + pio = new PosInOccurrence(sequentFormula, posInTerm.firstN(count - 1), inAntec); + + + return pio; + } + + /** + * @return the current subterm this object points to (i.e. corresponding to the latest + * next()-call); this method satisfies + * getPosInOccurrence().subTerm()==getSubTerm() + */ + public Term getSubTerm() { + return currentSubTerm; + } + + public boolean hasNext() { + return currentPathIt != null; + } + + /** + * @return the number of the next child on the path, or -1 if no further child + * exists + */ + public int next() { + int res; + + if (currentSubTerm == null) + currentSubTerm = sequentFormula.formula(); + else + currentSubTerm = currentSubTerm.sub(child); + + if (currentPathIt.hasNext()) + res = currentPathIt.next(); + else { + res = -1; + currentPathIt = null; + } + + child = res; + ++count; + return res; + } } - -} \ No newline at end of file + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInProgram.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInProgram.java index b06c85974c8..d90cc031b51 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInProgram.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/PosInProgram.java @@ -1,104 +1,106 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.java.NonTerminalProgramElement; import de.uka.ilkd.key.java.ProgramElement; -/** +/** * this class describes the position of a statement in a program. */ public class PosInProgram { - + /** pos at the beginning of the program */ public static final PosInProgram TOP = new PosInProgram(); /** often used positions */ public static final PosInProgram ZERO = TOP.down(0); public static final PosInProgram ZERO_ZERO = ZERO.down(0); - public static final PosInProgram ZERO_ONE = ZERO.down(1); + public static final PosInProgram ZERO_ONE = ZERO.down(1); public static final PosInProgram ONE = TOP.down(1); public static final PosInProgram ONE_ZERO = ONE.down(0); - public static final PosInProgram ONE_ONE = ONE.down(1); + public static final PosInProgram ONE_ONE = ONE.down(1); - /** + /** * the position number */ private final int[] pos; - + /** * pointer to the (last element + 1) in pos valid for this position */ private final int depth; - /** - * returns the ProgramElement at the given position - * @param pos the PosInProgram + /** + * returns the ProgramElement at the given position + * + * @param pos the PosInProgram * @param prg the ProgramElement we walk through - * @return the ProgramElement at the given position - * @throws IndexOutOfBoundsException if the given position - * refers to a non-existant program + * @return the ProgramElement at the given position + * @throws IndexOutOfBoundsException if the given position refers to a non-existant program */ - public static ProgramElement getProgramAt(PosInProgram pos, - ProgramElement prg) - { + public static ProgramElement getProgramAt(PosInProgram pos, ProgramElement prg) { ProgramElement result = prg; - for (int i = 0; i - *

  • obtain the position object representing the top level position, which refers to - * the term as a whole.
  • + *
  • obtain the position object representing the top level position, which refers to the term as a + * whole.
  • *
  • use method {@link #down(int)} to keep track of the current position. Pass as argument the * position of the subterm to be taken. Attention: Each invocation creates a new position in term * object which has to be used for further navigation. The original one remains unchanged.
  • * - * + * */ public final class PosInTerm { @@ -23,7 +26,7 @@ public final class PosInTerm { // to save memory, we use 16bit integers (unsigned) instead of 32bit private final char[] positions; private final char size; - private volatile char hash = (char)-1; + private volatile char hash = (char) -1; private volatile boolean copy; public PosInTerm(int[] path) { @@ -32,52 +35,54 @@ public PosInTerm(int[] path) { for (int i = 0; i < positions.length; i++) { positions[i] = (char) path[i]; } - copy=false; + copy = false; } - /** + /** * create a position from the string - * - * The string contains a comma separated list of integers. - * The position created from the string encapsulated the given list but in - * reverse order - * - * @param s the String with the list of integers to be interpreted as term indices in - * reverse order + * + * The string contains a comma separated list of integers. The position created from the string + * encapsulated the given list but in reverse order + * + * @param s the String with the list of integers to be interpreted as term indices in reverse + * order * @return the PosInTerm encapsulating the integer list in reverse order */ public static PosInTerm parseReverseString(String s) { if ("".equals(s)) { return getTopLevel(); } - - final LinkedList list = new LinkedList(); - final StringTokenizer tker = new StringTokenizer(s,",",false); - + + final LinkedList list = new LinkedList(); + final StringTokenizer tker = new StringTokenizer(s, ",", false); + while (tker.hasMoreTokens()) { list.addFirst(Integer.decode(tker.nextToken())); } - + final char[] positions = new char[list.size()]; int i = 0; for (int j : list) { - if (j > Character.MAX_VALUE) throw new ArithmeticException("Position "+j+" out of bounds"); - positions[i] = (char)j; + if (j > Character.MAX_VALUE) + throw new ArithmeticException("Position " + j + " out of bounds"); + positions[i] = (char) j; ++i; } - - return positions.length == 0 ? getTopLevel() : new PosInTerm(positions, (char) positions.length, true); + + return positions.length == 0 ? getTopLevel() + : new PosInTerm(positions, (char) positions.length, true); } /** * returns the instance representing the top level position + * * @return the top level position */ public static PosInTerm getTopLevel() { return TOP_LEVEL; } - + /** * only used once to create the singleton for the top level position */ @@ -90,8 +95,11 @@ private PosInTerm() { /** * creates an instance representing the position positions[0..size-1] - * @param positions the integer array where each element describes the position to be taken (in top-to-bottom order) - * @param size the size of the integer list (attention: might be shorter than the length of the position array) + * + * @param positions the integer array where each element describes the position to be taken (in + * top-to-bottom order) + * @param size the size of the integer list (attention: might be shorter than the length of the + * position array) * @param copy indicates (i.e. true) if the position array has to be copied when going downwards */ private PosInTerm(char[] positions, char size, boolean copy) { @@ -103,6 +111,7 @@ private PosInTerm(char[] positions, char size, boolean copy) { /** * the depth of the sub term described by this position + * * @return the term depth */ public int depth() { @@ -111,6 +120,7 @@ public int depth() { /** * true if the position describes the top level position, i.e., the term as a whole + * * @return true iff top level */ public boolean isTopLevel() { @@ -119,20 +129,23 @@ public boolean isTopLevel() { /** * returns the position of the enclosing term + * * @return the position of the parent */ public PosInTerm up() { if (size == 0) { return null; } - return size == 1 ? getTopLevel() : new PosInTerm(positions, (char)(size - 1), true); + return size == 1 ? getTopLevel() : new PosInTerm(positions, (char) (size - 1), true); } /** * returns the position of the depth-n parent term - * @param n the integer specifying the length of the prefix + * + * @param n the integer specifying the length of the prefix * @return the prefix of this position of length n - * @throws IndexOutOfBoundsException if n is greater than the depth of this position + * @throws IndexOutOfBoundsException if n is greater than the depth of this + * position */ public PosInTerm firstN(int n) { if (n > size) { @@ -142,85 +155,91 @@ public PosInTerm firstN(int n) { } else if (n == size) { return this; } - return new PosInTerm(positions, (char)n, true); + return new PosInTerm(positions, (char) n, true); } - + /** - * returns the position for the i-th subterm of the subterm described by this position + * returns the position for the i-th subterm of the subterm described by this + * position + * * @param i the index of the subterm * @return the position of the i-th subterm */ public PosInTerm down(int i) { - if (i > Character.MAX_VALUE) throw new ArithmeticException("Position "+i+" out of bounds"); - + if (i > Character.MAX_VALUE) + throw new ArithmeticException("Position " + i + " out of bounds"); + boolean localCopy = true; if (!copy) { // at most one thread is allowed to enter the non-copy branch synchronized (positions) { - localCopy = copy; + localCopy = copy; if (copy == false) { copy = true; } } } - final PosInTerm result; - if (localCopy) { - final char[] newPositions = + final PosInTerm result; + if (localCopy) { + final char[] newPositions = new char[positions.length <= size ? size + 4 : positions.length]; System.arraycopy(positions, 0, newPositions, 0, size); - newPositions[size] = (char)i; - result = new PosInTerm(newPositions, (char)(size + 1), false); + newPositions[size] = (char) i; + result = new PosInTerm(newPositions, (char) (size + 1), false); } else { - copy = true; - positions[size] = (char)i; - result = new PosInTerm(positions, (char)(size + 1), size >= positions.length - 1); + copy = true; + positions[size] = (char) i; + result = new PosInTerm(positions, (char) (size + 1), size >= positions.length - 1); } return result; } /** - * returns the index of the subterm at depth i + * returns the index of the subterm at depth i + * * @param i the depth of the subterm whose index it to be returned - * @return an int such that term.subAt(this).sub(getIndex(i)) == term.subAt(firstN(i+1)) + * @return an int such that + * term.subAt(this).sub(getIndex(i)) == term.subAt(firstN(i+1)) */ public int getIndexAt(int i) { - if (i<0 || i>=size) { - throw new IndexOutOfBoundsException("No position at index "+i); + if (i < 0 || i >= size) { + throw new IndexOutOfBoundsException("No position at index " + i); } return positions[i]; } - /** + /** * equivalent to getIndexAt(depth() - 1) + * * @return the index of the subterm described by this position */ public int getIndex() { return size == 0 ? -1 : positions[size - 1]; } - - + + /** - * navigate to the subterm described by this position and return it - * if the described position does not exist in the term an {@link IndexOutOfBoundsException} - * is thrown - * @param t the {@link Term} - * @return the sub term of term {@code t} at this position + * navigate to the subterm described by this position and return it if the described position + * does not exist in the term an {@link IndexOutOfBoundsException} is thrown + * + * @param t the {@link Term} + * @return the sub term of term {@code t} at this position * @throws an {@link IndexOutOfBoundsException} if no subterm exists at this position */ public Term getSubTerm(Term t) { Term sub = t; - for (int i = 0; i= pit.size) { + if (size >= pit.size) { return false; } - for(int i = 0; i < size; i++) { + for (int i = 0; i < size; i++) { if (positions[i] != pit.positions[i]) { return false; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramConstruct.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramConstruct.java index eb0c6fb4ddd..f5500b455a6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramConstruct.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramConstruct.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.java.Expression; @@ -15,13 +18,12 @@ import de.uka.ilkd.key.logic.op.IProgramMethod; import de.uka.ilkd.key.logic.op.IProgramVariable; -/** A type that implement this interface can be used in all java - * programs instead of an expression or statement. For example class - * SchemaVariable implements this interface to be able to stand for +/** + * A type that implement this interface can be used in all java programs instead of an expression or + * statement. For example class SchemaVariable implements this interface to be able to stand for * program constructs. */ -public interface ProgramConstruct extends Expression, Statement, ILoopInit, - IForUpdates, IGuard, Label, TerminalProgramElement, ExpressionStatement, - TypeReference, IProgramVariable, IProgramMethod, Branch, IExecutionContext, - MethodName { -} \ No newline at end of file +public interface ProgramConstruct extends Expression, Statement, ILoopInit, IForUpdates, IGuard, + Label, TerminalProgramElement, ExpressionStatement, TypeReference, IProgramVariable, + IProgramMethod, Branch, IExecutionContext, MethodName { +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramElementName.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramElementName.java index c776d0ceb2b..d587579c630 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramElementName.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramElementName.java @@ -1,5 +1,6 @@ -/** represents a name that is part of a program - */ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.java.Comment; @@ -21,8 +22,8 @@ import org.slf4j.LoggerFactory; import recoder.service.KeYCrossReferenceSourceInfo; -public class ProgramElementName extends Name - implements TerminalProgramElement, Label, ReferenceSuffix, MethodName { +public class ProgramElementName extends Name + implements TerminalProgramElement, Label, ReferenceSuffix, MethodName { public static final Logger LOGGER = LoggerFactory.getLogger(ProgramElementName.class); private final String qualifierString; @@ -30,153 +31,157 @@ public class ProgramElementName extends Name private final NameCreationInfo creationInfo; private final Comment[] comments; - /** create a new name + /** + * create a new name + * * @param name the String with the name of the program element */ public ProgramElementName(String name) { - super(name); - this.qualifierString = "".intern(); - this.shortName = name.intern(); + super(name); + this.qualifierString = "".intern(); + this.shortName = name.intern(); this.creationInfo = null; - comments = new Comment[0]; + comments = new Comment[0]; } - /** create a new name + /** + * create a new name + * * @param name the String with the name of the program element */ public ProgramElementName(String name, Comment[] c) { - super(name); - this.qualifierString = "".intern(); - this.shortName = name.intern(); + super(name); + this.qualifierString = "".intern(); + this.shortName = name.intern(); this.creationInfo = null; - comments = c; + comments = c; } public ProgramElementName(String name, NameCreationInfo creationInfo) { - super(name); - this.qualifierString = "".intern(); - this.shortName = name.intern(); + super(name); + this.qualifierString = "".intern(); + this.shortName = name.intern(); this.creationInfo = creationInfo; - comments = new Comment[0]; + comments = new Comment[0]; } public ProgramElementName(String name, NameCreationInfo creationInfo, Comment[] c) { - super(name); - this.qualifierString = "".intern(); - this.shortName = name.intern(); + super(name); + this.qualifierString = "".intern(); + this.shortName = name.intern(); this.creationInfo = creationInfo; - comments = c; + comments = c; } public ProgramElementName(String n, String q) { - super(q + "::" + n); - assert q.length() > 0 : "Tried to create qualified name with missing qualifier"; + super(q + "::" + n); + assert q.length() > 0 : "Tried to create qualified name with missing qualifier"; - this.qualifierString = q.intern(); - this.shortName = n.intern(); + this.qualifierString = q.intern(); + this.shortName = n.intern(); this.creationInfo = null; - comments = new Comment[0]; + comments = new Comment[0]; } public Comment[] getComments() { - return comments; + return comments; } - + /** * to be compatible to a ProgramElement */ public SourceElement getFirstElement() { - return this; + return this; } @Override public SourceElement getFirstElementIncludingBlocks() { - return getFirstElement(); + return getFirstElement(); } - - + + /** * to be compatible to a ProgramElement */ public SourceElement getLastElement() { - return this; + return this; } - + public void prettyPrint(PrettyPrinter w) throws java.io.IOException { - w.printProgramElementName(this); + w.printProgramElementName(this); } - - /** calls the corresponding method of a visitor in order to - * perform some action/transformation on this element + + /** + * 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.performActionOnProgramElementName(this); + v.performActionOnProgramElementName(this); } - - + + /** - 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 Position.UNDEFINED; - } - + * 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 Position.UNDEFINED; + } + /** - 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 Position.UNDEFINED; - } - + * 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 Position.UNDEFINED; + } + + /** + * 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 Position.UNDEFINED; + } + + + public PositionInfo getPositionInfo() { + return PositionInfo.UNDEFINED; + } + + /** - 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 Position.UNDEFINED; - } - - - public PositionInfo getPositionInfo(){ - return PositionInfo.UNDEFINED; - } - - - /** equals modulo renaming is described in the corresponding - * comment in class SourceElement. The ProgramElementName has to - * check if an abstract name has been assigned and if, if both - * elements are assigned to the same name, otherwise the names - * have to be equal + * equals modulo renaming is described in the corresponding comment in class SourceElement. The + * ProgramElementName has to check if an abstract name has been assigned and if, if both + * elements are assigned to the same name, otherwise the names have to be equal */ - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { - if (!(se instanceof ProgramElementName)) { - return false; - } - return nat.sameAbstractName(this, se); - } - - + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { + if (!(se instanceof ProgramElementName)) { + return false; + } + return nat.sameAbstractName(this, se); + } + + public String getQualifier() { - return qualifierString; + return qualifierString; } public String getProgramName() { - return shortName; + return shortName; } public NameCreationInfo getCreationInfo() { - return creationInfo; + return creationInfo; } public MatchConditions match(SourceData source, MatchConditions matchCond) { @@ -187,16 +192,16 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { } else { LOGGER.debug("Program match failed (pattern {}, source {})", this, src); return null; - } + } } - + @Override public boolean equals(Object o) { - return super.equals(o); + return super.equals(o); } - + @Override public int hashCode() { - return super.hashCode(); + return super.hashCode(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramInLogic.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramInLogic.java index 46f54f468ac..529709f3621 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramInLogic.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramInLogic.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.ExtList; @@ -5,11 +8,11 @@ import de.uka.ilkd.key.java.Expression; /** - * represents something in logic that originates from a program like - * queries, program variables and therefore has a KeYJavaType + * represents something in logic that originates from a program like queries, program variables and + * therefore has a KeYJavaType */ public interface ProgramInLogic { Expression convertToProgram(Term t, ExtList list); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramPrefix.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramPrefix.java index d922d621119..be7cb434d3b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramPrefix.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/ProgramPrefix.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableArray; @@ -6,33 +9,35 @@ import de.uka.ilkd.key.java.statement.MethodFrame; /** - * this interface is implemented by program elements that may be matched - * by the inactive program prefix + * this interface is implemented by program elements that may be matched by the inactive program + * prefix */ public interface ProgramPrefix extends NonTerminalProgramElement { - + /** return true if there is a next prefix element */ - boolean hasNextPrefixElement(); + boolean hasNextPrefixElement(); - /** return the next prefix element - * if no next prefix element is available an IndexOutOfBoundsException is thrown + /** + * return the next prefix element if no next prefix element is available an + * IndexOutOfBoundsException is thrown */ - ProgramPrefix getNextPrefixElement(); + ProgramPrefix getNextPrefixElement(); /** return the last prefix element */ - ProgramPrefix getLastPrefixElement(); - - /** returns an array with all prefix elements starting at - * this element */ + ProgramPrefix getLastPrefixElement(); + + /** + * returns an array with all prefix elements starting at this element + */ ImmutableArray getPrefixElements(); - + /** returns the position of the first active child */ PosInProgram getFirstActiveChildPos(); - + /** returns the length of the prefix */ int getPrefixLength(); - + /** returns the inner most {@link MethodFrame} */ MethodFrame getInnerMostMethodFrame(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenameTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenameTable.java index dde20986aac..2e1ff38e961 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenameTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenameTable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.DefaultImmutableMap; @@ -9,12 +12,12 @@ public class RenameTable { public static final RenameTable EMPTY_TABLE = new EmptyRenameTable(); - /** - * local map mapping a QuantifiableVariable object to an abstract name. This map - * is allowed to hide bound renaming of the parent table. + /** + * local map mapping a QuantifiableVariable object to an abstract name. This map is allowed to + * hide bound renaming of the parent table. */ - private final ImmutableMap localRenamingTable; - + private final ImmutableMap localRenamingTable; + /** * the maximal value of an abstract name */ @@ -24,87 +27,78 @@ public class RenameTable { private final RenameTable parent; - public RenameTable(RenameTable parent, - ImmutableMap localTable, - int newMax) { + public RenameTable(RenameTable parent, ImmutableMap localTable, + int newMax) { this.parent = parent; this.localRenamingTable = localTable; max = newMax; } /** - * returns true iff the given variable is mapped to an abstract name. - * The test is performed in the local as well as in the parent - * renaming table. - * @param n the QuantifiableVariable object the existence of an abstract name is - * checked. - * @return true if n has been already assigned to an - * abstract name + * returns true iff the given variable is mapped to an abstract name. The test is performed in + * the local as well as in the parent renaming table. + * + * @param n the QuantifiableVariable object the existence of an abstract name is checked. + * @return true if n has been already assigned to an abstract name */ public boolean contains(QuantifiableVariable n) { - return localRenamingTable.containsKey(n) || parent.contains(n); + return localRenamingTable.containsKey(n) || parent.contains(n); } /** - * does nearly the same as {@link #contains(QuantifiableVariable)} but performs - * the test only on the local table - * @param n the QuantifiableVariable object the existence of an abstract name is - * checked. - * @return true if n has been already locally - * assigned to an abstract name + * does nearly the same as {@link #contains(QuantifiableVariable)} but performs the test only on + * the local table + * + * @param n the QuantifiableVariable object the existence of an abstract name is checked. + * @return true if n has been already locally assigned to an abstract name */ public boolean containsLocally(QuantifiableVariable n) { - return localRenamingTable.containsKey(n); + return localRenamingTable.containsKey(n); } /** - * tests if both QuantifiableVariables are assigned to the same abstract - * name (locally or by the parent) - * @param n1 one of the QuantifiableVariables to be tested iff they have - * been assigned the same abstract name + * tests if both QuantifiableVariables are assigned to the same abstract name (locally or by the + * parent) + * + * @param n1 one of the QuantifiableVariables to be tested iff they have been assigned the same + * abstract name * @param n2 one of the QuantifiableVariables to be tested - * @return true iff n1 and n2 are mapped - * to the same abstract name + * @return true iff n1 and n2 are mapped to the same abstract name */ public boolean sameAbstractName(QuantifiableVariable n1, QuantifiableVariable n2) { - if (containsLocally(n1)) { - return localRenamingTable.get(n1).equals(localRenamingTable.get(n2)); - } else { - return parent.sameAbstractName(n1, n2); - } + if (containsLocally(n1)) { + return localRenamingTable.get(n1).equals(localRenamingTable.get(n2)); + } else { + return parent.sameAbstractName(n1, n2); + } } private Integer createNewAbstractName() { - if (max == Integer.MAX_VALUE) { - throw new IllegalStateException - ("Overflow in renaming table. Why on earth " + - "are there " + Integer.MAX_VALUE + - " + 1 variables to be renamed?"); - } - - return Integer.valueOf(max + 1); + if (max == Integer.MAX_VALUE) { + throw new IllegalStateException("Overflow in renaming table. Why on earth " + + "are there " + Integer.MAX_VALUE + " + 1 variables to be renamed?"); + } + + return Integer.valueOf(max + 1); } /** * assigns both QuantifiableVariable objects the same abstract name */ - public RenameTable assign(QuantifiableVariable n1, QuantifiableVariable n2) { - final Integer newAbstractName = createNewAbstractName(); - return new RenameTable(parent, - localRenamingTable.put(n1, newAbstractName). - put(n2, newAbstractName), - newAbstractName.intValue()); + public RenameTable assign(QuantifiableVariable n1, QuantifiableVariable n2) { + final Integer newAbstractName = createNewAbstractName(); + return new RenameTable(parent, + localRenamingTable.put(n1, newAbstractName).put(n2, newAbstractName), + newAbstractName.intValue()); } /** - * creates a nested renaming table with this - * as parent + * creates a nested renaming table with this as parent */ - public RenameTable extend() { - return new RenameTable(this, - DefaultImmutableMap.nilMap(), - createNewAbstractName().intValue()); + public RenameTable extend() { + return new RenameTable(this, DefaultImmutableMap.nilMap(), + createNewAbstractName().intValue()); } @@ -112,61 +106,58 @@ public RenameTable extend() { * toString */ public String toString() { - return localRenamingTable + " \n parent:" + parent; + return localRenamingTable + " \n parent:" + parent; } - private static class EmptyRenameTable extends RenameTable { - - private EmptyRenameTable() { - super(null, DefaultImmutableMap.nilMap(), 0); - } - - /** - * returns true iff the given name is mapped to an abstract name. - * The test is performed in the local as well as in the parent - * renaming table. - * @param n the QuantifiableVariable object the existence of an abstract name is - * checked. - * @return true if n has been already assigned to an - * abstract name - */ - public boolean contains(QuantifiableVariable n) { - return false; - } - - /** - * does nearly the same as {@link #contains(QuantifiableVariable)} but performs - * the test only on the local table- - * @param n the QuantifiableVariable object the existence of an abstract name is - * checked. - * @return true if n has been already locally - * assigned to an abstract name - */ - public boolean containsLocally(QuantifiableVariable n) { - return false; - } - - /** - * tests if both QuantifiableVariable object are assigned to the same abstract - * name (locally or by the parent) - * @param n1 one of the QuantifiableVariable objects to be tested iff they have - * been assigned the same abstract name - * @param n2 one of the QuantifiableVariable objects to be tested - * @return true iff n1 and n2 are mapped - * to the same abstract name - */ - public boolean sameAbstractName(QuantifiableVariable n1, QuantifiableVariable n2) { - return false; - } - - - public String toString() { - return "empty"; - } + private static class EmptyRenameTable extends RenameTable { + + private EmptyRenameTable() { + super(null, DefaultImmutableMap.nilMap(), 0); + } + + /** + * returns true iff the given name is mapped to an abstract name. The test is performed in + * the local as well as in the parent renaming table. + * + * @param n the QuantifiableVariable object the existence of an abstract name is checked. + * @return true if n has been already assigned to an abstract name + */ + public boolean contains(QuantifiableVariable n) { + return false; + } + + /** + * does nearly the same as {@link #contains(QuantifiableVariable)} but performs the test + * only on the local table- + * + * @param n the QuantifiableVariable object the existence of an abstract name is checked. + * @return true if n has been already locally assigned to an abstract name + */ + public boolean containsLocally(QuantifiableVariable n) { + return false; + } + + /** + * tests if both QuantifiableVariable object are assigned to the same abstract name (locally + * or by the parent) + * + * @param n1 one of the QuantifiableVariable objects to be tested iff they have been + * assigned the same abstract name + * @param n2 one of the QuantifiableVariable objects to be tested + * @return true iff n1 and n2 are mapped to the same abstract name + */ + public boolean sameAbstractName(QuantifiableVariable n1, QuantifiableVariable n2) { + return false; + } + + + public String toString() { + return "empty"; + } } - public RenameTable parent() { + public RenameTable parent() { return parent; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenamingTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenamingTable.java index 0836688ca4a..f30d836f7d5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenamingTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/RenamingTable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashMap; @@ -7,22 +10,24 @@ import de.uka.ilkd.key.java.SourceElement; -public abstract class RenamingTable{ +public abstract class RenamingTable { - public abstract SourceElement getRenaming(SourceElement se); + public abstract SourceElement getRenaming(SourceElement se); public abstract Iterator getRenamingIterator(); - public static RenamingTable getRenamingTable(HashMap hmap){ - if (hmap.size()==0)return null; - if (hmap.size()==1){ - Entry entry = - hmap.entrySet().iterator().next(); - return new SingleRenamingTable(entry.getKey(), entry.getValue()); - } - else return new MultiRenamingTable(hmap); + public static RenamingTable getRenamingTable( + HashMap hmap) { + if (hmap.size() == 0) + return null; + if (hmap.size() == 1) { + Entry entry = + hmap.entrySet().iterator().next(); + return new SingleRenamingTable(entry.getKey(), entry.getValue()); + } else + return new MultiRenamingTable(hmap); } - + public abstract HashMap getHashMap(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Semisequent.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Semisequent.java index 18a811220c2..50ed16da9b2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Semisequent.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Semisequent.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.Iterator; @@ -7,11 +10,10 @@ /** - * This class represents the succedent or antecendent part of a - * sequent. It is more or less a list without duplicates and subsumed - * formulas. This is ensured using method removeRedundancy. In future - * versions it can be enhanced to do other simplifications. A sequent - * and so a semisequent has to be immutable. + * This class represents the succedent or antecendent part of a sequent. It is more or less a list + * without duplicates and subsumed formulas. This is ensured using method removeRedundancy. In + * future versions it can be enhanced to do other simplifications. A sequent and so a semisequent + * has to be immutable. */ public class Semisequent implements Iterable { @@ -20,17 +22,16 @@ public class Semisequent implements Iterable { /** list with the {@link SequentFormula}s of the Semisequent */ private final ImmutableList seqList; - /** used by inner class Empty*/ + /** used by inner class Empty */ private Semisequent() { seqList = ImmutableSLList.nil(); } /** - * creates a new Semisequent with the Semisequent elements in - * seqList; the provided list must be redundance free, i.e., - * the created sequent must be exactly the same as when creating the sequent - * by subsequently inserting all formulas + * creates a new Semisequent with the Semisequent elements in seqList; the provided list must be + * redundance free, i.e., the created sequent must be exactly the same as when creating the + * sequent by subsequently inserting all formulas */ Semisequent(ImmutableList seqList) { assert !seqList.isEmpty(); @@ -38,79 +39,83 @@ private Semisequent() { } - /** creates a new Semisequent with the Semisequent elements in - * seqList */ + /** + * creates a new Semisequent with the Semisequent elements in seqList + */ public Semisequent(SequentFormula seqFormula) { assert seqFormula != null; this.seqList = ImmutableSLList.nil().append(seqFormula); } - /** inserts an element at a specified index performing redundancy - * checks, this may result in returning same semisequent if - * inserting would create redundancies + /** + * inserts an element at a specified index performing redundancy checks, this may result in + * returning same semisequent if inserting would create redundancies + * * @param idx int encoding the place the element has to be put * @param sequentFormula {@link SequentFormula} to be inserted - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insert(int idx, SequentFormula sequentFormula) { return removeRedundance(idx, sequentFormula); } - /** inserts the elements of the list at the specified index - * performing redundancy checks + /** + * inserts the elements of the list at the specified index performing redundancy checks + * * @param idx int encoding the place where the insertion starts - * @param insertionList IList to be inserted - * starting at idx - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @param insertionList IList to be inserted starting at idx + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insert(int idx, ImmutableList insertionList) { return removeRedundance(idx, insertionList); } - /** inserts element at index 0 performing redundancy - * checks, this may result in returning same semisequent if - * inserting would create redundancies + /** + * inserts element at index 0 performing redundancy checks, this may result in returning same + * semisequent if inserting would create redundancies + * * @param sequentFormula SequentFormula to be inserted - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insertFirst(SequentFormula sequentFormula) { - return insert(0,sequentFormula); + return insert(0, sequentFormula); } /** - * inserts element at index 0 performing redundancy - * checks, this may result in returning same semisequent if - * inserting would create redundancies + * inserts element at index 0 performing redundancy checks, this may result in returning same + * semisequent if inserting would create redundancies + * * @param insertions IList to be inserted - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insertFirst(ImmutableList insertions) { return insert(0, insertions); } - /** inserts element at the end of the semisequent performing - * redundancy checks, this may result in returning same - * semisequent if inserting would create redundancies + /** + * inserts element at the end of the semisequent performing redundancy checks, this may result + * in returning same semisequent if inserting would create redundancies + * * @param sequentFormula {@link SequentFormula} to be inserted - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insertLast(SequentFormula sequentFormula) { return insert(size(), sequentFormula); } /** - * inserts the formulas of the list at the end of the semisequent - * performing redundancy checks, this may result in returning same - * semisequent if inserting would create redundancies + * inserts the formulas of the list at the end of the semisequent performing redundancy checks, + * this may result in returning same semisequent if inserting would create redundancies + * * @param insertions the IList to be inserted - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo insertLast(ImmutableList insertions) { return insert(size(), insertions); @@ -118,6 +123,7 @@ public SemisequentChangeInfo insertLast(ImmutableList insertions /** * is this a semisequent that contains no formulas + * * @return true if the semisequent contains no formulas */ public boolean isEmpty() { @@ -126,34 +132,31 @@ public boolean isEmpty() { /** - * inserts new SequentFormula at index idx and removes - * duplicates, perform simplifications etc. - * @param fci null if the formula to be added is new, otherwise an - * object telling which formula is replaced with the new formula - * sequentFormula, and what are the differences between the - * two formulas - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * inserts new SequentFormula at index idx and removes duplicates, perform simplifications etc. + * + * @param fci null if the formula to be added is new, otherwise an object telling which formula + * is replaced with the new formula sequentFormula, and what are the + * differences between the two formulas + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ private SemisequentChangeInfo insertAndRemoveRedundancyHelper(int idx, - SequentFormula sequentFormula, - SemisequentChangeInfo semiCI, - FormulaChangeInfo fci) { + SequentFormula sequentFormula, SemisequentChangeInfo semiCI, FormulaChangeInfo fci) { // Search for equivalent formulas and weakest constraint ImmutableList searchList = semiCI.getFormulaList(); final SequentFormula[] newSeqList = new SequentFormula[searchList.size()]; - SequentFormula cf; - int pos = -1; + SequentFormula cf; + int pos = -1; - while ( !searchList.isEmpty() ) { + while (!searchList.isEmpty()) { ++pos; - cf = searchList.head (); + cf = searchList.head(); searchList = searchList.tail(); - if (sequentFormula != null && - cf.formula().equalsModRenaming(sequentFormula.formula())) { - semiCI.rejectedFormula( sequentFormula ); + if (sequentFormula != null + && cf.formula().equalsModRenaming(sequentFormula.formula())) { + semiCI.rejectedFormula(sequentFormula); return semiCI; // semisequent already contains formula } @@ -173,28 +176,29 @@ private SemisequentChangeInfo insertAndRemoveRedundancyHelper(int idx, searchList = semiCI.getFormulaList().take(pos).prepend(sequentFormula); - while ( pos > 0 ) { + while (pos > 0) { --pos; - searchList = searchList.prepend ( newSeqList[pos] ); + searchList = searchList.prepend(newSeqList[pos]); } // add new formula list to result object - semiCI.setFormulaList ( searchList ); + semiCI.setFormulaList(searchList); return semiCI; } - /** . - * inserts new ConstrainedFormulas starting at index idx and removes - * duplicates, perform simplifications etc. - * @param sequentFormulasToBeInserted the {@link ImmutableList} to be inserted at position idx - * @param idx an int that means insert sequentFormula at the idx-th - * position in the semisequent - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + /** + * . inserts new ConstrainedFormulas starting at index idx and removes duplicates, perform + * simplifications etc. + * + * @param sequentFormulasToBeInserted the {@link ImmutableList} to be inserted + * at position idx + * @param idx an int that means insert sequentFormula at the idx-th position in the semisequent + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ - private SemisequentChangeInfo insertAndRemoveRedundancy - (int idx, ImmutableList sequentFormulasToBeInserted, SemisequentChangeInfo sci) { + private SemisequentChangeInfo insertAndRemoveRedundancy(int idx, + ImmutableList sequentFormulasToBeInserted, SemisequentChangeInfo sci) { int pos = idx; ImmutableList oldFormulas = sci.getFormulaList(); @@ -203,7 +207,7 @@ private SemisequentChangeInfo insertAndRemoveRedundancyHelper(int idx, final SequentFormula aSequentFormula = sequentFormulasToBeInserted.head(); sequentFormulasToBeInserted = sequentFormulasToBeInserted.tail(); - sci = insertAndRemoveRedundancyHelper ( pos, aSequentFormula, sci, null ); + sci = insertAndRemoveRedundancyHelper(pos, aSequentFormula, sci, null); if (sci.getFormulaList() != oldFormulas) { pos = sci.getIndex() + 1; @@ -213,77 +217,70 @@ private SemisequentChangeInfo insertAndRemoveRedundancyHelper(int idx, return complete(sci); } - /** . - * inserts new ConstrainedFormulas starting at index idx and removes - * duplicates, perform simplifications etc. + /** + * . inserts new ConstrainedFormulas starting at index idx and removes duplicates, perform + * simplifications etc. + * * @param sequentFormula the IList to be inserted at position idx - * @param idx an int that means insert sequentFormula at the idx-th - * position in the semisequent - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @param idx an int that means insert sequentFormula at the idx-th position in the semisequent + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ - private SemisequentChangeInfo removeRedundance - (int idx, ImmutableList sequentFormula) { + private SemisequentChangeInfo removeRedundance(int idx, + ImmutableList sequentFormula) { return insertAndRemoveRedundancy(idx, sequentFormula, new SemisequentChangeInfo(seqList)); } - /** . - * inserts new SequentFormula at index {@code idx} and removes duplicates, perform simplifications etc. + /** + * . inserts new SequentFormula at index {@code idx} and removes duplicates, perform + * simplifications etc. + * * @param sequentFormula the SequentFormula to be inserted at position idx - * @param idx an int that means insert sequentFormula at the idx-th - * position in the semisequent - * @return new Semisequent with sequentFormula at index idx and removed - * redundancies + * @param idx an int that means insert sequentFormula at the idx-th position in the semisequent + * @return new Semisequent with sequentFormula at index idx and removed redundancies */ - private SemisequentChangeInfo removeRedundance(int idx, - SequentFormula sequentFormula) { - return complete - (insertAndRemoveRedundancyHelper(idx, sequentFormula, - new SemisequentChangeInfo(seqList), null)); + private SemisequentChangeInfo removeRedundance(int idx, SequentFormula sequentFormula) { + return complete(insertAndRemoveRedundancyHelper(idx, sequentFormula, + new SemisequentChangeInfo(seqList), null)); } /** * replaces the element at place idx with sequentFormula * - * @param pos - * the PosInOccurrence describing the position of and within the - * formula below which the formula differs from the new formula - * sequentFormula - * @param sequentFormula - * the SequentFormula replacing the old element at index idx - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @param pos the PosInOccurrence describing the position of and within the formula below which + * the formula differs from the new formula sequentFormula + * @param sequentFormula the SequentFormula replacing the old element at index idx + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ - public SemisequentChangeInfo replace(PosInOccurrence pos, - SequentFormula sequentFormula) { + public SemisequentChangeInfo replace(PosInOccurrence pos, SequentFormula sequentFormula) { final int idx = indexOf(pos.sequentFormula()); - final FormulaChangeInfo fci = new FormulaChangeInfo ( pos, sequentFormula ); + final FormulaChangeInfo fci = new FormulaChangeInfo(pos, sequentFormula); return complete(insertAndRemoveRedundancyHelper(idx, sequentFormula, remove(idx), fci)); } /** * replaces the idx-th formula by sequentFormula + * * @param idx the int with the position of the formula to be replaced * @param sequentFormula the SequentFormula replacing the formula at the given position - * @return a SemisequentChangeInfo containing the new sequent and a diff to the old - * one + * @return a SemisequentChangeInfo containing the new sequent and a diff to the old one */ public SemisequentChangeInfo replace(int idx, SequentFormula sequentFormula) { - return complete(insertAndRemoveRedundancyHelper ( idx, sequentFormula, remove(idx), null )); + return complete(insertAndRemoveRedundancyHelper(idx, sequentFormula, remove(idx), null)); } /** - * replaces the element at place idx with the first element of the - * given list and adds the rest of the list to the semisequent - * behind the replaced formula + * replaces the element at place idx with the first element of the given list and adds the rest + * of the list to the semisequent behind the replaced formula + * * @param pos the formula to be replaced - * @param replacements the IList whose head - * replaces the element at index idx and the tail is added to the - * semisequent - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * @param replacements the IList whose head replaces the element at index idx + * and the tail is added to the semisequent + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo replace(PosInOccurrence pos, ImmutableList replacements) { @@ -293,7 +290,8 @@ public SemisequentChangeInfo replace(PosInOccurrence pos, /** * replaces the formula at position {@code idx} by the given list of formulas - * @param idx the position + * + * @param idx the position * @param replacements the new formulas * @return change information including the resulting semisequent after the replacement */ @@ -307,47 +305,49 @@ public int size() { } /** - * creates a semisequent out of the semisequent change info (semiCI) - * object and hands it over to semiCI - * @deprecated Use {@link de.uka.ilkd.key.logic.SemisequentChangeInfo#complete(de.uka.ilkd.key.logic.Semisequent)} instead + * creates a semisequent out of the semisequent change info (semiCI) object and hands it over to + * semiCI + * + * @deprecated Use + * {@link de.uka.ilkd.key.logic.SemisequentChangeInfo#complete(de.uka.ilkd.key.logic.Semisequent)} + * instead */ @Deprecated - private SemisequentChangeInfo complete(SemisequentChangeInfo semiCI) - { + private SemisequentChangeInfo complete(SemisequentChangeInfo semiCI) { return semiCI; } /** * removes an element - * @param idx int being the index of the element that has to - * be removed - * @return a semi sequent change information object with the new semisequent - * and information which formulas have been added or removed + * + * @param idx int being the index of the element that has to be removed + * @return a semi sequent change information object with the new semisequent and information + * which formulas have been added or removed */ public SemisequentChangeInfo remove(int idx) { ImmutableList newList = seqList; int index = 0; - if (idx<0 || idx>=size()) { + if (idx < 0 || idx >= size()) { return complete(new SemisequentChangeInfo(seqList)); } final SequentFormula[] temp = new SequentFormula[idx]; - while (index=0; k--) { + for (int k = index - 1; k >= 0; k--) { newList = newList.prepend(temp[k]); } @@ -359,9 +359,8 @@ public SemisequentChangeInfo remove(int idx) { } /** - * returns the index of the given {@link SequentFormula} or {@code -1} - * if the sequent formula is not found. Equality of sequent formulas - * is checked sing the identy check (i.e.,{@link ==}) + * returns the index of the given {@link SequentFormula} or {@code -1} if the sequent formula is + * not found. Equality of sequent formulas is checked sing the identy check (i.e.,{@link ==}) * * @param sequentFormula the {@link SequentFormula} to look for * @return index of sequentFormula (-1 if not found) @@ -379,12 +378,13 @@ public int indexOf(SequentFormula sequentFormula) { return -1; } - /** gets the element at a specific index - * @param idx int representing the index of the element we - * want to have + /** + * gets the element at a specific index + * + * @param idx int representing the index of the element we want to have * @return {@link SequentFormula} found at index idx - * @throws IndexOutOfBoundsException if idx is negative or - * greater or equal to {@link Sequent#size()} + * @throws IndexOutOfBoundsException if idx is negative or greater or equal to + * {@link Sequent#size()} */ public SequentFormula get(int idx) { if (idx < 0 || idx >= seqList.size()) { @@ -398,21 +398,21 @@ public SequentFormula getFirst() { return seqList.head(); } - /** checks if the {@link SequentFormula} occurs in this - * Semisequent (identity check) + /** + * checks if the {@link SequentFormula} occurs in this Semisequent (identity check) + * * @param sequentFormula the {@link SequentFormula} to look for - * @return true iff. sequentFormula has been found in this - * Semisequent + * @return true iff. sequentFormula has been found in this Semisequent */ public boolean contains(SequentFormula sequentFormula) { - return indexOf(sequentFormula)!=-1; + return indexOf(sequentFormula) != -1; } - /** checks if a {@link SequentFormula} is in this Semisequent - * (equality check) + /** + * checks if a {@link SequentFormula} is in this Semisequent (equality check) + * * @param sequentFormula the {@link SequentFormula} to look for - * @return true iff. sequentFormula has been found in this - * Semisequent + * @return true iff. sequentFormula has been found in this Semisequent */ public boolean containsEqual(SequentFormula sequentFormula) { return seqList.contains(sequentFormula); @@ -420,6 +420,7 @@ public boolean containsEqual(SequentFormula sequentFormula) { /** * returns iterator about the elements of the sequent + * * @return Iterator */ @Override @@ -427,13 +428,13 @@ public Iterator iterator() { return seqList.iterator(); } - public ImmutableList asList () { + public ImmutableList asList() { return seqList; } @Override public boolean equals(Object o) { - if ( ! ( o instanceof Semisequent ) ) { + if (!(o instanceof Semisequent)) { return false; } return seqList.equals(((Semisequent) o).seqList); @@ -441,8 +442,8 @@ public boolean equals(Object o) { @Override - public int hashCode () { - return seqList.hashCode (); + public int hashCode() { + return seqList.hashCode(); } @@ -455,41 +456,46 @@ public String toString() { // inner class used to represent an empty semisequent - private static class Empty extends Semisequent{ + private static class Empty extends Semisequent { private Empty() { super(); } - /** inserts the element always at index 0 ignores the first - * argument + /** + * inserts the element always at index 0 ignores the first argument + * * @param idx int encoding the place the element has to be put * @param sequentFormula {@link SequentFormula} to be inserted - * @return semisequent change information object with new semisequent - * with sequentFormula at place idx + * @return semisequent change information object with new semisequent with sequentFormula at + * place idx */ @Override public SemisequentChangeInfo insert(int idx, SequentFormula sequentFormula) { return insertFirst(sequentFormula); } - /** inserts the element at index 0 + /** + * inserts the element at index 0 + * * @param sequentFormula {@link SequentFormula} to be inserted - * @return semisequent change information object with new semisequent - * with sequentFormula at place idx + * @return semisequent change information object with new semisequent with sequentFormula at + * place idx */ @Override public SemisequentChangeInfo insertFirst(SequentFormula sequentFormula) { - final SemisequentChangeInfo sci = new SemisequentChangeInfo - (ImmutableSLList.nil().prepend(sequentFormula)); + final SemisequentChangeInfo sci = new SemisequentChangeInfo( + ImmutableSLList.nil().prepend(sequentFormula)); sci.addedFormula(0, sequentFormula); return sci; } - /** inserts the element at the end of the semisequent + /** + * inserts the element at the end of the semisequent + * * @param sequentFormula {@link SequentFormula} to be inserted - * @return semisequent change information object with new semisequent - * with sequentFormula at place idx + * @return semisequent change information object with new semisequent with sequentFormula at + * place idx */ @Override public SemisequentChangeInfo insertLast(SequentFormula sequentFormula) { @@ -499,6 +505,7 @@ public SemisequentChangeInfo insertLast(SequentFormula sequentFormula) { /** * is this a semisequent that contains no formulas + * * @return true if the semisequent contains no formulas */ @Override @@ -506,13 +513,13 @@ public boolean isEmpty() { return true; } - /** replaces the element at place idx with sequentFormula - * @param idx an int specifying the index of the element that - * has to be replaced - * @param sequentFormula the {@link SequentFormula} replacing the old - * element at index idx - * @return semisequent change information object with new semisequent - * with sequentFormula at place idx + /** + * replaces the element at place idx with sequentFormula + * + * @param idx an int specifying the index of the element that has to be replaced + * @param sequentFormula the {@link SequentFormula} replacing the old element at index idx + * @return semisequent change information object with new semisequent with sequentFormula at + * place idx */ @Override public SemisequentChangeInfo replace(int idx, SequentFormula sequentFormula) { @@ -525,20 +532,21 @@ public int size() { return 0; } - /** removes an element - * @param idx int being the index of the element that has to - * be removed - * @return semisequent change information object with an empty - * semisequent as result + /** + * removes an element + * + * @param idx int being the index of the element that has to be removed + * @return semisequent change information object with an empty semisequent as result */ @Override public SemisequentChangeInfo remove(int idx) { return new SemisequentChangeInfo(ImmutableSLList.nil()); } - /** returns index of a {@link SequentFormula} - * @param sequentFormula the {@link SequentFormula} the index want to be - * determined + /** + * returns index of a {@link SequentFormula} + * + * @param sequentFormula the {@link SequentFormula} the index want to be determined * @return index of sequentFormula */ @Override @@ -546,9 +554,10 @@ public int indexOf(SequentFormula sequentFormula) { return -1; } - /** gets the element at a specific index - * @param idx int representing the index of the element we - * want to have + /** + * gets the element at a specific index + * + * @param idx int representing the index of the element we want to have * @return {@link SequentFormula} found at index idx */ @Override @@ -556,17 +565,19 @@ public SequentFormula get(int idx) { return null; } - /** @return the first SequentFormula of this Semisequent + /** + * @return the first SequentFormula of this Semisequent */ @Override public SequentFormula getFirst() { return null; } - /** checks if a {@link SequentFormula} is in this Semisequent + /** + * checks if a {@link SequentFormula} is in this Semisequent + * * @param sequentFormula the {@link SequentFormula} to look for - * @return true iff. sequentFormula has been found in this - * Semisequent + * @return true iff. sequentFormula has been found in this Semisequent */ @Override public boolean contains(SequentFormula sequentFormula) { @@ -579,7 +590,7 @@ public boolean equals(Object o) { } @Override - public int hashCode () { + public int hashCode() { return 34567; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SemisequentChangeInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SemisequentChangeInfo.java index 14b684d382b..91f4bfbaf6f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SemisequentChangeInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SemisequentChangeInfo.java @@ -1,212 +1,213 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; /** - * Records the changes made to a semisequent. Keeps track of added and - * removed formula to the semisequents. + * Records the changes made to a semisequent. Keeps track of added and removed formula to the + * semisequents. */ public class SemisequentChangeInfo { - + /** contains the added formulas to the semisequent */ - private ImmutableList added = ImmutableSLList.nil(); + private ImmutableList added = ImmutableSLList.nil(); /** contains the removed formulas from the semisequent */ private ImmutableList removed = ImmutableSLList.nil(); /** contains the modified formulas from the semisequent */ private ImmutableList modified = ImmutableSLList.nil(); /** stores the redundance free formula list of the semisequent */ - private ImmutableList modifiedSemisequent = ImmutableSLList.nil(); + private ImmutableList modifiedSemisequent = + ImmutableSLList.nil(); /** - * contains formulas that have been tried to add, but which have been rejected due to - * already existing formulas in the sequent subsuming these formulas + * contains formulas that have been tried to add, but which have been rejected due to already + * existing formulas in the sequent subsuming these formulas */ - private ImmutableList rejected = ImmutableSLList.nil(); - + private ImmutableList rejected = ImmutableSLList.nil(); + /** */ private int lastFormulaIndex = -1; - - public SemisequentChangeInfo() { - } + + public SemisequentChangeInfo() {} public SemisequentChangeInfo(ImmutableList formulas) { - this.modifiedSemisequent = formulas; + this.modifiedSemisequent = formulas; } - /** + /** * returns true if the semisequent has changed */ public boolean hasChanged() { - return !added.isEmpty() || - !removed.isEmpty() || - !modified.isEmpty(); + return !added.isEmpty() || !removed.isEmpty() || !modified.isEmpty(); } /** - * sets the list of constrained formula containing all formulas of - * the semisequent after the operation + * sets the list of constrained formula containing all formulas of the semisequent after the + * operation */ public void setFormulaList(ImmutableList list) { - modifiedSemisequent = list; + modifiedSemisequent = list; } /** * returns the list of constrained formula of the new semisequent */ public ImmutableList getFormulaList() { - return modifiedSemisequent; + return modifiedSemisequent; } - - /** + + /** * logs an added formula at position idx */ public void addedFormula(int idx, SequentFormula cf) { - added = added.prepend(cf); - lastFormulaIndex = idx; + added = added.prepend(cf); + lastFormulaIndex = idx; } - /** + /** * logs a modified formula at position idx */ - public void modifiedFormula(int idx, - FormulaChangeInfo fci) { - // This information can overwrite older records about removed - // formulas - removed = removed.removeAll - ( fci.getPositionOfModification ().sequentFormula () ); - modified = modified.prepend ( fci ); - lastFormulaIndex = idx; + public void modifiedFormula(int idx, FormulaChangeInfo fci) { + // This information can overwrite older records about removed + // formulas + removed = removed.removeAll(fci.getPositionOfModification().sequentFormula()); + modified = modified.prepend(fci); + lastFormulaIndex = idx; } - /** + /** * returns the list of all added constrained formulas + * * @return IList added to the semisequent */ public ImmutableList addedFormulas() { - return added; + return added; } - /** + /** * returns the list of all removed constrained formulas + * * @return IList removed from the semisequent */ public ImmutableList removedFormulas() { - return removed; + return removed; } - + /** - * returns a list of formulas that have been tried to add to - * the semisequent but got rejected as they were redundant + * returns a list of formulas that have been tried to add to the semisequent but got rejected as + * they were redundant + * * @return list of formulas rejected due to redundancy */ public ImmutableList rejectedFormulas() { return this.rejected; } - - + + /** - * adding formula f to the semisequent failed due to - * a redundance check. This means an equal or stronger formula - * is already present in the semisequent - * @param f the SequentFormula + * adding formula f to the semisequent failed due to a redundance check. This means an + * equal or stronger formula is already present in the semisequent + * + * @param f the SequentFormula */ public void rejectedFormula(SequentFormula f) { - this.rejected = this.rejected.append(f); + this.rejected = this.rejected.append(f); } - /** + /** * returns the list of all modification positions - * @return IList modified within the - * semisequent + * + * @return IList modified within the semisequent */ public ImmutableList modifiedFormulas() { - return modified; - } + return modified; + } - /** + /** * logs an added formula at position idx */ public void removedFormula(int idx, SequentFormula cf) { - removed = removed.prepend(cf); + removed = removed.prepend(cf); - lastFormulaIndex = ( lastFormulaIndex == idx ) ? -1 : - lastFormulaIndex > idx ? lastFormulaIndex - 1 : lastFormulaIndex; + lastFormulaIndex = (lastFormulaIndex == idx) ? -1 + : lastFormulaIndex > idx ? lastFormulaIndex - 1 : lastFormulaIndex; + + if (lastFormulaIndex < -1) { + lastFormulaIndex = -1; + } - if (lastFormulaIndex < -1) { - lastFormulaIndex = -1; - } - } - - + + /** - * This method combines this change information from this info and its successor. - * ATTENTION: it takes over ownership over {@link succ} and does not release it. This means - * when invoking the method it must be snsured that succ is never used afterwards. + * This method combines this change information from this info and its successor. ATTENTION: it + * takes over ownership over {@link succ} and does not release it. This means when invoking the + * method it must be snsured that succ is never used afterwards. */ public void combine(SemisequentChangeInfo succ) { - final SemisequentChangeInfo predecessor = this; - if (succ == predecessor) { - return ; - } - - for (SequentFormula sf : succ.removed) { - predecessor.added = predecessor.added.removeAll(sf); - - boolean skip = false; - for (FormulaChangeInfo fci : predecessor.modified) { - if (fci.getNewFormula() == sf) { - predecessor.modified = predecessor.modified.removeAll(fci); - if (!predecessor.removed.contains(fci.getOriginalFormula())) { - predecessor.removed = predecessor.removed.append(fci.getOriginalFormula()); + final SemisequentChangeInfo predecessor = this; + if (succ == predecessor) { + return; + } + + for (SequentFormula sf : succ.removed) { + predecessor.added = predecessor.added.removeAll(sf); + + boolean skip = false; + for (FormulaChangeInfo fci : predecessor.modified) { + if (fci.getNewFormula() == sf) { + predecessor.modified = predecessor.modified.removeAll(fci); + if (!predecessor.removed.contains(fci.getOriginalFormula())) { + predecessor.removed = predecessor.removed.append(fci.getOriginalFormula()); + } + skip = true; + break; } - skip = true; - break; - } - } - if (!skip) { - predecessor.removedFormula(succ.lastFormulaIndex, sf); - } - } - - for (FormulaChangeInfo fci : succ.modified) { - if (predecessor.addedFormulas().contains(fci.getOriginalFormula())) { - predecessor.added = predecessor.added.removeAll(fci.getOriginalFormula()); - predecessor.addedFormula(succ.lastFormulaIndex, fci.getNewFormula()); - } else { - predecessor.modifiedFormula(succ.lastFormulaIndex, fci); - } - } - - for (SequentFormula sf : succ.added) { - predecessor.removed = predecessor.removed.removeAll(sf); - if (!predecessor.added.contains(sf)) { - predecessor.addedFormula(succ.lastFormulaIndex, sf); - } - } - - for (SequentFormula sf : succ.rejected) { - if (!predecessor.rejected.contains(sf)) { - predecessor.rejectedFormula(sf); - } - } - - predecessor.lastFormulaIndex = succ.lastFormulaIndex; - predecessor.modifiedSemisequent = succ.modifiedSemisequent; - } - + } + if (!skip) { + predecessor.removedFormula(succ.lastFormulaIndex, sf); + } + } + + for (FormulaChangeInfo fci : succ.modified) { + if (predecessor.addedFormulas().contains(fci.getOriginalFormula())) { + predecessor.added = predecessor.added.removeAll(fci.getOriginalFormula()); + predecessor.addedFormula(succ.lastFormulaIndex, fci.getNewFormula()); + } else { + predecessor.modifiedFormula(succ.lastFormulaIndex, fci); + } + } + + for (SequentFormula sf : succ.added) { + predecessor.removed = predecessor.removed.removeAll(sf); + if (!predecessor.added.contains(sf)) { + predecessor.addedFormula(succ.lastFormulaIndex, sf); + } + } + + for (SequentFormula sf : succ.rejected) { + if (!predecessor.rejected.contains(sf)) { + predecessor.rejectedFormula(sf); + } + } + + predecessor.lastFormulaIndex = succ.lastFormulaIndex; + predecessor.modifiedSemisequent = succ.modifiedSemisequent; + } + /** * returns the index of the last added formula */ public int getIndex() { - return lastFormulaIndex; + return lastFormulaIndex; } - - /** - * returns the semisequent that is the result of the change - * operation + + /** + * returns the semisequent that is the result of the change operation */ - public Semisequent semisequent() { + public Semisequent semisequent() { final Semisequent semisequent; if (modifiedSemisequent.isEmpty()) { semisequent = Semisequent.EMPTY_SEMISEQUENT; @@ -221,11 +222,8 @@ public Semisequent semisequent() { * toString */ public String toString() { - return "changed:"+hasChanged()+ - "\n added (pos):"+added+"("+lastFormulaIndex+")"+ - "\n removed:"+removed+ - "\n modified:"+modified+ - "\n rejected:"+rejected + - "\n new semisequent:"+modifiedSemisequent; - } -} \ No newline at end of file + return "changed:" + hasChanged() + "\n added (pos):" + added + "(" + lastFormulaIndex + ")" + + "\n removed:" + removed + "\n modified:" + modified + "\n rejected:" + rejected + + "\n new semisequent:" + modifiedSemisequent; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sequent.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sequent.java index ac11b1c805c..da65ae46f57 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sequent.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sequent.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashSet; @@ -11,8 +14,8 @@ import de.uka.ilkd.key.logic.op.QuantifiableVariable; /** - * This class represents a sequent. A sequent consists of an antecedent and - * succedent. As a sequent is persistent there is no public constructor. + * This class represents a sequent. A sequent consists of an antecedent and succedent. As a sequent + * is persistent there is no public constructor. *

    * A sequent is created either by using one of the composition methods, that are * {@link Sequent#createSequent}, {@link Sequent#createAnteSequent} and @@ -26,10 +29,9 @@ public class Sequent implements Iterable { /** * creates a new Sequent with empty succedent * - * @param ante - * the Semisequent that plays the antecedent part - * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same - * as EMPTY_SEMISEQUENT + * @param ante the Semisequent that plays the antecedent part + * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same as + * EMPTY_SEMISEQUENT */ public static Sequent createAnteSequent(Semisequent ante) { if (ante.isEmpty()) { @@ -41,12 +43,10 @@ public static Sequent createAnteSequent(Semisequent ante) { /** * creates a new Sequent * - * @param ante - * the Semisequent that plays the antecedent part - * @param succ - * the Semisequent that plays the succedent part - * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same - * as EMPTY_SEMISEQUENT + * @param ante the Semisequent that plays the antecedent part + * @param succ the Semisequent that plays the succedent part + * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same as + * EMPTY_SEMISEQUENT */ public static Sequent createSequent(Semisequent ante, Semisequent succ) { if (ante.isEmpty() && succ.isEmpty()) { @@ -58,10 +58,9 @@ public static Sequent createSequent(Semisequent ante, Semisequent succ) { /** * creates a new Sequent with empty antecedent * - * @param succ - * the Semisequent that plays the succedent part - * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same - * as EMPTY_SEMISEQUENT + * @param succ the Semisequent that plays the succedent part + * @return the new sequent or the EMPTY_SEQUENT if both antec and succ are same as + * EMPTY_SEMISEQUENT */ public static Sequent createSuccSequent(Semisequent succ) { if (succ.isEmpty()) { @@ -91,22 +90,17 @@ private Sequent(Semisequent antecedent, Semisequent succedent) { } /** - * adds a formula to the antecedent (or succedent) of the sequent. Depending on - * the value of first the formulas are inserted at the beginning or end of the - * ante-/succedent. (NOTICE:Sequent determines index using identy (==) not - * equality.) + * adds a formula to the antecedent (or succedent) of the sequent. Depending on the value of + * first the formulas are inserted at the beginning or end of the ante-/succedent. + * (NOTICE:Sequent determines index using identy (==) not equality.) * - * @param cf - * the SequentFormula to be added - * @param antec - * boolean selecting the correct semisequent where to insert the - * formulas. If set to true, the antecedent is taken otherwise the - * succedent. - * @param first - * boolean if true the formula is added at the beginning of the - * ante-/succedent, otherwise to the end - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param cf the SequentFormula to be added + * @param antec boolean selecting the correct semisequent where to insert the formulas. If set + * to true, the antecedent is taken otherwise the succedent. + * @param first boolean if true the formula is added at the beginning of the ante-/succedent, + * otherwise to the end + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ public SequentChangeInfo addFormula(SequentFormula cf, boolean antec, boolean first) { @@ -114,22 +108,18 @@ public SequentChangeInfo addFormula(SequentFormula cf, boolean antec, boolean fi final SemisequentChangeInfo semiCI = first ? seq.insertFirst(cf) : seq.insertLast(cf); - return SequentChangeInfo - .createSequentChangeInfo( - antec, semiCI, composeSequent(antec, semiCI.semisequent()), - this); + return SequentChangeInfo.createSequentChangeInfo(antec, semiCI, + composeSequent(antec, semiCI.semisequent()), this); } /** - * adds a formula to the sequent at the given position. (NOTICE:Sequent - * determines index using identy (==) not equality.) + * adds a formula to the sequent at the given position. (NOTICE:Sequent determines index using + * identy (==) not equality.) * - * @param cf - * a SequentFormula to be added - * @param p - * a PosInOccurrence describes position in the sequent - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param cf a SequentFormula to be added + * @param p a PosInOccurrence describes position in the sequent + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ public SequentChangeInfo addFormula(SequentFormula cf, PosInOccurrence p) { final Semisequent seq = getSemisequent(p); @@ -141,56 +131,45 @@ public SequentChangeInfo addFormula(SequentFormula cf, PosInOccurrence p) { } /** - * adds list of formulas to the antecedent (or succedent) of the sequent. - * Depending on the value of first the formulas are inserted at the beginning or - * end of the ante-/succedent. (NOTICE:Sequent determines index using identity - * (==) not equality.) + * adds list of formulas to the antecedent (or succedent) of the sequent. Depending on the value + * of first the formulas are inserted at the beginning or end of the ante-/succedent. + * (NOTICE:Sequent determines index using identity (==) not equality.) * - * @param insertions - * the IList to be added - * @param antec - * boolean selecting the correct semisequent where to insert the - * formulas. If set to true, the antecedent is taken otherwise the - * succedent. - * @param first - * boolean if true the formulas are added at the beginning of the - * ante-/succedent, otherwise to the end - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param insertions the IList to be added + * @param antec boolean selecting the correct semisequent where to insert the formulas. If set + * to true, the antecedent is taken otherwise the succedent. + * @param first boolean if true the formulas are added at the beginning of the ante-/succedent, + * otherwise to the end + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ - public SequentChangeInfo addFormula( - ImmutableList insertions, boolean antec, boolean first) { + public SequentChangeInfo addFormula(ImmutableList insertions, boolean antec, + boolean first) { final Semisequent seq = antec ? antecedent : succedent; - final SemisequentChangeInfo semiCI = first - ? seq.insertFirst(insertions) - : seq.insertLast(insertions); + final SemisequentChangeInfo semiCI = + first ? seq.insertFirst(insertions) : seq.insertLast(insertions); - return SequentChangeInfo - .createSequentChangeInfo( - antec, semiCI, composeSequent(antec, semiCI.semisequent()), - this); + return SequentChangeInfo.createSequentChangeInfo(antec, semiCI, + composeSequent(antec, semiCI.semisequent()), this); } /** - * adds the formulas of list insertions to the sequent starting at position p. - * (NOTICE:Sequent determines index using identy (==) not equality.) + * adds the formulas of list insertions to the sequent starting at position p. (NOTICE:Sequent + * determines index using identy (==) not equality.) * - * @param insertions - * a IList with the formulas to be added - * @param p - * the PosInOccurrence describing the position where to insert the - * formulas - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param insertions a IList with the formulas to be added + * @param p the PosInOccurrence describing the position where to insert the formulas + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ - public SequentChangeInfo addFormula( - ImmutableList insertions, PosInOccurrence p) { + public SequentChangeInfo addFormula(ImmutableList insertions, + PosInOccurrence p) { final Semisequent seq = getSemisequent(p); - final SemisequentChangeInfo semiCI = seq.insert( - seq.indexOf(p.sequentFormula()), insertions); + final SemisequentChangeInfo semiCI = + seq.insert(seq.indexOf(p.sequentFormula()), insertions); return SequentChangeInfo.createSequentChangeInfo(p.isInAntec(), semiCI, composeSequent(p.isInAntec(), semiCI.semisequent()), this); @@ -202,15 +181,13 @@ public Semisequent antecedent() { } /** - * replaces the formula at the given position with another one (NOTICE:Sequent - * determines index using identity (==) not equality.) + * replaces the formula at the given position with another one (NOTICE:Sequent determines index + * using identity (==) not equality.) * - * @param newCF - * the SequentFormula replacing the old one - * @param p - * a PosInOccurrence describes position in the sequent - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param newCF the SequentFormula replacing the old one + * @param p a PosInOccurrence describes position in the sequent + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ public SequentChangeInfo changeFormula(SequentFormula newCF, PosInOccurrence p) { final SemisequentChangeInfo semiCI = getSemisequent(p).replace(p, newCF); @@ -220,29 +197,23 @@ public SequentChangeInfo changeFormula(SequentFormula newCF, PosInOccurrence p) } /** - * replaces the formula at position p with the head of the given list and adds - * the remaining list elements to the sequent (NOTICE:Sequent determines index - * using identity (==) not equality.) + * replaces the formula at position p with the head of the given list and adds the remaining + * list elements to the sequent (NOTICE:Sequent determines index using identity (==) not + * equality.) * - * @param replacements - * the IList whose head replaces the formula at - * position p and adds the rest of the list behind the changed - * formula - * @param p - * a PosInOccurrence describing the position of the formula to be - * replaced - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param replacements the IList whose head replaces the formula at position p + * and adds the rest of the list behind the changed formula + * @param p a PosInOccurrence describing the position of the formula to be replaced + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ - public SequentChangeInfo changeFormula( - ImmutableList replacements, PosInOccurrence p) { + public SequentChangeInfo changeFormula(ImmutableList replacements, + PosInOccurrence p) { final SemisequentChangeInfo semiCI = getSemisequent(p).replace(p, replacements); - final SequentChangeInfo sci = SequentChangeInfo - .createSequentChangeInfo( - p.isInAntec(), semiCI, - composeSequent(p.isInAntec(), semiCI.semisequent()), this); + final SequentChangeInfo sci = SequentChangeInfo.createSequentChangeInfo(p.isInAntec(), + semiCI, composeSequent(p.isInAntec(), semiCI.semisequent()), this); return sci; } @@ -251,10 +222,8 @@ public SequentChangeInfo changeFormula( * replaces the antecedent ({@code antec} is true) of this sequent by the given * {@link Semisequent} similar for the succedent if {@code antec} is false. * - * @param antec - * if the antecedent or succedent shall be replaced - * @param semiSeq - * the {@link Semisequent} to use + * @param antec if the antecedent or succedent shall be replaced + * @param semiSeq the {@link Semisequent} to use * @return the resulting sequent */ private Sequent composeSequent(boolean antec, Semisequent semiSeq) { @@ -276,8 +245,7 @@ private Sequent composeSequent(boolean antec, Semisequent semiSeq) { /** * determines if the sequent is empty. * - * @return true iff the sequent consists of two instances of - * Semisequent.EMPTY_SEMISEQUENT + * @return true iff the sequent consists of two instances of Semisequent.EMPTY_SEMISEQUENT */ public boolean isEmpty() { return antecedent.isEmpty() && succedent.isEmpty(); @@ -294,18 +262,18 @@ public boolean equals(Object o) { } /** - * Computes the position of the given sequent formula on the proof sequent, - * starting with one for the very first sequent formula. + * Computes the position of the given sequent formula on the proof sequent, starting with one + * for the very first sequent formula. + * * @param inAntec a boolean stating whether we search in the antecedent or the succedent * @param cfma the given sequent formula - * @return an integer strictly greater than zero for the position of the given - * sequent formula on the proof sequent. + * @return an integer strictly greater than zero for the position of the given sequent formula + * on the proof sequent. */ public int formulaNumberInSequent(boolean inAntec, SequentFormula cfma) { int n = inAntec ? 0 : antecedent.size(); - final Iterator formIter = inAntec - ? antecedent.iterator() - : succedent.iterator(); + final Iterator formIter = + inAntec ? antecedent.iterator() : succedent.iterator(); while (formIter.hasNext()) { n++; if (formIter.next().equals(cfma)) { @@ -327,8 +295,7 @@ public SequentFormula getFormulabyNr(int formulaNumber) { } /** - * returns the semisequent in which the SequentFormula described by - * PosInOccurrence p lies + * returns the semisequent in which the SequentFormula described by PosInOccurrence p lies */ private Semisequent getSemisequent(PosInOccurrence p) { return p.isInAntec() ? antecedent() : succedent(); @@ -354,28 +321,27 @@ public boolean numberInAntec(int formulaNumber) { } /** - * removes the formula at position p (NOTICE:Sequent determines index using - * identity (==) not equality.) + * removes the formula at position p (NOTICE:Sequent determines index using identity (==) not + * equality.) * - * @param p - * a PosInOccurrence that describes position in the sequent - * @return a SequentChangeInfo which contains the new sequent and information - * which formulas have been added or removed + * @param p a PosInOccurrence that describes position in the sequent + * @return a SequentChangeInfo which contains the new sequent and information which formulas + * have been added or removed */ public SequentChangeInfo removeFormula(PosInOccurrence p) { final Semisequent seq = getSemisequent(p); final SemisequentChangeInfo semiCI = seq.remove(seq.indexOf(p.sequentFormula())); - final SequentChangeInfo sci = SequentChangeInfo.createSequentChangeInfo( - p.isInAntec(), semiCI, - composeSequent(p.isInAntec(), semiCI.semisequent()), this); + final SequentChangeInfo sci = SequentChangeInfo.createSequentChangeInfo(p.isInAntec(), + semiCI, composeSequent(p.isInAntec(), semiCI.semisequent()), this); return sci; } /** * Computes the size of the proof sequent recursively (decends to antecedent and succedent). + * * @return the size of the proof sequent as an integer number */ public int size() { @@ -398,11 +364,10 @@ public String toString() { } /** - * returns true iff the given variable is bound in a formula of a SequentFormula - * in this sequent. + * returns true iff the given variable is bound in a formula of a SequentFormula in this + * sequent. * - * @param v - * the bound variable to search for + * @param v the bound variable to search for */ public boolean varIsBound(QuantifiableVariable v) { final Iterator it = iterator(); @@ -448,6 +413,7 @@ static class SequentIterator implements Iterator { /** * Constructs a new iterator over a proof sequent. + * * @param ante The antecedent of the sequent. * @param succ The succedent of the sequent. */ @@ -511,8 +477,7 @@ public Set getOccuringTermLabels() { /** * used to check whether this sequent contains a given sequent formula. * - * @param form - * the given formula + * @param form the given formula * @return true if this sequent contains the given formula */ public boolean contains(SequentFormula form) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentChangeInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentChangeInfo.java index 95caf38703f..6fa90f4a61e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentChangeInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentChangeInfo.java @@ -1,346 +1,349 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; /** - * Records the changes made to a sequent. Keeps track of added and removed - * formula to one of the semisequents. The intersection of added and removed - * formulas of the same semisequent may not be empty, in particular this means - * that a formula added and removed afterwards will occur in both lists. The - * situation where this can happen is that a list of formulas had to be added to - * the sequent and the list has not been redundance free. + * Records the changes made to a sequent. Keeps track of added and removed formula to one of the + * semisequents. The intersection of added and removed formulas of the same semisequent may not be + * empty, in particular this means that a formula added and removed afterwards will occur in both + * lists. The situation where this can happen is that a list of formulas had to be added to the + * sequent and the list has not been redundance free. */ public class SequentChangeInfo { - - - /** change information related to the antecedent, this means the - * there added and removed formulas*/ - private SemisequentChangeInfo antecedent; - - /** change information related to the antecedent, this means the - * there added and removed formulas*/ - private SemisequentChangeInfo succedent; - - /** - * the sequent before the changes - */ - private Sequent originalSequent; - - /** - * the sequent after the changes - */ - private Sequent resultingSequent; - - /** - * creates a new sequent change info whose semisequent described by position - * pos has changed. The made changes are stored in semiCI and the resulting - * sequent is given by result - * - * @param pos the PosInOccurrence describing the semisequent where - * the changes took place - * @param semiCI the SemisequentChangeInfo describing the changes in - * detail (which formulas have been added/removed) - * @return the sequent change information object describing the - * complete changes made to the sequent together with the operations - * result. - */ - public static SequentChangeInfo createSequentChangeInfo - (PosInOccurrence pos, SemisequentChangeInfo semiCI, Sequent result, Sequent original) { - return createSequentChangeInfo(pos.isInAntec(), semiCI, result, original); - } - - /** - * creates a new sequent change info whose semisequent described by the - * value of the selector antec (true selects antecedent; false selects - * succedent) has changed. The made changes are stored in semiCI and the - * resulting sequent is given by result - * - * @param antec a boolean indicating if the given semisequent change information - * describes the changes of the antecedent or succedent - * @param semiCI the SemisequentChangeInfo describing the - * changes in detail (which formulas have been added/removed) - * @param result the Sequent which is the result of the changes - * @param original the Sequent to which the described changes have been - * applied - * @return the sequent change information object describing the - * complete changes made to the sequent together with the operations - * result. */ - public static SequentChangeInfo createSequentChangeInfo - (boolean antec, SemisequentChangeInfo semiCI, Sequent result, Sequent original) { - if (antec) { - return new SequentChangeInfo(semiCI, null, result, original); - } else { - return new SequentChangeInfo(null, semiCI, result, original); + + + /** + * change information related to the antecedent, this means the there added and removed formulas + */ + private SemisequentChangeInfo antecedent; + + /** + * change information related to the antecedent, this means the there added and removed formulas + */ + private SemisequentChangeInfo succedent; + + /** + * the sequent before the changes + */ + private Sequent originalSequent; + + /** + * the sequent after the changes + */ + private Sequent resultingSequent; + + /** + * creates a new sequent change info whose semisequent described by position pos has changed. + * The made changes are stored in semiCI and the resulting sequent is given by result + * + * @param pos the PosInOccurrence describing the semisequent where the changes took place + * @param semiCI the SemisequentChangeInfo describing the changes in detail (which formulas have + * been added/removed) + * @return the sequent change information object describing the complete changes made to the + * sequent together with the operations result. + */ + public static SequentChangeInfo createSequentChangeInfo(PosInOccurrence pos, + SemisequentChangeInfo semiCI, Sequent result, Sequent original) { + return createSequentChangeInfo(pos.isInAntec(), semiCI, result, original); + } + + /** + * creates a new sequent change info whose semisequent described by the value of the selector + * antec (true selects antecedent; false selects succedent) has changed. The made changes are + * stored in semiCI and the resulting sequent is given by result + * + * @param antec a boolean indicating if the given semisequent change information describes the + * changes of the antecedent or succedent + * @param semiCI the SemisequentChangeInfo describing the changes in detail (which formulas have + * been added/removed) + * @param result the Sequent which is the result of the changes + * @param original the Sequent to which the described changes have been applied + * @return the sequent change information object describing the complete changes made to the + * sequent together with the operations result. + */ + public static SequentChangeInfo createSequentChangeInfo(boolean antec, + SemisequentChangeInfo semiCI, Sequent result, Sequent original) { + if (antec) { + return new SequentChangeInfo(semiCI, null, result, original); + } else { + return new SequentChangeInfo(null, semiCI, result, original); + } + } + + /** + * creates a new sequent change info whose semisequents have changed. The made changes are + * stored in semiCI and the resulting sequent is given by result + * + * @param anteCI the SemisequentChangeInfo describing the changes of the antecedent in detail + * (which formulas have been added/removed) + * @param sucCI the SemisequentChangeInfo describing the changes of the succedent detail (which + * formulas have been added/removed) + * @return the sequent change information object describing the complete changes made to the + * sequent together with the operations result. + */ + public static SequentChangeInfo createSequentChangeInfo(SemisequentChangeInfo anteCI, + SemisequentChangeInfo sucCI, Sequent result, Sequent original) { + return new SequentChangeInfo(anteCI, sucCI, result, original); + } + + /** + * creates a new sequent change information object. Therefore it combines the changes to the + * semisequents of the sequent. + * + * @param antecedent the SemisequentChangeInfo describing the changes of the antecedent + * @param succedent the SemisequentChangeInfo describing the changes of the succedent + * @param resultingSequent the Sequent being the result of the changes + * @param originalSequent the Sequent that has been transformed + */ + private SequentChangeInfo(SemisequentChangeInfo antecedent, SemisequentChangeInfo succedent, + Sequent resultingSequent, Sequent originalSequent) { + this.antecedent = antecedent; + this.succedent = succedent; + this.resultingSequent = resultingSequent; + this.originalSequent = originalSequent; + } + + /** + * returns true iff the sequent has been changed by the operation + * + * @return true iff the sequent has been changed by the operation + */ + public boolean hasChanged() { + return (antecedent == null || antecedent.hasChanged()) + || (succedent == null || succedent.hasChanged()); + } + + /** + * returns true if the selected part of sequent has changed. Thereby the flag 'antec' specifies + * the selection: true selects the antecedent and false the succedent of the sequent. + * + * @return true iff the sequent has been changed by the operation + */ + public boolean hasChanged(boolean antec) { + return antec ? (antecedent != null && antecedent.hasChanged()) + : (succedent != null && succedent.hasChanged()); + } + + public SemisequentChangeInfo getSemisequentChangeInfo(boolean antec) { + return antec ? antecedent : succedent; + } + + /** + * The formulas added to one of the semisequents are returned. The selected semisequent depends + * on the value of selector 'antec' which is the antecedent if 'antec' is true and the succedent + * otherwise. + * + * @param antec a boolean used to select one of the two semisequents of a sequent (true means + * antecedent; false means succedent) + * @return list of formulas added to the selected semisequent + */ + public ImmutableList addedFormulas(boolean antec) { + return antec + ? (antecedent != null ? antecedent.addedFormulas() + : ImmutableSLList.nil()) + : (succedent != null ? succedent.addedFormulas() + : ImmutableSLList.nil()); } - } - - /** - * creates a new sequent change info whose semisequents have changed. - * The made changes are stored in semiCI and the resulting sequent is given - * by result - * - * @param anteCI the SemisequentChangeInfo describing the changes of the - * antecedent in detail (which formulas have been added/removed) - * @param sucCI the SemisequentChangeInfo describing the changes of the - * succedent detail (which formulas have been added/removed) - * @return the sequent change information object describing the - * complete changes made to the sequent together with the operations - * result. */ - public static SequentChangeInfo createSequentChangeInfo - (SemisequentChangeInfo anteCI, SemisequentChangeInfo sucCI, Sequent result, Sequent original) { - return new SequentChangeInfo(anteCI, sucCI, result, original); - } - - /** - * creates a new sequent change information object. Therefore it - * combines the changes to the semisequents of the sequent. - * @param antecedent the SemisequentChangeInfo describing the changes of - * the antecedent - * @param succedent the SemisequentChangeInfo describing the changes of - * the succedent - * @param resultingSequent the Sequent being the result of the changes - * @param originalSequent the Sequent that has been transformed - */ - private SequentChangeInfo(SemisequentChangeInfo antecedent, - SemisequentChangeInfo succedent, - Sequent resultingSequent, - Sequent originalSequent) { - this.antecedent = antecedent; - this.succedent = succedent; - this.resultingSequent = resultingSequent; - this.originalSequent = originalSequent; - } - - /** - * returns true iff the sequent has been changed by the operation - * @return true iff the sequent has been changed by the operation - */ - public boolean hasChanged() { - return (antecedent == null || antecedent.hasChanged()) || (succedent == null || succedent.hasChanged()); - } - - /** - * returns true if the selected part of sequent has changed. Thereby the - * flag 'antec' specifies the selection: true selects the antecedent and - * false the succedent of the sequent. - * - * @return true iff the sequent has been changed by the operation */ - public boolean hasChanged(boolean antec) { - return antec ? (antecedent != null && antecedent.hasChanged()) : - (succedent != null && succedent.hasChanged()); - } - - public SemisequentChangeInfo getSemisequentChangeInfo ( boolean antec ) { - return antec ? antecedent : succedent; + + /** + * The formulas added to the sequent are returned as a concatenated list of the formulas added + * to each semisequent. + * + * @return list of formulas added to sequent + */ + public ImmutableList addedFormulas() { + final ImmutableList addedFormulasAntec = addedFormulas(true); + final ImmutableList addedFormulasSucc = addedFormulas(false); + + return concatenateHelper(addedFormulasAntec, addedFormulasSucc); + } - /** - * The formulas added to one of the semisequents are returned. The selected - * semisequent depends on the value of selector 'antec' which is the - * antecedent if 'antec' is true and the succedent otherwise. - * - * @param antec a boolean used to select one of the two semisequents - * of a sequent (true means antecedent; false means succedent) - * @return list of formulas added to the selected semisequent - */ - public ImmutableList addedFormulas(boolean antec) { - return antec ? (antecedent != null ? antecedent.addedFormulas() - : ImmutableSLList.nil()) : - (succedent != null ? succedent.addedFormulas() : - ImmutableSLList.nil()); - } - - /** - * The formulas added to the sequent are returned as a concatenated list of - * the formulas added to each semisequent. - * @return list of formulas added to sequent - */ - public ImmutableList addedFormulas() { - final ImmutableList addedFormulasAntec = addedFormulas(true); - final ImmutableList addedFormulasSucc = addedFormulas(false); - - return concatenateHelper(addedFormulasAntec, addedFormulasSucc); - - } - - /** - * The formulas removed from one of the semisequents are returned. The - * selected semisequent depends on the value of selector 'antec' which is - * the antecedent if 'antec' is true and the succedent otherwise. - * - * @param antec a boolean used to select one of the two semisequents - * of a sequent (true means antecedent; false means succedent) - * @return list of formulas removed from the selected semisequent - */ - public ImmutableList removedFormulas(boolean antec) { - return antec ? (antecedent != null ? antecedent.removedFormulas() - : ImmutableSLList.nil()) : - (succedent != null ? succedent.removedFormulas() : - ImmutableSLList.nil()); - } - - /** - * The formulas removed from the sequent are returned as a - * concatenated list of the formulas removed from each semisequent. - * @return list of formulas removed from the sequent - */ - public ImmutableList removedFormulas() { - final ImmutableList removedFormulasAntec = removedFormulas(true); - final ImmutableList removedFormulasSucc = removedFormulas(false); - - return concatenateHelper(removedFormulasAntec, removedFormulasSucc); - } - - /** - * The formulas modified within one of the semisequents are - * returned. The selected semisequent depends on the value of - * selector 'antec' which is the antecedent if 'antec' is true and - * the succedent otherwise. - * - * @param antec a boolean used to select one of the two semisequents - * of a sequent (true means antecedent; false means succedent) - * @return list of formulas modified within the selected semisequent - */ - public ImmutableList modifiedFormulas(boolean antec) { - return antec ? (antecedent != null ? antecedent.modifiedFormulas() - : ImmutableSLList.nil()) : - (succedent != null ? succedent.modifiedFormulas() : - ImmutableSLList.nil()); - } - - /** - * The formulas modified within the sequent are returned as a - * concatenated list of the formulas modified within each each - * semisequent. - * @return list of formulas modified to sequent - */ - public ImmutableList modifiedFormulas() { - final ImmutableList modifiedFormulasAntec = modifiedFormulas(true); - final ImmutableList modifiedFormulasSucc = modifiedFormulas(false); - - return concatenateHelper(modifiedFormulasAntec, modifiedFormulasSucc); - } - - /** - * Returns the formulas that have been rejected when trying to add as being redundant. - * @param antec a boolean used to select one of the two semisequents - * of a sequent (true means antecedent; false means succedent) - * @return list of formulas rejected when trying to add to the selected semisequent - */ - public ImmutableList rejectedFormulas(boolean antec) { - return antec ? (antecedent != null ? antecedent.rejectedFormulas() - : ImmutableSLList.nil()) : - (succedent != null ? succedent.rejectedFormulas() : - ImmutableSLList.nil()); - } - - /** - * Returns the formulas that have been rejected when trying to add as being redundant. - * @return list of rejected formulas - */ - public ImmutableList rejectedFormulas() { - final ImmutableList rejectedFormulasAntec = rejectedFormulas(true); - final ImmutableList rejectedFormulasSucc = rejectedFormulas(false); - - return concatenateHelper(rejectedFormulasAntec, rejectedFormulasSucc); - } - - /** - * concatenates the two lists in arbitrary but deterministic order - * @param antecList the list of antecedent elements - * @param succList the list of succeden elements - * @return the concatenated list - */ - private ImmutableList concatenateHelper( - final ImmutableList antecList, - final ImmutableList succList) { - final int sizeAntec = antecList.size(); - final int sizeSucc = succList.size(); - - if (sizeAntec == 0) { - return succList; - } else if (sizeSucc == 0) { - return antecList; - } else { - return sizeAntec > sizeSucc ? - succList.prepend(antecList) : - antecList.prepend(succList); - } - } - - /** - * This method combines the change information from this info and its successor. - * ATTENTION: it takes over ownership over {@code succ} and does not release it. This means - * when invoking the method it must be ensured that {@code succ} is never used afterwards. - */ - public void combine(SequentChangeInfo succ) { - final SequentChangeInfo antec = this; - if (antec == succ) { - return; - } - - antec.resultingSequent = succ.resultingSequent; - - if (antec.antecedent != succ.antecedent) { - if (antec.antecedent == null) { - antec.antecedent = succ.antecedent; - } else if (succ.antecedent != null){ - antec.antecedent.combine(succ.antecedent); + /** + * The formulas removed from one of the semisequents are returned. The selected semisequent + * depends on the value of selector 'antec' which is the antecedent if 'antec' is true and the + * succedent otherwise. + * + * @param antec a boolean used to select one of the two semisequents of a sequent (true means + * antecedent; false means succedent) + * @return list of formulas removed from the selected semisequent + */ + public ImmutableList removedFormulas(boolean antec) { + return antec + ? (antecedent != null ? antecedent.removedFormulas() + : ImmutableSLList.nil()) + : (succedent != null ? succedent.removedFormulas() + : ImmutableSLList.nil()); + } + + /** + * The formulas removed from the sequent are returned as a concatenated list of the formulas + * removed from each semisequent. + * + * @return list of formulas removed from the sequent + */ + public ImmutableList removedFormulas() { + final ImmutableList removedFormulasAntec = removedFormulas(true); + final ImmutableList removedFormulasSucc = removedFormulas(false); + + return concatenateHelper(removedFormulasAntec, removedFormulasSucc); + } + + /** + * The formulas modified within one of the semisequents are returned. The selected semisequent + * depends on the value of selector 'antec' which is the antecedent if 'antec' is true and the + * succedent otherwise. + * + * @param antec a boolean used to select one of the two semisequents of a sequent (true means + * antecedent; false means succedent) + * @return list of formulas modified within the selected semisequent + */ + public ImmutableList modifiedFormulas(boolean antec) { + return antec + ? (antecedent != null ? antecedent.modifiedFormulas() + : ImmutableSLList.nil()) + : (succedent != null ? succedent.modifiedFormulas() + : ImmutableSLList.nil()); + } + + /** + * The formulas modified within the sequent are returned as a concatenated list of the formulas + * modified within each each semisequent. + * + * @return list of formulas modified to sequent + */ + public ImmutableList modifiedFormulas() { + final ImmutableList modifiedFormulasAntec = modifiedFormulas(true); + final ImmutableList modifiedFormulasSucc = modifiedFormulas(false); + + return concatenateHelper(modifiedFormulasAntec, modifiedFormulasSucc); + } + + /** + * Returns the formulas that have been rejected when trying to add as being redundant. + * + * @param antec a boolean used to select one of the two semisequents of a sequent (true means + * antecedent; false means succedent) + * @return list of formulas rejected when trying to add to the selected semisequent + */ + public ImmutableList rejectedFormulas(boolean antec) { + return antec + ? (antecedent != null ? antecedent.rejectedFormulas() + : ImmutableSLList.nil()) + : (succedent != null ? succedent.rejectedFormulas() + : ImmutableSLList.nil()); + } + + /** + * Returns the formulas that have been rejected when trying to add as being redundant. + * + * @return list of rejected formulas + */ + public ImmutableList rejectedFormulas() { + final ImmutableList rejectedFormulasAntec = rejectedFormulas(true); + final ImmutableList rejectedFormulasSucc = rejectedFormulas(false); + + return concatenateHelper(rejectedFormulasAntec, rejectedFormulasSucc); + } + + /** + * concatenates the two lists in arbitrary but deterministic order + * + * @param antecList the list of antecedent elements + * @param succList the list of succeden elements + * @return the concatenated list + */ + private ImmutableList concatenateHelper(final ImmutableList antecList, + final ImmutableList succList) { + final int sizeAntec = antecList.size(); + final int sizeSucc = succList.size(); + + if (sizeAntec == 0) { + return succList; + } else if (sizeSucc == 0) { + return antecList; + } else { + return sizeAntec > sizeSucc ? succList.prepend(antecList) : antecList.prepend(succList); } - } + } - if (antec.succedent != succ.succedent) { - if (antec.succedent == null) { - antec.succedent = succ.succedent; - } else if (succ.succedent != null){ - antec.succedent.combine(succ.succedent); + /** + * This method combines the change information from this info and its successor. ATTENTION: it + * takes over ownership over {@code succ} and does not release it. This means when invoking the + * method it must be ensured that {@code succ} is never used afterwards. + */ + public void combine(SequentChangeInfo succ) { + final SequentChangeInfo antec = this; + if (antec == succ) { + return; + } + + antec.resultingSequent = succ.resultingSequent; + + if (antec.antecedent != succ.antecedent) { + if (antec.antecedent == null) { + antec.antecedent = succ.antecedent; + } else if (succ.antecedent != null) { + antec.antecedent.combine(succ.antecedent); + } + } + + if (antec.succedent != succ.succedent) { + if (antec.succedent == null) { + antec.succedent = succ.succedent; + } else if (succ.succedent != null) { + antec.succedent.combine(succ.succedent); + } } - } - } - - - /** - * @return the original sequent - */ - public Sequent getOriginalSequent() { - return originalSequent; - } - - /** - * returns the resulting sequent - * @return the resulting sequent - */ - public Sequent sequent() { - return resultingSequent; - } - - /** - * toString helper - */ - private String toStringHelp(boolean antec) { - String result = ""; - if (hasChanged(antec)) { - result += "\t added:" +addedFormulas(antec); - result += "\t removed:" +removedFormulas(antec); - result += "\t modified:" +modifiedFormulas(antec); } - return result; - } - /** - * toString - */ - public String toString() { - String result = "antecedent: "+hasChanged(true); - result += toStringHelp(true); - result += "\n succedent: "+hasChanged(false); - result += toStringHelp(false); + /** + * @return the original sequent + */ + public Sequent getOriginalSequent() { + return originalSequent; + } + + /** + * returns the resulting sequent + * + * @return the resulting sequent + */ + public Sequent sequent() { + return resultingSequent; + } - return result; - } + /** + * toString helper + */ + private String toStringHelp(boolean antec) { + String result = ""; + if (hasChanged(antec)) { + result += "\t added:" + addedFormulas(antec); + result += "\t removed:" + removedFormulas(antec); + result += "\t modified:" + modifiedFormulas(antec); + } + return result; + } + + /** + * toString + */ + public String toString() { + String result = "antecedent: " + hasChanged(true); + result += toStringHelp(true); + + result += "\n succedent: " + hasChanged(false); + result += toStringHelp(false); + + return result; + } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentFormula.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentFormula.java index e7e4348b4ac..2f6f39894cc 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentFormula.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SequentFormula.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.logic.op.AbstractTermTransformer; @@ -5,14 +8,12 @@ /** - * A sequent formula is a wrapper around a formula that occurs - * as top level formula in a sequent. SequentFormula instances have - * to be unique in the sequent as they are used by PosInOccurrence - * to determine the exact position. In earlier KeY versions this class - * was called ConstrainedFormula as it was equipped with an additional - * constraints. It would be interesting to add more value to this class - * by providing a way to add additional annotations or to cache local information - * about the formula. + * A sequent formula is a wrapper around a formula that occurs as top level formula in a sequent. + * SequentFormula instances have to be unique in the sequent as they are used by PosInOccurrence to + * determine the exact position. In earlier KeY versions this class was called ConstrainedFormula as + * it was equipped with an additional constraints. It would be interesting to add more value to this + * class by providing a way to add additional annotations or to cache local information about the + * formula. */ public class SequentFormula { @@ -20,40 +21,44 @@ public class SequentFormula { private final int hashCode; - /** creates a new SequentFormula + /** + * creates a new SequentFormula + * * @param term a Term of sort Sort.FORMULA */ public SequentFormula(Term term) { - if (term.sort() != Sort.FORMULA && term.sort() != AbstractTermTransformer.METASORT) { - throw new RuntimeException("A Term instead of a formula: " + term); - } - this.term = term; - this.hashCode = term.hashCode () * 13; + if (term.sort() != Sort.FORMULA && term.sort() != AbstractTermTransformer.METASORT) { + throw new RuntimeException("A Term instead of a formula: " + term); + } + this.term = term; + this.hashCode = term.hashCode() * 13; } /** @return the stored Term */ public Term formula() { - return term; + return term; } /** equal if terms and constraints are equal */ public boolean equals(Object obj) { - if (this == obj) { return true; } - if (obj instanceof SequentFormula) { - SequentFormula cmp=(SequentFormula)obj; - if (term.equals(cmp.formula())) { - return true; - } - } - return false; + if (this == obj) { + return true; + } + if (obj instanceof SequentFormula) { + SequentFormula cmp = (SequentFormula) obj; + if (term.equals(cmp.formula())) { + return true; + } + } + return false; } /** String representation */ public String toString() { - return term.toString(); + return term.toString(); } - public int hashCode () { + public int hashCode() { return hashCode; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SingleRenamingTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SingleRenamingTable.java index 06e43dc6f4d..14e71fb159a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SingleRenamingTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SingleRenamingTable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashMap; @@ -9,34 +12,36 @@ -public class SingleRenamingTable extends RenamingTable{ +public class SingleRenamingTable extends RenamingTable { - SourceElement oldVar,newVar; + SourceElement oldVar, newVar; - public SingleRenamingTable(SourceElement oldVar, SourceElement newVar){ - this.oldVar = oldVar; - this.newVar = newVar; + public SingleRenamingTable(SourceElement oldVar, SourceElement newVar) { + this.oldVar = oldVar; + this.newVar = newVar; } - public SourceElement getRenaming(SourceElement se){ - if (se.equals(oldVar)) return newVar; - return null; + public SourceElement getRenaming(SourceElement se) { + if (se.equals(oldVar)) + return newVar; + return null; } - public Iterator getRenamingIterator(){ - return new SingleIterator(oldVar); + public Iterator getRenamingIterator() { + return new SingleIterator(oldVar); } - - public String toString(){ + + public String toString() { LocationVariable ov = (LocationVariable) oldVar; LocationVariable nv = (LocationVariable) newVar; - return ("SingleRenamingTable: "+oldVar+" id: "+ System.identityHashCode(ov) +" -> "+ - newVar + " id: " + System.identityHashCode(nv)); + return ("SingleRenamingTable: " + oldVar + " id: " + System.identityHashCode(ov) + " -> " + + newVar + " id: " + System.identityHashCode(nv)); } - - public HashMap getHashMap(){ - HashMap hm = new LinkedHashMap(); - hm.put(oldVar,newVar); + + public HashMap getHashMap() { + HashMap hm = + new LinkedHashMap(); + hm.put(oldVar, newVar); return hm; } @@ -45,7 +50,7 @@ private static class SingleIterator implements Iterator { private SourceElement se; public SingleIterator(SourceElement se) { - this.se = se; + this.se = se; } @Override @@ -64,6 +69,6 @@ public SourceElement next() { public void remove() { throw new UnsupportedOperationException(); } - } - -} \ No newline at end of file + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SortCollector.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SortCollector.java index efe9790c57f..dc00142b393 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/SortCollector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/SortCollector.java @@ -1,6 +1,6 @@ -/** - * - */ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.HashSet; @@ -12,24 +12,26 @@ * @author mihai * */ -public class SortCollector extends DefaultVisitor { - - private Set sorts; - - public SortCollector() { - sorts = new HashSet(); - } - - public Set getSorts() { - return sorts; - } - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.DefaultVisitor#visit(de.uka.ilkd.key.logic.Term) - */ - @Override - public void visit(Term visited) { - sorts.add(visited.sort()); - } - -} \ No newline at end of file +public class SortCollector extends DefaultVisitor { + + private Set sorts; + + public SortCollector() { + sorts = new HashSet(); + } + + public Set getSorts() { + return sorts; + } + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.DefaultVisitor#visit(de.uka.ilkd.key.logic.Term) + */ + @Override + public void visit(Term visited) { + sorts.add(visited.sort()); + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sorted.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sorted.java index 80fc55dca21..194e73e7b85 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sorted.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Sorted.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.logic.sort.Sort; @@ -6,4 +9,4 @@ public interface Sorted { public Sort sort(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Term.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Term.java index 3e02980c2a7..0db71ed10ca 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Term.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Term.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import javax.annotation.Nullable; @@ -11,35 +14,27 @@ import de.uka.ilkd.key.logic.sort.Sort; /** - * In contrast to the distinction of formulas and terms as made by most of the - * inductive definitions of the syntax of a logic, an instance of this class can - * stand for a term or a formula. This is done for implementation reasons, as - * their structure is quite similar and there are good reasons concerning the - * software's design/architecture (for example using same visitors, reduction of - * case distinction, unified interfaces etc.). However, they are strictly - * separated by their sorts. A formula (and just a formula) must have - * the sort {@link Sort#FORMULA}. Terms of a different sort are terms in the - * customary logic sense. A term of sort formula is allowed exact there, where a - * formuala in logic is allowed to appear, same for terms of different sorts. - * Some words about other design decisions: + * In contrast to the distinction of formulas and terms as made by most of the inductive definitions + * of the syntax of a logic, an instance of this class can stand for a term or a formula. This is + * done for implementation reasons, as their structure is quite similar and there are good reasons + * concerning the software's design/architecture (for example using same visitors, reduction of case + * distinction, unified interfaces etc.). However, they are strictly separated by their sorts. A + * formula (and just a formula) must have the sort {@link Sort#FORMULA}. Terms of a different sort + * are terms in the customary logic sense. A term of sort formula is allowed exact there, where a + * formuala in logic is allowed to appear, same for terms of different sorts. Some words about other + * design decisions: *

      - *
    1. terms are immutable, this means after a term object is created, it - * cannot be changed. The advantage is that we can use term sharing and - * saving a lot of memory space. - *
    2. - *
    3. Term has to be created using the {@link TermFactory} and - * _not_ by using the constructors itself. - *
    4. - *
    5. Term is subclassed, but all subclasses have to be package private, so - * that all other classes except {@link TermFactory} know only the class - * Term and its interface. Even most classes of the logic package. - *
    6. - *
    7. as it is immutable, most (all) attributes should be declared final - *
    8. + *
    9. terms are immutable, this means after a term object is created, it cannot be changed. The + * advantage is that we can use term sharing and saving a lot of memory space.
    10. + *
    11. Term has to be created using the {@link TermFactory} and _not_ by using the constructors + * itself.
    12. + *
    13. Term is subclassed, but all subclasses have to be package private, so that all other classes + * except {@link TermFactory} know only the class Term and its interface. Even most classes of the + * logic package.
    14. + *
    15. as it is immutable, most (all) attributes should be declared final
    16. *
    - * Term supports the {@link Visitor} pattern. Two different visit strategies are - * currently supported: {@link Term#execPostOrder(Visitor)} and - * {@link Term#execPreOrder(Visitor)}. + * Term supports the {@link Visitor} pattern. Two different visit strategies are currently + * supported: {@link Term#execPostOrder(Visitor)} and {@link Term#execPreOrder(Visitor)}. */ public interface Term extends SVSubstitute, Sorted { @@ -49,8 +44,8 @@ public interface Term extends SVSubstitute, Sorted { public Operator op(); /** - * The top operator (e.g., in "A and B" this is "and", in f(x,y) it is "f") - * casted to the passed type. + * The top operator (e.g., in "A and B" this is "and", in f(x,y) it is "f") casted to the passed + * type. */ public T op(Class opClass) throws IllegalArgumentException; @@ -70,8 +65,7 @@ public interface Term extends SVSubstitute, Sorted { public ImmutableArray boundVars(); /** - * The logical variables bound by the top level operator for the nth - * subterm. + * The logical variables bound by the top level operator for the nth subterm. */ public ImmutableArray varsBoundHere(int n); @@ -82,7 +76,7 @@ public interface Term extends SVSubstitute, Sorted { /** * The arity of the term. - * */ + */ public int arity(); /** @@ -107,16 +101,17 @@ public interface Term extends SVSubstitute, Sorted { public ImmutableSet freeVars(); /** - * The visitor is handed through till the bottom of the tree and - * then it walks upwards, while at each upstep the method visit of - * the visitor is called. + * The visitor is handed through till the bottom of the tree and then it walks upwards, while at + * each upstep the method visit of the visitor is called. + * * @param visitor the Visitor */ public void execPostOrder(Visitor visitor); /** - * The visitor walks downwards the tree, while at each downstep the method - * visit of the visitor is called. + * The visitor walks downwards the tree, while at each downstep the method visit of the visitor + * is called. + * * @param visitor the Visitor */ public void execPreOrder(Visitor visitor); @@ -125,9 +120,8 @@ public interface Term extends SVSubstitute, Sorted { * Compares if two terms are equal modulo bound renaming * * @param o another term, - * @return true iff the given term has the same values in - * operator, sort, arity, varsBoundHere and javaBlock as this object - * modulo bound renaming + * @return true iff the given term has the same values in operator, sort, arity, varsBoundHere + * and javaBlock as this object modulo bound renaming */ public boolean equalsModRenaming(Term o); @@ -138,18 +132,21 @@ public interface Term extends SVSubstitute, Sorted { /** * checks if the given label is attached to the term + * * @param label the TermLabel for which to look (must not be null) */ public boolean containsLabel(TermLabel label); /** * returns list of labels attached to this term + * * @return list of labels (maybe be empty but never null */ public ImmutableArray getLabels(); /** * Returns the first {@link TermLabel} with the given {@link Name}. + * * @param termLabelName The {@link Name} of the {@link TermLabel} to search. * @return The first found {@link TermLabel} or {@code null} if not available. */ @@ -162,19 +159,21 @@ public interface Term extends SVSubstitute, Sorted { /** - * Checks if the {@link Term} or one of its direct or indirect children - * contains a non empty {@link JavaBlock}. - * @return {@code true} The {@link Term} or one of its direct or indirect children contains a non empty {@link JavaBlock}, {@code false} no {@link JavaBlock} available. + * Checks if the {@link Term} or one of its direct or indirect children contains a non empty + * {@link JavaBlock}. + * + * @return {@code true} The {@link Term} or one of its direct or indirect children contains a + * non empty {@link JavaBlock}, {@code false} no {@link JavaBlock} available. */ public boolean containsJavaBlockRecursive(); /** - * Checks if {@code o} is a term syntactically equal to this one, - * except for some irrelevant labels. + * Checks if {@code o} is a term syntactically equal to this one, except for some irrelevant + * labels. * * @param o an object - * @return {@code true} iff {@code o} is a term syntactically equal to this one, - * except for their labels. + * @return {@code true} iff {@code o} is a term syntactically equal to this one, except for + * their labels. * @see TermLabel#isStrategyRelevant */ boolean equalsModIrrelevantTermLabels(Object o); @@ -189,8 +188,9 @@ public interface Term extends SVSubstitute, Sorted { boolean equalsModTermLabels(Object o); /** - * Returns an human-readable source of this term. For example the filename - * with line and offset. + * Returns an human-readable source of this term. For example the filename with line and offset. */ - default @Nullable String getOrigin() {return null;} + default @Nullable String getOrigin() { + return null; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermBuilder.java index b2b95f60e2f..23f8385d1d6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import de.uka.ilkd.key.java.Services; @@ -35,14 +38,13 @@ /** *

    - * Use this class if you intend to build complex terms by hand. It is more - * convenient than the @link{TermFactory} class. + * Use this class if you intend to build complex terms by hand. It is more convenient than + * the @link{TermFactory} class. *

    * *

    - * Attention: some methods of this class try to simplify some terms. So if you - * want to be sure that the term looks exactly as you built it, you will have to - * use the TermFactory. + * Attention: some methods of this class try to simplify some terms. So if you want to be sure that + * the term looks exactly as you built it, you will have to use the TermFactory. *

    */ public class TermBuilder { @@ -72,8 +74,8 @@ public TermFactory tf() { // ------------------------------------------------------------------------- /** - * Parses the given string that represents the term (or createTerm) using - * the service's namespaces. + * Parses the given string that represents the term (or createTerm) using the service's + * namespaces. * * @param s the String to parse */ @@ -82,19 +84,17 @@ public Term parseTerm(String s) throws ParserException { } /** - * Parses the given string that represents the term (or createTerm) using - * the provided namespaces. + * Parses the given string that represents the term (or createTerm) using the provided + * namespaces. * - * @param s the String to parse + * @param s the String to parse * @param namespaces the namespaces used for name lookup. * @throws de.uka.ilkd.key.parser.ParserException */ - public Term parseTerm(String s, NamespaceSet namespaces) - throws ParserException { - AbbrevMap abbr = (services.getProof() == null) ? null - : services.getProof().abbreviations(); - Term term = new DefaultTermParser().parse(new StringReader(s), null, - services, namespaces, abbr); + public Term parseTerm(String s, NamespaceSet namespaces) throws ParserException { + AbbrevMap abbr = (services.getProof() == null) ? null : services.getProof().abbreviations(); + Term term = new DefaultTermParser().parse(new StringReader(s), null, services, namespaces, + abbr); return term; } @@ -114,18 +114,16 @@ public String shortBaseName(Sort s) { } /** - * Returns an available name constructed by affixing a counter to the passed - * base name. + * Returns an available name constructed by affixing a counter to the passed base name. *

    - * This method looks up the global {@link NamespaceSet} to check whether the - * {@link Name}s is free. This can be problematic, since {@link Namespace}s - * are now local to goals. Use {@link #newName(String, NamespaceSet)} to - * make sure that you have all the {@link Name}s you need available. + * This method looks up the global {@link NamespaceSet} to check whether the {@link Name}s is + * free. This can be problematic, since {@link Namespace}s are now local to goals. Use + * {@link #newName(String, NamespaceSet)} to make sure that you have all the {@link Name}s you + * need available. * * @param baseName The base name (prefix) for the name to generate. - * @return An available name constructed by affixing a counter to the passed - * base name, or some available free name (please consult comment - * above). + * @return An available name constructed by affixing a counter to the passed base name, or some + * available free name (please consult comment above). * @see #newName(String, NamespaceSet) */ public String newName(String baseName) { @@ -133,21 +131,18 @@ public String newName(String baseName) { } /** - * Returns an available name constructed by affixing a counter to the passed - * base name. + * Returns an available name constructed by affixing a counter to the passed base name. *

    *

    - * Warning (DS): This method ignores the baseName if there are free name - * proposals. This can, for instance, cause troubles in loading proofs - * containing rule apps with more than one introduced (and saved) new name. - * In this case, the order of new names in the saved proof file matters (the - * first unused name is returned, regardless of the baseName). + * Warning (DS): This method ignores the baseName if there are free name proposals. This can, + * for instance, cause troubles in loading proofs containing rule apps with more than one + * introduced (and saved) new name. In this case, the order of new names in the saved proof file + * matters (the first unused name is returned, regardless of the baseName). * - * @param baseName The base name (prefix) for the name to generate. + * @param baseName The base name (prefix) for the name to generate. * @param localNamespace The local {@link NamespaceSet} to check. - * @return An available name constructed by affixing a counter to the passed - * base name, or some available free name (please consult comment - * above). + * @return An available name constructed by affixing a counter to the passed base name, or some + * available free name (please consult comment above). */ public String newName(String baseName, NamespaceSet localNamespace) { final Name savedName = services.getNameRecorder().getProposal(); @@ -173,8 +168,8 @@ public String newName(String baseName, NamespaceSet localNamespace) { } /** - * Returns an available name constructed by affixing a counter to a self- - * chosen base name for the passed sort. + * Returns an available name constructed by affixing a counter to a self- chosen base name for + * the passed sort. */ public String newName(Sort sort) { return newName(shortBaseName(sort)); @@ -185,29 +180,25 @@ public String newName(Sort sort) { // ------------------------------------------------------------------------- /** - * Creates a program variable for "self". Take care to register it in the - * namespaces! + * Creates a program variable for "self". Take care to register it in the namespaces! */ public LocationVariable selfVar(KeYJavaType kjt, boolean makeNameUnique) { return selfVar(kjt, makeNameUnique, ""); } /** - * Creates a program variable for "self". Take care to register it in the - * namespaces! + * Creates a program variable for "self". Take care to register it in the namespaces! */ - public LocationVariable selfVar(KeYJavaType kjt, boolean makeNameUnique, - String postfix) { + public LocationVariable selfVar(KeYJavaType kjt, boolean makeNameUnique, String postfix) { String name = "self" + postfix; return locationVariable(name, kjt, makeNameUnique); } /** - * Creates a program variable for "self". Take care to register it in the - * namespaces! + * Creates a program variable for "self". Take care to register it in the namespaces! */ - public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, - boolean makeNameUnique, String postfix) { + public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, boolean makeNameUnique, + String postfix) { if (pm.isStatic()) { return null; } else { @@ -216,11 +207,9 @@ public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, } /** - * Creates a program variable for "self". Take care to register it in the - * namespaces! + * Creates a program variable for "self". Take care to register it in the namespaces! */ - public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, - boolean makeNameUnique) { + public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, boolean makeNameUnique) { if (pm.isStatic()) { return null; } else { @@ -229,13 +218,11 @@ public LocationVariable selfVar(IProgramMethod pm, KeYJavaType kjt, } /** - * Creates program variables for the parameters. Take care to register them - * in the namespaces! + * Creates program variables for the parameters. Take care to register them in the namespaces! */ public ImmutableList paramVars(IObserverFunction obs, - boolean makeNamesUnique) { - ImmutableList result = ImmutableSLList - .nil(); + boolean makeNamesUnique) { + ImmutableList result = ImmutableSLList.nil(); for (int i = 0, n = obs.getNumParams(); i < n; i++) { final KeYJavaType paramType = obs.getParamType(i); String name; @@ -252,39 +239,32 @@ public ImmutableList paramVars(IObserverFunction obs, } /** - * Creates program variables for the parameters. Take care to register them - * in the namespaces! + * Creates program variables for the parameters. Take care to register them in the namespaces! */ - public ImmutableList paramVars(String postfix, - IObserverFunction obs, boolean makeNamesUnique) { + public ImmutableList paramVars(String postfix, IObserverFunction obs, + boolean makeNamesUnique) { final ImmutableList paramVars = paramVars(obs, true); - ImmutableList result = ImmutableSLList - .nil(); + ImmutableList result = ImmutableSLList.nil(); for (ProgramVariable paramVar : paramVars) { - ProgramElementName pen = new ProgramElementName( - paramVar.name() + postfix); - LocationVariable formalParamVar = new LocationVariable(pen, - paramVar.getKeYJavaType()); + ProgramElementName pen = new ProgramElementName(paramVar.name() + postfix); + LocationVariable formalParamVar = new LocationVariable(pen, paramVar.getKeYJavaType()); result = result.append(formalParamVar); } return result; } /** - * Creates a program variable for the result. Take care to register it in - * the namespaces. + * Creates a program variable for the result. Take care to register it in the namespaces. */ - public LocationVariable resultVar(IProgramMethod pm, - boolean makeNameUnique) { + public LocationVariable resultVar(IProgramMethod pm, boolean makeNameUnique) { return resultVar("result", pm, makeNameUnique); } /** - * Creates a program variable for the result with passed name. Take care to - * register it in the namespaces. + * Creates a program variable for the result with passed name. Take care to register it in the + * namespaces. */ - public LocationVariable resultVar(String name, IProgramMethod pm, - boolean makeNameUnique) { + public LocationVariable resultVar(String name, IProgramMethod pm, boolean makeNameUnique) { if (pm.isVoid() || pm.isConstructor()) { return null; } else { @@ -294,37 +274,33 @@ public LocationVariable resultVar(String name, IProgramMethod pm, } /** - * Creates a program variable for the thrown exception. Take care to - * register it in the namespaces. + * Creates a program variable for the thrown exception. Take care to register it in the + * namespaces. */ public LocationVariable excVar(IProgramMethod pm, boolean makeNameUnique) { return excVar("exc", pm, makeNameUnique); } /** - * Creates a program variable for the thrown exception. Take care to - * register it in the namespaces. + * Creates a program variable for the thrown exception. Take care to register it in the + * namespaces. */ - public LocationVariable excVar(String name, IProgramMethod pm, - boolean makeNameUnique) { + public LocationVariable excVar(String name, IProgramMethod pm, boolean makeNameUnique) { return locationVariable(name, - services.getJavaInfo().getTypeByClassName(JAVA_LANG_THROWABLE), - makeNameUnique); + services.getJavaInfo().getTypeByClassName(JAVA_LANG_THROWABLE), makeNameUnique); } /** - * Creates a program variable for the atPre heap. Take care to register it - * in the namespaces. + * Creates a program variable for the atPre heap. Take care to register it in the namespaces. */ - public LocationVariable heapAtPreVar(String baseName, - boolean makeNameUnique) { + public LocationVariable heapAtPreVar(String baseName, boolean makeNameUnique) { HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); return locationVariable(baseName, heapLDT.getHeap().sort(), makeNameUnique); } /** - * Creates a location variable for prestate variables. Take care to register it - * in the namespaces. + * Creates a location variable for prestate variables. Take care to register it in the + * namespaces. * * @param baseName the base name to use * @param sort the sort of the variable @@ -336,8 +312,8 @@ public LocationVariable atPreVar(String baseName, Sort sort, boolean makeNameUni } /** - * Creates a location variable for prestate variables. Take care to register it - * in the namespaces. + * Creates a location variable for prestate variables. Take care to register it in the + * namespaces. * * @param baseName the base name to use * @param kjt the type of the variable @@ -349,8 +325,8 @@ public LocationVariable atPreVar(String baseName, KeYJavaType kjt, boolean makeN } /** - * Creates a location variable for example for prestate variables. Take care to register it - * in the namespaces. + * Creates a location variable for example for prestate variables. Take care to register it in + * the namespaces. * * @param baseName the base name to use * @param sort the sort of the variable @@ -362,8 +338,8 @@ public LocationVariable locationVariable(String baseName, Sort sort, boolean mak } /** - * Creates a location variable for example for prestate variables. Take care to register it - * in the namespaces. + * Creates a location variable for example for prestate variables. Take care to register it in + * the namespaces. * * @param baseName the base name to use * @param kjt the type of the variable @@ -371,7 +347,7 @@ public LocationVariable locationVariable(String baseName, Sort sort, boolean mak * @return a location variable for the given name and type */ public LocationVariable locationVariable(String baseName, KeYJavaType kjt, - boolean makeNameUnique) { + boolean makeNameUnique) { if (makeNameUnique) { baseName = newName(baseName); } @@ -440,18 +416,16 @@ public Term func(IObserverFunction f, Term... s) { return tf.createTerm(f, s, null, null); } - public Term func(Function f, Term[] s, - ImmutableArray boundVars) { + public Term func(Function f, Term[] s, ImmutableArray boundVars) { return tf.createTerm(f, s, boundVars, null); } public Term prog(Modality mod, JavaBlock jb, Term t) { - return tf.createTerm(mod, new Term[]{t}, null, jb); + return tf.createTerm(mod, new Term[] { t }, null, jb); } - public Term prog(Modality mod, JavaBlock jb, Term t, - ImmutableArray labels) { - return tf.createTerm(mod, new Term[]{t}, null, jb, labels); + public Term prog(Modality mod, JavaBlock jb, Term t, ImmutableArray labels) { + return tf.createTerm(mod, new Term[] { t }, null, jb, labels); } public Term box(JavaBlock jb, Term t) { @@ -463,15 +437,13 @@ public Term dia(JavaBlock jb, Term t) { } public Term ife(Term cond, Term _then, Term _else) { - return tf.createTerm(IfThenElse.IF_THEN_ELSE, - new Term[]{cond, _then, _else}); + return tf.createTerm(IfThenElse.IF_THEN_ELSE, new Term[] { cond, _then, _else }); } /** * Construct a term with the \ifEx operator. */ - public Term ifEx(QuantifiableVariable qv, Term cond, Term _then, - Term _else) { + public Term ifEx(QuantifiableVariable qv, Term cond, Term _then, Term _else) { return tf.createTerm(IfExThenElse.IF_EX_THEN_ELSE, new ImmutableArray(cond, _then, _else), new ImmutableArray(qv), null); @@ -480,16 +452,13 @@ public Term ifEx(QuantifiableVariable qv, Term cond, Term _then, /** * Construct a term with the \ifEx operator. */ - public Term ifEx(ImmutableList qvs, Term cond, - Term _then, Term _else) { + public Term ifEx(ImmutableList qvs, Term cond, Term _then, Term _else) { if (qvs.isEmpty()) - throw new TermCreationException( - "no quantifiable variables in ifEx term"); + throw new TermCreationException("no quantifiable variables in ifEx term"); if (qvs.size() == 1) { return ifEx(qvs.head(), cond, _then, _else); } else { - return ifEx(qvs.head(), tt(), ifEx(qvs.tail(), cond, _then, _else), - _else); + return ifEx(qvs.head(), tt(), ifEx(qvs.tail(), cond, _then, _else), _else); } } @@ -549,22 +518,19 @@ public Term ex(Iterable qvs, Term t) { public Term bsum(QuantifiableVariable qv, Term a, Term b, Term t) { Function bsum = services.getTypeConverter().getIntegerLDT().getBsum(); - return func(bsum, new Term[]{a, b, t}, - new ImmutableArray(qv)); + return func(bsum, new Term[] { a, b, t }, new ImmutableArray(qv)); } /** * General (unbounded) sum */ - public Term sum(ImmutableList qvs, Term range, - Term t) { - final Function sum = services.getNamespaces().functions() - .lookup("sum"); + public Term sum(ImmutableList qvs, Term range, Term t) { + final Function sum = services.getNamespaces().functions().lookup("sum"); final Iterator it = qvs.iterator(); - Term res = func(sum, new Term[]{convertToBoolean(range), t}, + Term res = func(sum, new Term[] { convertToBoolean(range), t }, new ImmutableArray(it.next())); while (it.hasNext()) { - res = func(sum, new Term[]{TRUE(), res}, + res = func(sum, new Term[] { TRUE(), res }, new ImmutableArray(it.next())); } return res; @@ -573,25 +539,22 @@ public Term sum(ImmutableList qvs, Term range, /** * Constructs a bounded product comprehension expression. */ - public Term bprod(QuantifiableVariable qv, Term a, Term b, Term t, - Services services) { + public Term bprod(QuantifiableVariable qv, Term a, Term b, Term t, Services services) { Function bprod = services.getTypeConverter().getIntegerLDT().getBprod(); - return func(bprod, new Term[]{a, b, t}, - new ImmutableArray(qv)); + return func(bprod, new Term[] { a, b, t }, new ImmutableArray(qv)); } /** * General (unbounded) product */ - public Term prod(ImmutableList qvs, Term range, - Term t, TermServices services) { - final Function prod = services.getNamespaces().functions() - .lookup("prod"); + public Term prod(ImmutableList qvs, Term range, Term t, + TermServices services) { + final Function prod = services.getNamespaces().functions().lookup("prod"); final Iterator it = qvs.iterator(); - Term res = func(prod, new Term[]{convertToBoolean(range), t}, + Term res = func(prod, new Term[] { convertToBoolean(range), t }, new ImmutableArray(it.next())); while (it.hasNext()) { - res = func(prod, new Term[]{TRUE(), res}, + res = func(prod, new Term[] { TRUE(), res }, new ImmutableArray(it.next())); } return res; @@ -601,14 +564,13 @@ public Term prod(ImmutableList qvs, Term range, * minimum operator */ public Term min(ImmutableList qvs, Term range, Term t, - TermServices services) { - final Function min = services.getNamespaces().functions() - .lookup("min"); + TermServices services) { + final Function min = services.getNamespaces().functions().lookup("min"); final Iterator it = qvs.iterator(); - Term res = func(min, new Term[]{convertToBoolean(range), t}, + Term res = func(min, new Term[] { convertToBoolean(range), t }, new ImmutableArray(it.next())); while (it.hasNext()) { - res = func(min, new Term[]{TRUE(), res}, + res = func(min, new Term[] { TRUE(), res }, new ImmutableArray(it.next())); } return res; @@ -618,14 +580,13 @@ public Term min(ImmutableList qvs, Term range, T * minimum operator */ public Term max(ImmutableList qvs, Term range, Term t, - TermServices services) { - final Function max = services.getNamespaces().functions() - .lookup("max"); + TermServices services) { + final Function max = services.getNamespaces().functions().lookup("max"); final Iterator it = qvs.iterator(); - Term res = func(max, new Term[]{convertToBoolean(range), t}, + Term res = func(max, new Term[] { convertToBoolean(range), t }, new ImmutableArray(it.next())); while (it.hasNext()) { - res = func(max, new Term[]{TRUE(), res}, + res = func(max, new Term[] { TRUE(), res }, new ImmutableArray(it.next())); } return res; @@ -656,8 +617,8 @@ public Term and(Term t1, Term t2) { } public Term andSC(Term t1, Term t2) { - if (t1.op() == Junctor.TRUE || t1.op() == Junctor.FALSE - || t2.op() == Junctor.FALSE || t2.op() == Junctor.TRUE) { + if (t1.op() == Junctor.TRUE || t1.op() == Junctor.FALSE || t2.op() == Junctor.FALSE + || t2.op() == Junctor.TRUE) { return and(t1, t2); } else { return shortcut(and(t1, t2)); @@ -717,8 +678,8 @@ public Term or(Term t1, Term t2) { } public Term orSC(Term t1, Term t2) { - if (t1.op() == Junctor.TRUE || t1.op() == Junctor.FALSE - || t2.op() == Junctor.FALSE || t2.op() == Junctor.TRUE) { + if (t1.op() == Junctor.TRUE || t1.op() == Junctor.FALSE || t2.op() == Junctor.FALSE + || t2.op() == Junctor.TRUE) { return or(t1, t2); } else { return shortcut(or(t1, t2)); @@ -805,19 +766,16 @@ public Term equals(Term t1, Term t2) { /** * Creates a substitution term * - * @param substVar the QuantifiableVariable to be substituted + * @param substVar the QuantifiableVariable to be substituted * @param substTerm the Term that replaces substVar - * @param origTerm the Term that is substituted + * @param origTerm the Term that is substituted */ - public Term subst(SubstOp op, QuantifiableVariable substVar, Term substTerm, - Term origTerm) { - return tf.createTerm(op, - new ImmutableArray(new Term[]{substTerm, origTerm}), + public Term subst(SubstOp op, QuantifiableVariable substVar, Term substTerm, Term origTerm) { + return tf.createTerm(op, new ImmutableArray(new Term[] { substTerm, origTerm }), new ImmutableArray(substVar), null); } - public Term subst(QuantifiableVariable substVar, Term substTerm, - Term origTerm) { + public Term subst(QuantifiableVariable substVar, Term substTerm, Term origTerm) { return subst(WarySubstOp.SUBST, substVar, substTerm, origTerm); } @@ -855,12 +813,10 @@ public Term prec(Term mby, Term mbyAtPre) { public Term measuredByCheck(Term mby) { final Namespace funcNS = services.getNamespaces().functions(); - final Function f = funcNS - .lookup(new Name("measuredByCheck")); + final Function f = funcNS.lookup(new Name("measuredByCheck")); if (f == null) - throw new RuntimeException( - "LDT: Function measuredByCheck not found.\n" - + "It seems that there are definitions missing from the .key files."); + throw new RuntimeException("LDT: Function measuredByCheck not found.\n" + + "It seems that there are definitions missing from the .key files."); return func(f, mby); } @@ -875,12 +831,10 @@ public Term measuredBy(Term mby) { public Function getMeasuredByEmpty() { final Namespace funcNS = services.getNamespaces().functions(); - final Function f = funcNS - .lookup(new Name("measuredByEmpty")); + final Function f = funcNS.lookup(new Name("measuredByEmpty")); if (f == null) - throw new RuntimeException( - "LDT: Function measuredByEmpty not found.\n" - + "It seems that there are definitions missing from the .key files."); + throw new RuntimeException("LDT: Function measuredByEmpty not found.\n" + + "It seems that there are definitions missing from the .key files."); return f; } @@ -893,8 +847,9 @@ public Term measuredByEmpty() { */ public Term convertToFormula(Term a) { BooleanLDT booleanLDT = services.getTypeConverter().getBooleanLDT(); - if(booleanLDT==null) throw new IllegalStateException("boolean ldt is not set in services"); - if(a == null) + if (booleanLDT == null) + throw new IllegalStateException("boolean ldt is not set in services"); + if (a == null) throw new NullPointerException(); if (a.sort() == Sort.FORMULA) { return a; @@ -926,8 +881,7 @@ public Term convertToBoolean(Term a) { return a; } else if (a.sort() == Sort.FORMULA) { // special case where a is the result of convertToFormula - if (a.op() == Equality.EQUALS - && a.sub(1).op() == booleanLDT.getTrueConst()) { + if (a.op() == Equality.EQUALS && a.sub(1).op() == booleanLDT.getTrueConst()) { return a.sub(0); } return ife(a, TRUE(), FALSE()); @@ -961,15 +915,15 @@ public Term elementary(Term lhs, Term rhs) { return elementary(heapLDT.getHeap(), fullRhs); } else if (lhs.op() == UpdateApplication.UPDATE_APPLICATION) { // #1536 A nested updates like - // { {a:=1} b :=a} + // { {a:=1} b :=a} // should be parsed as (see KeY-Book, Sec. 3.4.1, Def. 3.8) - // { {a:=1} (b :=a)} + // { {a:=1} (b :=a)} // but is parsed as: - // { ({a:=1} b) :=a} + // { ({a:=1} b) :=a} // The latter is (currently) not supported, hence the exception. throw new TermCreationException("lhs cannot have a nested update. " - + "If you have a nested update like '{{a:=1} b:=a}', " - + "replace it with the bracketed version '{{a:=1} (b:=a)}'."); + + "If you have a nested update like '{{a:=1} b:=a}', " + + "replace it with the bracketed version '{{a:=1} (b:=a)}'."); } else { throw new TermCreationException("Not a legal lhs: " + lhs); } @@ -1011,9 +965,8 @@ public Term parallel(ImmutableList updates) { public Term parallel(Term[] lhss, Term[] values) { if (lhss.length != values.length) { - throw new TermCreationException( - "Tried to create parallel update with " + lhss.length - + " locs and " + values.length + " values"); + throw new TermCreationException("Tried to create parallel update with " + lhss.length + + " locs and " + values.length + " values"); } Term[] updates = new Term[lhss.length]; for (int i = 0; i < updates.length; i++) { @@ -1071,8 +1024,7 @@ public ImmutableList apply(Term update, ImmutableList targets) { return result; } - public Term apply(Term update, Term target, - ImmutableArray labels) { + public Term apply(Term update, Term target, ImmutableArray labels) { if (update.sort() != Sort.UPDATE) { throw new TermCreationException("Not an update: " + update); } else if (update.op() == UpdateJunctor.SKIP) { @@ -1080,8 +1032,7 @@ public Term apply(Term update, Term target, } else if (target.equals(tt())) { return tt(); } else { - return tf.createTerm(UpdateApplication.UPDATE_APPLICATION, update, - target, labels); + return tf.createTerm(UpdateApplication.UPDATE_APPLICATION, update, target, labels); } } @@ -1093,8 +1044,7 @@ public Term applyElementary(Term heap, Term target) { return apply(elementary(heap), target, null); } - public ImmutableList applyElementary(Term heap, - Iterable targets) { + public ImmutableList applyElementary(Term heap, Iterable targets) { ImmutableList result = ImmutableSLList.nil(); for (Term target : targets) { result = result.append(apply(elementary(heap), target, null)); @@ -1118,8 +1068,7 @@ public Term applySequential(Term[] updates, Term target) { if (updates.length == 0) { return target; } else { - ImmutableList updateList = ImmutableSLList.nil() - .append(updates).tail(); + ImmutableList updateList = ImmutableSLList.nil().append(updates).tail(); return apply(updates[0], applySequential(updateList, target), null); } } @@ -1128,13 +1077,11 @@ public Term applySequential(ImmutableList updates, Term target) { if (updates.isEmpty()) { return target; } else { - return apply(updates.head(), - applySequential(updates.tail(), target), null); + return apply(updates.head(), applySequential(updates.tail(), target), null); } } - public Term applyUpdatePairsSequential( - ImmutableList updates, Term target) { + public Term applyUpdatePairsSequential(ImmutableList updates, Term target) { if (updates.isEmpty()) { return target; } else { @@ -1161,26 +1108,22 @@ public Term FALSE() { // ------------------------------------------------------------------------- public Term geq(Term t1, Term t2) { - final IntegerLDT integerLDT = services.getTypeConverter() - .getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); return func(integerLDT.getGreaterOrEquals(), t1, t2); } public Term gt(Term t1, Term t2) { - final IntegerLDT integerLDT = services.getTypeConverter() - .getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); return func(integerLDT.getGreaterThan(), t1, t2); } public Term lt(Term t1, Term t2) { - final IntegerLDT integerLDT = services.getTypeConverter() - .getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); return func(integerLDT.getLessThan(), t1, t2); } public Term leq(Term t1, Term t2) { - final IntegerLDT integerLDT = services.getTypeConverter() - .getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); return func(integerLDT.getLessOrEquals(), t1, t2); } @@ -1193,8 +1136,8 @@ public Term one() { } /** - * Creates terms to be used in Z/C/FP/DFP/R notations. - * The result does not have such a constructor applied yet. + * Creates terms to be used in Z/C/FP/DFP/R notations. The result does not have such a + * constructor applied yet. * * @param numberString a string containing the number in a decimal representation * @return Term in "number" notation representing the given number @@ -1238,8 +1181,7 @@ private Term numberTerm(String numberString) { /** * Get term for an integer literal. * - * @param numberString - * String representing an integer with radix 10, may be negative + * @param numberString String representing an integer with radix 10, may be negative * @return Term in Z-Notation representing the given number * @throws NumberFormatException if numberString is not a number */ @@ -1251,8 +1193,7 @@ public Term zTerm(String numberString) { /** * Get term for an integer literal. * - * @param number - * an integer + * @param number an integer * @return Term in Z-Notation representing the given number */ public Term zTerm(long number) { @@ -1279,8 +1220,7 @@ public Term fpTerm(float value) { int bitPattern = Float.floatToIntBits(value); String patternStr = Integer.toUnsignedString(bitPattern); Term numberTerm = numberTerm(patternStr); - return func(services.getTypeConverter().getFloatLDT().getFloatSymbol(), - numberTerm); + return func(services.getTypeConverter().getFloatLDT().getFloatSymbol(), numberTerm); } /** @@ -1293,13 +1233,11 @@ public Term dfpTerm(double value) { long bitPattern = Double.doubleToLongBits(value); String patternStr = Long.toUnsignedString(bitPattern); Term numberTerm = numberTerm(patternStr); - return func(services.getTypeConverter().getDoubleLDT().getDoubleSymbol(), - numberTerm); + return func(services.getTypeConverter().getDoubleLDT().getDoubleSymbol(), numberTerm); } public Term add(Term t1, Term t2) { - final IntegerLDT integerLDT = services.getTypeConverter() - .getIntegerLDT(); + final IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); final Term zero = integerLDT.zero(); if (t1.equals(zero)) { return t2; @@ -1311,32 +1249,27 @@ public Term add(Term t1, Term t2) { } public Term inByte(Term var) { - Function f = services.getNamespaces().functions() - .lookup(new Name("inByte")); + Function f = services.getNamespaces().functions().lookup(new Name("inByte")); return func(f, var); } public Term inShort(Term var) { - Function f = services.getNamespaces().functions() - .lookup(new Name("inShort")); + Function f = services.getNamespaces().functions().lookup(new Name("inShort")); return func(f, var); } public Term inChar(Term var) { - Function f = services.getNamespaces().functions() - .lookup(new Name("inChar")); + Function f = services.getNamespaces().functions().lookup(new Name("inChar")); return func(f, var); } public Term inInt(Term var) { - Function f = services.getNamespaces().functions() - .lookup(new Name("inInt")); + Function f = services.getNamespaces().functions().lookup(new Name("inInt")); return func(f, var); } public Term inLong(Term var) { - Function f = services.getNamespaces().functions() - .lookup(new Name("inLong")); + Function f = services.getNamespaces().functions().lookup(new Name("inLong")); return func(f, var); } @@ -1349,9 +1282,8 @@ public Term index() { // ------------------------------------------------------------------------- /** - * This value is only used as a marker for "\strictly_nothing" in JML. It - * may return any term. Preferably of type LocSet, but this is not - * necessary. + * This value is only used as a marker for "\strictly_nothing" in JML. It may return any term. + * Preferably of type LocSet, but this is not necessary. * * @return an arbitrary but fixed term. */ @@ -1368,8 +1300,7 @@ public Term allLocs() { } public Term singleton(Term o, Term f) { - return func(services.getTypeConverter().getLocSetLDT().getSingleton(), - o, f); + return func(services.getTypeConverter().getLocSetLDT().getSingleton(), o, f); } public Term union(Term s1, Term s2) { @@ -1439,7 +1370,7 @@ public Term setMinus(Term s1, Term s2) { public Term infiniteUnion(QuantifiableVariable[] qvs, Term s) { final LocSetLDT ldt = services.getTypeConverter().getLocSetLDT(); - return tf.createTerm(ldt.getInfiniteUnion(), new Term[]{s}, + return tf.createTerm(ldt.getInfiniteUnion(), new Term[] { s }, new ImmutableArray(qvs), null); } @@ -1451,29 +1382,24 @@ public Term setComprehension(QuantifiableVariable[] qvs, Term o, Term f) { return infiniteUnion(qvs, singleton(o, f)); } - public Term setComprehension(QuantifiableVariable[] qvs, Term guard, Term o, - Term f) { + public Term setComprehension(QuantifiableVariable[] qvs, Term guard, Term o, Term f) { return infiniteUnion(qvs, guard, singleton(o, f)); } public Term allFields(Term o) { - return func(services.getTypeConverter().getLocSetLDT().getAllFields(), - o); + return func(services.getTypeConverter().getLocSetLDT().getAllFields(), o); } public Term allObjects(Term f) { - return func(services.getTypeConverter().getLocSetLDT().getAllObjects(), - f); + return func(services.getTypeConverter().getLocSetLDT().getAllObjects(), f); } public Term arrayRange(Term o, Term lower, Term upper) { - return func(services.getTypeConverter().getLocSetLDT().getArrayRange(), - o, lower, upper); + return func(services.getTypeConverter().getLocSetLDT().getArrayRange(), o, lower, upper); } public Term freshLocs(Term h) { - return func(services.getTypeConverter().getLocSetLDT().getFreshLocs(), - h); + return func(services.getTypeConverter().getLocSetLDT().getFreshLocs(), h); } public Term elementOf(Term o, Term f, Term s) { @@ -1517,12 +1443,10 @@ public Term createdLocs() { } // The template of the well-definedness transformer for terms. - public static final Transformer WD_ANY = new Transformer(new Name("wd"), - Sort.ANY); + public static final Transformer WD_ANY = new Transformer(new Name("wd"), Sort.ANY); // The template of the well-definedness transformer for formulas. - public static final Transformer WD_FORMULA = new Transformer(new Name("WD"), - Sort.FORMULA); + public static final Transformer WD_FORMULA = new Transformer(new Name("WD"), Sort.FORMULA); public Term wd(Term t) { if (t.op() == Junctor.FALSE || t.op() == Junctor.TRUE) { @@ -1559,19 +1483,17 @@ public Term NULL() { } /** - * The "deep non null" predicate arising from JML non_null types. Deep non - * null means that it is recursively defined for arrays. See bug #1392. + * The "deep non null" predicate arising from JML non_null types. Deep non null means that it is + * recursively defined for arrays. See bug #1392. */ public Term deepNonNull(Term o, Term d) { - final Function nonNull = services.getNamespaces().functions() - .lookup("nonNull"); + final Function nonNull = services.getNamespaces().functions().lookup("nonNull"); final Term heap = getBaseHeap(); return func(nonNull, heap, o, d); } public Term wellFormed(Term heap) { - return func(services.getTypeConverter().getHeapLDT().getWellFormed(), - heap); + return func(services.getTypeConverter().getHeapLDT().getWellFormed(), heap); } public Term wellFormed(LocationVariable heap) { @@ -1579,12 +1501,11 @@ public Term wellFormed(LocationVariable heap) { } public Term permissionsFor(Term permHeap, Term regularHeap) { - return func(services.getTypeConverter().getPermissionLDT() - .getPermissionsFor(), permHeap, regularHeap); + return func(services.getTypeConverter().getPermissionLDT().getPermissionsFor(), permHeap, + regularHeap); } - public Term permissionsFor(LocationVariable permHeap, - LocationVariable regularHeap) { + public Term permissionsFor(LocationVariable permHeap, LocationVariable regularHeap) { return permissionsFor(var(permHeap), var(regularHeap)); } @@ -1620,16 +1541,15 @@ public Term staticInv(KeYJavaType t) { } public Term select(Sort asSort, Term h, Term o, Term f) { - return func(services.getTypeConverter().getHeapLDT().getSelect(asSort, - services), h, o, f); + return func(services.getTypeConverter().getHeapLDT().getSelect(asSort, services), h, o, f); } /** * Get the select expression for a location variabe representing the field. */ public Term select(Sort asSort, Term h, Term o, LocationVariable field) { - final Function f = services.getTypeConverter().getHeapLDT() - .getFieldSymbolForPV(field, services); + final Function f = + services.getTypeConverter().getHeapLDT().getFieldSymbolForPV(field, services); return select(asSort, h, o, func(f)); } @@ -1638,20 +1558,19 @@ public Term dot(Sort asSort, Term o, Term f) { } public Term getBaseHeap() { - return var((ProgramVariable) services.getNamespaces().programVariables().lookup(HeapLDT.BASE_HEAP_NAME)); - //return var(services.getTypeConverter().getHeapLDT().getHeap()); + return var((ProgramVariable) services.getNamespaces().programVariables() + .lookup(HeapLDT.BASE_HEAP_NAME)); + // return var(services.getTypeConverter().getHeapLDT().getHeap()); } public Term dot(Sort asSort, Term o, Function f) { - final Sort fieldSort = services.getTypeConverter().getHeapLDT() - .getFieldSort(); - return f.sort() == fieldSort ? dot(asSort, o, func(f)) - : func(f, getBaseHeap(), o); + final Sort fieldSort = services.getTypeConverter().getHeapLDT().getFieldSort(); + return f.sort() == fieldSort ? dot(asSort, o, func(f)) : func(f, getBaseHeap(), o); } public Term dot(Sort asSort, Term o, LocationVariable field) { - final Function f = services.getTypeConverter().getHeapLDT() - .getFieldSymbolForPV(field, services); + final Function f = + services.getTypeConverter().getHeapLDT().getFieldSymbolForPV(field, services); return dot(asSort, o, f); } @@ -1660,29 +1579,28 @@ public Term staticDot(Sort asSort, Term f) { } public Term staticDot(Sort asSort, Function f) { - final Sort fieldSort = services.getTypeConverter().getHeapLDT() - .getFieldSort(); - return f.sort() == fieldSort ? staticDot(asSort, func(f)) - : func(f, getBaseHeap()); + final Sort fieldSort = services.getTypeConverter().getHeapLDT().getFieldSort(); + return f.sort() == fieldSort ? staticDot(asSort, func(f)) : func(f, getBaseHeap()); } public Term arr(Term idx) { return func(services.getNamespaces().functions().lookup("arr"), idx); - //return func(services.getTypeConverter().getHeapLDT().getArr(), idx); + // return func(services.getTypeConverter().getHeapLDT().getArr(), idx); } /** * Applies the labels to the term and almost every (direct or indirect) sub-term recursively. * - *

    The labels are not added to heap variables.

    + *

    + * The labels are not added to heap variables. + *

    * - * @param term term to label. + * @param term term to label. * @param labels the labels to apply. * @return a labeled term. */ public Term addLabelToAllSubs(Term term, ImmutableArray labels) { - if (labels == null || labels.isEmpty() - || (!OriginTermLabel.canAddLabel(term, services) + if (labels == null || labels.isEmpty() || (!OriginTermLabel.canAddLabel(term, services) && labels.stream().anyMatch(l -> l instanceof OriginTermLabel))) { return term; } @@ -1695,11 +1613,7 @@ public Term addLabelToAllSubs(Term term, ImmutableArray labels) { } - Term result = tf.createTerm( - term.op(), - newSubs, - term.boundVars(), - term.javaBlock(), + Term result = tf.createTerm(term.op(), newSubs, term.boundVars(), term.javaBlock(), term.getLabels()); result = addLabel(result, labels); return result; @@ -1708,9 +1622,11 @@ public Term addLabelToAllSubs(Term term, ImmutableArray labels) { /** * Applies the label to the term and almost every (direct or indirect) sub-term recursively. * - *

    The label is not added to heap variables.

    + *

    + * The label is not added to heap variables. + *

    * - * @param term term to label. + * @param term term to label. * @param label the label to apply. * @return a labeled term. */ @@ -1721,7 +1637,7 @@ public Term addLabelToAllSubs(Term term, TermLabel label) { /** * Adds labels to a term, removing any existing labels of the same type. * - * @param term the term. + * @param term the term. * @param labels the labels to add. * @return the term with the labels added. */ @@ -1729,8 +1645,8 @@ public Term addLabel(Term term, ImmutableArray labels) { if ((labels == null || labels.isEmpty()) && !term.hasLabels()) { return term; } else if (!term.hasLabels()) { - return tf.createTerm(term.op(), term.subs(), term.boundVars(), - term.javaBlock(), labels); + return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock(), + labels); } else { List newLabelList = term.getLabels().toList(); @@ -1744,8 +1660,7 @@ public Term addLabel(Term term, ImmutableArray labels) { newLabelList.add(newLabel); } - return tf.createTerm(term.op(), term.subs(), term.boundVars(), - term.javaBlock(), + return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock(), new ImmutableArray(newLabelList)); } } @@ -1753,7 +1668,7 @@ public Term addLabel(Term term, ImmutableArray labels) { /** * Adds a label to a term, removing any existing labels of the same type. * - * @param term the term. + * @param term the term. * @param label the label to add. * @return the term with the label added. */ @@ -1768,7 +1683,7 @@ public Term addLabel(Term term, TermLabel label) { /** * Applies labels to a term, removing any existing labels. * - * @param term the term. + * @param term the term. * @param labels the labels to apply. * @return the modified term. */ @@ -1776,15 +1691,15 @@ public Term label(Term term, ImmutableArray labels) { if ((labels == null || labels.isEmpty())) { return term; } else { - return tf.createTerm(term.op(), term.subs(), term.boundVars(), - term.javaBlock(), labels); + return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock(), + labels); } } /** * Applies a label to a term, removing any existing labels. * - * @param term the term. + * @param term the term. * @param label the label to apply. * @return the modified term. */ @@ -1797,13 +1712,11 @@ public Term label(Term term, TermLabel label) { } public Term shortcut(Term term) { - return addLabel(term, - ParameterlessTermLabel.SHORTCUT_EVALUATION_LABEL); + return addLabel(term, ParameterlessTermLabel.SHORTCUT_EVALUATION_LABEL); } public Term unlabel(Term term) { - return tf.createTerm(term.op(), term.subs(), term.boundVars(), - term.javaBlock()); + return tf.createTerm(term.op(), term.subs(), term.boundVars(), term.javaBlock()); } public Term unlabelRecursive(Term term) { @@ -1811,26 +1724,24 @@ public Term unlabelRecursive(Term term) { for (int i = 0; i < subs.length; i++) { subs[i] = unlabelRecursive(term.sub(i)); } - return tf.createTerm(term.op(), subs, term.boundVars(), - term.javaBlock()); + return tf.createTerm(term.op(), subs, term.boundVars(), term.javaBlock()); } public Term dotArr(Term ref, Term idx) { if (ref == null || idx == null) { throw new TermCreationException("Tried to build an array access " - + "term without providing an " - + (ref == null ? "array reference." : "index.") + "(" + ref - + "[" + idx + "])"); + + "term without providing an " + (ref == null ? "array reference." : "index.") + + "(" + ref + "[" + idx + "])"); } final Sort elementSort; if (ref.sort() instanceof ArraySort) { elementSort = ((ArraySort) ref.sort()).elementSort(); } else { - throw new TermCreationException( - String.format("Tried to build an array access on an inacceptable sort: " + - "Sort: %s : %s with %s[%s] ", - ref.sort(), ref.sort().getClass().getSimpleName(), ref, idx)); + throw new TermCreationException(String.format( + "Tried to build an array access on an inacceptable sort: " + + "Sort: %s : %s with %s[%s] ", + ref.sort(), ref.sort().getClass().getSimpleName(), ref, idx)); } return select(elementSort, getBaseHeap(), ref, arr(idx)); @@ -1843,8 +1754,9 @@ public Term dotLength(Term a) { public Term created(Term h, Term o) { final TypeConverter tc = services.getTypeConverter(); - return equals(select(tc.getBooleanLDT().targetSort(), h, o, - func(tc.getHeapLDT().getCreated())), TRUE()); + return equals( + select(tc.getBooleanLDT().targetSort(), h, o, func(tc.getHeapLDT().getCreated())), + TRUE()); } public Term created(Term o) { @@ -1853,54 +1765,46 @@ public Term created(Term o) { public Term initialized(Term o) { final TypeConverter tc = services.getTypeConverter(); - return equals(dot(tc.getBooleanLDT().targetSort(), o, - tc.getHeapLDT().getInitialized()), TRUE()); + return equals(dot(tc.getBooleanLDT().targetSort(), o, tc.getHeapLDT().getInitialized()), + TRUE()); } public Term classPrepared(Sort classSort) { final TypeConverter tc = services.getTypeConverter(); - return equals( - staticDot(tc.getBooleanLDT().targetSort(), - tc.getHeapLDT().getClassPrepared(classSort, services)), - TRUE()); + return equals(staticDot(tc.getBooleanLDT().targetSort(), + tc.getHeapLDT().getClassPrepared(classSort, services)), TRUE()); } public Term classInitialized(Sort classSort) { final TypeConverter tc = services.getTypeConverter(); return equals(staticDot(tc.getBooleanLDT().targetSort(), - tc.getHeapLDT().getClassInitialized(classSort, services)), - TRUE()); + tc.getHeapLDT().getClassInitialized(classSort, services)), TRUE()); } public Term classInitializationInProgress(Sort classSort) { final TypeConverter tc = services.getTypeConverter(); return equals( - staticDot(tc.getBooleanLDT().targetSort(), tc.getHeapLDT() - .getClassInitializationInProgress(classSort, services)), + staticDot(tc.getBooleanLDT().targetSort(), + tc.getHeapLDT().getClassInitializationInProgress(classSort, services)), TRUE()); } public Term classErroneous(Sort classSort) { final TypeConverter tc = services.getTypeConverter(); - return equals( - staticDot(tc.getBooleanLDT().targetSort(), - tc.getHeapLDT().getClassErroneous(classSort, services)), - TRUE()); + return equals(staticDot(tc.getBooleanLDT().targetSort(), + tc.getHeapLDT().getClassErroneous(classSort, services)), TRUE()); } public Term store(Term h, Term o, Term f, Term v) { - return func(services.getTypeConverter().getHeapLDT().getStore(), h, o, - f, v); + return func(services.getTypeConverter().getHeapLDT().getStore(), h, o, f, v); } public Term create(Term h, Term o) { - return func(services.getTypeConverter().getHeapLDT().getCreate(), - new Term[]{h, o}); + return func(services.getTypeConverter().getHeapLDT().getCreate(), new Term[] { h, o }); } public Term anon(Term h1, Term s, Term h2) { - return func(services.getTypeConverter().getHeapLDT().getAnon(), h1, s, - h2); + return func(services.getTypeConverter().getHeapLDT().getAnon(), h1, s, h2); } public Term fieldStore(TermServices services, Term o, Function f, Term v) { @@ -1912,15 +1816,13 @@ public Term staticFieldStore(Function f, Term v) { } public Term arrayStore(Term o, Term i, Term v) { - return store(getBaseHeap(), o, - func(services.getTypeConverter().getHeapLDT().getArr(), i), v); + return store(getBaseHeap(), o, func(services.getTypeConverter().getHeapLDT().getArr(), i), + v); } public Term reachableValue(Term h, Term t, KeYJavaType kjt) { - assert t.sort().extendsTrans(kjt.getSort()) - || t.sort() instanceof ProgramSVSort; - final Sort s = t.sort() instanceof ProgramSVSort ? kjt.getSort() - : t.sort(); + assert t.sort().extendsTrans(kjt.getSort()) || t.sort() instanceof ProgramSVSort; + final Sort s = t.sort() instanceof ProgramSVSort ? kjt.getSort() : t.sort(); final IntegerLDT intLDT = services.getTypeConverter().getIntegerLDT(); final LocSetLDT setLDT = services.getTypeConverter().getLocSetLDT(); if (s.extendsTrans(services.getJavaInfo().objectSort())) { @@ -1945,14 +1847,12 @@ public Term reachableValue(ProgramVariable pv) { public Term frame(Term heapTerm, Map normalToAtPre, Term mod) { final Sort objectSort = services.getJavaInfo().objectSort(); - final Sort fieldSort = services.getTypeConverter().getHeapLDT() - .getFieldSort(); + final Sort fieldSort = services.getTypeConverter().getHeapLDT().getFieldSort(); final Name objVarName = new Name(newName("o")); final Name fieldVarName = new Name(newName("f")); final LogicVariable objVar = new LogicVariable(objVarName, objectSort); - final LogicVariable fieldVar = new LogicVariable(fieldVarName, - fieldSort); + final LogicVariable fieldVar = new LogicVariable(fieldVarName, fieldSort); final Term objVarTerm = var(objVar); final Term fieldVarTerm = var(fieldVar); @@ -1960,75 +1860,60 @@ public Term frame(Term heapTerm, Map normalToAtPre, Term mod) { final Term modAtPre = or.replace(mod); final Term createdAtPre = or.replace(created(heapTerm, objVarTerm)); - ImmutableList quantVars = ImmutableSLList - .nil(); + ImmutableList quantVars = ImmutableSLList.nil(); quantVars = quantVars.append(objVar); quantVars = quantVars.append(fieldVar); // selects on permission heaps have to be explicitly typed as field type // narrowing // does not follow Java typing for the permission heap - boolean permissionHeap = heapTerm.op() == services.getTypeConverter() - .getHeapLDT().getPermissionHeap(); - return all(quantVars, or(elementOf(objVarTerm, fieldVarTerm, modAtPre), - and(not(equals(objVarTerm, NULL())), not(createdAtPre)), - equals(select( - permissionHeap ? services.getTypeConverter() - .getPermissionLDT().targetSort() : Sort.ANY, - heapTerm, objVarTerm, fieldVarTerm), - select( - permissionHeap - ? services.getTypeConverter() - .getPermissionLDT().targetSort() - : Sort.ANY, - or.replace(heapTerm), objVarTerm, - fieldVarTerm)))); + boolean permissionHeap = + heapTerm.op() == services.getTypeConverter().getHeapLDT().getPermissionHeap(); + return all(quantVars, + or(elementOf(objVarTerm, fieldVarTerm, modAtPre), + and(not(equals(objVarTerm, NULL())), not(createdAtPre)), equals( + select(permissionHeap + ? services.getTypeConverter().getPermissionLDT() + .targetSort() + : Sort.ANY, heapTerm, objVarTerm, fieldVarTerm), + select(permissionHeap + ? services.getTypeConverter().getPermissionLDT() + .targetSort() + : Sort.ANY, or.replace(heapTerm), objVarTerm, + fieldVarTerm)))); } /** - * Returns the framing condition that the resulting heap is identical (i.e. - * has the same value in all locations) to the before-heap. + * Returns the framing condition that the resulting heap is identical (i.e. has the same value + * in all locations) to the before-heap. * * @see #frame(Term, Map, Term) */ - public Term frameStrictlyEmpty(Term heapTerm, - Map normalToAtPre) { + public Term frameStrictlyEmpty(Term heapTerm, Map normalToAtPre) { final Sort objectSort = services.getJavaInfo().objectSort(); - final Sort fieldSort = services.getTypeConverter().getHeapLDT() - .getFieldSort(); + final Sort fieldSort = services.getTypeConverter().getHeapLDT().getFieldSort(); final Name objVarName = new Name(newName("o")); final Name fieldVarName = new Name(newName("f")); final LogicVariable objVar = new LogicVariable(objVarName, objectSort); - final LogicVariable fieldVar = new LogicVariable(fieldVarName, - fieldSort); + final LogicVariable fieldVar = new LogicVariable(fieldVarName, fieldSort); final Term objVarTerm = var(objVar); final Term fieldVarTerm = var(fieldVar); final OpReplacer or = new OpReplacer(normalToAtPre, tf); - ImmutableList quantVars = ImmutableSLList - .nil(); + ImmutableList quantVars = ImmutableSLList.nil(); quantVars = quantVars.append(objVar); quantVars = quantVars.append(fieldVar); // see above - boolean permissionHeap = heapTerm.op() == services.getTypeConverter() - .getHeapLDT().getPermissionHeap(); + boolean permissionHeap = + heapTerm.op() == services.getTypeConverter().getHeapLDT().getPermissionHeap(); - return all(quantVars, - equals(select( - permissionHeap - ? services.getTypeConverter() - .getPermissionLDT().targetSort() - : Sort.ANY, - heapTerm, objVarTerm, fieldVarTerm), - select( - permissionHeap - ? services.getTypeConverter() - .getPermissionLDT().targetSort() - : Sort.ANY, - or.replace(heapTerm), objVarTerm, - fieldVarTerm))); + return all(quantVars, equals( + select(permissionHeap ? services.getTypeConverter().getPermissionLDT().targetSort() + : Sort.ANY, heapTerm, objVarTerm, fieldVarTerm), + select(permissionHeap ? services.getTypeConverter().getPermissionLDT().targetSort() + : Sort.ANY, or.replace(heapTerm), objVarTerm, fieldVarTerm))); } public Term anonUpd(LocationVariable heap, Term mod, Term anonHeap) { @@ -2037,9 +1922,9 @@ public Term anonUpd(LocationVariable heap, Term mod, Term anonHeap) { public Term forallHeaps(Services services, Term t) { final HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - final LogicVariable heapLV = new LogicVariable(new Name("h"), - heapLDT.targetSort()); - final Map map = new LinkedHashMap(); + final LogicVariable heapLV = new LogicVariable(new Name("h"), heapLDT.targetSort()); + final Map map = + new LinkedHashMap(); map.put(heapLDT.getHeap(), heapLV); final OpReplacer or = new OpReplacer(map, tf); t = or.replace(t); @@ -2051,13 +1936,11 @@ public Term forallHeaps(Services services, Term t) { // ------------------------------------------------------------------------- public Term acc(Term h, Term s, Term o1, Term o2) { - return func(services.getTypeConverter().getHeapLDT().getAcc(), h, s, o1, - o2); + return func(services.getTypeConverter().getHeapLDT().getAcc(), h, s, o1, o2); } public Term reach(Term h, Term s, Term o1, Term o2, Term n) { - return func(services.getTypeConverter().getHeapLDT().getReach(), h, s, - o1, o2, n); + return func(services.getTypeConverter().getHeapLDT().getReach(), h, s, o1, o2, n); } // ------------------------------------------------------------------------- @@ -2065,8 +1948,7 @@ public Term reach(Term h, Term s, Term o1, Term o2, Term n) { // ------------------------------------------------------------------------- public Term seqGet(Sort asSort, Term s, Term idx) { - return func(services.getTypeConverter().getSeqLDT().getSeqGet(asSort, - services), s, idx); + return func(services.getTypeConverter().getSeqLDT().getSeqGet(asSort, services), s, idx); } public Term seqLen(Term s) { @@ -2074,12 +1956,10 @@ public Term seqLen(Term s) { } /** - * Function representing the least index of an element x in a sequence s (or - * underspecified) + * Function representing the least index of an element x in a sequence s (or underspecified) */ public Term indexOf(Term s, Term x) { - return func(services.getTypeConverter().getSeqLDT().getSeqIndexOf(), s, - x); + return func(services.getTypeConverter().getSeqLDT().getSeqIndexOf(), s, x); } public Term seqEmpty() { @@ -2087,8 +1967,7 @@ public Term seqEmpty() { } public Term seqSingleton(Term x) { - return func(services.getTypeConverter().getSeqLDT().getSeqSingleton(), - x); + return func(services.getTypeConverter().getSeqLDT().getSeqSingleton(), x); } public Term seqConcat(Term s, Term s2) { @@ -2097,8 +1976,7 @@ public Term seqConcat(Term s, Term s2) { } else if (s2 == seqEmpty()) { return s; } else { - return func(services.getTypeConverter().getSeqLDT().getSeqConcat(), - s, s2); + return func(services.getTypeConverter().getSeqLDT().getSeqConcat(), s, s2); } } @@ -2119,8 +1997,7 @@ public Term seq(ImmutableList terms) { } public Term seqSub(Term s, Term from, Term to) { - return func(services.getTypeConverter().getSeqLDT().getSeqSub(), s, - from, to); + return func(services.getTypeConverter().getSeqLDT().getSeqSub(), s, from, to); } public Term seqReverse(Term s) { @@ -2134,8 +2011,8 @@ public Term seqReverse(Term s) { /** * Replaces a child term by another one. * - * @param term the term in which to perform the replacement. - * @param pos the position at which to perform the replacement. + * @param term the term in which to perform the replacement. + * @param pos the position at which to perform the replacement. * @param replacement the replacement term. * @return {@code term}, with the child at {@code pos} replaced by {@code replacement}. */ @@ -2159,11 +2036,7 @@ private Term replace(Term term, PosInTerm pos, Term replacement, int depth) { } } - return tf.createTerm( - term.op(), - newSubs, - term.boundVars(), - term.javaBlock(), + return tf.createTerm(term.op(), newSubs, term.boundVars(), term.javaBlock(), term.getLabels()); } @@ -2172,8 +2045,7 @@ public ImmutableSet unionToSet(Term s) { assert s.sort().equals(setLDT.targetSort()); final Function union = setLDT.getUnion(); ImmutableSet result = DefaultImmutableSet.nil(); - ImmutableList workingList = ImmutableSLList.nil() - .prepend(s); + ImmutableList workingList = ImmutableSLList.nil().prepend(s); while (!workingList.isEmpty()) { Term f = workingList.head(); workingList = workingList.tail(); @@ -2209,8 +2081,7 @@ public static Pair, Term> goBelowUpdates2(Term term) { } public Term seqDef(QuantifiableVariable qv, Term a, Term b, Term t) { - return func(services.getTypeConverter().getSeqLDT().getSeqDef(), - new Term[]{a, b, t}, + return func(services.getTypeConverter().getSeqLDT().getSeqDef(), new Term[] { a, b, t }, new ImmutableArray(qv)); } @@ -2233,8 +2104,8 @@ public ImmutableList getSorts(Iterable terms) { } /** - * Similar behavior as {@link #imp(Term, Term)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #imp(Term, Term)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param t1 The left side. * @param t2 The right side. @@ -2254,8 +2125,8 @@ public Term impPreserveLabels(Term t1, Term t2) { } /** - * Similar behavior as {@link #not(Term)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #not(Term)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param t The child {@link Term}. * @return The created {@link Term}. @@ -2273,8 +2144,8 @@ public Term notPreserveLabels(Term t) { } /** - * Similar behavior as {@link #and(Iterable)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #and(Iterable)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param subTerms The sub {@link Term}s. * @return The created {@link Term}. @@ -2288,8 +2159,8 @@ public Term andPreserveLabels(Iterable subTerms) { } /** - * Similar behavior as {@link #and(Term, Term)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #and(Term, Term)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param t1 The left side. * @param t2 The right side. @@ -2309,8 +2180,8 @@ public Term andPreserveLabels(Term t1, Term t2) { } /** - * Similar behavior as {@link #or(Iterable)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #or(Iterable)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param subTerms The sub {@link Term}s. * @return The created {@link Term}. @@ -2324,8 +2195,8 @@ public Term orPreserveLabels(Iterable subTerms) { } /** - * Similar behavior as {@link #or(Term, Term)} but simplifications are not - * performed if {@link TermLabel}s would be lost. + * Similar behavior as {@link #or(Term, Term)} but simplifications are not performed if + * {@link TermLabel}s would be lost. * * @param t1 The left side. * @param t2 The right side. @@ -2349,7 +2220,7 @@ public Term orPreserveLabels(Term t1, Term t2) { */ public Term fpEq(Term t1, Term t2) { FloatLDT floatLDT = services.getTypeConverter().getFloatLDT(); - if(t1.sort() == floatLDT.targetSort()) { + if (t1.sort() == floatLDT.targetSort()) { return func(floatLDT.getEquals(), t1, t2); } else { // If it is not float, assume double. It will fail if wrong args diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermCreationException.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermCreationException.java index 269f42ce19c..c3389a83041 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermCreationException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermCreationException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableArray; @@ -8,72 +11,66 @@ public class TermCreationException extends RuntimeException { - /** + /** * generated serial version UID */ private static final long serialVersionUID = -7173044450561438150L; public TermCreationException(String errorMessage) { - super(errorMessage); - } + super(errorMessage); + } - public TermCreationException(Operator op, Term failed) { - super(getErrorMessage(op, failed)); - } + public TermCreationException(Operator op, Term failed) { + super(getErrorMessage(op, failed)); + } - private static String getErrorMessage(Operator op, Term failed) { - ImmutableArray subs = failed.subs(); - for (int i = 0, n = subs.size(); i < n; i++) { - Term sub = subs.get(i); - assert sub == failed.subs().get(i); - } + private static String getErrorMessage(Operator op, Term failed) { + ImmutableArray subs = failed.subs(); + for (int i = 0, n = subs.size(); i < n; i++) { + Term sub = subs.get(i); + assert sub == failed.subs().get(i); + } - return "Building a term failed. Normally there is an arity mismatch " - + "or one of the subterms' sorts " - + "is not compatible (e.g. like the \'2\' in \"true & 2\")\n" - + "The top level operator was " - + op - + "(Sort: " - + op.sort(subs) - + ")" - + (op instanceof SortedOperator ? "; its expected arg sorts were:\n" - + argsToString((SortedOperator) op) - : "") + "\nThe subterms were:\n" + subsToString(subs); - } + return "Building a term failed. Normally there is an arity mismatch " + + "or one of the subterms' sorts " + + "is not compatible (e.g. like the \'2\' in \"true & 2\")\n" + + "The top level operator was " + op + "(Sort: " + op.sort(subs) + ")" + + (op instanceof SortedOperator + ? "; its expected arg sorts were:\n" + argsToString((SortedOperator) op) + : "") + + "\nThe subterms were:\n" + subsToString(subs); + } - private static String argsToString(SortedOperator f) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < f.arity(); i++) { - sb.append((i + 1) + ".) "); - sb.append("sort: " - + f.argSort(i) - + (f.argSort(i) == null ? "" : ", sort hash: " - + f.argSort(i).hashCode()) + "\n"); - } - return sb.toString(); - } + private static String argsToString(SortedOperator f) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < f.arity(); i++) { + sb.append((i + 1) + ".) "); + sb.append("sort: " + f.argSort(i) + + (f.argSort(i) == null ? "" : ", sort hash: " + f.argSort(i).hashCode()) + + "\n"); + } + return sb.toString(); + } - private static String subsToString(ImmutableArray subs) { - StringBuffer sb = new StringBuffer(); - for (int i = 0, n = subs.size(); i < n; i++) { - sb.append((i + 1) + ".) "); - Term subi = subs.get(i); - if (subi != null) { - sb.append(subi); - Sort subiSort = subi.sort(); - if (subiSort != null) { - sb.append("(sort: " + subi.sort() + ", sort hash: " - + subi.sort().hashCode() + ")\n"); + private static String subsToString(ImmutableArray subs) { + StringBuffer sb = new StringBuffer(); + for (int i = 0, n = subs.size(); i < n; i++) { + sb.append((i + 1) + ".) "); + Term subi = subs.get(i); + if (subi != null) { + sb.append(subi); + Sort subiSort = subi.sort(); + if (subiSort != null) { + sb.append("(sort: " + subi.sort() + ", sort hash: " + subi.sort().hashCode() + + ")\n"); + } else { + sb.append("(Unknown sort, \"null pointer\")"); + } + } else { + sb.append(" !null!\n"); } - else { - sb.append("(Unknown sort, \"null pointer\")"); - } - } - else { - sb.append(" !null!\n"); - } - } - return sb.toString(); - } + } + return sb.toString(); + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermFactory.java index 2d355061efb..6321b71ab18 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.List; @@ -12,16 +15,13 @@ import de.uka.ilkd.key.logic.op.QuantifiableVariable; /** - * The TermFactory is the only way to create terms using constructors - * of class Term or any of its subclasses. It is the only class that implements - * and may exploit knowledge about sub classes of {@link Term}. All other - * classes of the system only know about terms what the {@link Term} class - * offers them. + * The TermFactory is the only way to create terms using constructors of class Term or any + * of its subclasses. It is the only class that implements and may exploit knowledge about sub + * classes of {@link Term}. All other classes of the system only know about terms what the + * {@link Term} class offers them. * - * This class is used to encapsulate knowledge about the internal term - * structures. - * See {@link de.uka.ilkd.key.logic.TermBuilder} for more convenient methods to - * create terms. + * This class is used to encapsulate knowledge about the internal term structures. See + * {@link de.uka.ilkd.key.logic.TermBuilder} for more convenient methods to create terms. */ public final class TermFactory { @@ -30,9 +30,9 @@ public final class TermFactory { private final Map cache; - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- public TermFactory() { @@ -43,22 +43,20 @@ public TermFactory(Map cache) { this.cache = cache; } - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- /** - * Master method for term creation. Should be the only place where terms - * are created in the entire system. + * Master method for term creation. Should be the only place where terms are created in the + * entire system. */ - public Term createTerm(Operator op, - ImmutableArray subs, - ImmutableArray boundVars, - JavaBlock javaBlock, - ImmutableArray labels) { - if(op == null) { + public Term createTerm(Operator op, ImmutableArray subs, + ImmutableArray boundVars, JavaBlock javaBlock, + ImmutableArray labels) { + if (op == null) { throw new TermCreationException("Given operator is null."); } @@ -69,20 +67,16 @@ public Term createTerm(Operator op, return doCreateTerm(op, subs, boundVars, javaBlock, labels); } - public Term createTerm(Operator op, - ImmutableArray subs, - ImmutableArray boundVars, - JavaBlock javaBlock) { + public Term createTerm(Operator op, ImmutableArray subs, + ImmutableArray boundVars, JavaBlock javaBlock) { - return createTerm(op, subs, boundVars, javaBlock, null); + return createTerm(op, subs, boundVars, javaBlock, null); } - public Term createTerm(Operator op, - Term[] subs, - ImmutableArray boundVars, - JavaBlock javaBlock) { - return createTerm(op, createSubtermArray(subs), boundVars, javaBlock, null); + public Term createTerm(Operator op, Term[] subs, ImmutableArray boundVars, + JavaBlock javaBlock) { + return createTerm(op, createSubtermArray(subs), boundVars, javaBlock, null); } @@ -90,21 +84,15 @@ public Term createTerm(Operator op, Term... subs) { return createTerm(op, subs, null, null); } - public Term createTerm(Operator op, - Term[] subs, - ImmutableArray boundVars, - JavaBlock javaBlock, - ImmutableArray labels) { - return createTerm(op, createSubtermArray(subs), boundVars, javaBlock, labels); + public Term createTerm(Operator op, Term[] subs, ImmutableArray boundVars, + JavaBlock javaBlock, ImmutableArray labels) { + return createTerm(op, createSubtermArray(subs), boundVars, javaBlock, labels); } - public Term createTerm(Operator op, - Term[] subs, - ImmutableArray boundVars, - JavaBlock javaBlock, - TermLabel label) { - return createTerm(op, createSubtermArray(subs), boundVars, - javaBlock, new ImmutableArray(label)); + public Term createTerm(Operator op, Term[] subs, ImmutableArray boundVars, + JavaBlock javaBlock, TermLabel label) { + return createTerm(op, createSubtermArray(subs), boundVars, javaBlock, + new ImmutableArray(label)); } public Term createTerm(Operator op, Term[] subs, TermLabel label) { @@ -112,75 +100,70 @@ public Term createTerm(Operator op, Term[] subs, TermLabel label) { } public Term createTerm(Operator op, Term[] subs, ImmutableArray labels) { - return createTerm(op, createSubtermArray(subs), null, null, labels); + return createTerm(op, createSubtermArray(subs), null, null, labels); } public Term createTerm(Operator op, Term sub, ImmutableArray labels) { - return createTerm(op, new ImmutableArray(sub), null, null, labels); + return createTerm(op, new ImmutableArray(sub), null, null, labels); } public Term createTerm(Operator op, Term sub1, Term sub2, ImmutableArray labels) { - return createTerm(op, new Term[]{sub1, sub2}, null, null, labels); + return createTerm(op, new Term[] { sub1, sub2 }, null, null, labels); } public Term createTerm(Operator op, ImmutableArray labels) { - return createTerm(op, NO_SUBTERMS, null, null, labels); + return createTerm(op, NO_SUBTERMS, null, null, labels); } - //------------------------------------------------------------------------- - //private interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // private interface + // ------------------------------------------------------------------------- private ImmutableArray createSubtermArray(Term[] subs) { - return subs == null || subs.length == 0 ? - NO_SUBTERMS : new ImmutableArray(subs); + return subs == null || subs.length == 0 ? NO_SUBTERMS : new ImmutableArray(subs); } private Term doCreateTerm(Operator op, ImmutableArray subs, - ImmutableArray boundVars, - JavaBlock javaBlock, ImmutableArray labels) { - final Term newTerm - = (labels == null || labels.isEmpty() ? - new TermImpl(op, subs, boundVars, javaBlock) : - new LabeledTermImpl(op, subs, boundVars, javaBlock, labels)).checked(); + ImmutableArray boundVars, JavaBlock javaBlock, + ImmutableArray labels) { + final Term newTerm = + (labels == null || labels.isEmpty() ? new TermImpl(op, subs, boundVars, javaBlock) + : new LabeledTermImpl(op, subs, boundVars, javaBlock, labels)).checked(); // Check if caching is possible. It is not possible if a non empty JavaBlock is available // in the term or in one of its children because the meta information like PositionInfos // may be different. if (cache != null && !newTerm.containsJavaBlockRecursive()) { - Term term; - synchronized(cache) { - term = cache.get(newTerm); - } - if(term == null) { - term = newTerm; - synchronized(cache) { - cache.put(term, term); - } - } - return term; - } - else { - return newTerm; + Term term; + synchronized (cache) { + term = cache.get(newTerm); + } + if (term == null) { + term = newTerm; + synchronized (cache) { + cache.put(term, term); + } + } + return term; + } else { + return newTerm; } } /** - * Reduce the given list of terms into a one term by using the operator. - * The reduction is left-associative. e.g., the result is - * {@code ((a op b) op c) op d }. + * Reduce the given list of terms into a one term by using the operator. The reduction is + * left-associative. e.g., the result is {@code ((a op b) op c) op d }. * * @param junctor the left-associative operator to combine the terms together * @param terms a list of non-null temrs */ - public @Nonnull Term createTerm(@Nonnull Operator junctor, @Nonnull List terms) { - if(terms.size()==1) + public @Nonnull Term createTerm(@Nonnull Operator junctor, @Nonnull List terms) { + if (terms.size() == 1) return terms.get(0); else if (terms.size() == 2) return createTerm(junctor, terms.get(0), terms.get(1)); - final Optional reduce = terms.stream() - .reduce((a, b) -> createTerm(junctor, a, b)); - if(reduce.isPresent()) + final Optional reduce = terms.stream().reduce((a, b) -> createTerm(junctor, a, b)); + if (reduce.isPresent()) return reduce.get(); throw new IllegalArgumentException("list of terms is empty."); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermImpl.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermImpl.java index 7ff431e3892..35ec59b3138 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermImpl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermImpl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.concurrent.atomic.AtomicInteger; @@ -21,40 +24,42 @@ /** - * The currently only class implementing the Term interface. TermFactory should - * be the only class dealing directly with the TermImpl class. + * The currently only class implementing the Term interface. TermFactory should be the only class + * dealing directly with the TermImpl class. */ public class TermImpl implements Term { /** * A static empty list of terms used for memory reasons. */ - private static final ImmutableArray EMPTY_TERM_LIST - = new ImmutableArray(); + private static final ImmutableArray EMPTY_TERM_LIST = new ImmutableArray(); /** * A static empty list of quantifiable variables used for memory reasons. */ - private static final ImmutableArray EMPTY_VAR_LIST - = new ImmutableArray(); + private static final ImmutableArray EMPTY_VAR_LIST = + new ImmutableArray(); /** * A static empty list of term labels used for memory reasons. */ - private static final ImmutableArray EMPTY_LABEL_LIST - = new ImmutableArray(); + private static final ImmutableArray EMPTY_LABEL_LIST = + new ImmutableArray(); private static AtomicInteger serialNumberCounter = new AtomicInteger(); private final int serialNumber = serialNumberCounter.incrementAndGet(); - //content + // content private final Operator op; private final ImmutableArray subs; private final ImmutableArray boundVars; private final JavaBlock javaBlock; - //caches - private static enum ThreeValuedTruth { TRUE, FALSE, UNKNOWN } + // caches + private static enum ThreeValuedTruth { + TRUE, FALSE, UNKNOWN + } + private int depth = -1; /** * A cached value for computing the term's rigidness. @@ -64,58 +69,54 @@ private static enum ThreeValuedTruth { TRUE, FALSE, UNKNOWN } private int hashcode = -1; /** - * This flag indicates that the {@link Term} itself or one - * of its children contains a non empty {@link JavaBlock}. - * {@link Term}s which provides a {@link JavaBlock} directly or indirectly - * can't be cached because it is possible that the contained meta information - * inside the {@link JavaBlock}, e.g. {@link PositionInfo}s, are different. + * This flag indicates that the {@link Term} itself or one of its children contains a non empty + * {@link JavaBlock}. {@link Term}s which provides a {@link JavaBlock} directly or indirectly + * can't be cached because it is possible that the contained meta information inside the + * {@link JavaBlock}, e.g. {@link PositionInfo}s, are different. */ private ThreeValuedTruth containsJavaBlockRecursive = ThreeValuedTruth.UNKNOWN; - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- /** - * Constructs a term for the given operator, with the given sub terms, - * bounded variables and (if applicable) the code block on this term. + * Constructs a term for the given operator, with the given sub terms, bounded variables and (if + * applicable) the code block on this term. + * * @param op the operator of the term, e.g., some arithmetic operation - * @param subs the sub terms of the constructed term (whose type is - * constrained by the used operator) + * @param subs the sub terms of the constructed term (whose type is constrained by the used + * operator) * @param boundVars the bounded variables (if applicable), e.g., for quantifiers * @param javaBlock the code block (if applicable) after which the term is evaluated */ - public TermImpl(Operator op, - ImmutableArray subs, - ImmutableArray boundVars, - JavaBlock javaBlock) { + public TermImpl(Operator op, ImmutableArray subs, + ImmutableArray boundVars, JavaBlock javaBlock) { assert op != null; assert subs != null; this.op = op; this.subs = subs.size() == 0 ? EMPTY_TERM_LIST : subs; this.boundVars = boundVars == null ? EMPTY_VAR_LIST : boundVars; - this.javaBlock = javaBlock == null - ? JavaBlock.EMPTY_JAVABLOCK - : javaBlock; + this.javaBlock = javaBlock == null ? JavaBlock.EMPTY_JAVABLOCK : javaBlock; } - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- private ImmutableSet determineFreeVars() { ImmutableSet localFreeVars = DefaultImmutableSet.nil(); - if(op instanceof QuantifiableVariable) { + if (op instanceof QuantifiableVariable) { localFreeVars = localFreeVars.add((QuantifiableVariable) op); } - for(int i = 0, ar = arity(); i < ar; i++) { + for (int i = 0, ar = arity(); i < ar; i++) { ImmutableSet subFreeVars = sub(i).freeVars(); - for(int j = 0, sz = varsBoundHere(i).size(); j < sz; j++) { + for (int j = 0, sz = varsBoundHere(i).size(); j < sz; j++) { subFreeVars = subFreeVars.remove(varsBoundHere(i).get(j)); } localFreeVars = localFreeVars.union(subFreeVars); @@ -124,23 +125,21 @@ private ImmutableSet determineFreeVars() { } - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- /** - * Checks whether the Term is valid on the top level. If this is - * the case this method returns the Term unmodified. Otherwise a - * TermCreationException is thrown. + * Checks whether the Term is valid on the top level. If this is the case this method returns + * the Term unmodified. Otherwise a TermCreationException is thrown. */ public Term checked() { op.validTopLevelException(this); return this; - /*if (op.validTopLevel(this)) { - return this; - } else { - throw new TermCreationException(op, this); - }*/ + /* + * if (op.validTopLevel(this)) { return this; } else { throw new TermCreationException(op, + * this); } + */ } @Override @@ -150,13 +149,11 @@ public Operator op() { @Override - public T op(Class opClass) - throws IllegalArgumentException { + public T op(Class opClass) throws IllegalArgumentException { if (!opClass.isInstance(op)) { throw new IllegalArgumentException( - "Operator does not match the expected type:\n" - + "Operator type was: " + op.getClass() + "\n" - + "Expected type was: " + opClass); + "Operator does not match the expected type:\n" + "Operator type was: " + + op.getClass() + "\n" + "Expected type was: " + opClass); } return opClass.cast(op); } @@ -206,11 +203,11 @@ public Sort sort() { @Override public int depth() { - if(depth == -1) { + if (depth == -1) { int localDepth = -1; for (int i = 0, n = arity(); i < n; i++) { final int subTermDepth = sub(i).depth(); - if(subTermDepth > depth) { + if (subTermDepth > depth) { localDepth = subTermDepth; } } @@ -223,13 +220,13 @@ public int depth() { @Override public boolean isRigid() { - if(rigid == ThreeValuedTruth.UNKNOWN) { - if(!op.isRigid()) { + if (rigid == ThreeValuedTruth.UNKNOWN) { + if (!op.isRigid()) { rigid = ThreeValuedTruth.FALSE; } else { ThreeValuedTruth localIsRigid = ThreeValuedTruth.TRUE; - for(int i = 0, n = arity(); i < n; i++) { - if(!sub(i).isRigid()) { + for (int i = 0, n = arity(); i < n; i++) { + if (!sub(i).isRigid()) { localIsRigid = ThreeValuedTruth.FALSE; break; } @@ -244,7 +241,7 @@ public boolean isRigid() { @Override public ImmutableSet freeVars() { - if(freeVars == null) { + if (freeVars == null) { freeVars = determineFreeVars(); } return freeVars; @@ -254,7 +251,7 @@ public ImmutableSet freeVars() { public void execPostOrder(Visitor visitor) { visitor.subtreeEntered(this); if (visitor.visitSubtree(this)) { - for(int i = 0, ar = arity(); i < ar; i++) { + for (int i = 0, ar = arity(); i < ar; i++) { sub(i).execPostOrder(visitor); } } @@ -278,13 +275,11 @@ public void execPreOrder(Visitor visitor) { @Override public final boolean equalsModRenaming(Term o) { - if(o == this) { + if (o == this) { return true; } - return unifyHelp(this, o, - ImmutableSLList.nil(), - ImmutableSLList.nil(), - null); + return unifyHelp(this, o, ImmutableSLList.nil(), + ImmutableSLList.nil(), null); } // @@ -294,18 +289,13 @@ public final boolean equalsModRenaming(Term o) { /** * compare two quantifiable variables if they are equal modulo renaming * - * @param ownVar - * first QuantifiableVariable to be compared - * @param cmpVar - * second QuantifiableVariable to be compared - * @param ownBoundVars - * variables bound above the current position - * @param cmpBoundVars - * variables bound above the current position + * @param ownVar first QuantifiableVariable to be compared + * @param cmpVar second QuantifiableVariable to be compared + * @param ownBoundVars variables bound above the current position + * @param cmpBoundVars variables bound above the current position */ private static boolean compareBoundVariables(QuantifiableVariable ownVar, - QuantifiableVariable cmpVar, - ImmutableList ownBoundVars, + QuantifiableVariable cmpVar, ImmutableList ownBoundVars, ImmutableList cmpBoundVars) { final int ownNum = indexOf(ownVar, ownBoundVars); @@ -323,12 +313,10 @@ private static boolean compareBoundVariables(QuantifiableVariable ownVar, } /** - * @return the index of the first occurrence of var in - * list, or -1 if the variable is not an - * element of the list + * @return the index of the first occurrence of var in list, or + * -1 if the variable is not an element of the list */ - private static int indexOf(QuantifiableVariable var, - ImmutableList list) { + private static int indexOf(QuantifiableVariable var, ImmutableList list) { int res = 0; while (!list.isEmpty()) { if (list.head() == var) { @@ -343,21 +331,14 @@ private static int indexOf(QuantifiableVariable var, /** * Compares two terms modulo bound renaming * - * @param t0 - * the first term - * @param t1 - * the second term - * @param ownBoundVars - * variables bound above the current position - * @param cmpBoundVars - * variables bound above the current position - * @return true is returned iff the terms are equal modulo - * bound renaming + * @param t0 the first term + * @param t1 the second term + * @param ownBoundVars variables bound above the current position + * @param cmpBoundVars variables bound above the current position + * @return true is returned iff the terms are equal modulo bound renaming */ - private boolean unifyHelp(Term t0, Term t1, - ImmutableList ownBoundVars, - ImmutableList cmpBoundVars, - NameAbstractionTable nat) { + private boolean unifyHelp(Term t0, Term t1, ImmutableList ownBoundVars, + ImmutableList cmpBoundVars, NameAbstractionTable nat) { if (t0 == t1 && ownBoundVars.equals(cmpBoundVars)) { return true; @@ -366,8 +347,7 @@ private boolean unifyHelp(Term t0, Term t1, final Operator op0 = t0.op(); if (op0 instanceof QuantifiableVariable) { - return handleQuantifiableVariable(t0, t1, ownBoundVars, - cmpBoundVars); + return handleQuantifiableVariable(t0, t1, ownBoundVars, cmpBoundVars); } final Operator op1 = t1.op(); @@ -391,22 +371,21 @@ private boolean unifyHelp(Term t0, Term t1, private boolean handleQuantifiableVariable(Term t0, Term t1, ImmutableList ownBoundVars, ImmutableList cmpBoundVars) { - if (!((t1.op() instanceof QuantifiableVariable) && compareBoundVariables( - (QuantifiableVariable) t0.op(), (QuantifiableVariable) t1.op(), - ownBoundVars, cmpBoundVars))) { + if (!((t1.op() instanceof QuantifiableVariable) + && compareBoundVariables((QuantifiableVariable) t0.op(), + (QuantifiableVariable) t1.op(), ownBoundVars, cmpBoundVars))) { return false; } return true; } /** - * used to encode that handleJava results in an unsatisfiable - * constraint (faster than using exceptions) + * used to encode that handleJava results in an unsatisfiable constraint (faster than + * using exceptions) */ private static NameAbstractionTable FAILED = new NameAbstractionTable(); - private static NameAbstractionTable handleJava(Term t0, Term t1, - NameAbstractionTable nat) { + private static NameAbstractionTable handleJava(Term t0, Term t1, NameAbstractionTable nat) { if (!t0.javaBlock().isEmpty() || !t1.javaBlock().isEmpty()) { nat = checkNat(nat); @@ -415,14 +394,12 @@ private static NameAbstractionTable handleJava(Term t0, Term t1, } } - if (!(t0.op() instanceof SchemaVariable) - && t0.op() instanceof ProgramVariable) { + if (!(t0.op() instanceof SchemaVariable) && t0.op() instanceof ProgramVariable) { if (!(t1.op() instanceof ProgramVariable)) { return FAILED; } nat = checkNat(nat); - if (!((ProgramVariable) t0.op()).equalsModRenaming( - (ProgramVariable) t1.op(), nat)) { + if (!((ProgramVariable) t0.op()).equalsModRenaming((ProgramVariable) t1.op(), nat)) { return FAILED; } } @@ -432,8 +409,7 @@ private static NameAbstractionTable handleJava(Term t0, Term t1, private boolean descendRecursively(Term t0, Term t1, ImmutableList ownBoundVars, - ImmutableList cmpBoundVars, - NameAbstractionTable nat) { + ImmutableList cmpBoundVars, NameAbstractionTable nat) { for (int i = 0; i < t0.arity(); i++) { ImmutableList subOwnBoundVars = ownBoundVars; @@ -453,8 +429,8 @@ private boolean descendRecursively(Term t0, Term t1, subCmpBoundVars = subCmpBoundVars.prepend(cmpVar); } - boolean newConstraint = unifyHelp(t0.sub(i), t1.sub(i), - subOwnBoundVars, subCmpBoundVars, nat); + boolean newConstraint = + unifyHelp(t0.sub(i), t1.sub(i), subOwnBoundVars, subCmpBoundVars, nat); if (!newConstraint) { return false; @@ -479,42 +455,36 @@ private static NameAbstractionTable checkNat(NameAbstractionTable nat) { */ @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(o == null || o.getClass() != getClass() - || hashCode() != o.hashCode()) { + if (o == null || o.getClass() != getClass() || hashCode() != o.hashCode()) { return false; } final TermImpl t = (TermImpl) o; - return op.equals(t.op) - && t.hasLabels() == hasLabels() - && subs.equals(t.subs) - && boundVars.equals(t.boundVars) - && javaBlock.equals(t.javaBlock); + return op.equals(t.op) && t.hasLabels() == hasLabels() && subs.equals(t.subs) + && boundVars.equals(t.boundVars) && javaBlock.equals(t.javaBlock); } @Override public boolean equalsModIrrelevantTermLabels(Object o) { - if(o == this) { + if (o == this) { return true; } - if(o == null || !(o instanceof TermImpl)) { + if (o == null || !(o instanceof TermImpl)) { return false; } final TermImpl t = (TermImpl) o; - if (!(op.equals(t.op) - && boundVars.equals(t.boundVars) - && javaBlock.equals(t.javaBlock))) { + if (!(op.equals(t.op) && boundVars.equals(t.boundVars) && javaBlock.equals(t.javaBlock))) { return false; } - + Term other = (Term) o; for (TermLabel label : getLabels()) { @@ -530,9 +500,9 @@ public boolean equalsModIrrelevantTermLabels(Object o) { } for (int i = 0; i < subs.size(); ++i) { - if (!subs.get(i).equalsModIrrelevantTermLabels(t.subs.get(i))) { - return false; - } + if (!subs.get(i).equalsModIrrelevantTermLabels(t.subs.get(i))) { + return false; + } } return true; @@ -550,9 +520,7 @@ public boolean equalsModTermLabels(Object o) { final TermImpl t = (TermImpl) o; - if (!(op.equals(t.op) - && boundVars.equals(t.boundVars) - && javaBlock.equals(t.javaBlock))) { + if (!(op.equals(t.op) && boundVars.equals(t.boundVars) && javaBlock.equals(t.javaBlock))) { return false; } @@ -566,8 +534,8 @@ public boolean equalsModTermLabels(Object o) { @Override - public final int hashCode(){ - if(hashcode == -1) { + public final int hashCode() { + if (hashcode == -1) { // compute into local variable first to be thread-safe. this.hashcode = computeHashCode(); } @@ -576,8 +544,8 @@ public final int hashCode(){ /** - * Performs the actual computation of the hashcode and can be overwritten by subclasses - * if necessary + * Performs the actual computation of the hashcode and can be overwritten by subclasses if + * necessary */ protected int computeHashCode() { int hashcode = 5; @@ -586,7 +554,7 @@ protected int computeHashCode() { hashcode = hashcode * 17 + boundVars().hashCode(); hashcode = hashcode * 17 + javaBlock().hashCode(); - if(hashcode == -1) { + if (hashcode == -1) { hashcode = 0; } return hashcode; @@ -599,8 +567,8 @@ protected int computeHashCode() { @Override public String toString() { StringBuffer sb = new StringBuffer(); - if(!javaBlock.isEmpty()) { - if(op() == Modality.DIA) { + if (!javaBlock.isEmpty()) { + if (op() == Modality.DIA) { sb.append("\\<").append(javaBlock).append("\\> "); } else if (op() == Modality.BOX) { sb.append("\\[").append(javaBlock).append("\\] "); @@ -611,23 +579,23 @@ public String toString() { return sb.toString(); } else { sb.append(op().name().toString()); - if(!boundVars.isEmpty()) { + if (!boundVars.isEmpty()) { sb.append("{"); - for(int i = 0, n = boundVars.size(); i < n; i++) { + for (int i = 0, n = boundVars.size(); i < n; i++) { sb.append(boundVars.get(i)); - if(i < n - 1) { + if (i < n - 1) { sb.append(", "); } } sb.append("}"); } - if(arity() == 0) { + if (arity() == 0) { return sb.toString(); } sb.append("("); - for(int i = 0, ar = arity(); i < ar; i++) { + for (int i = 0, ar = arity(); i < ar; i++) { sb.append(sub(i)); - if(i < ar - 1) { + if (i < ar - 1) { sb.append(","); } } @@ -668,12 +636,12 @@ public ImmutableArray getLabels() { */ @Override public boolean containsJavaBlockRecursive() { - if ( containsJavaBlockRecursive == ThreeValuedTruth.UNKNOWN ) { + if (containsJavaBlockRecursive == ThreeValuedTruth.UNKNOWN) { ThreeValuedTruth result = ThreeValuedTruth.FALSE; - if (javaBlock != null && !javaBlock.isEmpty() ) { + if (javaBlock != null && !javaBlock.isEmpty()) { result = ThreeValuedTruth.TRUE; } else { - for (int i = 0, arity = subs.size(); ip_a
    is less than, equal, or greater than - * p_b regarding the ordering given by the - * implementing class + * + * @return a number negative, zero or a number positive if p_a is less than, equal, + * or greater than p_b regarding the ordering given by the implementing + * class */ - int compare ( Term p_a, Term p_b ); -} \ No newline at end of file + int compare(Term p_a, Term p_b); +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermServices.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermServices.java index 35d92f7af2c..e85f39cad92 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermServices.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/TermServices.java @@ -1,40 +1,45 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; /** - * This interface defines the basic functionalities of services - * required to construct {@link Term}s. + * This interface defines the basic functionalities of services required to construct {@link Term}s. + * * @author Richard Bubel */ public interface TermServices { /** * returns the namespaces for functions, predicates etc. + * * @return the proof specific namespaces */ public abstract NamespaceSet getNamespaces(); /** * Returns the {@link TermBuilder} used to create {@link Term}s. + * * @return The {@link TermBuilder} used to create {@link Term}s. */ public abstract TermBuilder getTermBuilder(); - + /** - * - * Returns either the cache backed or raw {@link TermBuilder} used to create {@link Term}s. - * Usually the cache backed version is the intended one. The non-cached version is for - * use cases where a lot of intermediate terms are created of which most exist only for a - * very short time. To avoid polluting the cache it is then recommended to use the non-cache - * version - * + * + * Returns either the cache backed or raw {@link TermBuilder} used to create {@link Term}s. + * Usually the cache backed version is the intended one. The non-cached version is for use cases + * where a lot of intermediate terms are created of which most exist only for a very short time. + * To avoid polluting the cache it is then recommended to use the non-cache version + * * @return The {@link TermBuilder} used to create {@link Term}s. */ public abstract TermBuilder getTermBuilder(boolean withCache); - + /** * Returns the {@link TermBuilder} used to create {@link Term}s. + * * @return The {@link TermBuilder} used to create {@link Term}s. */ public abstract TermFactory getTermFactory(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/VariableNamer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/VariableNamer.java index ebd829be30a..105760390d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/VariableNamer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/VariableNamer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import java.util.ArrayList; @@ -49,11 +52,11 @@ * Responsible for program variable naming issues. */ public abstract class VariableNamer implements InstantiationProposer { - private static final Logger LOGGER = LoggerFactory.getLogger(VariableNamer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(VariableNamer.class); - //------------------------------------------------------------------------- - //member variables - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // member variables + // ------------------------------------------------------------------------- /** * default basename for variable name proposals @@ -68,8 +71,7 @@ public abstract class VariableNamer implements InstantiationProposer { - - /** + /** * status of suggestive name proposing */ private static boolean suggestive_off = true; @@ -80,67 +82,67 @@ public abstract class VariableNamer implements InstantiationProposer { */ protected final Services services; - protected final HashMap map = new LinkedHashMap(); - protected HashMap renamingHistory = new LinkedHashMap(); + protected final HashMap map = + new LinkedHashMap(); + protected HashMap renamingHistory = + new LinkedHashMap(); - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- /** * @param services pointer to services object */ public VariableNamer(Services services) { - this.services = services; + this.services = services; } - //------------------------------------------------------------------------- - //internal: general stuff - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal: general stuff + // ------------------------------------------------------------------------- /** - * determines the passed ProgramElementName's basename and index (ignoring - * temporary indices) + * determines the passed ProgramElementName's basename and index (ignoring temporary indices) */ - protected BasenameAndIndex getBasenameAndIndex(ProgramElementName name){ - BasenameAndIndex result = new BasenameAndIndex(); - - if(name instanceof PermIndProgramElementName) { - result.basename = ((IndProgramElementName)name).getBaseName(); - result.index = ((IndProgramElementName)name).getIndex(); - } else if(name instanceof TempIndProgramElementName) { - result.basename = ((IndProgramElementName)name).getBaseName(); - result.index = 0; - } else { - result.basename = name.toString(); - result.index = 0; - } - - return result; + protected BasenameAndIndex getBasenameAndIndex(ProgramElementName name) { + BasenameAndIndex result = new BasenameAndIndex(); + + if (name instanceof PermIndProgramElementName) { + result.basename = ((IndProgramElementName) name).getBaseName(); + result.index = ((IndProgramElementName) name).getIndex(); + } else if (name instanceof TempIndProgramElementName) { + result.basename = ((IndProgramElementName) name).getBaseName(); + result.index = 0; + } else { + result.basename = name.toString(); + result.index = 0; + } + + return result; } - public HashMap getRenamingMap(){ - return renamingHistory; + public HashMap getRenamingMap() { + return renamingHistory; } /** - * returns the subterm containing a java block, or null - * (helper for getProgramFromPIO()) + * returns the subterm containing a java block, or null (helper for getProgramFromPIO()) */ private Term findProgramInTerm(Term term) { - if(!term.javaBlock().isEmpty()) { - return term; - } - for(int i = 0; i < term.arity(); i++) { - Term subterm = findProgramInTerm(term.sub(i)); - if(subterm != null) { - return subterm; - } - } - return null; + if (!term.javaBlock().isEmpty()) { + return term; + } + for (int i = 0; i < term.arity(); i++) { + Term subterm = findProgramInTerm(term.sub(i)); + if (subterm != null) { + return subterm; + } + } + return null; } @@ -148,46 +150,43 @@ private Term findProgramInTerm(Term term) { * returns the program contained in a PosInOccurrence */ protected ProgramElement getProgramFromPIO(PosInOccurrence pio) { - Term progTerm; - if(pio != null - && (progTerm = findProgramInTerm(pio.subTerm())) != null) { - return progTerm.javaBlock().program(); - } else { - return new EmptyStatement(); - } + Term progTerm; + if (pio != null && (progTerm = findProgramInTerm(pio.subTerm())) != null) { + return progTerm.javaBlock().program(); + } else { + return new EmptyStatement(); + } } /** * creates a ProgramElementName object to be used for permanent names */ - protected ProgramElementName createName(String basename, - int index, - NameCreationInfo creationInfo) { + protected ProgramElementName createName(String basename, int index, + NameCreationInfo creationInfo) { return new PermIndProgramElementName(basename, index, creationInfo); } - //------------------------------------------------------------------------- - //internal: counter finding - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal: counter finding + // ------------------------------------------------------------------------- /** - * returns the maximum counter value already associated with the passed - * basename in the passed list of global variables, or -1 + * returns the maximum counter value already associated with the passed basename in the passed + * list of global variables, or -1 */ - protected int getMaxCounterInGlobals(String basename, - Iterable globals) { + protected int getMaxCounterInGlobals(String basename, Iterable globals) { int result = -1; Iterator it = globals.iterator(); - while(it.hasNext()) { + while (it.hasNext()) { ProgramElementName name = it.next(); - BasenameAndIndex bai = getBasenameAndIndex(name); - if(bai.basename.equals(basename) && bai.index > result) { - result = bai.index; - } + BasenameAndIndex bai = getBasenameAndIndex(name); + if (bai.basename.equals(basename) && bai.index > result) { + result = bai.index; + } } return result; @@ -195,102 +194,97 @@ protected int getMaxCounterInGlobals(String basename, /** - * returns the maximum counter value already associated with the passed - * basename in the passed program (ignoring temporary counters), or -1 + * returns the maximum counter value already associated with the passed basename in the passed + * program (ignoring temporary counters), or -1 */ - protected int getMaxCounterInProgram(String basename, - ProgramElement program, - PosInProgram posOfDeclaration) { - class MyWalker extends CustomJavaASTWalker { - public String basename; - public int maxCounter = -1; - - public MyWalker(ProgramElement program, - PosInProgram posOfDeclaration) { - super(program, posOfDeclaration); - } - - protected void doAction(ProgramElement node) { - if(node instanceof ProgramVariable) { - ProgramVariable var = (ProgramVariable)node; - ProgramElementName name = var.getProgramElementName(); - if(!(name instanceof TempIndProgramElementName)) { - BasenameAndIndex bai = getBasenameAndIndex(name); - if(bai.basename.equals(basename) - && bai.index > maxCounter) { - maxCounter = bai.index; - } - } - } - } - } - - MyWalker walker = new MyWalker(program, posOfDeclaration); - walker.basename = basename; - walker.start(); - - return walker.maxCounter; + protected int getMaxCounterInProgram(String basename, ProgramElement program, + PosInProgram posOfDeclaration) { + class MyWalker extends CustomJavaASTWalker { + public String basename; + public int maxCounter = -1; + + public MyWalker(ProgramElement program, PosInProgram posOfDeclaration) { + super(program, posOfDeclaration); + } + + protected void doAction(ProgramElement node) { + if (node instanceof ProgramVariable) { + ProgramVariable var = (ProgramVariable) node; + ProgramElementName name = var.getProgramElementName(); + if (!(name instanceof TempIndProgramElementName)) { + BasenameAndIndex bai = getBasenameAndIndex(name); + if (bai.basename.equals(basename) && bai.index > maxCounter) { + maxCounter = bai.index; + } + } + } + } + } + + MyWalker walker = new MyWalker(program, posOfDeclaration); + walker.basename = basename; + walker.start(); + + return walker.maxCounter; } - //------------------------------------------------------------------------- - //internal: uniqueness checking - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal: uniqueness checking + // ------------------------------------------------------------------------- /** * tells whether a name is unique in the passed list of global variables */ protected boolean isUniqueInGlobals(String name, Iterable globals) { - Iterator it = globals.iterator(); - while(it.hasNext()) { - ProgramElementName n = it.next(); - if(n.toString().equals(name)) { - return false; - } - } - return true; + Iterator it = globals.iterator(); + while (it.hasNext()) { + ProgramElementName n = it.next(); + if (n.toString().equals(name)) { + return false; + } + } + return true; } /** * tells whether a name is unique in the passed program */ - protected boolean isUniqueInProgram(String name, - ProgramElement program, - PosInProgram posOfDeclaration) { - class MyWalker extends CustomJavaASTWalker { - public String nameToFind; - public boolean foundIt = false; - - public MyWalker(ProgramElement program, - PosInProgram posOfDeclaration) { - super(program, posOfDeclaration); - } - - protected void doAction(ProgramElement node) { - if(node instanceof ProgramVariable) { - ProgramVariable var = (ProgramVariable)node; - ProgramElementName varname = var.getProgramElementName(); - if(varname.getProgramName().equals(nameToFind)) { - foundIt = true; - } - } - } - } - - MyWalker walker = new MyWalker(program, posOfDeclaration); - walker.nameToFind = name; - walker.start(); - - return !walker.foundIt; + protected boolean isUniqueInProgram(String name, ProgramElement program, + PosInProgram posOfDeclaration) { + class MyWalker extends CustomJavaASTWalker { + public String nameToFind; + public boolean foundIt = false; + + public MyWalker(ProgramElement program, PosInProgram posOfDeclaration) { + super(program, posOfDeclaration); + } + + protected void doAction(ProgramElement node) { + if (node instanceof ProgramVariable) { + ProgramVariable var = (ProgramVariable) node; + ProgramElementName varname = var.getProgramElementName(); + if (varname.getProgramName().equals(nameToFind)) { + foundIt = true; + } + } + } + } + + MyWalker walker = new MyWalker(program, posOfDeclaration); + walker.nameToFind = name; + walker.start(); + + return !walker.foundIt; } - //------------------------------------------------------------------------- - //internal: uniform treatment of global variables - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal: uniform treatment of global variables + // ------------------------------------------------------------------------- /** * creates a Globals object for use with other internal methods @@ -317,38 +311,37 @@ protected Iterable wrapGlobals(ImmutableSet - //------------------------------------------------------------------------- - //interface: renaming - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // interface: renaming + // ------------------------------------------------------------------------- /** - * intended to be called when symbolically executing a variable declaration; - * resolves any naming conflicts between the new variable and other global - * variables by renaming the new variable and / or other variables + * intended to be called when symbolically executing a variable declaration; resolves any naming + * conflicts between the new variable and other global variables by renaming the new variable + * and / or other variables + * * @param var the new program variable * @param goal the goal * @param posOfFind the PosInOccurrence of the currently executed program * @return the renamed version of the var parameter */ - public abstract ProgramVariable rename(ProgramVariable var, - Goal goal, - PosInOccurrence posOfFind); + public abstract ProgramVariable rename(ProgramVariable var, Goal goal, + PosInOccurrence posOfFind); - //------------------------------------------------------------------------- - //internal: name proposals - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal: name proposals + // ------------------------------------------------------------------------- /** * proposes a base name for a given sort */ private String getBaseNameProposal(Type type) { - String result; - if(type instanceof ArrayType) { - result = getBaseNameProposal(((ArrayType)type).getBaseType() - .getKeYJavaType() - .getJavaType()); + String result; + if (type instanceof ArrayType) { + result = getBaseNameProposal( + ((ArrayType) type).getBaseType().getKeYJavaType().getJavaType()); result += "_arr"; } else { String name = type.getName(); @@ -360,43 +353,40 @@ private String getBaseNameProposal(Type type) { } } - return result; + return result; } /** - * proposes a unique name for the instantiation of a schema variable - * (like getProposal(), but somewhat less nicely) + * proposes a unique name for the instantiation of a schema variable (like getProposal(), but + * somewhat less nicely) + * * @param basename desired base name, or null to use default * @param sv the schema variable * @param posOfFind the PosInOccurrence containing the name's target program - * @param posOfDeclaration the PosInProgram where the name will be declared - * (or null to just be pessimistic about the scope) - * @param previousProposals list of names which should be considered taken, - * or null + * @param posOfDeclaration the PosInProgram where the name will be declared (or null to just be + * pessimistic about the scope) + * @param previousProposals list of names which should be considered taken, or null * @return the name proposal, or null if no proposal is available */ - protected ProgramElementName getNameProposalForSchemaVariable( - String basename, - SchemaVariable sv, - PosInOccurrence posOfFind, - PosInProgram posOfDeclaration, - ImmutableList previousProposals) { + protected ProgramElementName getNameProposalForSchemaVariable(String basename, + SchemaVariable sv, PosInOccurrence posOfFind, PosInProgram posOfDeclaration, + ImmutableList previousProposals) { ProgramElementName result = null; Sort svSort = sv.sort(); - if(svSort == ProgramSVSort.VARIABLE) { - if(basename == null || "".equals(basename)) { + if (svSort == ProgramSVSort.VARIABLE) { + if (basename == null || "".equals(basename)) { basename = DEFAULT_BASENAME; } - int cnt = getMaxCounterInProgram(basename, - getProgramFromPIO(posOfFind), - posOfDeclaration) + 1; + int cnt = + getMaxCounterInProgram(basename, getProgramFromPIO(posOfFind), posOfDeclaration) + + 1; result = createName(basename, cnt, null); - //avoid using a previous proposal again - if(previousProposals != null) { + // avoid using a previous proposal again + if (previousProposals != null) { boolean collision; do { collision = false; @@ -408,7 +398,7 @@ protected ProgramElementName getNameProposalForSchemaVariable( break; } } - } while(collision); + } while (collision); } } @@ -417,197 +407,168 @@ protected ProgramElementName getNameProposalForSchemaVariable( - //------------------------------------------------------------------------- - //interface: name proposals - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // interface: name proposals + // ------------------------------------------------------------------------- /** - * proposes a unique name; intended for use in places where the information - * required by getProposal() is not available + * proposes a unique name; intended for use in places where the information required by + * getProposal() is not available + * * @param basename desired base name, or null to use default * @return the name proposal */ public ProgramElementName getTemporaryNameProposal(String basename) { - if(basename == null || "".equals(basename)) { + if (basename == null || "".equals(basename)) { basename = DEFAULT_BASENAME; } int cnt = services.getCounter(TEMPCOUNTER_NAME).getCountPlusPlus(); - //using null as undo anchor should be okay, since the name which the - //the counter is used for is only temporary and will be changed - //before the variable enters the logic + // using null as undo anchor should be okay, since the name which the + // the counter is used for is only temporary and will be changed + // before the variable enters the logic - return new TempIndProgramElementName(basename, - cnt, - null); + return new TempIndProgramElementName(basename, cnt, null); } /** * proposes a unique name for the instantiation of a schema variable + * * @param app the taclet app * @param var the schema variable to be instantiated * @param services not used * @param undoAnchor not used - * @param previousProposals list of names which should be considered taken, - * or null + * @param previousProposals list of names which should be considered taken, or null * @return the name proposal, or null if no proposal is available */ - public String getProposal(TacletApp app, - SchemaVariable var, - Services services, - Node undoAnchor, - ImmutableList previousProposals) { - //determine posOfDeclaration from TacletApp - ContextInstantiationEntry cie - = app.instantiations().getContextInstantiation(); - PosInProgram posOfDeclaration - = (cie == null ? null : cie.prefix()); - - //determine a suitable base name + public String getProposal(TacletApp app, SchemaVariable var, Services services, Node undoAnchor, + ImmutableList previousProposals) { + // determine posOfDeclaration from TacletApp + ContextInstantiationEntry cie = app.instantiations().getContextInstantiation(); + PosInProgram posOfDeclaration = (cie == null ? null : cie.prefix()); + + // determine a suitable base name String basename = null; NewVarcond nv = app.taclet().varDeclaredNew(var); - if(nv != null) { - Type type = nv.getType(); - if(type != null) { - basename = getBaseNameProposal(type); - } else { - SchemaVariable psv = nv.getPeerSchemaVariable(); - Object inst = app.instantiations().getInstantiation(psv); - if(inst instanceof Expression) { - final ExecutionContext ec = - app.instantiations().getExecutionContext(); - if(ec != null) { - KeYJavaType kjt - = ((Expression)inst).getKeYJavaType(this.services, - ec); - basename = getBaseNameProposal(kjt.getJavaType()); - } else { - // usually this should never be entered, but because of - // naming issues we do not want nullpointer exceptions - // 'u' for unknown - basename = "u"; - } - } - } + if (nv != null) { + Type type = nv.getType(); + if (type != null) { + basename = getBaseNameProposal(type); + } else { + SchemaVariable psv = nv.getPeerSchemaVariable(); + Object inst = app.instantiations().getInstantiation(psv); + if (inst instanceof Expression) { + final ExecutionContext ec = app.instantiations().getExecutionContext(); + if (ec != null) { + KeYJavaType kjt = ((Expression) inst).getKeYJavaType(this.services, ec); + basename = getBaseNameProposal(kjt.getJavaType()); + } else { + // usually this should never be entered, but because of + // naming issues we do not want nullpointer exceptions + // 'u' for unknown + basename = "u"; + } + } + } } - //get the proposal - ProgramElementName name - = getNameProposalForSchemaVariable( - basename, - var, - app.posInOccurrence(), - posOfDeclaration, - previousProposals); + // get the proposal + ProgramElementName name = getNameProposalForSchemaVariable(basename, var, + app.posInOccurrence(), posOfDeclaration, previousProposals); return (name == null ? null : name.toString()); } - //------------------------------------------------------------------------- - //interface: uniqueness checking - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // interface: uniqueness checking + // ------------------------------------------------------------------------- /** - * tells whether a name for instantiating a schema variable is unique - * within its scope + * tells whether a name for instantiating a schema variable is unique within its scope + * * @param name the name to be checked * @param sv the schema variable * @param posOfFind the PosInOccurrence of the name's target program * @param posOfDeclaration the PosInProgram where the name will be declared - * @return true if the name is unique or if its uniqueness cannot be - * checked, else false + * @return true if the name is unique or if its uniqueness cannot be checked, else false */ - public boolean isUniqueNameForSchemaVariable(String name, - SchemaVariable sv, - PosInOccurrence posOfFind, - PosInProgram posOfDeclaration) { - boolean result = true; - - Sort svSort = sv.sort(); - if(svSort == ProgramSVSort.VARIABLE) { - result = isUniqueInProgram(name, - getProgramFromPIO(posOfFind), - posOfDeclaration); - } - - return result; + public boolean isUniqueNameForSchemaVariable(String name, SchemaVariable sv, + PosInOccurrence posOfFind, PosInProgram posOfDeclaration) { + boolean result = true; + + Sort svSort = sv.sort(); + if (svSort == ProgramSVSort.VARIABLE) { + result = isUniqueInProgram(name, getProgramFromPIO(posOfFind), posOfDeclaration); + } + + return result; } - //------------------------------------------------------------------------- - //interface: name parsing - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // interface: name parsing + // ------------------------------------------------------------------------- /** - * parses the passed string and creates a suitable program element name - * (this does *not* make the name unique - if that is necessary, use either - * getTemporaryNameProposal() or getProposal()) + * parses the passed string and creates a suitable program element name (this does *not* make + * the name unique - if that is necessary, use either getTemporaryNameProposal() or + * getProposal()) + * * @param name the name as a string * @param creationInfo optional name creation info the name should carry * @param comments any comments the name should carry * @return the name as a ProgramElementName */ - public static ProgramElementName parseName(String name, - NameCreationInfo creationInfo, - Comment[] comments) { - ProgramElementName result; - - int sepPos = name.lastIndexOf(TempIndProgramElementName.SEPARATOR); - if(sepPos > 0) { - String basename = name.substring(0, sepPos); - int index = Integer.parseInt(name.substring(sepPos + 1)); - result = new TempIndProgramElementName(basename, - index, - creationInfo, - comments); - } else { - sepPos = name.lastIndexOf(PermIndProgramElementName.SEPARATOR); - if(sepPos > 0) { - try { - String basename = name.substring(0, sepPos); - int index = Integer.parseInt(name.substring(sepPos + 1)); - result = new PermIndProgramElementName(basename, - index, - creationInfo, - comments); - } catch(NumberFormatException e) { - result = new ProgramElementName(name, - creationInfo, - comments); - } - } else { - result = new ProgramElementName(name, creationInfo, comments); - } - } - - return result; + public static ProgramElementName parseName(String name, NameCreationInfo creationInfo, + Comment[] comments) { + ProgramElementName result; + + int sepPos = name.lastIndexOf(TempIndProgramElementName.SEPARATOR); + if (sepPos > 0) { + String basename = name.substring(0, sepPos); + int index = Integer.parseInt(name.substring(sepPos + 1)); + result = new TempIndProgramElementName(basename, index, creationInfo, comments); + } else { + sepPos = name.lastIndexOf(PermIndProgramElementName.SEPARATOR); + if (sepPos > 0) { + try { + String basename = name.substring(0, sepPos); + int index = Integer.parseInt(name.substring(sepPos + 1)); + result = new PermIndProgramElementName(basename, index, creationInfo, comments); + } catch (NumberFormatException e) { + result = new ProgramElementName(name, creationInfo, comments); + } + } else { + result = new ProgramElementName(name, creationInfo, comments); + } + } + + return result; } - public static ProgramElementName parseName(String name, - NameCreationInfo creationInfo) { - return parseName(name, creationInfo, new Comment[0]); + public static ProgramElementName parseName(String name, NameCreationInfo creationInfo) { + return parseName(name, creationInfo, new Comment[0]); } - public static ProgramElementName parseName(String name, - Comment[] comments) { - return parseName(name, null, comments); + public static ProgramElementName parseName(String name, Comment[] comments) { + return parseName(name, null, comments); } public static ProgramElementName parseName(String name) { - return parseName(name, null, new Comment[0]); + return parseName(name, null, new Comment[0]); } - //------------------------------------------------------------------------- - //interface: suggestive name proposals - //(taken from VarNameDeliverer.java, pretty much unchanged) - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // interface: suggestive name proposals + // (taken from VarNameDeliverer.java, pretty much unchanged) + // ------------------------------------------------------------------------- public static void setSuggestiveEnabled(boolean enabled) { suggestive_off = !enabled; @@ -615,73 +576,64 @@ public static void setSuggestiveEnabled(boolean enabled) { // precondition: sv.sort()==ProgramSVSort.VARIABLE - public String getSuggestiveNameProposalForProgramVariable( - SchemaVariable sv, - TacletApp app, - Services services, - ImmutableList previousProposals){ - if(suggestive_off) { - return getProposal(app, sv, services, null, previousProposals); - } + public String getSuggestiveNameProposalForProgramVariable(SchemaVariable sv, TacletApp app, + Services services, ImmutableList previousProposals) { + if (suggestive_off) { + return getProposal(app, sv, services, null, previousProposals); + } String proposal; - try { - Iterator templs = - app.taclet().goalTemplates().iterator(); - RewriteTacletGoalTemplate rwgt =null; - String name = ""; - while (templs.hasNext()) { + try { + Iterator templs = app.taclet().goalTemplates().iterator(); + RewriteTacletGoalTemplate rwgt = null; + String name = ""; + while (templs.hasNext()) { rwgt = (RewriteTacletGoalTemplate) templs.next(); - Term t = findProgramInTerm(rwgt.replaceWith()); - ContextStatementBlock c = - (ContextStatementBlock) t.javaBlock().program(); - if (c.getStatementAt(0) instanceof LocalVariableDeclaration) { - VariableSpecification v = - ((LocalVariableDeclaration) c.getStatementAt(0)). - getVariables().get(0); - - if (v.hasInitializer()) { - ProgramElement rhs = instantiateExpression( - v.getInitializer(), app.instantiations(), services); - name = ProofSaver.printProgramElement(rhs).toString(); - break; - } else if (c.getStatementAt(1) instanceof CopyAssignment) { - CopyAssignment p2 = (CopyAssignment) c.getStatementAt(1); - Expression lhs = p2.getExpressionAt(0); - if (lhs.equals(sv)) { - SchemaVariable rhs = - (SchemaVariable) p2.getExpressionAt(1); - name=app.instantiations().getInstantiation(rhs). - toString(); - break; - } - } - } - - } - if ("".equals(name)) throw new Exception(); - proposal = "["+name+"]"; - } catch(Exception e) { - LOGGER.info("",e); - return getProposal(app, sv, services, null, previousProposals); - } - return proposal; + Term t = findProgramInTerm(rwgt.replaceWith()); + ContextStatementBlock c = (ContextStatementBlock) t.javaBlock().program(); + if (c.getStatementAt(0) instanceof LocalVariableDeclaration) { + VariableSpecification v = + ((LocalVariableDeclaration) c.getStatementAt(0)).getVariables().get(0); + + if (v.hasInitializer()) { + ProgramElement rhs = instantiateExpression(v.getInitializer(), + app.instantiations(), services); + name = ProofSaver.printProgramElement(rhs).toString(); + break; + } else if (c.getStatementAt(1) instanceof CopyAssignment) { + CopyAssignment p2 = (CopyAssignment) c.getStatementAt(1); + Expression lhs = p2.getExpressionAt(0); + if (lhs.equals(sv)) { + SchemaVariable rhs = (SchemaVariable) p2.getExpressionAt(1); + name = app.instantiations().getInstantiation(rhs).toString(); + break; + } + } + } + + } + if ("".equals(name)) + throw new Exception(); + proposal = "[" + name + "]"; + } catch (Exception e) { + LOGGER.info("", e); + return getProposal(app, sv, services, null, previousProposals); + } + return proposal; } public String getSuggestiveNameProposalForSchemaVariable(Expression e) { - if (suggestive_off) { - return - getTemporaryNameProposal(DEFAULT_BASENAME).toString(); - } - return "["+ProofSaver.printProgramElement(e)+"]"; + if (suggestive_off) { + return getTemporaryNameProposal(DEFAULT_BASENAME).toString(); + } + return "[" + ProofSaver.printProgramElement(e) + "]"; } - private ProgramElement instantiateExpression(ProgramElement e, - SVInstantiations svInst, - Services services) { + private ProgramElement instantiateExpression(ProgramElement e, SVInstantiations svInst, + Services services) { ProgramReplaceVisitor trans = new ProgramReplaceVisitor(e, services, svInst); trans.start(); return trans.result(); @@ -689,42 +641,36 @@ private ProgramElement instantiateExpression(ProgramElement e, - //------------------------------------------------------------------------- - //inner classes - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // inner classes + // ------------------------------------------------------------------------- /** * ProgramElementName carrying an additional index */ - public abstract static class IndProgramElementName - extends ProgramElementName { - private final String basename; + public abstract static class IndProgramElementName extends ProgramElementName { + private final String basename; private final int index; - IndProgramElementName(String name, - String basename, - int index, - NameCreationInfo creationInfo) { + IndProgramElementName(String name, String basename, int index, + NameCreationInfo creationInfo) { super(name, creationInfo); - this.basename = basename.intern(); + this.basename = basename.intern(); this.index = index; } - IndProgramElementName(String name, - String basename, - int index, - NameCreationInfo creationInfo, - Comment[] comments) { + IndProgramElementName(String name, String basename, int index, + NameCreationInfo creationInfo, Comment[] comments) { super(name, creationInfo, comments); - this.basename = basename.intern(); + this.basename = basename.intern(); this.index = index; } - public String getBaseName() { - return basename; - } + public String getBaseName() { + return basename; + } - public int getIndex() { + public int getIndex() { return index; } } @@ -733,25 +679,16 @@ public int getIndex() { /** * temporary indexed ProgramElementName */ - private static class TempIndProgramElementName - extends IndProgramElementName { - static final char SEPARATOR = '#'; + private static class TempIndProgramElementName extends IndProgramElementName { + static final char SEPARATOR = '#'; - TempIndProgramElementName(String basename, - int index, - NameCreationInfo creationInfo) { + TempIndProgramElementName(String basename, int index, NameCreationInfo creationInfo) { super(basename + SEPARATOR + index, basename, index, creationInfo); } - TempIndProgramElementName(String basename, - int index, - NameCreationInfo creationInfo, - Comment[] comments) { - super(basename + SEPARATOR + index, - basename, - index, - creationInfo, - comments); + TempIndProgramElementName(String basename, int index, NameCreationInfo creationInfo, + Comment[] comments) { + super(basename + SEPARATOR + index, basename, index, creationInfo, comments); } } @@ -759,28 +696,18 @@ private static class TempIndProgramElementName /** * regular indexed ProgramElementName */ - private static class PermIndProgramElementName - extends IndProgramElementName { - static final char SEPARATOR = '_'; - - PermIndProgramElementName(String basename, - int index, - NameCreationInfo creationInfo) { - super(basename + (index == 0 ? "" : SEPARATOR + "" + index), - basename, - index, - creationInfo); + private static class PermIndProgramElementName extends IndProgramElementName { + static final char SEPARATOR = '_'; + + PermIndProgramElementName(String basename, int index, NameCreationInfo creationInfo) { + super(basename + (index == 0 ? "" : SEPARATOR + "" + index), basename, index, + creationInfo); } - PermIndProgramElementName(String basename, - int index, - NameCreationInfo creationInfo, - Comment[] comments) { - super(basename + (index == 0 ? "" : SEPARATOR + "" + index), - basename, - index, - creationInfo, - comments); + PermIndProgramElementName(String basename, int index, NameCreationInfo creationInfo, + Comment[] comments) { + super(basename + (index == 0 ? "" : SEPARATOR + "" + index), basename, index, + creationInfo, comments); } } @@ -788,37 +715,34 @@ private static class PermIndProgramElementName * a customized JavaASTWalker */ private abstract static class CustomJavaASTWalker extends JavaASTWalker { - private ProgramElement declarationNode = null; - private int declarationScopeDepth = -2; - private int currentScopeDepth = -2; - - CustomJavaASTWalker(ProgramElement program, - PosInProgram posOfDeclaration) { - super(program); - if(posOfDeclaration != null) { - declarationNode = PosInProgram.getProgramAt(posOfDeclaration, - program); - } - } - - protected void walk(ProgramElement node) { - //ignore ExecutionContext and IProgramMethod branches; - //ignore anything rooted at a depth less or equal than the depth - //of the scope containing the declaration (except for this - //"declaration scope" itself); - if(node instanceof ExecutionContext - || node instanceof IProgramMethod) { - return; - } else if(node instanceof ScopeDefiningElement) { - currentScopeDepth = depth(); - } else if(node == declarationNode) { - declarationScopeDepth = currentScopeDepth; - } else if(depth() <= declarationScopeDepth) { - return; - } - - super.walk(node); - } + private ProgramElement declarationNode = null; + private int declarationScopeDepth = -2; + private int currentScopeDepth = -2; + + CustomJavaASTWalker(ProgramElement program, PosInProgram posOfDeclaration) { + super(program); + if (posOfDeclaration != null) { + declarationNode = PosInProgram.getProgramAt(posOfDeclaration, program); + } + } + + protected void walk(ProgramElement node) { + // ignore ExecutionContext and IProgramMethod branches; + // ignore anything rooted at a depth less or equal than the depth + // of the scope containing the declaration (except for this + // "declaration scope" itself); + if (node instanceof ExecutionContext || node instanceof IProgramMethod) { + return; + } else if (node instanceof ScopeDefiningElement) { + currentScopeDepth = depth(); + } else if (node == declarationNode) { + declarationScopeDepth = currentScopeDepth; + } else if (depth() <= declarationScopeDepth) { + return; + } + + super.walk(node); + } } @@ -826,14 +750,14 @@ protected void walk(ProgramElement node) { * tuple of a basename and an index */ protected static class BasenameAndIndex { - public String basename; - public int index; + public String basename; + public int index; } - public static Name getBasename(Name name){ - if(name instanceof IndProgramElementName){ - return new Name(((IndProgramElementName) name).getBaseName()); - } - return name; + public static Name getBasename(Name name) { + if (name instanceof IndProgramElementName) { + return new Name(((IndProgramElementName) name).getBaseName()); + } + return name; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Visitor.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Visitor.java index 8236beb1f52..edb09e5dc3f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/Visitor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/Visitor.java @@ -1,38 +1,43 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; public interface Visitor { /** * Checks if the subtree below the visited {@link Term} should be traversed. + * * @param visited The currently visited {@link Term}. * @return {@code true} visit sub tree, {@code false} skip sub tree. */ public boolean visitSubtree(Term visited); - + /** * the entry method for the visitor pattern + * * @param visited the Term to be visited */ public abstract void visit(Term visited); /** - * this method is called in execPreOrder and execPostOrder in class Term - * when entering the subtree rooted in the term subtreeRoot. - * Default implementation is to do nothing. Subclasses can - * override this method - * when the visitor behaviour depends on informations bound to subtrees. + * this method is called in execPreOrder and execPostOrder in class Term when entering the + * subtree rooted in the term subtreeRoot. Default implementation is to do nothing. Subclasses + * can override this method when the visitor behaviour depends on informations bound to + * subtrees. + * * @param subtreeRoot root of the subtree which the visitor enters. */ public void subtreeEntered(Term subtreeRoot); /** - * this method is called in execPreOrder and execPostOrder in class Term - * when leaving the subtree rooted in the term subtreeRoot. - * Default implementation is to do nothing. Subclasses can - * override this method - * when the visitor behaviour depends on informations bound to subtrees. + * this method is called in execPreOrder and execPostOrder in class Term when leaving the + * subtree rooted in the term subtreeRoot. Default implementation is to do nothing. Subclasses + * can override this method when the visitor behaviour depends on informations bound to + * subtrees. + * * @param subtreeRoot root of the subtree which the visitor leaves. */ public void subtreeLeft(Term subtreeRoot); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/WaryClashFreeSubst.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/WaryClashFreeSubst.java index 04bd296012e..127e399b446 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/WaryClashFreeSubst.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/WaryClashFreeSubst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic; import org.key_project.util.collection.ImmutableArray; @@ -12,214 +15,198 @@ public class WaryClashFreeSubst extends ClashFreeSubst { /** depth of recursion of the apply method */ - private int depth = 0; + private int depth = 0; /** the formula should be prepended with a quantifier */ - private boolean createQuantifier = false; + private boolean createQuantifier = false; - /** variable with which the original variable should be - * substituted below modalities */ - private QuantifiableVariable newVar = null; - private Term newVarTerm = null; + /** + * variable with which the original variable should be substituted below modalities + */ + private QuantifiableVariable newVar = null; + private Term newVarTerm = null; - /** variables occurring within the original term and within the - * term to be substituted */ - private ImmutableSet warysvars = null; + /** + * variables occurring within the original term and within the term to be substituted + */ + private ImmutableSet warysvars = null; - public WaryClashFreeSubst ( QuantifiableVariable v, Term s, TermBuilder tb ) { - super ( v, s, tb ); + public WaryClashFreeSubst(QuantifiableVariable v, Term s, TermBuilder tb) { + super(v, s, tb); warysvars = null; } /** - * substitute s for v in t, - * avoiding collisions by replacing bound variables in - * t if necessary. + * substitute s for v in t, avoiding collisions by + * replacing bound variables in t if necessary. */ @Override public Term apply(Term t) { Term res; - if ( depth == 0 ) { - if ( !getSubstitutedTerm ().isRigid () ) { - findUsedVariables ( t ); + if (depth == 0) { + if (!getSubstitutedTerm().isRigid()) { + findUsedVariables(t); } } ++depth; try { - res = super.apply ( t ); - } finally { - --depth; + res = super.apply(t); + } finally { + --depth; } - if ( createQuantifier && depth == 0 ) { - res = addWarySubst ( res ); + if (createQuantifier && depth == 0) { + res = addWarySubst(res); } return res; } /** - * Determine a set of variables that do already appear within - * t or the substituted term, and whose names should - * not be used for free variables + * Determine a set of variables that do already appear within t or the substituted + * term, and whose names should not be used for free variables */ - private void findUsedVariables ( Term t ) { + private void findUsedVariables(Term t) { VariableCollectVisitor vcv; - vcv = new VariableCollectVisitor (); - getSubstitutedTerm ().execPostOrder ( vcv ); - warysvars = vcv.vars (); + vcv = new VariableCollectVisitor(); + getSubstitutedTerm().execPostOrder(vcv); + warysvars = vcv.vars(); - vcv = new VariableCollectVisitor (); - t.execPostOrder ( vcv ); - warysvars = warysvars.union ( vcv.vars () ); + vcv = new VariableCollectVisitor(); + t.execPostOrder(vcv); + warysvars = warysvars.union(vcv.vars()); } /** - * Create a new logic variable to be used for substitutions below - * modalities + * Create a new logic variable to be used for substitutions below modalities */ - private void createVariable () { - if ( !createQuantifier ) { + private void createVariable() { + if (!createQuantifier) { createQuantifier = true; - if ( getSubstitutedTerm ().freeVars ().contains ( getVariable () ) ) { + if (getSubstitutedTerm().freeVars().contains(getVariable())) { // in this case one might otherwise get collisions, as the // substitution might be carried out partially within the scope // of the original substitution operator - newVar = newVarFor ( getVariable (), warysvars ); + newVar = newVarFor(getVariable(), warysvars); } else { - newVar = getVariable (); + newVar = getVariable(); } - newVarTerm = tb.var ( newVar ); + newVarTerm = tb.var(newVar); } } /** - * substitute s for v in - * t, avoiding collisions by replacing bound - * variables in t if necessary. It is - * assumed, that t contains a free occurrence of - * v. + * substitute s for v in t, avoiding collisions by + * replacing bound variables in t if necessary. It is assumed, that t + * contains a free occurrence of v. */ @Override protected Term apply1(Term t) { // don't move to a different modality level - if ( !getSubstitutedTerm ().isRigid () ) { - if ( t.op () instanceof Modality ) { - return applyOnModality ( t ); + if (!getSubstitutedTerm().isRigid()) { + if (t.op() instanceof Modality) { + return applyOnModality(t); } - if ( t.op () instanceof UpdateApplication ) { - return applyOnUpdate ( t ); + if (t.op() instanceof UpdateApplication) { + return applyOnUpdate(t); } } - if ( t.op() instanceof Transformer) { - return applyOnTransformer ( t ); + if (t.op() instanceof Transformer) { + return applyOnTransformer(t); } - return super.apply1 ( t ); + return super.apply1(t); } /** - * Apply the substitution (that replaces a variable with a - * non-rigid term) on t, which has a modality as top-level - * operator. This is done by creating a (top-level) existential - * quantifier. This method is only called from apply1 - * for substitutions with non-rigid terms + * Apply the substitution (that replaces a variable with a non-rigid term) on t, which has a + * modality as top-level operator. This is done by creating a (top-level) existential + * quantifier. This method is only called from apply1 for substitutions with + * non-rigid terms * * PRECONDITION: warysvars != null */ - private Term applyOnModality ( Term t ) { - return applyBelowModality ( t ); + private Term applyOnModality(Term t) { + return applyBelowModality(t); } /** - * Apply the substitution (that replaces a variable with a - * term) on t, which has a transformer procedure as top-level - * operator. This is done by creating a (top-level) existential - * quantifier. This method is only called from apply1 - * for substitutions with non-rigid terms + * Apply the substitution (that replaces a variable with a term) on t, which has a transformer + * procedure as top-level operator. This is done by creating a (top-level) existential + * quantifier. This method is only called from apply1 for substitutions with + * non-rigid terms * * PRECONDITION: warysvars != null */ - private Term applyOnTransformer ( Term t ) { - return applyBelowTransformer ( t ); + private Term applyOnTransformer(Term t) { + return applyBelowTransformer(t); } /** - * Apply the substitution (that replaces a variable with a - * non-rigid term) on t, which has an update operator as top-level - * operator. This is done by creating a (top-level) existential - * quantifier. This method is only called from apply1 - * for substitutions with non-rigid terms + * Apply the substitution (that replaces a variable with a non-rigid term) on t, which has an + * update operator as top-level operator. This is done by creating a (top-level) existential + * quantifier. This method is only called from apply1 for substitutions with + * non-rigid terms * * PRECONDITION: warysvars != null */ - private Term applyOnUpdate ( Term t ) { + private Term applyOnUpdate(Term t) { // only the last child is below the update - final Term target = UpdateApplication.getTarget ( t ); - if ( !target.freeVars ().contains ( getVariable () ) ) { - return super.apply1 ( t ); + final Term target = UpdateApplication.getTarget(t); + if (!target.freeVars().contains(getVariable())) { + return super.apply1(t); } final Term[] newSubterms = new Term[t.arity()]; @SuppressWarnings("unchecked") - final ImmutableArray[] newBoundVars = - new ImmutableArray[t.arity()]; + final ImmutableArray[] newBoundVars = new ImmutableArray[t.arity()]; final int targetPos = UpdateApplication.targetPos(); - for ( int i = 0; i < t.arity (); i++ ) { - if ( i != targetPos ) { - applyOnSubterm ( t, i, newSubterms, newBoundVars ); + for (int i = 0; i < t.arity(); i++) { + if (i != targetPos) { + applyOnSubterm(t, i, newSubterms, newBoundVars); } } newBoundVars[targetPos] = t.varsBoundHere(targetPos); - final boolean addSubst = - subTermChanges ( t.varsBoundHere ( targetPos ), target ); - newSubterms[targetPos] = addSubst ? substWithNewVar ( target ) - : target; - - return tb.tf().createTerm ( t.op (), - newSubterms, - getSingleArray(newBoundVars), - t.javaBlock ()); + final boolean addSubst = subTermChanges(t.varsBoundHere(targetPos), target); + newSubterms[targetPos] = addSubst ? substWithNewVar(target) : target; + + return tb.tf().createTerm(t.op(), newSubterms, getSingleArray(newBoundVars), t.javaBlock()); } /** * Apply the substitution to a term/formula below a modality or update */ - private Term applyBelowModality (Term t) { - return substWithNewVar ( t ); + private Term applyBelowModality(Term t) { + return substWithNewVar(t); } /** * Apply the substitution to a term/formula below a transformer procedure */ - private Term applyBelowTransformer (Term t) { - return substWithNewVar ( t ); + private Term applyBelowTransformer(Term t) { + return substWithNewVar(t); } /** - * Prepend the given term with a wary substitution (substituting - * newVar with getSubstitutedTerm()) + * Prepend the given term with a wary substitution (substituting newVar with + * getSubstitutedTerm()) */ - private Term addWarySubst (Term t) { - createVariable (); - return tb.subst(WarySubstOp.SUBST, - newVar, - getSubstitutedTerm (), - t ); + private Term addWarySubst(Term t) { + createVariable(); + return tb.subst(WarySubstOp.SUBST, newVar, getSubstitutedTerm(), t); } /** * Rename the original variable to be substituted to newVar */ - private Term substWithNewVar (Term t) { - createVariable (); - final ClashFreeSubst cfs = new ClashFreeSubst ( getVariable (), - newVarTerm, tb ); - return cfs.apply ( t ); + private Term substWithNewVar(Term t) { + createVariable(); + final ClashFreeSubst cfs = new ClashFreeSubst(getVariable(), newVarTerm, tb); + return cfs.apply(t); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabel.java index d614a5166ed..672665658e8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import de.uka.ilkd.key.logic.Name; @@ -19,7 +22,9 @@ public class BlockContractValidityTermLabel implements TermLabel { /** * Constructor. - * @param exceptionVariable the exception variable to distinguish normal from exceptional termination. + * + * @param exceptionVariable the exception variable to distinguish normal from exceptional + * termination. */ public BlockContractValidityTermLabel(ProgramVariable exceptionVariable) { this.exceptionVariable = exceptionVariable; @@ -31,9 +36,11 @@ public BlockContractValidityTermLabel(ProgramVariable exceptionVariable) { public String toString() { return NAME.toString() + "(" + getExceptionVariable() + ")"; } - + /** - * retrieves the original exception variable as found in the local variable declaration statement + * retrieves the original exception variable as found in the local variable declaration + * statement + * * @return the original exception variable */ public ProgramVariable getExceptionVariable() { @@ -46,8 +53,10 @@ public ProgramVariable getExceptionVariable() { @Override public ProgramVariable getChild(int i) { switch (i) { - case 0 : return getExceptionVariable(); - default : return null; + case 0: + return getExceptionVariable(); + default: + return null; } } @@ -59,7 +68,7 @@ public int getChildCount() { return 1; } - + /** * {@inheritDoc} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabelFactory.java index 2c1a84c42e8..dd747f91b87 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/BlockContractValidityTermLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.List; @@ -11,7 +14,8 @@ /** * A factory for creating {@link BlockContractValidityTermLabel} objects. */ -public class BlockContractValidityTermLabelFactory implements TermLabelFactory { +public class BlockContractValidityTermLabelFactory + implements TermLabelFactory { /** * {@inheritDoc} * @@ -19,16 +23,18 @@ public class BlockContractValidityTermLabelFactory implements TermLabelFactory parameters, TermServices services) throws TermLabelException { + public BlockContractValidityTermLabel parseInstance(List parameters, + TermServices services) throws TermLabelException { if (parameters == null || parameters.size() != 1) { - throw new TermLabelException("Label " + BlockContractValidityTermLabel.NAME + - " requires exactly one String-Parameter with the name of the exception variable."); + throw new TermLabelException("Label " + BlockContractValidityTermLabel.NAME + + " requires exactly one String-Parameter with the name of the exception variable."); } String val = ObjectUtil.toString(parameters.get(0)); if (StringUtil.isTrimmedEmpty(val)) { - throw new TermLabelException("Label " + BlockContractValidityTermLabel.NAME + - " requires exactly one String-Parameter with the name of the exception variable."); + throw new TermLabelException("Label " + BlockContractValidityTermLabel.NAME + + " requires exactly one String-Parameter with the name of the exception variable."); } - return new BlockContractValidityTermLabel((ProgramVariable) services.getNamespaces().programVariables().lookup(val)); + return new BlockContractValidityTermLabel( + (ProgramVariable) services.getNamespaces().programVariables().lookup(val)); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabel.java index a2898418fa5..7ea95b2badd 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.Collection; @@ -9,280 +12,289 @@ import de.uka.ilkd.key.logic.Sequent; /** - * Label attached to a predicates for instance in postconditions, loop invariants or precondition checks of applied operation contracts. + * Label attached to a predicates for instance in postconditions, loop invariants or precondition + * checks of applied operation contracts. */ public class FormulaTermLabel implements TermLabel { - /** - * The unique name of this label. - */ - public static final Name NAME = new Name("F"); + /** + * The unique name of this label. + */ + public static final Name NAME = new Name("F"); - /** - * The name used in {@link Services#getCounter(String)} to keep track - * of the already used IDs. - */ - public static final String PROOF_COUNTER_NAME = "F_LABEL_COUNTER"; + /** + * The name used in {@link Services#getCounter(String)} to keep track of the already used IDs. + */ + public static final String PROOF_COUNTER_NAME = "F_LABEL_COUNTER"; - /** - * The prefix of the name used in {@link Services#getCounter(String)} to - * keep track of the already used sub IDs. - */ - public static final String PROOF_COUNTER_SUB_PREFIX = "F_LABEL_SUB_COUNTER_"; - - /** - * Separator between multiple before IDs. - */ - public static final String BEFORE_ID_SEPARATOR = ";"; - - /** - * The unique major ID of this term label in the {@link Sequent}. - */ - private final int majorId; - - /** - * The per major ID unique minor ID of this term label in the {@link Sequent}. - */ - private final int minorId; - - /** - * The optional previous IDs of the label this one is derived from separated by {@value #BEFORE_ID_SEPARATOR}. - */ - private final String beforeIds; - - /** - * Constructor. - * @param id The unique ID of this term label in the {@link Sequent}. - * @throws TermLabelException Occurred Exception in case that the given ID is not valid. - */ - public FormulaTermLabel(String id) throws TermLabelException { - this(getMajorId(id), getMinorId(id)); - } - - /** - * Constructor. - * @param id The unique ID of this term label in the {@link Sequent}. - * @param beforeIds The optional previous IDs of the label this one is derived from separated by {@value #BEFORE_ID_SEPARATOR}. - * @throws TermLabelException Occurred Exception in case that the given IDs are not valid. - */ - public FormulaTermLabel(String id, String beforeIds) throws TermLabelException { - this(getMajorId(id), - getMinorId(id), - getValidBeforeIds(beforeIds)); // Ensure that before IDs are valid. - } - - /** - * Constructor. - * @param majorId The major part of the unique ID. - * @param minorId The minor part of the unique ID. - */ - public FormulaTermLabel(int majorId, int minorId) { - this(majorId, minorId, null); - } - - /** - * Constructor. - * @param majorId The major part of the unique ID. - * @param minorId The minor part of the unique ID. - * @param beforeIds The optional previous ID of the label this one is derived from. - */ - public FormulaTermLabel(int majorId, int minorId, Collection beforeIds) { - this.majorId = majorId; - this.minorId = minorId; - if (beforeIds != null && !beforeIds.isEmpty()) { - StringBuffer sb = new StringBuffer(); - boolean afterFirst = false; - for (String id : beforeIds) { - if (id != null) { - if (afterFirst) { - sb.append(BEFORE_ID_SEPARATOR); - } - else { - afterFirst = true; + /** + * The prefix of the name used in {@link Services#getCounter(String)} to keep track of the + * already used sub IDs. + */ + public static final String PROOF_COUNTER_SUB_PREFIX = "F_LABEL_SUB_COUNTER_"; + + /** + * Separator between multiple before IDs. + */ + public static final String BEFORE_ID_SEPARATOR = ";"; + + /** + * The unique major ID of this term label in the {@link Sequent}. + */ + private final int majorId; + + /** + * The per major ID unique minor ID of this term label in the {@link Sequent}. + */ + private final int minorId; + + /** + * The optional previous IDs of the label this one is derived from separated by + * {@value #BEFORE_ID_SEPARATOR}. + */ + private final String beforeIds; + + /** + * Constructor. + * + * @param id The unique ID of this term label in the {@link Sequent}. + * @throws TermLabelException Occurred Exception in case that the given ID is not valid. + */ + public FormulaTermLabel(String id) throws TermLabelException { + this(getMajorId(id), getMinorId(id)); + } + + /** + * Constructor. + * + * @param id The unique ID of this term label in the {@link Sequent}. + * @param beforeIds The optional previous IDs of the label this one is derived from separated by + * {@value #BEFORE_ID_SEPARATOR}. + * @throws TermLabelException Occurred Exception in case that the given IDs are not valid. + */ + public FormulaTermLabel(String id, String beforeIds) throws TermLabelException { + this(getMajorId(id), getMinorId(id), getValidBeforeIds(beforeIds)); // Ensure that before + // IDs are valid. + } + + /** + * Constructor. + * + * @param majorId The major part of the unique ID. + * @param minorId The minor part of the unique ID. + */ + public FormulaTermLabel(int majorId, int minorId) { + this(majorId, minorId, null); + } + + /** + * Constructor. + * + * @param majorId The major part of the unique ID. + * @param minorId The minor part of the unique ID. + * @param beforeIds The optional previous ID of the label this one is derived from. + */ + public FormulaTermLabel(int majorId, int minorId, Collection beforeIds) { + this.majorId = majorId; + this.minorId = minorId; + if (beforeIds != null && !beforeIds.isEmpty()) { + StringBuffer sb = new StringBuffer(); + boolean afterFirst = false; + for (String id : beforeIds) { + if (id != null) { + if (afterFirst) { + sb.append(BEFORE_ID_SEPARATOR); + } else { + afterFirst = true; + } + sb.append(id); } - sb.append(id); - } - } - this.beforeIds = sb.toString(); - } - else { - this.beforeIds = null; - } - } + } + this.beforeIds = sb.toString(); + } else { + this.beforeIds = null; + } + } + + /** + * {@inheritDoc} + */ + public boolean equals(Object o) { + return this == o; + } + + /** + * {@inheritDoc} + */ + public String toString() { + return NAME.toString() + "(" + getId() + (beforeIds != null ? ", " + beforeIds : "") + ")"; + } + + /** + * {@inheritDoc} + */ + @Override + public Object getChild(int i) { + switch (i) { + case 0: + return getId(); + case 1: + return beforeIds; + default: + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public int getChildCount() { + if (beforeIds != null) { + return 2; + } else { + return 1; + } + } + + /** + * Returns the unique ID of this label in the {@link Sequent}. + * + * @return The unique ID of this label in the {@link Sequent}. + */ + public String getId() { + return majorId + "." + minorId; + } + + /** + * Returns the major part of the unique ID. + * + * @return The major part of the unique ID. + */ + public int getMajorId() { + return majorId; + } - /** - * {@inheritDoc} - */ - public boolean equals(Object o) { - return this == o; - } + /** + * Returns the major part of the given ID. + * + * @param id The ID to extract its major part. + * @return The major part of the given ID. + * @throws TermLabelException Occurred Exception in case that the given ID is not valid. + */ + public static int getMajorId(String id) throws TermLabelException { + int index = id.indexOf("."); + if (index < 0) { + throw new TermLabelException( + "The ID '" + id + "' is not separated into major and minor ID by '.'."); + } + try { + return Integer.parseInt(id.substring(0, index)); + } catch (NumberFormatException e) { + throw new TermLabelException("The major ID of '" + id + "' is not a valid integer."); + } + } - /** - * {@inheritDoc} - */ - public String toString() { - return NAME.toString() + - "(" + - getId() + - (beforeIds != null ? ", " + beforeIds : "") + - ")"; - } + /** + * Returns the minor part of the unique ID. + * + * @return The minor part of the unique ID. + */ + public int getMinorId() { + return minorId; + } - /** - * {@inheritDoc} - */ - @Override - public Object getChild(int i) { - switch (i) { - case 0 : return getId(); - case 1 : return beforeIds; - default : return null; - } - } + /** + * Returns the minor part of the given ID. + * + * @param id The ID to extract its minor part. + * @return The minor part of the given ID. + * @throws TermLabelException Occurred Exception in case that the given ID is not valid. + */ + public static int getMinorId(String id) throws TermLabelException { + int index = id.indexOf("."); + if (index < 0) { + throw new TermLabelException( + "The ID '" + id + "' is not separated into major and minor ID by '.'."); + } + try { + return Integer.parseInt(id.substring(index + 1)); + } catch (NumberFormatException e) { + throw new TermLabelException("The minor ID of '" + id + "' is not a valid integer."); + } + } - /** - * {@inheritDoc} - */ - @Override - public int getChildCount() { - if (beforeIds != null) { - return 2; - } - else { - return 1; - } - } + /** + * Returns the optional previous IDs of the label this one is derived from. + * + * @return The optional previous IDs of the label this one is derived from. + */ + public String[] getBeforeIds() { + return getBeforeIds(beforeIds); + } - /** - * Returns the unique ID of this label in the {@link Sequent}. - * @return The unique ID of this label in the {@link Sequent}. - */ - public String getId() { - return majorId + "." + minorId; - } - - /** - * Returns the major part of the unique ID. - * @return The major part of the unique ID. - */ - public int getMajorId() { - return majorId; - } - - /** - * Returns the major part of the given ID. - * @param id The ID to extract its major part. - * @return The major part of the given ID. - * @throws TermLabelException Occurred Exception in case that the given ID is not valid. - */ - public static int getMajorId(String id) throws TermLabelException { - int index = id.indexOf("."); - if (index < 0) { - throw new TermLabelException("The ID '" + id + "' is not separated into major and minor ID by '.'."); - } - try { - return Integer.parseInt(id.substring(0, index)); - } - catch (NumberFormatException e) { - throw new TermLabelException("The major ID of '" + id + "' is not a valid integer."); - } - } - - /** - * Returns the minor part of the unique ID. - * @return The minor part of the unique ID. - */ - public int getMinorId() { - return minorId; - } - - /** - * Returns the minor part of the given ID. - * @param id The ID to extract its minor part. - * @return The minor part of the given ID. - * @throws TermLabelException Occurred Exception in case that the given ID is not valid. - */ - public static int getMinorId(String id) throws TermLabelException { - int index = id.indexOf("."); - if (index < 0) { - throw new TermLabelException("The ID '" + id + "' is not separated into major and minor ID by '.'."); - } - try { - return Integer.parseInt(id.substring(index + 1)); - } - catch (NumberFormatException e) { - throw new TermLabelException("The minor ID of '" + id + "' is not a valid integer."); - } - } + /** + * Returns the optional previous IDs of the label this one is derived from. + * + * @param beforeIds The {@link String} with the before IDs. + * @return The optional previous IDs of the label this one is derived from. + */ + private static String[] getBeforeIds(String beforeIds) { + return beforeIds != null ? beforeIds.split(BEFORE_ID_SEPARATOR) : new String[0]; + } - /** - * Returns the optional previous IDs of the label this one is derived from. - * @return The optional previous IDs of the label this one is derived from. - */ - public String[] getBeforeIds() { - return getBeforeIds(beforeIds); - } - - /** - * Returns the optional previous IDs of the label this one is derived from. - * @param beforeIds The {@link String} with the before IDs. - * @return The optional previous IDs of the label this one is derived from. - */ - private static String[] getBeforeIds(String beforeIds) { - return beforeIds != null ? - beforeIds.split(BEFORE_ID_SEPARATOR) : - new String[0]; - } - - /** - * Returns the optional previous IDs if they are all valid. - * @param beforeIds The {@link String} with the before IDs to analyze. - * @return The valid before IDs. - * @throws TermLabelException Occurred Exception in case that the given IDs are not valid. - */ - public static List getValidBeforeIds(String beforeIds) throws TermLabelException { - if (beforeIds == null || beforeIds.isEmpty()) { - throw new TermLabelException("No before IDs defined."); - } - List result = new LinkedList(); - String[] candidates = getBeforeIds(beforeIds); - for (String id : candidates) { - if (!id.isEmpty()) { - getMinorId(id); // Validate minor ID. - getMajorId(id); // Validate major ID. - result.add(id); - } - else { - throw new TermLabelException("Empty entry in beforeIds '" + beforeIds + "' found."); - } - } - return result; - } + /** + * Returns the optional previous IDs if they are all valid. + * + * @param beforeIds The {@link String} with the before IDs to analyze. + * @return The valid before IDs. + * @throws TermLabelException Occurred Exception in case that the given IDs are not valid. + */ + public static List getValidBeforeIds(String beforeIds) throws TermLabelException { + if (beforeIds == null || beforeIds.isEmpty()) { + throw new TermLabelException("No before IDs defined."); + } + List result = new LinkedList(); + String[] candidates = getBeforeIds(beforeIds); + for (String id : candidates) { + if (!id.isEmpty()) { + getMinorId(id); // Validate minor ID. + getMajorId(id); // Validate major ID. + result.add(id); + } else { + throw new TermLabelException("Empty entry in beforeIds '" + beforeIds + "' found."); + } + } + return result; + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return NAME; - } + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return NAME; + } - /** - * Creates a new label sub ID. - * @param services The {@link Services} to use. - * @param label The parent {@link FormulaTermLabel} which provides the major ID. - * @return The new label sub ID. - */ - public static int newLabelSubID(Services services, FormulaTermLabel label) { - return newLabelSubID(services, label.getMajorId()); - } + /** + * Creates a new label sub ID. + * + * @param services The {@link Services} to use. + * @param label The parent {@link FormulaTermLabel} which provides the major ID. + * @return The new label sub ID. + */ + public static int newLabelSubID(Services services, FormulaTermLabel label) { + return newLabelSubID(services, label.getMajorId()); + } - /** - * Creates a new label sub ID. - * @param services The {@link Services} to use. - * @param labelId The parent {@link FormulaTermLabel} which provides the major ID. - * @return The new label sub ID. - */ - public static int newLabelSubID(Services services, int labelId) { - return services.getCounter(FormulaTermLabel.PROOF_COUNTER_SUB_PREFIX + labelId).getCountPlusPlus(); - } -} \ No newline at end of file + /** + * Creates a new label sub ID. + * + * @param services The {@link Services} to use. + * @param labelId The parent {@link FormulaTermLabel} which provides the major ID. + * @return The new label sub ID. + */ + public static int newLabelSubID(Services services, int labelId) { + return services.getCounter(FormulaTermLabel.PROOF_COUNTER_SUB_PREFIX + labelId) + .getCountPlusPlus(); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabelFactory.java index b4c8e91d657..496cab2abd3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/FormulaTermLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.List; @@ -8,22 +11,22 @@ * A factory for creating {@link FormulaTermLabel} objects. */ public class FormulaTermLabelFactory implements TermLabelFactory { - /** - * {@inheritDoc} - * - *

    - * This method accepts single arguments which can be parsed as an integer. - */ - @Override - public FormulaTermLabel parseInstance(List parameters, TermServices services) throws TermLabelException { - if (parameters != null && parameters.size() == 1) { - return new FormulaTermLabel(parameters.get(0)); - } - else if (parameters != null && parameters.size() == 2) { - return new FormulaTermLabel(parameters.get(0), parameters.get(1)); - } - else { - throw new TermLabelException("Label " + FormulaTermLabel.NAME + " requires the unique ID as first parameter and an optional by semicolon separated list of parent IDs as second parameter."); - } - } -} \ No newline at end of file + /** + * {@inheritDoc} + * + *

    + * This method accepts single arguments which can be parsed as an integer. + */ + @Override + public FormulaTermLabel parseInstance(List parameters, TermServices services) + throws TermLabelException { + if (parameters != null && parameters.size() == 1) { + return new FormulaTermLabel(parameters.get(0)); + } else if (parameters != null && parameters.size() == 2) { + return new FormulaTermLabel(parameters.get(0), parameters.get(1)); + } else { + throw new TermLabelException("Label " + FormulaTermLabel.NAME + + " requires the unique ID as first parameter and an optional by semicolon separated list of parent IDs as second parameter."); + } + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabel.java index 23eeb09bc45..961a8ba7f47 100755 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.io.File; @@ -36,19 +39,22 @@ import recoder.service.KeYCrossReferenceSourceInfo; /** - *

    An {@link OriginTermLabel} saves a term's origin in the JML specification - * ({@link #getOrigin()}) as well as the origins of all of its subterms and former - * subterms ({@link #getSubtermOrigins()}).

    + *

    + * An {@link OriginTermLabel} saves a term's origin in the JML specification ({@link #getOrigin()}) + * as well as the origins of all of its subterms and former subterms ({@link #getSubtermOrigins()}). + *

    * - *

    For this to work correctly, you must call - * {@link #collectSubtermOrigins(Term, TermBuilder)} for every top-level formula in your - * original proof obligation.

    + *

    + * For this to work correctly, you must call {@link #collectSubtermOrigins(Term, TermBuilder)} for + * every top-level formula in your original proof obligation. + *

    * - *

    Before doing this, you can call {@link TermBuilder#addLabelToAllSubs(Term, TermLabel)} - * for every term you have added to the original contract in your PO to add an - * {@link OriginTermLabel} - * of your choosing. Terms for which you do not do this get a label of the form - * {@code new OriginTermLabel(SpecType.NONE, null, -1)}.

    + *

    + * Before doing this, you can call {@link TermBuilder#addLabelToAllSubs(Term, TermLabel)} for every + * term you have added to the original contract in your PO to add an {@link OriginTermLabel} of your + * choosing. Terms for which you do not do this get a label of the form + * {@code new OriginTermLabel(SpecType.NONE, null, -1)}. + *

    * * @author lanzinger */ @@ -67,8 +73,8 @@ public class OriginTermLabel implements TermLabel { /** - * Find a term's origin. - * If the term has no origin, iterate through its parent terms until we find one with an origin. + * Find a term's origin. If the term has no origin, iterate through its parent terms until we + * find one with an origin. * * @param pis the position of the term whose origin to find. * @return the term's origin, or the origin of one of its parents. @@ -82,8 +88,8 @@ public static Origin getOrigin(PosInSequent pis) { } /** - * Find a term's origin. - * If the term has no origin, iterate through its parent terms until we find one with an origin. + * Find a term's origin. If the term has no origin, iterate through its parent terms until we + * find one with an origin. * * @param pio the position of the term whose origin to find. * @return the term's origin, or the origin of one of its parents. @@ -95,8 +101,7 @@ public static Origin getOrigin(PosInOccurrence pio) { Term term = pio.subTerm(); - OriginTermLabel originLabel = - (OriginTermLabel) term.getLabel(OriginTermLabel.NAME); + OriginTermLabel originLabel = (OriginTermLabel) term.getLabel(OriginTermLabel.NAME); // If the term has no origin label, // iterate over its parent terms until we find one with an origin label, @@ -105,8 +110,7 @@ public static Origin getOrigin(PosInOccurrence pio) { pio = pio.up(); term = pio.subTerm(); - originLabel = - (OriginTermLabel) term.getLabel(OriginTermLabel.NAME); + originLabel = (OriginTermLabel) term.getLabel(OriginTermLabel.NAME); } if (originLabel != null && originLabel.getOrigin().specType != SpecType.NONE) { @@ -118,12 +122,14 @@ public static Origin getOrigin(PosInOccurrence pio) { /** * The term's origin. + * * @see #getOrigin() */ private Origin origin; /** * The origins of the term's sub-terms and former sub-terms. + * * @see #getSubtermOrigins() */ private final Set subtermOrigins; @@ -149,7 +155,7 @@ public OriginTermLabel(Origin origin, Set subtermOrigins) { this.subtermOrigins.addAll(subtermOrigins); this.subtermOrigins.removeIf(o -> o.specType == SpecType.NONE); // this.subtermOrigins = this.subtermOrigins.stream() - // .filter(o -> o.specType != SpecType.NONE).collect(Collectors.toSet()); + // .filter(o -> o.specType != SpecType.NONE).collect(Collectors.toSet()); } /** @@ -162,7 +168,7 @@ public OriginTermLabel(Set subtermOrigins) { this.subtermOrigins = new LinkedHashSet<>(subtermOrigins); this.subtermOrigins.removeIf(o -> o.specType == SpecType.NONE); // this.subtermOrigins = this.subtermOrigins.stream() - // .filter(o -> o.specType != SpecType.NONE).collect(Collectors.toSet()); + // .filter(o -> o.specType != SpecType.NONE).collect(Collectors.toSet()); } @Override @@ -185,10 +191,14 @@ public boolean equals(Object obj) { } /** - *

    Determines whether an {@code OriginTermLabel} can be added to the specified term.

    + *

    + * Determines whether an {@code OriginTermLabel} can be added to the specified term. + *

    * - *

    E.g., no labels should be added to terms whose operator is a heap variable as this leads - * to various problems during proof search.

    + *

    + * E.g., no labels should be added to terms whose operator is a heap variable as this leads to + * various problems during proof search. + *

    * * @param term a term * @param services services. @@ -199,19 +209,23 @@ public static boolean canAddLabel(Term term, Services services) { } /** - *

    Determines whether an {@code OriginTermLabel} can be added to a term with the specified - * operator.

    + *

    + * Determines whether an {@code OriginTermLabel} can be added to a term with the specified + * operator. + *

    * - *

    E.g., no labels should be added to terms whose operator is a heap variable as this leads - * to various problems during proof search.

    + *

    + * E.g., no labels should be added to terms whose operator is a heap variable as this leads to + * various problems during proof search. + *

    * * @param op the specified operator. * @param services services. - * @return {@code true} iff an {@code OriginTermLabel} can be added to a term - * with the specified operator. + * @return {@code true} iff an {@code OriginTermLabel} can be added to a term with the specified + * operator. */ public static boolean canAddLabel(Operator op, Services services) { - //TODO: Instead of not adding origin labels to certain terms, we should investigate why + // TODO: Instead of not adding origin labels to certain terms, we should investigate why // adding labels to these kinds of terms breaks the prover and fix these issues. final TypeConverter tc = services.getTypeConverter(); @@ -231,9 +245,8 @@ public static boolean canAddLabel(Operator op, Services services) { return false; } } else { - return !(op instanceof Function) - || (op.getClass().equals(Function.class) - && ((Function) op).sort().extendsTrans(Sort.FORMULA)); + return !(op instanceof Function) || (op.getClass().equals(Function.class) + && ((Function) op).sort().extendsTrans(Sort.FORMULA)); } } @@ -251,8 +264,7 @@ public static SequentChangeInfo removeOriginLabels(Sequent seq, Services service SequentFormula oldFormula = seq.getFormulabyNr(i); SequentFormula newFormula = new SequentFormula( OriginTermLabel.removeOriginLabels(oldFormula.formula(), services)); - SequentChangeInfo change = seq.changeFormula( - newFormula, + SequentChangeInfo change = seq.changeFormula(newFormula, PosInOccurrence.findInSequent(seq, i, PosInTerm.getTopLevel())); if (changes == null) { @@ -291,15 +303,13 @@ public static Term removeOriginLabels(Term term, Services services) { newSubs[i] = removeOriginLabels(oldSubs.get(i), services); } - return tf.createTerm(term.op(), - newSubs, - term.boundVars(), - term.javaBlock(), - new ImmutableArray<>(labels)); + return tf.createTerm(term.op(), newSubs, term.boundVars(), term.javaBlock(), + new ImmutableArray<>(labels)); } /** * Compute the common origin from all origins in the passed origins set. + * * @param origins the passed origins set * @return the computed common origin */ @@ -342,6 +352,7 @@ public static Origin computeCommonFileOrigin(final Set origins) { /** * Compute the common origin from all origins in the passed origins set. + * * @param origins the passed origins set * @return the computed common origin */ @@ -379,6 +390,7 @@ public static Origin computeCommonNodeOrigin(final Set origins) { /** * Compute the common origin from all origins in the passed origins set. + * * @param origins the passed origins set * @return the computed common origin */ @@ -417,9 +429,8 @@ public static Origin computeCommonOrigin(final Set origins) { } /** - * This method transforms a term in such a way that - * every {@link OriginTermLabel} contains all of the correct - * {@link #getSubtermOrigins()}. + * This method transforms a term in such a way that every {@link OriginTermLabel} contains all + * of the correct {@link #getSubtermOrigins()}. * * @param term the term to transform. * @param services services. @@ -434,11 +445,8 @@ public static Term collectSubtermOrigins(Term term, Services services) { final ImmutableArray labels = computeOriginLabelsFromSubTermOrigins(term, newSubs.origins); - return services.getTermFactory().createTerm(term.op(), - newSubs.terms, - term.boundVars(), - term.javaBlock(), - labels); + return services.getTermFactory().createTerm(term.op(), newSubs.terms, term.boundVars(), + term.javaBlock(), labels); } @Override @@ -481,10 +489,14 @@ public Origin getOrigin() { } /** - *

    Returns the origins of the term's sub-terms and former sub-terms.

    + *

    + * Returns the origins of the term's sub-terms and former sub-terms. + *

    * - *

    Note that you need to have called {@link #collectSubtermOrigins(Term, TermBuilder)} - * for this method to work correctly.

    + *

    + * Note that you need to have called {@link #collectSubtermOrigins(Term, TermBuilder)} for this + * method to work correctly. + *

    * * @return the origins of the term's sub-terms and former sub-terms. * @see OriginTermLabelRefactoring @@ -494,9 +506,8 @@ public Set getSubtermOrigins() { } - private static ImmutableArray - computeOriginLabelsFromSubTermOrigins(final Term term, - final Set origins) { + private static ImmutableArray computeOriginLabelsFromSubTermOrigins(final Term term, + final Set origins) { List labels = term.getLabels().toList(); final OriginTermLabel oldLabel = (OriginTermLabel) term.getLabel(NAME); @@ -504,9 +515,7 @@ public Set getSubtermOrigins() { labels.remove(oldLabel); if ((!origins.isEmpty() || oldLabel.getOrigin().specType != SpecType.NONE)) { - labels.add(new OriginTermLabel( - oldLabel.getOrigin(), - origins)); + labels.add(new OriginTermLabel(oldLabel.getOrigin(), origins)); } } else if (!origins.isEmpty()) { final OriginTermLabel newLabel = @@ -519,13 +528,13 @@ public Set getSubtermOrigins() { /** * @param subs the sub-terms to be searched - * @param services a services object used for getting type information - * and creating the new sub-term - * @return origin information about the searched sub-terms stored in a - * {@link SubTermOriginData} object. + * @param services a services object used for getting type information and creating the new + * sub-term + * @return origin information about the searched sub-terms stored in a {@link SubTermOriginData} + * object. */ private static SubTermOriginData getSubTermOriginData(final ImmutableArray subs, - final Services services) { + final Services services) { Term[] newSubs = new Term[subs.size()]; Set origins = new LinkedHashSet<>(); @@ -542,28 +551,27 @@ private static SubTermOriginData getSubTermOriginData(final ImmutableArray } /** - * This class stores an array of sub-terms and a set of all their origins. - * It is used when recursively collecting all origins from a term's sub-terms - * for setting its respective origin labels. The information of the sub-terms - * are used for propagating their origin label information upwards to their - * enclosing term. + * This class stores an array of sub-terms and a set of all their origins. It is used when + * recursively collecting all origins from a term's sub-terms for setting its respective origin + * labels. The information of the sub-terms are used for propagating their origin label + * information upwards to their enclosing term. * * @author Michael Kirsten * */ private static class SubTermOriginData { - /** All collected sub-terms */ + /** All collected sub-terms */ public final Term[] terms; /** All collected origins */ public final Set origins; /** * This method constructs an object of type {@link SubTermOriginData}. + * * @param subterms the collected sub-terms * @param subtermOrigins the origin information collected from these sub-terms */ - public SubTermOriginData(Term[] subterms, - Set subtermOrigins) { + public SubTermOriginData(Term[] subterms, Set subtermOrigins) { this.terms = subterms; this.origins = subtermOrigins; } @@ -599,8 +607,8 @@ public int compareTo(Origin other) { @Override public boolean equals(Object obj) { - return obj != null - && obj.getClass().equals(getClass()) && ((Origin) obj).specType == specType; + return obj != null && obj.getClass().equals(getClass()) + && ((Origin) obj).specType == specType; } @Override @@ -875,8 +883,8 @@ public static enum SpecType { USER_INTERACTION("User_Interaction"), /** - * None. Used when no other spec type fits and for terms whose origin was - * not set upon their creation. + * None. Used when no other spec type fits and for terms whose origin was not set upon their + * creation. */ NONE(""); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabelFactory.java index bf9bd6f8220..8e3f4a2b27f 100755 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/OriginTermLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.LinkedHashSet; @@ -23,10 +26,8 @@ public class OriginTermLabelFactory implements TermLabelFactory public OriginTermLabel parseInstance(List arguments, TermServices services) throws TermLabelException { if (arguments.size() != OriginTermLabel.CHILD_COUNT) { - throw new TermLabelException( - "OriginTermLabel has " - + arguments.size() - + " children, but should have " + OriginTermLabel.CHILD_COUNT); + throw new TermLabelException("OriginTermLabel has " + arguments.size() + + " children, but should have " + OriginTermLabel.CHILD_COUNT); } Origin origin = parseOrigin(arguments.get(0)); @@ -114,14 +115,11 @@ private Origin parseOrigin(String str) throws TermLabelException { } } } catch (NoSuchElementException | IllegalArgumentException e) { - throw new TermLabelException( - "Malformed origin string: \"" - + str + "\"\n" + throw new TermLabelException("Malformed origin string: \"" + str + "\"\n" + "(Well-formed origins have one of the following formats: \"" + "spec_type @ file @ line \")\n" + "spec_type @ node ()\")\n" - + "spec_type (implicit)\")\n" - ); + + "spec_type (implicit)\")\n"); } } @@ -148,34 +146,30 @@ private SpecType parseSpecType(String str) { * @return the token. * @throws TermLabelException if {@code !expected.equals(actual)} */ - private String matchId(String actual, String line, String expected) - throws TermLabelException { + private String matchId(String actual, String line, String expected) throws TermLabelException { if (!expected.equals(actual)) { - throw new TermLabelException("Unexpected token \"" + actual + "\", " - + "expected: \"" + expected + "\"" - + "\nin line \"" + line + "\""); + throw new TermLabelException("Unexpected token \"" + actual + "\", " + "expected: \"" + + expected + "\"" + "\nin line \"" + line + "\""); } return expected; } /** - * Throws an exception if the token is not a single character, or it does not occur - * in {@code expected.} + * Throws an exception if the token is not a single character, or it does not occur in + * {@code expected.} * * @param actual a token. * @param line the current line. * @param expected a string containing the expected characters. * @return the token as a single character. - * @throws TermLabelException if the token is not a single character, or it does not occur - * in {@code expected.} + * @throws TermLabelException if the token is not a single character, or it does not occur in + * {@code expected.} */ - private char matchChar(String actual, String line, String expected) - throws TermLabelException { + private char matchChar(String actual, String line, String expected) throws TermLabelException { if (actual.length() != 1 || !expected.contains(actual)) { throw new TermLabelException("Unexpected token \"" + actual + "\", " - + "expected any of: " + expected - + "\nin line \"" + line + "\""); + + "expected any of: " + expected + "\nin line \"" + line + "\""); } return actual.charAt(0); @@ -191,8 +185,7 @@ private char matchChar(String actual, String line, String expected) private void matchEnd(StringTokenizer tokenizer, String line) throws TermLabelException { if (tokenizer.hasMoreTokens()) { throw new TermLabelException("Unexpected token \'" + tokenizer.nextToken() + "\', " - + "expected: \'\"\'" - + "\nin line \"" + line + "\""); + + "expected: \'\"\'" + "\nin line \"" + line + "\""); } } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/ParameterlessTermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/ParameterlessTermLabel.java index 27f61909552..a4dbddff088 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/ParameterlessTermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/ParameterlessTermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import de.uka.ilkd.key.logic.Name; @@ -7,120 +10,116 @@ /** * The Class {@link ParameterlessTermLabel} can be used to define labels without parameters. * - * You can use a {@link SingletonLabelFactory} to create a factory for an - * instance of this class. + * You can use a {@link SingletonLabelFactory} to create a factory for an instance of this class. * * @see SingletonLabelFactory * * @author mattias ulbrich */ public final class ParameterlessTermLabel implements TermLabel { - /** - * Name of {@link #ANON_HEAP_LABEL}. - */ - public static final Name ANON_HEAP_LABEL_NAME = new Name("anonHeapFunction"); - - /** - * Label attached to anonymisation heap function symbols as for instance - * introduce in UseOperationContractRule or WhileInvariantRule. - */ - public static final TermLabel ANON_HEAP_LABEL = - new ParameterlessTermLabel(ANON_HEAP_LABEL_NAME); - - /** - * Name of {@link #SELECT_SKOLEM_LABEL}. - */ - public static final Name SELECT_SKOLEM_LABEL_NAME = new Name("selectSK"); - - /** - * Label attached to skolem constants introduced by the rule pullOutSelect. - */ - public static final TermLabel SELECT_SKOLEM_LABEL = - new ParameterlessTermLabel(SELECT_SKOLEM_LABEL_NAME); - - /** - * Name of {@link #IMPLICIT_SPECIFICATION_LABEL}. - */ - public static final Name IMPLICIT_SPECIFICATION_LABEL_NAME = new Name("impl"); - - /** - * Label attached to a term which is specified implicitly (by the JML specification). - */ - public static final TermLabel IMPLICIT_SPECIFICATION_LABEL = - new ParameterlessTermLabel(IMPLICIT_SPECIFICATION_LABEL_NAME); - - /** - * Name of {@link #SHORTCUT_EVALUATION_LABEL}. - */ - public static final Name SHORTCUT_EVALUATION_LABEL_NAME = new Name("SC"); - - /** - * Label attached to a term with the logical operator '{@literal ||}' or - * '{@literal &&}' to distinguish from '{@literal |}' or '{@literal &}' - * respectively. - */ - public static final TermLabel SHORTCUT_EVALUATION_LABEL = - new ParameterlessTermLabel(SHORTCUT_EVALUATION_LABEL_NAME); - - /** - * Name of {@link #UNDEFINED_VALUE_LABEL}. - */ - public static final Name UNDEFINED_VALUE_LABEL_NAME = new Name("undef"); - - /** - * Label attached to a term which denotes an undefined value. At present it is only - * used for the else-part of the {@link de.uka.ilkd.key.logic.op.IfExThenElse} operator, - * when it is used for the translation of JML's \min and \max operator. It is necessary - * to evaluate this constant expression to be not well-defined. - */ - public static final TermLabel UNDEFINED_VALUE_LABEL = - new ParameterlessTermLabel(UNDEFINED_VALUE_LABEL_NAME); - - /** - * Name of {@link #SELF_COMPOSITION_LABEL}. - */ - public static final Name SELF_COMPOSITION_LABEL_NAME = new Name("selfComposedExecution"); - - /** - * Label attached to the post condition. - */ - public static final TermLabel SELF_COMPOSITION_LABEL = - new ParameterlessTermLabel(SELF_COMPOSITION_LABEL_NAME); - - /** - * Name of {@link #POST_CONDITION_LABEL}. - */ - public static final Name POST_CONDITION_LABEL_NAME = new Name("postCondition"); - - /** - * Label attached to the post-condition. - */ - public static final TermLabel POST_CONDITION_LABEL = - new ParameterlessTermLabel(POST_CONDITION_LABEL_NAME); - - /** - * Name of {@link #LOOP_SCOPE_INDEX_LABEL}. - */ - public static final Name LOOP_SCOPE_INDEX_LABEL_NAME = new Name("loopScopeIndex"); - - /** - * Label attached to loop scope index variables in {@link LoopScopeInvariantRule}. - */ - public static final TermLabel LOOP_SCOPE_INDEX_LABEL = - new ParameterlessTermLabel(LOOP_SCOPE_INDEX_LABEL_NAME); - - /** - * The unique name of this label. - * This is the basename and does not include the parameters + /** + * Name of {@link #ANON_HEAP_LABEL}. + */ + public static final Name ANON_HEAP_LABEL_NAME = new Name("anonHeapFunction"); + + /** + * Label attached to anonymisation heap function symbols as for instance introduce in + * UseOperationContractRule or WhileInvariantRule. + */ + public static final TermLabel ANON_HEAP_LABEL = + new ParameterlessTermLabel(ANON_HEAP_LABEL_NAME); + + /** + * Name of {@link #SELECT_SKOLEM_LABEL}. + */ + public static final Name SELECT_SKOLEM_LABEL_NAME = new Name("selectSK"); + + /** + * Label attached to skolem constants introduced by the rule pullOutSelect. + */ + public static final TermLabel SELECT_SKOLEM_LABEL = + new ParameterlessTermLabel(SELECT_SKOLEM_LABEL_NAME); + + /** + * Name of {@link #IMPLICIT_SPECIFICATION_LABEL}. + */ + public static final Name IMPLICIT_SPECIFICATION_LABEL_NAME = new Name("impl"); + + /** + * Label attached to a term which is specified implicitly (by the JML specification). + */ + public static final TermLabel IMPLICIT_SPECIFICATION_LABEL = + new ParameterlessTermLabel(IMPLICIT_SPECIFICATION_LABEL_NAME); + + /** + * Name of {@link #SHORTCUT_EVALUATION_LABEL}. + */ + public static final Name SHORTCUT_EVALUATION_LABEL_NAME = new Name("SC"); + + /** + * Label attached to a term with the logical operator '{@literal ||}' or '{@literal &&}' to + * distinguish from '{@literal |}' or '{@literal &}' respectively. + */ + public static final TermLabel SHORTCUT_EVALUATION_LABEL = + new ParameterlessTermLabel(SHORTCUT_EVALUATION_LABEL_NAME); + + /** + * Name of {@link #UNDEFINED_VALUE_LABEL}. + */ + public static final Name UNDEFINED_VALUE_LABEL_NAME = new Name("undef"); + + /** + * Label attached to a term which denotes an undefined value. At present it is only used for the + * else-part of the {@link de.uka.ilkd.key.logic.op.IfExThenElse} operator, when it is used for + * the translation of JML's \min and \max operator. It is necessary to evaluate this constant + * expression to be not well-defined. + */ + public static final TermLabel UNDEFINED_VALUE_LABEL = + new ParameterlessTermLabel(UNDEFINED_VALUE_LABEL_NAME); + + /** + * Name of {@link #SELF_COMPOSITION_LABEL}. + */ + public static final Name SELF_COMPOSITION_LABEL_NAME = new Name("selfComposedExecution"); + + /** + * Label attached to the post condition. + */ + public static final TermLabel SELF_COMPOSITION_LABEL = + new ParameterlessTermLabel(SELF_COMPOSITION_LABEL_NAME); + + /** + * Name of {@link #POST_CONDITION_LABEL}. + */ + public static final Name POST_CONDITION_LABEL_NAME = new Name("postCondition"); + + /** + * Label attached to the post-condition. + */ + public static final TermLabel POST_CONDITION_LABEL = + new ParameterlessTermLabel(POST_CONDITION_LABEL_NAME); + + /** + * Name of {@link #LOOP_SCOPE_INDEX_LABEL}. + */ + public static final Name LOOP_SCOPE_INDEX_LABEL_NAME = new Name("loopScopeIndex"); + + /** + * Label attached to loop scope index variables in {@link LoopScopeInvariantRule}. + */ + public static final TermLabel LOOP_SCOPE_INDEX_LABEL = + new ParameterlessTermLabel(LOOP_SCOPE_INDEX_LABEL_NAME); + + /** + * The unique name of this label. This is the basename and does not include the parameters */ private final Name name; /** * Instantiates a new simple term label. * - * @param name - * the name, not null - * The fixed associated instantiator, may be null. + * @param name the name, not null The fixed associated instantiator, may be + * null. */ public ParameterlessTermLabel(Name name) { assert name != null; @@ -163,17 +162,16 @@ public String toString() { /** * {@inheritDoc} * - *

    This object is equal to another {@link ParameterlessTermLabel} iff they - * bear the same name. + *

    + * This object is equal to another {@link ParameterlessTermLabel} iff they bear the same name. */ @Override public boolean equals(Object obj) { if (obj instanceof ParameterlessTermLabel) { ParameterlessTermLabel other = (ParameterlessTermLabel) obj; return name.equals(other.name); - } - else { - return false; + } else { + return false; } } @@ -184,4 +182,4 @@ public boolean equals(Object obj) { public int hashCode() { return name.hashCode(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SingletonLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SingletonLabelFactory.java index b8e17deee3e..d26e846abe1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SingletonLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SingletonLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.List; @@ -8,11 +11,10 @@ * A factory for creating singleton {@link TermLabel}. * *

    - * The resulting factory does not accept arguments for the builder methods and - * always returns a fixed term level value. + * The resulting factory does not accept arguments for the builder methods and always returns a + * fixed term level value. * - * @param - * the type of the wrapped term label can be narrowed. + * @param the type of the wrapped term label can be narrowed. */ public final class SingletonLabelFactory implements TermLabelFactory { @@ -24,8 +26,7 @@ public final class SingletonLabelFactory implements TermLab /** * Instantiates a new singleton label factory for a label. * - * @param singletonLabel - * the label to be wrapped, not null. + * @param singletonLabel the label to be wrapped, not null. */ public SingletonLabelFactory(T singletonLabel) { assert singletonLabel != null; @@ -35,14 +36,17 @@ public SingletonLabelFactory(T singletonLabel) { /** * {@inheritDoc} * - *

    This implementation does not accept arguments and returns the stored label + *

    + * This implementation does not accept arguments and returns the stored label */ @Override - public T parseInstance(List arguments, TermServices services) throws TermLabelException { + public T parseInstance(List arguments, TermServices services) + throws TermLabelException { if (arguments.isEmpty()) { return singletonLabel; } else { - throw new TermLabelException("Label " + singletonLabel.name() + " does not expect arguments."); + throw new TermLabelException( + "Label " + singletonLabel.name() + " does not expect arguments."); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabel.java index fdc23585ed8..f1c7402c264 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import de.uka.ilkd.key.java.Services; @@ -8,76 +11,79 @@ * Label attached to a symbolic execution thread. */ public class SymbolicExecutionTermLabel implements TermLabel { - /** - * The unique name of this label. - */ - public static final Name NAME = new Name("SE"); + /** + * The unique name of this label. + */ + public static final Name NAME = new Name("SE"); - /** - * The name used in {@link Services#getCounter(String)} to keep track - * of the already used IDs. - */ - public static final String PROOF_COUNTER_NAME = "SE_LABEL_COUNTER"; - - /** - * The unique ID of this term label in the {@link Sequent}. - */ - private final int id; + /** + * The name used in {@link Services#getCounter(String)} to keep track of the already used IDs. + */ + public static final String PROOF_COUNTER_NAME = "SE_LABEL_COUNTER"; - /** - * Constructor. - * @param id The unique ID of this term label in the {@link Sequent}. - */ - public SymbolicExecutionTermLabel(int id) { - this.id = id; - } + /** + * The unique ID of this term label in the {@link Sequent}. + */ + private final int id; - /** - * {@inheritDoc} - */ - public boolean equals(Object o) { - return this == o; - } + /** + * Constructor. + * + * @param id The unique ID of this term label in the {@link Sequent}. + */ + public SymbolicExecutionTermLabel(int id) { + this.id = id; + } - /** - * {@inheritDoc} - */ - public String toString() { - return NAME.toString() + "(" + getId() + ")"; - } + /** + * {@inheritDoc} + */ + public boolean equals(Object o) { + return this == o; + } - /** - * {@inheritDoc} - */ - @Override - public Object getChild(int i) { - switch (i) { - case 0 : return getId(); - default : return null; - } - } + /** + * {@inheritDoc} + */ + public String toString() { + return NAME.toString() + "(" + getId() + ")"; + } - /** - * {@inheritDoc} - */ - @Override - public int getChildCount() { - return 1; - } + /** + * {@inheritDoc} + */ + @Override + public Object getChild(int i) { + switch (i) { + case 0: + return getId(); + default: + return null; + } + } - /** - * Returns the unique ID of this label in the {@link Sequent}. - * @return The unique ID of this label in the {@link Sequent}. - */ - public int getId() { - return id; - } + /** + * {@inheritDoc} + */ + @Override + public int getChildCount() { + return 1; + } - /** - * {@inheritDoc} - */ - @Override - public Name name() { - return NAME; - } -} \ No newline at end of file + /** + * Returns the unique ID of this label in the {@link Sequent}. + * + * @return The unique ID of this label in the {@link Sequent}. + */ + public int getId() { + return id; + } + + /** + * {@inheritDoc} + */ + @Override + public Name name() { + return NAME; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabelFactory.java index 973ef0e0f72..88c2bd5e51f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/SymbolicExecutionTermLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.List; @@ -7,7 +10,8 @@ /** * A factory for creating {@link SymbolicExecutionTermLabel} objects. */ -public class SymbolicExecutionTermLabelFactory implements TermLabelFactory { +public class SymbolicExecutionTermLabelFactory + implements TermLabelFactory { /** * {@inheritDoc} * @@ -15,19 +19,20 @@ public class SymbolicExecutionTermLabelFactory implements TermLabelFactory parameters, TermServices services) throws TermLabelException { + public SymbolicExecutionTermLabel parseInstance(List parameters, TermServices services) + throws TermLabelException { if (parameters == null || parameters.size() != 1) { - throw new TermLabelException("Label " + SymbolicExecutionTermLabel.NAME + - " requires exactly one Integer-Parameter with its ID."); + throw new TermLabelException("Label " + SymbolicExecutionTermLabel.NAME + + " requires exactly one Integer-Parameter with its ID."); } Integer val; try { val = Integer.valueOf(parameters.get(0)); } catch (NumberFormatException e) { - throw new TermLabelException("Label " + SymbolicExecutionTermLabel.NAME + - " requires exactly one Integer-Parameter with its ID.", e); + throw new TermLabelException("Label " + SymbolicExecutionTermLabel.NAME + + " requires exactly one Integer-Parameter with its ID.", e); } return new SymbolicExecutionTermLabel(val); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabel.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabel.java index 49df41a33c4..ba0cc8d0553 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabel.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabel.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.stream.Collectors; @@ -26,120 +29,115 @@ /** *

    - * The interface for term labels. Term labels are annotations that can be attached - * to {@link Term}s and carry additional information. - * They must not be soundness relevant. But they may be used in strategies - * to compute the order in which rules are applied. + * The interface for term labels. Term labels are annotations that can be attached to {@link Term}s + * and carry additional information. They must not be soundness relevant. But they may be + * used in strategies to compute the order in which rules are applied. *

    *

    - * {@link Term}s with or without term labels are still unmodifiable. - * It is recommended to implement {@link TermLabel}s including their parameters also unmodifiable. - * For new {@link TermLabel}s without parameters class {@link ParameterlessTermLabel} can be used. + * {@link Term}s with or without term labels are still unmodifiable. It is recommended to implement + * {@link TermLabel}s including their parameters also unmodifiable. For new {@link TermLabel}s + * without parameters class {@link ParameterlessTermLabel} can be used. *

    *

    * A term label can have parameters accessible via {@link #getChild(int)} and - * {@link #getChildCount()}. Such parameters can be any {@link Object}. - * But keep in mind that it is required to parse {@link String}s into {@link Term}s, - * e.g. if it is used in a Taclet definition or if a cut rule is applied. - * For convenience parameters are always printed as {@link String}s - * and have to be parsed individually into the required {@link Object} instances - * via a {@link TermLabelFactory}. + * {@link #getChildCount()}. Such parameters can be any {@link Object}. But keep in mind that it is + * required to parse {@link String}s into {@link Term}s, e.g. if it is used in a Taclet definition + * or if a cut rule is applied. For convenience parameters are always printed as {@link String}s and + * have to be parsed individually into the required {@link Object} instances via a + * {@link TermLabelFactory}. *

    *

    - * Which {@link TermLabel}s are available is defined by the {@link Profile} or - * more precise by its {@link TermLabelManager} available via {@link Profile#getTermLabelManager()}. - * The {@link TermLabelManager} provides also the functionality to parse and maintain them during prove. + * Which {@link TermLabel}s are available is defined by the {@link Profile} or more precise by its + * {@link TermLabelManager} available via {@link Profile#getTermLabelManager()}. The + * {@link TermLabelManager} provides also the functionality to parse and maintain them during prove. *

    *

    - * The {@link TermLabelManager} is responsible during prove to maintain term labels. - * This means that labels of new {@link Term}s created during rule application are computed - * via {@link TermLabelManager#instantiateLabels( - * de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, - * de.uka.ilkd.key.logic.PosInOccurrence, Term, de.uka.ilkd.key.rule.Rule, - * de.uka.ilkd.key.proof.Goal, Object, Term, de.uka.ilkd.key.logic.op.Operator, - * de.uka.ilkd.key.collection.ImmutableArray, - * de.uka.ilkd.key.collection.ImmutableArray, - * de.uka.ilkd.key.logic.JavaBlock)} + * The {@link TermLabelManager} is responsible during prove to maintain term labels. This means that + * labels of new {@link Term}s created during rule application are computed via + * {@link TermLabelManager#instantiateLabels( de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, de.uka.ilkd.key.logic.PosInOccurrence, Term, de.uka.ilkd.key.rule.Rule, de.uka.ilkd.key.proof.Goal, Object, Term, de.uka.ilkd.key.logic.op.Operator, de.uka.ilkd.key.collection.ImmutableArray, de.uka.ilkd.key.collection.ImmutableArray, de.uka.ilkd.key.logic.JavaBlock)} * and of existing {@link Term}s are refactored (added or removed) via - * {@link TermLabelManager#refactorGoal( - * de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, - * de.uka.ilkd.key.logic.PosInOccurrence, Term, de.uka.ilkd.key.rule.Rule, - * de.uka.ilkd.key.proof.Goal, Term)}. + * {@link TermLabelManager#refactorGoal( de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, de.uka.ilkd.key.logic.PosInOccurrence, Term, de.uka.ilkd.key.rule.Rule, de.uka.ilkd.key.proof.Goal, Term)}. *

    *

    - * Antecedent and succedent of a {@link Sequent} are sets. The equality check - * if a {@link SequentFormula} is already contained ignores {@link TermLabel}s. - * To ensure that {@link TermLabel}s are not lost, + * Antecedent and succedent of a {@link Sequent} are sets. The equality check if a + * {@link SequentFormula} is already contained ignores {@link TermLabel}s. To ensure that + * {@link TermLabel}s are not lost, * {@link TermLabelManager#mergeLabels(de.uka.ilkd.key.java.Services, de.uka.ilkd.key.logic.SequentChangeInfo)} - * merges the labels of the existing {@link SequentFormula} with those of the rejected {@link SequentFormula}. - * How this is done in detail is implemented by a {@link TermLabelMerger}. - * If no {@link TermLabelMerger} is available, the {@link TermLabel} of the rejected {@link SequentFormula} are lost. + * merges the labels of the existing {@link SequentFormula} with those of the rejected + * {@link SequentFormula}. How this is done in detail is implemented by a {@link TermLabelMerger}. + * If no {@link TermLabelMerger} is available, the {@link TermLabel} of the rejected + * {@link SequentFormula} are lost. *

    *

    * To implement a new {@link TermLabel} follow the following steps: *

      - *
    1. - * Provide {@link TermLabel} implementation. - *
        - *
      • Without parameters: Add a constant with the {@link Name} and one with the instance to {@link ParameterlessTermLabel}.
      • - *
      • With parameters: Implement new class realizing the interface {@link TermLabel}.
      • - *
      - *
    2. - *
    3. - * Provide a {@link TermLabelFactory} which will be used during the parse process. - *
        - *
      • Without parameters: Reuse class {@link SingletonLabelFactory} with the instance added as constant to {@link ParameterlessTermLabel}.
      • - *
      • With parameters: Implement new class realizing the interface {@link TermLabelFactory}.
      • - *
      - *
    4. - *
    5. - * Define how the {@link TermLabel} is maintained during prove. - * This may have to be done for different rules in different ways. - * Orienteer yourself for each rule on the examples provided in the following. - * They are ordered with the less to the most performance impact during prove. - * Try to treat as many rules as possible with the same solution, but - * choose always the solution with the less performance impact! - * - *
    6. - *
    7. - * Make sure that the {@link Profile} supports the new {@link TermLabel}. - * All implementations from the previous have to be bundled in a - * {@link TermLabelConfiguration} instance. This instance has to be - * created and returned in {@link AbstractProfile#computeTermLabelConfiguration()}. - *
    8. - *
    9. - * During rule application, especially for {@link BuiltInRule}, the - * functionality of {@link TermLabelManager} to maintain {@link TermLabel}s - * is only called for newly created {@link Term}s labeled up to now. If - * your {@link TermLabelPolicy}, {@link TermLabelUpdate} or {@link TermLabelRefactoring} - * is not called on the right {@link Term}, it is your task to call - * {@link TermLabelManager#instantiateLabels( - * de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, - * de.uka.ilkd.key.logic.PosInOccurrence, de.uka.ilkd.key.rule.Rule, - * de.uka.ilkd.key.proof.Goal, Object, Term, de.uka.ilkd.key.logic.op.Operator, - * de.uka.ilkd.key.collection.ImmutableArray, de.uka.ilkd.key.collection.ImmutableArray, - * de.uka.ilkd.key.logic.JavaBlock)} - * and - * {@link TermLabelManager#refactorLabels( - * de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, - * de.uka.ilkd.key.logic.PosInOccurrence, de.uka.ilkd.key.rule.Rule, - * de.uka.ilkd.key.proof.Goal, Term)} - * on the right place in the rule implementation. - *
    10. + *
    11. Provide {@link TermLabel} implementation. + *
        + *
      • Without parameters: Add a constant with the {@link Name} and one with the instance to + * {@link ParameterlessTermLabel}.
      • + *
      • With parameters: Implement new class realizing the interface {@link TermLabel}.
      • + *
      + *
    12. + *
    13. Provide a {@link TermLabelFactory} which will be used during the parse process. + *
        + *
      • Without parameters: Reuse class {@link SingletonLabelFactory} with the instance added as + * constant to {@link ParameterlessTermLabel}.
      • + *
      • With parameters: Implement new class realizing the interface {@link TermLabelFactory}.
      • + *
      + *
    14. + *
    15. Define how the {@link TermLabel} is maintained during prove. This may have to be done for + * different rules in different ways. Orienteer yourself for each rule on the examples provided in + * the following. They are ordered with the less to the most performance impact during prove. Try to + * treat as many rules as possible with the same solution, but choose always the solution with + * the less performance impact! + * + *
    16. + *
    17. Make sure that the {@link Profile} supports the new {@link TermLabel}. All implementations + * from the previous have to be bundled in a {@link TermLabelConfiguration} instance. This instance + * has to be created and returned in {@link AbstractProfile#computeTermLabelConfiguration()}.
    18. + *
    19. During rule application, especially for {@link BuiltInRule}, the functionality of + * {@link TermLabelManager} to maintain {@link TermLabel}s is only called for newly created + * {@link Term}s labeled up to now. If your {@link TermLabelPolicy}, {@link TermLabelUpdate} or + * {@link TermLabelRefactoring} is not called on the right {@link Term}, it is your task to call + * {@link TermLabelManager#instantiateLabels( de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, de.uka.ilkd.key.logic.PosInOccurrence, de.uka.ilkd.key.rule.Rule, de.uka.ilkd.key.proof.Goal, Object, Term, de.uka.ilkd.key.logic.op.Operator, de.uka.ilkd.key.collection.ImmutableArray, de.uka.ilkd.key.collection.ImmutableArray, de.uka.ilkd.key.logic.JavaBlock)} + * and + * {@link TermLabelManager#refactorLabels( de.uka.ilkd.key.logic.label.TermLabelState, de.uka.ilkd.key.java.Services, de.uka.ilkd.key.logic.PosInOccurrence, de.uka.ilkd.key.rule.Rule, de.uka.ilkd.key.proof.Goal, Term)} + * on the right place in the rule implementation.
    20. *
    *

    + * * @author Martin Hentschel * @see TermLabelManager */ @@ -154,8 +152,8 @@ public interface TermLabel extends Named { * @see #isProofRelevant() */ static Term removeIrrelevantLabels(Term term, Services services) { - if (!ProofIndependentSettings.DEFAULT_INSTANCE - .getTermLabelSettings().getUseOriginLabels()) { + if (!ProofIndependentSettings.DEFAULT_INSTANCE.getTermLabelSettings() + .getUseOriginLabels()) { return term; } else { return removeIrrelevantLabels(term, services.getTermFactory()); @@ -171,16 +169,10 @@ static Term removeIrrelevantLabels(Term term, Services services) { * @see #isProofRelevant() */ static Term removeIrrelevantLabels(Term term, TermFactory tf) { - return tf.createTerm( - term.op(), - new ImmutableArray<>( - term.subs().stream() - .map(t -> removeIrrelevantLabels(t, tf)) + return tf.createTerm(term.op(), + new ImmutableArray<>(term.subs().stream().map(t -> removeIrrelevantLabels(t, tf)) .collect(Collectors.toList())), - term.boundVars(), - term.javaBlock(), - new ImmutableArray<>( - term.getLabels().stream() + term.boundVars(), term.javaBlock(), new ImmutableArray<>(term.getLabels().stream() .filter(TermLabel::isProofRelevant).collect(Collectors.toList()))); } @@ -190,13 +182,10 @@ static Term removeIrrelevantLabels(Term term, TermFactory tf) { *

    * A term label may have structure, i.e. can be parameterized. * - * @param i - * the number of the parameter to retrieve ( - * {@code 0 <= i < getChildCount()}) + * @param i the number of the parameter to retrieve ( {@code 0 <= i < getChildCount()}) * @return the selected parameter - * @throws IndexOutOfBoundsException if the given parameter number - * i is negative or greater-or-equal the number of - * parameters returned by {@link #getChildCount()} + * @throws IndexOutOfBoundsException if the given parameter number i is negative or + * greater-or-equal the number of parameters returned by {@link #getChildCount()} */ Object getChild(int i); @@ -210,12 +199,12 @@ static Term removeIrrelevantLabels(Term term, TermFactory tf) { /** * Returns {@code true} iff this label is used in any way during the proof. * - * E.g., {@link OriginTermLabel}s are not used during the proof; - * they only provide a convenience for the user. + * E.g., {@link OriginTermLabel}s are not used during the proof; they only provide a convenience + * for the user. * * @return {@code true} iff this label is used in any way during the proof. */ default boolean isProofRelevant() { return true; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelException.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelException.java index 638fb30f609..73535079692 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelException.java @@ -1,15 +1,17 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; /** * An exception which can be thrown by the term label system. * *

    - * {@link TermLabelFactory} methods can throw an instance if the requested term - * label cannot be created. + * {@link TermLabelFactory} methods can throw an instance if the requested term label cannot be + * created. * *

    - * {@link TermLabelManager} can throw this if a requested label name has not - * been registered. + * {@link TermLabelManager} can throw this if a requested label name has not been registered. * * @author mattias ulbrich */ @@ -32,4 +34,4 @@ public TermLabelException(Throwable cause) { super(cause); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelFactory.java index 6c40102cf86..31192f9c2c6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.List; @@ -8,22 +11,19 @@ * A factory for creating TermLabel objects. * *

    - * The method in this factory allow you to retrieve term labels with given - * parameters. However, a factory may choose to reuse term labels rather than - * create new objects on every call. + * The method in this factory allow you to retrieve term labels with given parameters. However, a + * factory may choose to reuse term labels rather than create new objects on every call. * *

    - * Factories are identified by a name. This name corresponds to the name of the - * {@link TermLabel} objects they create. When parsing all queries to a label - * will be delegated to the factory with the same name. + * Factories are identified by a name. This name corresponds to the name of the {@link TermLabel} + * objects they create. When parsing all queries to a label will be delegated to the factory with + * the same name. * *

    - * Please see information in {@link TermLabels} on how to introduce new label - * types. + * Please see information in {@link TermLabels} on how to introduce new label types. *

    * - * @param - * the type of term labels which are returned by this factory. + * @param the type of term labels which are returned by this factory. * * @see SingletonLabelFactory * @author Mattias Ulbrich @@ -34,20 +34,15 @@ public interface TermLabelFactory { * Parses the arguments and produces a term label. * *

    - * An implementation should throw a {@link TermLabelException} if the - * arguments cannot be parsed correctly for this type. + * An implementation should throw a {@link TermLabelException} if the arguments cannot be parsed + * correctly for this type. * - * @param arguments - * the arguments for parsing, not null, no entry - * null - * @param services - * a non-null services object to look up symbols. + * @param arguments the arguments for parsing, not null, no entry null + * @param services a non-null services object to look up symbols. * - * @return the according term label with the given arguments, not - * null + * @return the according term label with the given arguments, not null * - * @throws TermLabelException - * if the parameters were illegally formatted + * @throws TermLabelException if the parameters were illegally formatted */ public T parseInstance(List arguments, TermServices services) throws TermLabelException; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelManager.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelManager.java index 7e6dcb18e9e..8cddeb2078a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelManager.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelManager.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.LinkedHashSet; @@ -51,401 +54,407 @@ * A {@link TermLabelManager} is associated to a {@link Profile} object using * {@link Profile#getTermLabelManager()}. It allows: *

      - *
    • To list all supported {@link TermLabel} {@link Name}s via {@link #getSupportedTermLabelNames()}.
    • - *
    • To instantiate a {@link TermLabel} via - * {@link #parseLabel(String, List, TermServices)}.
    • - *
    • To compute the {@link TermLabel}s of a {@link Term} to be created via - * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, - * Term, Rule, Goal, Object, Term, Operator, - * ImmutableArray, ImmutableArray, JavaBlock)} - * during rule application.
    • - *
    • To refactor existing {@link Term}s during rule application via: - *
        - *
      • {@link #refactorGoal(TermLabelState, Services, PosInOccurrence, - * Term, Rule, Goal, Term)} : The full sequent
      • - *
      • {@link #refactorSequentFormula(TermLabelState, Services, Term, - * PosInOccurrence, Rule, Goal, - * Object, Term)} : - * The sequent formula which contains the application term on - * which the rule is applied
      • - *
      • {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, - * Term, Rule, Goal, Object, Term)} : - * The current term.
      • - *
      - *
    • + *
    • To list all supported {@link TermLabel} {@link Name}s via + * {@link #getSupportedTermLabelNames()}.
    • + *
    • To instantiate a {@link TermLabel} via {@link #parseLabel(String, List, + * TermServices)}.
    • + *
    • To compute the {@link TermLabel}s of a {@link Term} to be created via + * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)} + * during rule application.
    • + *
    • To refactor existing {@link Term}s during rule application via: + *
        + *
      • {@link #refactorGoal(TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Term)} : + * The full sequent
      • + *
      • {@link #refactorSequentFormula(TermLabelState, Services, Term, PosInOccurrence, Rule, Goal, Object, Term)} + * : The sequent formula which contains the application term on which the rule is applied
      • + *
      • {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term)} + * : The current term.
      • + *
      + *
    • *
    *

    *

    - * For more information about {@link TermLabel}s and how they are maintained - * during prove read the documentation of interface {@link TermLabel}. + * For more information about {@link TermLabel}s and how they are maintained during prove read the + * documentation of interface {@link TermLabel}. *

    + * * @author Mattias Ulbrich * @see TermLabel */ public class TermLabelManager { - /** - * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelFactory}. - */ - private final Map> factoryMap = new LinkedHashMap>(); - - /** - * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelPolicy} applied on the application {@link Term}. - */ - private final Map applicationTermPolicyMap = new LinkedHashMap(); - - /** - * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelPolicy} applied on the modality {@link Term}. - */ - private final Map modalityTermPolicyMap = new LinkedHashMap(); - - /** - * All rule specific direct {@link ChildTermLabelPolicy}s. - */ - private final Map> ruleSpecificDirectChildTermLabelPolicies = new LinkedHashMap>(); - - /** - * All rule independent direct {@link ChildTermLabelPolicy}s. - */ - private final Map allRulesDirectChildTermLabelPolicies = new LinkedHashMap(); - - /** - * All rule specific child and grandchild {@link ChildTermLabelPolicy}s. - */ - private final Map> ruleSpecificChildAndGrandchildTermLabelPolicies = new LinkedHashMap>(); - - /** - * All rule independent child and grandchild {@link ChildTermLabelPolicy}s. - */ - private final Map allRulesChildAndGrandchildTermLabelPolicies = new LinkedHashMap(); - - /** - * All rule independent {@link TermLabelUpdate}s. - */ - private final Map> ruleSpecificUpdates = new LinkedHashMap>(); - - /** - * All rule independent {@link TermLabelUpdate}s. - */ - private ImmutableList allRulesUpdates = ImmutableSLList.nil(); - - /** - * All rule specific {@link TermLabelRefactoring}s. - */ - private final Map> ruleSpecificRefactorings = new LinkedHashMap>(); - - /** - * All rule independent {@link TermLabelRefactoring}s. - */ - private ImmutableList allRulesRefactorings = ImmutableSLList.nil(); - - /** - * The {@link Name}s of all supported {@link TermLabel}s. - */ - private ImmutableList supportedTermLabelnames = ImmutableSLList.nil(); - - /** - * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelMerger}. - */ - private final Map mergerMap = new LinkedHashMap(); - - /** - * Constructor. - * @param configurations The {@link TermLabelConfiguration} which defines how to support each {@link TermLabel}. - */ - public TermLabelManager(ImmutableList configurations) { - if (configurations != null) { - for (TermLabelConfiguration conf : configurations) { - supportedTermLabelnames = supportedTermLabelnames.prepend(conf.getTermLabelName()); - factoryMap.put(conf.getTermLabelName(), conf.getFactory()); - analyzeTermPolicies(conf.getTermLabelName(), conf.getApplicationTermPolicies(), applicationTermPolicyMap); - analyzeTermPolicies(conf.getTermLabelName(), conf.getModalityTermPolicies(), modalityTermPolicyMap); - analyzeChildTermPolicies(conf.getTermLabelName(), conf.getDirectChildTermLabelPolicies(), allRulesDirectChildTermLabelPolicies, ruleSpecificDirectChildTermLabelPolicies); - analyzeChildTermPolicies(conf.getTermLabelName(), conf.getChildAndGrandchildTermLabelPolicies(), allRulesChildAndGrandchildTermLabelPolicies, ruleSpecificChildAndGrandchildTermLabelPolicies); - analyzeUpdates(conf.getTermLabelUpdates()); - analyzeRefactorings(conf.getTermLabelRefactorings()); - analyzeMerger(conf.getTermLabelName(), conf.getTermLabelMerger()); - } - } - } - - /** - * Analyzes the given {@link TermLabelMerger} and adds it to {@link #mergerMap}. - * @param termLabelName The name of the supported {@link TermLabel}. - * @param termLabelMerger The {@link TermLabelMerger} to use. - */ - private void analyzeMerger(Name termLabelName, TermLabelMerger termLabelMerger) { - if (termLabelMerger != null) { - mergerMap.put(termLabelName, termLabelMerger); - } - } - - /** - *

    - * Analyzes the given {@link TermLabelPolicy} and adds it to the given policy {@link Map}. - *

    - *

    - * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. - *

    - * @param termLabelName The name of the supported {@link TermLabel}. - * @param policies The {@link TermLabelPolicy} instances to analyze. - * @param policyMap The policy {@link Map} to update. - */ - private void analyzeTermPolicies(Name termLabelName, - ImmutableList policies, - Map policyMap) { - if (policies != null) { - for (TermLabelPolicy policy : policies) { - policyMap.put(termLabelName, policy); - } - } - } - - /** - *

    - * Analyzes the given {@link ChildTermLabelPolicy} and adds it to the given policy {@link Map}s. - *

    - *

    - * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. - *

    - * @param termLabelName The name of the supported {@link TermLabel}. - * @param policies The {@link ChildTermLabelPolicy} instances to analyze. - * @param allRulesPolicyMap The policy {@link Map} with all rules to update. - * @param ruleSpecificPolicyMap The rule specific policy {@link Map} to update. - */ - private void analyzeChildTermPolicies(Name termLabelName, - ImmutableList policies, - Map allRulesPolicyMap, - Map> ruleSpecificPolicyMap) { - if (policies != null) { - for (ChildTermLabelPolicy policy : policies) { - ImmutableList supportedRules = policy.getSupportedRuleNames(); - if (supportedRules == null || supportedRules.isEmpty()) { - allRulesPolicyMap.put(termLabelName, policy); + /** + * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelFactory}. + */ + private final Map> factoryMap = + new LinkedHashMap>(); + + /** + * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelPolicy} applied + * on the application {@link Term}. + */ + private final Map applicationTermPolicyMap = + new LinkedHashMap(); + + /** + * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelPolicy} applied + * on the modality {@link Term}. + */ + private final Map modalityTermPolicyMap = + new LinkedHashMap(); + + /** + * All rule specific direct {@link ChildTermLabelPolicy}s. + */ + private final Map> ruleSpecificDirectChildTermLabelPolicies = + new LinkedHashMap>(); + + /** + * All rule independent direct {@link ChildTermLabelPolicy}s. + */ + private final Map allRulesDirectChildTermLabelPolicies = + new LinkedHashMap(); + + /** + * All rule specific child and grandchild {@link ChildTermLabelPolicy}s. + */ + private final Map> ruleSpecificChildAndGrandchildTermLabelPolicies = + new LinkedHashMap>(); + + /** + * All rule independent child and grandchild {@link ChildTermLabelPolicy}s. + */ + private final Map allRulesChildAndGrandchildTermLabelPolicies = + new LinkedHashMap(); + + /** + * All rule independent {@link TermLabelUpdate}s. + */ + private final Map> ruleSpecificUpdates = + new LinkedHashMap>(); + + /** + * All rule independent {@link TermLabelUpdate}s. + */ + private ImmutableList allRulesUpdates = ImmutableSLList.nil(); + + /** + * All rule specific {@link TermLabelRefactoring}s. + */ + private final Map> ruleSpecificRefactorings = + new LinkedHashMap>(); + + /** + * All rule independent {@link TermLabelRefactoring}s. + */ + private ImmutableList allRulesRefactorings = + ImmutableSLList.nil(); + + /** + * The {@link Name}s of all supported {@link TermLabel}s. + */ + private ImmutableList supportedTermLabelnames = ImmutableSLList.nil(); + + /** + * {@link Map}s the {@link Name} of a {@link TermLabel} to its {@link TermLabelMerger}. + */ + private final Map mergerMap = new LinkedHashMap(); + + /** + * Constructor. + * + * @param configurations The {@link TermLabelConfiguration} which defines how to support each + * {@link TermLabel}. + */ + public TermLabelManager(ImmutableList configurations) { + if (configurations != null) { + for (TermLabelConfiguration conf : configurations) { + supportedTermLabelnames = supportedTermLabelnames.prepend(conf.getTermLabelName()); + factoryMap.put(conf.getTermLabelName(), conf.getFactory()); + analyzeTermPolicies(conf.getTermLabelName(), conf.getApplicationTermPolicies(), + applicationTermPolicyMap); + analyzeTermPolicies(conf.getTermLabelName(), conf.getModalityTermPolicies(), + modalityTermPolicyMap); + analyzeChildTermPolicies(conf.getTermLabelName(), + conf.getDirectChildTermLabelPolicies(), + allRulesDirectChildTermLabelPolicies, + ruleSpecificDirectChildTermLabelPolicies); + analyzeChildTermPolicies(conf.getTermLabelName(), + conf.getChildAndGrandchildTermLabelPolicies(), + allRulesChildAndGrandchildTermLabelPolicies, + ruleSpecificChildAndGrandchildTermLabelPolicies); + analyzeUpdates(conf.getTermLabelUpdates()); + analyzeRefactorings(conf.getTermLabelRefactorings()); + analyzeMerger(conf.getTermLabelName(), conf.getTermLabelMerger()); } - else { - for (Name rule : supportedRules) { - Map ruleMap = ruleSpecificPolicyMap.get(rule); - if (ruleMap == null) { - ruleMap = new LinkedHashMap(); - ruleSpecificPolicyMap.put(rule, ruleMap); - } - ruleMap.put(termLabelName, policy); - } + } + } + + /** + * Analyzes the given {@link TermLabelMerger} and adds it to {@link #mergerMap}. + * + * @param termLabelName The name of the supported {@link TermLabel}. + * @param termLabelMerger The {@link TermLabelMerger} to use. + */ + private void analyzeMerger(Name termLabelName, TermLabelMerger termLabelMerger) { + if (termLabelMerger != null) { + mergerMap.put(termLabelName, termLabelMerger); + } + } + + /** + *

    + * Analyzes the given {@link TermLabelPolicy} and adds it to the given policy {@link Map}. + *

    + *

    + * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. + *

    + * + * @param termLabelName The name of the supported {@link TermLabel}. + * @param policies The {@link TermLabelPolicy} instances to analyze. + * @param policyMap The policy {@link Map} to update. + */ + private void analyzeTermPolicies(Name termLabelName, ImmutableList policies, + Map policyMap) { + if (policies != null) { + for (TermLabelPolicy policy : policies) { + policyMap.put(termLabelName, policy); } - } - } - } - - /** - *

    - * Analyzes the given {@link TermLabelUpdate} and updates {@link #allRulesUpdates} and {@link #ruleSpecificUpdates}. - *

    - *

    - * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. - *

    - * @param updates The {@link TermLabelUpdate}s to analyze. - */ - private void analyzeUpdates(ImmutableList updates) { - if (updates != null) { - for (TermLabelUpdate update : updates) { - ImmutableList supportedRules = update.getSupportedRuleNames(); - if (supportedRules == null || supportedRules.isEmpty()) { - allRulesUpdates = allRulesUpdates.prepend(update); + } + } + + /** + *

    + * Analyzes the given {@link ChildTermLabelPolicy} and adds it to the given policy {@link Map}s. + *

    + *

    + * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. + *

    + * + * @param termLabelName The name of the supported {@link TermLabel}. + * @param policies The {@link ChildTermLabelPolicy} instances to analyze. + * @param allRulesPolicyMap The policy {@link Map} with all rules to update. + * @param ruleSpecificPolicyMap The rule specific policy {@link Map} to update. + */ + private void analyzeChildTermPolicies(Name termLabelName, + ImmutableList policies, + Map allRulesPolicyMap, + Map> ruleSpecificPolicyMap) { + if (policies != null) { + for (ChildTermLabelPolicy policy : policies) { + ImmutableList supportedRules = policy.getSupportedRuleNames(); + if (supportedRules == null || supportedRules.isEmpty()) { + allRulesPolicyMap.put(termLabelName, policy); + } else { + for (Name rule : supportedRules) { + Map ruleMap = ruleSpecificPolicyMap.get(rule); + if (ruleMap == null) { + ruleMap = new LinkedHashMap(); + ruleSpecificPolicyMap.put(rule, ruleMap); + } + ruleMap.put(termLabelName, policy); + } + } } - else { - for (Name rule : supportedRules) { - ImmutableList ruleUpdates = ruleSpecificUpdates.get(rule); - if (ruleUpdates == null) { - ruleUpdates = ImmutableSLList.nil(); - } - ruleUpdates = ruleUpdates.prepend(update); - ruleSpecificUpdates.put(rule, ruleUpdates); - } + } + } + + /** + *

    + * Analyzes the given {@link TermLabelUpdate} and updates {@link #allRulesUpdates} and + * {@link #ruleSpecificUpdates}. + *

    + *

    + * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. + *

    + * + * @param updates The {@link TermLabelUpdate}s to analyze. + */ + private void analyzeUpdates(ImmutableList updates) { + if (updates != null) { + for (TermLabelUpdate update : updates) { + ImmutableList supportedRules = update.getSupportedRuleNames(); + if (supportedRules == null || supportedRules.isEmpty()) { + allRulesUpdates = allRulesUpdates.prepend(update); + } else { + for (Name rule : supportedRules) { + ImmutableList ruleUpdates = ruleSpecificUpdates.get(rule); + if (ruleUpdates == null) { + ruleUpdates = ImmutableSLList.nil(); + } + ruleUpdates = ruleUpdates.prepend(update); + ruleSpecificUpdates.put(rule, ruleUpdates); + } + } } - } - } - } - - /** - *

    - * Analyzes the given {@link TermLabelRefactoring} and updates {@link #allRulesRefactorings} and {@link #ruleSpecificRefactorings}. - *

    - *

    - * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. - *

    - * param updates The {@link TermLabelUpdate}s to analyze. - */ - private void analyzeRefactorings(ImmutableList refactorings) { - if (refactorings != null) { - for (TermLabelRefactoring refactoring : refactorings) { - ImmutableList supportedRules = refactoring.getSupportedRuleNames(); - if (supportedRules == null || supportedRules.isEmpty()) { - allRulesRefactorings = allRulesRefactorings.prepend(refactoring); + } + } + + /** + *

    + * Analyzes the given {@link TermLabelRefactoring} and updates {@link #allRulesRefactorings} and + * {@link #ruleSpecificRefactorings}. + *

    + *

    + * This is a helper {@link Map} of {@link #TermLabelManager(ImmutableList)}. + *

    + * param updates The {@link TermLabelUpdate}s to analyze. + */ + private void analyzeRefactorings(ImmutableList refactorings) { + if (refactorings != null) { + for (TermLabelRefactoring refactoring : refactorings) { + ImmutableList supportedRules = refactoring.getSupportedRuleNames(); + if (supportedRules == null || supportedRules.isEmpty()) { + allRulesRefactorings = allRulesRefactorings.prepend(refactoring); + } else { + for (Name rule : supportedRules) { + ImmutableList ruleRefactorings = + ruleSpecificRefactorings.get(rule); + if (ruleRefactorings == null) { + ruleRefactorings = ImmutableSLList.nil(); + } + ruleRefactorings = ruleRefactorings.prepend(refactoring); + ruleSpecificRefactorings.put(rule, ruleRefactorings); + } + } } - else { - for (Name rule : supportedRules) { - ImmutableList ruleRefactorings = ruleSpecificRefactorings.get(rule); - if (ruleRefactorings == null) { - ruleRefactorings = ImmutableSLList.nil(); - } - ruleRefactorings = ruleRefactorings.prepend(refactoring); - ruleSpecificRefactorings.put(rule, ruleRefactorings); - } + } + } + + /** + * Returns the {@link TermLabelManager} defined by the {@link Profile} of the given + * {@link Services}. + * + * @param services The {@link Services} which provides the {@link TermLabelManager}. + * @return The {@link TermLabelManager}s or {@code null} if not available. + */ + public static TermLabelManager getTermLabelManager(Services services) { + TermLabelManager result = null; + if (services != null) { + Profile profile = services.getProfile(); + if (profile != null) { + result = profile.getTermLabelManager(); } - } - } - } - - /** - * Returns the {@link TermLabelManager} defined by the {@link Profile} of the given {@link Services}. - * @param services The {@link Services} which provides the {@link TermLabelManager}. - * @return The {@link TermLabelManager}s or {@code null} if not available. - */ - public static TermLabelManager getTermLabelManager(Services services) { - TermLabelManager result = null; - if (services != null) { - Profile profile = services.getProfile(); - if (profile != null) { - result = profile.getTermLabelManager(); - } - } - return result; - } - - /** - * Returns the {@link Name}s of the supported {@link TermLabel}s. - * @param services The {@link Services} used by the {@link Proof} on which the {@link Name}s of supported {@link TermLabel}s are requested. - * @return The {@link Name}s of the supported {@link TermLabel}s. - */ - public static ImmutableList getSupportedTermLabelNames(Services services) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - return manager.getSupportedTermLabelNames(); - } - else { - return ImmutableSLList.nil(); - } - } - - /** - * Returns the {@link Name}s of all supported {@link TermLabel}s. - * @return The {@link Name}s of all supported {@link TermLabel}s. - */ - public ImmutableList getSupportedTermLabelNames() { - return supportedTermLabelnames; - } - - /** - *

    - * Get a term label for string parameters. - *

    - *

    - * Parses the string arguments and returns the term label of name - * name with the corresponding parameters. - *

    - *

    - * The name must be associated with a {@link TermLabelFactory}. Otherwise a - * {@link TermLabelException} is thrown to indicate that an unknown term - * label kind has been asked for. - *

    - * @param name The name of the term label, not null - * @param args The arguments, not null, no entry null - * @param services a non-null services object to look up symbols - * @return term label of kind {@code name} with parameters as parsed. - * @throws TermLabelException if name is not a registered label name or the arguments cannot be parsed. - */ - public TermLabel parseLabel(String name, List args, TermServices services) throws TermLabelException { - TermLabelFactory factory = factoryMap.get(new Name(name)); - if (factory == null) { - throw new TermLabelException("No TermLabelFactory available for term label name \"" + name + "\"."); - } - else { - return factory.parseInstance(args, services); - } - } + } + return result; + } + + /** + * Returns the {@link Name}s of the supported {@link TermLabel}s. + * + * @param services The {@link Services} used by the {@link Proof} on which the {@link Name}s of + * supported {@link TermLabel}s are requested. + * @return The {@link Name}s of the supported {@link TermLabel}s. + */ + public static ImmutableList getSupportedTermLabelNames(Services services) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + return manager.getSupportedTermLabelNames(); + } else { + return ImmutableSLList.nil(); + } + } + + /** + * Returns the {@link Name}s of all supported {@link TermLabel}s. + * + * @return The {@link Name}s of all supported {@link TermLabel}s. + */ + public ImmutableList getSupportedTermLabelNames() { + return supportedTermLabelnames; + } + + /** + *

    + * Get a term label for string parameters. + *

    + *

    + * Parses the string arguments and returns the term label of name name with the + * corresponding parameters. + *

    + *

    + * The name must be associated with a {@link TermLabelFactory}. Otherwise a + * {@link TermLabelException} is thrown to indicate that an unknown term label kind has been + * asked for. + *

    + * + * @param name The name of the term label, not null + * @param args The arguments, not null, no entry null + * @param services a non-null services object to look up symbols + * @return term label of kind {@code name} with parameters as parsed. + * @throws TermLabelException if name is not a registered label name or the arguments cannot be + * parsed. + */ + public TermLabel parseLabel(String name, List args, TermServices services) + throws TermLabelException { + TermLabelFactory factory = factoryMap.get(new Name(name)); + if (factory == null) { + throw new TermLabelException( + "No TermLabelFactory available for term label name \"" + name + "\"."); + } else { + return factory.parseInstance(args, services); + } + } /** * Computes the {@link TermLabel}s for the new {@link Term} via - * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, - * Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, - * JavaBlock, ImmutableArray)} + * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock, ImmutableArray)} * and refactors the labels below the new {@link Term} in addition via - * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, - * Rule, Term)}. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. + * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, Rule, Term)}. + * + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. * @param state The {@link TermLabelState} of the current rule application. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or {@code null} - * in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTerm The new {@link Term} to update its labels. * @return The {@link Term} with updates labels. */ - public static Term label(Services services, - TermLabelState state, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Term newTerm) { + public static Term label(Services services, TermLabelState state, + PosInOccurrence applicationPosInOccurrence, Rule rule, RuleApp ruleApp, Goal goal, + Object hint, Term tacletTerm, Term newTerm) { Term applicationTerm = - applicationPosInOccurrence != null ? - applicationPosInOccurrence.subTerm() : null; - return label(services, state, applicationTerm, applicationPosInOccurrence, - rule, ruleApp, goal, hint, tacletTerm, newTerm); + applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; + return label(services, state, applicationTerm, applicationPosInOccurrence, rule, ruleApp, + goal, hint, tacletTerm, newTerm); } /** * Computes the {@link TermLabel}s for the new {@link Term} via - * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, - * Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, - * JavaBlock, ImmutableArray)} + * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock, ImmutableArray)} * and refactors the labels below the new {@link Term} in addition via - * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, - * Rule, Term)}. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. + * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, Rule, Term)}. + * + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. * @param state The {@link TermLabelState} of the current rule application. * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the - * previous {@link Sequent}. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. + * previous {@link Sequent}. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which - * should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or {@code null} - * in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTerm The new {@link Term} to update its labels. * @return The {@link Term} with updates labels. */ - public static Term label(Services services, - TermLabelState state, - Term applicationTerm, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Term newTerm) { + public static Term label(Services services, TermLabelState state, Term applicationTerm, + PosInOccurrence applicationPosInOccurrence, Rule rule, RuleApp ruleApp, Goal goal, + Object hint, Term tacletTerm, Term newTerm) { TermLabelManager manager = getTermLabelManager(services); if (manager != null) { - return manager.label(state, services, applicationTerm, applicationPosInOccurrence, - rule, ruleApp, goal, hint, tacletTerm, newTerm); + return manager.label(state, services, applicationTerm, applicationPosInOccurrence, rule, + ruleApp, goal, hint, tacletTerm, newTerm); } else { return newTerm; } @@ -453,163 +462,122 @@ public static Term label(Services services, /** * Computes the {@link TermLabel}s for the new {@link Term} via - * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, - * Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, - * JavaBlock, ImmutableArray)} + * {@link #instantiateLabels(TermLabelState, Services, PosInOccurrence, Term, Rule, RuleApp, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock, ImmutableArray)} * and refactors the labels below the new {@link Term} in addition via - * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, - * Rule, Term)}. + * {@link #refactorTerm(TermLabelState, Services, PosInOccurrence, Term, Goal, Object, Rule, Term)}. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the - * previous {@link Sequent}. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. + * previous {@link Sequent}. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or - * {@code null} in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTerm The new {@link Term} to update its labels. * @return The {@link Term} with updates labels. */ - public Term label(TermLabelState state, - Services services, - Term applicationTerm, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Term newTerm) { - ImmutableArray newLabels = - instantiateLabels(state, services, applicationTerm, - applicationPosInOccurrence, rule, ruleApp, - goal, hint, tacletTerm, newTerm.op(), - newTerm.subs(), newTerm.boundVars(), - newTerm.javaBlock(), newTerm.getLabels()); + public Term label(TermLabelState state, Services services, Term applicationTerm, + PosInOccurrence applicationPosInOccurrence, Rule rule, RuleApp ruleApp, Goal goal, + Object hint, Term tacletTerm, Term newTerm) { + ImmutableArray newLabels = instantiateLabels(state, services, applicationTerm, + applicationPosInOccurrence, rule, ruleApp, goal, hint, tacletTerm, newTerm.op(), + newTerm.subs(), newTerm.boundVars(), newTerm.javaBlock(), newTerm.getLabels()); Term newlyLabeledTerm = services.getTermBuilder().addLabel(newTerm, newLabels); - return refactorTerm(state, services, applicationPosInOccurrence, - newlyLabeledTerm, goal, hint, rule, tacletTerm); + return refactorTerm(state, services, applicationPosInOccurrence, newlyLabeledTerm, goal, + hint, rule, tacletTerm); } /** *

    - * Computes the {@link TermLabel} to add to a new {@link Term} while - * a {@link Rule} is currently active. The labels of the new {@link Term} - * are computed just before the term is created. + * Computes the {@link TermLabel} to add to a new {@link Term} while a {@link Rule} is currently + * active. The labels of the new {@link Term} are computed just before the term is created. *

    *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. *

    + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or {@code null} - * in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTermOp The new {@link Operator} of the {@link Term} to create. * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} - * to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. * @param newTermOriginalLabels The original {@link TermLabel}s. * @return The {@link TermLabel}s to add to the new {@link Term} which should be created. */ - public static ImmutableArray - instantiateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels) { + public static ImmutableArray instantiateLabels(TermLabelState state, + Services services, PosInOccurrence applicationPosInOccurrence, Rule rule, + RuleApp ruleApp, Goal goal, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, ImmutableArray newTermOriginalLabels) { Term applicationTerm = - applicationPosInOccurrence != null ? - applicationPosInOccurrence.subTerm() : null; - return instantiateLabels(state, services, applicationTerm, - applicationPosInOccurrence, rule, ruleApp, - goal, hint, tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, newTermOriginalLabels); + applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; + return instantiateLabels(state, services, applicationTerm, applicationPosInOccurrence, rule, + ruleApp, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, newTermOriginalLabels); } /** *

    - * Computes the {@link TermLabel} to add to a new {@link Term} while - * a {@link Rule} is currently active. The labels of the new {@link Term} - * are computed just before the term is created. + * Computes the {@link TermLabel} to add to a new {@link Term} while a {@link Rule} is currently + * active. The labels of the new {@link Term} are computed just before the term is created. *

    *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. *

    + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the - * previous {@link Sequent}. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. + * previous {@link Sequent}. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible - * to instantiate the new {@link Term} for the new proof node or - * {@code null} in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTermOp The new {@link Operator} of the {@link Term} to create. * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the - * {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. * @param newTermOriginalLabels The original {@link TermLabel}s. * @return The {@link TermLabel}s to add to the new {@link Term} which should be created. */ - public static ImmutableArray - instantiateLabels(TermLabelState state, - Services services, - Term applicationTerm, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels) { + public static ImmutableArray instantiateLabels(TermLabelState state, + Services services, Term applicationTerm, PosInOccurrence applicationPosInOccurrence, + Rule rule, RuleApp ruleApp, Goal goal, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, ImmutableArray newTermOriginalLabels) { TermLabelManager manager = getTermLabelManager(services); if (manager != null) { return manager.instantiateLabels(state, services, applicationPosInOccurrence, - applicationTerm, rule, ruleApp, goal, hint, - tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, - newTermOriginalLabels); + applicationTerm, rule, ruleApp, goal, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, newTermOriginalLabels); } else { return new ImmutableArray(); } @@ -618,146 +586,115 @@ public Term label(TermLabelState state, /** * Do application term specific stuff. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} that - * is rewritten. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the - * previous {@link Sequent}. + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or - * {@code null} in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTermOp The new {@link Operator} of the {@link Term} to create. * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the - * {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. * @param newTermOriginalLabels The original {@link TermLabel}s. - * @param newLabels The set accumulating the {@link TermLabel}s to add to the new - * {@link Term} which should be created. + * @param newLabels The set accumulating the {@link TermLabel}s to add to the new {@link Term} + * which should be created. */ - private void - addLabelsBasedOnApplicationTerm(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels, - Set newLabels) { + private void addLabelsBasedOnApplicationTerm(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + ImmutableArray newTermOriginalLabels, Set newLabels) { if (applicationTerm == null) { return; } // Re-add exiting application term labels based on application term policies. - performTermLabelPolicies(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - newTermOp, newTermSubs, newTermBoundVars, - newTermJavaBlock, newTermOriginalLabels, - applicationTermPolicyMap, newLabels); + performTermLabelPolicies(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, + newTermOriginalLabels, applicationTermPolicyMap, newLabels); // Add labels from direct child term policies. - Map activeDirectChildPolicies = - computeActiveChildPolicies(services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, - ruleSpecificDirectChildTermLabelPolicies, - allRulesDirectChildTermLabelPolicies); + Map activeDirectChildPolicies = computeActiveChildPolicies( + services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, + ruleSpecificDirectChildTermLabelPolicies, allRulesDirectChildTermLabelPolicies); if (!activeDirectChildPolicies.isEmpty()) { - performDirectChildPolicies(services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, - activeDirectChildPolicies, newLabels); + performDirectChildPolicies(services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, activeDirectChildPolicies, newLabels); } // Add labels from child and grandchild term policies. Map activeChildAndGrandchildPolicies = - computeActiveChildPolicies(services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, - ruleSpecificChildAndGrandchildTermLabelPolicies, - allRulesChildAndGrandchildTermLabelPolicies); + computeActiveChildPolicies(services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, ruleSpecificChildAndGrandchildTermLabelPolicies, + allRulesChildAndGrandchildTermLabelPolicies); if (!activeChildAndGrandchildPolicies.isEmpty()) { - performChildAndGrandchildPolicies(services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, newTermOp, newTermSubs, - newTermBoundVars, newTermJavaBlock, - activeChildAndGrandchildPolicies, newLabels); + performChildAndGrandchildPolicies(services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, activeChildAndGrandchildPolicies, newLabels); } } /** - * Computes the {@link TermLabel} to add to a new {@link Term} while - * a {@link Rule} is currently active. The labels of the new {@link Term} - * are computed just before the term is created in the following way: + * Computes the {@link TermLabel} to add to a new {@link Term} while a {@link Rule} is currently + * active. The labels of the new {@link Term} are computed just before the term is created in + * the following way: *
      - *
    1. An empty result {@link List} is created.
    2. - *
    3. All labels from taclet term are added to the result {@link List}.
    4. - *
    5. Existing labels on application term are added to result {@link List} if - * {@link TermLabelPolicy} wants to keep it.
    6. - *
    7. Existing labels on modality term are added to result {@link List} if - * {@link TermLabelPolicy} wants to keep it.
    8. - *
    9. All {@link TermLabelUpdate} are asked to add or remove labels from result - * {@link List}
    10. - *
    11. Result {@link List} is returned.
    12. + *
    13. An empty result {@link List} is created.
    14. + *
    15. All labels from taclet term are added to the result {@link List}.
    16. + *
    17. Existing labels on application term are added to result {@link List} if + * {@link TermLabelPolicy} wants to keep it.
    18. + *
    19. Existing labels on modality term are added to result {@link List} if + * {@link TermLabelPolicy} wants to keep it.
    20. + *
    21. All {@link TermLabelUpdate} are asked to add or remove labels from result + * {@link List}
    22. + *
    23. Result {@link List} is returned.
    24. *
    + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} that - * is rewritten. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the - * previous {@link Sequent}. + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param ruleApp The {@link RuleApp} which is currently performed. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or - * {@code null} in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTermOp The new {@link Operator} of the {@link Term} to create. * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the - * {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. * @param newTermOriginalLabels The original {@link TermLabel}s. * @return The {@link TermLabel}s to add to the new {@link Term} which should be created. */ - public ImmutableArray - instantiateLabels(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - RuleApp ruleApp, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels) { + public ImmutableArray instantiateLabels(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, + RuleApp ruleApp, Goal goal, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, ImmutableArray newTermOriginalLabels) { // Compute current rule specific updates ImmutableList currentRuleSpecificUpdates = rule != null ? ruleSpecificUpdates.get(rule.name()) : null; // Compute modality term if required - Term modalityTerm = - applicationTerm != null - && (!modalityTermPolicyMap.isEmpty() || !allRulesUpdates.isEmpty() - || currentRuleSpecificUpdates != null) - ? TermBuilder.goBelowUpdates(applicationTerm) + Term modalityTerm = applicationTerm != null && (!modalityTermPolicyMap.isEmpty() + || !allRulesUpdates.isEmpty() || currentRuleSpecificUpdates != null) + ? TermBuilder.goBelowUpdates(applicationTerm) : null; // Instantiate empty result Set newLabels = new LinkedHashSet(); @@ -765,699 +702,686 @@ public Term label(TermLabelState state, if (tacletTerm != null && tacletTerm.hasLabels()) { performTacletTerm(tacletTerm, newLabels); } - addLabelsBasedOnApplicationTerm(state, services, - applicationPosInOccurrence, applicationTerm, rule, goal, hint, - tacletTerm, newTermOp, newTermSubs, newTermBoundVars, - newTermJavaBlock, newTermOriginalLabels, newLabels); + addLabelsBasedOnApplicationTerm(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, newTermOriginalLabels, newLabels); // Re-add exiting modality term labels based on symbolic execution term policies. if (modalityTerm != null) { - performTermLabelPolicies(state, services, applicationPosInOccurrence, - modalityTerm, rule, goal, hint, tacletTerm, - newTermOp, newTermSubs, newTermBoundVars, - newTermJavaBlock, newTermOriginalLabels, - modalityTermPolicyMap, newLabels); + performTermLabelPolicies(state, services, applicationPosInOccurrence, modalityTerm, + rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, newTermOriginalLabels, modalityTermPolicyMap, newLabels); } // Allow rule specific updater to remove and add labels if (currentRuleSpecificUpdates != null) { performUpdater(state, services, applicationPosInOccurrence, applicationTerm, - modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, - newTermSubs, newTermBoundVars, newTermJavaBlock, - currentRuleSpecificUpdates, newLabels); + modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, currentRuleSpecificUpdates, newLabels); } // Allow all rule updater to remove and add labels if (!allRulesUpdates.isEmpty()) { performUpdater(state, services, applicationPosInOccurrence, applicationTerm, - modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, - newTermSubs, newTermBoundVars, newTermJavaBlock, allRulesUpdates, - newLabels); + modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, allRulesUpdates, newLabels); } // Return result return new ImmutableArray(newLabels.toArray(new TermLabel[newLabels.size()])); } - /** - *

    - * Performs the {@link TermLabel}s provided by the taclet {@link Term}. - *

    - *

    - * This is a helper {@link Map} of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. - *

    - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. - */ - protected void performTacletTerm(Term tacletTerm, Set newLabels) { - for (TermLabel label : tacletTerm.getLabels()) { - newLabels.add(label); - } - } - - /** - *

    - * Performs the given {@link TermLabelPolicy} instances. - *

    - *

    - * This is a helper method of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newTermOp The new {@link Operator} of the {@link Term} to create. - * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to create. - * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. - * @param newTermOriginalLabels The original {@link TermLabel}s. - * @param policies The {@link TermLabelPolicy} instances to perform. - * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. - */ - protected void performTermLabelPolicies(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels, - Map policies, - Set newLabels) { - if (applicationTerm.hasLabels() && !policies.isEmpty()) { - for (TermLabel label : applicationTerm.getLabels()) { - performTermLabelPolicies(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, newTermOriginalLabels, policies, newLabels, label); - } - } -// if (newTermOriginalLabels != null && !policies.isEmpty()) { -// for (TermLabel label : newTermOriginalLabels) { -// performTermLabelPolicies(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, newTermOriginalLabels, policies, newLabels, label); -// } -// } - } - - /** - *

    - * Performs the given {@link TermLabelPolicy} instances. - *

    - *

    - * This is a helper method of {@link #performTermLabelPolicies( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock, - * ImmutableArray, Map, List)}. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newTermOp The new {@link Operator} of the {@link Term} to create. - * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to create. - * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. - * @param newTermOriginalLabels The original {@link TermLabel}s. - * @param policies The {@link TermLabelPolicy} instances to perform. - * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. - * @param label The current {@link TermLabel} to ask its {@link TermLabelPolicy}. - */ - protected void performTermLabelPolicies(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableArray newTermOriginalLabels, - Map policies, - Set newLabels, - TermLabel label) { - TermLabelPolicy policy = policies.get(label.name()); - if (policy != null) { - label = policy.keepLabel(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, newTermOriginalLabels, label); - if (label != null) { + /** + *

    + * Performs the {@link TermLabel}s provided by the taclet {@link Term}. + *

    + *

    + * This is a helper {@link Map} of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. + *

    + * + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. + */ + protected void performTacletTerm(Term tacletTerm, Set newLabels) { + for (TermLabel label : tacletTerm.getLabels()) { newLabels.add(label); - } - } - } - - /** - *

    - * Computes active {@link ChildTermLabelPolicy} instances which have to be executed during the given rule application. - *

    - *

    - * This is a helper {@link Map} of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. - *

    - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newTermOp The new {@link Operator} of the {@link Term} to create. - * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to create. - * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. - * @param ruleSpecificPolicies Rule specific {@link ChildTermLabelPolicy} instances. - * @param ruleIndependentPolicies All rules {@link ChildTermLabelPolicy} instances. - * @return The active {@link ChildTermLabelPolicy} which have to be performed. - */ - protected Map computeActiveChildPolicies(TermServices services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Map> ruleSpecificPolicies, - Map ruleIndependentPolicies) { - Map activeDirectChildPolicies = new LinkedHashMap(); - if (rule != null) { - Map rulePolicies = ruleSpecificPolicies.get(rule.name()); - if (rulePolicies != null) { - for (Entry entry : rulePolicies.entrySet()) { - if (entry.getValue().isRuleApplicationSupported(services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock)) { - activeDirectChildPolicies.put(entry.getKey(), entry.getValue()); - } + } + } + + /** + *

    + * Performs the given {@link TermLabelPolicy} instances. + *

    + *

    + * This is a helper method of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newTermOp The new {@link Operator} of the {@link Term} to create. + * @param newTermSubs The optional children of the {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. + * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. + * @param newTermOriginalLabels The original {@link TermLabel}s. + * @param policies The {@link TermLabelPolicy} instances to perform. + * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. + */ + protected void performTermLabelPolicies(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + ImmutableArray newTermOriginalLabels, Map policies, + Set newLabels) { + if (applicationTerm.hasLabels() && !policies.isEmpty()) { + for (TermLabel label : applicationTerm.getLabels()) { + performTermLabelPolicies(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, newTermOriginalLabels, policies, + newLabels, label); } - } - } - if (!ruleIndependentPolicies.isEmpty()) { - for (Entry entry : ruleIndependentPolicies.entrySet()) { - if (entry.getValue().isRuleApplicationSupported(services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock)) { - activeDirectChildPolicies.put(entry.getKey(), entry.getValue()); + } + // if (newTermOriginalLabels != null && !policies.isEmpty()) { + // for (TermLabel label : newTermOriginalLabels) { + // performTermLabelPolicies(state, services, applicationPosInOccurrence, applicationTerm, + // rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, + // newTermOriginalLabels, policies, newLabels, label); + // } + // } + } + + /** + *

    + * Performs the given {@link TermLabelPolicy} instances. + *

    + *

    + * This is a helper method of + * {@link #performTermLabelPolicies( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock, ImmutableArray, Map, List)}. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newTermOp The new {@link Operator} of the {@link Term} to create. + * @param newTermSubs The optional children of the {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. + * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. + * @param newTermOriginalLabels The original {@link TermLabel}s. + * @param policies The {@link TermLabelPolicy} instances to perform. + * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. + * @param label The current {@link TermLabel} to ask its {@link TermLabelPolicy}. + */ + protected void performTermLabelPolicies(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + ImmutableArray newTermOriginalLabels, Map policies, + Set newLabels, TermLabel label) { + TermLabelPolicy policy = policies.get(label.name()); + if (policy != null) { + label = policy.keepLabel(state, services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock, newTermOriginalLabels, label); + if (label != null) { + newLabels.add(label); } - } - } - return activeDirectChildPolicies; - } + } + } + + /** + *

    + * Computes active {@link ChildTermLabelPolicy} instances which have to be executed during the + * given rule application. + *

    + *

    + * This is a helper {@link Map} of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. + *

    + * + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newTermOp The new {@link Operator} of the {@link Term} to create. + * @param newTermSubs The optional children of the {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. + * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. + * @param ruleSpecificPolicies Rule specific {@link ChildTermLabelPolicy} instances. + * @param ruleIndependentPolicies All rules {@link ChildTermLabelPolicy} instances. + * @return The active {@link ChildTermLabelPolicy} which have to be performed. + */ + protected Map computeActiveChildPolicies(TermServices services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + Map> ruleSpecificPolicies, + Map ruleIndependentPolicies) { + Map activeDirectChildPolicies = + new LinkedHashMap(); + if (rule != null) { + Map rulePolicies = ruleSpecificPolicies.get(rule.name()); + if (rulePolicies != null) { + for (Entry entry : rulePolicies.entrySet()) { + if (entry.getValue().isRuleApplicationSupported(services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, + tacletTerm, newTermOp, newTermSubs, newTermBoundVars, + newTermJavaBlock)) { + activeDirectChildPolicies.put(entry.getKey(), entry.getValue()); + } + } + } + } + if (!ruleIndependentPolicies.isEmpty()) { + for (Entry entry : ruleIndependentPolicies.entrySet()) { + if (entry.getValue().isRuleApplicationSupported(services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock)) { + activeDirectChildPolicies.put(entry.getKey(), entry.getValue()); + } + } + } + return activeDirectChildPolicies; + } /** *

    * Performs the given direct {@link ChildTermLabelPolicy} instances. *

    *

    - * This is a helper {@link Map} of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. + * This is a helper {@link Map} of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. *

    - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to - * instantiate the new {@link Term} for the new proof node or - * {@code null} in case of built in rules. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. * @param newTermOp The new {@link Operator} of the {@link Term} to create. * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the - * {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. * @param policies The {@link ChildTermLabelPolicy} instances to perform. * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. */ - protected void - performDirectChildPolicies(TermServices services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - Map policies, - Set newLabels) { + protected void performDirectChildPolicies(TermServices services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Operator newTermOp, ImmutableArray newTermSubs, + ImmutableArray newTermBoundVars, JavaBlock newTermJavaBlock, + Map policies, Set newLabels) { for (Term child : applicationTerm.subs()) { for (TermLabel label : child.getLabels()) { ChildTermLabelPolicy policy = policies.get(label.name()); - if (policy != null - && policy.addLabel(services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - newTermOp, newTermSubs, newTermBoundVars, - newTermJavaBlock, child, label)) { + if (policy != null && policy.addLabel(services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, child, label)) { newLabels.add(label); } } } } - /** - *

    - * Performs the given child and grandchild {@link ChildTermLabelPolicy} instances. - *

    - *

    - * This is a helper {@link Map} of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. - *

    - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newTermOp The new {@link Operator} of the {@link Term} to create. - * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to create. - * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. - * @param policies The {@link ChildTermLabelPolicy} instances to perform. - * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. - */ - protected void performChildAndGrandchildPolicies(final TermServices services, - final PosInOccurrence applicationPosInOccurrence, - final Term applicationTerm, - final Rule rule, - final Goal goal, - final Object hint, - final Term tacletTerm, - final Operator newTermOp, - final ImmutableArray newTermSubs, - final ImmutableArray newTermBoundVars, - final JavaBlock newTermJavaBlock, - final Map policies, - final Set newLabels) { - applicationTerm.execPreOrder(new DefaultVisitor() { - @Override - public void visit(Term visited) { - if (visited != applicationTerm) { - for (TermLabel label : visited.getLabels()) { - ChildTermLabelPolicy policy = policies.get(label.name()); - if (policy != null && policy.addLabel(services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, visited, label)) { - newLabels.add(label); - } - } + /** + *

    + * Performs the given child and grandchild {@link ChildTermLabelPolicy} instances. + *

    + *

    + * This is a helper {@link Map} of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. + *

    + * + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newTermOp The new {@link Operator} of the {@link Term} to create. + * @param newTermSubs The optional children of the {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. + * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. + * @param policies The {@link ChildTermLabelPolicy} instances to perform. + * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. + */ + protected void performChildAndGrandchildPolicies(final TermServices services, + final PosInOccurrence applicationPosInOccurrence, final Term applicationTerm, + final Rule rule, final Goal goal, final Object hint, final Term tacletTerm, + final Operator newTermOp, final ImmutableArray newTermSubs, + final ImmutableArray newTermBoundVars, + final JavaBlock newTermJavaBlock, final Map policies, + final Set newLabels) { + applicationTerm.execPreOrder(new DefaultVisitor() { + @Override + public void visit(Term visited) { + if (visited != applicationTerm) { + for (TermLabel label : visited.getLabels()) { + ChildTermLabelPolicy policy = policies.get(label.name()); + if (policy != null && policy.addLabel(services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, newTermOp, + newTermSubs, newTermBoundVars, newTermJavaBlock, visited, label)) { + newLabels.add(label); + } + } + } } - } - }); - } - - /** - *

    - * Performs the given child and grandchild {@link TermLabelUpdate} instances. - *

    - *

    - * This is a helper {@link Map} of {@link #instantiateLabels( - * TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, - * Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param modalityTerm The optional modality {@link Term}. - * @param rule The {@link Rule} which is applied. - * @param ruleApp The {@link RuleApp} which is currently performed. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate the new {@link Term} for the new proof node or {@code null} in case of built in rules. - * @param newTermOp The new {@link Operator} of the {@link Term} to create. - * @param newTermSubs The optional children of the {@link Term} to create. - * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to create. - * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. - * @param updater The {@link TermLabelUpdate} instances to perform. - * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. - */ - protected void performUpdater(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Term modalityTerm, - Rule rule, - RuleApp ruleApp, - Object hint, - Term tacletTerm, - Operator newTermOp, - ImmutableArray newTermSubs, - ImmutableArray newTermBoundVars, - JavaBlock newTermJavaBlock, - ImmutableList updater, - Set newLabels) { - for (TermLabelUpdate update : updater) { - update.updateLabels(state, services, applicationPosInOccurrence, applicationTerm, modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, newTermSubs, newTermBoundVars, newTermJavaBlock, newLabels); - } - } - - /** - * Refactors all labels on the {@link PosInOccurrence} in the given {@link Term} of a {@link SequentFormula}. - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - * @return The updated application {@link Term}. - */ - public static Term refactorSequentFormula(TermLabelState state, - Services services, - Term sequentFormula, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - return manager.refactorSequentFormula(state, services, sequentFormula, applicationPosInOccurrence, goal, hint, rule, tacletTerm); - } - else { - return sequentFormula; - } - } - - /** - * Refactors all labels on the {@link PosInOccurrence} in the given {@link Term} of a {@link SequentFormula}. - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param rule The {@link Rule} which is applied. - * @param tacletTerm The optional taclet {@link Term}. - * @return The updated application {@link Term}. - */ - public Term refactorSequentFormula(TermLabelState state, - Services services, - Term sequentFormula, - PosInOccurrence applicationPosInOccurrence, - Goal goal, - Object hint, - Rule rule, - Term tacletTerm) { - final PosInTerm pos = applicationPosInOccurrence.posInTerm(); - final Term oldTerm = pos.getSubTerm(sequentFormula); - // Compute active refactorings - RefactoringsContainer refactorings = computeRefactorings(state, services, applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); - // Perform refactoring - Term newTerm = refactorApplicationTerm(state, services, applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm, refactorings, services.getTermFactory()); - if (newTerm != null && !newTerm.equals(oldTerm)) { - return replaceTerm(state, applicationPosInOccurrence, newTerm, services.getTermFactory(), refactorings.getChildAndGrandchildRefactoringsAndParents(), services, applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); - } - else if (!refactorings.getChildAndGrandchildRefactoringsAndParents().isEmpty()) { - return replaceTerm(state, applicationPosInOccurrence, oldTerm, services.getTermFactory(), refactorings.getChildAndGrandchildRefactoringsAndParents(), services, applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); - } - else { - return sequentFormula; - } - } - - /** - *

    - * Refactors all labels in the complete {@link Sequent}. This is the last - * step of each rule application. - *

    - *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - * @return The updated application {@link Term}. - */ - public static Term refactorTerm(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - return manager.refactorTerm(state, services, applicationPosInOccurrence, applicationTerm, goal, hint, rule, tacletTerm); - } - else { - return applicationTerm; - } - } - - /** - * Refactors all labels in the given application {@link Term}. - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param rule The {@link Rule} which is applied. - * @param tacletTerm The optional taclet {@link Term}. - * @return The updated application {@link Term}. - */ - public Term refactorTerm(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Goal goal, - Object hint, - Rule rule, - Term tacletTerm) { - // Compute active refactorings - RefactoringsContainer refactorings = computeRefactorings(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); - // Refactor application term - Term newApplicationTerm = refactorApplicationTerm(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, refactorings, services.getTermFactory()); - return newApplicationTerm != null ? newApplicationTerm : applicationTerm; - } - - /** - *

    - * Refactors all labels in the complete {@link Sequent}. This is the last - * step of each rule application. - *

    - *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - */ - public static void refactorGoal(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - Term applicationTerm = applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; - manager.refactorGoal(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); - } - } + }); + } /** *

    - * Refactors all labels in the complete {@link Sequent}. This is the last - * step of each rule application. + * Performs the given child and grandchild {@link TermLabelUpdate} instances. *

    *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. + * This is a helper {@link Map} of + * {@link #instantiateLabels( TermLabelState, Services, PosInOccurrence, Term, Rule, Goal, Object, Term, Operator, ImmutableArray, ImmutableArray, JavaBlock)}. *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param modalityTerm The optional modality {@link Term}. + * @param rule The {@link Rule} which is applied. + * @param ruleApp The {@link RuleApp} which is currently performed. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional {@link Term} in the taclet which is responsible to instantiate + * the new {@link Term} for the new proof node or {@code null} in case of built in rules. + * @param newTermOp The new {@link Operator} of the {@link Term} to create. + * @param newTermSubs The optional children of the {@link Term} to create. + * @param newTermBoundVars The optional {@link QuantifiableVariable}s of the {@link Term} to + * create. + * @param newTermJavaBlock The optional {@link JavaBlock} of the {@link Term} to create. + * @param updater The {@link TermLabelUpdate} instances to perform. + * @param newLabels The result {@link Set} with the {@link TermLabel}s of the new {@link Term}. + */ + protected void performUpdater(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Term modalityTerm, + Rule rule, RuleApp ruleApp, Object hint, Term tacletTerm, Operator newTermOp, + ImmutableArray newTermSubs, ImmutableArray newTermBoundVars, + JavaBlock newTermJavaBlock, ImmutableList updater, + Set newLabels) { + for (TermLabelUpdate update : updater) { + update.updateLabels(state, services, applicationPosInOccurrence, applicationTerm, + modalityTerm, rule, ruleApp, hint, tacletTerm, newTermOp, newTermSubs, + newTermBoundVars, newTermJavaBlock, newLabels); + } + } + + /** + * Refactors all labels on the {@link PosInOccurrence} in the given {@link Term} of a + * {@link SequentFormula}. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a - * {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + * @return The updated application {@link Term}. + */ + public static Term refactorSequentFormula(TermLabelState state, Services services, + Term sequentFormula, PosInOccurrence applicationPosInOccurrence, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + return manager.refactorSequentFormula(state, services, sequentFormula, + applicationPosInOccurrence, goal, hint, rule, tacletTerm); + } else { + return sequentFormula; + } + } + + /** + * Refactors all labels on the {@link PosInOccurrence} in the given {@link Term} of a + * {@link SequentFormula}. + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param rule The {@link Rule} which is applied. * @param tacletTerm The optional taclet {@link Term}. + * @return The updated application {@link Term}. */ - public void refactorGoal(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { + public Term refactorSequentFormula(TermLabelState state, Services services, Term sequentFormula, + PosInOccurrence applicationPosInOccurrence, Goal goal, Object hint, Rule rule, + Term tacletTerm) { + final PosInTerm pos = applicationPosInOccurrence.posInTerm(); + final Term oldTerm = pos.getSubTerm(sequentFormula); // Compute active refactorings - RefactoringsContainer refactorings = - computeRefactorings(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm); + RefactoringsContainer refactorings = computeRefactorings(state, services, + applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); + // Perform refactoring + Term newTerm = refactorApplicationTerm(state, services, applicationPosInOccurrence, oldTerm, + rule, goal, hint, tacletTerm, refactorings, services.getTermFactory()); + if (newTerm != null && !newTerm.equals(oldTerm)) { + return replaceTerm(state, applicationPosInOccurrence, newTerm, + services.getTermFactory(), + refactorings.getChildAndGrandchildRefactoringsAndParents(), services, + applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); + } else if (!refactorings.getChildAndGrandchildRefactoringsAndParents().isEmpty()) { + return replaceTerm(state, applicationPosInOccurrence, oldTerm, + services.getTermFactory(), + refactorings.getChildAndGrandchildRefactoringsAndParents(), services, + applicationPosInOccurrence, oldTerm, rule, goal, hint, tacletTerm); + } else { + return sequentFormula; + } + } + + /** + *

    + * Refactors all labels in the complete {@link Sequent}. This is the last step of each rule + * application. + *

    + *

    + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + * @return The updated application {@link Term}. + */ + public static Term refactorTerm(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + return manager.refactorTerm(state, services, applicationPosInOccurrence, + applicationTerm, goal, hint, rule, tacletTerm); + } else { + return applicationTerm; + } + } + + /** + * Refactors all labels in the given application {@link Term}. + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param rule The {@link Rule} which is applied. + * @param tacletTerm The optional taclet {@link Term}. + * @return The updated application {@link Term}. + */ + public Term refactorTerm(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Goal goal, + Object hint, Rule rule, Term tacletTerm) { + // Compute active refactorings + RefactoringsContainer refactorings = computeRefactorings(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); + // Refactor application term + Term newApplicationTerm = refactorApplicationTerm(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + refactorings, services.getTermFactory()); + return newApplicationTerm != null ? newApplicationTerm : applicationTerm; + } + + /** + *

    + * Refactors all labels in the complete {@link Sequent}. This is the last step of each rule + * application. + *

    + *

    + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + */ + public static void refactorGoal(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Rule rule, Goal goal, Object hint, + Term tacletTerm) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + Term applicationTerm = + applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() + : null; + manager.refactorGoal(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm); + } + } + + /** + *

    + * Refactors all labels in the complete {@link Sequent}. This is the last step of each rule + * application. + *

    + *

    + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + */ + public void refactorGoal(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + // Compute active refactorings + RefactoringsContainer refactorings = computeRefactorings(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); // Refactor application term final TermFactory tf = services.getTermFactory(); Term newApplicationTerm = refactorApplicationTerm(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - refactorings, tf); + applicationTerm, rule, goal, hint, tacletTerm, refactorings, tf); if (newApplicationTerm != null && !newApplicationTerm.equals(applicationTerm)) { - Term root = - replaceTerm(state, applicationPosInOccurrence, newApplicationTerm, tf, - refactorings.getChildAndGrandchildRefactoringsAndParents(), - services, applicationPosInOccurrence, newApplicationTerm, - rule, goal, hint, tacletTerm); + Term root = replaceTerm(state, applicationPosInOccurrence, newApplicationTerm, tf, + refactorings.getChildAndGrandchildRefactoringsAndParents(), services, + applicationPosInOccurrence, newApplicationTerm, rule, goal, hint, tacletTerm); goal.changeFormula(new SequentFormula(root), applicationPosInOccurrence.topLevel()); } else if (!refactorings.getChildAndGrandchildRefactoringsAndParents().isEmpty()) { - Term root = - replaceTerm(state, applicationPosInOccurrence, applicationTerm, tf, - refactorings.getChildAndGrandchildRefactoringsAndParents(), - services, applicationPosInOccurrence, newApplicationTerm, - rule, goal, hint, tacletTerm); + Term root = replaceTerm(state, applicationPosInOccurrence, applicationTerm, tf, + refactorings.getChildAndGrandchildRefactoringsAndParents(), services, + applicationPosInOccurrence, newApplicationTerm, rule, goal, hint, tacletTerm); goal.changeFormula(new SequentFormula(root), applicationPosInOccurrence.topLevel()); } // Do sequent refactoring if required if (!refactorings.getSequentRefactorings().isEmpty() && goal != null) { Sequent sequent = goal.sequent(); - refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, - rule, goal, hint, tacletTerm, sequent.antecedent(), true, - refactorings.getSequentRefactorings()); - refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, - rule, goal, hint, tacletTerm, sequent.succedent(), false, - refactorings.getSequentRefactorings()); + refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, sequent.antecedent(), true, + refactorings.getSequentRefactorings()); + refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, sequent.succedent(), false, + refactorings.getSequentRefactorings()); + } + } + + /** + *

    + * Refactors all labels in the complete {@link Sequent}. This is the last step of each rule + * application. Only refactorings with scope {@link RefactoringScope#SEQUENT} are performed! + *

    + *

    + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + */ + public static void refactorSequent(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Rule rule, Goal goal, Object hint, + Term tacletTerm) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + Term applicationTerm = + applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() + : null; + manager.refactorSequent(state, services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm); } } - /** - *

    - * Refactors all labels in the complete {@link Sequent}. This is the last - * step of each rule application. Only refactorings with scope - * {@link RefactoringScope#SEQUENT} are performed! - *

    - *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - */ - public static void refactorSequent(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - Term applicationTerm = applicationPosInOccurrence != null ? applicationPosInOccurrence.subTerm() : null; - manager.refactorSequent(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); - } - } - - /** - *

    - * Refactors all labels in the complete {@link Sequent}. This is the last - * step of each rule application. Only refactorings with scope - * {@link RefactoringScope#SEQUENT} are performed! - *

    - *

    - * This method delegates the request to the {@link TermLabelManager} - * of the given {@link Services} if possible. Otherwise no labels are returned. - *

    - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - */ - public void refactorSequent(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { - // Compute active refactorings - RefactoringsContainer refactorings = computeRefactorings(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); - // Do sequent refactoring if required - if (!refactorings.getSequentRefactorings().isEmpty()) { - Sequent sequent = goal.sequent(); - refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, sequent.antecedent(), true, refactorings.getSequentRefactorings()); - refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, sequent.succedent(), false, refactorings.getSequentRefactorings()); - } - } + /** + *

    + * Refactors all labels in the complete {@link Sequent}. This is the last step of each rule + * application. Only refactorings with scope {@link RefactoringScope#SEQUENT} are performed! + *

    + *

    + * This method delegates the request to the {@link TermLabelManager} of the given + * {@link Services} if possible. Otherwise no labels are returned. + *

    + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + */ + public void refactorSequent(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { + // Compute active refactorings + RefactoringsContainer refactorings = computeRefactorings(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); + // Do sequent refactoring if required + if (!refactorings.getSequentRefactorings().isEmpty()) { + Sequent sequent = goal.sequent(); + refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, sequent.antecedent(), true, + refactorings.getSequentRefactorings()); + refactorSemisequent(state, services, applicationPosInOccurrence, applicationTerm, rule, + goal, hint, tacletTerm, sequent.succedent(), false, + refactorings.getSequentRefactorings()); + } + } /** * Replaces the {@link Term} at the specified {@link PosInOccurrence}. + * * @param state The {@link TermLabelState} of the current rule application. * @param pio The {@link PosInOccurrence} to replace {@link Term} at. * @param newTerm The new {@link Term} to set. * @param tf The {@link TermFactory} to use. * @param parentRefactorings The {@link RefactoringsContainer} to consider. - * @param services The {@link Services} used by the {@link Proof} on which a - * {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @return The root of the {@link PosInOccurrence} containing the new {@link Term} - * at the specified {@link PosInOccurrence}. + * @return The root of the {@link PosInOccurrence} containing the new {@link Term} at the + * specified {@link PosInOccurrence}. */ - protected Term replaceTerm(TermLabelState state, - PosInOccurrence pio, - Term newTerm, - TermFactory tf, - ImmutableList parentRefactorings, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { + protected Term replaceTerm(TermLabelState state, PosInOccurrence pio, Term newTerm, + TermFactory tf, ImmutableList parentRefactorings, + Services services, PosInOccurrence applicationPosInOccurrence, Term applicationTerm, + Rule rule, Goal goal, Object hint, Term tacletTerm) { do { if (pio.isTopLevel()) { pio = null; @@ -1468,10 +1392,9 @@ protected Term replaceTerm(TermLabelState state, newTerm = pio.subTerm(); ImmutableArray newLabels; if (!parentRefactorings.isEmpty()) { - newLabels = - performRefactoring(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - newTerm, parentRefactorings); + newLabels = performRefactoring(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, newTerm, + parentRefactorings); } else { newLabels = newTerm.getLabels(); } @@ -1481,9 +1404,8 @@ protected Term replaceTerm(TermLabelState state, if (!newSubsImmutable.equals(newTerm.subs()) || !newLabels.equals(newTerm.getLabels())) { - newTerm = tf.createTerm(newTerm.op(), newSubsImmutable, - newTerm.boundVars(), newTerm.javaBlock(), - newLabels); + newTerm = tf.createTerm(newTerm.op(), newSubsImmutable, newTerm.boundVars(), + newTerm.javaBlock(), newLabels); } } } while (pio != null); @@ -1492,31 +1414,27 @@ protected Term replaceTerm(TermLabelState state, /** * Computes the rule-independent {@link TermLabelRefactoring} to consider. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the - * term which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. * @param refactorings The already accumulated refactorings - * @return The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @return The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s to consider. */ - private RefactoringsContainer - computeRuleSpecificRefactorings(TermLabelState state, Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, - RefactoringsContainer refactorings) { - ImmutableList sequentRefactorings = - refactorings.sequentRefactorings; + private RefactoringsContainer computeRuleSpecificRefactorings(TermLabelState state, + Services services, PosInOccurrence applicationPosInOccurrence, Term applicationTerm, + Rule rule, Goal goal, Object hint, Term tacletTerm, + RefactoringsContainer refactorings) { + ImmutableList sequentRefactorings = refactorings.sequentRefactorings; ImmutableList belowUpdatesRefactorings = refactorings.belowUpdatesRefactorings; ImmutableList childAndGrandchildRefactorings = @@ -1530,11 +1448,9 @@ protected Term replaceTerm(TermLabelState state, ruleSpecificRefactorings.get(rule.name()); if (ruleRefactorings != null) { for (TermLabelRefactoring refactoring : ruleRefactorings) { - RefactoringScope scope = - refactoring.defineRefactoringScope(state, services, - applicationPosInOccurrence, - applicationTerm, rule, goal, - hint, tacletTerm); + RefactoringScope scope = refactoring.defineRefactoringScope(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, + tacletTerm); if (RefactoringScope.SEQUENT.equals(scope)) { sequentRefactorings = sequentRefactorings.prepend(refactoring); } else if (RefactoringScope.APPLICATION_BELOW_UPDATES.equals(scope)) { @@ -1545,8 +1461,7 @@ protected Term replaceTerm(TermLabelState state, childAndGrandchildRefactorings.prepend(refactoring); } else if (RefactoringScope.APPLICATION_DIRECT_CHILDREN.equals(scope)) { directChildRefactorings = directChildRefactorings.prepend(refactoring); - } else if (RefactoringScope - .APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS + } else if (RefactoringScope.APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS .equals(scope)) { childAndGrandchildRefactoringsAndParents = childAndGrandchildRefactoringsAndParents.prepend(refactoring); @@ -1555,45 +1470,37 @@ protected Term replaceTerm(TermLabelState state, } } return new RefactoringsContainer( - refactorings.sequentRefactorings - .prepend(sequentRefactorings), - refactorings.belowUpdatesRefactorings - .prepend(belowUpdatesRefactorings), - refactorings.childAndGrandchildRefactorings - .prepend(childAndGrandchildRefactorings), + refactorings.sequentRefactorings.prepend(sequentRefactorings), + refactorings.belowUpdatesRefactorings.prepend(belowUpdatesRefactorings), + refactorings.childAndGrandchildRefactorings.prepend(childAndGrandchildRefactorings), refactorings.childAndGrandchildRefactoringsAndParents - .prepend(childAndGrandchildRefactoringsAndParents), - refactorings.directChildRefactorings - .prepend(directChildRefactorings)); + .prepend(childAndGrandchildRefactoringsAndParents), + refactorings.directChildRefactorings.prepend(directChildRefactorings)); } /** * Computes the rule-independent {@link TermLabelRefactoring} to consider. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the - * term which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. * @param refactorings The already accumulated refactorings - * @return The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @return The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s to consider. */ - private RefactoringsContainer - computeRuleIndependentRefactorings(TermLabelState state, Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, - RefactoringsContainer refactorings) { - ImmutableList sequentRefactorings2 = - refactorings.sequentRefactorings; + private RefactoringsContainer computeRuleIndependentRefactorings(TermLabelState state, + Services services, PosInOccurrence applicationPosInOccurrence, Term applicationTerm, + Rule rule, Goal goal, Object hint, Term tacletTerm, + RefactoringsContainer refactorings) { + ImmutableList sequentRefactorings2 = refactorings.sequentRefactorings; ImmutableList belowUpdatesRefactorings2 = refactorings.belowUpdatesRefactorings; ImmutableList childAndGrandchildRefactorings2 = @@ -1603,10 +1510,8 @@ protected Term replaceTerm(TermLabelState state, ImmutableList childAndGrandchildRefactoringsAndParents2 = refactorings.childAndGrandchildRefactorings; for (TermLabelRefactoring refactoring : allRulesRefactorings) { - RefactoringScope scope = - refactoring.defineRefactoringScope(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm); + RefactoringScope scope = refactoring.defineRefactoringScope(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm); if (RefactoringScope.SEQUENT.equals(scope)) { sequentRefactorings2 = sequentRefactorings2.prepend(refactoring); } else if (RefactoringScope.APPLICATION_BELOW_UPDATES.equals(scope)) { @@ -1624,205 +1529,210 @@ protected Term replaceTerm(TermLabelState state, } } return new RefactoringsContainer(sequentRefactorings2, belowUpdatesRefactorings2, - childAndGrandchildRefactorings2, - childAndGrandchildRefactoringsAndParents2, - directChildRefactorings2); + childAndGrandchildRefactorings2, childAndGrandchildRefactoringsAndParents2, + directChildRefactorings2); } /** * Computes the {@link TermLabelRefactoring} to consider. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} - * is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the - * term which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @return The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @return The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s to consider. */ - protected RefactoringsContainer computeRefactorings(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm) { + protected RefactoringsContainer computeRefactorings(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm) { RefactoringsContainer refactorings = new RefactoringsContainer(ImmutableSLList.nil(), ImmutableSLList.nil(), - ImmutableSLList.nil(), ImmutableSLList.nil(), - ImmutableSLList.nil()); + ImmutableSLList.nil(), ImmutableSLList.nil(), ImmutableSLList.nil()); + refactorings = computeRuleSpecificRefactorings(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, refactorings); refactorings = - computeRuleSpecificRefactorings(state, services, - applicationPosInOccurrence, - applicationTerm, rule, goal, - hint, tacletTerm, refactorings); - refactorings = - computeRuleIndependentRefactorings(state, services, - applicationPosInOccurrence, - applicationTerm, rule, goal, - hint, tacletTerm, refactorings); + computeRuleIndependentRefactorings(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, refactorings); return refactorings; } - /** - * Utility class used by {@link TermLabelManager#computeRefactorings( - * TermLabelState, TermServices, PosInOccurrence, Term, Rule, Goal, - * Term)}. - * @author Martin Hentschel - */ - protected static class RefactoringsContainer { - /** - * The {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. - */ - private final ImmutableList sequentRefactorings; - - /** - * The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. - */ - private final ImmutableList belowUpdatesRefactorings; - - /** - * The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. - */ - private final ImmutableList childAndGrandchildRefactorings; - - /** - * The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. - */ - private final ImmutableList childAndGrandchildRefactoringsAndParents; - - /** - * The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. - */ - private final ImmutableList directChildRefactorings; - - /** - * Constructor. - * @param sequentRefactorings The {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. - * @param belowUpdatesRefactorings The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. - * @param childAndGrandchildRefactorings The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. - * @param childAndGrandchildRefactoringsAndParents The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. - * @param directChildRefactorings The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. - */ - public RefactoringsContainer(ImmutableList sequentRefactorings, - ImmutableList belowUpdatesRefactorings, - ImmutableList childAndGrandchildRefactorings, - ImmutableList childAndGrandchildRefactoringsAndParents, - ImmutableList directChildRefactorings) { - this.sequentRefactorings = sequentRefactorings; - this.belowUpdatesRefactorings = belowUpdatesRefactorings; - this.childAndGrandchildRefactorings = childAndGrandchildRefactorings; - this.childAndGrandchildRefactoringsAndParents = childAndGrandchildRefactoringsAndParents; - this.directChildRefactorings = directChildRefactorings; - } - - /** - * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. - * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. - */ - public ImmutableList getSequentRefactorings() { - return sequentRefactorings; - } - - /** - * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. - * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. - */ - public ImmutableList getChildAndGrandchildRefactorings() { - return childAndGrandchildRefactorings; - } - - /** - * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. - * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. - */ - public ImmutableList getChildAndGrandchildRefactoringsAndParents() { - return childAndGrandchildRefactoringsAndParents; - } - - /** - * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. - * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. - */ - public ImmutableList getDirectChildRefactorings() { - return directChildRefactorings; - } - - /** - * Returns all {@link TermLabelRefactoring}s which operate on application child and grand children, - * which are {@link #getChildAndGrandchildRefactorings()} and {@link #getChildAndGrandchildRefactoringsAndParents()}. - * @return The combined {@link ImmutableList}. - */ - public ImmutableList getAllApplicationChildAndGrandchildRefactorings() { - return childAndGrandchildRefactorings.prepend(childAndGrandchildRefactoringsAndParents); - } - - /** - * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. - * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. - */ - public ImmutableList getBelowUpdatesRefactorings() { - return belowUpdatesRefactorings; - } - } + /** + * Utility class used by + * {@link TermLabelManager#computeRefactorings( TermLabelState, TermServices, PosInOccurrence, Term, Rule, Goal, Term)}. + * + * @author Martin Hentschel + */ + protected static class RefactoringsContainer { + /** + * The {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. + */ + private final ImmutableList sequentRefactorings; + + /** + * The {@link TermLabelRefactoring} for {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. + */ + private final ImmutableList belowUpdatesRefactorings; + + /** + * The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. + */ + private final ImmutableList childAndGrandchildRefactorings; + + /** + * The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. + */ + private final ImmutableList childAndGrandchildRefactoringsAndParents; + + /** + * The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. + */ + private final ImmutableList directChildRefactorings; + + /** + * Constructor. + * + * @param sequentRefactorings The {@link TermLabelRefactoring} for + * {@link RefactoringScope#SEQUENT}. + * @param belowUpdatesRefactorings The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. + * @param childAndGrandchildRefactorings The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. + * @param childAndGrandchildRefactoringsAndParents The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. + * @param directChildRefactorings The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. + */ + public RefactoringsContainer(ImmutableList sequentRefactorings, + ImmutableList belowUpdatesRefactorings, + ImmutableList childAndGrandchildRefactorings, + ImmutableList childAndGrandchildRefactoringsAndParents, + ImmutableList directChildRefactorings) { + this.sequentRefactorings = sequentRefactorings; + this.belowUpdatesRefactorings = belowUpdatesRefactorings; + this.childAndGrandchildRefactorings = childAndGrandchildRefactorings; + this.childAndGrandchildRefactoringsAndParents = + childAndGrandchildRefactoringsAndParents; + this.directChildRefactorings = directChildRefactorings; + } + + /** + * Returns the {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. + * + * @return The {@link TermLabelRefactoring} for {@link RefactoringScope#SEQUENT}. + */ + public ImmutableList getSequentRefactorings() { + return sequentRefactorings; + } + + /** + * Returns the {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. + * + * @return The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE}. + */ + public ImmutableList getChildAndGrandchildRefactorings() { + return childAndGrandchildRefactorings; + } + + /** + * Returns the {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. + * + * @return The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_CHILDREN_AND_GRANDCHILDREN_SUBTREE_AND_PARENTS}. + */ + public ImmutableList getChildAndGrandchildRefactoringsAndParents() { + return childAndGrandchildRefactoringsAndParents; + } + + /** + * Returns the {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. + * + * @return The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_DIRECT_CHILDREN}. + */ + public ImmutableList getDirectChildRefactorings() { + return directChildRefactorings; + } + + /** + * Returns all {@link TermLabelRefactoring}s which operate on application child and grand + * children, which are {@link #getChildAndGrandchildRefactorings()} and + * {@link #getChildAndGrandchildRefactoringsAndParents()}. + * + * @return The combined {@link ImmutableList}. + */ + public ImmutableList getAllApplicationChildAndGrandchildRefactorings() { + return childAndGrandchildRefactorings.prepend(childAndGrandchildRefactoringsAndParents); + } + + /** + * Returns the {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. + * + * @return The {@link TermLabelRefactoring} for + * {@link RefactoringScope#APPLICATION_BELOW_UPDATES}. + */ + public ImmutableList getBelowUpdatesRefactorings() { + return belowUpdatesRefactorings; + } + } /** * Do direct child refactoring if required. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @param refactorings The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @param refactorings The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s + * to consider. * @param tf The {@link TermFactory} to create the term. * @return The new application {@link Term} or {@code null} if no refactoring was performed. */ private Term refactorChildTerms(TermLabelState state, Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, - RefactoringsContainer refactorings, - TermFactory tf) { + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, RefactoringsContainer refactorings, TermFactory tf) { Term newApplicationTerm = applicationTerm; if (!refactorings.getDirectChildRefactorings().isEmpty()) { boolean changed = false; Term[] newSubs = new Term[newApplicationTerm.arity()]; for (int i = 0; i < newSubs.length; i++) { Term sub = newApplicationTerm.sub(i); - ImmutableArray newLabels = - performRefactoring(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - sub, refactorings.getDirectChildRefactorings()); - newSubs[i] = tf.createTerm(sub.op(), sub.subs(), sub.boundVars(), - sub.javaBlock(), newLabels); + ImmutableArray newLabels = performRefactoring(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + sub, refactorings.getDirectChildRefactorings()); + newSubs[i] = tf.createTerm(sub.op(), sub.subs(), sub.boundVars(), sub.javaBlock(), + newLabels); if (!newSubs[i].equals(sub)) { changed = true; } } - newApplicationTerm = changed ? - tf.createTerm(newApplicationTerm.op(), newSubs, - newApplicationTerm.boundVars(), - newApplicationTerm.javaBlock(), - newApplicationTerm.getLabels()) : - applicationTerm; + newApplicationTerm = changed ? tf.createTerm(newApplicationTerm.op(), newSubs, + newApplicationTerm.boundVars(), newApplicationTerm.javaBlock(), + newApplicationTerm.getLabels()) : applicationTerm; } return newApplicationTerm; } @@ -1830,50 +1740,43 @@ private Term refactorChildTerms(TermLabelState state, Services services, /** * Do below updates refactoring if required. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @param refactorings The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @param refactorings The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s + * to consider. * @param tf The {@link TermFactory} to create the term. * @param newApplicationTerm The refactored application term until now. * @return The new application {@link Term} or {@code null} if no refactoring was performed. */ private Term refactorBelowUpdates(TermLabelState state, Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, - RefactoringsContainer refactorings, - TermFactory tf, Term newApplicationTerm) { + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, RefactoringsContainer refactorings, TermFactory tf, + Term newApplicationTerm) { if (!refactorings.getBelowUpdatesRefactorings().isEmpty()) { - Pair, Term> pair = - TermBuilder.goBelowUpdates2(newApplicationTerm); - ImmutableArray newLabels = - performRefactoring(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, pair.second, - refactorings.getBelowUpdatesRefactorings()); + Pair, Term> pair = TermBuilder.goBelowUpdates2(newApplicationTerm); + ImmutableArray newLabels = performRefactoring(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + pair.second, refactorings.getBelowUpdatesRefactorings()); if (!newLabels.equals(pair.second.getLabels())) { Term newModality = tf.createTerm(pair.second.op(), pair.second.subs(), - pair.second.boundVars(), - pair.second.javaBlock(), newLabels); + pair.second.boundVars(), pair.second.javaBlock(), newLabels); ImmutableArray applicationLabels = newApplicationTerm.getLabels(); newApplicationTerm = services.getTermBuilder().applyParallel(pair.first, newModality); if (!applicationLabels.isEmpty()) { - newApplicationTerm = - services.getTermBuilder().addLabel(newApplicationTerm, - applicationLabels); + newApplicationTerm = services.getTermBuilder().addLabel(newApplicationTerm, + applicationLabels); } } } @@ -1882,32 +1785,29 @@ private Term refactorBelowUpdates(TermLabelState state, Services services, /** * Do child and grandchild refactoring if required. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @param refactorings The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @param refactorings The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s + * to consider. * @param tf The {@link TermFactory} to create the term. * @param newApplicationTerm The refactored application term until now. * @return The new application {@link Term} or {@code null} if no refactoring was performed. */ - private Term refactorChildrenRecursively(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, Rule rule, Goal goal, - Object hint, Term tacletTerm, - RefactoringsContainer refactorings, - TermFactory tf, Term newApplicationTerm) { + private Term refactorChildrenRecursively(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, RefactoringsContainer refactorings, TermFactory tf, + Term newApplicationTerm) { ImmutableList allChildAndGrandchildRefactorings = refactorings.getAllApplicationChildAndGrandchildRefactorings(); if (!allChildAndGrandchildRefactorings.isEmpty()) { @@ -1915,22 +1815,16 @@ private Term refactorChildrenRecursively(TermLabelState state, Term[] newSubs = new Term[newApplicationTerm.arity()]; for (int i = 0; i < newSubs.length; i++) { Term sub = newApplicationTerm.sub(i); - newSubs[i] = - refactorLabelsRecursive(state, services, - applicationPosInOccurrence, - applicationTerm, rule, goal, - hint, tacletTerm, sub, - allChildAndGrandchildRefactorings); + newSubs[i] = refactorLabelsRecursive(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, sub, + allChildAndGrandchildRefactorings); if (!newSubs[i].equals(sub)) { changed = true; } } - newApplicationTerm = - changed ? tf.createTerm(newApplicationTerm.op(), newSubs, - newApplicationTerm.boundVars(), - newApplicationTerm.javaBlock(), - newApplicationTerm.getLabels()) - : newApplicationTerm; + newApplicationTerm = changed ? tf.createTerm(newApplicationTerm.op(), newSubs, + newApplicationTerm.boundVars(), newApplicationTerm.javaBlock(), + newApplicationTerm.getLabels()) : newApplicationTerm; } return newApplicationTerm; } @@ -1938,175 +1832,144 @@ private Term refactorChildrenRecursively(TermLabelState state, /** * Refactors the labels of the application term. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in - * the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. - * @param refactorings The {@link RefactoringsContainer} with the - * {@link TermLabelRefactoring}s to consider. + * @param refactorings The {@link RefactoringsContainer} with the {@link TermLabelRefactoring}s + * to consider. * @param tf The {@link TermFactory} to create the term. * @return The new application {@link Term} or {@code null} if no refactoring was performed. */ - protected Term refactorApplicationTerm(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - RefactoringsContainer refactorings, - TermFactory tf) { - if (applicationTerm != null && - (!refactorings.getDirectChildRefactorings().isEmpty() || - !refactorings.getChildAndGrandchildRefactorings().isEmpty() || - !refactorings.getBelowUpdatesRefactorings().isEmpty())) { + protected Term refactorApplicationTerm(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, RefactoringsContainer refactorings, TermFactory tf) { + if (applicationTerm != null && (!refactorings.getDirectChildRefactorings().isEmpty() + || !refactorings.getChildAndGrandchildRefactorings().isEmpty() + || !refactorings.getBelowUpdatesRefactorings().isEmpty())) { Term newApplicationTerm = applicationTerm; // Do direct child refactoring if required - newApplicationTerm = - refactorChildTerms(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, - tacletTerm, refactorings, tf); + newApplicationTerm = refactorChildTerms(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, refactorings, tf); // Do below updates refactoring - newApplicationTerm = - refactorBelowUpdates(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - refactorings, tf, newApplicationTerm); + newApplicationTerm = refactorBelowUpdates(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, refactorings, tf, + newApplicationTerm); // Do child and grandchild refactoring if required - newApplicationTerm = - refactorChildrenRecursively(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - refactorings, tf, newApplicationTerm); + newApplicationTerm = refactorChildrenRecursively(state, services, + applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, + refactorings, tf, newApplicationTerm); return newApplicationTerm; } else { return null; } } - /** - * Performs a {@link TermLabel} refactoring on the given {@link Semisequent}. - * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} which defines the {@link Term} that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the previous {@link Sequent}. - * @param rule The {@link Rule} which is applied. - * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term which should be created. - * @param tacletTerm The optional taclet {@link Term}. - * @param semisequent The {@link Semisequent} to refactor. - * @param inAntec {@code true} antecedent, {@code false} succedent. - * @param activeRefactorings The active {@link TermLabelRefactoring}s to execute. - */ - protected void refactorSemisequent(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Semisequent semisequent, - boolean inAntec, - ImmutableList activeRefactorings) { - for (SequentFormula sfa : semisequent) { - Term updatedTerm = refactorLabelsRecursive(state, services, applicationPosInOccurrence, applicationTerm, rule, goal, hint, tacletTerm, sfa.formula(), activeRefactorings); - goal.changeFormula(new SequentFormula(updatedTerm), - new PosInOccurrence(sfa, PosInTerm.getTopLevel(), inAntec)); - } - } + /** + * Performs a {@link TermLabel} refactoring on the given {@link Semisequent}. + * + * @param state The {@link TermLabelState} of the current rule application. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. + * @param rule The {@link Rule} which is applied. + * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. + * @param tacletTerm The optional taclet {@link Term}. + * @param semisequent The {@link Semisequent} to refactor. + * @param inAntec {@code true} antecedent, {@code false} succedent. + * @param activeRefactorings The active {@link TermLabelRefactoring}s to execute. + */ + protected void refactorSemisequent(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Semisequent semisequent, boolean inAntec, + ImmutableList activeRefactorings) { + for (SequentFormula sfa : semisequent) { + Term updatedTerm = refactorLabelsRecursive(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, sfa.formula(), + activeRefactorings); + goal.changeFormula(new SequentFormula(updatedTerm), + new PosInOccurrence(sfa, PosInTerm.getTopLevel(), inAntec)); + } + } /** * Performs a {@link TermLabel} refactoring recursively on the given {@link Term}. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. * @param term The {@link Term} to refactor. * @param activeRefactorings The active {@link TermLabelRefactoring}s to execute. * @return The refactored {@link Term} in which the {@link TermLabel}s may have changed. */ - protected Term - refactorLabelsRecursive(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Term term, - ImmutableList activeRefactorings) { + protected Term refactorLabelsRecursive(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Term term, + ImmutableList activeRefactorings) { boolean subsChanged = false; Term[] newSubs = new Term[term.arity()]; for (int i = 0; i < newSubs.length; i++) { Term oldSub = term.sub(i); - newSubs[i] = - refactorLabelsRecursive(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - oldSub, activeRefactorings); + newSubs[i] = refactorLabelsRecursive(state, services, applicationPosInOccurrence, + applicationTerm, rule, goal, hint, tacletTerm, oldSub, activeRefactorings); if (!newSubs[i].equals(oldSub)) { subsChanged = true; } } ImmutableArray newLabels = - performRefactoring(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - term, activeRefactorings); - return subsChanged || !newLabels.equals(term.getLabels()) ? - services.getTermFactory().createTerm(term.op(), newSubs, - term.boundVars(), term.javaBlock(), - newLabels) + performRefactoring(state, services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm, term, activeRefactorings); + return subsChanged || !newLabels.equals(term.getLabels()) ? services.getTermFactory() + .createTerm(term.op(), newSubs, term.boundVars(), term.javaBlock(), newLabels) : term; } /** * Computes the new labels as part of the refactoring for the given {@link Term}. + * * @param state The {@link TermLabelState} of the current rule application. - * @param services The {@link Services} used by the {@link Proof} on which - * a {@link Rule} is applied right now. - * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous - * {@link Sequent} which defines the {@link Term} - * that is rewritten. - * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} - * in the previous {@link Sequent}. + * @param services The {@link Services} used by the {@link Proof} on which a {@link Rule} is + * applied right now. + * @param applicationPosInOccurrence The {@link PosInOccurrence} in the previous {@link Sequent} + * which defines the {@link Term} that is rewritten. + * @param applicationTerm The {@link Term} defined by the {@link PosInOccurrence} in the + * previous {@link Sequent}. * @param rule The {@link Rule} which is applied. * @param goal The optional {@link Goal} on which the {@link Term} to create will be used. - * @param hint An optional hint passed from the active rule to describe the term - * which should be created. + * @param hint An optional hint passed from the active rule to describe the term which should be + * created. * @param tacletTerm The optional taclet {@link Term}. * @param term The {@link Term} to refactor. * @param activeRefactorings The active {@link TermLabelRefactoring}s to execute. * @return The new {@link TermLabel} which should be used for the given {@link Term}. */ - protected ImmutableArray - performRefactoring(TermLabelState state, - Services services, - PosInOccurrence applicationPosInOccurrence, - Term applicationTerm, - Rule rule, - Goal goal, - Object hint, - Term tacletTerm, - Term term, - ImmutableList activeRefactorings) { + protected ImmutableArray performRefactoring(TermLabelState state, Services services, + PosInOccurrence applicationPosInOccurrence, Term applicationTerm, Rule rule, Goal goal, + Object hint, Term tacletTerm, Term term, + ImmutableList activeRefactorings) { // Create list with all old labels List newLabels = new LinkedList(); for (TermLabel oldLabel : term.getLabels()) { @@ -2115,236 +1978,259 @@ protected void refactorSemisequent(TermLabelState state, // Give all TermLabelInstantiator instances the chance to remove or to // add labels from/to the list for (TermLabelRefactoring refactoring : activeRefactorings) { - refactoring.refactorLabels(state, services, applicationPosInOccurrence, - applicationTerm, rule, goal, hint, tacletTerm, - term, newLabels); + refactoring.refactorLabels(state, services, applicationPosInOccurrence, applicationTerm, + rule, goal, hint, tacletTerm, term, newLabels); } return new ImmutableArray(newLabels); } - /** - * Instances of this class are used to group everything which is required - * to support one specific {@link TermLabel}. - * @author Martin Hentschel - */ - public static final class TermLabelConfiguration { - /** - * The {@link Name} of the supported {@link TermLabel}. - */ - private final Name termLabelName; - - /** - * The {@link TermLabelFactory} to use. - */ - private final TermLabelFactory factory; - - /** - * The {@link TermLabelPolicy} instances applied on the application term. - */ - private final ImmutableList applicationTermPolicies; - - /** - * The {@link TermLabelPolicy} instances applied on the modality term. - */ - private final ImmutableList modalityTermPolicies; - - /** - * The direct {@link ChildTermLabelPolicy} instances to use. - */ - private final ImmutableList directChildTermLabelPolicies; - - /** - * The child and grandchild {@link ChildTermLabelPolicy} instances to use. - */ - private final ImmutableList childAndGrandchildTermLabelPolicies; - - /** - * The {@link TermLabelUpdate} instances. - */ - private final ImmutableList termLabelUpdates; - - /** - * The {@link TermLabelRefactoring} instances. - */ - private final ImmutableList termLabelRefactorings; - - /** - * The {@link TermLabelMerger} instance. - */ - private final TermLabelMerger termLabelMerger; - - /** - * Constructor. - * @param termLabelName The {@link Name} of the supported {@link TermLabel}. - * @param factory The {@link TermLabelFactory} to use. - */ - public TermLabelConfiguration(Name termLabelName, TermLabelFactory factory) { - this(termLabelName, factory, null, null, null, null, null, null, null); - } - - /** - * Constructor. - * @param termLabelName The {@link Name} of the supported {@link TermLabel}. - * @param factory The {@link TermLabelFactory} to use. - * @param applicationTermPolicies The {@link TermLabelPolicy} instances applied on the application term. - * @param modalityTermPolicies The {@link TermLabelPolicy} instances applied on the modality term. - * @param directChildTermLabelPolicies The direct {@link ChildTermLabelPolicy} instances to use. - * @param childAndGrandchildTermLabelPolicies The child and grandchild {@link ChildTermLabelPolicy} instances to use. - * @param termLabelUpdates The {@link TermLabelUpdate} instances. - * @param termLabelRefactorings The {@link TermLabelRefactoring} instances. - * @param termLabelMerger The {@link TermLabelMerger} instance. - */ - public TermLabelConfiguration(Name termLabelName, - TermLabelFactory factory, - ImmutableList applicationTermPolicies, - ImmutableList modalityTermPolicies, - ImmutableList directChildTermLabelPolicies, - ImmutableList childAndGrandchildTermLabelPolicies, - ImmutableList termLabelUpdates, - ImmutableList termLabelRefactorings, - TermLabelMerger termLabelMerger) { - assert termLabelName != null; - assert factory != null; - this.termLabelName = termLabelName; - this.factory = factory; - this.applicationTermPolicies = applicationTermPolicies; - this.modalityTermPolicies = modalityTermPolicies; - this.directChildTermLabelPolicies = directChildTermLabelPolicies; - this.childAndGrandchildTermLabelPolicies = childAndGrandchildTermLabelPolicies; - this.termLabelUpdates = termLabelUpdates; - this.termLabelRefactorings = termLabelRefactorings; - this.termLabelMerger = termLabelMerger; - } - - /** - * Returns the {@link Name} of the supported {@link TermLabel}. - * @return The {@link Name} of the supported {@link TermLabel}. - */ - public Name getTermLabelName() { - return termLabelName; - } - - /** - * Returns the {@link TermLabelFactory} to use. - * @return The {@link TermLabelFactory} to use. - */ - public TermLabelFactory getFactory() { - return factory; - } - - /** - * Returns the {@link TermLabelPolicy} instances applied on the application term. - * @return The {@link TermLabelPolicy} instances applied on the application term. - */ - public ImmutableList getApplicationTermPolicies() { - return applicationTermPolicies; - } - - /** - * Returns the {@link TermLabelPolicy} instances applied on the modality term. - * @return The {@link TermLabelPolicy} instances applied on the modality term. - */ - public ImmutableList getModalityTermPolicies() { - return modalityTermPolicies; - } - - /** - * Returns the direct {@link ChildTermLabelPolicy} instances to use. - * @return The direct {@link ChildTermLabelPolicy} instances to use. - */ - public ImmutableList getDirectChildTermLabelPolicies() { - return directChildTermLabelPolicies; - } - - /** - * Returns the child and grandchild {@link ChildTermLabelPolicy} instances to use. - * @return The child and grandchild {@link ChildTermLabelPolicy} instances to use. - */ - public ImmutableList getChildAndGrandchildTermLabelPolicies() { - return childAndGrandchildTermLabelPolicies; - } - - /** - * Returns the {@link TermLabelUpdate} instances. - * @return The {@link TermLabelUpdate} instances. - */ - public ImmutableList getTermLabelUpdates() { - return termLabelUpdates; - } - - /** - * Returns the {@link TermLabelRefactoring} instances. - * @return The {@link TermLabelRefactoring} instances. - */ - public ImmutableList getTermLabelRefactorings() { - return termLabelRefactorings; - } - - /** - * Returns the {@link TermLabelMerger} instance. - * @return The {@link TermLabelMerger} instance. - */ - public TermLabelMerger getTermLabelMerger() { - return termLabelMerger; - } - } - - /** - * Searches the inner most {@link TermLabel} wit the given {@link Name} in the parent hierarchy of the {@link PosInOccurrence}. - * @param pio The {@link PosInOccurrence} to search in. - * @param termLabelName The {@link Name} of the {@link TermLabel} to search. - * @return The found {@link TermLabel} or {@code null} if not available. - */ - public static TermLabel findInnerMostParentLabel(PosInOccurrence pio, Name termLabelName) { - TermLabel label = null; - while (label == null && pio != null) { - Term subTerm = pio.subTerm(); - label = subTerm.getLabel(termLabelName); - pio = pio.isTopLevel() ? null : pio.up(); - } - return label; - } - - /** - * Merges the {@link TermLabel}s of the rejected {@link SequentFormula}s into the resulting {@link Sequent}. - * @param currentSequent The {@link SequentChangeInfo} which lists the rejected {@link SequentFormula}s. - * @param services The {@link Services} to use. - */ - public static void mergeLabels(SequentChangeInfo currentSequent, Services services) { - TermLabelManager manager = getTermLabelManager(services); - if (manager != null) { - manager.mergeLabels(services, currentSequent); - } - } - - /** - * Merges the {@link TermLabel}s of the rejected {@link SequentFormula}s into the resulting {@link Sequent}. - * @param services The {@link Services} to use. - * @param currentSequent The {@link SequentChangeInfo} which lists the rejected {@link SequentFormula}s. - */ - public void mergeLabels(Services services, SequentChangeInfo currentSequent) { - for (SequentFormula rejectedSF : currentSequent.getSemisequentChangeInfo(true).rejectedFormulas()) { - mergeLabels(currentSequent, services, rejectedSF, true); - } - for (final SequentFormula rejectedSF : currentSequent.getSemisequentChangeInfo(false).rejectedFormulas()) { - mergeLabels(currentSequent, services, rejectedSF, false); - } - } + /** + * Instances of this class are used to group everything which is required to support one + * specific {@link TermLabel}. + * + * @author Martin Hentschel + */ + public static final class TermLabelConfiguration { + /** + * The {@link Name} of the supported {@link TermLabel}. + */ + private final Name termLabelName; + + /** + * The {@link TermLabelFactory} to use. + */ + private final TermLabelFactory factory; + + /** + * The {@link TermLabelPolicy} instances applied on the application term. + */ + private final ImmutableList applicationTermPolicies; + + /** + * The {@link TermLabelPolicy} instances applied on the modality term. + */ + private final ImmutableList modalityTermPolicies; + + /** + * The direct {@link ChildTermLabelPolicy} instances to use. + */ + private final ImmutableList directChildTermLabelPolicies; + + /** + * The child and grandchild {@link ChildTermLabelPolicy} instances to use. + */ + private final ImmutableList childAndGrandchildTermLabelPolicies; + + /** + * The {@link TermLabelUpdate} instances. + */ + private final ImmutableList termLabelUpdates; + + /** + * The {@link TermLabelRefactoring} instances. + */ + private final ImmutableList termLabelRefactorings; + + /** + * The {@link TermLabelMerger} instance. + */ + private final TermLabelMerger termLabelMerger; + + /** + * Constructor. + * + * @param termLabelName The {@link Name} of the supported {@link TermLabel}. + * @param factory The {@link TermLabelFactory} to use. + */ + public TermLabelConfiguration(Name termLabelName, TermLabelFactory factory) { + this(termLabelName, factory, null, null, null, null, null, null, null); + } + + /** + * Constructor. + * + * @param termLabelName The {@link Name} of the supported {@link TermLabel}. + * @param factory The {@link TermLabelFactory} to use. + * @param applicationTermPolicies The {@link TermLabelPolicy} instances applied on the + * application term. + * @param modalityTermPolicies The {@link TermLabelPolicy} instances applied on the modality + * term. + * @param directChildTermLabelPolicies The direct {@link ChildTermLabelPolicy} instances to + * use. + * @param childAndGrandchildTermLabelPolicies The child and grandchild + * {@link ChildTermLabelPolicy} instances to use. + * @param termLabelUpdates The {@link TermLabelUpdate} instances. + * @param termLabelRefactorings The {@link TermLabelRefactoring} instances. + * @param termLabelMerger The {@link TermLabelMerger} instance. + */ + public TermLabelConfiguration(Name termLabelName, TermLabelFactory factory, + ImmutableList applicationTermPolicies, + ImmutableList modalityTermPolicies, + ImmutableList directChildTermLabelPolicies, + ImmutableList childAndGrandchildTermLabelPolicies, + ImmutableList termLabelUpdates, + ImmutableList termLabelRefactorings, + TermLabelMerger termLabelMerger) { + assert termLabelName != null; + assert factory != null; + this.termLabelName = termLabelName; + this.factory = factory; + this.applicationTermPolicies = applicationTermPolicies; + this.modalityTermPolicies = modalityTermPolicies; + this.directChildTermLabelPolicies = directChildTermLabelPolicies; + this.childAndGrandchildTermLabelPolicies = childAndGrandchildTermLabelPolicies; + this.termLabelUpdates = termLabelUpdates; + this.termLabelRefactorings = termLabelRefactorings; + this.termLabelMerger = termLabelMerger; + } + + /** + * Returns the {@link Name} of the supported {@link TermLabel}. + * + * @return The {@link Name} of the supported {@link TermLabel}. + */ + public Name getTermLabelName() { + return termLabelName; + } + + /** + * Returns the {@link TermLabelFactory} to use. + * + * @return The {@link TermLabelFactory} to use. + */ + public TermLabelFactory getFactory() { + return factory; + } + + /** + * Returns the {@link TermLabelPolicy} instances applied on the application term. + * + * @return The {@link TermLabelPolicy} instances applied on the application term. + */ + public ImmutableList getApplicationTermPolicies() { + return applicationTermPolicies; + } + + /** + * Returns the {@link TermLabelPolicy} instances applied on the modality term. + * + * @return The {@link TermLabelPolicy} instances applied on the modality term. + */ + public ImmutableList getModalityTermPolicies() { + return modalityTermPolicies; + } + + /** + * Returns the direct {@link ChildTermLabelPolicy} instances to use. + * + * @return The direct {@link ChildTermLabelPolicy} instances to use. + */ + public ImmutableList getDirectChildTermLabelPolicies() { + return directChildTermLabelPolicies; + } + + /** + * Returns the child and grandchild {@link ChildTermLabelPolicy} instances to use. + * + * @return The child and grandchild {@link ChildTermLabelPolicy} instances to use. + */ + public ImmutableList getChildAndGrandchildTermLabelPolicies() { + return childAndGrandchildTermLabelPolicies; + } + + /** + * Returns the {@link TermLabelUpdate} instances. + * + * @return The {@link TermLabelUpdate} instances. + */ + public ImmutableList getTermLabelUpdates() { + return termLabelUpdates; + } + + /** + * Returns the {@link TermLabelRefactoring} instances. + * + * @return The {@link TermLabelRefactoring} instances. + */ + public ImmutableList getTermLabelRefactorings() { + return termLabelRefactorings; + } + + /** + * Returns the {@link TermLabelMerger} instance. + * + * @return The {@link TermLabelMerger} instance. + */ + public TermLabelMerger getTermLabelMerger() { + return termLabelMerger; + } + } + + /** + * Searches the inner most {@link TermLabel} wit the given {@link Name} in the parent hierarchy + * of the {@link PosInOccurrence}. + * + * @param pio The {@link PosInOccurrence} to search in. + * @param termLabelName The {@link Name} of the {@link TermLabel} to search. + * @return The found {@link TermLabel} or {@code null} if not available. + */ + public static TermLabel findInnerMostParentLabel(PosInOccurrence pio, Name termLabelName) { + TermLabel label = null; + while (label == null && pio != null) { + Term subTerm = pio.subTerm(); + label = subTerm.getLabel(termLabelName); + pio = pio.isTopLevel() ? null : pio.up(); + } + return label; + } + + /** + * Merges the {@link TermLabel}s of the rejected {@link SequentFormula}s into the resulting + * {@link Sequent}. + * + * @param currentSequent The {@link SequentChangeInfo} which lists the rejected + * {@link SequentFormula}s. + * @param services The {@link Services} to use. + */ + public static void mergeLabels(SequentChangeInfo currentSequent, Services services) { + TermLabelManager manager = getTermLabelManager(services); + if (manager != null) { + manager.mergeLabels(services, currentSequent); + } + } + + /** + * Merges the {@link TermLabel}s of the rejected {@link SequentFormula}s into the resulting + * {@link Sequent}. + * + * @param services The {@link Services} to use. + * @param currentSequent The {@link SequentChangeInfo} which lists the rejected + * {@link SequentFormula}s. + */ + public void mergeLabels(Services services, SequentChangeInfo currentSequent) { + for (SequentFormula rejectedSF : currentSequent.getSemisequentChangeInfo(true) + .rejectedFormulas()) { + mergeLabels(currentSequent, services, rejectedSF, true); + } + for (final SequentFormula rejectedSF : currentSequent.getSemisequentChangeInfo(false) + .rejectedFormulas()) { + mergeLabels(currentSequent, services, rejectedSF, false); + } + } /** - * Merges the {@link TermLabel}s of the given {@link SequentFormula} into - * the resulting {@link Sequent}. - * @param currentSequent The {@link SequentChangeInfo} which lists the - * rejected {@link SequentFormula}s. + * Merges the {@link TermLabel}s of the given {@link SequentFormula} into the resulting + * {@link Sequent}. + * + * @param currentSequent The {@link SequentChangeInfo} which lists the rejected + * {@link SequentFormula}s. * @param services The {@link Services} to use. * @param rejectedSF The rejected {@link SequentFormula} to work with. - * @param inAntecedent {@code true} rejected {@link SequentFormula} is - * in antecedent, {@code false} it is in succedent. + * @param inAntecedent {@code true} rejected {@link SequentFormula} is in antecedent, + * {@code false} it is in succedent. */ - protected void mergeLabels(SequentChangeInfo currentSequent, - Services services, - SequentFormula rejectedSF, - boolean inAntecedent) { + protected void mergeLabels(SequentChangeInfo currentSequent, Services services, + SequentFormula rejectedSF, boolean inAntecedent) { final Term rejectedTerm = rejectedSF.formula(); if (rejectedTerm.hasLabels()) { // Search existing SequentFormula @@ -2367,29 +2253,20 @@ public boolean select(SequentFormula element) { // Label is present, solve conflict with help of the TermLabelMerger. TermLabelMerger merger = mergerMap.get(rejectedLabel.name()); if (merger != null) { - if (merger.mergeLabels(existingSF, existingTerm, - existingLabel, rejectedSF, - rejectedTerm, rejectedLabel, - mergedLabels)) { + if (merger.mergeLabels(existingSF, existingTerm, existingLabel, rejectedSF, + rejectedTerm, rejectedLabel, mergedLabels)) { labelsChanged = true; } } } // Replace sequent formula if (labelsChanged) { - Term newTerm = - services.getTermFactory().createTerm(existingTerm.op(), - existingTerm.subs(), - existingTerm.boundVars(), - existingTerm.javaBlock(), - new ImmutableArray( - mergedLabels)); - SequentChangeInfo sci = - currentSequent.sequent() - .changeFormula(new SequentFormula(newTerm), - new PosInOccurrence(existingSF, - PosInTerm.getTopLevel(), - inAntecedent)); + Term newTerm = services.getTermFactory().createTerm(existingTerm.op(), + existingTerm.subs(), existingTerm.boundVars(), existingTerm.javaBlock(), + new ImmutableArray(mergedLabels)); + SequentChangeInfo sci = currentSequent.sequent().changeFormula( + new SequentFormula(newTerm), + new PosInOccurrence(existingSF, PosInTerm.getTopLevel(), inAntecedent)); currentSequent.combine(sci); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelOperationsInterpreter.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelOperationsInterpreter.java index 7380e511b00..d6c45f06dac 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelOperationsInterpreter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/label/TermLabelOperationsInterpreter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.label; import java.util.HashSet; @@ -16,19 +19,19 @@ */ class TermLabelOperationsInterpreter { - public static ImmutableArray intersection( - ImmutableArray left, ImmutableArray right) { - final HashSet set = new LinkedHashSet(); - for (TermLabel r : right) { - if (left.contains(r)) { - set.add(r); - } - } - return new ImmutableArray(set.toArray(new TermLabel[set.size()])); - } - - public static ImmutableArray union( - ImmutableArray left, ImmutableArray right) { + public static ImmutableArray intersection(ImmutableArray left, + ImmutableArray right) { + final HashSet set = new LinkedHashSet(); + for (TermLabel r : right) { + if (left.contains(r)) { + set.add(r); + } + } + return new ImmutableArray(set.toArray(new TermLabel[set.size()])); + } + + public static ImmutableArray union(ImmutableArray left, + ImmutableArray right) { final HashSet set = new LinkedHashSet(); for (TermLabel l : left) { set.add(l); @@ -39,8 +42,8 @@ public static ImmutableArray union( return new ImmutableArray(set.toArray(new TermLabel[set.size()])); } - public static ImmutableArray sub( - ImmutableArray left, ImmutableArray right) { + public static ImmutableArray sub(ImmutableArray left, + ImmutableArray right) { final HashSet set = new LinkedHashSet(); for (TermLabel l : left) { set.add(l); @@ -52,15 +55,16 @@ public static ImmutableArray sub( } /** - * resolves term redundancy (used by Sequent to avoid duplicate formulas). - * In case of t2 being unlabeled a list with t1 as single element is - * returned. Otherwise if t1 is unlabeled (and t2 labeled), then a list with t2 as single element - * is returned. If both terms are labeled a list of terms is returned which is not redundant. - * + * resolves term redundancy (used by Sequent to avoid duplicate formulas). In case of t2 being + * unlabeled a list with t1 as single element is returned. Otherwise if t1 is unlabeled (and t2 + * labeled), then a list with t2 as single element is returned. If both terms are labeled a list + * of terms is returned which is not redundant. + * * The terms t1 and t2 may only differ in their attached labels. Otherwise they have to be - * structural identical - * + * structural identical + * * This method should be used in case to implement more complex redundancy checks. + * * @param t1 the Term t1 which is structural equivalent to t2 (except maybe labels) * @param t2 the Term t2 * @return a list which represents a redundancy free result of merging labels in t1 and t2 @@ -72,14 +76,14 @@ public static ImmutableList resolveRedundancy(Term t1, Term t2) { } else if (!t1.hasLabels()) { return result.prepend(t2); } - - for (int i = 0; i - *
  • {@link TermLabelPolicy}
  • - *
  • {@link TermLabelUpdate}
  • - *
  • {@link TermLabelRefactoring}
  • + *
  • {@link TermLabelPolicy}
  • + *
  • {@link TermLabelUpdate}
  • + *
  • {@link TermLabelRefactoring}
  • * *

    * Exactly one {@link TermLabelState} instance is created in each * {@link Rule#apply(de.uka.ilkd.key.proof.Goal, de.uka.ilkd.key.java.Services, de.uka.ilkd.key.rule.RuleApp)} - * implementation and passed to each performed {@link TermLabelManager} call - * during rule application and thus passed to the participants. + * implementation and passed to each performed {@link TermLabelManager} call during rule application + * and thus passed to the participants. + * * @author Martin Hentschel */ public class TermLabelState { - /** - * Stores for each {@link TermLabel} {@link Name} the state. - */ - private final Map> labelStateMap = new HashMap>(); + /** + * Stores for each {@link TermLabel} {@link Name} the state. + */ + private final Map> labelStateMap = + new HashMap>(); - /** - * Constructor. - */ - public TermLabelState() { - } - - /** - * Return the state {@link Map} in which arbitrary key values pairs can be stored - * for the given {@link TermLabel} {@link Name}. - * @param termLabelName The {@link Name} of the {@link TermLabel}. - * @return The {@link Map} used by the {@link TermLabel}s participants. - */ - public Map getLabelState(Name termLabelName) { - synchronized (labelStateMap) { - Map result = labelStateMap.get(termLabelName); - if (result == null) { - result = new HashMap(); - labelStateMap.put(termLabelName, result); - } - return result; - } - } + /** + * Constructor. + */ + public TermLabelState() {} - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "TermLabelState " + System.identityHashCode(this) + ": " + labelStateMap; - } + /** + * Return the state {@link Map} in which arbitrary key values pairs can be stored for the given + * {@link TermLabel} {@link Name}. + * + * @param termLabelName The {@link Name} of the {@link TermLabel}. + * @return The {@link Map} used by the {@link TermLabel}s participants. + */ + public Map getLabelState(Name termLabelName) { + synchronized (labelStateMap) { + Map result = labelStateMap.get(termLabelName); + if (result == null) { + result = new HashMap(); + labelStateMap.put(termLabelName, result); + } + return result; + } + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "TermLabelState " + System.identityHashCode(this) + ": " + labelStateMap; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractOperator.java index f0646afcf28..a89f619205f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractOperator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -7,83 +10,78 @@ import de.uka.ilkd.key.logic.Term; -/** +/** * Abstract operator class offering some common functionality. */ abstract class AbstractOperator implements Operator { - + private final Name name; private final int arity; private final ImmutableArray whereToBind; private final boolean isRigid; - - - protected AbstractOperator(Name name, - int arity, - ImmutableArray whereToBind, - boolean isRigid) { - assert name != null; - assert arity >= 0; - assert whereToBind == null || whereToBind.size() == arity; - this.name = name; - this.arity = arity; - this.whereToBind = whereToBind; - this.isRigid = isRigid; + + + protected AbstractOperator(Name name, int arity, ImmutableArray whereToBind, + boolean isRigid) { + assert name != null; + assert arity >= 0; + assert whereToBind == null || whereToBind.size() == arity; + this.name = name; + this.arity = arity; + this.whereToBind = whereToBind; + this.isRigid = isRigid; } - - - protected AbstractOperator(Name name, - int arity, - Boolean[] whereToBind, - boolean isRigid) { - this(name, arity, new ImmutableArray(whereToBind), isRigid); - } - - + + + protected AbstractOperator(Name name, int arity, Boolean[] whereToBind, boolean isRigid) { + this(name, arity, new ImmutableArray(whereToBind), isRigid); + } + + protected AbstractOperator(Name name, int arity, boolean isRigid) { - this(name, arity, (ImmutableArray) null, isRigid); + this(name, arity, (ImmutableArray) null, isRigid); } - - + + protected final ImmutableArray whereToBind() { - return whereToBind; + return whereToBind; } - - + + @Override public final Name name() { - return name; + return name; } - - + + @Override public final int arity() { return arity; } - - + + @Override public final boolean bindVarsAt(int n) { - return whereToBind != null && whereToBind.get(n); + return whereToBind != null && whereToBind.get(n); } - - + + @Override public final boolean isRigid() { - return isRigid; + return isRigid; } - - + + /** - * Allows subclasses to impose custom demands on what constitutes a - * valid term using the operator represented by the subclass. + * Allows subclasses to impose custom demands on what constitutes a valid term using the + * operator represented by the subclass. */ protected abstract void additionalValidTopLevel(Term term) throws TermCreationException; - - + + @Override public void validTopLevelException(Term term) throws TermCreationException { - if(arity != term.arity()) { + if (arity != term.arity()) { throw new TermCreationException(this, term); } @@ -91,22 +89,22 @@ public void validTopLevelException(Term term) throws TermCreationException { throw new TermCreationException(this, term); } - if((whereToBind == null) != term.boundVars().isEmpty()) { + if ((whereToBind == null) != term.boundVars().isEmpty()) { throw new TermCreationException(this, term); } - - for(int i = 0; i < arity; i++) { - if(term.sub(i) == null) { + + for (int i = 0; i < arity; i++) { + if (term.sub(i) == null) { throw new TermCreationException(this, term); } } additionalValidTopLevel(term); } - - + + @Override public String toString() { - return name().toString(); + return name().toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSV.java index e90d4fa2076..afaab4973e2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSV.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -8,46 +11,35 @@ /** * Abstract base class for schema variables. */ -public abstract class AbstractSV extends AbstractSortedOperator - implements SchemaVariable { - +public abstract class AbstractSV extends AbstractSortedOperator implements SchemaVariable { + private final boolean isStrict; - - - protected AbstractSV(Name name, - ImmutableArray argSorts, - Sort sort, - boolean isRigid, - boolean isStrict) { - super(name, argSorts, sort, isRigid); - this.isStrict = isStrict; + + + protected AbstractSV(Name name, ImmutableArray argSorts, Sort sort, boolean isRigid, + boolean isStrict) { + super(name, argSorts, sort, isRigid); + this.isStrict = isStrict; + } + + + protected AbstractSV(Name name, Sort[] argSorts, Sort sort, boolean isRigid, boolean isStrict) { + this(name, new ImmutableArray(argSorts), sort, isRigid, isStrict); } - - - protected AbstractSV(Name name, - Sort[] argSorts, - Sort sort, - boolean isRigid, - boolean isStrict) { - this(name, new ImmutableArray(argSorts), sort, isRigid, isStrict); + + + protected AbstractSV(Name name, Sort sort, boolean isRigid, boolean isStrict) { + this(name, (ImmutableArray) null, sort, isRigid, isStrict); } - - - protected AbstractSV(Name name, - Sort sort, - boolean isRigid, - boolean isStrict) { - this(name,(ImmutableArray) null, sort, isRigid, isStrict); - } - - + + protected final String toString(String sortSpec) { - return name() +" (" + sortSpec + ")"; - } + return name() + " (" + sortSpec + ")"; + } + - @Override public final boolean isStrict() { - return isStrict; + return isStrict; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSortedOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSortedOperator.java index fcbac07f124..bec0037a53a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSortedOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractSortedOperator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -14,129 +17,103 @@ * Abstract sorted operator class offering some common functionality. */ public abstract class AbstractSortedOperator extends AbstractOperator - implements SortedOperator, Sorted { - - private static final ImmutableArray EMPTY_SORT_LIST - = new ImmutableArray(); - - private final Sort sort; - private final ImmutableArray argSorts; - - - protected AbstractSortedOperator(Name name, - ImmutableArray argSorts, - Sort sort, - ImmutableArray whereToBind, - boolean isRigid) { - super(name, - argSorts == null ? 0 : argSorts.size(), - whereToBind, - isRigid); - if (sort == null) throw new NullPointerException("Given sort is null"); - this.argSorts = argSorts == null ? EMPTY_SORT_LIST : argSorts; - this.sort = sort; - } - - - protected AbstractSortedOperator(Name name, - Sort[] argSorts, - Sort sort, - Boolean[] whereToBind, - boolean isRigid) { - this(name, - new ImmutableArray(argSorts), - sort, - new ImmutableArray(whereToBind), - isRigid); - } - - - protected AbstractSortedOperator(Name name, - ImmutableArray argSorts, - Sort sort, - boolean isRigid) { - this(name, argSorts, sort, null, isRigid); - } - - - protected AbstractSortedOperator(Name name, - Sort[] argSorts, - Sort sort, - boolean isRigid) { - this(name, new ImmutableArray(argSorts), sort, null, isRigid); - } - - - protected AbstractSortedOperator(Name name, - Sort sort, - boolean isRigid) { - this(name, (ImmutableArray) null, sort, null, isRigid); - } - - - @Override - public final Sort sort(ImmutableArray terms) { - return sort; - } - - - /** - * checks if a given Term could be subterm (at the at'th subterm - * position) of a term with this function at its top level. The - * validity of the given subterm is NOT checked. - * - * @param at theposition of the term where this method should check - * the validity. - * @param possibleSub the subterm to be ckecked. - * @return true iff the given term can be subterm at the indicated - * position - */ - private boolean possibleSub(int at, Term possibleSub) { - final Sort s = possibleSub.sort(); - - return s == AbstractTermTransformer.METASORT - || s instanceof ProgramSVSort - || argSort(at) == AbstractTermTransformer.METASORT - || argSort(at) instanceof ProgramSVSort - || s.extendsTrans(argSort(at)); - } - - - /* weigl: disable this method, not used. You should use inheritance! - - * Allows subclasses to impose custom demands on what constitutes a - * valid term using the operator represented by the subclass. The - * default implementation here does not impose any such demands. - protected boolean additionalValidTopLevel2(Term term) { - return true; - } - */ - - - @Override - protected final void additionalValidTopLevel(Term term) { - for (int i = 0, n = arity(); i < n; i++) { - if (!possibleSub(i, term.sub(i))) { - throw new TermCreationException(this, term); - } - } - } - - - @Override - public final Sort argSort(int i) { - return argSorts.get(i); - } - - - @Override - public final ImmutableArray argSorts() { - return argSorts; - } - - - @Override - public final Sort sort() { - return sort; - } + implements SortedOperator, Sorted { + + private static final ImmutableArray EMPTY_SORT_LIST = new ImmutableArray(); + + private final Sort sort; + private final ImmutableArray argSorts; + + + protected AbstractSortedOperator(Name name, ImmutableArray argSorts, Sort sort, + ImmutableArray whereToBind, boolean isRigid) { + super(name, argSorts == null ? 0 : argSorts.size(), whereToBind, isRigid); + if (sort == null) + throw new NullPointerException("Given sort is null"); + this.argSorts = argSorts == null ? EMPTY_SORT_LIST : argSorts; + this.sort = sort; + } + + + protected AbstractSortedOperator(Name name, Sort[] argSorts, Sort sort, Boolean[] whereToBind, + boolean isRigid) { + this(name, new ImmutableArray(argSorts), sort, + new ImmutableArray(whereToBind), isRigid); + } + + + protected AbstractSortedOperator(Name name, ImmutableArray argSorts, Sort sort, + boolean isRigid) { + this(name, argSorts, sort, null, isRigid); + } + + + protected AbstractSortedOperator(Name name, Sort[] argSorts, Sort sort, boolean isRigid) { + this(name, new ImmutableArray(argSorts), sort, null, isRigid); + } + + + protected AbstractSortedOperator(Name name, Sort sort, boolean isRigid) { + this(name, (ImmutableArray) null, sort, null, isRigid); + } + + + @Override + public final Sort sort(ImmutableArray terms) { + return sort; + } + + + /** + * checks if a given Term could be subterm (at the at'th subterm position) of a term with this + * function at its top level. The validity of the given subterm is NOT checked. + * + * @param at theposition of the term where this method should check the validity. + * @param possibleSub the subterm to be ckecked. + * @return true iff the given term can be subterm at the indicated position + */ + private boolean possibleSub(int at, Term possibleSub) { + final Sort s = possibleSub.sort(); + + return s == AbstractTermTransformer.METASORT || s instanceof ProgramSVSort + || argSort(at) == AbstractTermTransformer.METASORT + || argSort(at) instanceof ProgramSVSort || s.extendsTrans(argSort(at)); + } + + + /* + * weigl: disable this method, not used. You should use inheritance! + * + * Allows subclasses to impose custom demands on what constitutes a valid term using the + * operator represented by the subclass. The default implementation here does not impose any + * such demands. protected boolean additionalValidTopLevel2(Term term) { return true; } + */ + + + @Override + protected final void additionalValidTopLevel(Term term) { + for (int i = 0, n = arity(); i < n; i++) { + if (!possibleSub(i, term.sub(i))) { + throw new TermCreationException(this, term); + } + } + } + + + @Override + public final Sort argSort(int i) { + return argSorts.get(i); + } + + + @Override + public final ImmutableArray argSorts() { + return argSorts; + } + + + @Override + public final Sort sort() { + return sort; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractTermTransformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractTermTransformer.java index fceed47976b..f931bc7e6b0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractTermTransformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/AbstractTermTransformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.util.LinkedHashMap; @@ -17,8 +20,8 @@ import recoder.service.KeYCrossReferenceSourceInfo; /** - * Abstract class factoring out commonalities of typical term transformer implementations. - * The available singletons of term transformers are kept here. + * Abstract class factoring out commonalities of typical term transformer implementations. The + * available singletons of term transformers are kept here. */ public abstract class AbstractTermTransformer extends AbstractSortedOperator implements TermTransformer { @@ -74,11 +77,15 @@ public abstract class AbstractTermTransformer extends AbstractSortedOperator public static final AbstractTermTransformer DIVIDE_LCR_MONOMIALS = new DivideLCRMonomials(); - public static final AbstractTermTransformer INTRODUCE_ATPRE_DEFINITIONS = new IntroAtPreDefsOp(); + public static final AbstractTermTransformer INTRODUCE_ATPRE_DEFINITIONS = + new IntroAtPreDefsOp(); - public static final AbstractTermTransformer CREATE_LOCAL_ANON_UPDATE = new CreateLocalAnonUpdate(); - public static final AbstractTermTransformer CREATE_HEAP_ANON_UPDATE = new CreateHeapAnonUpdate(); - public static final AbstractTermTransformer CREATE_BEFORE_LOOP_UPDATE = new CreateBeforeLoopUpdate(); + public static final AbstractTermTransformer CREATE_LOCAL_ANON_UPDATE = + new CreateLocalAnonUpdate(); + public static final AbstractTermTransformer CREATE_HEAP_ANON_UPDATE = + new CreateHeapAnonUpdate(); + public static final AbstractTermTransformer CREATE_BEFORE_LOOP_UPDATE = + new CreateBeforeLoopUpdate(); public static final AbstractTermTransformer CREATE_FRAME_COND = new CreateFrameCond(); public static final AbstractTermTransformer CREATE_WELLFORMED_COND = new CreateWellformedCond(); @@ -114,8 +121,8 @@ public static TermTransformer name2metaop(String s) { return NAME_TO_META_OP.get(s); } - /** @return String representing a logical integer literal - * in decimal representation + /** + * @return String representing a logical integer literal in decimal representation */ public static String convertToDecimalString(Term term, Services services) { StringBuilder result = new StringBuilder(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ElementaryUpdate.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ElementaryUpdate.java index 49595db17c9..48971d1d26b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ElementaryUpdate.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ElementaryUpdate.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.lang.ref.WeakReference; @@ -8,52 +11,48 @@ /** - * Class of operators for elementary updates, i.e., updates of the form - * "x := t". There is one such operator for every left hand side "x". - * Each of these operator is unary, accepting a single argument "t". + * Class of operators for elementary updates, i.e., updates of the form "x := t". There is one such + * operator for every left hand side "x". Each of these operator is unary, accepting a single + * argument "t". */ public final class ElementaryUpdate extends AbstractSortedOperator { - - private static final WeakHashMap> instances - = new WeakHashMap>(); - - + + private static final WeakHashMap> instances = + new WeakHashMap>(); + + private final UpdateableOperator lhs; - + private ElementaryUpdate(UpdateableOperator lhs) { - super(new Name("elem-update(" + lhs + ")"), - new Sort[]{lhs.sort()}, - Sort.UPDATE, - false); - this.lhs = lhs; - assert lhs.arity() == 0; + super(new Name("elem-update(" + lhs + ")"), new Sort[] { lhs.sort() }, Sort.UPDATE, false); + this.lhs = lhs; + assert lhs.arity() == 0; } - - + + /** * Returns the elementary update operator for the passed left hand side. */ public static ElementaryUpdate getInstance(UpdateableOperator lhs) { WeakReference ref = instances.get(lhs); ElementaryUpdate result = null; - if(ref != null) { + if (ref != null) { result = ref.get(); } - if(result == null) { + if (result == null) { result = new ElementaryUpdate(lhs); ref = new WeakReference(result); instances.put(lhs, ref); } return result; } - - + + /** * Returns the left hand side of this elementary update operator. */ public UpdateableOperator lhs() { - return lhs; + return lhs; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Equality.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Equality.java index aab9267e2cc..1b9d4c77cd6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Equality.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Equality.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -5,30 +8,27 @@ /** - * This class defines the equality operator "=". It is a binary - * predicate accepting arbitrary terms (sort "any") as arguments. - * - * It also defines the formula equivalence operator "<->" (which - * could alternatively be seen as a Junctor). + * This class defines the equality operator "=". It is a binary predicate accepting arbitrary terms + * (sort "any") as arguments. + * + * It also defines the formula equivalence operator "<->" (which could alternatively be seen as a + * Junctor). */ public final class Equality extends AbstractSortedOperator { - /** + /** * the usual 'equality' operator '=' */ - public static final Equality EQUALS = new Equality(new Name("equals"), - Sort.ANY); - - /** - * the usual 'equivalence' operator '<->' (be A, B formulae then - * 'A <-> B' is true if and only if A and B have the same truth - * value - */ - public static final Equality EQV = new Equality(new Name("equiv"), - Sort.FORMULA); - - - private Equality(Name name, Sort targetSort){ - super(name, new Sort[]{targetSort, targetSort}, Sort.FORMULA, true); + public static final Equality EQUALS = new Equality(new Name("equals"), Sort.ANY); + + /** + * the usual 'equivalence' operator '<->' (be A, B formulae then 'A <-> B' is true if and only + * if A and B have the same truth value + */ + public static final Equality EQV = new Equality(new Name("equiv"), Sort.FORMULA); + + + private Equality(Name name, Sort targetSort) { + super(name, new Sort[] { targetSort, targetSort }, Sort.FORMULA, true); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/FormulaSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/FormulaSV.java index f8c4e2483e9..14b1ed7a997 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/FormulaSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/FormulaSV.java @@ -1,30 +1,33 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; -/** +/** * A schema variable that is used as placeholder for formulas. - */ + */ public final class FormulaSV extends AbstractSV { - - /** + + /** * @param name the name of the SchemaVariable * @param isRigid true iff this SV may only match rigid formulas */ FormulaSV(Name name, boolean isRigid) { - super(name, Sort.FORMULA, isRigid, true); + super(name, Sort.FORMULA, isRigid, true); } - + @Override public String toString() { - return toString("formula"); - } - - + return toString("formula"); + } + + @Override public String proofToString() { - return "\\schemaVar \\formula " + name() + ";\n"; + return "\\schemaVar \\formula " + name() + ";\n"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java index 4164be0bb7e..288eb0ddd8f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Function.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -10,9 +13,8 @@ /** - * Objects of this class represent function and predicate symbols. Note - * that program variables are a separate syntactic category, and not a type - * of function. + * Objects of this class represent function and predicate symbols. Note that program variables are a + * separate syntactic category, and not a type of function. */ public class Function extends AbstractSortedOperator { private final MixFitInfo mixFitInfo; @@ -21,17 +23,12 @@ public class Function extends AbstractSortedOperator { private final boolean skolemConstant; - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- - Function(Name name, - Sort sort, - ImmutableArray argSorts, - ImmutableArray whereToBind, - boolean unique, - boolean isRigid, - boolean isSkolemConstant, - @Nullable MixFitInfo mixFitInfo) { + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- + Function(Name name, Sort sort, ImmutableArray argSorts, + ImmutableArray whereToBind, boolean unique, boolean isRigid, + boolean isSkolemConstant, @Nullable MixFitInfo mixFitInfo) { super(name, argSorts, sort, whereToBind, isRigid); this.unique = unique; @@ -43,66 +40,44 @@ public class Function extends AbstractSortedOperator { this.mixFitInfo = mixFitInfo; } - Function(Name name, - Sort sort, - ImmutableArray argSorts, - ImmutableArray whereToBind, - boolean unique, - boolean isRigid, - boolean isSkolemConstant) { + Function(Name name, Sort sort, ImmutableArray argSorts, + ImmutableArray whereToBind, boolean unique, boolean isRigid, + boolean isSkolemConstant) { this(name, sort, argSorts, whereToBind, unique, isRigid, isSkolemConstant, null); } - public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, - boolean unique) { + public Function(Name name, Sort sort, ImmutableArray argSorts, + ImmutableArray whereToBind, boolean unique) { this(name, sort, argSorts, whereToBind, unique, true, false); } - public Function(Name name, Sort sort, ImmutableArray argSorts, ImmutableArray whereToBind, - boolean unique, MixFitInfo mixFitInfo) { + public Function(Name name, Sort sort, ImmutableArray argSorts, + ImmutableArray whereToBind, boolean unique, MixFitInfo mixFitInfo) { this(name, sort, argSorts, whereToBind, unique, true, false, mixFitInfo); } - public Function(Name name, - Sort sort, - ImmutableArray argSorts, - ImmutableArray whereToBind, - boolean unique, - boolean isSkolemConstant) { + public Function(Name name, Sort sort, ImmutableArray argSorts, + ImmutableArray whereToBind, boolean unique, boolean isSkolemConstant) { this(name, sort, argSorts, whereToBind, unique, true, isSkolemConstant); } - public Function(Name name, - Sort sort, - Sort[] argSorts, - Boolean[] whereToBind, - boolean unique) { - this(name, - sort, - new ImmutableArray(argSorts), - whereToBind == null ? null : new ImmutableArray(whereToBind), - unique); + public Function(Name name, Sort sort, Sort[] argSorts, Boolean[] whereToBind, boolean unique) { + this(name, sort, new ImmutableArray(argSorts), + whereToBind == null ? null : new ImmutableArray(whereToBind), unique); } public Function(Name name, Sort sort, Sort[] argSorts, Boolean[] whereToBind, boolean unique, - MixFitInfo mixFitInfo) { + MixFitInfo mixFitInfo) { this(name, sort, new ImmutableArray<>(argSorts), whereToBind == null ? null : new ImmutableArray<>(whereToBind), unique, mixFitInfo); } - public Function(Name name, - Sort sort, - Sort[] argSorts, - Boolean[] whereToBind, - boolean unique, - boolean isSkolemConstant) { - this(name, - sort, - new ImmutableArray(argSorts), - whereToBind == null ? null : new ImmutableArray(whereToBind), - unique, - isSkolemConstant); + public Function(Name name, Sort sort, Sort[] argSorts, Boolean[] whereToBind, boolean unique, + boolean isSkolemConstant) { + this(name, sort, new ImmutableArray(argSorts), + whereToBind == null ? null : new ImmutableArray(whereToBind), unique, + isSkolemConstant); } Function(Name name, Sort sort, ImmutableArray argSorts, boolean isRigid) { @@ -110,19 +85,19 @@ public Function(Name name, } public Function(Name name, Sort sort, ImmutableArray argSorts) { - this(name, sort, argSorts, null, false); + this(name, sort, argSorts, null, false); } - public Function(Name name, Sort sort, Sort ... argSorts) { - this(name, sort, argSorts, null, false); + public Function(Name name, Sort sort, Sort... argSorts) { + this(name, sort, argSorts, null, false); } - public Function(Name name, Sort sort, boolean isSkolemConstant, Sort ... argSorts) { + public Function(Name name, Sort sort, boolean isSkolemConstant, Sort... argSorts) { this(name, sort, argSorts, null, false, isSkolemConstant); } public Function(Name name, Sort sort) { - this(name, sort, new ImmutableArray(), null, false); + this(name, sort, new ImmutableArray(), null, false); } public Function(Name name, Sort sort, boolean isSkolemConstant) { @@ -131,20 +106,17 @@ public Function(Name name, Sort sort, boolean isSkolemConstant) { - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- /** - * Indicates whether the function or predicate symbol has the "uniqueness" - * property. For two unique symbols f1: A1 -> B1, f2: A2 -> B2 by definition - * we have - * (1) f1(x) != f1(y) for all x, y in A1 with x != y (i.e., injectivity), - * and (2) f1(x) != f2(y) for all x in A1, y in A2. + * Indicates whether the function or predicate symbol has the "uniqueness" property. For two + * unique symbols f1: A1 -> B1, f2: A2 -> B2 by definition we have (1) f1(x) != f1(y) for all x, + * y in A1 with x != y (i.e., injectivity), and (2) f1(x) != f2(y) for all x in A1, y in A2. */ public final boolean isUnique() { - return unique; + return unique; } public final boolean isSkolemConstant() { @@ -153,14 +125,12 @@ public final boolean isSkolemConstant() { @Override public final String toString() { - return (name() + (whereToBind() == null - ? "" - : "{" + whereToBind() + "}")); + return (name() + (whereToBind() == null ? "" : "{" + whereToBind() + "}")); } /** - * Returns a parsable string representation of the declaration of this - * function or predicate symbol. + * Returns a parsable string representation of the declaration of this function or predicate + * symbol. */ public final String proofToString() { String s = (sort() == Sort.FORMULA ? "" : sort().toString()) + " "; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IObserverFunction.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IObserverFunction.java index b5551f3b748..4261a30222a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IObserverFunction.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IObserverFunction.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -7,52 +10,49 @@ public interface IObserverFunction extends SortedOperator { - /** - * Returns the result type of this symbol. - */ - public abstract KeYJavaType getType(); - - /** - * Returns the container type of this symbol; for non-static observer - * symbols, this corresponds to the sort of its second argument. - */ - public abstract KeYJavaType getContainerType(); - - /** - * Tells whether the observer symbol is static. - */ - public abstract boolean isStatic(); - - /** - * Check the state count of the declaration (no_state = 0, two_state = 2, 1 otherwise). - */ - public abstract int getStateCount(); - - /** - * Check the heap count of the declaration, e.g. the base heap and extra heap. - */ - public abstract int getHeapCount(Services services); - - /** - * Gives the number of parameters of the observer symbol. "Parameters" here - * includes only the *explicit* parameters, not the heap and the receiver - * object. Thus, for observer symbols representing model fields, this will - * always return 0. - */ - public abstract int getNumParams(); - - /** - * Gives the type of the i-th parameter of this observer symbol. - * "Parameters" here includes only the *explicit* parameters, not the heap - * and the receiver object. - */ - public abstract KeYJavaType getParamType(int i); - - /** - * Returns the parameter types of this observer symbol. "Parameters" here - * includes only the *explicit* parameters, not the heap and the receiver - * object. - */ - public abstract ImmutableArray getParamTypes(); - -} \ No newline at end of file + /** + * Returns the result type of this symbol. + */ + public abstract KeYJavaType getType(); + + /** + * Returns the container type of this symbol; for non-static observer symbols, this corresponds + * to the sort of its second argument. + */ + public abstract KeYJavaType getContainerType(); + + /** + * Tells whether the observer symbol is static. + */ + public abstract boolean isStatic(); + + /** + * Check the state count of the declaration (no_state = 0, two_state = 2, 1 otherwise). + */ + public abstract int getStateCount(); + + /** + * Check the heap count of the declaration, e.g. the base heap and extra heap. + */ + public abstract int getHeapCount(Services services); + + /** + * Gives the number of parameters of the observer symbol. "Parameters" here includes only the + * *explicit* parameters, not the heap and the receiver object. Thus, for observer symbols + * representing model fields, this will always return 0. + */ + public abstract int getNumParams(); + + /** + * Gives the type of the i-th parameter of this observer symbol. "Parameters" here includes only + * the *explicit* parameters, not the heap and the receiver object. + */ + public abstract KeYJavaType getParamType(int i); + + /** + * Returns the parameter types of this observer symbol. "Parameters" here includes only the + * *explicit* parameters, not the heap and the receiver object. + */ + public abstract ImmutableArray getParamTypes(); + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramMethod.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramMethod.java index 8a91a7626ec..dfcc7ae4c55 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramMethod.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -14,17 +17,16 @@ import de.uka.ilkd.key.java.declaration.VariableSpecification; import de.uka.ilkd.key.logic.ProgramElementName; -public interface IProgramMethod extends IObserverFunction, SourceElement, - ProgramElement, MemberDeclaration { +public interface IProgramMethod + extends IObserverFunction, SourceElement, ProgramElement, MemberDeclaration { public abstract MethodDeclaration getMethodDeclaration(); /** - * returns the KeYJavaType of the i-th parameter declaration. This - * method does not care about the invoker as argSort does. - * - * @param i - * the int specifying the parameter position + * returns the KeYJavaType of the i-th parameter declaration. This method does not care + * about the invoker as argSort does. + * + * @param i the int specifying the parameter position * @return the KeYJavaType of the i-th parameter */ public abstract KeYJavaType getParameterType(int i); @@ -83,8 +85,8 @@ public interface IProgramMethod extends IObserverFunction, SourceElement, public ImmutableArray getParamTypes(); /** - * @return The list of {@link LocationVariable}s passed as parameters to - * this {@link IProgramMethod}. + * @return The list of {@link LocationVariable}s passed as parameters to this + * {@link IProgramMethod}. */ public ImmutableList collectParameters(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramVariable.java index ac278063a82..84dd7c37438 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IProgramVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.java.Services; @@ -6,10 +9,10 @@ import de.uka.ilkd.key.java.reference.ExecutionContext; import de.uka.ilkd.key.logic.Named; -public interface IProgramVariable extends TerminalProgramElement, - Named, - SortedOperator { +public interface IProgramVariable extends TerminalProgramElement, Named, SortedOperator { KeYJavaType getKeYJavaType(); + KeYJavaType getKeYJavaType(Services javaServ); + 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/logic/op/IfExThenElse.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfExThenElse.java index 5cb30aa2701..ddee97ed5b6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfExThenElse.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfExThenElse.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -9,35 +12,31 @@ /** - * This singleton class implements a conditional operator - * "\ifEx iv; (phi) \then (t1) \else (t2)", where iv is an integer logic - * variable, phi is a formula, and where t1 and t2 are terms with the same sort. - * The variable iv is bound in phi and in t1, but not in t2. + * This singleton class implements a conditional operator "\ifEx iv; (phi) \then (t1) \else (t2)", + * where iv is an integer logic variable, phi is a formula, and where t1 and t2 are terms with the + * same sort. The variable iv is bound in phi and in t1, but not in t2. */ public final class IfExThenElse extends AbstractOperator { - + public static final IfExThenElse IF_EX_THEN_ELSE = new IfExThenElse(); - - + + private IfExThenElse() { - super(new Name("ifExThenElse"), - 3, - new Boolean[]{true, true, false}, - true); + super(new Name("ifExThenElse"), 3, new Boolean[] { true, true, false }, true); } - - + + @Override public Sort sort(ImmutableArray terms) { - return terms.get(1).sort(); + return terms.get(1).sort(); } - + @Override protected void additionalValidTopLevel(Term term) { - for(QuantifiableVariable var : term.varsBoundHere(0)) { - if(!var.sort().name().toString().equals("int")) { - throw new TermCreationException(this, term); + for (QuantifiableVariable var : term.varsBoundHere(0)) { + if (!var.sort().name().toString().equals("int")) { + throw new TermCreationException(this, term); } } @@ -49,4 +48,4 @@ protected void additionalValidTopLevel(Term term) { throw new TermCreationException(this, term); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfThenElse.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfThenElse.java index 8fdb162cc21..a89d762a274 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfThenElse.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/IfThenElse.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -12,28 +15,28 @@ /** - * This singleton class implements a general conditional operator + * This singleton class implements a general conditional operator * \if (phi) \then (t1) \else (t2). */ public final class IfThenElse extends AbstractOperator { - + public static final IfThenElse IF_THEN_ELSE = new IfThenElse(); - - - private IfThenElse () { - super(new Name("if-then-else"), 3, true); + + + private IfThenElse() { + super(new Name("if-then-else"), 3, true); } - - + + private Sort getCommonSuperSort(Sort s1, Sort s2) { - if(s1 == Sort.FORMULA) { - assert s2 == Sort.FORMULA: "Sorts FORMULA and "+s2+" are incompatible."; + if (s1 == Sort.FORMULA) { + assert s2 == Sort.FORMULA : "Sorts FORMULA and " + s2 + " are incompatible."; return Sort.FORMULA; - } else if(s1.extendsTrans(s2)) { + } else if (s1.extendsTrans(s2)) { return s2; - } else if(s2.extendsTrans(s1)) { + } else if (s2.extendsTrans(s1)) { return s1; - } else if(s1 instanceof NullSort || s2 instanceof NullSort) { + } else if (s1 instanceof NullSort || s2 instanceof NullSort) { return Sort.ANY; } else { Sort result = Sort.ANY; @@ -41,50 +44,46 @@ private Sort getCommonSuperSort(Sort s1, Sort s2) { final ImmutableSet set2 = s2.extendsSorts(); assert set1 != null : "null for sort: " + s1; assert set2 != null : "null for sort: " + s2; - - for(final Sort sort1 : set1) { - if(set2.contains(sort1)) { - if(result == Sort.ANY) { + + for (final Sort sort1 : set1) { + if (set2.contains(sort1)) { + if (result == Sort.ANY) { result = sort1; } else { // not uniquely determinable return Sort.ANY; } - } + } } - + return result; } - } + } + - @Override public Sort sort(ImmutableArray terms) { final Sort s2 = terms.get(1).sort(); final Sort s3 = terms.get(2).sort(); - if(s2 instanceof ProgramSVSort - || s2 == AbstractTermTransformer.METASORT ) { - return s3; - } else if(s3 instanceof ProgramSVSort - || s3 == AbstractTermTransformer.METASORT ) { + if (s2 instanceof ProgramSVSort || s2 == AbstractTermTransformer.METASORT) { + return s3; + } else if (s3 instanceof ProgramSVSort || s3 == AbstractTermTransformer.METASORT) { return s2; - } else { + } else { return getCommonSuperSort(s2, s3); } } - + @Override protected void additionalValidTopLevel(Term term) { final Sort s0 = term.sub(0).sort(); final Sort s1 = term.sub(1).sort(); final Sort s2 = term.sub(2).sort(); - - if(!(s0 == Sort.FORMULA - && (s1 == Sort.FORMULA) == (s2 == Sort.FORMULA) - && s1 != Sort.UPDATE - && s2 != Sort.UPDATE)) { + + if (!(s0 == Sort.FORMULA && (s1 == Sort.FORMULA) == (s2 == Sort.FORMULA) + && s1 != Sort.UPDATE && s2 != Sort.UPDATE)) { throw new TermCreationException(this, term); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Junctor.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Junctor.java index 0082c3e9f09..bc5421c7798 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Junctor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Junctor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -5,57 +8,56 @@ /** - * Class of junctor operators, i.e., operators connecting - * a given number of formula to create another formula. There - * are six such operators: true, false, conjunction, - * disjunction, negation, and implication. + * Class of junctor operators, i.e., operators connecting a given number of formula to create + * another formula. There are six such operators: true, false, conjunction, disjunction, negation, + * and implication. */ public final class Junctor extends AbstractSortedOperator { - - /** - * the true constant + + /** + * the true constant */ - public static final Junctor TRUE = new Junctor(new Name("true"),0); + public static final Junctor TRUE = new Junctor(new Name("true"), 0); - /** - * the false constant + /** + * the false constant */ - public static final Junctor FALSE = new Junctor(new Name("false"),0); - - /** - * the usual 'and' operator '/\' (be A, B formulae then 'A /\ B' - * is true if and only if A is true and B is true + public static final Junctor FALSE = new Junctor(new Name("false"), 0); + + /** + * the usual 'and' operator '/\' (be A, B formulae then 'A /\ B' is true if and only if A is + * true and B is true */ - public static final Junctor AND = new Junctor(new Name("and"),2); - - /** - * the usual 'or' operator '\/' (be A, B formulae then 'A \/ B' - * is true if and only if A is true or B is true + public static final Junctor AND = new Junctor(new Name("and"), 2); + + /** + * the usual 'or' operator '\/' (be A, B formulae then 'A \/ B' is true if and only if A is true + * or B is true */ - public static final Junctor OR = new Junctor(new Name("or"),2); - - /** + public static final Junctor OR = new Junctor(new Name("or"), 2); + + /** * the usual 'negation' operator '-' */ public static final Junctor NOT = new Junctor(new Name("not"), 1); /** - * the usual 'implication' operator '->' (be A, B formulae then - * 'A -> B' is true if and only if A is false or B is true + * the usual 'implication' operator '->' (be A, B formulae then 'A -> B' is true if and only if + * A is false or B is true */ - public static final Junctor IMP = new Junctor(new Name("imp"),2); + public static final Junctor IMP = new Junctor(new Name("imp"), 2); + - private static Sort[] createFormulaSortArray(int arity) { - Sort[] result = new Sort[arity]; - for(int i = 0; i < arity; i++) { - result[i] = Sort.FORMULA; - } - return result; + Sort[] result = new Sort[arity]; + for (int i = 0; i < arity; i++) { + result[i] = Sort.FORMULA; + } + return result; } - - + + private Junctor(Name name, int arity) { - super(name, createFormulaSortArray(arity), Sort.FORMULA, true); + super(name, createFormulaSortArray(arity), Sort.FORMULA, true); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LocationVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LocationVariable.java index 33672ffa3c5..9178d4c69c5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LocationVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LocationVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -6,27 +9,17 @@ import de.uka.ilkd.key.logic.sort.Sort; /** - * This class represents proper program variables, which are not program - * constants. See the description of the superclass ProgramVariable for - * more information. + * This class represents proper program variables, which are not program constants. See the + * description of the superclass ProgramVariable for more information. */ -public final class LocationVariable extends ProgramVariable - implements UpdateableOperator { - public LocationVariable(ProgramElementName name, - KeYJavaType t, - KeYJavaType containingType, - boolean isStatic, - boolean isModel, - boolean isGhost, - boolean isFinal) { +public final class LocationVariable extends ProgramVariable implements UpdateableOperator { + public LocationVariable(ProgramElementName name, KeYJavaType t, KeYJavaType containingType, + boolean isStatic, boolean isModel, boolean isGhost, boolean isFinal) { super(name, t.getSort(), t, containingType, isStatic, isModel, isGhost, isFinal); } - - public LocationVariable(ProgramElementName name, - KeYJavaType t, - KeYJavaType containingType, - boolean isStatic, - boolean isModel) { + + public LocationVariable(ProgramElementName name, KeYJavaType t, KeYJavaType containingType, + boolean isStatic, boolean isModel) { super(name, t.getSort(), t, containingType, isStatic, isModel, false); } @@ -40,7 +33,8 @@ public LocationVariable(ProgramElementName name, KeYJavaType t, boolean isFinal) super(name, t.getSort(), t, null, false, false, false, isFinal); } - public LocationVariable(ProgramElementName name, KeYJavaType t, boolean isGhost, boolean isFinal) { + public LocationVariable(ProgramElementName name, KeYJavaType t, boolean isGhost, + boolean isFinal) { super(name, t.getSort(), t, null, false, false, isGhost, isFinal); } @@ -58,11 +52,10 @@ public void visit(de.uka.ilkd.key.java.visitor.Visitor v) { @Override public UpdateableOperator rename(Name name) { if (getKeYJavaType() != null) { - return new LocationVariable(new ProgramElementName(name.toString()), - getKeYJavaType(), getContainerType(), - isStatic(), isModel()); + return new LocationVariable(new ProgramElementName(name.toString()), getKeYJavaType(), + getContainerType(), isStatic(), isModel()); } else { return new LocationVariable(new ProgramElementName(name.toString()), sort()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LogicVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LogicVariable.java index e9a8fa95b7a..4788bc47b6b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LogicVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/LogicVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -5,21 +8,20 @@ /** - * The objects of this class represent logical variables, - * used e.g. for quantification. + * The objects of this class represent logical variables, used e.g. for quantification. */ -public final class LogicVariable extends AbstractSortedOperator - implements QuantifiableVariable, ParsableVariable { +public final class LogicVariable extends AbstractSortedOperator + implements QuantifiableVariable, ParsableVariable { public LogicVariable(Name name, Sort sort) { - super(name, sort, true); - assert sort != Sort.FORMULA; - assert sort != Sort.UPDATE; + super(name, sort, true); + assert sort != Sort.FORMULA; + assert sort != Sort.UPDATE; } - - + + @Override public String toString() { - return name() + ":" + sort(); + return name() + ":" + sort(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java index 44c019b0b40..203c00b3571 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/MixFitInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import javax.annotation.Nonnull; @@ -17,7 +20,9 @@ public MixFitInfo(@Nonnull Kind kind, @Nonnull String symbol) { this.symbol = symbol; } - public enum Kind {PREFIX, INFIX, SHORTCUT, POSTFIX} + public enum Kind { + PREFIX, INFIX, SHORTCUT, POSTFIX + } @Nonnull public Kind getKind() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ModalOperatorSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ModalOperatorSV.java index 5954167dc74..481212b61f9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ModalOperatorSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ModalOperatorSV.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableSet; @@ -8,21 +11,22 @@ /** * Schema variable matching modal operators. */ -public final class ModalOperatorSV extends AbstractSV { - - /** - * the set of modalities this sv can match +public final class ModalOperatorSV extends AbstractSV { + + /** + * the set of modalities this sv can match */ - private final ImmutableSet modalities; - - - /** creates a new SchemaVariable that is used as placeholder for - * modal operators. + private final ImmutableSet modalities; + + + /** + * creates a new SchemaVariable that is used as placeholder for modal operators. + * * @param name the Name of the SchemaVariable * @param modalities modal operators matched by this SV - */ + */ ModalOperatorSV(Name name, ImmutableSet modalities) { - super(name, new Sort[]{Sort.FORMULA}, Sort.FORMULA, false, false); + super(name, new Sort[] { Sort.FORMULA }, Sort.FORMULA, false, false); this.modalities = modalities; } @@ -32,28 +36,28 @@ public final class ModalOperatorSV extends AbstractSV { public ImmutableSet getModalities() { return modalities; } - - + + @Override public String toString() { - return toString(" (modal operator)"); + return toString(" (modal operator)"); } - - - @Override + + + @Override public String proofToString() { - StringBuffer result = new StringBuffer(); - result.append("\\schemaVar \\modalOperator {"); + StringBuffer result = new StringBuffer(); + result.append("\\schemaVar \\modalOperator {"); boolean first = true; - for(Modality modality : modalities) { - if(!first) { - result.append(", "); - }else{ - first = false; + for (Modality modality : modalities) { + if (!first) { + result.append(", "); + } else { + first = false; } - result.append(modality); - } - result.append("} ").append(name()).append(";\n"); - return result.toString(); + result.append(modality); + } + result.append("} ").append(name()).append(";\n"); + return result.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Modality.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Modality.java index b29e5599d65..42f2c878fe3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Modality.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Modality.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.util.LinkedHashMap; @@ -6,85 +9,86 @@ import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; -/** - * This class is used to represent a dynamic logic modality like - * diamond and box (but also extensions of DL like - * preserves and throughout are possible in the future). +/** + * This class is used to represent a dynamic logic modality like diamond and box (but also + * extensions of DL like preserves and throughout are possible in the future). */ public final class Modality extends AbstractSortedOperator { - private static final Map nameMap - = new LinkedHashMap(10); - - /** - * The diamond operator of dynamic logic. A formula - * Phi can be read as after processing the program alpha - * there exists a state such that Phi holds. - */ + private static final Map nameMap = new LinkedHashMap(10); + + /** + * The diamond operator of dynamic logic. A formula Phi can be read as after processing + * the program alpha there exists a state such that Phi holds. + */ public static final Modality DIA = new Modality(new Name("diamond")); - - /** - * The box operator of dynamic logic. A formula - * [alpha;]Phi can be read as 'In all states reachable - * processing the program alpha the formula Phi holds'. + + /** + * The box operator of dynamic logic. A formula [alpha;]Phi can be read as 'In all states + * reachable processing the program alpha the formula Phi holds'. */ public static final Modality BOX = new Modality(new Name("box")); - /** + /** * A Java Card transaction version of the diamond modality. Means that a transaction is * currently underway. - */ + */ public static final Modality DIA_TRANSACTION = new Modality(new Name("diamond_transaction")); - /** - * A Java Card transaction version of the box modality. Means that a transaction is - * currently underway. - */ + /** + * A Java Card transaction version of the box modality. Means that a transaction is currently + * underway. + */ public static final Modality BOX_TRANSACTION = new Modality(new Name("box_transaction")); - /** - * The throughout operator of dynamic logic. A formula - * [[alpha;]]Phi can be read as during processing the program alpha - * Phi should hold at every step of execution. - */ + /** + * The throughout operator of dynamic logic. A formula [[alpha;]]Phi can be read as during + * processing the program alpha Phi should hold at every step of execution. + */ public static final Modality TOUT = new Modality(new Name("throughout")); - /** + /** * A Java Card transaction version of the throughout modality. Means that a transaction is * currently underway. - */ - public static final Modality TOUT_TRANSACTION = new Modality(new Name("throughout_transaction")); + */ + public static final Modality TOUT_TRANSACTION = + new Modality(new Name("throughout_transaction")); + - - /** creates a modal operator with the given name - * @param name the Name of the modality + /** + * creates a modal operator with the given name + * + * @param name the Name of the modality */ private Modality(Name name) { - super(name, new Sort[]{Sort.FORMULA}, Sort.FORMULA, false); - nameMap.put(name.toString(), this); + super(name, new Sort[] { Sort.FORMULA }, Sort.FORMULA, false); + nameMap.put(name.toString(), this); } /** * Returns a modality corresponding to a string + * * @param str name of the modality to return */ public static Modality getModality(String str) { return nameMap.get(str); } - - /** Whether this modality is termination sensitive, - * i.e., it is a "diamond-kind" modality. + + /** + * Whether this modality is termination sensitive, i.e., it is a "diamond-kind" modality. + * * @return */ - public boolean terminationSensitive(){ + public boolean terminationSensitive() { return (this == DIA || this == DIA_TRANSACTION); } - - /** Whether this is a transaction modality + + /** + * Whether this is a transaction modality */ - public boolean transaction(){ + public boolean transaction() { return (this == BOX_TRANSACTION || this == DIA_TRANSACTION); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ObserverFunction.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ObserverFunction.java index 851ecf3586e..828d883025c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ObserverFunction.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ObserverFunction.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -9,18 +12,16 @@ /** - * Objects of this class represent "observer" function or predicate symbols. - * An observer symbol is a symbol taking a heap array as its first argument, - * and an object as its second argument (unless it is static). Observer - * symbols are used to represent JML model fields as well as occurrences of - * pure methods in specifications (via the subclass ProgramMethod). As they - * come from the Java program, both their parameter sorts and their result - * sorts always have an associated KeYJavaType. Observer symbols serve as - * the targets of contracts (i.e., as the subjects that the contracts are + * Objects of this class represent "observer" function or predicate symbols. An observer symbol is a + * symbol taking a heap array as its first argument, and an object as its second argument (unless it + * is static). Observer symbols are used to represent JML model fields as well as occurrences of + * pure methods in specifications (via the subclass ProgramMethod). As they come from the Java + * program, both their parameter sorts and their result sorts always have an associated KeYJavaType. + * Observer symbols serve as the targets of contracts (i.e., as the subjects that the contracts are * about). */ public class ObserverFunction extends Function implements IObserverFunction { - + private final KeYJavaType container; private final boolean isStatic; private final ImmutableArray paramTypes; @@ -28,105 +29,102 @@ public class ObserverFunction extends Function implements IObserverFunction { private final int heapCount; private final int stateCount; - - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- - - public ObserverFunction(String baseName, - Sort sort, - KeYJavaType type, - Sort heapSort, - KeYJavaType container, - boolean isStatic, - ImmutableArray paramTypes, - int heapCount, - int stateCount) { - super(createName(baseName, container), - sort, - getArgSorts(heapSort, container, isStatic, paramTypes, heapCount, stateCount)); - assert type == null || type.getSort() == sort; - assert container != null; - this.type = type; - this.container = container; - this.isStatic = isStatic; - this.paramTypes = paramTypes; - this.heapCount = heapCount; - this.stateCount = stateCount; + + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- + + public ObserverFunction(String baseName, Sort sort, KeYJavaType type, Sort heapSort, + KeYJavaType container, boolean isStatic, ImmutableArray paramTypes, + int heapCount, int stateCount) { + super(createName(baseName, container), sort, + getArgSorts(heapSort, container, isStatic, paramTypes, heapCount, stateCount)); + assert type == null || type.getSort() == sort; + assert container != null; + this.type = type; + this.container = container; + this.isStatic = isStatic; + this.paramTypes = paramTypes; + this.heapCount = heapCount; + this.stateCount = stateCount; } - + public static ProgramElementName createName(String baseName, KeYJavaType container) { - return new ProgramElementName(baseName, container.getSort().toString()); + return new ProgramElementName(baseName, container.getSort().toString()); } - - - - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- - - private static Sort[] getArgSorts(Sort heapSort, - KeYJavaType container, - boolean isStatic, - ImmutableArray paramTypes, - int heapCount, - int stateCount) { - final int arity = paramTypes.size() + stateCount*heapCount + (isStatic ? 0 : 1); - - final Sort[] result = new Sort[arity]; - - int offset; - - for(offset = 0; offset < stateCount * heapCount; offset++) { - result[offset] = heapSort; - } - if(!isStatic) { - result[offset] = container.getSort(); - assert result[offset] != null : "Bad KJT: " + container; - offset++; - } - - for(int i = 0, n = paramTypes.size(); i < n; i++) { - result[i + offset] = paramTypes.get(i).getSort(); - } - - return result; + + + + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- + + private static Sort[] getArgSorts(Sort heapSort, KeYJavaType container, boolean isStatic, + ImmutableArray paramTypes, int heapCount, int stateCount) { + final int arity = paramTypes.size() + stateCount * heapCount + (isStatic ? 0 : 1); + + final Sort[] result = new Sort[arity]; + + int offset; + + for (offset = 0; offset < stateCount * heapCount; offset++) { + result[offset] = heapSort; + } + if (!isStatic) { + result[offset] = container.getSort(); + assert result[offset] != null : "Bad KJT: " + container; + offset++; + } + + for (int i = 0, n = paramTypes.size(); i < n; i++) { + result[i + offset] = paramTypes.get(i).getSort(); + } + + return result; } - - - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#getType() - */ + + + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#getType() + */ @Override - public final KeYJavaType getType() { - return type; + public final KeYJavaType getType() { + return type; } - - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#getContainerType() - */ + + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#getContainerType() + */ @Override - public final KeYJavaType getContainerType() { - return container; + public final KeYJavaType getContainerType() { + return container; } - - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#isStatic() - */ + + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#isStatic() + */ @Override public final boolean isStatic() { - return isStatic; + return isStatic; } - - - /* (non-Javadoc) + + + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.logic.op.IObserverFunction#getStateCount() */ @Override @@ -135,34 +133,40 @@ public int getStateCount() { } @Override - public int getHeapCount(Services services) { - return heapCount; - } - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#getNumParams() - */ + public int getHeapCount(Services services) { + return heapCount; + } + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#getNumParams() + */ @Override - public final int getNumParams() { - return paramTypes.size(); + public final int getNumParams() { + return paramTypes.size(); } - - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#getParamType(int) - */ + + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#getParamType(int) + */ @Override - public final KeYJavaType getParamType(int i) { - return paramTypes.get(i); + public final KeYJavaType getParamType(int i) { + return paramTypes.get(i); } - - - /* (non-Javadoc) - * @see de.uka.ilkd.key.logic.op.IObserverFunction#getParamTypes() - */ + + + /* + * (non-Javadoc) + * + * @see de.uka.ilkd.key.logic.op.IObserverFunction#getParamTypes() + */ @Override - public final ImmutableArray getParamTypes() { - return paramTypes; + public final ImmutableArray getParamTypes() { + return paramTypes; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Operator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Operator.java index 4c4e4e1eca1..f27efa1d48c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Operator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Operator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Named; @@ -8,8 +11,8 @@ /** - * All symbols acting as members of a term e.g. logical operators, predicates, - * functions, variables etc. have to implement this interface. + * All symbols acting as members of a term e.g. logical operators, predicates, functions, variables + * etc. have to implement this interface. */ public interface Operator extends Named, SVSubstitute { @@ -20,14 +23,13 @@ public interface Operator extends Named, SVSubstitute { /** - * Determines the sort of the {@link Term} if it would be created using this - * Operator as top level operator and the given terms as sub terms. The - * assumption that the constructed term would be allowed is not checked. + * Determines the sort of the {@link Term} if it would be created using this Operator as top + * level operator and the given terms as sub terms. The assumption that the constructed term + * would be allowed is not checked. * - * @param terms an array of Term containing the subterms of a (potential) - * term with this operator as top level operator - * @return sort of the term with this operator as top level operator of the - * given substerms + * @param terms an array of Term containing the subterms of a (potential) term with this + * operator as top level operator + * @return sort of the term with this operator as top level operator of the given substerms */ Sort sort(ImmutableArray terms); @@ -45,11 +47,9 @@ public interface Operator extends Named, SVSubstitute { /** - * Checks whether the top level structure of the given @link Term - * is syntactically valid, given the assumption that the top level - * operator of the term is the same as this Operator. The - * assumption that the top level operator and the term are equal - * is NOT checked. + * Checks whether the top level structure of the given @link Term is syntactically valid, given + * the assumption that the top level operator of the term is the same as this Operator. The + * assumption that the top level operator and the term are equal is NOT checked. * * @throws TermCreationException if a construction error was recognise */ @@ -57,8 +57,8 @@ public interface Operator extends Named, SVSubstitute { /** - * @return true iff the top level structure of - * the {@link Term} is valid, i.e. its parameters and types are correct. + * @return true iff the top level structure of the {@link Term} is valid, i.e. its parameters + * and types are correct. */ default boolean validTopLevel(Term term) { try { @@ -68,4 +68,4 @@ default boolean validTopLevel(Term term) { return false; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ParsableVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ParsableVariable.java index d458ee4b5d8..b58d2e9b8f5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ParsableVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ParsableVariable.java @@ -1,9 +1,11 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; -/** - * This interface represents the variables that can be recognized - * by one of the parsers. +/** + * This interface represents the variables that can be recognized by one of the parsers. */ public interface ParsableVariable extends SortedOperator { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramConstant.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramConstant.java index 3dedd28b91b..a11401efe3c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramConstant.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramConstant.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -6,32 +9,27 @@ import de.uka.ilkd.key.logic.ProgramElementName; /** - * This class represents currently only static final fields initialised with - * a compile time constant. These fields cannot occur on the left side of an - * update. + * This class represents currently only static final fields initialised with a compile time + * constant. These fields cannot occur on the left side of an update. */ public final class ProgramConstant extends ProgramVariable { // the value of the initializer as a literal, if this variable is // a compile-time constant, null otherwise private final Literal compileTimeConstant; - - public ProgramConstant(ProgramElementName name, - KeYJavaType t, - KeYJavaType containingType, - boolean isStatic, - Literal compileTimeConstant) { + + public ProgramConstant(ProgramElementName name, KeYJavaType t, KeYJavaType containingType, + boolean isStatic, Literal compileTimeConstant) { super(name, t.getSort(), t, containingType, isStatic, false, false); this.compileTimeConstant = compileTimeConstant; } - - + + /** - * @return the value of the initializer as a literal, if this - * variable is a compile-time constant, null - * otherwise + * @return the value of the initializer as a literal, if this variable is a compile-time + * constant, null otherwise */ - public Literal getCompileTimeConstant () { + public Literal getCompileTimeConstant() { return compileTimeConstant; } @@ -44,8 +42,7 @@ public void visit(de.uka.ilkd.key.java.visitor.Visitor v) { @Override public Operator rename(Name name) { - return new ProgramConstant(new ProgramElementName(name.toString()), - getKeYJavaType(), getContainerType(), - isStatic(), compileTimeConstant); + return new ProgramConstant(new ProgramElementName(name.toString()), getKeYJavaType(), + getContainerType(), isStatic(), compileTimeConstant); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramMethod.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramMethod.java index 3ffe050a60d..d8805927fdf 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramMethod.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramMethod.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.io.IOException; @@ -40,9 +43,8 @@ import org.slf4j.LoggerFactory; /** - * The program method represents a (pure) method in the logic. In case of a - * non-static method the first argument represents the object on which the - * method is invoked. + * The program method represents a (pure) method in the logic. In case of a non-static method the + * first argument represents the object on which the method is invoked. */ public final class ProgramMethod extends ObserverFunction implements ProgramInLogic, IProgramMethod { @@ -51,8 +53,7 @@ public final class ProgramMethod extends ObserverFunction private final MethodDeclaration method; /** - * Return type of the method. Must not be null. Use KeYJavaType.VOID_TYPE - * for void methods. + * Return type of the method. Must not be null. Use KeYJavaType.VOID_TYPE for void methods. */ private final KeYJavaType returnType; private final PositionInfo pi; @@ -60,16 +61,15 @@ public final class ProgramMethod extends ObserverFunction // ------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------- - public ProgramMethod(MethodDeclaration method, KeYJavaType container, - KeYJavaType kjt, PositionInfo pi, final Sort heapSort) { + public ProgramMethod(MethodDeclaration method, KeYJavaType container, KeYJavaType kjt, + PositionInfo pi, final Sort heapSort) { this(method, container, kjt, pi, heapSort, 1); } - public ProgramMethod(MethodDeclaration method, KeYJavaType container, - KeYJavaType kjt, PositionInfo pi, Sort heapSort, int heapCount) { - super(method.getProgramElementName().toString(), kjt.getSort(), kjt, - heapSort, container, method.isStatic(), getParamTypes(method), - heapCount, method.getStateCount()); + public ProgramMethod(MethodDeclaration method, KeYJavaType container, KeYJavaType kjt, + PositionInfo pi, Sort heapSort, int heapCount) { + super(method.getProgramElementName().toString(), kjt.getSort(), kjt, heapSort, container, + method.isStatic(), getParamTypes(method), heapCount, method.getStateCount()); this.method = method; this.returnType = kjt; this.pi = pi; @@ -79,14 +79,11 @@ public ProgramMethod(MethodDeclaration method, KeYJavaType container, // internal methods // ------------------------------------------------------------------------- - private static ImmutableArray getParamTypes( - MethodDeclaration md) { - KeYJavaType[] result = new KeYJavaType[md - .getParameterDeclarationCount()]; + private static ImmutableArray getParamTypes(MethodDeclaration md) { + KeYJavaType[] result = new KeYJavaType[md.getParameterDeclarationCount()]; for (int i = 0; i < result.length; i++) { - result[i] = md.getParameterDeclarationAt(i) - .getVariableSpecification().getProgramVariable() - .getKeYJavaType(); + result[i] = md.getParameterDeclarationAt(i).getVariableSpecification() + .getProgramVariable().getKeYJavaType(); } return new ImmutableArray(result); } @@ -101,7 +98,7 @@ private static ImmutableArray getParamTypes( /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getMethodDeclaration() */ @Override @@ -111,18 +108,18 @@ public MethodDeclaration getMethodDeclaration() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getParameterType(int) */ @Override public KeYJavaType getParameterType(int i) { - return method.getParameterDeclarationAt(i).getVariableSpecification() - .getProgramVariable().getKeYJavaType(); + return method.getParameterDeclarationAt(i).getVariableSpecification().getProgramVariable() + .getKeYJavaType(); } /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getBody() */ @Override @@ -156,11 +153,10 @@ public void prettyPrint(PrettyPrinter w) throws IOException { } /** - * calls the corresponding method of a visitor in order to perform some - * action/transformation on this element - * - * @param v - * the Visitor + * 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) { @@ -168,10 +164,9 @@ public void visit(Visitor v) { } /** - * 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(). - * + * 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. */ @Override @@ -180,10 +175,9 @@ public Position 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(). - * + * 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. */ @Override @@ -192,11 +186,10 @@ public Position 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(). - * + * 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. */ @Override @@ -235,7 +228,7 @@ public boolean isPublic() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isConstructor() */ @Override @@ -245,7 +238,7 @@ public boolean isConstructor() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isModel() */ @Override @@ -263,7 +256,7 @@ public boolean isStrictFp() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isVoid() */ @Override @@ -290,8 +283,7 @@ public ProgramElement getChildAt(int i) { * equals modulo renaming is described in class SourceElement. */ @Override - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { if (se == null || !(se instanceof IProgramMethod)) { return false; } @@ -306,7 +298,7 @@ public KeYJavaType getKJT() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getReturnType() */ @Override @@ -323,13 +315,12 @@ public Expression convertToProgram(Term t, ExtList l) { called = (ProgramElement) l.get(0); l.remove(0); } - return new MethodReference(l, getProgramElementName(), - (ReferencePrefix) called); + return new MethodReference(l, getProgramElementName(), (ReferencePrefix) called); } /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getProgramElementName() */ @Override @@ -339,20 +330,20 @@ public ProgramElementName getProgramElementName() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getUniqueName() */ @Override public String getUniqueName() { return getName() + "_" - + Math.abs(ContractFactory.generateContractTypeName("", - getContainerType(), this, getContainerType()) + + Math.abs(ContractFactory + .generateContractTypeName("", getContainerType(), this, getContainerType()) .hashCode()); } // Included HashCode to make IF-Predicates unique and still reproducible /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getFullName() */ @Override @@ -362,7 +353,7 @@ public String getFullName() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getName() */ @Override @@ -372,7 +363,7 @@ public String getName() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isAbstract() */ @Override @@ -382,7 +373,7 @@ public boolean isAbstract() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isImplicit() */ @Override @@ -392,7 +383,7 @@ public boolean isImplicit() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isNative() */ @Override @@ -402,7 +393,7 @@ public boolean isNative() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isFinal() */ @Override @@ -412,7 +403,7 @@ public boolean isFinal() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#isSynchronized() */ @Override @@ -422,7 +413,7 @@ public boolean isSynchronized() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getThrown() */ @Override @@ -432,9 +423,8 @@ public Throws getThrown() { /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.logic.op.IProgramMethod#getParameterDeclarationAt(int) + * + * @see de.uka.ilkd.key.logic.op.IProgramMethod#getParameterDeclarationAt(int) */ @Override public ParameterDeclaration getParameterDeclarationAt(int index) { @@ -443,21 +433,18 @@ public ParameterDeclaration getParameterDeclarationAt(int index) { /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.logic.op.IProgramMethod#getVariableSpecification(int) + * + * @see de.uka.ilkd.key.logic.op.IProgramMethod#getVariableSpecification(int) */ @Override public VariableSpecification getVariableSpecification(int index) { - return method.getParameterDeclarationAt(index) - .getVariableSpecification(); + return method.getParameterDeclarationAt(index).getVariableSpecification(); } /* * (non-Javadoc) - * - * @see - * de.uka.ilkd.key.logic.op.IProgramMethod#getParameterDeclarationCount() + * + * @see de.uka.ilkd.key.logic.op.IProgramMethod#getParameterDeclarationCount() */ @Override public int getParameterDeclarationCount() { @@ -466,7 +453,7 @@ public int getParameterDeclarationCount() { /* * (non-Javadoc) - * + * * @see de.uka.ilkd.key.logic.op.IProgramMethod#getParameters() */ @Override @@ -488,14 +475,13 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { @Override public ImmutableList collectParameters() { - ImmutableList paramVars = ImmutableSLList - . nil(); + ImmutableList paramVars = ImmutableSLList.nil(); int numParams = getParameterDeclarationCount(); for (int i = numParams - 1; i >= 0; i--) { ParameterDeclaration pd = getParameterDeclarationAt(i); - IProgramVariable paramProgVar = pd.getVariableSpecification() - .getProgramVariable(); - assert paramProgVar instanceof LocationVariable : "Parameter declaration expected to be location var!"; + IProgramVariable paramProgVar = pd.getVariableSpecification().getProgramVariable(); + assert paramProgVar instanceof LocationVariable + : "Parameter declaration expected to be location var!"; LocationVariable paramLocVar = (LocationVariable) paramProgVar; paramVars = paramVars.prepend(paramLocVar); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramSV.java index 7a549142709..551586b498d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramSV.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.io.IOException; @@ -44,25 +47,21 @@ import recoder.service.KeYCrossReferenceSourceInfo; /** - * Objects of this class are schema variables matching program constructs within - * modal operators. The particular construct being matched is determined by the - * ProgramSVSort of the schema variable. + * Objects of this class are schema variables matching program constructs within modal operators. + * The particular construct being matched is determined by the ProgramSVSort of the schema variable. */ -public final class ProgramSV extends AbstractSV - implements ProgramConstruct, UpdateableOperator { +public final class ProgramSV extends AbstractSV implements ProgramConstruct, UpdateableOperator { public static final Logger LOGGER = LoggerFactory.getLogger(ProgramSV.class); - private static final ProgramList EMPTY_LIST_INSTANTIATION = new ProgramList( - new ImmutableArray(new ProgramElement[0])); + private static final ProgramList EMPTY_LIST_INSTANTIATION = + new ProgramList(new ImmutableArray(new ProgramElement[0])); private final boolean isListSV; /** * creates a new SchemaVariable used as a placeholder for program constructs - * - * @param name - * the Name of the SchemaVariable allowed to match a list of - * program constructs + * + * @param name the Name of the SchemaVariable allowed to match a list of program constructs */ ProgramSV(Name name, ProgramSVSort s, boolean isListSV) { super(name, s, false, false); @@ -77,14 +76,13 @@ public boolean isListSV() { * this method tests on object identity */ @Override - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { return se == this; } /** - * @return comments if the schemavariable stands for programm construct and - * has comments attached to it (not supported yet) + * @return comments if the schemavariable stands for programm construct and has comments + * attached to it (not supported yet) */ @Override public Comment[] getComments() { @@ -232,22 +230,18 @@ public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { } /** - * adds a found mapping from schema variable var to program - * element pe and returns the updated match conditions or null - * if mapping is not possible because of violating some variable condition - * - * @param pe - * the ProgramElement var is mapped to - * @param matchCond - * the MatchConditions to be updated - * @param services - * the Services provide access to the Java model - * @return the updated match conditions including mapping var - * to pe or null if some variable condition would be - * hurt by the mapping + * adds a found mapping from schema variable var to program element pe + * and returns the updated match conditions or null if mapping is not possible because of + * violating some variable condition + * + * @param pe the ProgramElement var is mapped to + * @param matchCond the MatchConditions to be updated + * @param services the Services provide access to the Java model + * @return the updated match conditions including mapping var to pe or + * null if some variable condition would be hurt by the mapping */ - private MatchConditions addProgramInstantiation(ProgramElement pe, - MatchConditions matchCond, Services services) { + private MatchConditions addProgramInstantiation(ProgramElement pe, MatchConditions matchCond, + Services services) { if (matchCond == null) { return null; } @@ -277,23 +271,18 @@ private MatchConditions addProgramInstantiation(ProgramElement pe, } /** - * adds a found mapping from schema variable var to the list of - * program elements list and returns the updated match - * conditions or null if mapping is not possible because of violating some - * variable condition - * - * @param list - * the ProgramList var is mapped to - * @param matchCond - * the MatchConditions to be updated - * @param services - * the Services provide access to the Java model - * @return the updated match conditions including mapping var - * to list or null if some variable condition would be - * hurt by the mapping + * adds a found mapping from schema variable var to the list of program elements + * list and returns the updated match conditions or null if mapping is not possible + * because of violating some variable condition + * + * @param list the ProgramList var is mapped to + * @param matchCond the MatchConditions to be updated + * @param services the Services provide access to the Java model + * @return the updated match conditions including mapping var to list + * or null if some variable condition would be hurt by the mapping */ - private MatchConditions addProgramInstantiation(ProgramList list, - MatchConditions matchCond, Services services) { + private MatchConditions addProgramInstantiation(ProgramList list, MatchConditions matchCond, + Services services) { if (matchCond == null) { return null; } @@ -312,26 +301,26 @@ private MatchConditions addProgramInstantiation(ProgramList list, return insts == null ? null : matchCond.setInstantiations(insts); } - private MatchConditions matchListSV(SourceData source, - MatchConditions matchCond) { + private MatchConditions matchListSV(SourceData source, MatchConditions matchCond) { final Services services = source.getServices(); ProgramElement src = source.getSource(); if (src == null) { - return addProgramInstantiation(EMPTY_LIST_INSTANTIATION, matchCond, - services); + return addProgramInstantiation(EMPTY_LIST_INSTANTIATION, matchCond, services); } SVInstantiations instantiations = matchCond.getInstantiations(); final ExecutionContext ec = instantiations.getExecutionContext(); - final java.util.ArrayList matchedElements = new java.util.ArrayList(); + final java.util.ArrayList matchedElements = + new java.util.ArrayList(); while (src != null) { if (!check(src, ec, services)) { - LOGGER.debug("taclet: Stopped list matching because of " - + "incompatible elements {} {}", this, src); + LOGGER.debug( + "taclet: Stopped list matching because of " + "incompatible elements {} {}", + this, src); break; } matchedElements.add(src); @@ -341,24 +330,19 @@ private MatchConditions matchListSV(SourceData source, LOGGER.debug("Program list match: {} {}", this, matchedElements); return addProgramInstantiation( - new ProgramList( - new ImmutableArray(matchedElements)), - matchCond, services); + new ProgramList(new ImmutableArray(matchedElements)), matchCond, + services); } /** - * returns true, if the given SchemaVariable can stand for the - * ProgramElement - * - * @param match - * the ProgramElement to be matched - * @param services - * the Services object encapsulating information about the java - * datastructures like (static)types etc. + * returns true, if the given SchemaVariable can stand for the ProgramElement + * + * @param match the ProgramElement to be matched + * @param services the Services object encapsulating information about the java datastructures + * like (static)types etc. * @return true if the SchemaVariable can stand for the given element */ - private boolean check(ProgramElement match, ExecutionContext ec, - Services services) { + private boolean check(ProgramElement match, ExecutionContext ec, Services services) { if (match == null) { return false; } @@ -386,8 +370,8 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { } final Object instant = instantiations.getInstantiation(this); - if (instant == null || instant.equals(src) || (instant instanceof Term - && ((Term) instant).op().equals(src))) { + if (instant == null || instant.equals(src) + || (instant instanceof Term && ((Term) instant).op().equals(src))) { matchCond = addProgramInstantiation(src, matchCond, services); @@ -398,8 +382,7 @@ public MatchConditions match(SourceData source, MatchConditions matchCond) { } } else { LOGGER.debug("taclet: MATCH FAILED 3. Former match of " - + " SchemaVariable incompatible with " - + " the current match."); + + " SchemaVariable incompatible with " + " the current match."); return null; // FAILED mismatch } source.next(); @@ -413,8 +396,7 @@ public String toString() { @Override public String proofToString() { - return "\\schemaVar \\program " + sort().declarationString() + " " - + name() + ";\n"; + return "\\schemaVar \\program " + sort().declarationString() + " " + name() + ";\n"; } @Override @@ -596,4 +578,4 @@ public IProgramMethod getMethodContext() { public ReferencePrefix getRuntimeInstance() { return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramVariable.java index 3d521474a8e..17197814667 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/ProgramVariable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import java.io.IOException; @@ -34,27 +37,20 @@ import recoder.service.KeYCrossReferenceSourceInfo; /** - * The objects of this class represent program variables and program - * constants (resulting from static final declarations in programs; TODO: it is - * weird that constants are a special case of variables). - * - * Additionally, as a legacy of the past, the RecodeR front end of KeY still - * creates objects of this class also for fields (aka. attributes, member - * variables), even though theoretically, these are *not* program variables - * (not any more)! Such fake "program variables" can be recognized by the fact - * that calling isMember() on them returns true. Thus, they must never occur in - * actual proofs. The method HeapLDT.getFieldSymbolForPV() serves to convert - * such fake program variables to the appropriate constant symbols. + * The objects of this class represent program variables and program constants (resulting from + * static final declarations in programs; TODO: it is weird that constants are a special case of + * variables). + * + * Additionally, as a legacy of the past, the RecodeR front end of KeY still creates objects of this + * class also for fields (aka. attributes, member variables), even though theoretically, these are + * *not* program variables (not any more)! Such fake "program variables" can be recognized by the + * fact that calling isMember() on them returns true. Thus, they must never occur in actual proofs. + * The method HeapLDT.getFieldSymbolForPV() serves to convert such fake program variables to the + * appropriate constant symbols. */ -public abstract class ProgramVariable extends AbstractSortedOperator - implements SourceElement, - ProgramElement, - Expression, - ReferencePrefix, - IProgramVariable, - ParsableVariable, - ReferenceSuffix, - ProgramInLogic { +public abstract class ProgramVariable extends AbstractSortedOperator + implements SourceElement, ProgramElement, Expression, ReferencePrefix, IProgramVariable, + ParsableVariable, ReferenceSuffix, ProgramInLogic { public static final Logger LOGGER = LoggerFactory.getLogger(ProgramVariable.class); private final KeYJavaType type; @@ -67,68 +63,58 @@ public abstract class ProgramVariable extends AbstractSortedOperator // the program variable denotes a field private final KeYJavaType containingType; - protected ProgramVariable(ProgramElementName name, - Sort s, - KeYJavaType t, - KeYJavaType containingType, - boolean isStatic, - boolean isModel, - boolean isGhost, - boolean isFinal) { - super(name, s == null ? t.getSort() : s, false); - this.type = t; - this.containingType = containingType; - this.isStatic = isStatic; - this.isModel = isModel; - this.isGhost = isGhost; - assert !(isModel && isGhost) : "Program variable cannot be model and ghost"; - this.isFinal = isFinal; - - assert sort() != Sort.FORMULA; - assert sort() != Sort.UPDATE; + protected ProgramVariable(ProgramElementName name, Sort s, KeYJavaType t, + KeYJavaType containingType, boolean isStatic, boolean isModel, boolean isGhost, + boolean isFinal) { + super(name, s == null ? t.getSort() : s, false); + this.type = t; + this.containingType = containingType; + this.isStatic = isStatic; + this.isModel = isModel; + this.isGhost = isGhost; + assert !(isModel && isGhost) : "Program variable cannot be model and ghost"; + this.isFinal = isFinal; + + assert sort() != Sort.FORMULA; + assert sort() != Sort.UPDATE; } - - - protected ProgramVariable(ProgramElementName name, - Sort s, - KeYJavaType t, - KeYJavaType containingType, - boolean isStatic, - boolean isModel, - boolean isGhost) { + + + protected ProgramVariable(ProgramElementName name, Sort s, KeYJavaType t, + KeYJavaType containingType, boolean isStatic, boolean isModel, boolean isGhost) { this(name, s, t, containingType, isStatic, isModel, isGhost, false); } - - + + /** @return name of the ProgramVariable */ public ProgramElementName getProgramElementName() { - return (ProgramElementName) name(); + return (ProgramElementName) name(); } - + /** * returns true iff the program variable has been declared as static */ public boolean isStatic() { - return isStatic; + return isStatic; } - + /** * returns true iff the program variable has been declared as model - */ + */ public boolean isModel() { - return isModel; + return isModel; } /** * returns true if the program variable has been declared as ghost */ public boolean isGhost() { - return isGhost; + return isGhost; } - - + + /** * returns true iff the program variable has been declared as final */ @@ -136,172 +122,170 @@ public boolean isFinal() { return isFinal; } - + /** * returns true iff the program variable is a member */ public boolean isMember() { - return containingType != null; + return containingType != null; } - + /** - * returns the KeYJavaType where the program variable is declared or - * null if the program variable denotes not a field + * returns the KeYJavaType where the program variable is declared or null if the program + * variable denotes not a field */ public KeYJavaType getContainerType() { - return containingType; + return containingType; } - + @Override - public SourceElement getFirstElement(){ - return this; + public SourceElement getFirstElement() { + return this; } @Override public SourceElement getFirstElementIncludingBlocks() { - return getFirstElement(); + return getFirstElement(); } - - @Override - public SourceElement getLastElement(){ - return this; + + @Override + public SourceElement getLastElement() { + return this; } - - @Override + + @Override public Comment[] getComments() { - return new Comment[0]; + return new Comment[0]; } - + @Override public void visit(de.uka.ilkd.key.java.visitor.Visitor v) { - v.performActionOnProgramVariable(this); + v.performActionOnProgramVariable(this); } @Override public void prettyPrint(PrettyPrinter w) throws IOException { - w.printProgramVariable(this); + w.printProgramVariable(this); } - + @Override - public Position getStartPosition(){ - return Position.UNDEFINED; + public Position getStartPosition() { + return Position.UNDEFINED; } - + @Override - public Position getEndPosition(){ - return Position.UNDEFINED; + public Position getEndPosition() { + return Position.UNDEFINED; } - + @Override - public Position getRelativePosition(){ - return Position.UNDEFINED; + public Position getRelativePosition() { + return Position.UNDEFINED; } - - @Override - public PositionInfo getPositionInfo(){ - return PositionInfo.UNDEFINED; + + @Override + public PositionInfo getPositionInfo() { + return PositionInfo.UNDEFINED; } - + @Override public KeYJavaType getKeYJavaType() { - return type; + return type; } - - @Override + + @Override public KeYJavaType getKeYJavaType(Services javaServ) { - return getKeYJavaType(); + return getKeYJavaType(); } - - @Override - public KeYJavaType getKeYJavaType(Services javaServ, - ExecutionContext ec) { - return getKeYJavaType(); + + @Override + public KeYJavaType getKeYJavaType(Services javaServ, ExecutionContext ec) { + return getKeYJavaType(); } - + /** - * We do not have a prefix, so fake it! - * This way we implement ReferencePrefix + * We do not have a prefix, so fake it! This way we implement ReferencePrefix + * * @author VK */ - @Override + @Override public ReferencePrefix getReferencePrefix() { - return null; + return null; } - - /** equals modulo renaming is described in the corresponding - * comment in class SourceElement. In this case two - * programvariables are considered to be equal if they are - * assigned to the same abstract name or if they are the same - * object. + + /** + * equals modulo renaming is described in the corresponding comment in class SourceElement. In + * this case two programvariables are considered to be equal if they are assigned to the same + * abstract name or if they are the same object. */ - @Override - public boolean equalsModRenaming(SourceElement se, - NameAbstractionTable nat) { - return nat.sameAbstractName(this, se); + @Override + public boolean equalsModRenaming(SourceElement se, NameAbstractionTable nat) { + return nat.sameAbstractName(this, se); } - - @Override + + @Override public Expression convertToProgram(Term t, ExtList l) { - if(isStatic()) { - return new FieldReference(this, - new TypeRef(getContainerType())); - } else { - return this; - } + if (isStatic()) { + return new FieldReference(this, new TypeRef(getContainerType())); + } else { + return this; + } } - - + + public String proofToString() { - final Type javaType = type.getJavaType(); - final String typeName; - if(javaType instanceof ArrayType) { - typeName = ((ArrayType)javaType).getAlternativeNameRepresentation(); - } else if(javaType != null) { - typeName = javaType.getFullName(); - } else { - typeName = type.getSort().name().toString(); - } - return typeName + " " + name() + ";\n"; + final Type javaType = type.getJavaType(); + final String typeName; + if (javaType instanceof ArrayType) { + typeName = ((ArrayType) javaType).getAlternativeNameRepresentation(); + } else if (javaType != null) { + typeName = javaType.getFullName(); + } else { + typeName = type.getSort().name().toString(); + } + return typeName + " " + name() + ";\n"; } - + public boolean isImplicit() { - return getProgramElementName().getProgramName().startsWith("<"); + return getProgramElementName().getProgramName().startsWith("<"); } @Override - public MatchConditions match(SourceData source, MatchConditions matchCond) { + public MatchConditions match(SourceData source, MatchConditions matchCond) { final ProgramElement src = source.getSource(); source.next(); if (src == this) { return matchCond; } else { - LOGGER.debug("Program match failed. Not same program variable (pattern {}, source {})", this, src); + LOGGER.debug("Program match failed. Not same program variable (pattern {}, source {})", + this, src); return null; - } + } } /** * Returns an equivalent variable with the new name. - * @param name the new name - * @return equivalent operator with the new name + * + * @param name the new name + * @return equivalent operator with the new name */ abstract public Operator rename(Name name); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/QuantifiableVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/QuantifiableVariable.java index 922f949ed50..3150bc4a085 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/QuantifiableVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/QuantifiableVariable.java @@ -1,9 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; -/** - * This interface represents the variables that can be bound - * (by quantifiers or other binding operators). +/** + * This interface represents the variables that can be bound (by quantifiers or other binding + * operators). */ public interface QuantifiableVariable extends ParsableVariable { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Quantifier.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Quantifier.java index cb4b2708b35..1f29564b69e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Quantifier.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Quantifier.java @@ -1,36 +1,33 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; /** - * The two objects of this class represent the universal and the existential - * quantifier, respectively. + * The two objects of this class represent the universal and the existential quantifier, + * respectively. */ public final class Quantifier extends AbstractSortedOperator { public static final Name ALL_NAME = new Name("all"); public static final Name EX_NAME = new Name("exists"); - - /** - * the usual 'forall' operator 'all' (be A a formula then - * 'all x.A' is true if and only if for all elements d of the - * universe A{x<-d} (x substituted with d) is true + + /** + * the usual 'forall' operator 'all' (be A a formula then 'all x.A' is true if and only if for + * all elements d of the universe A{x<-d} (x substituted with d) is true */ public static final Quantifier ALL = new Quantifier(ALL_NAME); - - /** - * the usual 'exists' operator 'ex' (be A a formula then - * 'ex x.A' is true if and only if there is at least one elements - * d of the universe such that A{x<-d} (x substituted with d) is true - */ + + /** + * the usual 'exists' operator 'ex' (be A a formula then 'ex x.A' is true if and only if there + * is at least one elements d of the universe such that A{x<-d} (x substituted with d) is true + */ public static final Quantifier EX = new Quantifier(EX_NAME); private Quantifier(Name name) { - super(name, - new Sort[]{Sort.FORMULA}, - Sort.FORMULA, - new Boolean[]{true}, - true); + super(name, new Sort[] { Sort.FORMULA }, Sort.FORMULA, new Boolean[] { true }, true); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SVSubstitute.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SVSubstitute.java index 1efb1d97575..f9ccf66a5f1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SVSubstitute.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SVSubstitute.java @@ -1,9 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; -/** - * JavaCardDL syntactical elements implement this interface if they can - * occur as instantiations of schema variables. +/** + * JavaCardDL syntactical elements implement this interface if they can occur as instantiations of + * schema variables. */ public interface SVSubstitute { -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariable.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariable.java index 91d549bcd03..268eab14428 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariable.java @@ -1,26 +1,26 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; /** - * This interface represents the root of a schema variable hierarchy to be - * express termstructures that match on logical terms. Schema variables - * are used in Taclets where they act as placeholders for other - * TermSymbols. The TermSymbols a SchemaVariable is allowed to match - * is specified by their type and sort. + * This interface represents the root of a schema variable hierarchy to be express termstructures + * that match on logical terms. Schema variables are used in Taclets where they act as placeholders + * for other TermSymbols. The TermSymbols a SchemaVariable is allowed to match is specified by their + * type and sort. */ public interface SchemaVariable extends ParsableVariable { - + /** - * @return true if the schemavariable has the strict modifier which forces - * the instantiation to have exactly the same sort as the - * schemavariable (or if the sv is of generic sort - the - * instantiation of the generic sort) + * @return true if the schemavariable has the strict modifier which forces the instantiation to + * have exactly the same sort as the schemavariable (or if the sv is of generic sort - + * the instantiation of the generic sort) */ boolean isStrict(); - + /** - * Creates a parseable string representation of the declaration of the - * schema variable. + * Creates a parseable string representation of the declaration of the schema variable. */ String proofToString(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariableFactory.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariableFactory.java index aa19909b36b..746baebb82e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariableFactory.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SchemaVariableFactory.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableSet; @@ -7,95 +10,92 @@ import de.uka.ilkd.key.logic.sort.ProgramSVSort; import de.uka.ilkd.key.logic.sort.Sort; -/** A factory class for different Schema Variables +/** + * A factory class for different Schema Variables */ public class SchemaVariableFactory { private SchemaVariableFactory() {} - + /** - * creates a SchemaVariable representing quantified variables + * creates a SchemaVariable representing quantified variables + * * @param name the Name of the SchemaVariable - * @param sort the Sort of the variable the SchemaVariable will be - * used to represent + * @param sort the Sort of the variable the SchemaVariable will be used to represent * @return the SchemaVariable */ - public static VariableSV createVariableSV(Name name, - Sort sort) { - return new VariableSV(name, sort); + public static VariableSV createVariableSV(Name name, Sort sort) { + return new VariableSV(name, sort); } - /** + /** * creates a SchemaVariable representing a term but not a formula + * * @param name the Name of the SchemaVariable - * @param sort the Sort of the term the SchemaVariable will be - * used to represent - * @param rigidness true iff this SV may only match rigid - * terms/formulas - * @param strictSV boolean indicating if the schemavariable is declared as strict - * forcing exact type match + * @param sort the Sort of the term the SchemaVariable will be used to represent + * @param rigidness true iff this SV may only match rigid terms/formulas + * @param strictSV boolean indicating if the schemavariable is declared as strict forcing exact + * type match * @return the SchemaVariable */ - public static TermSV createTermSV(Name name, - Sort sort, - boolean rigidness, - boolean strictSV) { - return new TermSV(name, sort, rigidness, strictSV); + public static TermSV createTermSV(Name name, Sort sort, boolean rigidness, boolean strictSV) { + return new TermSV(name, sort, rigidness, strictSV); } - + /** - * creates a SchemaVariable representing an operator - * @param name the Name of the SchemaVariable - * @return the SchemaVariable - */ - public static ModalOperatorSV createModalOperatorSV(Name name, - Sort sort, - ImmutableSet modalities) { - return new ModalOperatorSV(name, modalities); + * creates a SchemaVariable representing an operator + * + * @param name the Name of the SchemaVariable + * @return the SchemaVariable + */ + public static ModalOperatorSV createModalOperatorSV(Name name, Sort sort, + ImmutableSet modalities) { + return new ModalOperatorSV(name, modalities); } - + public static TermSV createTermSV(Name name, Sort sort) { - return createTermSV(name, sort, false, false); + return createTermSV(name, sort, false, false); } - - /** creates a SchemaVariable representing a formula + + /** + * creates a SchemaVariable representing a formula + * * @param name the Name of the SchemaVariable - * @param rigidness true iff this SV may only match rigid - * terms/formulas + * @param rigidness true iff this SV may only match rigid terms/formulas * @return the SchemaVariable */ public static FormulaSV createFormulaSV(Name name, boolean rigidness) { - return new FormulaSV(name, rigidness); + return new FormulaSV(name, rigidness); } - + public static FormulaSV createFormulaSV(Name name) { - return createFormulaSV(name, false); + return createFormulaSV(name, false); } - - + + public static UpdateSV createUpdateSV(Name name) { - return new UpdateSV(name); + return new UpdateSV(name); } - - /** creates a SchemaVariable representing a program construct + + /** + * creates a SchemaVariable representing a program construct */ - public static ProgramSV createProgramSV(ProgramElementName name, - ProgramSVSort s, - boolean listSV) { - return new ProgramSV(name, s, listSV); + public static ProgramSV createProgramSV(ProgramElementName name, ProgramSVSort s, + boolean listSV) { + return new ProgramSV(name, s, listSV); } - /** + /** * creates a SchemaVariable representing a skolem term */ public static SkolemTermSV createSkolemTermSV(Name name, Sort s) { - return new SkolemTermSV(name, s); + return new SkolemTermSV(name, s); } /** @@ -104,4 +104,4 @@ public static SkolemTermSV createSkolemTermSV(Name name, Sort s) { public static TermLabelSV createTermLabelSV(Name name) { return new TermLabelSV(name); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SkolemTermSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SkolemTermSV.java index 7fbd298e6de..61cb37bae8b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SkolemTermSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SkolemTermSV.java @@ -1,42 +1,40 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; /** - * Schema variable that is instantiated with fresh Skolem constants. At the - * moment, such schema variables have to be accompanied by a "NewDependingOn" - * varcond, although with the removal of the meta variable mechanism, this - * would no longer really be necessary. + * Schema variable that is instantiated with fresh Skolem constants. At the moment, such schema + * variables have to be accompanied by a "NewDependingOn" varcond, although with the removal of the + * meta variable mechanism, this would no longer really be necessary. */ public final class SkolemTermSV extends AbstractSV { - /** - * Creates a new schema variable that is used as placeholder for - * skolem terms. + /** + * Creates a new schema variable that is used as placeholder for skolem terms. + * * @param name the Name of the SchemaVariable - * @param sort the Sort of the SchemaVariable and the matched type - * allowed to match a list of program constructs - */ + * @param sort the Sort of the SchemaVariable and the matched type allowed to match a list of + * program constructs + */ SkolemTermSV(Name name, Sort sort) { - super(name, sort, true, false); - assert sort != Sort.UPDATE; + super(name, sort, true, false); + assert sort != Sort.UPDATE; } - + @Override public String toString() { - return toString(sort().toString() + " skolem term"); + return toString(sort().toString() + " skolem term"); } - - + + @Override public String proofToString() { - return "\\schemaVar " - + (sort() == Sort.FORMULA - ? "\\skolemFormula" - : "\\skolemTerm " + sort().name()) - + " " - + name() - + ";\n"; + return "\\schemaVar " + + (sort() == Sort.FORMULA ? "\\skolemFormula" : "\\skolemTerm " + sort().name()) + + " " + name() + ";\n"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortDependingFunction.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortDependingFunction.java index 8d94de41ae5..872d9fe214b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortDependingFunction.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortDependingFunction.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.java.Services; @@ -14,13 +17,10 @@ /** - * The objects of this class represent families of function symbols, where - * each family contains an instantiation of a template symbol for a particular - * sort. - * The following invariant has to hold: - * Given two sort depending functions f1 and f2 then - * from f1.isSimilar(f2) and f1.getSortDependingOn() == f2.getSortDependingOn() - * follows f1 == f2 + * The objects of this class represent families of function symbols, where each family contains an + * instantiation of a template symbol for a particular sort. The following invariant has to hold: + * Given two sort depending functions f1 and f2 then from f1.isSimilar(f2) and + * f1.getSortDependingOn() == f2.getSortDependingOn() follows f1 == f2 */ public final class SortDependingFunction extends Function { private static final Logger LOGGER = LoggerFactory.getLogger(SortDependingFunction.class); @@ -29,93 +29,71 @@ public final class SortDependingFunction extends Function { private final Sort sortDependingOn; - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- - private SortDependingFunction(SortDependingFunctionTemplate template, - Sort sortDependingOn) { + private SortDependingFunction(SortDependingFunctionTemplate template, Sort sortDependingOn) { super(instantiateName(template.kind, sortDependingOn), instantiateResultSort(template, sortDependingOn), - instantiateArgSorts(template, sortDependingOn), - null, - template.unique, false); + instantiateArgSorts(template, sortDependingOn), null, template.unique, false); this.template = template; this.sortDependingOn = sortDependingOn; } - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- - private static Name instantiateName(Name kind, - Sort sortDependingOn) { + private static Name instantiateName(Name kind, Sort sortDependingOn) { return new Name(sortDependingOn + "::" + kind); } - private static Sort instantiateResultSort( - SortDependingFunctionTemplate template, + private static Sort instantiateResultSort(SortDependingFunctionTemplate template, Sort sortDependingOn) { - return template.sort == template.sortDependingOn - ? sortDependingOn - : template.sort; + return template.sort == template.sortDependingOn ? sortDependingOn : template.sort; } - private static ImmutableArray instantiateArgSorts( - SortDependingFunctionTemplate template, + private static ImmutableArray instantiateArgSorts(SortDependingFunctionTemplate template, Sort sortDependingOn) { Sort[] result = new Sort[template.argSorts.size()]; for (int i = 0; i < result.length; i++) { - result[i] - = (template.argSorts.get(i) == template.sortDependingOn - ? sortDependingOn + result[i] = (template.argSorts.get(i) == template.sortDependingOn ? sortDependingOn : template.argSorts.get(i)); } return new ImmutableArray<>(result); } - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- @Override public int hashCode() { return name().hashCode(); } - public static SortDependingFunction createFirstInstance( - GenericSort sortDependingOn, - Name kind, - Sort sort, - Sort[] argSorts, - boolean unique) { - SortDependingFunctionTemplate template - = new SortDependingFunctionTemplate(sortDependingOn, - kind, - sort, - new ImmutableArray<>(argSorts), - unique); + public static SortDependingFunction createFirstInstance(GenericSort sortDependingOn, Name kind, + Sort sort, Sort[] argSorts, boolean unique) { + SortDependingFunctionTemplate template = new SortDependingFunctionTemplate(sortDependingOn, + kind, sort, new ImmutableArray<>(argSorts), unique); return new SortDependingFunction(template, Sort.ANY); } - public static SortDependingFunction getFirstInstance(Name kind, - TermServices services) { - return (SortDependingFunction) - services.getNamespaces() - .functions() - .lookup(instantiateName(kind, Sort.ANY)); + public static SortDependingFunction getFirstInstance(Name kind, TermServices services) { + return (SortDependingFunction) services.getNamespaces().functions() + .lookup(instantiateName(kind, Sort.ANY)); } /** * returns the variant for the given sort * - * @param sort the {@link Sort} for which to retrieve the corresponding - * variant of this function + * @param sort the {@link Sort} for which to retrieve the corresponding variant of this function * @param services the {@link Services} * @return the variant for the given sort */ @@ -124,32 +102,32 @@ public synchronized SortDependingFunction getInstanceFor(Sort sort, TermServices return this; } - SortDependingFunction n = - (SortDependingFunction) - services.getNamespaces().lookup(instantiateName(getKind(), sort)); + SortDependingFunction n = (SortDependingFunction) services.getNamespaces() + .lookup(instantiateName(getKind(), sort)); - if (sort instanceof ProgramSVSort) throw new AssertionError(); - if (sort == AbstractTermTransformer.METASORT) throw new AssertionError(); + if (sort instanceof ProgramSVSort) + throw new AssertionError(); + if (sort == AbstractTermTransformer.METASORT) + throw new AssertionError(); final NamespaceSet namespaces = services.getNamespaces(); Namespace functions = namespaces.functions(); SortDependingFunction result; synchronized (namespaces) { - result = (SortDependingFunction) - namespaces.lookup(instantiateName(getKind(), sort)); - //ugly: multiple generic sorts with the same name may exist over time + result = (SortDependingFunction) namespaces.lookup(instantiateName(getKind(), sort)); + // ugly: multiple generic sorts with the same name may exist over time - if (result != null - && sort instanceof GenericSort + if (result != null && sort instanceof GenericSort && result.getSortDependingOn() != sort) { result = new SortDependingFunction(template, sort); synchronized (functions) { functions.add(result); if (instantiateName(getKind(), sort).toString().contains("String") && instantiateName(getKind(), sort).toString().contains("seqGet") - && (n == null || sort instanceof GenericSort && n.getSortDependingOn() != sort)) { + && (n == null || sort instanceof GenericSort + && n.getSortDependingOn() != sort)) { LOGGER.debug("Hash code: {}", result.hashCode()); } } @@ -170,8 +148,9 @@ && instantiateName(getKind(), sort).toString().contains("seqGet") } if (result.getSortDependingOn() != sort) { - throw new AssertionError(String.format("%s depends on %s (hash %d) but should depend on %s (hash %d)", - result, result.getSortDependingOn(), result.hashCode(), sort, sort.hashCode())); + throw new AssertionError(String.format( + "%s depends on %s (hash %d) but should depend on %s (hash %d)", result, + result.getSortDependingOn(), result.hashCode(), sort, sort.hashCode())); } if (!isSimilar(result)) { throw new AssertionError(result + " should be similar to " + this); @@ -198,9 +177,9 @@ public Name getKind() { return template.kind; } - //------------------------------------------------------------------------- - //inner classes - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // inner classes + // ------------------------------------------------------------------------- private static final class SortDependingFunctionTemplate { public final GenericSort sortDependingOn; @@ -209,11 +188,8 @@ private static final class SortDependingFunctionTemplate { public final ImmutableArray argSorts; public final boolean unique; - public SortDependingFunctionTemplate(GenericSort sortDependingOn, - Name kind, - Sort sort, - ImmutableArray argSorts, - boolean unique) { + public SortDependingFunctionTemplate(GenericSort sortDependingOn, Name kind, Sort sort, + ImmutableArray argSorts, boolean unique) { this.sortDependingOn = sortDependingOn; this.kind = kind; this.sort = sort; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortedOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortedOperator.java index 8267ac257a2..5f33adcec3e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortedOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SortedOperator.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -5,14 +8,14 @@ import de.uka.ilkd.key.logic.sort.Sort; -/** +/** * Operator with well-defined argument and result sorts. */ public interface SortedOperator extends Operator { - + Sort sort(); Sort argSort(int i); - + public ImmutableArray argSorts(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SubstOp.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SubstOp.java index de540e4d983..960caca6afe 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SubstOp.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/SubstOp.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -9,62 +12,60 @@ import de.uka.ilkd.key.logic.sort.Sort; /** - * Standard first-order substitution operator, resolving clashes but not - * preventing (usually unsound) substitution of non-rigid terms across modal - * operators. Currently, only the subclass WarySubstOp is used - * and accessible through the key parser. + * Standard first-order substitution operator, resolving clashes but not preventing (usually + * unsound) substitution of non-rigid terms across modal operators. Currently, only the subclass + * WarySubstOp is used and accessible through the key parser. */ public abstract class SubstOp extends AbstractOperator { protected SubstOp(Name name) { - super(name, 2, new Boolean[]{false, true}, true); + super(name, 2, new Boolean[] { false, true }, true); } /** - * @return sort of the second subterm or throws an - * IllegalArgumentException if the given term has no correct (2=) arity + * @return sort of the second subterm or throws an IllegalArgumentException if the given term + * has no correct (2=) arity */ @Override public Sort sort(ImmutableArray terms) { - if(terms.size() == 2) { + if (terms.size() == 2) { return terms.get(1).sort(); - } - else throw new IllegalArgumentException("Cannot determine sort of "+ - "invalid term (Wrong arity)."); + } else + throw new IllegalArgumentException( + "Cannot determine sort of " + "invalid term (Wrong arity)."); } /** - * @return true iff the sort of the subterm 0 of the given term - * has the same sort as or a subsort of the variable to be substituted - * and the - * term's arity is 2 and the numer of variables bound there is 0 - * for the 0th subterm and 1 for the 1st subterm. + * @return true iff the sort of the subterm 0 of the given term has the same sort as or a + * subsort of the variable to be substituted and the term's arity is 2 and the numer of + * variables bound there is 0 for the 0th subterm and 1 for the 1st subterm. */ @Override - protected void additionalValidTopLevel(Term term){ - if(term.varsBoundHere(1).size() != 1) { + protected void additionalValidTopLevel(Term term) { + if (term.varsBoundHere(1).size() != 1) { throw new TermCreationException(this, term); } Sort substSort = term.sub(0).sort(); Sort varSort = term.varsBoundHere(1).get(0).sort(); - if(!substSort.extendsTrans(varSort)) { + if (!substSort.extendsTrans(varSort)) { throw new TermCreationException(this, term); } } /** - * Apply this substitution operator to term, which - * has this operator as top-level operator + * Apply this substitution operator to term, which has this operator as top-level + * operator + * * @param term the {@link Term} on which to apply the substitution * @param tb the {@link TermBuilder} to use for term construction */ public abstract Term apply(Term term, TermBuilder tb);// { - // QuantifiableVariable v = term.varsBoundHere(1).getQuantifiableVariable(0); - // ClashFreeSubst cfSubst = new ClashFreeSubst(v, term.sub(0)); - // Term res = cfSubst.apply(term.sub(1)); - // return res; - // } -} \ No newline at end of file + // QuantifiableVariable v = term.varsBoundHere(1).getQuantifiableVariable(0); + // ClashFreeSubst cfSubst = new ClashFreeSubst(v, term.sub(0)); + // Term res = cfSubst.apply(term.sub(1)); + // return res; + // } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermLabelSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermLabelSV.java index fa797f7fc8d..45148dddd39 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermLabelSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermLabelSV.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -38,4 +41,4 @@ public Object getChild(int i) { public int getChildCount() { return 0; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermSV.java index 56b35302463..bec04063c11 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermSV.java @@ -1,36 +1,38 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; -/** +/** * A schema variable that is used as placeholder for terms. - */ + */ public final class TermSV extends AbstractSV { - /** + /** * @param name the name of the schema variable - * @param sort the sort of the schema variable - * @param isRigid true iff this schema variable may only match rigid - * terms - * @param isStrict boolean indicating if the schema variable is declared as - * strict forcing exact type match - */ - TermSV(Name name, Sort sort, boolean isRigid, boolean isStrict) { + * @param sort the sort of the schema variable + * @param isRigid true iff this schema variable may only match rigid terms + * @param isStrict boolean indicating if the schema variable is declared as strict forcing exact + * type match + */ + TermSV(Name name, Sort sort, boolean isRigid, boolean isStrict) { super(name, sort, isRigid, isStrict); assert sort != Sort.FORMULA; assert sort != Sort.UPDATE; } - + @Override public String toString() { - return toString(sort().toString()+" term"); + return toString(sort().toString() + " term"); } - - + + @Override public String proofToString() { - return "\\schemaVar \\term " + sort().name() + " " + name() + ";\n"; + return "\\schemaVar \\term " + sort().name() + " " + name() + ";\n"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermTransformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermTransformer.java index 559f644535c..be7161df389 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermTransformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/TermTransformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.java.Services; @@ -5,14 +8,14 @@ import de.uka.ilkd.key.rule.inst.SVInstantiations; /** - * TermTransformer perform complex term transformation which cannot be - * (efficiently or at all) described by taclets. + * TermTransformer perform complex term transformation which cannot be (efficiently or at all) + * described by taclets. */ public interface TermTransformer extends SortedOperator { /** - * initiates term transformation of term. Note the top level operator of - * of parameter term has to be this term transformer. + * initiates term transformation of term. Note the top level operator of of parameter + * term has to be this term transformer. */ Term transform(Term term, SVInstantiations svInst, Services services); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Transformer.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Transformer.java index ce62a97acd7..87b20f7f4a0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Transformer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/Transformer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import org.key_project.util.collection.ImmutableArray; @@ -11,11 +14,11 @@ import de.uka.ilkd.key.logic.sort.Sort; /** - * Functions with a restricted/special rule set only applicable for the top level - * of the term transformer and not directly for its arguments, prohibiting any rule - * applications to sub arguments as well as applications from outside such as update applications. - * They work similar to the idea of 'Predicate Transformer Semantics' as introduced by Dijkstra in - * "Guarded commands, nondeterminacy and formal derivation of programs". + * Functions with a restricted/special rule set only applicable for the top level of the term + * transformer and not directly for its arguments, prohibiting any rule applications to sub + * arguments as well as applications from outside such as update applications. They work similar to + * the idea of 'Predicate Transformer Semantics' as introduced by Dijkstra in "Guarded commands, + * nondeterminacy and formal derivation of programs". * * Note that in the taclets, arguments such as "a -> b" need to be written as "(a -> b)", in order * to let the parser know that the argument is "a -> b" and not "a" followed by a syntactic error. @@ -33,22 +36,20 @@ public Transformer(Name name, Sort argSort) { } /** - * Looks up the function namespace for a term transformer with the given - * attributes, assuming it to be uniquely defined by its name. If none is found, - * a new term transformer is created. + * Looks up the function namespace for a term transformer with the given attributes, assuming it + * to be uniquely defined by its name. If none is found, a new term transformer is created. + * * @param name name of the term transformer * @param sort sort of the term transformer * @param argSorts array of the transformer's argument sorts * @param services * @return the term transformer of interest */ - public static Transformer getTransformer(Name name, - Sort sort, - ImmutableArray argSorts, - TermServices services) { + public static Transformer getTransformer(Name name, Sort sort, ImmutableArray argSorts, + TermServices services) { final Named f = services.getNamespaces().functions().lookup(name); if (f != null && f instanceof Transformer) { - Transformer t = (Transformer)f; + Transformer t = (Transformer) f; assert t.sort() == sort; assert t.argSorts().size() == argSorts.size(); return t; @@ -57,20 +58,21 @@ public static Transformer getTransformer(Name name, } /** - * Takes a template for a term transformer and checks in the function - * namespace, whether an equivalent already exists. If this is the case, - * it returns the found transformer, otherwise it creates a new one. + * Takes a template for a term transformer and checks in the function namespace, whether an + * equivalent already exists. If this is the case, it returns the found transformer, otherwise + * it creates a new one. + * * @param t the template for a term transformer * @param services * @return the term transformer to be used */ - public static Transformer getTransformer(Transformer t, - TermServices services) { + public static Transformer getTransformer(Transformer t, TermServices services) { return getTransformer(t.name(), t.sort(), t.argSorts(), services); } /** * Examines a position for whether it is inside a term transformer. + * * @param pio A position in an occurrence of a term * @return true if inside a term transformer, false otherwise */ @@ -79,13 +81,13 @@ public static boolean inTransformer(PosInOccurrence pio) { if (pio == null) { return false; } - if ( pio.posInTerm () != null ) { - PIOPathIterator it = pio.iterator (); - Operator op; + if (pio.posInTerm() != null) { + PIOPathIterator it = pio.iterator(); + Operator op; - while ( it.next () != -1 && !trans) { - final Term t = it.getSubTerm (); - op = t.op (); + while (it.next() != -1 && !trans) { + final Term t = it.getSubTerm(); + op = t.op(); trans = op instanceof Transformer; } } @@ -93,23 +95,24 @@ public static boolean inTransformer(PosInOccurrence pio) { } /** - * Examines a position for whether it is inside a term transformer. - * If this is the case, the found term transformer is returned. + * Examines a position for whether it is inside a term transformer. If this is the case, the + * found term transformer is returned. + * * @param pio A position in an occurrence of a term * @return the term transformer the position is in, null otherwise */ public static Transformer getTransformer(PosInOccurrence pio) { - if ( pio.posInTerm () != null ) { - PIOPathIterator it = pio.iterator (); - Operator op; + if (pio.posInTerm() != null) { + PIOPathIterator it = pio.iterator(); + Operator op; - while ( it.next () != -1) { - final Term t = it.getSubTerm (); - op = t.op (); + while (it.next() != -1) { + final Term t = it.getSubTerm(); + op = t.op(); if (op instanceof Transformer) - return (Transformer)op; + return (Transformer) op; } } return null; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateApplication.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateApplication.java index 94451d016de..cb79b4681b2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateApplication.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateApplication.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.TermCreationException; @@ -9,67 +12,66 @@ /** - * Singleton class defining a binary operator {u}t that applies updates u to - * terms, formulas, or other updates t. + * Singleton class defining a binary operator {u}t that applies updates u to terms, formulas, or + * other updates t. */ public final class UpdateApplication extends AbstractOperator { - - public static final UpdateApplication UPDATE_APPLICATION - = new UpdateApplication(); + + public static final UpdateApplication UPDATE_APPLICATION = new UpdateApplication(); private UpdateApplication() { - super(new Name("update-application" ), 2, false); + super(new Name("update-application"), 2, false); } - - @Override + + @Override public Sort sort(ImmutableArray terms) { - return terms.get(1).sort(); - } - - + return terms.get(1).sort(); + } + + @Override - public void additionalValidTopLevel (Term term) { + public void additionalValidTopLevel(Term term) { if (term.sub(0).sort() != Sort.UPDATE) { throw new TermCreationException(this, term); } } - - + + /** * @return the index of the subterm representing the update being applied */ public static int updatePos() { - return 0; + return 0; } - - + + /** * @return the subterm representing the update being applies * @param t term with this operator as top level operator */ public static Term getUpdate(Term t) { - assert t.op() == UPDATE_APPLICATION; - return t.sub(updatePos()); + assert t.op() == UPDATE_APPLICATION; + return t.sub(updatePos()); } - - + + /** - * @return the index of the subterm representing the formula/term/update - * that the update is applied to + * @return the index of the subterm representing the formula/term/update that the update is + * applied to */ public static int targetPos() { - return 1; + return 1; } - - + + /** * @return the subterm representing the formula/term the update is applied to * @param t term with this operator as top level operator - */ + */ public static Term getTarget(Term t) { - assert t.op() == UPDATE_APPLICATION; - return t.sub(targetPos()); + assert t.op() == UPDATE_APPLICATION; + return t.sub(targetPos()); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateJunctor.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateJunctor.java index da9e4ca71a8..f8b6de56a52 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateJunctor.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateJunctor.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -5,30 +8,28 @@ /** - * Class of update junctor operators, i.e., operators connecting - * a given number of updates to create another update. There - * are currently two such operators: the empty update "skip" and - * the parallel update connector "|". + * Class of update junctor operators, i.e., operators connecting a given number of updates to create + * another update. There are currently two such operators: the empty update "skip" and the parallel + * update connector "|". */ public final class UpdateJunctor extends AbstractSortedOperator { - - public static final UpdateJunctor SKIP - = new UpdateJunctor(new Name("skip"), 0); - - public static final UpdateJunctor PARALLEL_UPDATE - = new UpdateJunctor(new Name("parallel-upd"), 2); - - + + public static final UpdateJunctor SKIP = new UpdateJunctor(new Name("skip"), 0); + + public static final UpdateJunctor PARALLEL_UPDATE = + new UpdateJunctor(new Name("parallel-upd"), 2); + + private static Sort[] createUpdateSortArray(int arity) { - Sort[] result = new Sort[arity]; - for(int i = 0; i < arity; i++) { - result[i] = Sort.UPDATE; - } - return result; + Sort[] result = new Sort[arity]; + for (int i = 0; i < arity; i++) { + result[i] = Sort.UPDATE; + } + return result; } - - + + private UpdateJunctor(Name name, int arity) { - super(name, createUpdateSortArray(arity), Sort.UPDATE, false); - } -} \ No newline at end of file + super(name, createUpdateSortArray(arity), Sort.UPDATE, false); + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateSV.java index 7a2250e46c5..37dc7f9f112 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateSV.java @@ -1,28 +1,31 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.sort.Sort; -/** +/** * A schema variable that is used as placeholder for updates. - */ + */ public final class UpdateSV extends AbstractSV { - - UpdateSV(Name name) { + + UpdateSV(Name name) { super(name, Sort.UPDATE, false, true); } - - + + @Override public String toString() { return toString("update"); } - - + + @Override public String proofToString() { - return "\\schemaVar \\update " + name() + ";\n"; - } -} \ No newline at end of file + return "\\schemaVar \\update " + name() + ";\n"; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateableOperator.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateableOperator.java index 9227371bb09..46e107bd163 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateableOperator.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/UpdateableOperator.java @@ -1,10 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; -/** - * Operators implementing this interface may stand for - * locations as well. This means e.g. occur as top level operators on the - * left side of an assignment pair of an update. +/** + * Operators implementing this interface may stand for locations as well. This means e.g. occur as + * top level operators on the left side of an assignment pair of an update. */ public interface UpdateableOperator extends SortedOperator, ParsableVariable { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/VariableSV.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/VariableSV.java index d7d6a013834..aa95de070e7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/VariableSV.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/VariableSV.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -8,29 +11,25 @@ */ public final class VariableSV extends AbstractSV implements QuantifiableVariable { - /** - * Creates a new SchemaVariable that is used as placeholder for - * bound(quantified) variables. + /** + * Creates a new SchemaVariable that is used as placeholder for bound(quantified) variables. + * * @param name the Name of the SchemaVariable - * @param sort the Sort of the SchemaVariable and the matched type + * @param sort the Sort of the SchemaVariable and the matched type */ VariableSV(Name name, Sort sort) { - super(name, sort, true, false); + super(name, sort, true, false); } - + @Override public String toString() { - return toString("variable"); + return toString("variable"); } - - + + @Override public String proofToString() { - return "\\schemaVar \\variables " - + sort().name() - + " " - + name() - + ";\n"; - } -} \ No newline at end of file + return "\\schemaVar \\variables " + sort().name() + " " + name() + ";\n"; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/WarySubstOp.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/WarySubstOp.java index f88c9c5bc8b..8ece8985b5a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/WarySubstOp.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/op/WarySubstOp.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.op; import de.uka.ilkd.key.logic.Name; @@ -8,9 +11,10 @@ public final class WarySubstOp extends SubstOp { - /** the wary substitution operator {var<-term}'. {x<-d}'A(x) means - * replace all free occurrences of variable x in A with d, however - * without replacing x with a non-rigid A below modalities */ + /** + * the wary substitution operator {var<-term}'. {x<-d}'A(x) means replace all free occurrences + * of variable x in A with d, however without replacing x with a non-rigid A below modalities + */ public static final SubstOp SUBST = new WarySubstOp(new Name("subst")); @@ -20,8 +24,8 @@ private WarySubstOp(Name name) { @Override - public Term apply ( Term term, TermBuilder tb ) { - QuantifiableVariable v=term.varsBoundHere(1).get(0); + public Term apply(Term term, TermBuilder tb) { + QuantifiableVariable v = term.varsBoundHere(1).get(0); WaryClashFreeSubst cfSubst = new WaryClashFreeSubst(v, term.sub(0), tb); return cfSubst.apply(term.sub(1)); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/AbstractSort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/AbstractSort.java index 63bcac9429b..5e3062fcd91 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/AbstractSort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/AbstractSort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import de.uka.ilkd.key.java.Services; @@ -20,6 +23,7 @@ public abstract class AbstractSort implements Sort { /** * Documentation for this sort given by the an associated documentation comment. + * * @see de.uka.ilkd.key.nparser.KeYParser.One_sort_declContext#doc */ private String documentation; @@ -63,7 +67,8 @@ public final boolean extendsTrans(Sort sort) { return true; } - return extendsSorts().exists((Sort superSort) -> superSort == sort || superSort.extendsTrans(sort)); + return extendsSorts() + .exists((Sort superSort) -> superSort == sort || superSort.extendsTrans(sort)); } @@ -81,7 +86,8 @@ public final boolean isAbstract() { @Override public final SortDependingFunction getCastSymbol(TermServices services) { - SortDependingFunction castFunction = SortDependingFunction.getFirstInstance(CAST_NAME, services); + SortDependingFunction castFunction = + SortDependingFunction.getFirstInstance(CAST_NAME, services); if (castFunction == null) { throw new IllegalStateException("Your namespaces does `cast' defined."); } @@ -93,9 +99,8 @@ public final SortDependingFunction getCastSymbol(TermServices services) { @Override public final SortDependingFunction getInstanceofSymbol(TermServices services) { - SortDependingFunction result - = SortDependingFunction.getFirstInstance(INSTANCE_NAME, services) - .getInstanceFor(this, services); + SortDependingFunction result = SortDependingFunction + .getFirstInstance(INSTANCE_NAME, services).getInstanceFor(this, services); assert result.getSortDependingOn() == this; return result; } @@ -103,9 +108,8 @@ public final SortDependingFunction getInstanceofSymbol(TermServices services) { @Override public final SortDependingFunction getExactInstanceofSymbol(TermServices services) { - SortDependingFunction result - = SortDependingFunction.getFirstInstance(EXACT_INSTANCE_NAME, services) - .getInstanceFor(this, services); + SortDependingFunction result = SortDependingFunction + .getFirstInstance(EXACT_INSTANCE_NAME, services).getInstanceFor(this, services); assert result.getSortDependingOn() == this; return result; } @@ -139,4 +143,4 @@ public String getOrigin() { public void setOrigin(@Nullable String origin) { this.origin = origin; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ArraySort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ArraySort.java index fbb305f2cfe..5c6db16e679 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ArraySort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ArraySort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import de.uka.ilkd.key.java.abstraction.PrimitiveType; @@ -10,21 +13,19 @@ import java.util.WeakHashMap; /** - * The objects of this class represent array sorts (in the sense of *Java* - * arrays). There can be one such sort for every element sort; however, the - * array sorts are only created lazily on demand. + * The objects of this class represent array sorts (in the sense of *Java* arrays). There can be one + * such sort for every element sort; however, the array sorts are only created lazily on demand. *

    - * More precisely, there can be one array sort for every pair (element sort, - * element type); i.e., there can be several array sorts for the same element - * sort, distinguished by their element *type*. This is used for the integer - * types of Java: these are all mapped to the sort "int" (i.e., the mathematical - * integers), but we have different array sorts int[], byte[], char[], short[] - * and long[], all storing mathematical integers. + * More precisely, there can be one array sort for every pair (element sort, element type); i.e., + * there can be several array sorts for the same element sort, distinguished by their element + * *type*. This is used for the integer types of Java: these are all mapped to the sort "int" (i.e., + * the mathematical integers), but we have different array sorts int[], byte[], char[], short[] and + * long[], all storing mathematical integers. */ public final class ArraySort extends AbstractSort { - private static final WeakHashMap> aSH - = new WeakHashMap>(); + private static final WeakHashMap> aSH = + new WeakHashMap>(); /** * keeping this key is important to prevent for too early hashmap removal @@ -32,52 +33,48 @@ public final class ArraySort extends AbstractSort { private final SortKey sk; - //------------------------------------------------------------------------- - //constructors - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // constructors + // ------------------------------------------------------------------------- private ArraySort(ImmutableSet extendsSorts, SortKey sk) { - super(new Name((sk.elemType != null - ? sk.elemType.getName() - : sk.elemSort.name()) - + "[]"), - extendsSorts, - false); + super(new Name((sk.elemType != null ? sk.elemType.getName() : sk.elemSort.name()) + "[]"), + extendsSorts, false); if (extendsSorts.isEmpty()) { - throw new IllegalArgumentException("An ArraySort extends typically three sorts" + - " (java.lang.Object, java.lang.Serializable, java.lang.Cloneable). You gave 0 sorts."); + throw new IllegalArgumentException("An ArraySort extends typically three sorts" + + " (java.lang.Object, java.lang.Serializable, java.lang.Cloneable). You gave 0 sorts."); } if (sk.elemSort instanceof GenericSort) { - throw new IllegalArgumentException("array sorts with generic element sorts currently not supported"); + throw new IllegalArgumentException( + "array sorts with generic element sorts currently not supported"); } this.sk = sk; } - //------------------------------------------------------------------------- - //internal methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // internal methods + // ------------------------------------------------------------------------- - private static ImmutableSet getArraySuperSorts(Sort elemSort, - Sort objectSort, - Sort cloneableSort, - Sort serializableSort) { + private static ImmutableSet getArraySuperSorts(Sort elemSort, Sort objectSort, + Sort cloneableSort, Sort serializableSort) { ImmutableSet result = DefaultImmutableSet.nil(); ImmutableSet elemDirectSuperSorts = elemSort.extendsSorts(); - if (elemDirectSuperSorts.size() == 1 && elemDirectSuperSorts.iterator().next().equals(Sort.ANY)) { - if (objectSort != null) result = result.add(objectSort); - if (cloneableSort != null) result = result.add(cloneableSort); - if (serializableSort != null) result = result.add(serializableSort); + if (elemDirectSuperSorts.size() == 1 + && elemDirectSuperSorts.iterator().next().equals(Sort.ANY)) { + if (objectSort != null) + result = result.add(objectSort); + if (cloneableSort != null) + result = result.add(cloneableSort); + if (serializableSort != null) + result = result.add(serializableSort); } else { for (Sort s : elemDirectSuperSorts) { - result = result.add(getArraySort(s, - objectSort, - cloneableSort, - serializableSort)); + result = result.add(getArraySort(s, objectSort, cloneableSort, serializableSort)); } } @@ -85,42 +82,31 @@ private static ImmutableSet getArraySuperSorts(Sort elemSort, } - //------------------------------------------------------------------------- - //public interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- + // public interface + // ------------------------------------------------------------------------- /** - * Returns the ArraySort to the given element sort and element type. This - * method ensures that only one ArraySort-object exists for each array sort. + * Returns the ArraySort to the given element sort and element type. This method ensures that + * only one ArraySort-object exists for each array sort. */ - public static ArraySort getArraySort(Sort elemSort, - Type elemType, - Sort objectSort, - Sort cloneableSort, - Sort serializableSort) { - if (elemType != PrimitiveType.JAVA_BYTE - && elemType != PrimitiveType.JAVA_CHAR - && elemType != PrimitiveType.JAVA_INT - && elemType != PrimitiveType.JAVA_LONG + public static ArraySort getArraySort(Sort elemSort, Type elemType, Sort objectSort, + Sort cloneableSort, Sort serializableSort) { + if (elemType != PrimitiveType.JAVA_BYTE && elemType != PrimitiveType.JAVA_CHAR + && elemType != PrimitiveType.JAVA_INT && elemType != PrimitiveType.JAVA_LONG && elemType != PrimitiveType.JAVA_SHORT) { elemType = null; } // this wrapper is required as some element sorts are shared among // several environments (int, boolean) - final SortKey sortKey = new SortKey(elemSort, - elemType, - objectSort, - cloneableSort, - serializableSort); + final SortKey sortKey = + new SortKey(elemSort, elemType, objectSort, cloneableSort, serializableSort); WeakReference ref = aSH.get(sortKey); ArraySort as = ref != null ? ref.get() : null; if (as == null) { - ImmutableSet localExtendsSorts - = getArraySuperSorts(elemSort, - objectSort, - cloneableSort, - serializableSort); + ImmutableSet localExtendsSorts = + getArraySuperSorts(elemSort, objectSort, cloneableSort, serializableSort); as = new ArraySort(localExtendsSorts, sortKey); aSH.put(sortKey, new WeakReference(as)); } @@ -128,39 +114,22 @@ public static ArraySort getArraySort(Sort elemSort, } - public static ArraySort getArraySort(Sort elemSort, - Sort objectSort, - Sort cloneableSort, - Sort serializableSort) { - return getArraySort(elemSort, - null, - objectSort, - cloneableSort, - serializableSort); + public static ArraySort getArraySort(Sort elemSort, Sort objectSort, Sort cloneableSort, + Sort serializableSort) { + return getArraySort(elemSort, null, objectSort, cloneableSort, serializableSort); } /** * returns elemSort([])^n. */ - public static Sort getArraySortForDim(Sort elemSort, - Type elemType, - int n, - Sort objectSort, - Sort cloneableSort, - Sort serializableSort) { + public static Sort getArraySortForDim(Sort elemSort, Type elemType, int n, Sort objectSort, + Sort cloneableSort, Sort serializableSort) { assert n > 0; - Sort result = getArraySort(elemSort, - elemType, - objectSort, - cloneableSort, - serializableSort); + Sort result = getArraySort(elemSort, elemType, objectSort, cloneableSort, serializableSort); while (n > 1) { - result = getArraySort(result, - objectSort, - cloneableSort, - serializableSort); + result = getArraySort(result, objectSort, cloneableSort, serializableSort); n--; } return result; @@ -182,11 +151,8 @@ private static final class SortKey { final Sort javaLangSerializable; final Sort javaLangCloneable; - public SortKey(Sort elemSort, - Type elemType, - Sort javaLangObjectSort, - Sort javaLangCloneable, - Sort javaLangSerializable) { + public SortKey(Sort elemSort, Type elemType, Sort javaLangObjectSort, + Sort javaLangCloneable, Sort javaLangSerializable) { this.elemSort = elemSort; this.elemType = elemType; this.javaLangObjectSort = javaLangObjectSort; @@ -200,8 +166,7 @@ public boolean equals(Object o) { return false; } final SortKey sk = (SortKey) o; - return elemSort == sk.elemSort - && elemType == sk.elemType + return elemSort == sk.elemSort && elemType == sk.elemType && javaLangObjectSort == sk.javaLangObjectSort && javaLangSerializable == sk.javaLangSerializable && javaLangCloneable == sk.javaLangCloneable; @@ -209,11 +174,10 @@ public boolean equals(Object o) { public int hashCode() { - return elemSort.hashCode() - + (elemType == null ? 0 : 31 * elemType.hashCode()) + return elemSort.hashCode() + (elemType == null ? 0 : 31 * elemType.hashCode()) + (javaLangCloneable == null ? 0 : 31 * javaLangCloneable.hashCode()) + (javaLangObjectSort == null ? 0 : 17 * javaLangObjectSort.hashCode()) + (javaLangSerializable == null ? 0 : 3 * javaLangSerializable.hashCode()); } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSort.java index 17124fff22f..0cfea8c5b61 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import java.util.Iterator; @@ -10,118 +13,104 @@ /** * Sort used for generic taclets * - * Within an SVInstantiations-object a generic sort is instantiated by - * a concrete sort, which has to be a subsort of the instantiations of - * the supersorts of this sort + * Within an SVInstantiations-object a generic sort is instantiated by a concrete sort, which has to + * be a subsort of the instantiations of the supersorts of this sort */ public final class GenericSort extends AbstractSort { - + /** - * A possible instantiation of this generic sort by a concrete - * sort must satisfy each of these conditions: + * A possible instantiation of this generic sort by a concrete sort must satisfy each of these + * conditions: * - * - if any generic supersort is to be instantiated simultanously, - then this instantiation has to be a supersort of the - instantiation of this sort + * - if any generic supersort is to be instantiated simultanously, then this instantiation has + * to be a supersort of the instantiation of this sort * - * - the instantiation of this sort has to be a subsort of every - concrete supersort + * - the instantiation of this sort has to be a subsort of every concrete supersort * - * - if "oneOf" is not empty, the instantiation must be an element - of "oneOf" + * - if "oneOf" is not empty, the instantiation must be an element of "oneOf" */ - + /** - * list of sorts this generic sort may be instantiated with; - * EMPTY_SORT_SORT means that every sort may be used + * list of sorts this generic sort may be instantiated with; EMPTY_SORT_SORT means that every + * sort may be used */ private final ImmutableSet oneOf; - - /** + + /** * creates a generic sort - * @param ext supersorts of this sort, which have to be either - * concrete sorts or plain generic sorts (i.e. not collection - * sorts of generic sorts) + * + * @param ext supersorts of this sort, which have to be either concrete sorts or plain generic + * sorts (i.e. not collection sorts of generic sorts) */ - public GenericSort( - Name name, - ImmutableSet ext, - ImmutableSet oneOf) - throws GenericSupersortException { + public GenericSort(Name name, ImmutableSet ext, ImmutableSet oneOf) + throws GenericSupersortException { super(name, ext, false); - this.oneOf = oneOf; - checkSupersorts(); + this.oneOf = oneOf; + checkSupersorts(); } - + public GenericSort(Name name) { - super(name, DefaultImmutableSet.nil(), false); - this.oneOf = DefaultImmutableSet.nil(); + super(name, DefaultImmutableSet.nil(), false); + this.oneOf = DefaultImmutableSet.nil(); } - - private void checkSupersorts () - throws GenericSupersortException { - Iterator it = extendsSorts ().iterator (); - Sort s, t; - while ( it.hasNext () ) { - s = it.next (); - if ( s instanceof ArraySort ) { - t = ((ArraySort)s).elementSort (); - while ( t instanceof ArraySort ) - t = ((ArraySort)t).elementSort (); - if ( t instanceof GenericSort ) - throw new GenericSupersortException - ( "Illegal supersort " + s + - " for generic sort " + name (), - s ); - } - } + + private void checkSupersorts() throws GenericSupersortException { + Iterator it = extendsSorts().iterator(); + Sort s, t; + while (it.hasNext()) { + s = it.next(); + if (s instanceof ArraySort) { + t = ((ArraySort) s).elementSort(); + while (t instanceof ArraySort) + t = ((ArraySort) t).elementSort(); + if (t instanceof GenericSort) + throw new GenericSupersortException( + "Illegal supersort " + s + " for generic sort " + name(), s); + } + } } /** * @return possible instantiations */ - public ImmutableSet getOneOf () { - return oneOf; + public ImmutableSet getOneOf() { + return oneOf; } /** - * @return true if "p_s" is a possible instantiation of this - * sort. This method does not check the instantiations of other - * generic sorts, i.e. the return value true is possible even if - * "p_s" is not a valid instantiation. + * @return true if "p_s" is a possible instantiation of this sort. This method does not check + * the instantiations of other generic sorts, i.e. the return value true is possible + * even if "p_s" is not a valid instantiation. * - * Use "GenericSortInstantiations" instead + * Use "GenericSortInstantiations" instead */ - public boolean isPossibleInstantiation ( Sort p_s ) { - return - p_s != Sort.FORMULA && - ( oneOf.isEmpty() || oneOf.contains ( p_s ) ) && - checkNonGenericSupersorts ( p_s ); + public boolean isPossibleInstantiation(Sort p_s) { + return p_s != Sort.FORMULA && (oneOf.isEmpty() || oneOf.contains(p_s)) + && checkNonGenericSupersorts(p_s); } /** - * @return true iff "p_s" is subsort of every non-generic - * supersort of this sort + * @return true iff "p_s" is subsort of every non-generic supersort of this sort */ - protected boolean checkNonGenericSupersorts ( Sort p_s ) { - Iterator it = extendsSorts().iterator (); - Sort ss; - - while ( it.hasNext () ) { - ss = it.next (); - if ( ss instanceof GenericSort ) { - if ( !((GenericSort)ss).checkNonGenericSupersorts ( p_s ) ) - return false; - } else { - if ( !p_s.extendsTrans ( ss ) ) - return false; - } - } - - return true; + protected boolean checkNonGenericSupersorts(Sort p_s) { + Iterator it = extendsSorts().iterator(); + Sort ss; + + while (it.hasNext()) { + ss = it.next(); + if (ss instanceof GenericSort) { + if (!((GenericSort) ss).checkNonGenericSupersorts(p_s)) + return false; + } else { + if (!p_s.extendsTrans(ss)) + return false; + } + } + + return true; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSupersortException.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSupersortException.java index fd34eb237d5..b93904c65ed 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSupersortException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/GenericSupersortException.java @@ -1,23 +1,26 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; -/** this exception is thrown if a generic sort has been declared with - * an illegal supersort */ +/** + * this exception is thrown if a generic sort has been declared with an illegal supersort + */ public class GenericSupersortException extends Exception { /** - * + * */ private static final long serialVersionUID = -5897308261866997061L; Sort illegalSort; - public GenericSupersortException ( String description, - Sort illegalSort ) { - super(description); - this.illegalSort = illegalSort; + public GenericSupersortException(String description, Sort illegalSort) { + super(description); + this.illegalSort = illegalSort; } - public Sort getIllegalSort () { - return illegalSort; + public Sort getIllegalSort() { + return illegalSort; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/NullSort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/NullSort.java index a3ddf7fdc98..73947ad405f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/NullSort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/NullSort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import java.lang.ref.WeakReference; @@ -13,113 +16,105 @@ /** - * There is one instance of this class per proof, representing the sort "Null". - * This sort is a subsort of all object sorts. Unfortunately, NullSort sometimes - * has to be treated as a special case, because it cannot support the method - * extendsSorts() (without a Services parameter) -- for this, the object would - * have to "know" all the object sorts, but these sorts are created only after - * the NullSort object itself has to be created; and immutability prevents us - * from filling in this information later. + * There is one instance of this class per proof, representing the sort "Null". This sort is a + * subsort of all object sorts. Unfortunately, NullSort sometimes has to be treated as a special + * case, because it cannot support the method extendsSorts() (without a Services parameter) -- for + * this, the object would have to "know" all the object sorts, but these sorts are created only + * after the NullSort object itself has to be created; and immutability prevents us from filling in + * this information later. */ -public final class NullSort implements Sort { - +public final class NullSort implements Sort { + public static final Name NAME = new Name("Null"); - + private final Sort objectSort; - - private WeakReference lastServices - = new WeakReference(null); - private WeakReference> extCache - = new WeakReference>(null); - - + + private WeakReference lastServices = new WeakReference(null); + private WeakReference> extCache = + new WeakReference>(null); + + public NullSort(Sort objectSort) { - assert objectSort != null; - this.objectSort = objectSort; + assert objectSort != null; + this.objectSort = objectSort; } - - + + @Override public Name name() { - return NAME; + return NAME; } - - + + @Override public ImmutableSet extendsSorts() { - throw new UnsupportedOperationException( - "NullSort.extendsSorts() cannot be supported"); + throw new UnsupportedOperationException("NullSort.extendsSorts() cannot be supported"); } - - + + @Override public ImmutableSet extendsSorts(Services services) { - assert services != null; - assert objectSort == services.getJavaInfo().objectSort(); - - ImmutableSet result = extCache.get(); - if(result == null || lastServices.get() != services) { - result = DefaultImmutableSet.nil(); - - for(Named n : services.getNamespaces().sorts().allElements()) { - Sort s = (Sort)n; - if(s != this && s.extendsTrans(objectSort)) { - result = result.add(s); - } - } - - lastServices = new WeakReference(services); - extCache = new WeakReference>(result); - } - - return result; + assert services != null; + assert objectSort == services.getJavaInfo().objectSort(); + + ImmutableSet result = extCache.get(); + if (result == null || lastServices.get() != services) { + result = DefaultImmutableSet.nil(); + + for (Named n : services.getNamespaces().sorts().allElements()) { + Sort s = (Sort) n; + if (s != this && s.extendsTrans(objectSort)) { + result = result.add(s); + } + } + + lastServices = new WeakReference(services); + extCache = new WeakReference>(result); + } + + return result; } - - + + @Override public boolean extendsTrans(Sort sort) { - return sort == this - || sort == Sort.ANY - || sort.extendsTrans(objectSort); + return sort == this || sort == Sort.ANY || sort.extendsTrans(objectSort); } - - + + @Override public boolean isAbstract() { - return false; + return false; } - - + + @Override public final SortDependingFunction getCastSymbol(TermServices services) { - SortDependingFunction result - = SortDependingFunction.getFirstInstance(CAST_NAME, services) - .getInstanceFor(this, services); + SortDependingFunction result = SortDependingFunction.getFirstInstance(CAST_NAME, services) + .getInstanceFor(this, services); assert result.getSortDependingOn() == this && result.sort() == this; return result; } - - - @Override + + + @Override public final SortDependingFunction getInstanceofSymbol(TermServices services) { - SortDependingFunction result - = SortDependingFunction.getFirstInstance(INSTANCE_NAME, services) - .getInstanceFor(this, services); - assert result.getSortDependingOn() == this; - return result; - } - - + SortDependingFunction result = SortDependingFunction + .getFirstInstance(INSTANCE_NAME, services).getInstanceFor(this, services); + assert result.getSortDependingOn() == this; + return result; + } + + @Override public final SortDependingFunction getExactInstanceofSymbol(TermServices services) { - SortDependingFunction result - = SortDependingFunction.getFirstInstance(EXACT_INSTANCE_NAME, services) - .getInstanceFor(this, services); - assert result.getSortDependingOn() == this; - return result; + SortDependingFunction result = SortDependingFunction + .getFirstInstance(EXACT_INSTANCE_NAME, services).getInstanceFor(this, services); + assert result.getSortDependingOn() == this; + return result; } - - + + @Override public final String toString() { return NAME.toString(); @@ -129,4 +124,4 @@ public final String toString() { public String declarationString() { return NAME.toString(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProgramSVSort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProgramSVSort.java index 9475d15477f..03f958d2038 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProgramSVSort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProgramSVSort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import java.util.LinkedHashMap; @@ -52,8 +55,8 @@ import org.slf4j.LoggerFactory; /** - * Special "sorts" used for schema variables matching program constructs - * (class ProgramSV). Not really sorts in the theoretical meaning of the word. + * Special "sorts" used for schema variables matching program constructs (class ProgramSV). Not + * really sorts in the theoretical meaning of the word. */ public abstract class ProgramSVSort extends AbstractSort { private static final Logger LOGGER = LoggerFactory.getLogger(ProgramSVSort.class); @@ -64,7 +67,7 @@ public abstract class ProgramSVSort extends AbstractSort { private static final Map NAME2SORT = new LinkedHashMap<>(60); - //----------- Types of Expression Program SVs ---------------------------- + // ----------- Types of Expression Program SVs ---------------------------- public static final ProgramSVSort LEFTHANDSIDE = new LeftHandSideSort(); @@ -84,7 +87,7 @@ public abstract class ProgramSVSort extends AbstractSort { public static final ProgramSVSort EXPRESSION = new ExpressionSort(); - //----------- Initialisation and Creation expressions ------------------- + // ----------- Initialisation and Creation expressions ------------------- public static final ProgramSVSort SIMPLE_NEW = new SimpleNewSVSort(); @@ -98,13 +101,13 @@ public abstract class ProgramSVSort extends AbstractSort { new SpecialConstructorReferenceSort(); - //----------- Expressions with restrictions on kind of type ------------- + // ----------- Expressions with restrictions on kind of type ------------- public static final NonSimpleMethodReferenceSort NONSIMPLEMETHODREFERENCE = new NonSimpleMethodReferenceSort(); - //----------- Types of Statement Program SVs ----------------------------- + // ----------- Types of Statement Program SVs ----------------------------- public static final ProgramSVSort STATEMENT = new StatementSort(); @@ -118,7 +121,7 @@ public abstract class ProgramSVSort extends AbstractSort { public static final ProgramSVSort PROGRAMMETHOD = new ProgramMethodSort(); - //-----------Types-------------------------------------------------------- + // -----------Types-------------------------------------------------------- public static final ProgramSVSort TYPE = new TypeReferenceSort(); @@ -127,157 +130,96 @@ public abstract class ProgramSVSort extends AbstractSort { public static final ProgramSVSort CLASSREFERENCE = new MetaClassReferenceSort(); - //-----------Others------------------------------------------------------- + // -----------Others------------------------------------------------------- public static final ProgramSVSort METHODNAME = new MethodNameSort(); public static final ProgramSVSort LABEL = new LabelSort(); - //-----------Specials for primitive types--------------------------------- + // -----------Specials for primitive types--------------------------------- public static final ProgramSVSort JAVABOOLEANEXPRESSION = - new ExpressionSpecialPrimitiveTypeSort( - "JavaBooleanExpression", - new PrimitiveType[] { PrimitiveType.JAVA_BOOLEAN } - ); + new ExpressionSpecialPrimitiveTypeSort("JavaBooleanExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BOOLEAN }); public static final ProgramSVSort SIMPLEJAVABYTEEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaByteExpression", - new PrimitiveType[] { PrimitiveType.JAVA_BYTE } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaByteExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE }); public static final ProgramSVSort SIMPLEJAVACHAREXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaCharExpression", - new PrimitiveType[] { PrimitiveType.JAVA_CHAR } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaCharExpression", + new PrimitiveType[] { PrimitiveType.JAVA_CHAR }); public static final ProgramSVSort SIMPLEJAVASHORTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaShortExpression", - new PrimitiveType[] { PrimitiveType.JAVA_SHORT } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaShortExpression", + new PrimitiveType[] { PrimitiveType.JAVA_SHORT }); public static final ProgramSVSort SIMPLEJAVAINTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaIntExpression", - new PrimitiveType[] { PrimitiveType.JAVA_INT } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaIntExpression", + new PrimitiveType[] { PrimitiveType.JAVA_INT }); public static final ProgramSVSort SIMPLEJAVALONGEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaLongExpression", - new PrimitiveType[] { PrimitiveType.JAVA_LONG } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaLongExpression", + new PrimitiveType[] { PrimitiveType.JAVA_LONG }); - public static final ProgramSVSort SIMPLEJAVAFLOATEXPRESSION - = new SimpleExpressionSpecialPrimitiveTypeSort - ("JavaFloatExpression", new - PrimitiveType[]{PrimitiveType.JAVA_FLOAT}); + public static final ProgramSVSort SIMPLEJAVAFLOATEXPRESSION = + new SimpleExpressionSpecialPrimitiveTypeSort("JavaFloatExpression", + new PrimitiveType[] { PrimitiveType.JAVA_FLOAT }); - public static final ProgramSVSort SIMPLEJAVADOUBLEEXPRESSION - = new SimpleExpressionSpecialPrimitiveTypeSort - ("JavaDoubleExpression", new - PrimitiveType[]{PrimitiveType.JAVA_DOUBLE}); + public static final ProgramSVSort SIMPLEJAVADOUBLEEXPRESSION = + new SimpleExpressionSpecialPrimitiveTypeSort("JavaDoubleExpression", + new PrimitiveType[] { PrimitiveType.JAVA_DOUBLE }); public static final ProgramSVSort SIMPLEJAVABYTESHORTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaByteShortExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaByteShortExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE, PrimitiveType.JAVA_SHORT }); public static final ProgramSVSort SIMPLEJAVABYTESHORTINTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaByteShortIntExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaByteShortIntExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE, PrimitiveType.JAVA_SHORT, + PrimitiveType.JAVA_INT }); public static final ProgramSVSort SIMPLEANYJAVATYPEEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "AnyJavaTypeExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT, - PrimitiveType.JAVA_LONG - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("AnyJavaTypeExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE, PrimitiveType.JAVA_SHORT, + PrimitiveType.JAVA_INT, PrimitiveType.JAVA_LONG }); public static final ProgramSVSort SIMPLEANYJAVANUMBERTYPEEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "AnyJavaNumberTypeExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT, - PrimitiveType.JAVA_LONG, - PrimitiveType.JAVA_CHAR - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("AnyJavaNumberTypeExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE, PrimitiveType.JAVA_SHORT, + PrimitiveType.JAVA_INT, PrimitiveType.JAVA_LONG, + PrimitiveType.JAVA_CHAR }); public static final ProgramSVSort SIMPLEJAVASHORTINTLONGEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaShortIntLongExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT, - PrimitiveType.JAVA_LONG - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaShortIntLongExpression", + new PrimitiveType[] { PrimitiveType.JAVA_SHORT, PrimitiveType.JAVA_INT, + PrimitiveType.JAVA_LONG }); public static final ProgramSVSort SIMPLEJAVAINTLONGEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaIntLongExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_INT, - PrimitiveType.JAVA_LONG - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaIntLongExpression", + new PrimitiveType[] { PrimitiveType.JAVA_INT, PrimitiveType.JAVA_LONG }); public static final ProgramSVSort SIMPLEJAVACHARBYTESHORTINTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaCharByteShortIntExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_CHAR, - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("JavaCharByteShortIntExpression", + new PrimitiveType[] { PrimitiveType.JAVA_CHAR, PrimitiveType.JAVA_BYTE, + PrimitiveType.JAVA_SHORT, PrimitiveType.JAVA_INT }); public static final ProgramSVSort SIMPLEJAVABIGINTEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "JavaBigintExpression", + new SimpleExpressionSpecialPrimitiveTypeSort("JavaBigintExpression", new PrimitiveType[] { PrimitiveType.JAVA_BIGINT }); public static final ProgramSVSort SIMPLEANYNUMBERTYPEEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "AnyNumberTypeExpression", - new PrimitiveType[] { - PrimitiveType.JAVA_BYTE, - PrimitiveType.JAVA_SHORT, - PrimitiveType.JAVA_INT, - PrimitiveType.JAVA_LONG, - PrimitiveType.JAVA_CHAR, - PrimitiveType.JAVA_BIGINT - } - ); + new SimpleExpressionSpecialPrimitiveTypeSort("AnyNumberTypeExpression", + new PrimitiveType[] { PrimitiveType.JAVA_BYTE, PrimitiveType.JAVA_SHORT, + PrimitiveType.JAVA_INT, PrimitiveType.JAVA_LONG, + PrimitiveType.JAVA_CHAR, PrimitiveType.JAVA_BIGINT }); public static final ProgramSVSort SIMPLEJAVABOOLEANEXPRESSION = - new SimpleExpressionSpecialPrimitiveTypeSort( - "SimpleJavaBooleanExpression", + new SimpleExpressionSpecialPrimitiveTypeSort("SimpleJavaBooleanExpression", new PrimitiveType[] { PrimitiveType.JAVA_BOOLEAN }); public static final ProgramSVSort SIMPLESTRINGEXPRESSION = @@ -287,15 +229,13 @@ public abstract class ProgramSVSort extends AbstractSort { new SimpleExpressionNonStringObjectSort("SimpleNonStringObjectExpression"); - //--------------- Specials excepting some primitive types-------------- - - public static final ProgramSVSort SIMPLEEXPRESSIONNONFLOATDOUBLE - = new SimpleExpressionExceptingTypeSort - ("SimpleExpressionNonFloatDouble", new - PrimitiveType[]{PrimitiveType.JAVA_FLOAT, - PrimitiveType.JAVA_DOUBLE}); + // --------------- Specials excepting some primitive types-------------- - //--------------- Specials that can be get rid of perhaps-------------- + public static final ProgramSVSort SIMPLEEXPRESSIONNONFLOATDOUBLE = + new SimpleExpressionExceptingTypeSort("SimpleExpressionNonFloatDouble", + new PrimitiveType[] { PrimitiveType.JAVA_FLOAT, PrimitiveType.JAVA_DOUBLE }); + + // --------------- Specials that can be get rid of perhaps-------------- public static final ProgramSVSort LOOPINIT = new LoopInitSort(); @@ -305,14 +245,11 @@ public abstract class ProgramSVSort extends AbstractSort { public static final ProgramSVSort FORLOOP = new ForLoopSort(); - public static final ProgramSVSort MULTIPLEVARDECL = - new MultipleVariableDeclarationSort(); + public static final ProgramSVSort MULTIPLEVARDECL = new MultipleVariableDeclarationSort(); - public static final ProgramSVSort ARRAYPOSTDECL = - new ArrayPostDeclarationSort(); + public static final ProgramSVSort ARRAYPOSTDECL = new ArrayPostDeclarationSort(); - public static final ProgramSVSort SWITCH = - new SwitchSVSort(); + public static final ProgramSVSort SWITCH = new SwitchSVSort(); public static final ProgramSVSort CONSTANT_PRIMITIVE_TYPE_VARIABLE = new ConstantProgramVariableSort(new Name("ConstantPrimitiveTypeVariable"), false); @@ -323,24 +260,23 @@ public abstract class ProgramSVSort extends AbstractSort { public static final ProgramSVSort VARIABLEINIT = new ProgramSVSort(new Name("VariableInitializer")) { - @Override - public boolean canStandFor(ProgramElement pe, - Services services) { - return true; - } - }; + @Override + public boolean canStandFor(ProgramElement pe, Services services) { + return true; + } + }; public static final ProgramSVSort NONSTRINGLITERAL = new NonStringLiteralSort(); public static final ProgramSVSort STRINGLITERAL = new StringLiteralSort(); - //--------------- Specials that match on certain names----------------- + // --------------- Specials that match on certain names----------------- public static final ProgramSVSort ARRAYLENGTH = new ArrayLengthSort(); - //---------------REFERENCE SORTS ------------------------ + // ---------------REFERENCE SORTS ------------------------ public static final ProgramSVSort EXECUTIONCONTEXT = new ExecutionContextSort(); - //-------------------------------------------------------------------------- + // -------------------------------------------------------------------------- public ProgramSVSort(Name name) { super(name, DefaultImmutableSet.nil(), false); @@ -351,30 +287,31 @@ public boolean canStandFor(Term t) { return true; } - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { return canStandFor(check, services); } - protected abstract boolean canStandFor(ProgramElement check, - Services services); + protected abstract boolean canStandFor(ProgramElement check, Services services); public ProgramSVSort createInstance(String parameter) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } - //-------------Now the inner classes representing the----------------------- - //-------------different kinds of program SVs------------------------------- + // -------------Now the inner classes representing the----------------------- + // -------------different kinds of program SVs------------------------------- /** - * This sort represents a type of program schema variables that match - * only on

    • program variables or
    • static field references with - * a prefix that consists of
      • a program variable followed by a - * sequence of attribute accesses or
      • of a type reference followed by - * a sequence of attribute accesses
    + * This sort represents a type of program schema variables that match only on + *
      + *
    • program variables or + *
    • static field references with a prefix that consists of + *
        + *
      • a program variable followed by a sequence of attribute accesses or + *
      • of a type reference followed by a sequence of attribute accesses + *
      + *
    */ private static class LeftHandSideSort extends ProgramSVSort { @@ -392,24 +329,20 @@ public boolean canStandFor(Term t) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { - if (pe instanceof ProgramVariable - || pe instanceof ThisReference + protected boolean canStandFor(ProgramElement pe, Services services) { + if (pe instanceof ProgramVariable || pe instanceof ThisReference || pe instanceof VariableSpecification) { return true; } if (pe instanceof FieldReference) { - FieldReference fr = (FieldReference)pe; + FieldReference fr = (FieldReference) pe; // we allow only static field references with a // sequence of PVs or TypeRef ReferencePrefix rp = fr.getReferencePrefix(); if ((fr.getProgramVariable()).isStatic()) { - return (rp == null - || rp instanceof ThisReference - || rp instanceof TypeReference + return (rp == null || rp instanceof ThisReference || rp instanceof TypeReference || canStandFor(rp, services)); } } @@ -418,13 +351,17 @@ protected boolean canStandFor(ProgramElement pe, } /** - * This sort represents a type of program schema variables that match - * only on
    • program variables or
    • static field references with - * a prefix that consists of
      • a program variable followed by a - * sequence of attribute accesses or
      • of a type reference followed by - * a sequence of attribute accesses
    . In opposite to its - * super class it matches only if the field reference does not - * trigger static initialisation (i.e. if it is no active reference) + * This sort represents a type of program schema variables that match only on + *
      + *
    • program variables or + *
    • static field references with a prefix that consists of + *
        + *
      • a program variable followed by a sequence of attribute accesses or + *
      • of a type reference followed by a sequence of attribute accesses + *
      + *
    + * . In opposite to its super class it matches only if the field reference does not trigger + * static initialisation (i.e. if it is no active reference) */ private static class ProgramVariableSort extends LeftHandSideSort { @@ -438,17 +375,15 @@ public boolean canStandFor(Term t) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { ProgramVariable accessedField = null; if (pe instanceof FieldReference) { - accessedField = ((FieldReference)pe).getProgramVariable(); + accessedField = ((FieldReference) pe).getProgramVariable(); } else if (pe instanceof ProgramVariable) { accessedField = (ProgramVariable) pe; } - if (accessedField != null - && accessedField.isStatic() + if (accessedField != null && accessedField.isStatic() && !(accessedField instanceof ProgramConstant)) { return false; } @@ -461,27 +396,24 @@ protected boolean canStandFor(ProgramElement pe, private static class StaticVariableSort extends LeftHandSideSort { public StaticVariableSort() { - super (new Name("StaticVariable")); + super(new Name("StaticVariable")); } @Override public boolean canStandFor(Term t) { - return t.op() instanceof ProgramVariable - && ((ProgramVariable)t.op()).isStatic(); + return t.op() instanceof ProgramVariable && ((ProgramVariable) t.op()).isStatic(); } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { ProgramVariable accessedField = null; if (pe instanceof FieldReference) { - accessedField = ((FieldReference)pe).getProgramVariable(); + accessedField = ((FieldReference) pe).getProgramVariable(); } else if (pe instanceof ProgramVariable) { accessedField = (ProgramVariable) pe; } if (accessedField != null) { - return accessedField.isStatic() - && !(accessedField instanceof ProgramConstant) + return accessedField.isStatic() && !(accessedField instanceof ProgramConstant) && super.canStandFor(pe, services); } return false; @@ -489,22 +421,19 @@ protected boolean canStandFor(ProgramElement pe, } - private static class LocalVariableSort - extends LeftHandSideSort { + private static class LocalVariableSort extends LeftHandSideSort { public LocalVariableSort() { - super (new Name("LocalVariable")); + super(new Name("LocalVariable")); } @Override public boolean canStandFor(Term t) { - return t.op() instanceof ProgramVariable && - !((ProgramVariable)t.op()).isStatic(); + return t.op() instanceof ProgramVariable && !((ProgramVariable) t.op()).isStatic(); } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return pe instanceof ProgramVariable && !((ProgramVariable) pe).isStatic(); } @@ -512,13 +441,18 @@ protected boolean canStandFor(ProgramElement pe, /** - * This sort represents a type of program schema variables that match - * only on
    • program variables or
    • static field references with - * a prefix that consists of
      • a program variable followed by a - * sequence of attribute accesses or
      • of a type reference followed by - * a sequence of attribute accesses
    • (negated) literal - * expressions or
    • instanceof expressions v instanceof T with an - * expression v that matches on a program variable SV
    + * This sort represents a type of program schema variables that match only on + *
      + *
    • program variables or + *
    • static field references with a prefix that consists of + *
        + *
      • a program variable followed by a sequence of attribute accesses or + *
      • of a type reference followed by a sequence of attribute accesses + *
      + *
    • (negated) literal expressions or + *
    • instanceof expressions v instanceof T with an expression v that matches on a program + * variable SV + *
    */ private static class SimpleExpressionSort extends ProgramSVSort { @@ -536,10 +470,9 @@ public boolean canStandFor(Term t) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { if (pe instanceof Negative) { - return ((Negative)pe).getChildAt(0) instanceof Literal; + return ((Negative) pe).getChildAt(0) instanceof Literal; } if (pe instanceof StringLiteral) { @@ -555,18 +488,11 @@ protected boolean canStandFor(ProgramElement pe, return VARIABLE.canStandFor(v, services); } - if(pe instanceof SetUnion - || pe instanceof Singleton - || pe instanceof Intersect - || pe instanceof SetMinus - || pe instanceof AllFields - || pe instanceof SeqSingleton - || pe instanceof SeqConcat - || pe instanceof SeqLength - || pe instanceof SeqGet - || pe instanceof SeqIndexOf - || pe instanceof SeqConcat - || pe instanceof SeqSub + if (pe instanceof SetUnion || pe instanceof Singleton || pe instanceof Intersect + || pe instanceof SetMinus || pe instanceof AllFields + || pe instanceof SeqSingleton || pe instanceof SeqConcat + || pe instanceof SeqLength || pe instanceof SeqGet || pe instanceof SeqIndexOf + || pe instanceof SeqConcat || pe instanceof SeqSub || pe instanceof SeqReverse) { if (pe instanceof NonTerminalProgramElement) { final NonTerminalProgramElement npe = (NonTerminalProgramElement) pe; @@ -597,8 +523,7 @@ public NonSimpleExpressionNoClassReferenceSort() { /* Will not match on MetaClassReference variables */ @Override - public boolean canStandFor(ProgramElement check, - Services services) { + public boolean canStandFor(ProgramElement check, Services services) { if (!super.canStandFor(check, services) || CLASSREFERENCE.canStandFor(check, services)) { return false; @@ -609,9 +534,8 @@ public boolean canStandFor(ProgramElement check, /** - * This sort represents a type of program schema variables that match - * only on all expressions which are not matched by simple expression - * SVs. + * This sort represents a type of program schema variables that match only on all expressions + * which are not matched by simple expression SVs. */ private static class NonSimpleExpressionSort extends ProgramSVSort { @@ -624,10 +548,8 @@ protected NonSimpleExpressionSort(Name n) { } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { - if (!(check instanceof Expression) - || check instanceof SuperReference) { + protected boolean canStandFor(ProgramElement check, Services services) { + if (!(check instanceof Expression) || check instanceof SuperReference) { return false; } return !SIMPLEEXPRESSION.canStandFor(check, services); @@ -635,8 +557,7 @@ protected boolean canStandFor(ProgramElement check, } /** - * This sort represents a type of program schema variables that match on - * all expressions only. + * This sort represents a type of program schema variables that match on all expressions only. */ private static class ExpressionSort extends ProgramSVSort { @@ -656,8 +577,8 @@ protected boolean canStandFor(ProgramElement pe, Services services) { } /** - * This sort represents a type of program schema variables that match - * only string literals, e.g. "abc" + * This sort represents a type of program schema variables that match only string literals, e.g. + * "abc" */ private static class StringLiteralSort extends ProgramSVSort { public StringLiteralSort() { @@ -675,15 +596,14 @@ public boolean canStandFor(Term t) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return (pe instanceof StringLiteral); } } /** - * This sort represents a type of program schema variables that match - * only on non-string literals + * This sort represents a type of program schema variables that match only on non-string + * literals */ private static class NonStringLiteralSort extends ProgramSVSort { @@ -702,21 +622,18 @@ public boolean canStandFor(Term t) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { - return (pe instanceof Literal - && !(pe instanceof StringLiteral)); + protected boolean canStandFor(ProgramElement pe, Services services) { + return (pe instanceof Literal && !(pe instanceof StringLiteral)); } } - //----------- Initialisation and Creation expressions ------------------- + // ----------- Initialisation and Creation expressions ------------------- /** - * This sort represents a type of program schema variables that match - * only on Class Instance Creation Expressions, new C(), where all - * arguments are simple expressions. + * This sort represents a type of program schema variables that match only on Class Instance + * Creation Expressions, new C(), where all arguments are simple expressions. */ private static class SimpleNewSVSort extends ProgramSVSort { @@ -725,12 +642,11 @@ public SimpleNewSVSort() { } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { if (!(check instanceof New)) { return false; } - for (Expression arg : ((New)check).getArguments()) { + for (Expression arg : ((New) check).getArguments()) { if (NONSIMPLEEXPRESSION.canStandFor(arg, services)) { return false; } @@ -741,23 +657,21 @@ protected boolean canStandFor(ProgramElement check, /** - * This sort represents a type of program schema variables that match - * only on Class Instance Creation Expressions, new C(), where at - * least one argument is a non-simple expression + * This sort represents a type of program schema variables that match only on Class Instance + * Creation Expressions, new C(), where at least one argument is a non-simple expression */ - private static class NonSimpleNewSVSort extends ProgramSVSort { + private static class NonSimpleNewSVSort extends ProgramSVSort { public NonSimpleNewSVSort() { super(new Name("NonSimpleInstanceCreation")); } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { if (!(check instanceof New)) { return false; } - for (Expression arg : ((New)check).getArguments()) { + for (Expression arg : ((New) check).getArguments()) { if (NONSIMPLEEXPRESSION.canStandFor(arg, services)) { return true; } @@ -767,24 +681,23 @@ protected boolean canStandFor(ProgramElement check, } /** - * This sort represents a type of program schema variables that match - * only on Array Creation Expressions, new A[] + * This sort represents a type of program schema variables that match only on Array Creation + * Expressions, new A[] */ - private static class NewArraySVSort extends ProgramSVSort{ + private static class NewArraySVSort extends ProgramSVSort { public NewArraySVSort() { super(new Name("ArrayCreation")); } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { return (check instanceof NewArray); } } /** - * This sort represents a type of program schema variables that - * match only on Array Initializers. + * This sort represents a type of program schema variables that match only on Array + * Initializers. */ private static final class ArrayInitializerSVSort extends ProgramSVSort { @@ -793,16 +706,15 @@ public ArrayInitializerSVSort() { } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { return (check instanceof ArrayInitializer); } } /** - * This sort represents a type of program schema variables that - * match only on Special Constructor References. + * This sort represents a type of program schema variables that match only on Special + * Constructor References. */ private static class SpecialConstructorReferenceSort extends ProgramSVSort { @@ -811,25 +723,22 @@ public SpecialConstructorReferenceSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return (pe instanceof SpecialConstructorReference); } @Override public boolean canStandFor(Term t) { - return (t.op() instanceof IProgramMethod - && !((IProgramMethod) t.op()).isModel()); + return (t.op() instanceof IProgramMethod && !((IProgramMethod) t.op()).isModel()); } } - //----------- Types of Statement Program SVs ----------------------------- + // ----------- Types of Statement Program SVs ----------------------------- /** - * This sort represents a type of program schema variables that - * match only on statements + * This sort represents a type of program schema variables that match only on statements */ private static class StatementSort extends ProgramSVSort { public StatementSort() { @@ -843,8 +752,8 @@ protected boolean canStandFor(ProgramElement pe, Services services) { } /** - * This sort represents a type of program schema variables that - * match only on catch branches of try-catch-finally blocks + * This sort represents a type of program schema variables that match only on catch branches of + * try-catch-finally blocks */ private static final class CatchSort extends ProgramSVSort { @@ -859,8 +768,8 @@ protected boolean canStandFor(ProgramElement pe, Services services) { } /** - * This sort represents a type of program schema variables that - * match only on ccatch branches of exec blocks + * This sort represents a type of program schema variables that match only on ccatch branches of + * exec blocks */ private static final class CcatchSort extends ProgramSVSort { @@ -875,8 +784,8 @@ protected boolean canStandFor(ProgramElement pe, Services services) { } /** - * This sort represents a type of program schema variables that - * match only on method body statements + * This sort represents a type of program schema variables that match only on method body + * statements */ private static final class MethodBodySort extends ProgramSVSort { public MethodBodySort() { @@ -890,9 +799,8 @@ protected boolean canStandFor(ProgramElement check, Services services) { } /** - * This sort represents a type of program schema variables that - * match only on method body statements for nonmodel methods for which - * an implementation is present. + * This sort represents a type of program schema variables that match only on method body + * statements for nonmodel methods for which an implementation is present. */ private static final class NonModelMethodBodySort extends ProgramSVSort { @@ -906,24 +814,22 @@ protected boolean canStandFor(ProgramElement pe, Services services) { return false; } - final IProgramMethod pm = - ((MethodBodyStatement) pe).getProgramMethod(services); + final IProgramMethod pm = ((MethodBodyStatement) pe).getProgramMethod(services); if (pm == null) { return false; } final MethodDeclaration methodDeclaration = pm.getMethodDeclaration(); - return !(//pm.isModel() || - methodDeclaration.getBody() == null) + return !(// pm.isModel() || + methodDeclaration.getBody() == null) || (methodDeclaration instanceof ConstructorDeclaration); } } /** - * This sort represents a type of program schema variables that - * match on a method call with SIMPLE PREFIX and AT LEAST a - * NONSIMPLE expression in the ARGUMENTS. + * This sort represents a type of program schema variables that match on a method call with + * SIMPLE PREFIX and AT LEAST a NONSIMPLE expression in the ARGUMENTS. */ private static final class NonSimpleMethodReferenceSort extends ProgramSVSort { @@ -932,16 +838,13 @@ public NonSimpleMethodReferenceSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { if (pe instanceof MethodReference) { - MethodReference mr = (MethodReference)pe; + MethodReference mr = (MethodReference) pe; // FIX to bug #1223 (according to CS) /* - if (mr.getReferencePrefix() instanceof SuperReference || - mr.getReferencePrefix() instanceof TypeReference) { - return false; - } + * if (mr.getReferencePrefix() instanceof SuperReference || mr.getReferencePrefix() + * instanceof TypeReference) { return false; } */ if (mr.getReferencePrefix() != null && NONSIMPLEEXPRESSION.canStandFor(mr.getReferencePrefix(), services)) { @@ -951,8 +854,7 @@ protected boolean canStandFor(ProgramElement pe, return false; } for (int i = 0; i < mr.getArguments().size(); i++) { - if (NONSIMPLEEXPRESSION.canStandFor(mr.getArgumentAt(i), - services)) { + if (NONSIMPLEEXPRESSION.canStandFor(mr.getArgumentAt(i), services)) { return true; } } @@ -967,26 +869,24 @@ public boolean canStandFor(Term t) { } /** - * This sort represents a type of program schema variables that - * match only on program methods + * This sort represents a type of program schema variables that match only on program methods */ private static final class ProgramMethodSort extends ProgramSVSort { - public ProgramMethodSort() { - super(new Name("ProgramMethod")); - } + public ProgramMethodSort() { + super(new Name("ProgramMethod")); + } - @Override -protected boolean canStandFor(ProgramElement check, Services services) { - return (check instanceof IProgramMethod); - } + @Override + protected boolean canStandFor(ProgramElement check, Services services) { + return (check instanceof IProgramMethod); + } } - //-----------Types-------------------------------------------------------- + // -----------Types-------------------------------------------------------- /** - * This sort represents a type of program schema variables that - * match only on type references. + * This sort represents a type of program schema variables that match only on type references. */ private static final class TypeReferenceSort extends ProgramSVSort { public TypeReferenceSort() { @@ -1001,8 +901,8 @@ protected boolean canStandFor(ProgramElement check, Services services) { /** - * This sort represents a type of program schema variables that - * match anything except byte, char, short, int, and long. + * This sort represents a type of program schema variables that match anything except byte, + * char, short, int, and long. */ private static final class TypeReferenceNotPrimitiveSort extends ProgramSVSort { private final String matchName; @@ -1022,14 +922,12 @@ protected boolean canStandFor(ProgramElement check, Services services) { if (!(check instanceof TypeReference)) { return false; } - if(((TypeReference)(check)).getKeYJavaType().getJavaType() - instanceof PrimitiveType) { + if (((TypeReference) (check)).getKeYJavaType().getJavaType() instanceof PrimitiveType) { return false; } - if(matchName != null) { + if (matchName != null) { return matchName.equals( - ((TypeReference)(check)).getKeYJavaType().getJavaType().getFullName() - ); + ((TypeReference) (check)).getKeYJavaType().getJavaType().getFullName()); } return true; } @@ -1041,8 +939,8 @@ public ProgramSVSort createInstance(String parameter) { } /** - * This sort represents a type of program schema variables that - * match only on meta class references. + * This sort represents a type of program schema variables that match only on meta class + * references. */ private static final class MetaClassReferenceSort extends ProgramSVSort { @@ -1057,14 +955,13 @@ protected boolean canStandFor(ProgramElement check, Services services) { } - //-----------Names-------------------------------------------------------- + // -----------Names-------------------------------------------------------- /** - * This sort represents a type of program schema variables that match - * on names of method references, i.e. the "m" of o.m(p1,pn). + * This sort represents a type of program schema variables that match on names of method + * references, i.e. the "m" of o.m(p1,pn). * - * It can also be made to match only specific method names - * defined by the parameter "name". + * It can also be made to match only specific method names defined by the parameter "name". */ private static class MethodNameSort extends ProgramSVSort { private final ProgramElementName methodName; @@ -1080,8 +977,7 @@ public MethodNameSort(ProgramElementName name) { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { if (pe instanceof MethodName) { return methodName == null || pe.equals(methodName); } @@ -1101,8 +997,7 @@ public String declarationString() { } /** - * This sort represents a type of program schema variables that match - * on labels. + * This sort represents a type of program schema variables that match on labels. */ private static final class LabelSort extends ProgramSVSort { public LabelSort() { @@ -1110,16 +1005,15 @@ public LabelSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return (pe instanceof Label); } } /** - * This sort represents a type of program schema variables that match - * on string literals and string variables. + * This sort represents a type of program schema variables that match on string literals and + * string variables. */ public static final class SimpleExpressionStringSort extends SimpleExpressionSort { public SimpleExpressionStringSort(String name) { @@ -1128,18 +1022,16 @@ public SimpleExpressionStringSort(String name) { /* Will only match on String variables */ @Override - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { if (!super.canStandFor(check, ec, services)) { return false; } - //String Literal has SideEffects, but SimpleExpressionSort will not match - //if (check instanceof StringLiteral) return false; + // String Literal has SideEffects, but SimpleExpressionSort will not match + // if (check instanceof StringLiteral) return false; if (check instanceof ProgramVariable) { Namespace ns = services.getNamespaces().sorts(); Sort stringSort = ns.lookup(new Name("java.lang.String")); - return ((ProgramVariable)check).getKeYJavaType().getSort().equals(stringSort); + return ((ProgramVariable) check).getKeYJavaType().getSort().equals(stringSort); } return false; } @@ -1147,8 +1039,8 @@ public boolean canStandFor(ProgramElement check, /** - * This sort represents a type of program schema variables that match - * on non string object variables. + * This sort represents a type of program schema variables that match on non string object + * variables. */ public static class SimpleExpressionNonStringObjectSort extends SimpleExpressionSort { public SimpleExpressionNonStringObjectSort(String name) { @@ -1156,14 +1048,12 @@ public SimpleExpressionNonStringObjectSort(String name) { } @Override - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { if (!super.canStandFor(check, ec, services)) { return false; } if (check instanceof ProgramVariable) { - final Sort checkSort = ((ProgramVariable)check).sort(); + final Sort checkSort = ((ProgramVariable) check).sort(); Namespace ns = services.getNamespaces().sorts(); Sort stringSort = ns.lookup(new Name("java.lang.String")); return checkSort.extendsTrans(services.getJavaInfo().objectSort()) @@ -1173,28 +1063,25 @@ public boolean canStandFor(ProgramElement check, } } - //-----------Specials for primitive types--------------------------------- + // -----------Specials for primitive types--------------------------------- /** - * This sort represents a type of program schema variables that match - * on simple expressions which have a special primitive type. + * This sort represents a type of program schema variables that match on simple expressions + * which have a special primitive type. */ private static final class SimpleExpressionSpecialPrimitiveTypeSort extends SimpleExpressionSort { private final PrimitiveType[] allowedPrimitiveTypes; - public SimpleExpressionSpecialPrimitiveTypeSort(String name, - PrimitiveType[] allowedTypes) { + public SimpleExpressionSpecialPrimitiveTypeSort(String name, PrimitiveType[] allowedTypes) { super(new Name(name)); this.allowedPrimitiveTypes = allowedTypes; } @Override - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { if (!super.canStandFor(check, ec, services)) { return false; } @@ -1212,28 +1099,24 @@ public boolean canStandFor(ProgramElement check, } /** - * This sort represents a type of program schema variables that match - * on simple expressions, except if they match a special primitive type. + * This sort represents a type of program schema variables that match on simple expressions, + * except if they match a special primitive type. */ - private static final class SimpleExpressionExceptingTypeSort - extends SimpleExpressionSort{ - - private final PrimitiveType[] forbidden_types; - - public SimpleExpressionExceptingTypeSort - (String name, PrimitiveType[] forbidden_types) { - - super(new Name(name)); - this.forbidden_types = forbidden_types; - } - - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { - if (!super.canStandFor(check, ec, services)) { - return false; - } - final KeYJavaType kjt = getKeYJavaType(check, ec, services); + private static final class SimpleExpressionExceptingTypeSort extends SimpleExpressionSort { + + private final PrimitiveType[] forbidden_types; + + public SimpleExpressionExceptingTypeSort(String name, PrimitiveType[] forbidden_types) { + + super(new Name(name)); + this.forbidden_types = forbidden_types; + } + + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { + if (!super.canStandFor(check, ec, services)) { + return false; + } + final KeYJavaType kjt = getKeYJavaType(check, ec, services); if (kjt != null) { final Type type = kjt.getJavaType(); for (PrimitiveType forbidden_type : forbidden_types) { @@ -1246,8 +1129,8 @@ public boolean canStandFor(ProgramElement check, } /** - * This sort represents a type of program schema variables that match - * on simple expressions which have a special primitive type. + * This sort represents a type of program schema variables that match on simple expressions + * which have a special primitive type. */ private static final class ExpressionSpecialPrimitiveTypeSort extends ExpressionSort { @@ -1259,9 +1142,7 @@ public ExpressionSpecialPrimitiveTypeSort(String name, PrimitiveType[] allowedTy } @Override - public boolean canStandFor(ProgramElement check, - ExecutionContext ec, - Services services) { + public boolean canStandFor(ProgramElement check, ExecutionContext ec, Services services) { if (!super.canStandFor(check, ec, services)) { return false; } @@ -1280,7 +1161,7 @@ public boolean canStandFor(ProgramElement check, } } - //-----------Specials (unnecessary?)-------------------------------------- + // -----------Specials (unnecessary?)-------------------------------------- private static final class LoopInitSort extends ProgramSVSort { @@ -1310,6 +1191,7 @@ private static final class ForUpdatesSort extends ProgramSVSort { public ForUpdatesSort() { super(new Name("ForUpdates")); } + @Override protected boolean canStandFor(ProgramElement check, Services services) { return (check instanceof ForUpdates); @@ -1336,8 +1218,7 @@ public SwitchSVSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return (pe instanceof Switch); } } @@ -1349,8 +1230,7 @@ public MultipleVariableDeclarationSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return pe instanceof VariableDeclaration && ((VariableDeclaration) pe).getVariables().size() > 1; } @@ -1363,19 +1243,17 @@ public ArrayPostDeclarationSort() { } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return pe instanceof VariableDeclaration && ((VariableDeclaration) pe).getVariables().size() == 1 - && ((VariableDeclaration) pe).getVariables(). - get(0).getDimensions() > 0; + && ((VariableDeclaration) pe).getVariables().get(0).getDimensions() > 0; } } - //------------------ stuff concerned with explicit and implicit elements---- + // ------------------ stuff concerned with explicit and implicit elements---- private static final class ConstantProgramVariableSort extends ProgramSVSort { @@ -1390,13 +1268,11 @@ public ConstantProgramVariableSort(Name svSortName, boolean string) { @Override public boolean canStandFor(Term t) { - return t.op () instanceof ProgramConstant - && isString == t.sort().name().equals(type); + return t.op() instanceof ProgramConstant && isString == t.sort().name().equals(type); } @Override - protected boolean canStandFor(ProgramElement pe, - Services services) { + protected boolean canStandFor(ProgramElement pe, Services services) { return false; } } @@ -1408,8 +1284,7 @@ public ArrayLengthSort() { } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { if (check instanceof ProgramVariable) { return check == services.getJavaInfo().getArrayLength(); } @@ -1424,27 +1299,23 @@ public ExecutionContextSort() { } @Override - protected boolean canStandFor(ProgramElement check, - Services services) { + protected boolean canStandFor(ProgramElement check, Services services) { return (check instanceof ExecutionContext); } } - //-------------------helper methods ------------------------------------ + // -------------------helper methods ------------------------------------ static boolean methodConstrReference(ProgramElement pe) { - return (pe instanceof MethodReference) - || (pe instanceof ConstructorReference); + return (pe instanceof MethodReference) || (pe instanceof ConstructorReference); } public ProgramElement getSVWithSort(ExtList l, Class alternative) { for (final Object o : l) { - if (o instanceof SchemaVariable - && (((SchemaVariable)o).sort() == this)) { + if (o instanceof SchemaVariable && (((SchemaVariable) o).sort() == this)) { return (ProgramElement) o; - } else if ((alternative.isInstance(o)) - && (!(o instanceof SchemaVariable))) { + } else if ((alternative.isInstance(o)) && (!(o instanceof SchemaVariable))) { return (ProgramElement) o; } } @@ -1452,23 +1323,23 @@ public ProgramElement getSVWithSort(ExtList l, Class alternative) { } static KeYJavaType getKeYJavaType(ProgramElement pe, ExecutionContext ec, Services services) { - return services.getTypeConverter().getKeYJavaType((Expression)pe, ec); + return services.getTypeConverter().getKeYJavaType((Expression) pe, ec); } static boolean implicit(ProgramElement pe) { if (pe instanceof ProgramVariable) { - if (!((ProgramVariable)pe).isMember()) { + if (!((ProgramVariable) pe).isMember()) { return false; } } final String elemname; if (pe instanceof NamedProgramElement) { - elemname = ((NamedProgramElement)pe).getProgramElementName().getProgramName(); + elemname = ((NamedProgramElement) pe).getProgramElementName().getProgramName(); } else if (pe instanceof Named) { - final Name n = ((Named)pe).name(); + final Name n = ((Named) pe).name(); if (n instanceof ProgramElementName) { - elemname = ((ProgramElementName)n).getProgramName(); + elemname = ((ProgramElementName) n).getProgramName(); } else { elemname = n.toString(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProxySort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProxySort.java index 0dc6e99799b..e0f8c1a39b3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProxySort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/ProxySort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import org.key_project.util.collection.DefaultImmutableSet; @@ -14,4 +17,4 @@ public ProxySort(Name name, ImmutableSet ext) { public ProxySort(Name name) { this(name, DefaultImmutableSet.nil()); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/Sort.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/Sort.java index cc4510a4d09..38fecf6d2f8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/Sort.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/Sort.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import de.uka.ilkd.key.rule.HasOrigin; @@ -63,8 +66,7 @@ public interface Sort extends Named, HasOrigin { /** * @param s some sort. - * @return whether the given sort is a reflexive, transitive subsort of this - * sort. + * @return whether the given sort is a reflexive, transitive subsort of this sort. */ boolean extendsTrans(Sort s); @@ -94,9 +96,11 @@ public interface Sort extends Named, HasOrigin { String declarationString(); /** - * Returns an human explainable text describing this sort. - * This field is typical set by the parser, who captures the documentation comments. + * Returns an human explainable text describing this sort. This field is typical set by the + * parser, who captures the documentation comments. */ @Nullable - default String getDocumentation() {return null;} + default String getDocumentation() { + return null; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/SortImpl.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/SortImpl.java index d1bd0fedbc1..d3724135923 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/SortImpl.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/sort/SortImpl.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.sort; import org.key_project.util.collection.DefaultImmutableSet; @@ -9,28 +12,29 @@ * Standard implementation of the Sort interface. */ public final class SortImpl extends AbstractSort { - + public SortImpl(Name name, ImmutableSet ext, boolean isAbstract) { super(name, ext, isAbstract); - } - + } + public SortImpl(Name name, ImmutableSet ext) { this(name, ext, false); } - + public SortImpl(Name name, Sort ext) { this(name, DefaultImmutableSet.nil().add(ext), false); - } - + } + public SortImpl(Name name) { - this(name, DefaultImmutableSet.nil()); + this(name, DefaultImmutableSet.nil()); } - - public boolean equals(Object o){ - if (o instanceof SortImpl){ - return ((SortImpl)o).name().equals(name()); - } else return false; + + public boolean equals(Object o) { + if (o instanceof SortImpl) { + return ((SortImpl) o).name().equals(name()); + } else + return false; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/logic/util/TermHelper.java b/key/key.core/src/main/java/de/uka/ilkd/key/logic/util/TermHelper.java index b91acb07e12..2b66d7ce329 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/logic/util/TermHelper.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/logic/util/TermHelper.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.logic.util; import de.uka.ilkd.key.logic.Term; @@ -9,35 +12,33 @@ /** - * Provides some helper methods used by classes outside the logic package - * Please be careful with putting things here. This class has been mainly created - * to give getMaxSort a home which is scheduled to become obsolete soon - * (see method comment) + * Provides some helper methods used by classes outside the logic package Please be careful with + * putting things here. This class has been mainly created to give getMaxSort a home which is + * scheduled to become obsolete soon (see method comment) */ public class TermHelper { - + private TermHelper() {} /** - * helper function to determine the maximal sort the term - * tSub may have as i sub term - * This method will become obsolete in the near future as all operators - * will become a fixed signature. But currently there ar eto many chnages - * pending (new sort hierarchy for integers, new pos) that much of the work would be - * for made new. That is the reason for this HACK - * @param term the Term of which a part of the i-th sub term - * may be replaced + * helper function to determine the maximal sort the term tSub may have as i sub term + * This method will become obsolete in the near future as all operators will become a fixed + * signature. But currently there ar eto many chnages pending (new sort hierarchy for integers, + * new pos) that much of the work would be for made new. That is the reason for this HACK + * + * @param term the Term of which a part of the i-th sub term may be replaced * @param i an int giving the position of sub term of which a part is to be replaced * @param services the Services object * @return the maximal sort allowed at the i-th position */ - public static Sort getMaxSort(Term term, int i, TermServices services) { - if (term.sub(i).sort() == Sort.FORMULA) return Sort.FORMULA; - + public static Sort getMaxSort(Term term, int i, TermServices services) { + if (term.sub(i).sort() == Sort.FORMULA) + return Sort.FORMULA; + if (term.op() instanceof IfThenElse && i > 0) { return term.sort(); } - return getMaxSortHelper(term.op(), i, term.sub(i).sort(), services); + return getMaxSortHelper(term.op(), i, term.sub(i).sort(), services); } /** @@ -47,16 +48,14 @@ public static Sort getMaxSort(Term term, int i, TermServices services) { * @param services the Services object * @return the maximal sort allowed at argument i */ - private static Sort getMaxSortHelper(final Operator op, - int i, - Sort maxSortDefault, - TermServices services) { + private static Sort getMaxSortHelper(final Operator op, int i, Sort maxSortDefault, + TermServices services) { final Sort newMaxSort; if (op instanceof SortedOperator) { - newMaxSort = ((SortedOperator)op).argSort(i); - } else { + newMaxSort = ((SortedOperator) op).argSort(i); + } else { newMaxSort = maxSortDefault; } return newMaxSort; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractBlastingMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractBlastingMacro.java index ad16d24cbb0..01722fa2bf5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractBlastingMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractBlastingMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.LinkedList; @@ -129,8 +132,8 @@ private List createFormulae(Services services, Set sorts) return result; } - private static void addFormulas(List result, KeYJavaType kjt, - ClassAxiom c, LogicVariable o, LogicVariable h, Services services) { + private static void addFormulas(List result, KeYJavaType kjt, ClassAxiom c, + LogicVariable o, LogicVariable h, Services services) { TermBuilder tb = new TermBuilder(services.getTermFactory(), services); Term exactInstance = tb.exactInstance(kjt.getSort(), tb.var(o)); RepresentsAxiom ra = (RepresentsAxiom) c; @@ -189,7 +192,8 @@ private static void addFormulas(List result, KeYJavaType kjt, f = tb.all(h, tb.all(o, f)); result.add(new SequentFormula(f)); } - } catch (Exception e) { } + } catch (Exception e) { + } } private class SemanticsBlastingStrategy implements Strategy { @@ -246,8 +250,7 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { @Override public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, - RuleAppCostCollector collector) { - } + RuleAppCostCollector collector) {} @Override public boolean isStopAtFirstNonCloseableGoal() { @@ -256,4 +259,4 @@ public boolean isStopAtFirstNonCloseableGoal() { } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractProofMacro.java index 8294fc190c1..78ce37e3043 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -12,14 +15,12 @@ import de.uka.ilkd.key.settings.ProofSettings; /** - * Takes care of providing the whole ProofMacro interface by only making it - * necessary to implement to most general application methods for a given - * list of goals and translating the less general versions (firstly for a - * given node and secondly having neither any goals nor a node). Although - * all these methods can be redefined by inheritance, this is usually not - * necessary, unless you know exactly what you are doing. - * The exception is {@link #finishAfterMacro()} for compound macros - * (see description in {@link ProofMacro#finishAfterMacro()}). + * Takes care of providing the whole ProofMacro interface by only making it necessary to implement + * to most general application methods for a given list of goals and translating the less general + * versions (firstly for a given node and secondly having neither any goals nor a node). Although + * all these methods can be redefined by inheritance, this is usually not necessary, unless you know + * exactly what you are doing. The exception is {@link #finishAfterMacro()} for compound + * macros (see description in {@link ProofMacro#finishAfterMacro()}). * * @author Michael Kirsten */ @@ -37,8 +38,7 @@ private static ImmutableList getGoals(Node node) { /** * {@inheritDoc} * - * By default, proof macros do not support scripts, thus null - * is returned. + * By default, proof macros do not support scripts, thus null is returned. */ @Override public String getScriptCommandName() { @@ -51,46 +51,40 @@ public boolean hasParameter(String paramName) { } @Override - public void setParameter(String paramName, String paramValue) - throws IllegalArgumentException { + public void setParameter(String paramName, String paramValue) throws IllegalArgumentException { throw new IllegalArgumentException( - String.format("There is no parameter of name %s in macro %s", - paramName, this.getClass().getSimpleName())); + String.format("There is no parameter of name %s in macro %s", paramName, + this.getClass().getSimpleName())); } @Override - public void resetParams() { - } + public void resetParams() {} @Override - public boolean canApplyTo(Node node, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Node node, PosInOccurrence posInOcc) { return canApplyTo(node.proof(), getGoals(node), posInOcc); } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Node node, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Node node, + PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception { return applyTo(uic, node.proof(), getGoals(node), posInOcc, listener); } /** - * Gets the maximum number of rule applications allowed for a macro. The - * implementation is the maximum amount of proof steps for automatic mode. + * Gets the maximum number of rule applications allowed for a macro. The implementation is the + * maximum amount of proof steps for automatic mode. * * @return the maximum number of rule applications allowed for this macro */ final protected int getMaxSteps(Proof proof) { final int steps; if (proof != null) { - steps = proof.getSettings() - .getStrategySettings().getMaxSteps(); + steps = proof.getSettings().getStrategySettings().getMaxSteps(); } else { - steps = ProofSettings.DEFAULT_SETTINGS - .getStrategySettings().getMaxSteps(); + steps = ProofSettings.DEFAULT_SETTINGS.getStrategySettings().getMaxSteps(); } return steps; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractPropositionalExpansionMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractPropositionalExpansionMacro.java index a3dea175d46..4e2b1d03686 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractPropositionalExpansionMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AbstractPropositionalExpansionMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Arrays; @@ -18,14 +21,12 @@ import de.uka.ilkd.key.strategy.TopRuleAppCost; /** - * The Class AbstractPropositionalExpansionMacro applies purely propositional - * rules. + * The Class AbstractPropositionalExpansionMacro applies purely propositional rules. * * The names of the set of rules to be applied is defined by the abstract method * {@link #getAdmittedRuleNames()}. * - * This is very helpful to perform many "andLeft", "impRight" or even "andRight" - * steps at a time. + * This is very helpful to perform many "andLeft", "impRight" or even "andRight" steps at a time. * * @author mattias ulbrich */ @@ -34,7 +35,7 @@ public abstract class AbstractPropositionalExpansionMacro extends StrategyProofM /* * convert a string array to a set of strings */ - protected static Set asSet(String... strings) { + protected static Set asSet(String... strings) { return Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(strings))); } @@ -49,7 +50,7 @@ public String getCategory() { * @return a constant non-null set */ protected abstract Set getAdmittedRuleNames(); - + /** * Whether this macro includes One Step Simplification. */ @@ -57,26 +58,26 @@ public String getCategory() { @Override protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { - return new PropExpansionStrategy(proof.getActiveStrategy(), - getAdmittedRuleNames(), allowOSS()); + return new PropExpansionStrategy(proof.getActiveStrategy(), getAdmittedRuleNames(), + allowOSS()); } - + /** - * Checks whether the application of the passed rule is ok in the given - * context. - * - * @param ruleApp rule to be applied - * @param pio context - * @param goal context - * @return true if rule may be applied + * Checks whether the application of the passed rule is ok in the given context. + * + * @param ruleApp rule to be applied + * @param pio context + * @param goal context + * @return true if rule may be applied */ - protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { + protected boolean ruleApplicationInContextAllowed(RuleApp ruleApp, PosInOccurrence pio, + Goal goal) { return true; } /** - * This strategy accepts all rule apps for which the rule name is in the - * admitted set and rejects everything else. + * This strategy accepts all rule apps for which the rule name is in the admitted set and + * rejects everything else. */ private class PropExpansionStrategy implements Strategy { @@ -86,7 +87,8 @@ private class PropExpansionStrategy implements Strategy { private final Strategy delegate; private final boolean allowOSS; - public PropExpansionStrategy(Strategy delegate, Set admittedRuleNames, boolean allowOSS) { + public PropExpansionStrategy(Strategy delegate, Set admittedRuleNames, + boolean allowOSS) { this.delegate = delegate; this.admittedRuleNames = admittedRuleNames; this.allowOSS = allowOSS; @@ -102,10 +104,11 @@ public RuleAppCost computeCost(RuleApp ruleApp, PosInOccurrence pio, Goal goal) String name = ruleApp.rule().name().toString(); if (ruleApp instanceof OneStepSimplifierRuleApp && allowOSS) { return delegate.computeCost(ruleApp, pio, goal); - } else if(admittedRuleNames.contains(name)) { + } else if (admittedRuleNames.contains(name)) { final RuleAppCost origCost = delegate.computeCost(ruleApp, pio, goal); // pass through negative costs - if (origCost instanceof NumberRuleAppCost && ((NumberRuleAppCost) origCost).getValue() < 0) + if (origCost instanceof NumberRuleAppCost + && ((NumberRuleAppCost) origCost).getValue() < 0) return origCost; // cap costs at zero return NumberRuleAppCost.getZeroCost(); @@ -121,12 +124,11 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { @Override public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, - RuleAppCostCollector collector) { - } + RuleAppCostCollector collector) {} @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AlternativeMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AlternativeMacro.java index 14583ab0ad9..bf5d8375e8a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AlternativeMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AlternativeMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Arrays; @@ -15,9 +18,8 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * The abstract class AlternativeMacro can be used to create compound macros - * which apply the first applicable macro (similar to a shortcut disjunction) - * and then it returns. + * The abstract class AlternativeMacro can be used to create compound macros which apply the first + * applicable macro (similar to a shortcut disjunction) and then it returns. * * @author Michael Kirsten */ @@ -33,8 +35,8 @@ public abstract class AlternativeMacro extends AbstractProofMacro { /** * Creates the proof macro array. * - * Override this method by returning an array with the macro alternatives of - * which you want to call the first applicable one in the order of their priority. + * Override this method by returning an array with the macro alternatives of which you want to + * call the first applicable one in the order of their priority. * * @return a non-null array which should not be altered afterwards. */ @@ -44,13 +46,11 @@ public abstract class AlternativeMacro extends AbstractProofMacro { * {@inheritDoc} * *

    - * This compound macro is applicable if and only if any one of the macros is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if any one of the macros is applicable. If + * there is no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { final List macros = getProofMacros(); for (int i = 0; i < macros.size(); i++) { if (macros.get(i).canApplyTo(proof, goals, posInOcc)) { @@ -66,22 +66,18 @@ public boolean canApplyTo(Proof proof, *

    * This launches the first applicable macro of {@link #getProofMacros()}. * - * @throws InterruptedException - * if the macro is interrupted. + * @throws InterruptedException if the macro is interrupted. */ @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception { ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals); for (final ProofMacro macro : getProofMacros()) { - if(macro.canApplyTo(proof, goals, posInOcc)) { - final ProverTaskListener pml = - new ProofMacroListener(macro.getName(), listener); + if (macro.canApplyTo(proof, goals, posInOcc)) { + final ProverTaskListener pml = new ProofMacroListener(macro.getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - synchronized(macro) { + synchronized (macro) { // wait for macro to terminate info = macro.applyTo(uic, proof, goals, posInOcc, pml); } @@ -100,11 +96,11 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, * @return the proofMacros as an unmodifiable list. */ public List getProofMacros() { - if(proofMacros == null) { + if (proofMacros == null) { this.proofMacros = createProofMacroArray(); assert proofMacros != null; assert proofMacros.length > 0; } return Collections.unmodifiableList(Arrays.asList(proofMacros)); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoMacro.java index a323a1dbdb7..31c5f3d47b4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.ArrayList; @@ -20,29 +23,27 @@ import de.uka.ilkd.key.strategy.Strategy; /** - * The macro {@link AutoMacro} is a customizable {@link ProofMacro} for use in - * proof scripts. It is possible to + * The macro {@link AutoMacro} is a customizable {@link ProofMacro} for use in proof scripts. It is + * possible to * *

      - *
    • set a breakpoint statement which makes the macro stop when the breakpoint - * is reached (option "breakpoint", default is no breakpoint),
    • - *
    • prevent the proof from splitting (option "splits", default is true, i.e., - * splitting allowed),
    • - *
    • whitelist certain rule names which will always be allowed, even after a - * breakpoint (option "whitelist", default is none, supply a comma-separated - * list of rule names),
    • - *
    • limit the rule applications to those working on formulas with a modality - * (parameter "symbex-only", default is true),
    • - *
    • prevent the application of rules that are tagged as not "human-readable" - * (parameter "human-readable-only", default is true).
    • + *
    • set a breakpoint statement which makes the macro stop when the breakpoint is reached (option + * "breakpoint", default is no breakpoint),
    • + *
    • prevent the proof from splitting (option "splits", default is true, i.e., splitting + * allowed),
    • + *
    • whitelist certain rule names which will always be allowed, even after a breakpoint (option + * "whitelist", default is none, supply a comma-separated list of rule names),
    • + *
    • limit the rule applications to those working on formulas with a modality (parameter + * "symbex-only", default is true),
    • + *
    • prevent the application of rules that are tagged as not "human-readable" (parameter + * "human-readable-only", default is true).
    • *
    * * All parameters are optional, the default configuration works like the - * {@link FinishSymbolicExecutionMacro}. The parameters mentioned above have to - * be prefixed with "arg_" in proof scripts. From proof scripts, it is also - * possible (for all macros, and so also for this one) to start the macro on one - * particular formula (via parameter "occ") and thus to realize focussed - * applications. + * {@link FinishSymbolicExecutionMacro}. The parameters mentioned above have to be prefixed with + * "arg_" in proof scripts. From proof scripts, it is also possible (for all macros, and so also for + * this one) to start the macro on one particular formula (via parameter "occ") and thus to realize + * focussed applications. * * @author Dominic Steinhoefel */ diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoPilotPrepareProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoPilotPrepareProofMacro.java index fb371060828..f448a89cde1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoPilotPrepareProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/AutoPilotPrepareProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Arrays; @@ -30,16 +33,16 @@ public class AutoPilotPrepareProofMacro extends StrategyProofMacro { - private static final String[] ADMITTED_RULES = { - "orRight", "impRight", "close", "andRight" - }; + private static final String[] ADMITTED_RULES = { "orRight", "impRight", "close", "andRight" }; private static final Set ADMITTED_RULES_SET = asSet(ADMITTED_RULES); private static final Name NON_HUMAN_INTERACTION_RULESET = new Name("notHumanReadable"); - public AutoPilotPrepareProofMacro() { super(); } - + public AutoPilotPrepareProofMacro() { + super(); + } + @Override public String getName() { return "Auto Pilot (Preparation Only)"; @@ -52,9 +55,8 @@ public String getCategory() { @Override public String getDescription() { - return "
    1. Finish symbolic execution" + - "
    2. Separate proof obligations" + - "
    3. Expand invariant definitions
    "; + return "
    1. Finish symbolic execution" + "
    2. Separate proof obligations" + + "
    3. Expand invariant definitions
    "; } @Override @@ -75,7 +77,7 @@ protected static Set asSet(String[] strings) { private static boolean hasModality(Node node) { Sequent sequent = node.sequent(); for (SequentFormula sequentFormula : sequent) { - if(hasModality(sequentFormula.formula())) { + if (hasModality(sequentFormula.formula())) { return true; } } @@ -87,12 +89,12 @@ private static boolean hasModality(Node node) { * recursively descent into the term to detect a modality. */ private static boolean hasModality(Term term) { - if(term.op() instanceof Modality) { + if (term.op() instanceof Modality) { return true; } for (Term sub : term.subs()) { - if(hasModality(sub)) { + if (hasModality(sub)) { return true; } } @@ -111,13 +113,13 @@ private static boolean isInRuleSet(Rule rule, Name ruleSetName) { if (rule instanceof Taclet) { Taclet taclet = (Taclet) rule; for (RuleSet rs : taclet.getRuleSets()) { - if (ruleSetName.equals(rs.name())) + if (ruleSetName.equals(rs.name())) return true; } } return false; } - + private static class AutoPilotStrategy implements Strategy { private static final Name NAME = new Name("Autopilot filter strategy"); @@ -135,42 +137,42 @@ public Name name() { @Override public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { return computeCost(app, pio, goal) != TopRuleAppCost.INSTANCE && - // Assumptions are normally not considered by the cost - // computation, because they are normally not yet - // instantiated when the costs are computed. Because the - // application of a rule sometimes makes sense only if - // the assumptions are instantiated in a particular way - // (for instance equalities should not be applied on - // themselves), we need to give the delegate the possiblity - // to reject the application of a rule by calling - // isApprovedApp. Otherwise, in particular equalities may - // be applied on themselves. - delegate.isApprovedApp(app, pio, goal); + // Assumptions are normally not considered by the cost + // computation, because they are normally not yet + // instantiated when the costs are computed. Because the + // application of a rule sometimes makes sense only if + // the assumptions are instantiated in a particular way + // (for instance equalities should not be applied on + // themselves), we need to give the delegate the possiblity + // to reject the application of a rule by calling + // isApprovedApp. Otherwise, in particular equalities may + // be applied on themselves. + delegate.isApprovedApp(app, pio, goal); } @Override public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, Goal goal) { Rule rule = app.rule(); - if(isNonHumanInteractionTagged(rule)) { + if (isNonHumanInteractionTagged(rule)) { return TopRuleAppCost.INSTANCE; } - if(hasModality(goal.node())) { + if (hasModality(goal.node())) { return delegate.computeCost(app, pio, goal); } String name = rule.name().toString(); - if(ADMITTED_RULES_SET.contains(name)) { + if (ADMITTED_RULES_SET.contains(name)) { return NumberRuleAppCost.getZeroCost(); } - + // apply OSS to () calls. - if(rule instanceof OneStepSimplifier) { + if (rule instanceof OneStepSimplifier) { Term target = pio.subTerm(); - if(target.op() instanceof UpdateApplication) { + if (target.op() instanceof UpdateApplication) { Operator updatedOp = target.sub(1).op(); - if(updatedOp instanceof ObserverFunction) { + if (updatedOp instanceof ObserverFunction) { return NumberRuleAppCost.getZeroCost(); } } @@ -187,7 +189,7 @@ public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/DoWhileFinallyMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/DoWhileFinallyMacro.java index eda49fc33cf..d015f773b38 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/DoWhileFinallyMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/DoWhileFinallyMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -11,17 +14,19 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * The abstract class DoWhileFinallyMacro can be used to create compound macros - * which apply the macro given by {@link getProofMacro()} as long the given bound - * of steps is not reached yet, the condition given by {@link getCondition()} - * holds, and the macro is applicable. When this becomes false and the step bound - * is not reached yet, the macro given by {@link getAltProofMacro()} is applied. + * The abstract class DoWhileFinallyMacro can be used to create compound macros which apply the + * macro given by {@link getProofMacro()} as long the given bound of steps is not reached yet, the + * condition given by {@link getCondition()} holds, and the macro is applicable. When this becomes + * false and the step bound is not reached yet, the macro given by {@link getAltProofMacro()} is + * applied. * * @author Michael Kirsten */ public abstract class DoWhileFinallyMacro extends AbstractProofMacro { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getName() */ @Override @@ -29,21 +34,21 @@ public String getName() { return "Apply macro as long as condition is met, then apply other macro"; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getDescription() */ @Override public String getDescription() { - return "Applies specificed macro as long as specified condition is met" + - "with no more rule applications than specified. If the" + - "macro is not applicable anymore and the maximum steps" + - "are not reached yet, then apply other macro once."; + return "Applies specificed macro as long as specified condition is met" + + "with no more rule applications than specified. If the" + + "macro is not applicable anymore and the maximum steps" + + "are not reached yet, then apply other macro once."; } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { if (getCondition()) { return getProofMacro().canApplyTo(proof, goals, posInOcc); } else { @@ -52,19 +57,16 @@ public boolean canApplyTo(Proof proof, } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception { ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals); int steps = getMaxSteps(proof); final ProofMacro macro = getProofMacro(); while (steps > 0 && getCondition() && macro.canApplyTo(proof, goals, posInOcc)) { - final ProverTaskListener pml = - new ProofMacroListener(getName(), listener); + final ProverTaskListener pml = new ProofMacroListener(getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - synchronized(macro) { + synchronized (macro) { // wait for macro to terminate info = macro.applyTo(uic, proof, goals, posInOcc, pml); } @@ -77,11 +79,10 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, } final ProofMacro altMacro = getAltProofMacro(); if (steps > 0 && altMacro.canApplyTo(proof, goals, posInOcc)) { - final ProverTaskListener pml = - new ProofMacroListener(getName(), listener); + final ProverTaskListener pml = new ProofMacroListener(getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, altMacro.getName(), 0)); info = altMacro.applyTo(uic, proof, goals, posInOcc, pml); - synchronized(altMacro) { + synchronized (altMacro) { // wait for macro to terminate info = new ProofMacroFinishedInfo(this, info); } @@ -105,4 +106,4 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, protected abstract ProofMacro getAltProofMacro(); protected abstract boolean getCondition(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FilterStrategy.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FilterStrategy.java index c74b681cd15..e81cb3f76b4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FilterStrategy.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FilterStrategy.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.logic.PosInOccurrence; @@ -23,7 +26,7 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { @Override public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, Goal goal) { - if(!isApprovedApp(app, pio, goal)) { + if (!isApprovedApp(app, pio, goal)) { return TopRuleAppCost.INSTANCE; } return delegate.computeCost(app, pio, goal); @@ -35,4 +38,4 @@ public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, delegate.instantiateApp(app, pio, goal, collector); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionMacro.java index 798138df255..f2b4316ee49 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.logic.Name; @@ -17,11 +20,11 @@ import de.uka.ilkd.key.strategy.Strategy; /** - * The macro FinishSymbolicExecutionMacro continues automatic rule application - * until there is no more modality on the sequent. + * The macro FinishSymbolicExecutionMacro continues automatic rule application until there is no + * more modality on the sequent. * - * This is done by implementing a delegation {@link Strategy} which assigns to - * any rule application infinite costs if there is no modality on the sequent. + * This is done by implementing a delegation {@link Strategy} which assigns to any rule application + * infinite costs if there is no modality on the sequent. * * @author mattias ulbrich */ @@ -52,14 +55,13 @@ public String getDescription() { /** * find a modality term in a node * - * @param node - * TODO + * @param node TODO * @return TODO */ static boolean hasModality(Node node) { Sequent sequent = node.sequent(); for (SequentFormula sequentFormula : sequent) { - if(hasModality(sequentFormula.formula())) { + if (hasModality(sequentFormula.formula())) { return true; } } @@ -71,17 +73,17 @@ static boolean hasModality(Node node) { * recursively descent into the term to detect a modality. */ private static boolean hasModality(Term term) { - if(term.containsLabel(ParameterlessTermLabel.SELF_COMPOSITION_LABEL)) { + if (term.containsLabel(ParameterlessTermLabel.SELF_COMPOSITION_LABEL)) { // ignore self composition terms return false; } - if(term.op() instanceof Modality) { + if (term.op() instanceof Modality) { return true; } for (Term sub : term.subs()) { - if(hasModality(sub)) { + if (hasModality(sub)) { return true; } } @@ -92,8 +94,7 @@ private static boolean hasModality(Term term) { /** * Checks if a rule is marked as not suited for interaction. * - * @param rule - * TODO + * @param rule TODO * @return TODO */ static boolean isNonHumanInteractionTagged(Rule rule) { @@ -113,13 +114,12 @@ private static boolean isInRuleSet(Rule rule, Name ruleSetName) { @Override protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { - return new FilterSymbexStrategy( - proof.getActiveStrategy()); + return new FilterSymbexStrategy(proof.getActiveStrategy()); } /** - * The Class FilterAppManager is a special strategy assigning to any rule - * infinite costs if the goal has no modality + * The Class FilterAppManager is a special strategy assigning to any rule infinite costs if the + * goal has no modality */ private static class FilterSymbexStrategy extends FilterStrategy { @@ -136,20 +136,20 @@ public Name name() { @Override public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { - if(!hasModality(goal.node())) { + if (!hasModality(goal.node())) { return false; } - if(isNonHumanInteractionTagged(app.rule())) { + if (isNonHumanInteractionTagged(app.rule())) { return false; } return super.isApprovedApp(app, pio, goal); } - @Override - public boolean isStopAtFirstNonCloseableGoal() { - return false; - } + @Override + public boolean isStopAtFirstNonCloseableGoal() { + return false; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionUntilMergePointMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionUntilMergePointMacro.java index c901ade0d53..7a7605f9074 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionUntilMergePointMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FinishSymbolicExecutionUntilMergePointMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.HashSet; @@ -49,31 +52,28 @@ import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; /** - * The macro FinishSymbolicExecutionUntilJionPointMacro continues automatic rule - * application until a merge point is reached (i.e. a point where a {@link MergeRule} can - * be applied) or there is no more modality on the sequent. + * The macro FinishSymbolicExecutionUntilJionPointMacro continues automatic rule application until a + * merge point is reached (i.e. a point where a {@link MergeRule} can be applied) or there is no + * more modality on the sequent. *

    - * - * This is done by implementing a delegation {@link Strategy} which assigns to - * any rule application infinite costs if there is no modality on the sequent. - * + * + * This is done by implementing a delegation {@link Strategy} which assigns to any rule application + * infinite costs if there is no modality on the sequent. + * * @author Mattias Ulbrich * @author Dominic Scheurer * @see FinishSymbolicExecutionMacro */ -public class FinishSymbolicExecutionUntilMergePointMacro extends - StrategyProofMacro { +public class FinishSymbolicExecutionUntilMergePointMacro extends StrategyProofMacro { private HashSet blockElems = new HashSet(); private HashSet alreadySeen = new HashSet(); private UserInterfaceControl uic = null; - public FinishSymbolicExecutionUntilMergePointMacro() { - } + public FinishSymbolicExecutionUntilMergePointMacro() {} - public FinishSymbolicExecutionUntilMergePointMacro( - HashSet blockElems) { + public FinishSymbolicExecutionUntilMergePointMacro(HashSet blockElems) { this.blockElems = blockElems; } @@ -95,9 +95,8 @@ public String getDescription() { /** * Returns true iff there is a modality in the sequent of the given node. - * - * @param node - * Node to check. + * + * @param node Node to check. * @return True iff there is a modality in the sequent of the given node. */ private static boolean hasModality(Node node) { @@ -113,9 +112,8 @@ private static boolean hasModality(Node node) { /** * Recursive check for existence of modality. - * - * @param term - * The term to check. + * + * @param term The term to check. * @return True iff there is a modality in the sequent of the given term. */ private static boolean hasModality(Term term) { @@ -138,9 +136,9 @@ private static boolean hasModality(Term term) { } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, ImmutableList goals, PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException { this.uic = uic; return super.applyTo(uic, proof, goals, posInOcc, listener); } @@ -176,21 +174,17 @@ protected void doPostProcessing(Proof proof) { // Do single proof step new OneStepProofMacro().applyTo(uic, goal.node(), null, DUMMY_PROVER_TASK_LISTENER); // TODO Change - } - catch (InterruptedException e) { - } - catch (Exception e) { + } catch (InterruptedException e) { + } catch (Exception e) { } // We want no splits, but the proof must have changed if (lastNode.childrenCount() == 1) { lastNode = lastNode.child(0); - } - else { + } else { break; } - } - while (hasBreakPoint(goal.sequent().succedent())); + } while (hasBreakPoint(goal.sequent().succedent())); // Undo until a break condition is the first active statement again. while (!hasBreakPoint(lastNode.sequent().succedent())) { @@ -206,30 +200,23 @@ protected void doPostProcessing(Proof proof) { */ private static final ProverTaskListener DUMMY_PROVER_TASK_LISTENER = new ProverTaskListener() { @Override - public void taskProgress(int position) { - } + public void taskProgress(int position) {} @Override - public void taskStarted(TaskStartedInfo info) { - } + public void taskStarted(TaskStartedInfo info) {} @Override - public void taskFinished(TaskFinishedInfo info) { - } + public void taskFinished(TaskFinishedInfo info) {} }; /** - * @param succedent - * Succedent of a sequent. - * @return true iff the given succedent has one formula with a break point - * statement. + * @param succedent Succedent of a sequent. + * @return true iff the given succedent has one formula with a break point statement. */ private boolean hasBreakPoint(Semisequent succedent) { for (SequentFormula formula : succedent.asList()) { - if (blockElems - .contains(JavaTools - .getActiveStatement(MergeRuleUtils.getJavaBlockRecursive(formula - .formula())))) { + if (blockElems.contains(JavaTools + .getActiveStatement(MergeRuleUtils.getJavaBlockRecursive(formula.formula())))) { return true; } } @@ -238,14 +225,12 @@ private boolean hasBreakPoint(Semisequent succedent) { } /** - * The Class FilterSymbexStrategy is a special strategy assigning to any - * rule infinite costs if the goal has no modality or if a merge point is - * reached. + * The Class FilterSymbexStrategy is a special strategy assigning to any rule infinite costs if + * the goal has no modality or if a merge point is reached. */ private class FilterSymbexStrategy extends FilterStrategy { - private final Name NAME = new Name( - FilterSymbexStrategy.class.getSimpleName()); + private final Name NAME = new Name(FilterSymbexStrategy.class.getSimpleName()); public FilterSymbexStrategy(Strategy delegate) { super(delegate); @@ -268,27 +253,24 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { if (pio != null) { JavaBlock theJavaBlock = MergeRuleUtils.getJavaBlockRecursive(pio.subTerm()); - SourceElement activeStmt = JavaTools - .getActiveStatement(theJavaBlock); + SourceElement activeStmt = JavaTools.getActiveStatement(theJavaBlock); if (!(theJavaBlock.program() instanceof StatementBlock) - || (alreadySeen.contains(theJavaBlock) && !blockElems - .contains(activeStmt))) { + || (alreadySeen.contains(theJavaBlock) + && !blockElems.contains(activeStmt))) { // For sake of efficiency: Do not treat the same // statement block multiple times. However, we have // to consider it if it is a break point, of course. return super.isApprovedApp(app, pio, goal); - } - else if (!theJavaBlock.equals(JavaBlock.EMPTY_JAVABLOCK)) { + } else if (!theJavaBlock.equals(JavaBlock.EMPTY_JAVABLOCK)) { alreadySeen.add(theJavaBlock); } // Find break points - blockElems.addAll(findMergePoints((StatementBlock) theJavaBlock - .program(), goal.proof().getServices())); + blockElems.addAll(findMergePoints((StatementBlock) theJavaBlock.program(), + goal.proof().getServices())); - if (app.rule().name().toString() - .equals("One Step Simplification")) { + if (app.rule().name().toString().equals("One Step Simplification")) { // We allow One Step Simplification, otherwise we sometimes // would have to do a simplification ourselves before @@ -302,12 +284,10 @@ else if (!theJavaBlock.equals(JavaBlock.EMPTY_JAVABLOCK)) { } /** - * Returns a set of merge points for the given statement block. A merge - * point is the statement in a program directly after an if-then-else or - * a try-catch-finally block. - * - * @param toSearch - * The statement block to search for merge points. + * Returns a set of merge points for the given statement block. A merge point is the + * statement in a program directly after an if-then-else or a try-catch-finally block. + * + * @param toSearch The statement block to search for merge points. * @return A set of merge points for the given statement block. */ private HashSet findMergePoints(StatementBlock toSearch, @@ -333,8 +313,7 @@ private HashSet findMergePoints(StatementBlock toSearch, for (int i = 0; i < stmts.size(); i++) { SourceElement stmt = stmts.get(i); - if ((stmt instanceof If || stmt instanceof Try) - && i < stmts.size() - 1) { + if ((stmt instanceof If || stmt instanceof Try) && i < stmts.size() - 1) { // We have found a reason for a break point (i.e., // a try or if statement), so let's add the next // statement as a break point. @@ -348,8 +327,8 @@ private HashSet findMergePoints(StatementBlock toSearch, // of potential nested loops, so there may occur // an early stop in this case. - FindBreakVisitor visitor = new FindBreakVisitor(getBodies( - stmt).element(), services); + FindBreakVisitor visitor = + new FindBreakVisitor(getBodies(stmt).element(), services); visitor.start(); if (visitor.containsBreak()) { result.add(stmts.get(i + 1)); @@ -361,8 +340,8 @@ private HashSet findMergePoints(StatementBlock toSearch, } /** - * Visitor for finding out whether there is a break statement contained - * in a program element. + * Visitor for finding out whether there is a break statement contained in a program + * element. */ private class FindBreakVisitor extends JavaASTVisitor { private boolean containsBreak = false; @@ -379,8 +358,7 @@ public boolean containsBreak() { } @Override - protected void doDefaultAction(SourceElement node) { - } + protected void doDefaultAction(SourceElement node) {} @Override public void performActionOnBreak(Break x) { @@ -389,61 +367,47 @@ public void performActionOnBreak(Break x) { }; /** - * Returns the bodies for various compound statements like if, try, - * case, etc. If there is no body, an empty list is returned. - * - * @param elem - * The element to return the bodies for. + * Returns the bodies for various compound statements like if, try, case, etc. If there is + * no body, an empty list is returned. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(SourceElement elem) { if (elem instanceof If) { return getBodies((If) elem); - } - else if (elem instanceof Then) { + } else if (elem instanceof Then) { return getBodies((Then) elem); - } - else if (elem instanceof Else) { + } else if (elem instanceof Else) { return getBodies((Else) elem); - } - else if (elem instanceof Try) { + } else if (elem instanceof Try) { return getBodies((Try) elem); - } - else if (elem instanceof Catch) { + } else if (elem instanceof Catch) { return getBodies((Catch) elem); - } - else if (elem instanceof Finally) { + } else if (elem instanceof Finally) { return getBodies((Finally) elem); - } - else if (elem instanceof MethodFrame) { + } else if (elem instanceof MethodFrame) { return getBodies((MethodFrame) elem); - } - else if (elem instanceof Case) { + } else if (elem instanceof Case) { return getBodies((Case) elem); - } - else if (elem instanceof CatchAllStatement) { + } else if (elem instanceof CatchAllStatement) { return getBodies((CatchAllStatement) elem); - } - else if (elem instanceof LabeledStatement) { + } else if (elem instanceof LabeledStatement) { return getBodies((LabeledStatement) elem); - } - else if (elem instanceof LoopStatement) { + } else if (elem instanceof LoopStatement) { return getBodies((LoopStatement) elem); - } - else if (elem instanceof SynchronizedBlock) { + } else if (elem instanceof SynchronizedBlock) { return getBodies((SynchronizedBlock) elem); - } - else { + } else { return new LinkedList(); } } /** - * Returns the bodies for an If element. NOTE: This includes the bodies - * for the Then *and* the Else part! - * - * @param elem - * The element to return the bodies for. + * Returns the bodies for an If element. NOTE: This includes the bodies for the Then *and* + * the Else part! + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(If elem) { @@ -460,9 +424,8 @@ private LinkedList getBodies(If elem) { /** * Returns the body for a Then element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Then elem) { @@ -478,9 +441,8 @@ private LinkedList getBodies(Then elem) { /** * Returns the body for an Else element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Else elem) { @@ -495,11 +457,10 @@ private LinkedList getBodies(Else elem) { } /** - * Returns the bodies for a Try element. NOTE: This includes the bodies - * for Try *and* for the branches! - * - * @param elem - * The element to return the bodies for. + * Returns the bodies for a Try element. NOTE: This includes the bodies for Try *and* for + * the branches! + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Try elem) { @@ -522,9 +483,8 @@ private LinkedList getBodies(Try elem) { /** * Returns the body for a Catch element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Catch elem) { @@ -540,9 +500,8 @@ private LinkedList getBodies(Catch elem) { /** * Returns the body for a Finally element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Finally elem) { @@ -558,9 +517,8 @@ private LinkedList getBodies(Finally elem) { /** * Returns the body for a MethodFrame element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(MethodFrame elem) { @@ -576,9 +534,8 @@ private LinkedList getBodies(MethodFrame elem) { /** * Returns the bodies for a Case element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(Case elem) { @@ -596,9 +553,8 @@ private LinkedList getBodies(Case elem) { /** * Returns the body for a CatchAllStatement element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(CatchAllStatement elem) { @@ -614,9 +570,8 @@ private LinkedList getBodies(CatchAllStatement elem) { /** * Returns the body for a LabeledStatement element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(LabeledStatement elem) { @@ -632,9 +587,8 @@ private LinkedList getBodies(LabeledStatement elem) { /** * Returns the body for a LoopStatement element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(LoopStatement elem) { @@ -650,9 +604,8 @@ private LinkedList getBodies(LoopStatement elem) { /** * Returns the body for a SynchronizedBlock element. - * - * @param elem - * The element to return the bodies for. + * + * @param elem The element to return the bodies for. * @return The bodies for the given source element. */ private LinkedList getBodies(SynchronizedBlock elem) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullAutoPilotProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullAutoPilotProofMacro.java index f4c1e9119cb..34dd8354f85 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullAutoPilotProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullAutoPilotProofMacro.java @@ -1,8 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; /** - * This class captures a proof macro which is meant to fully automise KeY proof - * workflow. + * This class captures a proof macro which is meant to fully automise KeY proof workflow. * * It is experimental. * @@ -19,8 +21,8 @@ public class FullAutoPilotProofMacro extends SequentialProofMacro { /** - * The number of proof steps that should be run by the {@link TryCloseMacro} - * before retracting. This overrides the strategy setting. + * The number of proof steps that should be run by the {@link TryCloseMacro} before retracting. + * This overrides the strategy setting. */ private static final int NUMBER_OF_TRY_STEPS = Integer.getInteger("key.autopilot.closesteps", 1000); @@ -43,17 +45,14 @@ public String getScriptCommandName() { @Override public String getDescription() { - return "

    1. Finish symbolic execution" + - "
    2. Separate proof obligations" + - "
    3. Expand invariant definitions" + - "
    4. Try to close all proof obligations
    "; + return "
    1. Finish symbolic execution" + "
    2. Separate proof obligations" + + "
    3. Expand invariant definitions" + + "
    4. Try to close all proof obligations
    "; } @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { - new AutoPilotPrepareProofMacro(), - new TryCloseMacro(NUMBER_OF_TRY_STEPS) - }; + return new ProofMacro[] { new AutoPilotPrepareProofMacro(), + new TryCloseMacro(NUMBER_OF_TRY_STEPS) }; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullPropositionalExpansionMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullPropositionalExpansionMacro.java index 7adda6b3d47..f8ccdff5411 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullPropositionalExpansionMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/FullPropositionalExpansionMacro.java @@ -1,10 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Set; /** - * The macro FullPropositionalExpansionMacro apply rules to decompose - * propositional toplevel formulas; it even splits the goal if necessary. + * The macro FullPropositionalExpansionMacro apply rules to decompose propositional toplevel + * formulas; it even splits the goal if necessary. * * The rules that are applied can be set in {@link #ADMITTED_RULES}. * @@ -19,8 +22,8 @@ public String getName() { @Override public String getDescription() { - return "Apply rules to decompose propositional toplevel formulas; " + - "splits the goal if necessary"; + return "Apply rules to decompose propositional toplevel formulas; " + + "splits the goal if necessary"; } @Override @@ -28,13 +31,11 @@ public String getScriptCommandName() { return "split-prop"; } - private static final String[] ADMITTED_RULES = { - "andLeft", "orRight", "impRight", "notLeft", "notRight", "close", - "andRight", "orLeft", "impLeft", - "closeTrue", "closeFalse", "true_left", "false_right", -// "ifthenelse_split", "ifthenelse_split_for", - "equivLeft", "equivRight" - }; + private static final String[] ADMITTED_RULES = + { "andLeft", "orRight", "impRight", "notLeft", "notRight", "close", "andRight", + "orLeft", "impLeft", "closeTrue", "closeFalse", "true_left", "false_right", + // "ifthenelse_split", "ifthenelse_split_for", + "equivLeft", "equivRight" }; private static final Set ADMITTED_RULES_SET = asSet(ADMITTED_RULES); @@ -47,4 +48,4 @@ protected Set getAdmittedRuleNames() { protected boolean allowOSS() { return false; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/HeapSimplificationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/HeapSimplificationMacro.java index 42b6ea9197b..d5d570f17f3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/HeapSimplificationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/HeapSimplificationMacro.java @@ -1,11 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Set; /** - * This macro performs simplification of Heap and LocSet terms. - * It applies simplification rules (including the "unoptimized" select rules), - * One Step Simplification, alpha, and delta rules. + * This macro performs simplification of Heap and LocSet terms. It applies simplification rules + * (including the "unoptimized" select rules), One Step Simplification, alpha, and delta rules. + * * @author bruns * */ @@ -29,163 +32,83 @@ public String getScriptCommandName() { @Override public String getDescription() { return "This macro performs simplification of Heap and LocSet terms.\n" - +"It applies simplification rules (including the \"unoptimized\" select rules), " - +"One Step Simplification, alpha, and delta rules."; + + "It applies simplification rules (including the \"unoptimized\" select rules), " + + "One Step Simplification, alpha, and delta rules."; } // note that rules in the 'concrete' rule set are usually not included here - private static final Set ADMITTED_RULES_SET = asSet(new String[]{ - "selectOfStore", - "selectOfCreate", - "selectOfAnon", - "selectOfMemset", - - "selectCreatedOfStore", - "selectCreatedOfCreate", - "selectCreatedOfAnon", - "selectCreatedOfMemset", - - "dismissNonSelectedField", - "dismissNonSelectedFieldEQ", - "replaceKnownSelect", - "dropEffectlessStores", - "memsetEmpty", - "selectCreatedOfAnonAsFormula", - - "wellFormedStoreObject", - "wellFormedStoreArray", - "wellFormedStorePrimitive", - "wellFormedStorePrimitiveArray", - "wellFormedStoreLocSet", - "wellFormedCreate", - "wellFormedAnon", - "wellFormedMemsetArrayObject", - "wellFormedMemsetArrayPrimitive", - "wellFormedMemsetObject", - "wellFormedMemsetLocSet", - "wellFormedMemsetPrimitive", - - - // EQ versions of the above - "selectOfStoreEQ", - "selectOfCreateEQ", - "selectOfAnonEQ", - "selectOfMemsetEQ", - - "selectCreatedOfStoreEQ", - "selectCreatedOfCreateEQ", - "selectCreatedOfAnonEQ", - "selectCreatedOfMemsetEQ", - - "wellFormedStoreObjectEQ", - "wellFormedStoreArrayEQ", - "wellFormedStorePrimitiveEQ", - "wellFormedStorePrimitiveArrayEQ", - "wellFormedStoreLocSetEQ", - "wellFormedCreateEQ", - "wellFormedAnonEQ", - "wellFormedMemsetArrayObjectEQ", - "wellFormedMemsetArrayPrimitiveEQ", - "wellFormedMemsetObjectEQ", - "wellFormedMemsetLocSetEQ", - "wellFormedMemsetPrimitiveEQ", - - // locset rules - "elementOfEmpty", - "elementOfAllLocs", - "elementOfSingleton", - "elementOfUnion", - "elementOfIntersect", - "elementOfSetMinus", - "elementOfAllFields", - "elementOfAllObjects", - "elementOfArrayRange", - "elementOfFreshLocs", - "elementOfInfiniteUnion", - "elementOfInfiniteUnion2Vars", - - "allFieldsEq", - "subsetSingletonLeft", - "subsetSingletonLeftEQ", - "subsetSingletonRight", - "subsetSingletonRightEQ", - "subsetUnionLeft", - "subsetUnionLeftEQ", - "subsetOfIntersectWithItSelfEQ1", - "subsetOfIntersectWithItSelfEQ2", - "allFieldsSubsetOf", - "disjointAllFields", - "disjointAllObjects", - "disjointInfiniteUnion", - "disjointInfiniteUnion_2", - "intersectAllFieldsFreshLocs", - "disjointWithSingleton1", - "disjointWithSingleton2", - "sortsDisjointModuloNull", - - "createdInHeapWithSingleton", - "createdInHeapWithAllFields", - "createdInHeapWithArrayRange", - "createdInHeapWithSingletonEQ", - "createdInHeapWithUnionEQ", - "createdInHeapWithSetMinusFreshLocsEQ", - "createdInHeapWithAllFieldsEQ", - "createdInHeapWithArrayRangeEQ", - "createdInHeapWithSelectEQ", - "createdInHeapWithObserverEQ", - - "elementOfEmptyEQ", - "elementOfAllLocsEQ", - "elementOfSingletonEQ", - "elementOfUnionEQ", - "elementOfIntersectEQ", - "elementOfSetMinusEQ", - "elementOfAllFieldsEQ", - "elementOfAllObjectsEQ", - "elementOfArrayRangeEQ", - "elementOfFreshLocsEQ", - "elementOfInfiniteUnion2VarsEQ", - - // rules listed under "other lemma" - "unionEqualsEmpty", - "unionEqualsEmptyEQ", - "intersectWithSingleton", - "setMinusSingleton", - "unionIntersectItself", - "unionIntersectItself_2", - "unionIntersectItself_3", - "unionIntersectItself_4", - "unionIntersectItself_5", - "unionIntersectItself_6", - - // normalization rules are currently not included - - // semantics blasting rules -// "equalityToElementOfRight", -// "subsetToElementOfRight", - "disjointDefinition", // TODO: may have own rules in future - "definitionAllElementsOfArray", - "definitionAllElementsOfArrayLocsets", - - // alpha rules - "impRight", - "andLeft", - "orRight", - "close", - "closeTrue", - "closeFalse", - "ifthenelse_negated", - // TODO: those must be more expensive -// "replace_known_left", -// "replace_known_right", - - // others - "castDel", - "nonNull", - "nonNullZero", - "allRight", - "exLeft", - }); + private static final Set ADMITTED_RULES_SET = asSet(new String[] { "selectOfStore", + "selectOfCreate", "selectOfAnon", "selectOfMemset", + + "selectCreatedOfStore", "selectCreatedOfCreate", "selectCreatedOfAnon", + "selectCreatedOfMemset", + + "dismissNonSelectedField", "dismissNonSelectedFieldEQ", "replaceKnownSelect", + "dropEffectlessStores", "memsetEmpty", "selectCreatedOfAnonAsFormula", + + "wellFormedStoreObject", "wellFormedStoreArray", "wellFormedStorePrimitive", + "wellFormedStorePrimitiveArray", "wellFormedStoreLocSet", "wellFormedCreate", + "wellFormedAnon", "wellFormedMemsetArrayObject", "wellFormedMemsetArrayPrimitive", + "wellFormedMemsetObject", "wellFormedMemsetLocSet", "wellFormedMemsetPrimitive", + + + // EQ versions of the above + "selectOfStoreEQ", "selectOfCreateEQ", "selectOfAnonEQ", "selectOfMemsetEQ", + + "selectCreatedOfStoreEQ", "selectCreatedOfCreateEQ", "selectCreatedOfAnonEQ", + "selectCreatedOfMemsetEQ", + + "wellFormedStoreObjectEQ", "wellFormedStoreArrayEQ", "wellFormedStorePrimitiveEQ", + "wellFormedStorePrimitiveArrayEQ", "wellFormedStoreLocSetEQ", "wellFormedCreateEQ", + "wellFormedAnonEQ", "wellFormedMemsetArrayObjectEQ", "wellFormedMemsetArrayPrimitiveEQ", + "wellFormedMemsetObjectEQ", "wellFormedMemsetLocSetEQ", "wellFormedMemsetPrimitiveEQ", + + // locset rules + "elementOfEmpty", "elementOfAllLocs", "elementOfSingleton", "elementOfUnion", + "elementOfIntersect", "elementOfSetMinus", "elementOfAllFields", "elementOfAllObjects", + "elementOfArrayRange", "elementOfFreshLocs", "elementOfInfiniteUnion", + "elementOfInfiniteUnion2Vars", + + "allFieldsEq", "subsetSingletonLeft", "subsetSingletonLeftEQ", "subsetSingletonRight", + "subsetSingletonRightEQ", "subsetUnionLeft", "subsetUnionLeftEQ", + "subsetOfIntersectWithItSelfEQ1", "subsetOfIntersectWithItSelfEQ2", "allFieldsSubsetOf", + "disjointAllFields", "disjointAllObjects", "disjointInfiniteUnion", + "disjointInfiniteUnion_2", "intersectAllFieldsFreshLocs", "disjointWithSingleton1", + "disjointWithSingleton2", "sortsDisjointModuloNull", + + "createdInHeapWithSingleton", "createdInHeapWithAllFields", + "createdInHeapWithArrayRange", "createdInHeapWithSingletonEQ", + "createdInHeapWithUnionEQ", "createdInHeapWithSetMinusFreshLocsEQ", + "createdInHeapWithAllFieldsEQ", "createdInHeapWithArrayRangeEQ", + "createdInHeapWithSelectEQ", "createdInHeapWithObserverEQ", + + "elementOfEmptyEQ", "elementOfAllLocsEQ", "elementOfSingletonEQ", "elementOfUnionEQ", + "elementOfIntersectEQ", "elementOfSetMinusEQ", "elementOfAllFieldsEQ", + "elementOfAllObjectsEQ", "elementOfArrayRangeEQ", "elementOfFreshLocsEQ", + "elementOfInfiniteUnion2VarsEQ", + + // rules listed under "other lemma" + "unionEqualsEmpty", "unionEqualsEmptyEQ", "intersectWithSingleton", "setMinusSingleton", + "unionIntersectItself", "unionIntersectItself_2", "unionIntersectItself_3", + "unionIntersectItself_4", "unionIntersectItself_5", "unionIntersectItself_6", + + // normalization rules are currently not included + + // semantics blasting rules + // "equalityToElementOfRight", + // "subsetToElementOfRight", + "disjointDefinition", // TODO: may have own rules in future + "definitionAllElementsOfArray", "definitionAllElementsOfArrayLocsets", + + // alpha rules + "impRight", "andLeft", "orRight", "close", "closeTrue", "closeFalse", + "ifthenelse_negated", + // TODO: those must be more expensive + // "replace_known_left", + // "replace_known_right", + + // others + "castDel", "nonNull", "nonNullZero", "allRight", "exLeft", }); @Override @@ -194,7 +117,7 @@ protected Set getAdmittedRuleNames() { } @Override - protected boolean allowOSS () { + protected boolean allowOSS() { return true; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/IntegerSimplificationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/IntegerSimplificationMacro.java index 7d71589ecf0..5245abdc866 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/IntegerSimplificationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/IntegerSimplificationMacro.java @@ -1,10 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Set; /** - * This macro performs simplification of integers and terms with integers. - * It applies only non-splitting simplification rules. + * This macro performs simplification of integers and terms with integers. It applies only + * non-splitting simplification rules. + * * @author Michael Kirsten * */ @@ -28,110 +32,35 @@ public String getScriptCommandName() { @Override public String getDescription() { return "This macro performs simplification of integers and terms with integers.\n" - +"It applies only non-splitting simplification rules."; + + "It applies only non-splitting simplification rules."; } - private static final Set ADMITTED_RULES_SET = asSet(new String[]{ - "add_eq_back", - "add_eq_back_2", - "add_eq_back_2_fst_comm", - "add_eq_back_3", - "add_less_back", - "add_less_back_zero_1", - "add_less_back_zero_1_comm", - "add_less_back_zero_2", - "add_less_back_zero_2_comm", - "add_literals", - "add_sub_elim_left", - "add_sub_elim_right", - "add_zero_left", - "add_zero_right", - "binaryAndOne", - "binaryAndZeroLeft", - "binaryAndZeroRight", - "binaryOrNeutralLeft", - "binaryOrNeutralRight", - "bprod_lower_equals_upper", - "bprod_one", - "bprod_zero", - "bsum_lower_equals_upper", - "bsum_zero", - "castDel", - "castDel2", - "castDel3", - //"castedGetAny", - "div_literals", - "double_unary_minus_literal", - "equal_literals", - "greater_literals", - "i_minus_i_is_zero", - "inChar", - "inByte", - "inInt", - "inLong", - "inShort", - "le1_add1_eq_le", - "leq_diff1_eq", - "leq_diff_1", - "leq_literals", - "less_base", - "less_literals", - "lt_diff_1", - "lt_to_leq_1", - "lt_to_leq_2", - "minus_distribute_1", - "minus_distribute_2", - "moduloByteIsInByte", - "moduloCharIsInChar", - "moduloIntIsInInt", - "moduloLongIsInLong", - "moduloShortIsInShort", - "mul_literals", - "neg_literal", - "polySimp_addAssoc", - "polySimp_addLiterals", - "polySimp_elimOne", - "polySimp_elimOneLeft0", - "polySimp_mulAssoc", - "polySimp_mulLiterals", - "pow_literals", - "precOfInt", - "precOfIntPair", - "precOfPairInt", - "prod_empty", - "prod_one", - "qeq_literals", - "square_nonneg", - "sub", - "sub_literals", - "sub_sub_elim", - "sub_zero_1", - "sub_zero_2", - "sum_empty", - "sum_zero", - "times_minus_one_1", - "times_minus_one_2", - "times_one_1", - "times_one_2", - "times_zero_1", - "times_zero_2", - "translateJavaAddInt", - "translateJavaAddLong", - "translateJavaCastByte", - "translateJavaCastChar", - "translateJavaCastInt", - "translateJavaCastLong", - "translateJavaCastShort", - "translateJavaDivInt", - "translateJavaDivLong", - "translateJavaMod", - "translateJavaMulInt", - "translateJavaMulLong", - "translateJavaSubInt", - "translateJavaSubLong", - "translateJavaUnaryMinusInt", - "translateJavaUnaryMinusLong" - }); + private static final Set ADMITTED_RULES_SET = asSet(new String[] { "add_eq_back", + "add_eq_back_2", "add_eq_back_2_fst_comm", "add_eq_back_3", "add_less_back", + "add_less_back_zero_1", "add_less_back_zero_1_comm", "add_less_back_zero_2", + "add_less_back_zero_2_comm", "add_literals", "add_sub_elim_left", "add_sub_elim_right", + "add_zero_left", "add_zero_right", "binaryAndOne", "binaryAndZeroLeft", + "binaryAndZeroRight", "binaryOrNeutralLeft", "binaryOrNeutralRight", + "bprod_lower_equals_upper", "bprod_one", "bprod_zero", "bsum_lower_equals_upper", + "bsum_zero", "castDel", "castDel2", "castDel3", + // "castedGetAny", + "div_literals", "double_unary_minus_literal", "equal_literals", "greater_literals", + "i_minus_i_is_zero", "inChar", "inByte", "inInt", "inLong", "inShort", "le1_add1_eq_le", + "leq_diff1_eq", "leq_diff_1", "leq_literals", "less_base", "less_literals", "lt_diff_1", + "lt_to_leq_1", "lt_to_leq_2", "minus_distribute_1", "minus_distribute_2", + "moduloByteIsInByte", "moduloCharIsInChar", "moduloIntIsInInt", "moduloLongIsInLong", + "moduloShortIsInShort", "mul_literals", "neg_literal", "polySimp_addAssoc", + "polySimp_addLiterals", "polySimp_elimOne", "polySimp_elimOneLeft0", + "polySimp_mulAssoc", "polySimp_mulLiterals", "pow_literals", "precOfInt", + "precOfIntPair", "precOfPairInt", "prod_empty", "prod_one", "qeq_literals", + "square_nonneg", "sub", "sub_literals", "sub_sub_elim", "sub_zero_1", "sub_zero_2", + "sum_empty", "sum_zero", "times_minus_one_1", "times_minus_one_2", "times_one_1", + "times_one_2", "times_zero_1", "times_zero_2", "translateJavaAddInt", + "translateJavaAddLong", "translateJavaCastByte", "translateJavaCastChar", + "translateJavaCastInt", "translateJavaCastLong", "translateJavaCastShort", + "translateJavaDivInt", "translateJavaDivLong", "translateJavaMod", + "translateJavaMulInt", "translateJavaMulLong", "translateJavaSubInt", + "translateJavaSubLong", "translateJavaUnaryMinusInt", "translateJavaUnaryMinusLong" }); @Override protected Set getAdmittedRuleNames() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/OneStepProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/OneStepProofMacro.java index b385057e296..0bab68bf6d9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/OneStepProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/OneStepProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.logic.Name; @@ -11,7 +14,7 @@ /** * Apply a single proof step. - * + * * @author Simon Greiner */ public class OneStepProofMacro extends StrategyProofMacro { @@ -32,7 +35,7 @@ public String getCategory() { } @Override - public String getDescription() { + public String getDescription() { return "One single proof step is applied"; } @@ -43,8 +46,8 @@ protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { /** - * Strategy with counter, s.t. only one rule is applied - * + * Strategy with counter, s.t. only one rule is applied + * * */ @@ -53,6 +56,7 @@ private static class OneStepStrategy implements Strategy { private static final Name NAME = new Name(OneStepStrategy.class.getSimpleName()); private int counter; public Strategy delegate; + public OneStepStrategy(Strategy delegate) { this.delegate = delegate; this.counter = 0; @@ -62,22 +66,23 @@ public OneStepStrategy(Strategy delegate) { public Name name() { return NAME; } + /** - * If no rule was applied yet, apply the first rule and increase counter, s.t. no more rules can be applied. + * If no rule was applied yet, apply the first rule and increase counter, s.t. no more rules + * can be applied. */ @Override public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { - if(counter == 0 && delegate.isApprovedApp(app, pio, goal)){ + if (counter == 0 && delegate.isApprovedApp(app, pio, goal)) { counter++; return true; - }else{ + } else { return false; } } @Override - public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, - Goal goal) { + public RuleAppCost computeCost(RuleApp app, PosInOccurrence pio, Goal goal) { return delegate.computeCost(app, pio, goal); } @@ -91,7 +96,7 @@ public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PrepareInfFlowContractPreBranchesMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PrepareInfFlowContractPreBranchesMacro.java index 258d4384249..546dcf94ce7 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PrepareInfFlowContractPreBranchesMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PrepareInfFlowContractPreBranchesMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.logic.Name; @@ -16,17 +19,16 @@ /** - * The macro UseInformationFlowContractMacro applies all applicable information - * flow contracts. + * The macro UseInformationFlowContractMacro applies all applicable information flow contracts. *

    * The rules that are applied can be set in {@link #ADMITTED_RULENAMES}. *

    + * * @author christoph */ public class PrepareInfFlowContractPreBranchesMacro extends StrategyProofMacro { - private static final String INF_FLOW_RULENAME_PREFIX = - "Use_information_flow_contract"; + private static final String INF_FLOW_RULENAME_PREFIX = "Use_information_flow_contract"; private static final String IMP_LEFT_RULENAME = "impLeft"; @@ -46,21 +48,20 @@ public String getCategory() { @Override public String getDescription() { - return "Removes the original post condition from information flow " + - "contract application pre-branches."; + return "Removes the original post condition from information flow " + + "contract application pre-branches."; } @Override - protected Strategy createStrategy(Proof proof, - PosInOccurrence posInOcc) { + protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { return new RemovePostStrategy(proof); } /** - * This strategy accepts all rule apps for which the rule name starts with a - * string in the admitted set and rejects everything else. + * This strategy accepts all rule apps for which the rule name starts with a string in the + * admitted set and rejects everything else. */ protected class RemovePostStrategy extends AbstractFeatureStrategy { @@ -79,15 +80,14 @@ public Name name() { @Override - public RuleAppCost computeCost(RuleApp ruleApp, - PosInOccurrence pio, - Goal goal) { + public RuleAppCost computeCost(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { String name = ruleApp.rule().name().toString(); if (name.equals("hide_right")) { - return applyTF( "b", IsPostConditionTermFeature.INSTANCE ).computeCost(ruleApp, pio, goal); + return applyTF("b", IsPostConditionTermFeature.INSTANCE).computeCost(ruleApp, pio, + goal); } else if (name.equals(AND_RIGHT_RULENAME)) { - RuleAppCost andRightCost = - FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE.computeCost(ruleApp, pio, goal); + RuleAppCost andRightCost = FocusIsSubFormulaOfInfFlowContractAppFeature.INSTANCE + .computeCost(ruleApp, pio, goal); return andRightCost.add(NumberRuleAppCost.create(1)); } else { return TopRuleAppCost.INSTANCE; @@ -96,30 +96,28 @@ public RuleAppCost computeCost(RuleApp ruleApp, @Override - public boolean isApprovedApp(RuleApp app, - PosInOccurrence pio, - Goal goal) { + public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { String name = app.rule().name().toString(); if (!name.equals("hide_right")) { return true; } // approve if - // - the parent.parent rule application is an information - // flow contract rule application, - // - the parent rule application is an impLeft rule application - // and - // - we are in the branch where we have to show the left hand side - // of the implication - if (goal.node().parent() != null && - goal.node().parent().parent() != null) { + // - the parent.parent rule application is an information + // flow contract rule application, + // - the parent rule application is an impLeft rule application + // and + // - we are in the branch where we have to show the left hand side + // of the implication + if (goal.node().parent() != null && goal.node().parent().parent() != null) { Node parent = goal.node().parent(); - return getAppRuleName(parent).equals(IMP_LEFT_RULENAME) && - getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) && - parent.child(0) == goal.node() || - getAppRuleName(parent).equals(DOUBLE_IMP_LEFT_RULENAME) && - getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) && - parent.child(2) != goal.node(); + return getAppRuleName(parent).equals(IMP_LEFT_RULENAME) + && getAppRuleName(parent.parent()).startsWith(INF_FLOW_RULENAME_PREFIX) + && parent.child(0) == goal.node() + || getAppRuleName(parent).equals(DOUBLE_IMP_LEFT_RULENAME) + && getAppRuleName(parent.parent()).startsWith( + INF_FLOW_RULENAME_PREFIX) + && parent.child(2) != goal.node(); } return false; } @@ -133,15 +131,13 @@ private String getAppRuleName(Node parent) { @Override - protected RuleAppCost instantiateApp(RuleApp app, - PosInOccurrence pio, - Goal goal) { + protected RuleAppCost instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal) { return computeCost(app, pio, goal); } @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacro.java index 163271dd4a3..6d24ec1e15c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -14,43 +17,39 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * The interface ProofMacro is the entry point to a general strategy extension - * system. + * The interface ProofMacro is the entry point to a general strategy extension system. * *

    Idea

    * - * Doing interaction with KeY is often tedious, many steps have to be performed - * over and over again. To facilitate the interaction, this frameworks allows a - * developer to define "macro strategy steps" which combine many individual - * steps and are helpful in an interactive verification attempt. + * Doing interaction with KeY is often tedious, many steps have to be performed over and over again. + * To facilitate the interaction, this frameworks allows a developer to define "macro strategy + * steps" which combine many individual steps and are helpful in an interactive verification + * attempt. * - * This interface is kept deliberately separate from many of the other - * mechanisms to remain open on how to implement the macro. + * This interface is kept deliberately separate from many of the other mechanisms to remain open on + * how to implement the macro. * *

    Usage

    * * Proof macros are meant to be stateless singletons. * - * Whenever a situation arises where the user wants to apply macros, they are - * asked whether they can be applied ( - * {@link #canApplyTo(KeYMediator, PosInOccurrence)}). A macro is offered to the - * user iff it returns true. No changes should be made there. + * Whenever a situation arises where the user wants to apply macros, they are asked whether they can + * be applied ( {@link #canApplyTo(KeYMediator, PosInOccurrence)}). A macro is offered to the user + * iff it returns true. No changes should be made there. * - * A macro is then applied using {@link #applyTo(KeYMediator, PosInOccurrence)}. - * This may change the proof by applying rule applications. It is allowed to use - * automatic runs, manual instantiations, ... + * A macro is then applied using {@link #applyTo(KeYMediator, PosInOccurrence)}. This may change the + * proof by applying rule applications. It is allowed to use automatic runs, manual instantiations, + * ... * - * A proof macro needs to extract all necessary information on the application - * from the mediator passed to the - * {@link #applyTo(KeYMediator, PosInOccurrence)} (or - * {@link #canApplyTo(KeYMediator, PosInOccurrence)}) method. You will be able - * to access any interesting data from that starting point, especially - * {@link KeYMediator#getInteractiveProver()}. + * A proof macro needs to extract all necessary information on the application from the mediator + * passed to the {@link #applyTo(KeYMediator, PosInOccurrence)} (or + * {@link #canApplyTo(KeYMediator, PosInOccurrence)}) method. You will be able to access any + * interesting data from that starting point, especially {@link KeYMediator#getInteractiveProver()}. * *

    Registration

    * - * When implementing a new proof macro, no existing code needs to be adapted. - * Please add the class name of your new implementation to the file + * When implementing a new proof macro, no existing code needs to be adapted. Please add the class + * name of your new implementation to the file * resources/META-INF/services/de.uka.ilkd.key.macros.ProofMacro. * * @see KeYMediator @@ -69,22 +68,20 @@ public interface ProofMacro { public String getName(); /** - * Gets a unique short name for this macro that can be used in proof - * scripts. + * Gets a unique short name for this macro that can be used in proof scripts. * - * If null is returned, the macro cannot be addressed from - * within scripts. + * If null is returned, the macro cannot be addressed from within scripts. * - * @return null if not supported, or a non-null - * constant string as the short name + * @return null if not supported, or a non-null constant string as the + * short name */ public String getScriptCommandName(); /** * Gets the category of this macro. * - * Used as name of the menu under which the macro is sorted. - * Return null if no submenu is to be created. + * Used as name of the menu under which the macro is sorted. Return null if no + * submenu is to be created. * * @return a constant string, or null */ @@ -100,31 +97,24 @@ public interface ProofMacro { public String getDescription(); /** - * Checks whether this {@link ProofMacro} has a parameter named - * paramName. For use in proof scripts. + * Checks whether this {@link ProofMacro} has a parameter named paramName. For use + * in proof scripts. * - * @param paramName - * The name to check. - * @return true iff this {@link ProofMacro} has a parameter named - * paramName. + * @param paramName The name to check. + * @return true iff this {@link ProofMacro} has a parameter named paramName. */ public boolean hasParameter(String paramName); /** - * Sets the parameter named paramName to the given String - * representation in paramValue. For use in proof scripts. + * Sets the parameter named paramName to the given String representation in + * paramValue. For use in proof scripts. * - * @param paramName - * The name of the parameter. - * @param paramValue - * The value of the parameter. - * @throws IllegalArgumentException - * if there is no parameter of that name or the value is - * incorrectly formatted (e.g., cannot be converted to a - * number). + * @param paramName The name of the parameter. + * @param paramValue The value of the parameter. + * @throws IllegalArgumentException if there is no parameter of that name or the value is + * incorrectly formatted (e.g., cannot be converted to a number). */ - public void setParameter(String paramName, String paramValue) - throws IllegalArgumentException; + public void setParameter(String paramName, String paramValue) throws IllegalArgumentException; /** * Resets the macro parameters to their defaults. @@ -134,121 +124,93 @@ public void setParameter(String paramName, String paramValue) /** * Can this macro be applied on the given goals? * - * This method should not make any changes but check if the macro can be - * applied or not on the given goals. + * This method should not make any changes but check if the macro can be applied or not on the + * given goals. * - * This method may be called from within the GUI thread and be compatible - * with that fact. + * This method may be called from within the GUI thread and be compatible with that fact. * - * @param proof - * the current {@link Proof} (not null) - * @param goals - * the goals (not null) - * @param posInOcc - * the position in occurrence (may be null) + * @param proof the current {@link Proof} (not null) + * @param goals the goals (not null) + * @param posInOcc the position in occurrence (may be null) * * @return true, if the macro is allowed to be applied */ - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc); + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc); /** * Can this macro be applied on the given node? * - * This method should not make any changes but check if the macro can be - * applied or not on the given node. + * This method should not make any changes but check if the macro can be applied or not on the + * given node. * - * This method may be called from within the GUI thread and be compatible - * with that fact. + * This method may be called from within the GUI thread and be compatible with that fact. * * This method must be implemented to have the same effect as calling - * {@link #canApplyTo(Proof, ImmutableList, PosInOccurrence)} with - * node.proof() as proof and all open goals below - * node. + * {@link #canApplyTo(Proof, ImmutableList, PosInOccurrence)} with node.proof() as + * proof and all open goals below node. * - * @param node - * the node (not null) - * @param posInOcc - * the position in occurrence (may be null) + * @param node the node (not null) + * @param posInOcc the position in occurrence (may be null) * * @return true, if the macro is allowed to be applied */ - public boolean canApplyTo(Node node, - PosInOccurrence posInOcc); + public boolean canApplyTo(Node node, PosInOccurrence posInOcc); /** * Apply this macro on the given goals. * * This method can change the proof by applying rules to it. * - * This method is usually called from a dedicated thread and not the GUI - * thread. The thread it runs on may be interrupted. In this case, the macro - * may report the interruption by an {@link InterruptedException}. + * This method is usually called from a dedicated thread and not the GUI thread. The thread it + * runs on may be interrupted. In this case, the macro may report the interruption by an + * {@link InterruptedException}. * - * A {@link ProverTaskListener} can be provided to which the progress will - * be reported. If no reports are desired, null cna be used for - * this parameter. If more than one listener is needed, consider combining - * them using a single listener object using the composite pattern. + * A {@link ProverTaskListener} can be provided to which the progress will be reported. If no + * reports are desired, null cna be used for this parameter. If more than one + * listener is needed, consider combining them using a single listener object using the + * composite pattern. * - * @param uic - * the {@link UserInterfaceControl} to use - * @param proof - * the current {@link Proof} (not null) - * @param goals - * the goals (not null) - * @param posInOcc - * the position in occurrence (may be null) - * @param listener - * the listener to use for progress reports (may be - * null) - * @throws InterruptedException - * if the application of the macro has been interrupted. + * @param uic the {@link UserInterfaceControl} to use + * @param proof the current {@link Proof} (not null) + * @param goals the goals (not null) + * @param posInOcc the position in occurrence (may be null) + * @param listener the listener to use for progress reports (may be null) + * @throws InterruptedException if the application of the macro has been interrupted. */ - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception; + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception; /** * Apply this macro on the given node. * * This method can change the proof by applying rules to it. * - * This method is usually called from a dedicated thread and not the GUI - * thread. The thread it runs on may be interrupted. In this case, the macro - * may report the interruption by an {@link InterruptedException}. + * This method is usually called from a dedicated thread and not the GUI thread. The thread it + * runs on may be interrupted. In this case, the macro may report the interruption by an + * {@link InterruptedException}. * - * A {@link ProverTaskListener} can be provided to which the progress will - * be reported. If no reports are desired, null can be used for - * this parameter. If more than one listener is needed, consider combining - * them using a single listener object using the composite pattern. + * A {@link ProverTaskListener} can be provided to which the progress will be reported. If no + * reports are desired, null can be used for this parameter. If more than one + * listener is needed, consider combining them using a single listener object using the + * composite pattern. * - * @param uic - * the {@link UserInterfaceControl} to use - * @param node - * the node (not null) - * @param posInOcc - * the position in occurrence (may be null) - * @param listener - * the listener to use for progress reports (may be - * null) - * @throws InterruptedException - * if the application of the macro has been interrupted. + * @param uic the {@link UserInterfaceControl} to use + * @param node the node (not null) + * @param posInOcc the position in occurrence (may be null) + * @param listener the listener to use for progress reports (may be null) + * @throws InterruptedException if the application of the macro has been interrupted. */ - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Node node, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception; + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Node node, + PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception; /** - * This observer acts as intermediate instance between the reports by the - * strategy and the UI reporting progress. + * This observer acts as intermediate instance between the reports by the strategy and the UI + * reporting progress. * - * The number of total steps is computed and all local reports are - * translated in termini of the total number of steps such that a continuous - * progress is reported. + * The number of total steps is computed and all local reports are translated in termini of the + * total number of steps such that a continuous progress is reported. * * fixes #1356 */ @@ -257,24 +219,22 @@ class ProgressBarListener extends ProofMacroListener { private final int numberSteps; private int completedGoals; - ProgressBarListener(String name, int numberGoals, - int numberSteps, ProverTaskListener l) { + ProgressBarListener(String name, int numberGoals, int numberSteps, ProverTaskListener l) { super(name, l); this.numberGoals = numberGoals; this.numberSteps = numberSteps; } - public ProgressBarListener(int size, int numberSteps, - ProverTaskListener listener) { + public ProgressBarListener(int size, int numberSteps, ProverTaskListener listener) { this("", size, numberSteps, listener); } @Override public void taskStarted(TaskStartedInfo info) { - //assert size == numberSteps; + // assert size == numberSteps; String suffix = getMessageSuffix(); - super.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, - info.getMessage() + suffix, numberGoals * numberSteps)); + super.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, info.getMessage() + suffix, + numberGoals * numberSteps)); super.taskProgress(completedGoals * numberSteps); } @@ -290,7 +250,7 @@ public void taskProgress(int position) { @Override public void taskFinished(TaskFinishedInfo info) { super.taskFinished(info); - completedGoals ++; + completedGoals++; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroFinishedInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroFinishedInfo.java index 701eadb9d17..a0020034fce 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroFinishedInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroFinishedInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.HashMap; @@ -13,11 +16,9 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskFinishedInfo; /** - * An information object with additional information about the - * finished proof macro. The source is always a proof macro and - * the result is always a list of goals. This information is - * created and passed on by every application of a proof macro - * as for the passed listener(s) to deal with it. + * An information object with additional information about the finished proof macro. The source is + * always a proof macro and the result is always a list of goals. This information is created and + * passed on by every application of a proof macro as for the passed listener(s) to deal with it. * * @author Michael Kirsten */ @@ -27,37 +28,33 @@ public class ProofMacroFinishedInfo extends DefaultTaskFinishedInfo { private final boolean cancelled; - ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, - Proof proof, long time, int appliedRules, - int closedGoals, boolean cancelled) { + ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, Proof proof, long time, + int appliedRules, int closedGoals, boolean cancelled) { super(macro, goals, proof, time, appliedRules, closedGoals); this.cancelled = cancelled; } - ProofMacroFinishedInfo(ProofMacro macro, Goal goal, Proof proof, - long time, int appliedRules, int closedGoals) { - this(macro, ImmutableSLList.nil().prepend(goal), proof, - time, appliedRules, closedGoals, false); + ProofMacroFinishedInfo(ProofMacro macro, Goal goal, Proof proof, long time, int appliedRules, + int closedGoals) { + this(macro, ImmutableSLList.nil().prepend(goal), proof, time, appliedRules, + closedGoals, false); } - ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, - Proof proof, Statistics statistics) { - this(macro, goals, proof, - statistics == null ? 0 : statistics.timeInMillis, - statistics == null ? 0 : statistics.totalRuleApps, - proof == null ? 0 : (proof.countBranches() - proof.openGoals().size()), - false); + ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, Proof proof, + Statistics statistics) { + this(macro, goals, proof, statistics == null ? 0 : statistics.timeInMillis, + statistics == null ? 0 : statistics.totalRuleApps, + proof == null ? 0 : (proof.countBranches() - proof.openGoals().size()), false); } - ProofMacroFinishedInfo(ProofMacro macro, Goal goal, Proof proof, - Statistics statistics) { - this(macro, goal, proof, - statistics == null ? 0 : statistics.timeInMillis, - statistics == null ? 0 : statistics.totalRuleApps, - proof == null ? 0 : (proof.countBranches() - proof.openGoals().size())); + ProofMacroFinishedInfo(ProofMacro macro, Goal goal, Proof proof, Statistics statistics) { + this(macro, goal, proof, statistics == null ? 0 : statistics.timeInMillis, + statistics == null ? 0 : statistics.totalRuleApps, + proof == null ? 0 : (proof.countBranches() - proof.openGoals().size())); } - ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, Proof proof, boolean cancelled) { + ProofMacroFinishedInfo(ProofMacro macro, ImmutableList goals, Proof proof, + boolean cancelled) { this(macro, goals, proof, proof == null ? null : proof.getStatistics()); } @@ -86,32 +83,25 @@ public ProofMacroFinishedInfo(ProofMacro macro, ProofMacroFinishedInfo info) { } ProofMacroFinishedInfo(ProofMacro macro, ProofMacroFinishedInfo info, - ImmutableList goals) { - this(macro, goals, info.getProof(), info.getTime(), - info.getAppliedRules(), info.getClosedGoals(), info.cancelled); + ImmutableList goals) { + this(macro, goals, info.getProof(), info.getTime(), info.getAppliedRules(), + info.getClosedGoals(), info.cancelled); } ProofMacroFinishedInfo(ProofMacroFinishedInfo info, ApplyStrategyInfo stratInfo) { - this(info.getMacro(), - info.getGoals(), - info.getProof(), - info.getTime() + stratInfo.getTime(), - info.getAppliedRules() + stratInfo.getAppliedRuleApps(), - info.getClosedGoals() + stratInfo.getClosedGoals(), - info.cancelled); - } - - ProofMacroFinishedInfo(ProofMacroFinishedInfo info, - ApplyStrategyInfo stratInfo, - ImmutableList goals) { - this(info.getMacro(), - goals, - stratInfo.getProof(), - info.getTime() + stratInfo.getTime(), - info.getAppliedRules() + stratInfo.getAppliedRuleApps(), - goals.size() <= info.getGoals().size() - ? (info.getGoals().size() - goals.size()) : 0, - false); + this(info.getMacro(), info.getGoals(), info.getProof(), + info.getTime() + stratInfo.getTime(), + info.getAppliedRules() + stratInfo.getAppliedRuleApps(), + info.getClosedGoals() + stratInfo.getClosedGoals(), info.cancelled); + } + + ProofMacroFinishedInfo(ProofMacroFinishedInfo info, ApplyStrategyInfo stratInfo, + ImmutableList goals) { + this(info.getMacro(), goals, stratInfo.getProof(), info.getTime() + stratInfo.getTime(), + info.getAppliedRules() + stratInfo.getAppliedRuleApps(), + goals.size() <= info.getGoals().size() ? (info.getGoals().size() - goals.size()) + : 0, + false); } public void addInfo(String key, Object value) { @@ -123,7 +113,7 @@ public Object getValueFor(String key) { } public ProofMacro getMacro() { - return (ProofMacro)getSource(); + return (ProofMacro) getSource(); } public boolean isCancelled() { @@ -136,7 +126,7 @@ public ImmutableList getGoals() { if (result == null) { return ImmutableSLList.nil(); } else { - return (ImmutableList)result; + return (ImmutableList) result; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroListener.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroListener.java index 817b841e8a0..28881614477 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroListener.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/ProofMacroListener.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.prover.ProverTaskListener; @@ -7,13 +10,12 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * Listener for the application of proof macros (which may be run in - * a separate worker thread). They work in a mutual way by also storing - * a reference to the superordinate listener on the level above. - * Additionally, an integer for remembering how many proof macros have - * been invoked by the according macro is stored. This integer is especially - * important in console mode in order to know when to finish batch mode. - * In GUI mode, the proof macro names are being displayed in the status bar. + * Listener for the application of proof macros (which may be run in a separate worker thread). They + * work in a mutual way by also storing a reference to the superordinate listener on the level + * above. Additionally, an integer for remembering how many proof macros have been invoked by the + * according macro is stored. This integer is especially important in console mode in order to know + * when to finish batch mode. In GUI mode, the proof macro names are being displayed in the status + * bar. * * @author Michael Kirsten */ @@ -33,10 +35,8 @@ public void taskStarted(TaskStartedInfo info) { numOfInvokedMacros++; if (superordinateListener != null) { superordinateListener.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, - macroName - + (macroName.length() == 0 - ? "" : " -- ") - + info.getMessage(), info.getSize())); + macroName + (macroName.length() == 0 ? "" : " -- ") + info.getMessage(), + info.getSize())); } } @@ -58,4 +58,4 @@ public void taskFinished(TaskFinishedInfo info) { public int getLevel() { return this.numOfInvokedMacros; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionMacro.java index fcecd46388d..b057b295b7b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionMacro.java @@ -1,10 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Set; /** - * The macro PropositionalExpansionMacro apply rules to decompose propositional - * toplevel formulas; but does not split the goal. + * The macro PropositionalExpansionMacro apply rules to decompose propositional toplevel formulas; + * but does not split the goal. * * The rules that are applied can be set in {@link #ADMITTED_RULES}. * @@ -19,8 +22,8 @@ public String getName() { @Override public String getDescription() { - return "Apply rules to decompose propositional toplevel formulas; " + - "does not split the goal."; + return "Apply rules to decompose propositional toplevel formulas; " + + "does not split the goal."; } @Override @@ -28,10 +31,8 @@ public String getScriptCommandName() { return "nosplit-prop"; } - private static final String[] ADMITTED_RULES = { - "andLeft", "orRight", "impRight", "notLeft", "notRight", "close", - "closeTrue", "closeFalse", "true_left", "false_right" - }; + private static final String[] ADMITTED_RULES = { "andLeft", "orRight", "impRight", "notLeft", + "notRight", "close", "closeTrue", "closeFalse", "true_left", "false_right" }; private static final Set ADMITTED_RULES_SET = asSet(ADMITTED_RULES); @@ -44,4 +45,4 @@ protected Set getAdmittedRuleNames() { protected boolean allowOSS() { return false; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionWithSimplificationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionWithSimplificationMacro.java index 95aaf748ae1..629e3d0d8ee 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionWithSimplificationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/PropositionalExpansionWithSimplificationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Set; @@ -6,7 +9,8 @@ * * @author christoph */ -public class PropositionalExpansionWithSimplificationMacro extends AbstractPropositionalExpansionMacro { +public class PropositionalExpansionWithSimplificationMacro + extends AbstractPropositionalExpansionMacro { @Override public String getName() { @@ -15,14 +19,12 @@ public String getName() { @Override public String getDescription() { - return "Apply rules to decompose propositional toplevel formulas; " + - "does not split the goal. Applies one step simplifications."; + return "Apply rules to decompose propositional toplevel formulas; " + + "does not split the goal. Applies one step simplifications."; } - private static final String[] ADMITTED_RULES = { - "andLeft", "orRight", "impRight", "notLeft", "notRight", "close", - "One Step Simplification" - }; + private static final String[] ADMITTED_RULES = { "andLeft", "orRight", "impRight", "notLeft", + "notRight", "close", "One Step Simplification" }; private static final Set ADMITTED_RULES_SET = asSet(ADMITTED_RULES); @@ -35,4 +37,4 @@ protected Set getAdmittedRuleNames() { protected boolean allowOSS() { return false; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SMTPreparationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SMTPreparationMacro.java index 2bbdb620ac5..bda1e0ac4a3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SMTPreparationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SMTPreparationMacro.java @@ -1,16 +1,20 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; /** - * A macro that performs all simplifications that are necessary in order to perform a translation - * of the sequent to SMT. These include symbolic execution and heap simplification. + * A macro that performs all simplifications that are necessary in order to perform a translation of + * the sequent to SMT. These include symbolic execution and heap simplification. + * * @author js */ public class SMTPreparationMacro extends SequentialProofMacro { /** * Creates the proof macro array. *

    - * Override this method by returning an array with the macros you want to - * call in the order of execution. + * Override this method by returning an array with the macros you want to call in the order of + * execution. * * @return a non-null array which should not be altered afterwards. */ @@ -37,8 +41,8 @@ public String getName() { /** * Gets the category of this macro. *

    - * Used as name of the menu under which the macro is sorted. - * Return null if no submenu is to be created. + * Used as name of the menu under which the macro is sorted. Return null if no + * submenu is to be created. * * @return a constant string, or null */ @@ -56,9 +60,7 @@ public String getCategory() { */ @Override public String getDescription() { - return "

    1. Finish symbolic execution" + - "
    2. Separate proof obligations" + - "
    3. Expand invariant definitions" + - "
    4. Simplify heap expressions
    "; + return "
    1. Finish symbolic execution" + "
    2. Separate proof obligations" + + "
    3. Expand invariant definitions" + "
    4. Simplify heap expressions
    "; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialOnLastGoalProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialOnLastGoalProofMacro.java index f4c3e352397..0b9c143c7ec 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialOnLastGoalProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialOnLastGoalProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -20,25 +23,22 @@ public abstract class SequentialOnLastGoalProofMacro extends SequentialProofMacr * {@inheritDoc} * *

    - * The macros are always started on the last active goal (in contrast - * to the same goal as it is done in the SequentialProofMacro). + * The macros are always started on the last active goal (in contrast to the same goal as it is + * done in the SequentialProofMacro). * - * @throws InterruptedException - * if one of the wrapped macros is interrupted. + * @throws InterruptedException if one of the wrapped macros is interrupted. */ @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - final ProverTaskListener listener) throws InterruptedException, Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, final ProverTaskListener listener) + throws InterruptedException, Exception { ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals); for (final ProofMacro macro : getProofMacros()) { // (here we do not reverse to original node) if (macro.canApplyTo(proof, goals, posInOcc)) { final ProverTaskListener pml = new ProofMacroListener(macro.getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - synchronized(macro) { + synchronized (macro) { // wait for macro to terminate info = macro.applyTo(uic, proof, goals, posInOcc, pml); } @@ -53,4 +53,4 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, } return info; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialProofMacro.java index 671779c21f0..d162087a78c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SequentialProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.ArrayList; @@ -18,13 +21,13 @@ import de.uka.ilkd.key.prover.impl.DefaultTaskStartedInfo; /** - * The abstract class SequentialProofMacro can be used to create compound macros - * which sequentially apply macros one after the other. This works only for macros - * which use {@link KeYMediator#startAutoMode()}. + * The abstract class SequentialProofMacro can be used to create compound macros which sequentially + * apply macros one after the other. This works only for macros which use + * {@link KeYMediator#startAutoMode()}. * *

    - * Since {@link ProofMacro}s run asynchronously, the start of the next macro - * must be performed in a listener call at the end of a autostart. + * Since {@link ProofMacro}s run asynchronously, the start of the next macro must be performed in a + * listener call at the end of a autostart. * * @author mattias ulbrich */ @@ -40,8 +43,8 @@ public abstract class SequentialProofMacro extends AbstractProofMacro { /** * Creates the proof macro array. * - * Override this method by returning an array with the macros you want to - * call in the order of execution. + * Override this method by returning an array with the macros you want to call in the order of + * execution. * * @return a non-null array which should not be altered afterwards. */ @@ -51,15 +54,13 @@ public abstract class SequentialProofMacro extends AbstractProofMacro { * {@inheritDoc} * *

    - * This compound macro is applicable if and only if the first macro is applicable. - * If there is no first macro, this is not applicable. + * This compound macro is applicable if and only if the first macro is applicable. If there is + * no first macro, this is not applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { List macros = getProofMacros(); - if(macros.isEmpty()) { + if (macros.isEmpty()) { return false; } else { return macros.get(0).canApplyTo(proof, goals, posInOcc); @@ -70,25 +71,21 @@ public boolean canApplyTo(Proof proof, * {@inheritDoc} * *

    - * This launches the first macro and registers a new - * {@link AutoModeListener} with the {@code mediator}. This listener - * unregisters itself after the last macro. + * This launches the first macro and registers a new {@link AutoModeListener} with the + * {@code mediator}. This listener unregisters itself after the last macro. * - * @throws InterruptedException - * if one of the wrapped macros is interrupted. + * @throws InterruptedException if one of the wrapped macros is interrupted. */ @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException, Exception { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException, Exception { final List initNodes = new ArrayList(goals.size()); for (Goal goal : goals) { initNodes.add(goal.node()); } - final ImmutableList gs = initNodes.isEmpty() ? - proof.openEnabledGoals() : proof.getSubtreeEnabledGoals(initNodes.get(0)); + final ImmutableList gs = initNodes.isEmpty() ? proof.openEnabledGoals() + : proof.getSubtreeEnabledGoals(initNodes.get(0)); ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, gs, proof, false); for (final ProofMacro macro : getProofMacros()) { // reverse to original nodes @@ -97,7 +94,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, final ProverTaskListener pml = new ProofMacroListener(macro.getName(), listener); pml.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, macro.getName(), 0)); - synchronized(macro) { + synchronized (macro) { // wait for macro to terminate info = macro.applyTo(uic, initNode, posInOcc, pml); } @@ -115,7 +112,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, * @return the proofMacros as an unmodifiable list. */ public List getProofMacros() { - if(proofMacros == null) { + if (proofMacros == null) { this.proofMacros = createProofMacroArray(); assert proofMacros != null; assert proofMacros.length > 0; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SkipMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SkipMacro.java index 34dd8bfbf4a..170db5f2e68 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/SkipMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/SkipMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -9,8 +12,8 @@ import de.uka.ilkd.key.prover.ProverTaskListener; /** - * This macro does nothing and is not applicable. It can be used to create - * compound macros, e.g. as an alternative macro for {@link DoWhileFinallyMacro}. + * This macro does nothing and is not applicable. It can be used to create compound macros, e.g. as + * an alternative macro for {@link DoWhileFinallyMacro}. * * @author christoph */ @@ -32,18 +35,14 @@ public String getDescription() { } @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { return false; } @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException { // do nothing return new ProofMacroFinishedInfo(this, goals); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/StrategyProofMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/StrategyProofMacro.java index 2f90e6a621d..596789f8744 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/StrategyProofMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/StrategyProofMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -15,16 +18,15 @@ import de.uka.ilkd.key.strategy.Strategy; /** - * The abstract class StrategyProofMacro can be used to define proof macros - * which use their own strategy. + * The abstract class StrategyProofMacro can be used to define proof macros which use their own + * strategy. * * In order to implement a {@link StrategyProofMacro}, override * {@link #createStrategy(KeYMediator, PosInOccurrence)}. * - * This class is aware of Position in occurrences and can also be applied to - * inner nodes. Both {@link AutomatedRuleApplicationManager} and - * {@link Strategy} are changed for the course of the macro but are restored - * afterwards using a {@link ProverTaskListener}. + * This class is aware of Position in occurrences and can also be applied to inner nodes. Both + * {@link AutomatedRuleApplicationManager} and {@link Strategy} are changed for the course of the + * macro but are restored afterwards using a {@link ProverTaskListener}. * * @see ProverTaskListener * @see Strategy @@ -42,54 +44,50 @@ public abstract class StrategyProofMacro extends AbstractProofMacro { * */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { return goals != null && !goals.isEmpty(); } /** - * Subclasses can use this method to do some postprocessing on the - * proof-object after the strategy has finished. - * @param proof The proof object. + * Subclasses can use this method to do some postprocessing on the proof-object after the + * strategy has finished. + * + * @param proof The proof object. */ protected void doPostProcessing(Proof proof) {} /* - * Set a new rule app manager similar to the focussed mode. - * Set a new strategy which only allows for the named admitted rules. - * Then run automation mode and in the end reset the managers. - * and the strategy. + * Set a new rule app manager similar to the focussed mode. Set a new strategy which only allows + * for the named admitted rules. Then run automation mode and in the end reset the managers. and + * the strategy. * * If the automation is interrupted, report the interruption as an exception. */ @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException { if (goals == null || goals.isEmpty()) { // should not happen, because in this case canApplyTo returns // false return null; } - final GoalChooser goalChooser = proof.getInitConfig().getProfile().getSelectedGoalChooserBuilder().create(); + final GoalChooser goalChooser = + proof.getInitConfig().getProfile().getSelectedGoalChooserBuilder().create(); final ProverCore applyStrategy = new ApplyStrategy(goalChooser); - final ImmutableList ignoredOpenGoals = - setDifference(proof.openGoals(), goals); + final ImmutableList ignoredOpenGoals = setDifference(proof.openGoals(), goals); // // The observer to handle the progress bar - final ProofMacroListener pml = new ProgressBarListener(goals.size(), - getMaxSteps(proof), listener); + final ProofMacroListener pml = + new ProgressBarListener(goals.size(), getMaxSteps(proof), listener); applyStrategy.addProverTaskObserver(pml); // add a focus manager if there is a focus - if(posInOcc != null && goals != null) { + if (posInOcc != null && goals != null) { AutomatedRuleApplicationManager realManager = null; FocussedRuleApplicationManager manager = null; - for (Goal goal: goals) { + for (Goal goal : goals) { realManager = goal.getRuleAppManager(); realManager.clearCache(); manager = new FocussedRuleApplicationManager(realManager, goal, posInOcc); @@ -101,14 +99,15 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Strategy oldStrategy = proof.getActiveStrategy(); proof.setActiveStrategy(createStrategy(proof, posInOcc)); - ProofMacroFinishedInfo info = - new ProofMacroFinishedInfo(this, goals, proof, false); + ProofMacroFinishedInfo info = new ProofMacroFinishedInfo(this, goals, proof, false); try { // find the relevant goals // and start applyStrategy.start(proof, goals); - synchronized(applyStrategy) { // wait for applyStrategy to finish its last rule application - if(applyStrategy.hasBeenInterrupted()) { // reraise interrupted exception if necessary + synchronized (applyStrategy) { // wait for applyStrategy to finish its last rule + // application + if (applyStrategy.hasBeenInterrupted()) { // reraise interrupted exception if + // necessary throw new InterruptedException(); } } @@ -118,7 +117,7 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, for (final Goal openGoal : proof.openGoals()) { AutomatedRuleApplicationManager manager = openGoal.getRuleAppManager(); // touch the manager only if necessary - if(manager instanceof FocussedRuleApplicationManager) { + if (manager instanceof FocussedRuleApplicationManager) { manager = ((FocussedRuleApplicationManager) manager).rootManager; manager.clearCache(); openGoal.setRuleAppManager(manager); @@ -135,11 +134,11 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, } private static ImmutableList setDifference(ImmutableList goals1, - ImmutableList goals2) { + ImmutableList goals2) { ImmutableList difference = goals1; for (Goal goal : goals2) { difference = difference.removeFirst(goal); } return difference; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/TranscendentalFloatSMTMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/TranscendentalFloatSMTMacro.java index 8abe7d9cdbd..2e4734ec675 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/TranscendentalFloatSMTMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/TranscendentalFloatSMTMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import de.uka.ilkd.key.control.UserInterfaceControl; @@ -12,8 +15,7 @@ import java.util.Set; /** - * This class captures a proof macro which is meant to fully automise KeY proof - * workflow. + * This class captures a proof macro which is meant to fully automise KeY proof workflow. * * It is experimental. * @@ -53,10 +55,7 @@ public String getDescription() { @Override protected ProofMacro[] createProofMacroArray() { - return new ProofMacro[] { - new FullAutoMacro(), - new TranscendentalMacro() - }; + return new ProofMacro[] { new FullAutoMacro(), new TranscendentalMacro() }; } private static class FullAutoMacro extends StrategyProofMacro { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/TryCloseMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/TryCloseMacro.java index 13b764b1286..ff0b2fc2d01 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/TryCloseMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/TryCloseMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; @@ -15,14 +18,12 @@ import de.uka.ilkd.key.prover.impl.ApplyStrategyInfo; /** - * The Class TryCloseMacro tries to close goals. Goals are either closed or left - * untouched. + * The Class TryCloseMacro tries to close goals. Goals are either closed or left untouched. * - * This uses the code provided by Michael Kirsten in - * {@link InteractiveProver$AutoWorker}. + * This uses the code provided by Michael Kirsten in {@link InteractiveProver$AutoWorker}. * - * Unlike many macros, this macros has got a parameter ({@link #numberSteps}), such - * that several instances of the class may exist with different semantics. + * Unlike many macros, this macros has got a parameter ({@link #numberSteps}), such that several + * instances of the class may exist with different semantics. * * The number of autosteps may be temporarily altered for this macro. * @@ -34,21 +35,24 @@ private static class TryCloseProgressBarListener extends ProgressBarListener { private int notClosedGoals = 0; - private TryCloseProgressBarListener(String name, int numberGoals, int numberSteps, ProverTaskListener l) { + private TryCloseProgressBarListener(String name, int numberGoals, int numberSteps, + ProverTaskListener l) { super(name, numberGoals, numberSteps, l); } - public TryCloseProgressBarListener(int numberGoals, int numberSteps, ProverTaskListener listener) { + public TryCloseProgressBarListener(int numberGoals, int numberSteps, + ProverTaskListener listener) { super(numberGoals, numberSteps, listener); } @Override protected String getMessageSuffix() { - if(notClosedGoals == 0) { - return super.getMessageSuffix(); + if (notClosedGoals == 0) { + return super.getMessageSuffix(); } else { - return super.getMessageSuffix() + ", " + notClosedGoals + " goal(s) remain(s) open."; - } + return super.getMessageSuffix() + ", " + notClosedGoals + + " goal(s) remain(s) open."; + } } private void incrementNotClosedGoals() { @@ -58,16 +62,14 @@ private void incrementNotClosedGoals() { } /** - * The max number of steps to be applied. - * A value of -1 means no changes. + * The max number of steps to be applied. A value of -1 means no changes. * * This value may differ between instances of this class; */ private final int numberSteps; /** - * Instantiates a new try close macro. - * No changes to the max number of steps. + * Instantiates a new try close macro. No changes to the max number of steps. */ public TryCloseMacro() { this(-1); @@ -76,14 +78,15 @@ public TryCloseMacro() { /** * Instantiates a new try close macro. * - * @param numberSteps - * the max number of steps. -1 means no change. + * @param numberSteps the max number of steps. -1 means no change. */ public TryCloseMacro(int numberSteps) { this.numberSteps = numberSteps; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getName() */ @Override @@ -91,7 +94,9 @@ public String getName() { return "Close Provable Goals Below"; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.macros.AbstractProofMacro#getScriptCommandName() */ @Override @@ -101,6 +106,7 @@ public String getScriptCommandName() { /* * (non-Javadoc) + * * @see de.uka.ilkd.key.macros.ProofMacro#getCategory() */ @Override @@ -108,22 +114,22 @@ public String getCategory() { return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see de.uka.ilkd.key.gui.macros.ProofMacro#getDescription() */ @Override public String getDescription() { - return "Closes closable goals, leave rest untouched (see settings AutoPrune). " + - "Applies only to goals beneath the selected node."; + return "Closes closable goals, leave rest untouched (see settings AutoPrune). " + + "Applies only to goals beneath the selected node."; } /* * This macro is always applicable. */ @Override - public boolean canApplyTo(Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc) { + public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { return goals != null && !goals.isEmpty(); } @@ -131,11 +137,9 @@ public boolean canApplyTo(Proof proof, * Run the automation on the goal. Retreat if not successful. */ @Override - public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, - Proof proof, - ImmutableList goals, - PosInOccurrence posInOcc, - ProverTaskListener listener) throws InterruptedException { + public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, Proof proof, + ImmutableList goals, PosInOccurrence posInOcc, ProverTaskListener listener) + throws InterruptedException { if (goals == null || goals.isEmpty()) { // should not happen, because in this case canApplyTo returns // false @@ -144,16 +148,15 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, // // create the rule application engine - final ProverCore applyStrategy = - new ApplyStrategy(proof.getServices().getProfile().getSelectedGoalChooserBuilder().create()); + final ProverCore applyStrategy = new ApplyStrategy( + proof.getServices().getProfile().getSelectedGoalChooserBuilder().create()); // assert: all goals have the same proof // // The observer to handle the progress bar - final TryCloseProgressBarListener pml = new TryCloseProgressBarListener(goals.size(), - numberSteps, listener); - final ImmutableList ignoredOpenGoals = - setDifference(proof.openGoals(), goals); + final TryCloseProgressBarListener pml = + new TryCloseProgressBarListener(goals.size(), numberSteps, listener); + final ImmutableList ignoredOpenGoals = setDifference(proof.openGoals(), goals); applyStrategy.addProverTaskObserver(pml); // @@ -166,32 +169,34 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, try { for (final Goal goal : goals) { Node node = goal.node(); - int maxSteps = numberSteps > 0 ? numberSteps : proof.getSettings().getStrategySettings().getMaxSteps(); - final ApplyStrategyInfo result = - applyStrategy.start(proof, ImmutableSLList.nil().prepend(goal), - maxSteps, -1, false); - //final Goal closedGoal; + int maxSteps = numberSteps > 0 ? numberSteps + : proof.getSettings().getStrategySettings().getMaxSteps(); + final ApplyStrategyInfo result = applyStrategy.start(proof, + ImmutableSLList.nil().prepend(goal), maxSteps, -1, false); + // final Goal closedGoal; // retreat if not closed - if(!node.isClosed()) { + if (!node.isClosed()) { proof.pruneProof(node); pml.incrementNotClosedGoals(); - //closedGoal = null; + // closedGoal = null; } else { - //closedGoal = goal; + // closedGoal = goal; } - synchronized(applyStrategy) { // wait for applyStrategy to finish its last rule application + synchronized (applyStrategy) { // wait for applyStrategy to finish its last rule + // application // update statistics - /*if (closedGoal == null) { TODO: This incremental approach would be nicer, but - * therefore the comparison of Goal needs to be fixed. - info = new ProofMacroFinishedInfo(info, result); - } else { - info = new ProofMacroFinishedInfo(info, result, - info.getGoals().removeFirst(closedGoal)); - }*/ + /* + * if (closedGoal == null) { TODO: This incremental approach would be nicer, but + * therefore the comparison of Goal needs to be fixed. info = new + * ProofMacroFinishedInfo(info, result); } else { info = new + * ProofMacroFinishedInfo(info, result, + * info.getGoals().removeFirst(closedGoal)); } + */ info = new ProofMacroFinishedInfo(info, result); - if(applyStrategy.hasBeenInterrupted()) { // only now reraise the interruption exception + if (applyStrategy.hasBeenInterrupted()) { // only now reraise the interruption + // exception throw new InterruptedException(); } } @@ -206,11 +211,11 @@ public ProofMacroFinishedInfo applyTo(UserInterfaceControl uic, } private static ImmutableList setDifference(ImmutableList goals1, - ImmutableList goals2) { + ImmutableList goals2) { ImmutableList difference = goals1; for (Goal goal : goals2) { difference = difference.removeFirst(goal); } return difference; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/UpdateSimplificationMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/UpdateSimplificationMacro.java index bd24eb41207..dfa4bbf6ac4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/UpdateSimplificationMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/UpdateSimplificationMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import java.util.Collections; @@ -6,66 +9,53 @@ /** * This macro applies only update simplification rules. + * * @author Richard Bubel */ -public class UpdateSimplificationMacro extends - AbstractPropositionalExpansionMacro { - - public static final String UPDATE_SIMPLIFICATION_ONLY = "Update Simplification Only"; - - private static final String[] ADMITTED_RULE_NAMES = { - "simplifyUpdate1", - "simplifyUpdate2", - "simplifyUpdate3", - "sequentialToParallel1", - "sequentialToParallel2", - "sequentialToParallel3", - "applyOnRigidTerm", - "applyOnRigidFormula", - "applyOnElementary", - "applyOnParallel", - "applyOnSkip", - "applyOnPV", - "parallelWithSkip1", - "parallelWithSkip2", - "applySkip1", - "applySkip2", - }; - - private static final Set ADMITTED_RULE_NAMES_AS_SET = new HashSet(); - static { - Collections.addAll(ADMITTED_RULE_NAMES_AS_SET, ADMITTED_RULE_NAMES); - } - - - @Override - public String getName() { - return UPDATE_SIMPLIFICATION_ONLY; - } - - @Override - public String getCategory() { - return "Simplification"; - } - - @Override - public String getScriptCommandName() { - return "simp-upd"; - } - - @Override - public String getDescription() { - return "Applies only update simplification rules"; - } - - @Override - protected Set getAdmittedRuleNames() { - return ADMITTED_RULE_NAMES_AS_SET; - } - - @Override - protected boolean allowOSS() { - return true; - } +public class UpdateSimplificationMacro extends AbstractPropositionalExpansionMacro { + + public static final String UPDATE_SIMPLIFICATION_ONLY = "Update Simplification Only"; + + private static final String[] ADMITTED_RULE_NAMES = { "simplifyUpdate1", "simplifyUpdate2", + "simplifyUpdate3", "sequentialToParallel1", "sequentialToParallel2", + "sequentialToParallel3", "applyOnRigidTerm", "applyOnRigidFormula", "applyOnElementary", + "applyOnParallel", "applyOnSkip", "applyOnPV", "parallelWithSkip1", "parallelWithSkip2", + "applySkip1", "applySkip2", }; + + private static final Set ADMITTED_RULE_NAMES_AS_SET = new HashSet(); + static { + Collections.addAll(ADMITTED_RULE_NAMES_AS_SET, ADMITTED_RULE_NAMES); + } + + + @Override + public String getName() { + return UPDATE_SIMPLIFICATION_ONLY; + } + + @Override + public String getCategory() { + return "Simplification"; + } + + @Override + public String getScriptCommandName() { + return "simp-upd"; + } + + @Override + public String getDescription() { + return "Applies only update simplification rules"; + } + + @Override + protected Set getAdmittedRuleNames() { + return ADMITTED_RULE_NAMES_AS_SET; + } + + @Override + protected boolean allowOSS() { + return true; + } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/WellDefinednessMacro.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/WellDefinednessMacro.java index d5fd9e7f315..202b2d22d02 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/WellDefinednessMacro.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/WellDefinednessMacro.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros; import org.key_project.util.collection.ImmutableList; @@ -19,11 +22,11 @@ import de.uka.ilkd.key.strategy.TopRuleAppCost; /** - * This macro resolves the well-definedness transformer, i.e. it applies exactly - * all applicable rules to resolve the operators WD and wd (which are formula/term - * transformers). These rules all have the prefix defined in {@link #WD_PREFIX}. - * The macro is only applicable for proof obligations created in {@link #WellDefinednessPO} - * and the Well-Definedness branches in {@link #WhileInvariantRule} and {@link #BlockContractRule}. + * This macro resolves the well-definedness transformer, i.e. it applies exactly all applicable + * rules to resolve the operators WD and wd (which are formula/term transformers). These rules all + * have the prefix defined in {@link #WD_PREFIX}. The macro is only applicable for proof obligations + * created in {@link #WellDefinednessPO} and the Well-Definedness branches in + * {@link #WhileInvariantRule} and {@link #BlockContractRule}. * * @author Michael Kirsten */ @@ -48,16 +51,13 @@ public String getDescription() { } @Override - protected Strategy createStrategy(Proof proof, - PosInOccurrence posInOcc) { + protected Strategy createStrategy(Proof proof, PosInOccurrence posInOcc) { return new WellDefinednessStrategy(); } @Override public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrence posInOcc) { - if (proof == null - || proof.isDisposed() - || !WellDefinednessCheck.isOn()) { + if (proof == null || proof.isDisposed() || !WellDefinednessCheck.isOn()) { return false; } final ContractPO po = proof.getServices().getSpecificationRepository().getPOForProof(proof); @@ -67,30 +67,30 @@ public boolean canApplyTo(Proof proof, ImmutableList goals, PosInOccurrenc if (!(po instanceof FunctionalOperationContractPO)) { return false; } - for (Goal goal: goals) { + for (Goal goal : goals) { Node n = goal.node(); while (n != null) { - // Applicable in a well-definedness branch (e.g. of a loop statement or a block contract) + // Applicable in a well-definedness branch (e.g. of a loop statement or a block + // contract) if (n.getNodeInfo().getBranchLabel() != null && n.getNodeInfo().getBranchLabel().equals(WD_BRANCH)) { return true; } n = n.parent(); } - } + } return false; } /** - * This strategy accepts all rule apps for which the rule name is a - * Well-Definedness rule and rejects everything else. + * This strategy accepts all rule apps for which the rule name is a Well-Definedness rule and + * rejects everything else. */ private static class WellDefinednessStrategy implements Strategy { private static final Name NAME = new Name(WellDefinednessStrategy.class.getSimpleName()); - public WellDefinednessStrategy() { - } + public WellDefinednessStrategy() {} @Override public Name name() { @@ -100,7 +100,7 @@ public Name name() { @Override public RuleAppCost computeCost(RuleApp ruleApp, PosInOccurrence pio, Goal goal) { String name = ruleApp.rule().name().toString(); - if(name.startsWith(WD_PREFIX)) { + if (name.startsWith(WD_PREFIX)) { return NumberRuleAppCost.getZeroCost(); } else { return TopRuleAppCost.INSTANCE; @@ -114,12 +114,11 @@ public boolean isApprovedApp(RuleApp app, PosInOccurrence pio, Goal goal) { @Override public void instantiateApp(RuleApp app, PosInOccurrence pio, Goal goal, - RuleAppCostCollector collector) { - } + RuleAppCostCollector collector) {} @Override public boolean isStopAtFirstNonCloseableGoal() { - return false; + return false; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AbstractCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AbstractCommand.java index 02e8f4d76a2..f0d84135b7d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AbstractCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AbstractCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; @@ -13,7 +16,9 @@ import java.util.logging.Logger; /** - *

    Inheritance:

    + *

    + * Inheritance: + *

    * * @param * @author Alexander Weigl @@ -66,7 +71,7 @@ public void execute(AbstractUserInterfaceControl uiControl, T args, EngineState try { execute(args); } finally { - //preventing memory leak + // preventing memory leak proof = null; service = null; state = null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ActivateCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ActivateCommand.java index 1672339e001..14c06bc7e27 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ActivateCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ActivateCommand.java @@ -1,13 +1,15 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; import de.uka.ilkd.key.proof.Goal; /** - * Command for re-activating the first open (not necessarily enabled) - * {@link Goal} after a "leave" command. Can be useful for complicated proofs - * where "tryclose" should not apply on certain branches temporarily, but where - * one still wants to finish the proof. + * Command for re-activating the first open (not necessarily enabled) {@link Goal} after a "leave" + * command. Can be useful for complicated proofs where "tryclose" should not apply on certain + * branches temporarily, but where one still wants to finish the proof. * * @author Dominic Steinhoefel */ @@ -18,8 +20,8 @@ public String getName() { } @Override - public void execute(AbstractUserInterfaceControl uiControl, Void args, - EngineState state) throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Void args, EngineState state) + throws ScriptException, InterruptedException { Goal goal = state.getFirstOpenGoal(false); goal.setEnabled(true); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AllCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AllCommand.java index 055231570db..87f5101f59e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AllCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AllCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.proof.Goal; @@ -26,7 +29,7 @@ public String getName() { @Override protected void execute(Map args) throws ScriptException, InterruptedException { String wrappedCmdname = args.get("#2"); - if(wrappedCmdname == null) { + if (wrappedCmdname == null) { throw new ScriptException("Missing command to apply onAll to"); } @@ -48,9 +51,9 @@ protected void execute(Map args) throws ScriptException, Interru private HashMap rearrangeArgs(Map args) { HashMap newArgs = new HashMap<>(); for (Entry en : args.entrySet()) { - if(en.getKey().matches("#[0-9]+")) { + if (en.getKey().matches("#[0-9]+")) { int no = Integer.parseInt(en.getKey().substring(1)); - if(no != 1) { + if (no != 1) { newArgs.put("#" + (no - 1), en.getValue()); } } else { @@ -60,14 +63,15 @@ private HashMap rearrangeArgs(Map args) { return newArgs; } - private
    void executeWrappedCommand(ProofScriptCommand command, HashMap newArgs) throws Exception { + private void executeWrappedCommand(ProofScriptCommand command, + HashMap newArgs) throws Exception { A params = command.evaluateArguments(state, newArgs); // Node selectedNode = state.getSelectedNode(); for (Goal g : proof.openGoals()) { // if (isBelow(g, selectedNode)) { - state.setGoal(g); - command.execute(uiControl, params, state); + state.setGoal(g); + command.execute(uiControl, params, state); // } } // state.setGoal(selectedNode); @@ -79,7 +83,7 @@ private boolean isBelow(Goal g, Node above) { } Node node = g.node(); - while(node != null) { + while (node != null) { if (node == above) { return true; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssertCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssertCommand.java index 87c105cff1d..eb45ca29bde 100755 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssertCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssertCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -19,26 +22,21 @@ public AssertCommand() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(Parameters args) - throws ScriptException, InterruptedException { + public void execute(Parameters args) throws ScriptException, InterruptedException { if (args.goals == null) { throw new ScriptException("No parameter specified!"); } if (state.getProof().openEnabledGoals().size() != args.goals.intValue()) { - throw new ScriptException( - "Assertion failed: number of open goals is " + - state.getProof().openGoals().size() + - ", but should be " + - args.goals.intValue() - ); + throw new ScriptException("Assertion failed: number of open goals is " + + state.getProof().openGoals().size() + ", but should be " + + args.goals.intValue()); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssumeCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssumeCommand.java index f5c853c865c..e03a45bec3e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssumeCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AssumeCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -11,11 +14,9 @@ import de.uka.ilkd.key.rule.TacletApp; /** - * The assume command takes one argument: * a formula to which the command is - * applied + * The assume command takes one argument: * a formula to which the command is applied */ -public class AssumeCommand - extends AbstractCommand { +public class AssumeCommand extends AbstractCommand { private static final Name TACLET_NAME = new Name("UNSOUND_ASSUME"); public AssumeCommand() { @@ -23,10 +24,9 @@ public AssumeCommand() { } @Override - public FormulaParameter evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new FormulaParameter(), - arguments); + public FormulaParameter evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new FormulaParameter(), arguments); } @Override @@ -35,15 +35,14 @@ public String getName() { } @Override - public void execute(FormulaParameter parameter) - throws ScriptException, InterruptedException { + public void execute(FormulaParameter parameter) throws ScriptException, InterruptedException { Taclet cut = state.getProof().getEnv().getInitConfigForEnvironment() .lookupActiveTaclet(TACLET_NAME); TacletApp app = NoPosTacletApp.createNoPosTacletApp(cut); SchemaVariable sv = app.uninstantiatedVars().iterator().next(); - app = app.addCheckedInstantiation(sv, parameter.formula, - state.getProof().getServices(), true); + app = app.addCheckedInstantiation(sv, parameter.formula, state.getProof().getServices(), + true); state.getFirstOpenAutomaticGoal().apply(app); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AutoCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AutoCommand.java index 2d0ef13b5bb..b870daf9f8c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AutoCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AutoCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -37,8 +40,7 @@ public String getName() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) { + public Parameters evaluateArguments(EngineState state, Map arguments) { Parameters args = new Parameters(); try { ValueInjector.getInstance().inject(this, args, arguments); @@ -49,15 +51,14 @@ public Parameters evaluateArguments(EngineState state, } @Override - public void execute(AbstractUserInterfaceControl uiControl, - Parameters arguments, EngineState state) - throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Parameters arguments, + EngineState state) throws ScriptException, InterruptedException { final Services services = state.getProof().getServices(); final Profile profile = services.getProfile(); // create the rule application engine - final ProverCore applyStrategy = new ApplyStrategy( - profile.getSelectedGoalChooserBuilder().create()); + final ProverCore applyStrategy = + new ApplyStrategy(profile.getSelectedGoalChooserBuilder().create()); // find the targets final ImmutableList goals; @@ -65,16 +66,13 @@ public void execute(AbstractUserInterfaceControl uiControl, goals = state.getProof().openGoals(); } else { final Goal goal = state.getFirstOpenAutomaticGoal(); - goals = ImmutableSLList. nil().prepend(goal); + goals = ImmutableSLList.nil().prepend(goal); - final Optional matchesRegEx = Optional - .ofNullable(arguments.matches); - final Optional breakpoint = Optional - .ofNullable(arguments.breakpoint); + final Optional matchesRegEx = Optional.ofNullable(arguments.matches); + final Optional breakpoint = Optional.ofNullable(arguments.breakpoint); if (matchesRegEx.isPresent() || breakpoint.isPresent()) { setupFocussedBreakpointStrategy( // - matchesRegEx, breakpoint, goal, applyStrategy, - services); + matchesRegEx, breakpoint, goal, applyStrategy, services); } } @@ -89,8 +87,7 @@ public void execute(AbstractUserInterfaceControl uiControl, // start actual autoprove try { for (Goal goal : goals) { - applyStrategy.start(state.getProof(), - ImmutableSLList. nil().prepend(goal)); + applyStrategy.start(state.getProof(), ImmutableSLList.nil().prepend(goal)); // only now reraise the interruption exception if (applyStrategy.hasBeenInterrupted()) { @@ -104,32 +101,23 @@ public void execute(AbstractUserInterfaceControl uiControl, } /** - * Sets up a focused automatic strategy. Focus is on the sequent formula - * matching the matchesRegEx (may not be null). + * Sets up a focused automatic strategy. Focus is on the sequent formula matching the + * matchesRegEx (may not be null). * - * @param maybeMatchesRegEx - * The RegEx which should match on the sequent formula to focus. - * @param breakpointArg - * An optional breakpoint argument. - * @param goal - * The {@link Goal} to apply the strategy on, needed for the rule - * application manager. - * @param proverCore - * The {@link ProverCore}, needed for resetting the strategy - * afterward. - * @param services - * The {@link Services} object. + * @param maybeMatchesRegEx The RegEx which should match on the sequent formula to focus. + * @param breakpointArg An optional breakpoint argument. + * @param goal The {@link Goal} to apply the strategy on, needed for the rule application + * manager. + * @param proverCore The {@link ProverCore}, needed for resetting the strategy afterward. + * @param services The {@link Services} object. * @throws ScriptException */ - private void setupFocussedBreakpointStrategy( - final Optional maybeMatchesRegEx, - final Optional breakpointArg, final Goal goal, - final ProverCore proverCore, final Services services) - throws ScriptException { + private void setupFocussedBreakpointStrategy(final Optional maybeMatchesRegEx, + final Optional breakpointArg, final Goal goal, final ProverCore proverCore, + final Services services) throws ScriptException { final Optional focus = maybeMatchesRegEx.isPresent() - ? Optional.of( - MacroCommand.extractMatchingPio(goal.node().sequent(), - maybeMatchesRegEx.get(), services)) + ? Optional.of(MacroCommand.extractMatchingPio(goal.node().sequent(), + maybeMatchesRegEx.get(), services)) : Optional.empty(); final AutomatedRuleApplicationManager realManager = // @@ -137,13 +125,12 @@ private void setupFocussedBreakpointStrategy( goal.setRuleAppManager(null); final AutomatedRuleApplicationManager focusManager = // - new FocussedBreakpointRuleApplicationManager(realManager, goal, - focus, breakpointArg); + new FocussedBreakpointRuleApplicationManager(realManager, goal, focus, + breakpointArg); goal.setRuleAppManager(focusManager); proverCore.addProverTaskObserver( - new AbstractProofControl.FocussedAutoModeTaskListener( - services.getProof())); + new AbstractProofControl.FocussedAutoModeTaskListener(services.getProof())); } public static class Parameters { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AxiomCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AxiomCommand.java index 19f56ce0bfd..a21ebd406fa 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AxiomCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/AxiomCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -11,13 +14,11 @@ import de.uka.ilkd.key.rule.TacletApp; /** - * The axiom command takes one argument: a formula to which the command is - * applied. + * The axiom command takes one argument: a formula to which the command is applied. * * @see AssumeCommand The assume command is a synonym for the axiom command. */ -public class AxiomCommand - extends AbstractCommand { +public class AxiomCommand extends AbstractCommand { private static final Name TACLET_NAME = new Name("introduceAxiom"); public AxiomCommand() { @@ -25,10 +26,9 @@ public AxiomCommand() { } @Override - public FormulaParameter evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new FormulaParameter(), - arguments); + public FormulaParameter evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new FormulaParameter(), arguments); } @Override @@ -37,15 +37,14 @@ public String getName() { } @Override - public void execute(FormulaParameter parameter) - throws ScriptException, InterruptedException { + public void execute(FormulaParameter parameter) throws ScriptException, InterruptedException { Taclet cut = state.getProof().getEnv().getInitConfigForEnvironment() .lookupActiveTaclet(TACLET_NAME); TacletApp app = NoPosTacletApp.createNoPosTacletApp(cut); SchemaVariable sv = app.uninstantiatedVars().iterator().next(); - app = app.addCheckedInstantiation(sv, parameter.formula, - state.getProof().getServices(), true); + app = app.addCheckedInstantiation(sv, parameter.formula, state.getProof().getServices(), + true); state.getFirstOpenAutomaticGoal().apply(app); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/CutCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/CutCommand.java index 57c9d5eb6ba..eb2e719bf8c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/CutCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/CutCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -12,9 +15,8 @@ import de.uka.ilkd.key.rule.TacletApp; /** - * The command object CutCommand has as scriptcommand name "cut" - * As parameters: - * a formula with the id "#2" + * The command object CutCommand has as scriptcommand name "cut" As parameters: a formula with the + * id "#2" */ public class CutCommand extends AbstractCommand { private static final Name CUT_TACLET_NAME = new Name("cut"); @@ -23,12 +25,14 @@ public CutCommand() { super(Parameters.class); } - @Override public String getName() { + @Override + public String getName() { return "cut"; } - @Override public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { + @Override + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { return state.getValueInjector().inject(this, new Parameters(), arguments); } @@ -40,16 +44,15 @@ public CutCommand() { * @throws ScriptException * @throws InterruptedException */ - @Override public void execute(AbstractUserInterfaceControl uiControl, - Parameters args, EngineState state) + @Override + public void execute(AbstractUserInterfaceControl uiControl, Parameters args, EngineState state) throws ScriptException, InterruptedException { Taclet cut = state.getProof().getEnv().getInitConfigForEnvironment() .lookupActiveTaclet(CUT_TACLET_NAME); TacletApp app = NoPosTacletApp.createNoPosTacletApp(cut); SchemaVariable sv = app.uninstantiatedVars().iterator().next(); - app = app.addCheckedInstantiation(sv, args.formula, - state.getProof().getServices(), true); + app = app.addCheckedInstantiation(sv, args.formula, state.getProof().getServices(), true); state.getFirstOpenAutomaticGoal().apply(app); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EchoCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EchoCommand.java index cbc807b180a..89a92e8c046 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EchoCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EchoCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -7,8 +10,7 @@ import de.uka.ilkd.key.macros.scripts.meta.Option; /** - * A simple "echo" command for giving feedback to human observers during lengthy - * executions. + * A simple "echo" command for giving feedback to human observers during lengthy executions. */ public class EchoCommand extends AbstractCommand { public EchoCommand() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EngineState.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EngineState.java index 801c0a13c3b..42a5e23c8c2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EngineState.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/EngineState.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.io.File; @@ -28,7 +31,7 @@ */ public class EngineState { private final static DefaultTermParser PARSER = new DefaultTermParser(); - //private final Map arbitraryVariables = new HashMap<>(); + // private final Map arbitraryVariables = new HashMap<>(); private final Proof proof; private AbbrevMap abbrevMap = new AbbrevMap(); /** @@ -41,15 +44,14 @@ public class EngineState { private Node lastSetGoalNode; /** - * If set to true, outputs all commands to observers and console. Otherwise, - * only shows explicit echo messages. + * If set to true, outputs all commands to observers and console. Otherwise, only shows explicit + * echo messages. */ private boolean echoOn = true; - + /** - * If set to true, an already closed proof leads to an exception if another goal - * should be picked. Otherwise, script execution terminates without an - * exception. + * If set to true, an already closed proof leads to an exception if another goal should be + * picked. Otherwise, script execution terminates without an exception. */ private boolean failOnClosedOn = true; @@ -79,35 +81,27 @@ public Proof getProof() { } /** - * Returns the first open goal, which has to be automatic iff checkAutomatic - * is true. + * Returns the first open goal, which has to be automatic iff checkAutomatic is true. * - * @param checkAutomatic - * Set to true if the returned {@link Goal} should be automatic. - * @return the first open goal, which has to be automatic iff checkAutomatic - * is true. + * @param checkAutomatic Set to true if the returned {@link Goal} should be automatic. + * @return the first open goal, which has to be automatic iff checkAutomatic is true. * - * @throws ProofAlreadyClosedException - * If the proof is already closed when calling this method. - * @throws ScriptException - * If there is no such {@link Goal}, or something else goes - * wrong. + * @throws ProofAlreadyClosedException If the proof is already closed when calling this method. + * @throws ScriptException If there is no such {@link Goal}, or something else goes wrong. */ @SuppressWarnings("unused") - public Goal getFirstOpenGoal(boolean checkAutomatic) - throws ScriptException { + public Goal getFirstOpenGoal(boolean checkAutomatic) throws ScriptException { if (proof.closed()) { throw new ProofAlreadyClosedException("The proof is closed already"); } Node rootNodeForSearch = proof.root(); Goal newGoal = goal; - if (newGoal != null && ((checkAutomatic && !newGoal.isAutomatic()) - || newGoal.node().isClosed())) { + if (newGoal != null + && ((checkAutomatic && !newGoal.isAutomatic()) || newGoal.node().isClosed())) { assert rootNodeForSearch != null; /* - * The first subtree of the previous goal is closed. Try with other - * subtrees. + * The first subtree of the previous goal is closed. Try with other subtrees. */ rootNodeForSearch = goUpUntilOpen(lastSetGoalNode); newGoal = null; @@ -121,8 +115,7 @@ public Goal getFirstOpenGoal(boolean checkAutomatic) lastSetGoalNode = newGoal.node(); if (newGoal == null) { - throw new ScriptException( - "There must be an open goal at this point"); + throw new ScriptException("There must be an open goal at this point"); } return newGoal; @@ -131,8 +124,7 @@ public Goal getFirstOpenGoal(boolean checkAutomatic) /** * @return The first open and automatic {@link Goal}. * - * @throws ScriptException - * If there is no such {@link Goal}. + * @throws ScriptException If there is no such {@link Goal}. */ public Goal getFirstOpenAutomaticGoal() throws ScriptException { return getFirstOpenGoal(true); @@ -143,8 +135,8 @@ private static Node goUpUntilOpen(final Node start) { while (currNode.isClosed()) { /* - * There should always be a non-closed parent since we check whether - * the proof is closed at the beginning. + * There should always be a non-closed parent since we check whether the proof is closed + * at the beginning. */ currNode = currNode.parent(); } @@ -200,8 +192,7 @@ private Goal findGoalFromRoot(final Node rootNode, boolean checkAutomatic) { return result; } - public Term toTerm(String string, Sort sort) - throws ParserException, ScriptException { + public Term toTerm(String string, Sort sort) throws ParserException, ScriptException { StringReader reader = new StringReader(string); Services services = proof.getServices(); Term formula = PARSER.parse(reader, sort, services, @@ -209,22 +200,17 @@ public Term toTerm(String string, Sort sort) return formula; } - public Sort toSort(String sortName) - throws ParserException, ScriptException { - return (getFirstOpenAutomaticGoal() == null - ? getProof().getServices().getNamespaces() - : getFirstOpenAutomaticGoal().getLocalNamespaces()).sorts() - .lookup(sortName); + public Sort toSort(String sortName) throws ParserException, ScriptException { + return (getFirstOpenAutomaticGoal() == null ? getProof().getServices().getNamespaces() + : getFirstOpenAutomaticGoal().getLocalNamespaces()).sorts().lookup(sortName); } - public Sequent toSequent(String sequent) - throws ParserException, ScriptException { + public Sequent toSequent(String sequent) throws ParserException, ScriptException { StringReader reader = new StringReader(sequent); Services services = proof.getServices(); Sequent seq = PARSER.parseSeq(reader, services, - getFirstOpenAutomaticGoal().getLocalNamespaces(), - getAbbreviations()); + getFirstOpenAutomaticGoal().getLocalNamespaces(), getAbbreviations()); return seq; } @@ -232,8 +218,7 @@ public int getMaxAutomaticSteps() { if (proof != null) { return proof.getSettings().getStrategySettings().getMaxSteps(); } else { - return ProofSettings.DEFAULT_SETTINGS.getStrategySettings() - .getMaxSteps(); + return ProofSettings.DEFAULT_SETTINGS.getStrategySettings().getMaxSteps(); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ExitCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ExitCommand.java index 54f14546165..74b47648399 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ExitCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ExitCommand.java @@ -1,18 +1,21 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; public class ExitCommand extends NoArgumentCommand { - @Override public void execute(AbstractUserInterfaceControl uiControl, - Void args, EngineState stateMap) + @Override + public void execute(AbstractUserInterfaceControl uiControl, Void args, EngineState stateMap) throws ScriptException, InterruptedException { - throw new InterruptedException( - "Interruption requested from within script"); + throw new InterruptedException("Interruption requested from within script"); } - @Override public String getName() { + @Override + public String getName() { return "exit"; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/FocusOnSelectionAndHideCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/FocusOnSelectionAndHideCommand.java index a6705a3f6e4..803c2e2ac7f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/FocusOnSelectionAndHideCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/FocusOnSelectionAndHideCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.logic.*; @@ -15,10 +18,8 @@ import java.util.Set; /** - * Hide all formulas that are not selected - * Parameter: - * * The sequent with those formulas that should not be hidden - * Created by sarah on 1/12/17. + * Hide all formulas that are not selected Parameter: * The sequent with those formulas that should + * not be hidden Created by sarah on 1/12/17. */ public class FocusOnSelectionAndHideCommand extends AbstractCommand { @@ -28,47 +29,39 @@ public FocusOnSelectionAndHideCommand() { } static class Parameters { - @Option("#2") public Sequent toKeep; + @Option("#2") + public Sequent toKeep; } - @Override public void execute(Parameters s) - throws ScriptException, InterruptedException { + @Override + public void execute(Parameters s) throws ScriptException, InterruptedException { if (s == null) { throw new ScriptException("Missing 'sequent' argument for focus"); } Sequent toKeep = s.toKeep; - //toKeep = parseSequent(sequentString, getGoalFromCurrentState()); + // toKeep = parseSequent(sequentString, getGoalFromCurrentState()); try { hideAll(toKeep); - } - catch (ParserException e) { + } catch (ParserException e) { e.printStackTrace(); } } - @Override public String getName() { + @Override + public String getName() { return "focus"; } /* - private Goal getGoalFromCurrentState() { - Object fixedGoal = stateMap.get(GOAL_KEY); - if (fixedGoal instanceof Node) { - Node fixed = (Node) fixedGoal; - //case node is already modified by focus, the child has to be returned - if (!fixed.leaf()) { - assert fixed.childrenCount() == 1; - fixed = fixed.child(0); - } - Goal g = state.getGoal(proof.openGoals(), fixed); - return g; - } - return null; - } - */ + * private Goal getGoalFromCurrentState() { Object fixedGoal = stateMap.get(GOAL_KEY); if + * (fixedGoal instanceof Node) { Node fixed = (Node) fixedGoal; //case node is already modified + * by focus, the child has to be returned if (!fixed.leaf()) { assert fixed.childrenCount() == + * 1; fixed = fixed.child(0); } Goal g = state.getGoal(proof.openGoals(), fixed); return g; } + * return null; } + */ /** * Hide all formulas of the sequent that are not focus sequent @@ -77,20 +70,18 @@ private Goal getGoalFromCurrentState() { * @throws ParserException * @throws ScriptException */ - private void hideAll(Sequent toKeep) - throws ParserException, ScriptException { + private void hideAll(Sequent toKeep) throws ParserException, ScriptException { while (true) { - //get current goal + // get current goal Goal g = state.getFirstOpenAutomaticGoal(); - //find formulas that should be hidden in sequent of current goal + // find formulas that should be hidden in sequent of current goal - //hide + // hide if (g != null) { - SequentFormula toHide = iterateThroughSequentAndFindNonMatch(g, - toKeep); - //as long as there is a match + SequentFormula toHide = iterateThroughSequentAndFindNonMatch(g, toKeep); + // as long as there is a match if (toHide != null) { boolean antec = false; @@ -99,29 +90,26 @@ private void hideAll(Sequent toKeep) tac = getTaclet(toHide.formula(), "left"); antec = true; - } - else { + } else { tac = getTaclet(toHide.formula(), "right"); } makeTacletApp(g, toHide, tac, antec); - } - else { - //no formulas to hide any more on sequent + } else { + // no formulas to hide any more on sequent break; } - } - else { - //goal is null + } else { + // goal is null break; } } } - //determine where formula in sequent and apply either hide_left or hide_right + // determine where formula in sequent and apply either hide_left or hide_right private Taclet getTaclet(Term t, String pos) throws ScriptException { String ruleName; Taclet tac; @@ -134,19 +122,18 @@ private Taclet getTaclet(Term t, String pos) throws ScriptException { break; default: ruleName = ""; - throw new ScriptException( - "Position of term " + t.toString() + "unknown"); + throw new ScriptException("Position of term " + t.toString() + "unknown"); } - tac = proof.getEnv().getInitConfigForEnvironment() - .lookupActiveTaclet(new Name(ruleName)); + tac = proof.getEnv().getInitConfigForEnvironment().lookupActiveTaclet(new Name(ruleName)); return tac; } /** - * Iterate through sequent and find first formula that is not in the list of formulas to keep and return this formula + * Iterate through sequent and find first formula that is not in the list of formulas to keep + * and return this formula * * @param g * @param toKeep @@ -155,8 +142,8 @@ private Taclet getTaclet(Term t, String pos) throws ScriptException { * @throws ParserException */ - private SequentFormula iterateThroughSequentAndFindNonMatch(Goal g, - Sequent toKeep) throws ScriptException, ParserException { + private SequentFormula iterateThroughSequentAndFindNonMatch(Goal g, Sequent toKeep) + throws ScriptException, ParserException { Semisequent focusedAntec = toKeep.antecedent(); Semisequent focusedSucc = toKeep.succedent(); @@ -164,7 +151,7 @@ private SequentFormula iterateThroughSequentAndFindNonMatch(Goal g, Semisequent currentAntec = currentGoalSeq.antecedent(); Semisequent currentSucc = currentGoalSeq.succedent(); - //first iterate through antecedent + // first iterate through antecedent Iterator iterator = currentAntec.iterator(); while (iterator.hasNext()) { SequentFormula form = iterator.next(); @@ -179,15 +166,15 @@ private SequentFormula iterateThroughSequentAndFindNonMatch(Goal g, } } -/* if(form.formula().equalsModRenaming(t) ){ - isIn = true; - }*/ + /* + * if(form.formula().equalsModRenaming(t) ){ isIn = true; } + */ if (!isIn) { return form; } } - //if in antecedent no formula to hide iterate through succedent + // if in antecedent no formula to hide iterate through succedent Iterator iteratorSucc = currentSucc.iterator(); while (iteratorSucc.hasNext()) { @@ -206,23 +193,23 @@ private SequentFormula iterateThroughSequentAndFindNonMatch(Goal g, return form; } } - //if no formulas to hide, return null + // if no formulas to hide, return null return null; } /** * Make tacletApp for one sequent formula to hide on the sequent * - * @param g the goal on which this hide rule should be applied to + * @param g the goal on which this hide rule should be applied to * @param toHide the sequent formula to hide - * @param tac the taclet top apply (either hide_left or hide_right) - * @param antec whether the formula is in the antecedent + * @param tac the taclet top apply (either hide_left or hide_right) + * @param antec whether the formula is in the antecedent * @throws ScriptException */ - private void makeTacletApp(Goal g, SequentFormula toHide, Taclet tac, - boolean antec) throws ScriptException { + private void makeTacletApp(Goal g, SequentFormula toHide, Taclet tac, boolean antec) + throws ScriptException { - //hide rules only applicable to top-level terms/sequent formulas + // hide rules only applicable to top-level terms/sequent formulas PosInTerm pit = PosInTerm.getTopLevel(); PosInOccurrence pio = new PosInOccurrence(toHide, pit, antec); @@ -234,11 +221,9 @@ private void makeTacletApp(Goal g, SequentFormula toHide, Taclet tac, SVInstantiations inst = SVInstantiations.EMPTY_SVINSTANTIATIONS; - TacletApp app = PosTacletApp - .createPosTacletApp((FindTaclet) tac, inst, pio, - proof.getServices()); - app = app.addCheckedInstantiation(sv, toHide.formula(), - proof.getServices(), true); + TacletApp app = + PosTacletApp.createPosTacletApp((FindTaclet) tac, inst, pio, proof.getServices()); + app = app.addCheckedInstantiation(sv, toHide.formula(), proof.getServices(), true); g.apply(app); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/HideCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/HideCommand.java index 844c8f11d79..792d234af2b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/HideCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/HideCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.logic.Name; @@ -27,12 +30,12 @@ * Proof script command to hide a formula from the sequent. * * Usage: + * *
      *     hide "f1, f2 ==> f3, f4"
      * 
    * - * All formulas in the parameter sequent are hidden using hide_left or using - * hide_right. + * All formulas in the parameter sequent are hidden using hide_left or using hide_right. * * @author Mattias Ulbrich */ @@ -46,15 +49,13 @@ public HideCommand() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(Parameters args) - throws ScriptException, InterruptedException { + public void execute(Parameters args) throws ScriptException, InterruptedException { Goal goal = state.getFirstOpenAutomaticGoal(); @@ -65,7 +66,8 @@ public void execute(Parameters args) SequentFormula s2 = find(s, goal.sequent().antecedent()); SchemaVariable sv = app.uninstantiatedVars().iterator().next(); app = app.addCheckedInstantiation(sv, s2.formula(), service, true); - app = app.setPosInOccurrence(new PosInOccurrence(s2, PosInTerm.getTopLevel(), true), service); + app = app.setPosInOccurrence(new PosInOccurrence(s2, PosInTerm.getTopLevel(), true), + service); goal.apply(app); } @@ -76,14 +78,15 @@ public void execute(Parameters args) SequentFormula s2 = find(s, goal.sequent().succedent()); SchemaVariable sv = app.uninstantiatedVars().iterator().next(); app = app.addCheckedInstantiation(sv, s2.formula(), service, true); - app = app.setPosInOccurrence(new PosInOccurrence(s2, PosInTerm.getTopLevel(), false), service); + app = app.setPosInOccurrence(new PosInOccurrence(s2, PosInTerm.getTopLevel(), false), + service); goal.apply(app); } } private SequentFormula find(SequentFormula sf, Semisequent semiseq) throws ScriptException { for (SequentFormula s : semiseq) { - if(s.formula().equalsModTermLabels(sf.formula())) { + if (s.formula().equalsModTermLabels(sf.formula())) { return s; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/InstantiateCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/InstantiateCommand.java index 7f56dad6d5a..8868ae101ad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/InstantiateCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/InstantiateCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -33,27 +36,26 @@ * * @author mulbrich */ -public class InstantiateCommand - extends AbstractCommand { +public class InstantiateCommand extends AbstractCommand { public InstantiateCommand() { super(Parameters.class); } - @Override public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { + @Override + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { return state.getValueInjector().inject(this, new Parameters(), arguments); } - @Override public void execute(AbstractUserInterfaceControl uiControl, - Parameters params, EngineState state) - throws ScriptException, InterruptedException { + @Override + public void execute(AbstractUserInterfaceControl uiControl, Parameters params, + EngineState state) throws ScriptException, InterruptedException { Goal goal = state.getFirstOpenAutomaticGoal(); if ((params.var == null) == (params.formula == null)) { - throw new ScriptException( - "One of 'var' or 'formula' must be specified"); + throw new ScriptException("One of 'var' or 'formula' must be specified"); } if (params.var != null) { @@ -69,7 +71,7 @@ public InstantiateCommand() { SchemaVariable sv = theApp.uninstantiatedVars().iterator().next(); - theApp = theApp.addInstantiation(sv, params.with, true /*???*/, + theApp = theApp.addInstantiation(sv, params.with, true /* ??? */, state.getProof().getServices()); theApp = theApp.tryToInstantiate(state.getProof().getServices()); @@ -78,8 +80,7 @@ public InstantiateCommand() { g.apply(theApp); } - private TacletApp findTacletApp(Parameters p, EngineState state) - throws ScriptException { + private TacletApp findTacletApp(Parameters p, EngineState state) throws ScriptException { ImmutableList allApps = findAllTacletApps(p, state); TacletApp matchingApp = filterList(p, allApps); @@ -90,16 +91,15 @@ private TacletApp findTacletApp(Parameters p, EngineState state) return matchingApp; } - private ImmutableList findAllTacletApps(Parameters p, - EngineState state) throws ScriptException { + private ImmutableList findAllTacletApps(Parameters p, EngineState state) + throws ScriptException { boolean hide = p.hide.equals("hide"); String rulename; if (p.formula.op() == Quantifier.ALL) { rulename = "allLeft" + (hide ? "Hide" : ""); - } - else { + } else { rulename = "exRight" + (hide ? "Hide" : ""); } @@ -116,8 +116,7 @@ private ImmutableList findAllTacletApps(Parameters p, continue; } allApps = allApps.append(index.getTacletAppAtAndBelow(filter, - new PosInOccurrence(sf, PosInTerm.getTopLevel(), true), - services)); + new PosInOccurrence(sf, PosInTerm.getTopLevel(), true), services)); } for (SequentFormula sf : g.node().sequent().succedent()) { @@ -125,8 +124,7 @@ private ImmutableList findAllTacletApps(Parameters p, continue; } allApps = allApps.append(index.getTacletAppAtAndBelow(filter, - new PosInOccurrence(sf, PosInTerm.getTopLevel(), false), - services)); + new PosInOccurrence(sf, PosInTerm.getTopLevel(), false), services)); } return allApps; @@ -147,8 +145,7 @@ private TacletApp filterList(Parameters p, ImmutableList list) { return null; } - private void computeFormula(Parameters params, Goal goal) - throws ScriptException { + private void computeFormula(Parameters params, Goal goal) throws ScriptException { Node n = goal.node(); Sequent seq = n.sequent(); int occ = params.occ; @@ -183,8 +180,7 @@ private void computeFormula(Parameters params, Goal goal) } throw new ScriptException( - "Variable '" + params.var + "' has no occurrence no. '" - + params.occ + "'."); + "Variable '" + params.var + "' has no occurrence no. '" + params.occ + "'."); } private Term stripUpdates(Term term) { @@ -195,62 +191,30 @@ private Term stripUpdates(Term term) { } /* - public Parameters createArguments(EngineState state, - Map args) throws ScriptException { - Parameters params = new Parameters(); - - // - // var="a" - params.var = args.get("var"); - - // - // formula="toplevel formula in which it appears" - // formula="\forall int a; phi(a)" - String formStr = args.get("formula"); - if (formStr != null) { - try { - params.formula = toTerm(proof, state, formStr, Sort.FORMULA); - } - catch (Exception e) { - throw new ScriptException(e); - } - } - - // - // occurrence number; - String occStr = args.get("occ"); - if (occStr != null) { - try { - params.occ = Integer.parseInt(occStr); - } - catch (NumberFormatException e) { - throw new ScriptException(e); - } - } - - // - // instantiation - String withStr = args.get("with"); - if (withStr != null) { - try { - params.with = toTerm(proof, state, withStr, null); - } - catch (ParserException e) { - throw new ScriptException(e); - } - } - else { - throw new ScriptException("'with' must be specified"); - } - - // - // hide - params.hide = args.containsKey("#2") && args.get("#2").equals("hide"); - - return params; - } -*/ - @Override public String getName() { + * public Parameters createArguments(EngineState state, Map args) throws + * ScriptException { Parameters params = new Parameters(); + * + * // // var="a" params.var = args.get("var"); + * + * // // formula="toplevel formula in which it appears" // formula="\forall int a; phi(a)" + * String formStr = args.get("formula"); if (formStr != null) { try { params.formula = + * toTerm(proof, state, formStr, Sort.FORMULA); } catch (Exception e) { throw new + * ScriptException(e); } } + * + * // // occurrence number; String occStr = args.get("occ"); if (occStr != null) { try { + * params.occ = Integer.parseInt(occStr); } catch (NumberFormatException e) { throw new + * ScriptException(e); } } + * + * // // instantiation String withStr = args.get("with"); if (withStr != null) { try { + * params.with = toTerm(proof, state, withStr, null); } catch (ParserException e) { throw new + * ScriptException(e); } } else { throw new ScriptException("'with' must be specified"); } + * + * // // hide params.hide = args.containsKey("#2") && args.get("#2").equals("hide"); + * + * return params; } + */ + @Override + public String getName() { return "instantiate"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/JavascriptCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/JavascriptCommand.java index 2f8965481fa..9b8487d3d1b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/JavascriptCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/JavascriptCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.logic.Sequent; @@ -13,20 +16,17 @@ import javax.script.ScriptEngineManager; import java.util.Map; -public class JavascriptCommand - extends AbstractCommand { +public class JavascriptCommand extends AbstractCommand { - private static final String PREAMBLE = - "var goal = __state.getSelectedGoal();\n" - + "function setVar(v, t) { __state.setVar(v,t); }\n"; + private static final String PREAMBLE = "var goal = __state.getSelectedGoal();\n" + + "function setVar(v, t) { __state.setVar(v,t); }\n"; public JavascriptCommand() { super(Parameters.class); } @Override - public void execute(Parameters args) - throws ScriptException, InterruptedException { + public void execute(Parameters args) throws ScriptException, InterruptedException { ScriptEngineManager factory = new ScriptEngineManager(); // create JavaScript engine ScriptEngine engine = factory.getEngineByName("JavaScript"); @@ -43,8 +43,8 @@ public void execute(Parameters args) } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { return ValueInjector.injection(this, new Parameters(), arguments); } @@ -54,7 +54,8 @@ public String getName() { } public static class Parameters { - @Option("#2") public String script; + @Option("#2") + public String script; } public static class JavascriptInterface { @@ -81,8 +82,7 @@ public void setVar(String var, Term term) throws ScriptException { var = var.substring(1); try { state.getAbbreviations().put(term, var, true); - } - catch (AbbrevException e) { + } catch (AbbrevException e) { throw new ScriptException(); } } @@ -90,8 +90,7 @@ public void setVar(String var, Term term) throws ScriptException { public void setVar(String var, String term) throws ScriptException { try { setVar(var, state.toTerm(term, null)); - } - catch (ParserException e) { + } catch (ParserException e) { throw new ScriptException(e); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LeaveCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LeaveCommand.java index dd3f665d292..097abc9a07d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LeaveCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LeaveCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.logging.Logger; @@ -15,8 +18,8 @@ public String getName() { } @Override - public void execute(AbstractUserInterfaceControl uiControl, - Void args, EngineState state) throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Void args, EngineState state) + throws ScriptException, InterruptedException { Goal goal = state.getFirstOpenAutomaticGoal(); log.info("Deactivating " + goal.node().serialNr()); goal.setEnabled(false); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LetCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LetCommand.java index 2e342a2cd13..9688de163ae 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LetCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/LetCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -11,14 +14,14 @@ public LetCommand() { super(null); } - @Override public Map evaluateArguments(EngineState state, - Map arguments) { + @Override + public Map evaluateArguments(EngineState state, Map arguments) { return arguments; } - @Override public void execute(AbstractUserInterfaceControl uiControl, - Map args, EngineState stateMap) - throws ScriptException, InterruptedException { + @Override + public void execute(AbstractUserInterfaceControl uiControl, Map args, + EngineState stateMap) throws ScriptException, InterruptedException { AbbrevMap abbrMap = stateMap.getAbbreviations(); for (Map.Entry entry : args.entrySet()) { @@ -30,9 +33,7 @@ public LetCommand() { continue; } if (!key.startsWith("@")) { - throw new ScriptException( - "Unexpected parameter to let, only @var allowed: " - + key); + throw new ScriptException("Unexpected parameter to let, only @var allowed: " + key); } // get rid of @ @@ -40,20 +41,19 @@ public LetCommand() { if (abbrMap.containsAbbreviation(key)) { // XXX desired or not? - throw new ScriptException( - key + " is already fixed in this script"); + throw new ScriptException(key + " is already fixed in this script"); } try { abbrMap.put(stateMap.toTerm(entry.getValue(), null), key, true); - } - catch (Exception e) { + } catch (Exception e) { throw new ScriptException(e); } } } - @Override public String getName() { + @Override + public String getName() { return "let"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/MacroCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/MacroCommand.java index 03d4dfbc76d..395b6399e18 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/MacroCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/MacroCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.HashMap; @@ -40,10 +43,9 @@ private static Map loadMacroMap() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override @@ -52,52 +54,47 @@ public String getName() { } @Override - public void execute(AbstractUserInterfaceControl uiControl, Parameters args, - EngineState state) throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Parameters args, EngineState state) + throws ScriptException, InterruptedException { final Services services = state.getProof().getServices(); // look up macro name ProofMacro macro = macroMap.get(args.macroName); if (macro == null) { - throw new ScriptException( - "Macro '" + args.macroName + "' not found"); + throw new ScriptException("Macro '" + args.macroName + "' not found"); } macro.resetParams(); if (args.instantiations != null) { - for (final Map.Entry macroParam : args.instantiations - .entrySet()) { + for (final Map.Entry macroParam : args.instantiations.entrySet()) { if (macro.hasParameter(macroParam.getKey())) { try { - macro.setParameter(macroParam.getKey(), - macroParam.getValue()); + macro.setParameter(macroParam.getKey(), macroParam.getValue()); } catch (IllegalArgumentException e) { throw new ScriptException(String.format( "Wrong format for parameter %s of macro %s: %s.\nMessage: %s", - macroParam.getKey(), args.macroName, - macroParam.getValue(), e.getMessage())); + macroParam.getKey(), args.macroName, macroParam.getValue(), + e.getMessage())); } } else { - throw new ScriptException( - String.format("Unknown parameter %s for macro %s", - macroParam.getKey(), args.macroName)); + throw new ScriptException(String.format("Unknown parameter %s for macro %s", + macroParam.getKey(), args.macroName)); } } } Goal g = state.getFirstOpenAutomaticGoal(); - ProofMacroFinishedInfo info = ProofMacroFinishedInfo - .getDefaultInfo(macro, state.getProof()); + ProofMacroFinishedInfo info = + ProofMacroFinishedInfo.getDefaultInfo(macro, state.getProof()); try { - uiControl.taskStarted(new DefaultTaskStartedInfo( - TaskStartedInfo.TaskKind.Macro, macro.getName(), 0)); + uiControl.taskStarted( + new DefaultTaskStartedInfo(TaskStartedInfo.TaskKind.Macro, macro.getName(), 0)); final Sequent sequent = g.node().sequent(); PosInOccurrence pio = null; if (args.occ > -1) { pio = new PosInOccurrence(sequent.getFormulabyNr(args.occ + 1), - PosInTerm.getTopLevel(), - args.occ + 1 <= sequent.antecedent().size()); + PosInTerm.getTopLevel(), args.occ + 1 <= sequent.antecedent().size()); } final String matchRegEx = args.matches; @@ -109,8 +106,8 @@ public void execute(AbstractUserInterfaceControl uiControl, Parameters args, info = macro.applyTo(uiControl, g.node(), pio, uiControl); } } catch (Exception e) { - throw new ScriptException("Macro '" + args.macroName - + "' raised an exception: " + e.getMessage(), e); + throw new ScriptException( + "Macro '" + args.macroName + "' raised an exception: " + e.getMessage(), e); } finally { uiControl.taskFinished(info); macro.resetParams(); @@ -126,32 +123,28 @@ public void execute(AbstractUserInterfaceControl uiControl, Parameters args, * @return * @throws ScriptException */ - public static PosInOccurrence extractMatchingPio(final Sequent sequent, - final String matchRegEx, final Services services) - throws ScriptException { + public static PosInOccurrence extractMatchingPio(final Sequent sequent, final String matchRegEx, + final Services services) throws ScriptException { PosInOccurrence pio = null; boolean matched = false; for (int i = 1; i < sequent.size() + 1; i++) { final boolean matchesRegex = formatTermString( - LogicPrinter.quickPrintTerm( - sequent.getFormulabyNr(i).formula(), services)) - .matches(".*" + matchRegEx + ".*"); + LogicPrinter.quickPrintTerm(sequent.getFormulabyNr(i).formula(), services)) + .matches(".*" + matchRegEx + ".*"); if (matchesRegex) { if (matched) { - throw new ScriptException( - "More than one occurrence of a matching term."); + throw new ScriptException("More than one occurrence of a matching term."); } matched = true; - pio = new PosInOccurrence(sequent.getFormulabyNr(i), - PosInTerm.getTopLevel(), + pio = new PosInOccurrence(sequent.getFormulabyNr(i), PosInTerm.getTopLevel(), i <= sequent.antecedent().size()); } } if (!matched) { - throw new ScriptException(String.format( - "Did not find a formula matching regex %s", matchRegEx)); + throw new ScriptException( + String.format("Did not find a formula matching regex %s", matchRegEx)); } return pio; @@ -160,8 +153,7 @@ public static PosInOccurrence extractMatchingPio(final Sequent sequent, /** * Removes spaces and line breaks from the string representation of a term. * - * @param str - * The string to "clean up". + * @param str The string to "clean up". * @return The original without spaces and line breaks. */ private static String formatTermString(String str) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/NoArgumentCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/NoArgumentCommand.java index f54a9794161..09c028045d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/NoArgumentCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/NoArgumentCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.macros.scripts.meta.DescriptionFacade; @@ -12,12 +15,13 @@ * @version 1 (28.03.17) */ public abstract class NoArgumentCommand implements ProofScriptCommand { - @Override public List getArguments() { + @Override + public List getArguments() { return new ArrayList<>(); } - @Override public Void evaluateArguments(EngineState state, - Map arguments) { + @Override + public Void evaluateArguments(EngineState state, Map arguments) { return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofAlreadyClosedException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofAlreadyClosedException.java index b9a9bb8a94c..1704a11788f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofAlreadyClosedException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofAlreadyClosedException.java @@ -1,12 +1,14 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.net.URL; /** - * Thrown if during the execution of a command, the proof is already closed. May - * or may not lead to exceptional termination of the whole script based on the - * @failonclosed setting. - * + * Thrown if during the execution of a command, the proof is already closed. May or may not lead to + * exceptional termination of the whole script based on the @failonclosed setting. + * * @author Dominic Steinhoefel */ public class ProofAlreadyClosedException extends ScriptException { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptCommand.java index d4c658f08ae..a3c8fd6447b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; @@ -7,11 +10,12 @@ import java.util.Map; /** - * A {@link ProofScriptCommand} is an executable mutation on the given proof. - * It abstracts complex operations, and made them accessible for an API. + * A {@link ProofScriptCommand} is an executable mutation on the given proof. It abstracts complex + * operations, and made them accessible for an API. *

    - * {@link ProofScriptCommand} are supported by the java.util.{@link java.util.ServiceLoader}. - * You can add new proof script commands by add a new entry to META-INF/service/de.uka.ilkd.key.macros.scripts.ProofScriptCommand. + * {@link ProofScriptCommand} are supported by the java.util.{@link java.util.ServiceLoader}. You + * can add new proof script commands by add a new entry to + * META-INF/service/de.uka.ilkd.key.macros.scripts.ProofScriptCommand. *

    * Version 2 (2017-03-28): change of the interface support for structured arguments. *

    @@ -31,24 +35,22 @@ public interface ProofScriptCommand { * @param arguments * @return */ - T evaluateArguments(EngineState state, Map arguments) - throws Exception; + T evaluateArguments(EngineState state, Map arguments) throws Exception; /** * @param uiControl the current ui controller - * @param args the script arguments - * @param stateMap the current state - * @throws ScriptException if something bad happens + * @param args the script arguments + * @param stateMap the current state + * @throws ScriptException if something bad happens * @throws InterruptedException if something bad happens */ - //TODO downgrade AbstractUserInterfaceControl to UserInterfaceControl - void execute(AbstractUserInterfaceControl uiControl, T args, - EngineState stateMap) throws ScriptException, InterruptedException; + // TODO downgrade AbstractUserInterfaceControl to UserInterfaceControl + void execute(AbstractUserInterfaceControl uiControl, T args, EngineState stateMap) + throws ScriptException, InterruptedException; /** - * Returns the name of this proof command. - * The name should be constant and not be clash with the name of other commands. - * The name is essential for finding this command within an hashmap. + * Returns the name of this proof command. The name should be constant and not be clash with the + * name of other commands. The name is essential for finding this command within an hashmap. * * @return a non-null, non-empty string * @see ProofScriptEngine @@ -61,4 +63,4 @@ void execute(AbstractUserInterfaceControl uiControl, T args, * @return a non-null string */ String getDocumentation(); -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptEngine.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptEngine.java index e8d7ec76b2d..36ed467566e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptEngine.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ProofScriptEngine.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.io.File; @@ -122,9 +125,9 @@ public void execute(AbstractUserInterfaceControl uiControl, Proof proof) cmd = cmd.substring(0, MAX_CHARS_PER_COMMAND) + " ...'"; } - if (commandMonitor != null && stateMap.isEchoOn() && !Optional - .ofNullable(argMap.get(ScriptLineParser.COMMAND_KEY)) - .orElse("").startsWith(SYSTEM_COMMAND_PREFIX)) { + if (commandMonitor != null && stateMap.isEchoOn() + && !Optional.ofNullable(argMap.get(ScriptLineParser.COMMAND_KEY)).orElse("") + .startsWith(SYSTEM_COMMAND_PREFIX)) { commandMonitor.update(null, cmd); } @@ -134,7 +137,8 @@ public void execute(AbstractUserInterfaceControl uiControl, Proof proof) throw new ScriptException("No command"); } - ProofScriptCommand command = (ProofScriptCommand) COMMANDS.get(name); + ProofScriptCommand command = + (ProofScriptCommand) COMMANDS.get(name); if (command == null) { throw new ScriptException("Unknown command " + name); } @@ -165,12 +169,12 @@ public void execute(AbstractUserInterfaceControl uiControl, Proof proof) } } catch (Exception e) { LOGGER.debug("GOALS: {}", proof.getSubtreeGoals(proof.root()).size()); - proof.getSubtreeGoals(stateMap.getProof().root()).forEach(g -> LOGGER.debug("{}", g.sequent())); + proof.getSubtreeGoals(stateMap.getProof().root()) + .forEach(g -> LOGGER.debug("{}", g.sequent())); throw new ScriptException( String.format("Error while executing script: %s\n\nCommand: %s", e.getMessage(), argMap.get(ScriptLineParser.LITERAL_KEY)), - initialLocation.getFileURL(), mlp.getLine(), - mlp.getColumn(), e); + initialLocation.getFileURL(), mlp.getLine(), mlp.getColumn(), e); } } } @@ -180,11 +184,9 @@ public EngineState getStateMap() { } /** - * Set the routine that is executed before every successfully executed - * command. + * Set the routine that is executed before every successfully executed command. * - * @param monitor - * the monitor to set + * @param monitor the monitor to set */ public void setCommandMonitor(Observer monitor) { this.commandMonitor = monitor; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RewriteCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RewriteCommand.java index b8dff02e047..73331451252 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RewriteCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RewriteCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; @@ -20,11 +23,13 @@ /** * This class provides the command rewrite. *

    - * This command takes two parameters. A term to find, and a term - * as the substitutent. Parameter class is {@link RewriteCommand.Parameters}. + * This command takes two parameters. A term to find, and a term as the substitutent. Parameter + * class is {@link RewriteCommand.Parameters}. *

    * - *

    Usage: + *

    + * Usage: + * *

      *     rewrite find="x+y" replace="y+x"; //(mulbrich script syntax)
      *     rewrite find=`y+x` replace=`y+x`; //(psdbg)
    @@ -59,22 +64,20 @@ public String getName() {
     
     
         @Override
    -    public Parameters evaluateArguments(EngineState state,
    -                                        Map arguments) throws Exception {
    -        return state.getValueInjector()
    -                .inject(this, new Parameters(), arguments);
    +    public Parameters evaluateArguments(EngineState state, Map arguments)
    +            throws Exception {
    +        return state.getValueInjector().inject(this, new Parameters(), arguments);
         }
     
         @Override
    -    public void execute(AbstractUserInterfaceControl uiControl,
    -                        Parameters args, EngineState state)
    +    public void execute(AbstractUserInterfaceControl uiControl, Parameters args, EngineState state)
                 throws ScriptException, InterruptedException {
             Proof proof = state.getProof();
             assert proof != null;
     
             ImmutableList allApps = findAllTacletApps(args, state);
     
    -        //filter all taclets for being applicable on the find term
    +        // filter all taclets for being applicable on the find term
             List failposInOccs = findAndExecReplacement(args, allApps, state);
     
             // if not all find terms successfully replaced, apply cut
    @@ -92,8 +95,8 @@ public void execute(AbstractUserInterfaceControl uiControl,
         /**
          * get all TacletApps that are applicable on the formula term
          */
    -    private ImmutableList findAllTacletApps(Parameters p,
    -                                                       EngineState state) throws ScriptException {
    +    private ImmutableList findAllTacletApps(Parameters p, EngineState state)
    +            throws ScriptException {
             Services services = state.getProof().getServices();
             TacletFilter filter = TacletFilter.TRUE;
             Goal g = state.getFirstOpenAutomaticGoal();
    @@ -102,41 +105,37 @@ private ImmutableList findAllTacletApps(Parameters p,
     
             ImmutableList allApps = ImmutableSLList.nil();
     
    -        //filter taclets that are applicable on the given formula
    -        //filter taclets that are applicable on the given formula in the antecedent
    +        // filter taclets that are applicable on the given formula
    +        // filter taclets that are applicable on the given formula in the antecedent
             for (SequentFormula sf : g.node().sequent().antecedent()) {
     
    -            if (p.formula != null && !sf.formula()
    -                    .equalsModRenaming(p.formula)) {
    +            if (p.formula != null && !sf.formula().equalsModRenaming(p.formula)) {
                     continue;
                 }
                 allApps = allApps.append(index.getTacletAppAtAndBelow(filter,
    -                    new PosInOccurrence(sf, PosInTerm.getTopLevel(), true),
    -                    services));
    +                    new PosInOccurrence(sf, PosInTerm.getTopLevel(), true), services));
             }
     
    -        //filter taclets that are applicable on the given formula in the succedent
    +        // filter taclets that are applicable on the given formula in the succedent
             for (SequentFormula sf : g.node().sequent().succedent()) {
    -            if (p.formula != null && !sf.formula()
    -                    .equalsModRenaming(p.formula)) {
    +            if (p.formula != null && !sf.formula().equalsModRenaming(p.formula)) {
                     continue;
                 }
                 allApps = allApps.append(index.getTacletAppAtAndBelow(filter,
    -                    new PosInOccurrence(sf, PosInTerm.getTopLevel(), false),
    -                    services));
    +                    new PosInOccurrence(sf, PosInTerm.getTopLevel(), false), services));
             }
     
             return allApps;
         }
     
         /**
    -     * Filter tacletapps: term = find && result = replace
    -     * and execute taclet that matches the conditions
    +     * Filter tacletapps: term = find && result = replace and execute taclet that matches the
    +     * conditions
          **/
    -    private List findAndExecReplacement(
    -            Parameters p, ImmutableList list, EngineState state) {
    +    private List findAndExecReplacement(Parameters p,
    +            ImmutableList list, EngineState state) {
     
    -        //Find taclet that transforms find term to replace term, when applied on find term
    +        // Find taclet that transforms find term to replace term, when applied on find term
             for (TacletApp tacletApp : list) {
                 if (tacletApp instanceof PosTacletApp) {
                     PosTacletApp pta = (PosTacletApp) tacletApp;
    @@ -145,19 +144,18 @@ private List findAndExecReplacement(
                             continue;
                         }
                         if (pta.posInOccurrence().subTerm().equals(p.find) && pta.complete()) {
    -                        //if Term already succ replaced, then skip
    +                        // if Term already succ replaced, then skip
                             if (succposInOccs.contains(pta.posInOccurrence())) {
                                 continue;
                             }
     
    -                        try { //Term not already successfully replaced
    +                        try { // Term not already successfully replaced
                                 Goal goalold = state.getFirstOpenAutomaticGoal();
     
                                 RewriteTaclet rw = (RewriteTaclet) pta.taclet();
                                 if (pta.complete()) {
    -                                SequentFormula rewriteResult = rw.getExecutor()
    -                                        .getRewriteResult(goalold, null,
    -                                                goalold.proof().getServices(), pta);
    +                                SequentFormula rewriteResult = rw.getExecutor().getRewriteResult(
    +                                        goalold, null, goalold.proof().getServices(), pta);
     
                                     executeRewriteTaclet(p, pta, goalold, rewriteResult);
                                     break;
    @@ -175,31 +173,32 @@ private List findAndExecReplacement(
         }
     
         /**
    -     * Execute taclet pta if after application p.find term is replaced by p.replace
    -     * throws IllegalArgumentException on not successfully applicable pta
    +     * Execute taclet pta if after application p.find term is replaced by p.replace throws
    +     * IllegalArgumentException on not successfully applicable pta
    +     *
          * @param p
          * @param pta
          * @param goalold
          * @param rewriteResult
          */
         private void executeRewriteTaclet(Parameters p, PosTacletApp pta, Goal goalold,
    -                                      SequentFormula rewriteResult) {
    -        if (rewriteResult.formula().equals(p.replace) ||
    -                getTermAtPos(rewriteResult, pta.posInOccurrence())
    -                        .equals(p.replace)) {
    +            SequentFormula rewriteResult) {
    +        if (rewriteResult.formula().equals(p.replace)
    +                || getTermAtPos(rewriteResult, pta.posInOccurrence()).equals(p.replace)) {
                 failposInOccs.remove(pta.posInOccurrence());
                 succposInOccs.add(pta.posInOccurrence());
                 goalold.apply(pta);
                 return;
             } else {
    -            throw new IllegalArgumentException("Unsuccessful application of rewrite taclet "
    -                    + pta.taclet().displayName());
    +            throw new IllegalArgumentException(
    +                    "Unsuccessful application of rewrite taclet " + pta.taclet().displayName());
             }
         }
     
     
         /**
          * Calculates term at the PosInOccurrence pio
    +     *
          * @param sf top-level formula
          * @param pio PosInOccurrence of the to be returned term
          * @return term at pio
    @@ -217,6 +216,7 @@ public Term getTermAtPos(SequentFormula sf, PosInOccurrence pio) {
     
         /**
          * Gets subterm of t at the postion of pit
    +     *
          * @param t
          * @param pit
          * @return subterm
    diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RuleCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RuleCommand.java
    index 82a609b0a11..6926f4d8453 100644
    --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RuleCommand.java
    +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/RuleCommand.java
    @@ -1,3 +1,6 @@
    +/* This file is part of KeY - https://key-project.org
    + * KeY is licensed by the GNU General Public License Version 2
    + * SPDX-License-Identifier: GPL-2.0 */
     package de.uka.ilkd.key.macros.scripts;
     
     import java.util.ArrayList;
    @@ -39,12 +42,12 @@
     import de.uka.ilkd.key.rule.TacletApp;
     
     /**
    - * Command that applies a calculus rule All parameters are passed as strings and
    - * converted by the command. The parameters are:
    + * Command that applies a calculus rule All parameters are passed as strings and converted by the
    + * command. The parameters are:
      * 
      *
    1. #2 = rule name
    2. - *
    3. on= key.core.logic.Term on which the rule should be applied to as String - * (find part of the rule)
    4. + *
    5. on= key.core.logic.Term on which the rule should be applied to as String (find part of the + * rule)
    6. *
    7. formula= toplevel formula in which term appears in
    8. *
    9. occ = occurrence number
    10. *
    11. inst_= instantiation
    12. @@ -62,15 +65,14 @@ public String getName() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(AbstractUserInterfaceControl uiControl, Parameters args, - EngineState state) throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Parameters args, EngineState state) + throws ScriptException, InterruptedException { RuleApp theApp = makeRuleApp(args, state); Goal g = state.getFirstOpenAutomaticGoal(); @@ -83,30 +85,25 @@ public void execute(AbstractUserInterfaceControl uiControl, Parameters args, g.apply(theApp); } - private RuleApp makeRuleApp(Parameters p, EngineState state) - throws ScriptException { + private RuleApp makeRuleApp(Parameters p, EngineState state) throws ScriptException { final Proof proof = state.getProof(); - final Optional maybeBuiltInRule = proof.getInitConfig() - .getProfile().getStandardRules().getStandardBuiltInRules() - .stream().filter(r -> r.name().toString().equals(p.rulename)) - .findAny(); + final Optional maybeBuiltInRule = + proof.getInitConfig().getProfile().getStandardRules().getStandardBuiltInRules() + .stream().filter(r -> r.name().toString().equals(p.rulename)).findAny(); - final Optional maybeTaclet = Optional - .ofNullable(proof.getEnv().getInitConfigForEnvironment() - .lookupActiveTaclet(new Name(p.rulename))); + final Optional maybeTaclet = Optional.ofNullable(proof.getEnv() + .getInitConfigForEnvironment().lookupActiveTaclet(new Name(p.rulename))); if (!maybeBuiltInRule.isPresent() && !maybeTaclet.isPresent()) { /* - * (DS, 2019-01-31): Might be a locally introduced taclet, e.g., by - * hide_left etc. + * (DS, 2019-01-31): Might be a locally introduced taclet, e.g., by hide_left etc. */ - final Optional maybeApp = Optional - .ofNullable(state.getFirstOpenAutomaticGoal() - .indexOfTaclets().lookup(p.rulename)); + final Optional maybeApp = Optional.ofNullable( + state.getFirstOpenAutomaticGoal().indexOfTaclets().lookup(p.rulename)); - TacletApp app = maybeApp.orElseThrow(() -> new ScriptException( - "Taclet '" + p.rulename + "' not known.")); + TacletApp app = maybeApp.orElseThrow( + () -> new ScriptException("Taclet '" + p.rulename + "' not known.")); if (app.taclet() instanceof FindTaclet) { app = findTacletApp(p, state); @@ -128,22 +125,19 @@ private RuleApp makeRuleApp(Parameters p, EngineState state) IBuiltInRuleApp builtInRuleApp = // builtInRuleApp(p, state, maybeBuiltInRule.get()); if (builtInRuleApp.isSufficientlyComplete()) { - builtInRuleApp = builtInRuleApp - .forceInstantiate(state.getFirstOpenAutomaticGoal()); + builtInRuleApp = builtInRuleApp.forceInstantiate(state.getFirstOpenAutomaticGoal()); } return builtInRuleApp; } } - private TacletApp instantiateTacletApp(final Parameters p, - final EngineState state, final Proof proof, final TacletApp theApp) - throws ScriptException { + private TacletApp instantiateTacletApp(final Parameters p, final EngineState state, + final Proof proof, final TacletApp theApp) throws ScriptException { TacletApp result = theApp; Services services = proof.getServices(); ImmutableList assumesCandidates = theApp - .findIfFormulaInstantiations( - state.getFirstOpenAutomaticGoal().sequent(), services); + .findIfFormulaInstantiations(state.getFirstOpenAutomaticGoal().sequent(), services); assumesCandidates = ImmutableList.fromList(filterList(p, assumesCandidates)); @@ -154,23 +148,21 @@ private TacletApp instantiateTacletApp(final Parameters p, result = assumesCandidates.head(); /* - * NOTE (DS, 2019-02-22): If we change something by instantiating the - * app as much as possible, it might happen that the match conditions - * (those which are not really conditions, but which change the - * instantiations based on others that are yet to be added) have to be - * evaluated again, since the second call to tryToInstantiate won't do - * this if everything already has been instantiated. That's a little sad - * and a border case, but I had that problem. + * NOTE (DS, 2019-02-22): If we change something by instantiating the app as much as + * possible, it might happen that the match conditions (those which are not really + * conditions, but which change the instantiations based on others that are yet to be added) + * have to be evaluated again, since the second call to tryToInstantiate won't do this if + * everything already has been instantiated. That's a little sad and a border case, but I + * had that problem. */ boolean recheckMatchConditions; { /* - * (DS, 2019-01-31): Try to instantiate first, otherwise, we cannot - * apply taclets with "\newPV", Skolem terms etc. + * (DS, 2019-01-31): Try to instantiate first, otherwise, we cannot apply taclets with + * "\newPV", Skolem terms etc. */ - final TacletApp maybeInstApp = result - .tryToInstantiateAsMuchAsPossible(services.getOverlay(state - .getFirstOpenAutomaticGoal().getLocalNamespaces())); + final TacletApp maybeInstApp = result.tryToInstantiateAsMuchAsPossible( + services.getOverlay(state.getFirstOpenAutomaticGoal().getLocalNamespaces())); if (maybeInstApp != null) { result = maybeInstApp; @@ -186,8 +178,7 @@ private TacletApp instantiateTacletApp(final Parameters p, if (result.isInstantiationRequired(sv)) { Term inst = p.instantiations.get(sv.name().toString()); if (inst == null) { - throw new ScriptException( - "missing instantiation for " + sv); + throw new ScriptException("missing instantiation for " + sv); } result = result.addInstantiation(sv, inst, true, services); @@ -195,8 +186,8 @@ private TacletApp instantiateTacletApp(final Parameters p, } // try to instantiate remaining symbols - result = result.tryToInstantiate(services.getOverlay( - state.getFirstOpenAutomaticGoal().getLocalNamespaces())); + result = result.tryToInstantiate( + services.getOverlay(state.getFirstOpenAutomaticGoal().getLocalNamespaces())); if (result == null) { throw new ScriptException("Cannot instantiate this rule"); @@ -220,8 +211,8 @@ private TacletApp makeNoFindTacletApp(Taclet taclet) { return app; } - private IBuiltInRuleApp builtInRuleApp(Parameters p, EngineState state, - BuiltInRule rule) throws ScriptException { + private IBuiltInRuleApp builtInRuleApp(Parameters p, EngineState state, BuiltInRule rule) + throws ScriptException { final List matchingApps = // findBuiltInRuleApps(p, state).stream() .filter(r -> r.rule().name().equals(rule.name())) @@ -233,24 +224,22 @@ private IBuiltInRuleApp builtInRuleApp(Parameters p, EngineState state, if (p.occ < 0) { if (matchingApps.size() > 1) { - throw new ScriptException( - "More than one applicable occurrence"); + throw new ScriptException("More than one applicable occurrence"); } return matchingApps.get(0); } else { if (p.occ >= matchingApps.size()) { - throw new ScriptException("Occurence " + p.occ - + " has been specified, but there are only " - + matchingApps.size() + " hits."); + throw new ScriptException( + "Occurence " + p.occ + " has been specified, but there are only " + + matchingApps.size() + " hits."); } return matchingApps.get(p.occ); } } - private TacletApp findTacletApp(Parameters p, EngineState state) - throws ScriptException { + private TacletApp findTacletApp(Parameters p, EngineState state) throws ScriptException { ImmutableList allApps = findAllTacletApps(p, state); List matchingApps = filterList(p, allApps); @@ -261,28 +250,26 @@ private TacletApp findTacletApp(Parameters p, EngineState state) if (p.occ < 0) { if (matchingApps.size() > 1) { - throw new ScriptException( - "More than one applicable occurrence"); + throw new ScriptException("More than one applicable occurrence"); } return matchingApps.get(0); } else { if (p.occ >= matchingApps.size()) { - throw new ScriptException("Occurence " + p.occ - + " has been specified, but there are only " - + matchingApps.size() + " hits."); + throw new ScriptException( + "Occurence " + p.occ + " has been specified, but there are only " + + matchingApps.size() + " hits."); } return matchingApps.get(p.occ); } } - private ImmutableList findBuiltInRuleApps(Parameters p, - EngineState state) throws ScriptException { + private ImmutableList findBuiltInRuleApps(Parameters p, EngineState state) + throws ScriptException { final Services services = state.getProof().getServices(); assert services != null; final Goal g = state.getFirstOpenAutomaticGoal(); - final BuiltInRuleAppIndex index = g.ruleAppIndex() - .builtInRuleAppIndex(); + final BuiltInRuleAppIndex index = g.ruleAppIndex().builtInRuleAppIndex(); ImmutableList allApps = ImmutableSLList.nil(); for (SequentFormula sf : g.node().sequent().antecedent()) { @@ -306,8 +293,8 @@ private ImmutableList findBuiltInRuleApps(Parameters p, return allApps; } - private ImmutableList findAllTacletApps(Parameters p, - EngineState state) throws ScriptException { + private ImmutableList findAllTacletApps(Parameters p, EngineState state) + throws ScriptException { Services services = state.getProof().getServices(); assert services != null; TacletFilter filter = new TacletNameFilter(p.rulename); @@ -322,8 +309,7 @@ private ImmutableList findAllTacletApps(Parameters p, } allApps = allApps.append(index.getTacletAppAtAndBelow(filter, - new PosInOccurrence(sf, PosInTerm.getTopLevel(), true), - services)); + new PosInOccurrence(sf, PosInTerm.getTopLevel(), true), services)); } for (SequentFormula sf : g.node().sequent().succedent()) { @@ -332,8 +318,7 @@ private ImmutableList findAllTacletApps(Parameters p, } allApps = allApps.append(index.getTacletAppAtAndBelow(filter, - new PosInOccurrence(sf, PosInTerm.getTopLevel(), false), - services)); + new PosInOccurrence(sf, PosInTerm.getTopLevel(), false), services)); } return allApps; @@ -341,35 +326,30 @@ private ImmutableList findAllTacletApps(Parameters p, /** * Returns true iff the given {@link SequentFormula} either matches the - * {@link Parameters#formula} parameter or its String representation matches - * the {@link Parameters#matches} regex. If both parameters are not - * supplied, always returns true. + * {@link Parameters#formula} parameter or its String representation matches the + * {@link Parameters#matches} regex. If both parameters are not supplied, always returns true. * - * @param p - * The {@link Parameters} object. - * @param sf - * The {@link SequentFormula} to check. + * @param p The {@link Parameters} object. + * @param sf The {@link SequentFormula} to check. * @return true if sf matches. */ - private boolean isFormulaSearchedFor(Parameters p, SequentFormula sf, - Services services) throws ScriptException { - final boolean satisfiesFormulaParameter = p.formula != null - && sf.formula().equalsModRenaming(p.formula); + private boolean isFormulaSearchedFor(Parameters p, SequentFormula sf, Services services) + throws ScriptException { + final boolean satisfiesFormulaParameter = + p.formula != null && sf.formula().equalsModRenaming(p.formula); final boolean satisfiesMatchesParameter = p.matches != null - && formatTermString( - LogicPrinter.quickPrintTerm(sf.formula(), services)) - .matches(".*" + p.matches + ".*"); + && formatTermString(LogicPrinter.quickPrintTerm(sf.formula(), services)) + .matches(".*" + p.matches + ".*"); - return (p.formula == null && p.matches == null) - || satisfiesFormulaParameter || satisfiesMatchesParameter; + return (p.formula == null && p.matches == null) || satisfiesFormulaParameter + || satisfiesMatchesParameter; } /** * Removes spaces and line breaks from the string representation of a term. * - * @param str - * The string to "clean up". + * @param str The string to "clean up". * @return The original without spaces and line breaks. */ private static String formatTermString(String str) { @@ -381,21 +361,20 @@ private static String formatTermString(String str) { /* * Filter those apps from a list that are according to the parameters. */ - private List filterList(Parameters p, - ImmutableList list) { + private List filterList(Parameters p, ImmutableList list) { List matchingApps = new ArrayList(); for (TacletApp tacletApp : list) { if (tacletApp instanceof PosTacletApp) { PosTacletApp pta = (PosTacletApp) tacletApp; - boolean add = p.on == null - || pta.posInOccurrence().subTerm().equalsModRenaming(p.on); + boolean add = + p.on == null || pta.posInOccurrence().subTerm().equalsModRenaming(p.on); Iterator it = pta.instantiations().svIterator(); while (it.hasNext()) { SchemaVariable sv = it.next(); Term userInst = p.instantiations.get(sv.name().toString()); - Object ptaInst - = pta.instantiations().getInstantiationEntry(sv).getInstantiation(); + Object ptaInst = + pta.instantiations().getInstantiationEntry(sv).getInstantiation(); add &= userInst == null || userInst.equalsModIrrelevantTermLabels(ptaInst); } @@ -418,9 +397,8 @@ public static class Parameters { @Option(value = "occ", required = false) public int occ = -1; /** - * Represents a part of a formula (may use Java regular expressions as - * long as supported by proof script parser). Rule is applied to the - * sequent formula which matches that string. + * Represents a part of a formula (may use Java regular expressions as long as supported by + * proof script parser). Rule is applied to the sequent formula which matches that string. */ @Option(value = "matches", required = false) public String matches = null; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SMTCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SMTCommand.java index 3633d78a7be..2636ac81e43 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SMTCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SMTCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.macros.scripts.meta.Option; @@ -15,8 +18,7 @@ import java.util.*; -public class SMTCommand - extends AbstractCommand { +public class SMTCommand extends AbstractCommand { private static final Map SOLVER_MAP = computeSolverMap(); public SMTCommand() { @@ -33,24 +35,26 @@ private static Map computeSolverMap() { return Collections.unmodifiableMap(result); } - @Override public SMTCommandArguments evaluateArguments(EngineState state, - Map arguments) throws Exception { + @Override + public SMTCommandArguments evaluateArguments(EngineState state, Map arguments) + throws Exception { return ValueInjector.injection(this, new SMTCommandArguments(), arguments); } - @Override public String getName() { + @Override + public String getName() { return "smt"; } - @Override public void execute(SMTCommandArguments args) - throws ScriptException, InterruptedException { + @Override + public void execute(SMTCommandArguments args) throws ScriptException, InterruptedException { SolverTypeCollection su = computeSolvers(args.solver); ImmutableList goals; if (args.all) { - goals = state.getProof().openGoals(); + goals = state.getProof().openGoals(); } else { - goals = ImmutableSLList.nil().prepend(state.getFirstOpenAutomaticGoal()); + goals = ImmutableSLList.nil().prepend(state.getFirstOpenAutomaticGoal()); } for (Goal goal : goals) { @@ -59,13 +63,12 @@ private static Map computeSolverMap() { } private void runSMT(SMTCommandArguments args, SolverTypeCollection su, Goal goal) { - DefaultSMTSettings settings = new DefaultSMTSettings( - goal.proof().getSettings().getSMTSettings(), - ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), - goal.proof().getSettings().getNewSMTSettings(), - goal.proof()); + DefaultSMTSettings settings = + new DefaultSMTSettings(goal.proof().getSettings().getSMTSettings(), + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), + goal.proof().getSettings().getNewSMTSettings(), goal.proof()); - if(args.timeout >= 0) { + if (args.timeout >= 0) { settings = new SMTSettingsTimeoutWrapper(settings, args.timeout); } @@ -79,14 +82,11 @@ private void runSMT(SMTCommandArguments args, SolverTypeCollection su, Goal goal for (SMTProblem problem : probList) { SMTSolverResult finalResult = problem.getFinalResult(); if (finalResult.isValid() == ThreeValuedTruth.VALID) { - IBuiltInRuleApp app = RuleAppSMT.rule.createApp(null) - .setTitle(args.solver); + IBuiltInRuleApp app = RuleAppSMT.rule.createApp(null).setTitle(args.solver); problem.getGoal().apply(app); -} - System.err.println("SMT Runtime, goal " + - goal.node().serialNr() + ": " + - timerListener.getRuntime() + " ms; " + - finalResult); + } + System.err.println("SMT Runtime, goal " + goal.node().serialNr() + ": " + + timerListener.getRuntime() + " ms; " + finalResult); } } @@ -119,12 +119,14 @@ private static class TimerListener implements SolverLauncherListener { private long stop; @Override - public void launcherStarted(Collection problems, Collection solverTypes, SolverLauncher launcher) { + public void launcherStarted(Collection problems, + Collection solverTypes, SolverLauncher launcher) { this.start = System.currentTimeMillis(); } @Override - public void launcherStopped(SolverLauncher launcher, Collection finishedSolvers) { + public void launcherStopped(SolverLauncher launcher, + Collection finishedSolvers) { this.stop = System.currentTimeMillis(); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveInstCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveInstCommand.java index cdeb60f7647..c5683f1d786 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveInstCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveInstCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -12,14 +15,12 @@ import de.uka.ilkd.key.rule.TacletApp; /** - * Special "Let" usually to be applied immediately after a manual rule - * application. Saves the instantiation of a {@link SchemaVariable} by the last - * {@link TacletApp} into an abbreviation for later use. A nice use case is a - * manual loop invariant rule application, where the newly introduced - * anonymizing Skolem constants can be saved for later interactive - * instantiations. As for the {@link LetCommand}, it is not allowed to call this - * command multiple times with the same name argument (all names used for - * remembering instantiations are "final"). + * Special "Let" usually to be applied immediately after a manual rule application. Saves the + * instantiation of a {@link SchemaVariable} by the last {@link TacletApp} into an abbreviation for + * later use. A nice use case is a manual loop invariant rule application, where the newly + * introduced anonymizing Skolem constants can be saved for later interactive instantiations. As for + * the {@link LetCommand}, it is not allowed to call this command multiple times with the same name + * argument (all names used for remembering instantiations are "final"). * * @author Dominic Steinhoefel */ @@ -29,15 +30,13 @@ public SaveInstCommand() { } @Override - public Map evaluateArguments(EngineState state, - Map arguments) { + public Map evaluateArguments(EngineState state, Map arguments) { return arguments; } @Override - public void execute(AbstractUserInterfaceControl uiControl, - Map args, EngineState stateMap) - throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Map args, + EngineState stateMap) throws ScriptException, InterruptedException { AbbrevMap abbrMap = stateMap.getAbbreviations(); for (Map.Entry entry : args.entrySet()) { @@ -50,35 +49,30 @@ public void execute(AbstractUserInterfaceControl uiControl, continue; } if (!key.startsWith("@")) { - throw new ScriptException( - "Unexpected parameter to let, only @var allowed: " - + key); + throw new ScriptException("Unexpected parameter to let, only @var allowed: " + key); } // get rid of @ key = key.substring(1); if (abbrMap.containsAbbreviation(key)) { - throw new ScriptException( - key + " is already fixed in this script"); + throw new ScriptException(key + " is already fixed in this script"); } try { - final RuleApp ruleApp = stateMap.getFirstOpenAutomaticGoal().node() - .parent().getAppliedRuleApp(); + final RuleApp ruleApp = + stateMap.getFirstOpenAutomaticGoal().node().parent().getAppliedRuleApp(); if (ruleApp instanceof TacletApp) { final TacletApp tacletApp = (TacletApp) ruleApp; - final Object inst = tacletApp.matchConditions() - .getInstantiations().lookupValue(new Name(value)); - if (inst != null - && ((Term) inst).op() instanceof Function) { + final Object inst = tacletApp.matchConditions().getInstantiations() + .lookupValue(new Name(value)); + if (inst != null && ((Term) inst).op() instanceof Function) { abbrMap.put((Term) inst, key, true); } else { throw new ScriptException(String.format( "Tried to remember instantiation of schema variable %s " + "as \"%s\", but instantiation is \"%s\" and not a function", - value, key, - inst == null ? "null" : inst.toString())); + value, key, inst == null ? "null" : inst.toString())); } } } catch (Exception e) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveNewNameCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveNewNameCommand.java index 6100191566b..febbf9c0db5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveNewNameCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SaveNewNameCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.List; @@ -18,39 +21,33 @@ import de.uka.ilkd.key.rule.TacletApp; /** - * Special "Let" usually to be applied immediately after a manual rule - * application. Saves a new name introduced by the last {@link TacletApp} which - * matches certain criteria into an abbreviation for later use. A nice use case - * is a manual loop invariant rule application, where the newly introduced - * anonymizing Skolem constants can be saved for later interactive - * instantiations. As for the {@link LetCommand}, it is not allowed to call this - * command multiple times with the same name argument (all names used for - * remembering instantiations are "final"). + * Special "Let" usually to be applied immediately after a manual rule application. Saves a new name + * introduced by the last {@link TacletApp} which matches certain criteria into an abbreviation for + * later use. A nice use case is a manual loop invariant rule application, where the newly + * introduced anonymizing Skolem constants can be saved for later interactive instantiations. As for + * the {@link LetCommand}, it is not allowed to call this command multiple times with the same name + * argument (all names used for remembering instantiations are "final"). * * @author Dominic Steinhoefel */ -public class SaveNewNameCommand - extends AbstractCommand { +public class SaveNewNameCommand extends AbstractCommand { public SaveNewNameCommand() { super(Parameters.class); } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(AbstractUserInterfaceControl uiControl, - Parameters params, EngineState stateMap) - throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Parameters params, + EngineState stateMap) throws ScriptException, InterruptedException { if (!params.abbreviation.startsWith("@")) { - throw new ScriptException( - "Unexpected parameter to saveNewName, only @var allowed: " - + params.abbreviation); + throw new ScriptException("Unexpected parameter to saveNewName, only @var allowed: " + + params.abbreviation); } final AbbrevMap abbrMap = stateMap.getAbbreviations(); @@ -60,19 +57,17 @@ public void execute(AbstractUserInterfaceControl uiControl, try { final Goal goal = stateMap.getFirstOpenAutomaticGoal(); final Node node = goal.node().parent(); - final List matches = node.getNameRecorder().getProposals() - .stream().map(Name::toString) - .filter(str -> str.matches(stringToMatch)) - .collect(Collectors.toList()); + final List matches = + node.getNameRecorder().getProposals().stream().map(Name::toString) + .filter(str -> str.matches(stringToMatch)).collect(Collectors.toList()); if (matches.size() != 1) { - throw new ScriptException(String.format( - "Found %d matches for expression %s in new names, expected 1", - matches.size(), stringToMatch)); + throw new ScriptException( + String.format("Found %d matches for expression %s in new names, expected 1", + matches.size(), stringToMatch)); } - final Named lookupResult = goal.getLocalNamespaces() - .lookup(new Name(matches.get(0))); + final Named lookupResult = goal.getLocalNamespaces().lookup(new Name(matches.get(0))); assert lookupResult != null; @@ -85,9 +80,9 @@ public void execute(AbstractUserInterfaceControl uiControl, } else if (lookupResult instanceof ProgramVariable) { t = tb.var((ProgramVariable) lookupResult); } else { - throw new ScriptException(String.format( - "Unexpected instantiation type in SaveNewName: %s", - lookupResult.getClass().getSimpleName())); + throw new ScriptException( + String.format("Unexpected instantiation type in SaveNewName: %s", + lookupResult.getClass().getSimpleName())); } if (abbrMap.containsAbbreviation(key)) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SchemaVarCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SchemaVarCommand.java index 2afa90f0bf2..c2d17383ac2 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SchemaVarCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SchemaVarCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.logic.Name; @@ -13,20 +16,20 @@ /** * */ -public class SchemaVarCommand - extends AbstractCommand { +public class SchemaVarCommand extends AbstractCommand { public SchemaVarCommand() { super(Parameters.class); } - @Override public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { + @Override + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { return state.getValueInjector().inject(this, new Parameters(), arguments); } - @Override public void execute(Parameters args) - throws ScriptException, InterruptedException { + @Override + public void execute(Parameters args) throws ScriptException, InterruptedException { if (args.type == null || args.var == null) { throw new ScriptException("Missing argument: type var"); @@ -44,24 +47,22 @@ public SchemaVarCommand() { SchemaVariable sv; if ("Formula".equals(args.type)) { sv = SchemaVariableFactory.createFormulaSV(schemaVar); - } - else { + } else { Sort sort = state.toSort(args.type); sv = SchemaVariableFactory.createTermSV(schemaVar, sort); } - Term term = state.getProof().getServices().getTermFactory() - .createTerm(sv); + Term term = state.getProof().getServices().getTermFactory().createTerm(sv); abbrMap.put(term, args.var, true); - } - catch (Exception e) { + } catch (Exception e) { throw new ScriptException(e); } } - @Override public String getName() { + @Override + public String getName() { return "schemaVar"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptCommand.java index 512a1f7f78b..6092fe0348b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.macros.scripts.meta.Option; @@ -11,11 +14,12 @@ public ScriptCommand() { } public static class Parameters { - @Option("#2") public String filename; + @Option("#2") + public String filename; } - @Override public void execute(Parameters args) - throws ScriptException, InterruptedException { + @Override + public void execute(Parameters args) throws ScriptException, InterruptedException { File root = state.getBaseFileName(); if (!root.isDirectory()) root = root.getParentFile(); @@ -27,20 +31,17 @@ public static class Parameters { ProofScriptEngine pse = new ProofScriptEngine(file); pse.setCommandMonitor(state.getObserver()); pse.execute(uiControl, proof); - } - catch (NoSuchFileException e) { + } catch (NoSuchFileException e) { // The message is very cryptic otherwise. - throw new ScriptException("Script file '" + file + "' not found", + throw new ScriptException("Script file '" + file + "' not found", e); + } catch (Exception e) { + throw new ScriptException("Error while running script'" + file + "': " + e.getMessage(), e); } - catch (Exception e) { - throw new ScriptException( - "Error while running script'" + file + "': " + e - .getMessage(), e); - } } - @Override public String getName() { + @Override + public String getName() { return "script"; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptException.java index 00453abd852..e6a636dc42f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.parser.Location; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptLineParser.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptLineParser.java index 634e5ad2272..0ecc74f90b6 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptLineParser.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptLineParser.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.io.BufferedReader; @@ -54,8 +57,7 @@ class ScriptLineParser { private int readChars; /** - * While within a string literal, this stores the character with which the - * string has started. + * While within a string literal, this stores the character with which the string has started. */ private int stringInitChar; @@ -71,7 +73,7 @@ enum State { AFTER_EQ, /* after having observed a "\"" and before seeing it again */ IN_QUOTE, - /* within an identifier after "=" (to distinguish from IN_ID)*/ + /* within an identifier after "=" (to distinguish from IN_ID) */ IN_UNQUOTE, /* within a (single line) comment */ IN_COMMENT @@ -84,6 +86,7 @@ public ScriptLineParser(Reader reader) { /** * Creates a ScriptLineParser that reads from the given resource. + * * @param fileURL the resource to read from * @throws IOException if opening an InputStream from the resource fails */ @@ -102,123 +105,172 @@ public Map parseCommand() throws IOException, ScriptException { State stateBeforeComment = null; int impCounter = 1; - while(true) { + while (true) { int c = reader.read(); - if(c == '\n') { + if (c == '\n') { line++; col = 1; } else { - col ++; + col++; } - pos ++; + pos++; - switch(c) { + switch (c) { case -1: - if(sb.length() > 0 || key != null || !result.isEmpty()) { + if (sb.length() > 0 || key != null || !result.isEmpty()) { throw new ScriptException("Trailing characters at end of script (missing ';'?)", fileURL, line, col); } return null; case '=': - switch(state) { - case IN_ID: state = State.AFTER_EQ; key = sb.toString(); sb.setLength(0); break; - case IN_QUOTE: sb.append((char)c); break; - case IN_COMMENT: break; - default: exc(c); + switch (state) { + case IN_ID: + state = State.AFTER_EQ; + key = sb.toString(); + sb.setLength(0); + break; + case IN_QUOTE: + sb.append((char) c); + break; + case IN_COMMENT: + break; + default: + exc(c); } break; case ' ': case '\t': case '\n': - switch(state) { - case IN_ID: state = State.INIT; + switch (state) { + case IN_ID: + state = State.INIT; result.put("#" + (impCounter++), sb.toString()); - sb.setLength(0); break; - case IN_QUOTE: sb.append((char)c); break; - case IN_UNQUOTE: state = State.INIT; - result.put(key, sb.toString()); sb.setLength(0); break; - case IN_COMMENT: if(c=='\n') { state = stateBeforeComment; } break; - default: break; + sb.setLength(0); + break; + case IN_QUOTE: + sb.append((char) c); + break; + case IN_UNQUOTE: + state = State.INIT; + result.put(key, sb.toString()); + sb.setLength(0); + break; + case IN_COMMENT: + if (c == '\n') { + state = stateBeforeComment; + } + break; + default: + break; } break; - case '\r': break; + case '\r': + break; case '"': case '\'': - switch(state) { - case INIT: state = State.IN_QUOTE; + switch (state) { + case INIT: + state = State.IN_QUOTE; stringInitChar = c; - key = "#" + (impCounter++); break; - case AFTER_EQ: state = State.IN_QUOTE; + key = "#" + (impCounter++); + break; + case AFTER_EQ: + state = State.IN_QUOTE; stringInitChar = c; break; case IN_QUOTE: - if(stringInitChar == c) { + if (stringInitChar == c) { state = State.INIT; result.put(key, sb.toString()); sb.setLength(0); } else { - sb.append((char)c); + sb.append((char) c); } break; - case IN_COMMENT: break; - default: exc(c); + case IN_COMMENT: + break; + default: + exc(c); } break; case '#': - switch(state) { - case IN_QUOTE: sb.append((char)c); break; - case IN_COMMENT: break; - default: stateBeforeComment = state; state = State.IN_COMMENT; + switch (state) { + case IN_QUOTE: + sb.append((char) c); + break; + case IN_COMMENT: + break; + default: + stateBeforeComment = state; + state = State.IN_COMMENT; } break; case ';': - switch(state) { - case IN_QUOTE: sb.append((char)c); break; - case IN_COMMENT: break; - case IN_ID: result.put("#" + (impCounter++), sb.toString()); break; - case INIT: break; - case IN_UNQUOTE: result.put(key, sb.toString()); break; - default: exc(c); + switch (state) { + case IN_QUOTE: + sb.append((char) c); + break; + case IN_COMMENT: + break; + case IN_ID: + result.put("#" + (impCounter++), sb.toString()); + break; + case INIT: + break; + case IN_UNQUOTE: + result.put(key, sb.toString()); + break; + default: + exc(c); } - if(state != State.IN_COMMENT && state != State.IN_QUOTE) { + if (state != State.IN_COMMENT && state != State.IN_QUOTE) { result.put(LITERAL_KEY, cmdBuilder.toString().trim()); return result; } break; default: - switch(state) { + switch (state) { case INIT: - case IN_ID: state = State.IN_ID; // fallthru intended! - if(!isIDChar(c)) { + case IN_ID: + state = State.IN_ID; // fallthru intended! + if (!isIDChar(c)) { exc(c); } - sb.append((char)c); break; + sb.append((char) c); + break; case IN_UNQUOTE: - case AFTER_EQ: state = State.IN_UNQUOTE; - if(!isIDChar(c)) { + case AFTER_EQ: + state = State.IN_UNQUOTE; + if (!isIDChar(c)) { exc(c); } - sb.append((char)c); break; - case IN_QUOTE: sb.append((char)c); break; - case IN_COMMENT: break; - default: assert false; + sb.append((char) c); + break; + case IN_QUOTE: + sb.append((char) c); + break; + case IN_COMMENT: + break; + default: + assert false; } } - if(state != State.IN_COMMENT) { - cmdBuilder.append((char)c); + if (state != State.IN_COMMENT) { + cmdBuilder.append((char) c); } - readChars ++; + readChars++; } } private boolean isIDChar(int c) { - return Character.isLetterOrDigit(c) || ADMISSIBLE_CHARS.indexOf((char)c) > -1; + return Character.isLetterOrDigit(c) || ADMISSIBLE_CHARS.indexOf((char) c) > -1; } private void exc(int c) throws ScriptException { - throw new ScriptException(String.format("Unexpected char '%s' at %d:%d", (char) c, line, col), - fileURL, line, col); + throw new ScriptException( + String.format("Unexpected char '%s' at %d:%d", (char) c, line, col), fileURL, line, + col); } /** diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptNode.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptNode.java index a93f1e5d594..efa8530f9c1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptNode.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptNode.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.proof.Node; @@ -29,12 +32,10 @@ public ScriptNode(ScriptNode parent, Map command, int fromPos, i public void addNode(ScriptNode node) { children.add(node); } - + public void dump(int indent) { - LOGGER.debug("{} {} {}", - " ".repeat(indent), - proofNode == null ? "xxx" : proofNode.serialNr(), - command); + LOGGER.debug("{} {} {}", " ".repeat(indent), + proofNode == null ? "xxx" : proofNode.serialNr(), command); for (ScriptNode child : children) { child.dump(indent + 1); } @@ -63,7 +64,7 @@ public int getFromPos() { public int getToPos() { return toPos; } - + public void clearChildren() { children.clear(); } @@ -75,10 +76,12 @@ public Throwable getEncounteredException() { public void setEncounteredException(Throwable encounteredException) { this.encounteredException = encounteredException; } - public ScriptNode getParent(){ + + public ScriptNode getParent() { return parent; } - public boolean isRoot(){ + + public boolean isRoot() { return (parent == null); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptTreeParser.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptTreeParser.java index 44c53c66f7b..c063243f6d4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptTreeParser.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/ScriptTreeParser.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.io.IOException; @@ -9,24 +12,24 @@ public class ScriptTreeParser { public static ScriptNode parse(Reader reader) throws IOException, ScriptException { - + ScriptNode root = null; ScriptNode last = null; Stack branchStack = new Stack<>(); - + ScriptLineParser lineParser = new ScriptLineParser(reader); - while(true) { + while (true) { int from = lineParser.getPosition(); Map command = lineParser.parseCommand(); int to = lineParser.getPosition(); - if(command == null) { + if (command == null) { return root; } - switch(command.get(ScriptLineParser.COMMAND_KEY)) { + switch (command.get(ScriptLineParser.COMMAND_KEY)) { case "branches": branchStack.push(last); break; @@ -39,9 +42,9 @@ public static ScriptNode parse(Reader reader) throws IOException, ScriptExceptio break; default: ScriptNode node = new ScriptNode(last, command, from, to); - if(root == null) { + if (root == null) { root = node; - } else if(last == null) { + } else if (last == null) { throw new ScriptException("unexpected last"); } else { last.addNode(node); @@ -54,12 +57,11 @@ public static ScriptNode parse(Reader reader) throws IOException, ScriptExceptio } public static void main(String[] args) throws IOException, ScriptException { - - ScriptNode root = - ScriptTreeParser.parse(new InputStreamReader(System.in)); - + + ScriptNode root = ScriptTreeParser.parse(new InputStreamReader(System.in)); + root.dump(0); - + } - + } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SelectCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SelectCommand.java index 722c0a07bb6..e59fc1b51d1 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SelectCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SelectCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Deque; @@ -23,18 +26,15 @@ public SelectCommand() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(Parameters args) - throws ScriptException, InterruptedException { + public void execute(Parameters args) throws ScriptException, InterruptedException { Goal g; - if (args.number != null && args.formula == null - && args.branch == null) { + if (args.number != null && args.formula == null && args.branch == null) { ImmutableList goals = state.getProof().openEnabledGoals(); if (args.number >= 0) { @@ -42,11 +42,9 @@ public void execute(Parameters args) } else { g = goals.take(goals.size() + args.number).head(); } - } else if (args.formula != null && args.number == null - && args.branch == null) { + } else if (args.formula != null && args.number == null && args.branch == null) { g = findGoalWith(args.formula, state.getProof()); - } else if (args.branch != null && args.formula == null - && args.number == null) { + } else if (args.branch != null && args.formula == null && args.number == null) { g = findGoalWith(args.branch, state.getProof()); } else { throw new ScriptException( @@ -56,12 +54,9 @@ public void execute(Parameters args) state.setGoal(g); } - private Goal findGoalWith(String branchTitle, Proof proof) - throws ScriptException { - return findGoalWith( - node -> Optional.ofNullable(node.getNodeInfo().getBranchLabel()) - .orElse("").equals(branchTitle), - node -> getFirstSubtreeGoal(node, proof), proof); + private Goal findGoalWith(String branchTitle, Proof proof) throws ScriptException { + return findGoalWith(node -> Optional.ofNullable(node.getNodeInfo().getBranchLabel()) + .orElse("").equals(branchTitle), node -> getFirstSubtreeGoal(node, proof), proof); } private static Goal getFirstSubtreeGoal(Node node, Proof proof) { @@ -86,16 +81,13 @@ private static Goal getFirstSubtreeGoal(Node node, Proof proof) { return null; } - private Goal findGoalWith(Term formula, Proof proof) - throws ScriptException { - return findGoalWith( - node -> node.leaf() && contains(node.sequent(), formula), + private Goal findGoalWith(Term formula, Proof proof) throws ScriptException { + return findGoalWith(node -> node.leaf() && contains(node.sequent(), formula), node -> EngineState.getGoal(proof.openGoals(), node), proof); } - private Goal findGoalWith(Function filter, - Function goalRetriever, Proof proof) - throws ScriptException { + private Goal findGoalWith(Function filter, Function goalRetriever, + Proof proof) throws ScriptException { Deque choices = new LinkedList(); Node node = proof.root(); @@ -141,8 +133,7 @@ private Goal findGoalWith(Function filter, } private boolean contains(Sequent seq, Term formula) { - return contains(seq.antecedent(), formula) - || contains(seq.succedent(), formula); + return contains(seq.antecedent(), formula) || contains(seq.succedent(), formula); } private boolean contains(Semisequent semiseq, Term formula) { @@ -164,8 +155,8 @@ public class Parameters { @Option(value = "formula", required = false) public Term formula; /** - * The number of the goal to select, starts with 0. - * Negative indices are also allowed: -1 is the last goal, -2 the second-to-last, etc. + * The number of the goal to select, starts with 0. Negative indices are also allowed: -1 is + * the last goal, -2 the second-to-last, etc. */ @Option(value = "number", required = false) public Integer number; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetCommand.java index 4864db1c068..d9c32fb6ab5 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Iterator; @@ -33,8 +36,8 @@ public void execute(Parameters args) throws ScriptException, InterruptedExceptio final Proof proof = state.getProof(); - final StrategyProperties newProps = proof.getSettings().getStrategySettings() - .getActiveStrategyProperties(); + final StrategyProperties newProps = + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); if (args.oneStepSimplification != null) { newProps.setProperty(StrategyProperties.OSS_OPTIONS_KEY, @@ -53,11 +56,10 @@ public void execute(Parameters args) throws ScriptException, InterruptedExceptio } /* - * NOTE (DS, 2020-04-08): You have to update most importantly the strategy's - * strategy properties. It does not suffice to update the proof's properties. - * Otherwise, changes are displayed, but have no effect after a proof has - * already been started. For this, the following quite complicated - * implementation, which is inspired by StrategySelectionView. + * NOTE (DS, 2020-04-08): You have to update most importantly the strategy's strategy + * properties. It does not suffice to update the proof's properties. Otherwise, changes are + * displayed, but have no effect after a proof has already been started. For this, the following + * quite complicated implementation, which is inspired by StrategySelectionView. */ private void updateStrategySettings(StrategyProperties p) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetEchoCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetEchoCommand.java index 03d4b426692..a8010012076 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetEchoCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetEchoCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -6,8 +9,7 @@ import de.uka.ilkd.key.macros.scripts.meta.Option; /** - * A simple "echo" command for giving feedback to human observers during lengthy - * executions. + * A simple "echo" command for giving feedback to human observers during lengthy executions. */ public class SetEchoCommand extends AbstractCommand { public SetEchoCommand() { @@ -20,15 +22,14 @@ public String getName() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(AbstractUserInterfaceControl uiControl, Parameters args, - EngineState state) throws ScriptException, InterruptedException { + public void execute(AbstractUserInterfaceControl uiControl, Parameters args, EngineState state) + throws ScriptException, InterruptedException { if ("on".equalsIgnoreCase(args.command)) { state.setEchoOn(true); } else { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetFailOnClosedCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetFailOnClosedCommand.java index 988c4dc26b8..5b692e3a96d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetFailOnClosedCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SetFailOnClosedCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -6,12 +9,11 @@ import de.uka.ilkd.key.macros.scripts.meta.Option; /** - * Sets the behavior if an already closed proof is encountered: Either throw an - * exception (default behavior, sensible for specially tailored scripts for - * which a prematurely closed proof is unexpected) or peacefully terminate (if - * the script addresses different problems of different complexity in a - * try-and-error manner, etc.). - * + * Sets the behavior if an already closed proof is encountered: Either throw an exception (default + * behavior, sensible for specially tailored scripts for which a prematurely closed proof is + * unexpected) or peacefully terminate (if the script addresses different problems of different + * complexity in a try-and-error manner, etc.). + * * @author Dominic Steinhoefel */ public class SetFailOnClosedCommand extends AbstractCommand { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SkipCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SkipCommand.java index 02aeb19bafd..dc749aaf406 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SkipCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/SkipCommand.java @@ -1,15 +1,19 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.control.AbstractUserInterfaceControl; public class SkipCommand extends NoArgumentCommand { - @Override public void execute(AbstractUserInterfaceControl uiControl, - Void args, EngineState stateMap) + @Override + public void execute(AbstractUserInterfaceControl uiControl, Void args, EngineState stateMap) throws ScriptException, InterruptedException { } - @Override public String getName() { + @Override + public String getName() { return "skip"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/TryCloseCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/TryCloseCommand.java index 71c9bf67a8b..165548d9965 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/TryCloseCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/TryCloseCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import java.util.Map; @@ -17,33 +20,30 @@ *
    13. #2: STRING the number of the branch which should be closed
    14. * * - * If #2 is not given or not a number, the TryClose macro is applied to all open - * goals. + * If #2 is not given or not a number, the TryClose macro is applied to all open goals. */ -public class TryCloseCommand - extends AbstractCommand { +public class TryCloseCommand extends AbstractCommand { public TryCloseCommand() { super(TryCloseArguments.class); } - @Override public TryCloseArguments evaluateArguments(EngineState state, - Map arguments) throws Exception { + @Override + public TryCloseArguments evaluateArguments(EngineState state, Map arguments) + throws Exception { return ValueInjector.injection(this, new TryCloseArguments(), arguments); } - @Override public void execute(TryCloseArguments args) - throws ScriptException, InterruptedException { + @Override + public void execute(TryCloseArguments args) throws ScriptException, InterruptedException { - TryCloseMacro macro = args.steps == null ? - new TryCloseMacro() : - new TryCloseMacro(args.steps); + TryCloseMacro macro = + args.steps == null ? new TryCloseMacro() : new TryCloseMacro(args.steps); boolean branch = "branch".equals(args.branch); Node target; if (branch) { target = state.getFirstOpenAutomaticGoal().node(); - } - else { + } else { try { int num = Integer.parseInt(args.branch); ImmutableList goals = state.getProof().openEnabledGoals(); @@ -60,18 +60,16 @@ public TryCloseCommand() { try { macro.applyTo(uiControl, target, null, uiControl); if (args.assertClosed && !target.isClosed()) { - throw new ScriptException( - "Could not close subtree of node " + target.serialNr()); + throw new ScriptException("Could not close subtree of node " + target.serialNr()); } - } - catch (Exception e) { - throw new ScriptException( - "tryclose caused an exception: " + e.getMessage(), e); + } catch (Exception e) { + throw new ScriptException("tryclose caused an exception: " + e.getMessage(), e); } } - @Override public String getName() { + @Override + public String getName() { return "tryclose"; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/UnhideCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/UnhideCommand.java index 3a4743c3118..c63b708e298 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/UnhideCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/UnhideCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts; import de.uka.ilkd.key.logic.Name; @@ -22,6 +25,7 @@ * Proof script command to insert a formula hidden earlier in the proof. * * Usage: + * *
        *     unhide "f1, f2 ==> f3, f4"
        * 
      @@ -46,15 +50,13 @@ public UnhideCommand() { } @Override - public Parameters evaluateArguments(EngineState state, - Map arguments) throws Exception { - return state.getValueInjector().inject(this, new Parameters(), - arguments); + public Parameters evaluateArguments(EngineState state, Map arguments) + throws Exception { + return state.getValueInjector().inject(this, new Parameters(), arguments); } @Override - public void execute(Parameters args) - throws ScriptException, InterruptedException { + public void execute(Parameters args) throws ScriptException, InterruptedException { Goal goal = state.getFirstOpenAutomaticGoal(); @@ -71,12 +73,12 @@ public void execute(Parameters args) SchemaVariable b = app.instantiations().svIterator().next(); Object bInst = app.instantiations().getInstantiation(b); boolean succApp = app.taclet().goalTemplates().head().sequent().antecedent().isEmpty(); - if(succApp) { + if (succApp) { if (succs.contains(bInst)) { goal.apply(app); } } else { - if(antes.contains(bInst)) { + if (antes.contains(bInst)) { goal.apply(app); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentRequiredException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentRequiredException.java index eca9e2d878d..4b88fb48680 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentRequiredException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentRequiredException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** @@ -12,6 +15,7 @@ public class ArgumentRequiredException extends InjectionException { /** * An argument required exception with no cause (to display). + * * @param message the respective String message to be passed. * @param meta the proof script argument. */ diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentsLifter.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentsLifter.java index 189bba1b70a..022f4b04631 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentsLifter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ArgumentsLifter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import java.lang.reflect.Field; @@ -11,28 +14,24 @@ * @version 1 (21.04.17) */ public final class ArgumentsLifter { - //private static final Map TYPE_MAP = new HashMap<>(); + // private static final Map TYPE_MAP = new HashMap<>(); - private ArgumentsLifter() { - } + private ArgumentsLifter() {} - public static List - inferScriptArguments(Class clazz, - ProofScriptCommand command) { + public static List inferScriptArguments(Class clazz, + ProofScriptCommand command) { List args = new ArrayList<>(); for (Field field : clazz.getDeclaredFields()) { Option option = field.getDeclaredAnnotation(Option.class); if (option != null) { args.add(lift(option, field)); - } - else { + } else { Flag flag = field.getDeclaredAnnotation(Flag.class); if (flag != null) { args.add(lift(flag, field)); - } - else { + } else { Varargs vargs = field.getDeclaredAnnotation(Varargs.class); - if (vargs!=null) { + if (vargs != null) { args.add(lift(vargs, field)); } } @@ -66,4 +65,4 @@ private static ProofScriptArgument lift(Option option, Field field) { private static ProofScriptArgument lift(Flag flag, Field field) { throw new IllegalStateException("not implemented"); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ConversionException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ConversionException.java index 34056acfbb4..58cd47e2bff 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ConversionException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ConversionException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** @@ -10,22 +13,22 @@ public class ConversionException extends InjectionException { /** * A conversion exception with no cause (to display). + * * @param message the respective String message to be passed. * @param argument the proof script argument. */ - public ConversionException(String message, - ProofScriptArgument argument) { + public ConversionException(String message, ProofScriptArgument argument) { super(message, argument); } /** * A conversion exception with a cause to be displayed. + * * @param message the respective String message to be passed. * @param cause the cause of the exception. * @param argument the proof script argument. */ - public ConversionException(String message, Throwable cause, - ProofScriptArgument argument) { + public ConversionException(String message, Throwable cause, ProofScriptArgument argument) { super(message, cause, argument); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/DescriptionFacade.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/DescriptionFacade.java index 1f3da8dc6a6..2fe954ef250 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/DescriptionFacade.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/DescriptionFacade.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import de.uka.ilkd.key.macros.scripts.ProofScriptCommand; @@ -30,8 +33,7 @@ public final class DescriptionFacade { */ private static Properties properties = null; - private DescriptionFacade() { - } + private DescriptionFacade() {} /** * Lazy loading of the properties. @@ -52,8 +54,8 @@ public static Properties getProperties() { } /** - * Looks up the documentation for the given command in the properties file. - * If no documentation is available an empty string is returned. + * Looks up the documentation for the given command in the properties file. If no documentation + * is available an empty string is returned. * * @param cmd non-null proof script command * @return a non-null string @@ -64,15 +66,15 @@ public static String getDocumentation(ProofScriptCommand cmd) { } /** - * Looks up the documentation for the given proof script argument. - * If no documentation is available an empty string is returned. + * Looks up the documentation for the given proof script argument. If no documentation is + * available an empty string is returned. * * @param arg non-null proof script argument * @return a string or null, if {@code arg} is null or {@code arg.getCommand} returns null * @see ProofScriptArgument#getDocumentation() */ public static String getDocumentation(ProofScriptArgument arg) { - if(arg==null || arg.getCommand() == null) { + if (arg == null || arg.getCommand() == null) { return null; } String key = arg.getCommand().getName() + "." + arg.getName(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Flag.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Flag.java index 63f61a24b98..cafd8a78636 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Flag.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Flag.java @@ -1,13 +1,16 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** * Currently not implemented in {@link ArgumentsLifter} *

      - * Used to mark flag for proof script commands. - * For example "instantitate formula='...' ... hide" is denoted as + * Used to mark flag for proof script commands. For example "instantitate formula='...' ... hide" is + * denoted as *

      *

      - * @Flag(name="hide"}
      + * @Flag(name="hide"}
        * boolean hideFormula.
        * 
      *

      diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionException.java index 3801e1e5d46..c4a33e98e87 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** @@ -6,36 +9,37 @@ * @author Alexander Weigl * @version 1 (02.05.17) */ -public class InjectionException extends Exception{ +public class InjectionException extends Exception { private static final long serialVersionUID = 4922701573932568352L; private final ProofScriptArgument argument; /** * An injection reflection exception with no cause (to display). + * * @param message the respective String message to be passed. * @param argument the proof script argument. */ - public InjectionException(String message, - ProofScriptArgument argument) { + public InjectionException(String message, ProofScriptArgument argument) { super(message); this.argument = argument; } /** * An injection exception with a cause to be displayed. + * * @param message the respective String message to be passed. * @param cause the cause of the exception. * @param argument the proof script argument. */ - public InjectionException(String message, Throwable cause, - ProofScriptArgument argument) { + public InjectionException(String message, Throwable cause, ProofScriptArgument argument) { super(message, cause); this.argument = argument; } /** * Get the (proof script) argument of this injection exception. + * * @return the proof script argument. */ public ProofScriptArgument getArgument() { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionReflectionException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionReflectionException.java index 5f56c281e29..d2e5b206eac 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionReflectionException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/InjectionReflectionException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** @@ -10,22 +13,23 @@ public class InjectionReflectionException extends InjectionException { /** * An injection reflection exception with no cause (to display). + * * @param message the respective String message to be passed. * @param argument the proof script argument. */ - public InjectionReflectionException(String message, - ProofScriptArgument argument) { + public InjectionReflectionException(String message, ProofScriptArgument argument) { super(message, argument); } /** * An injection reflection exception with a cause to be displayed. + * * @param message the respective String message to be passed. * @param cause the cause of the exception. * @param argument the proof script argument. */ public InjectionReflectionException(String message, Throwable cause, - ProofScriptArgument argument) { + ProofScriptArgument argument) { super(message, cause, argument); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/NoSpecifiedConverterException.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/NoSpecifiedConverterException.java index 7a1d3e40023..d7594400622 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/NoSpecifiedConverterException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/NoSpecifiedConverterException.java @@ -1,11 +1,13 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** * Indicates a missing converter. *

      - * This is exception is raised if {@link StringConverter} is found for string to the - * desired type {@code T}. - * The desired type is in the stored {@link ProofScriptArgument}. + * This is exception is raised if {@link StringConverter} is found for string to the desired type + * {@code T}. The desired type is in the stored {@link ProofScriptArgument}. * * @author Alexander Weigl * @version 1 (02.05.17) @@ -17,23 +19,22 @@ public class NoSpecifiedConverterException extends InjectionException { /** * Creates an exception with the given {@code message} and {@code argument}. * - * @param message a non-null string + * @param message a non-null string * @param argument the argument for which the conversion failed */ - public NoSpecifiedConverterException(String message, - ProofScriptArgument argument) { + public NoSpecifiedConverterException(String message, ProofScriptArgument argument) { super(message, argument); } /** * Creates an exception with the given arguments. * - * @param message a non-null string - * @param cause a cause of this exception + * @param message a non-null string + * @param cause a cause of this exception * @param argument the argument for which the conversion failed */ public NoSpecifiedConverterException(String message, Throwable cause, - ProofScriptArgument argument) { + ProofScriptArgument argument) { super(message, cause, argument); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Option.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Option.java index f832a481236..bb341dedcc8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Option.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Option.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import java.lang.annotation.ElementType; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ProofScriptArgument.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ProofScriptArgument.java index f8c707d62a9..79205d95bf3 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ProofScriptArgument.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ProofScriptArgument.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import de.uka.ilkd.key.macros.scripts.ProofScriptCommand; @@ -86,9 +89,7 @@ public boolean equals(Object o) { if (flag != that.flag) { return false; } - if (command != null ? - !command.equals(that.command) : - that.command != null) { + if (command != null ? !command.equals(that.command) : that.command != null) { return false; } if (name != null ? !name.equals(that.name) : that.name != null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/StringConverter.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/StringConverter.java index 76003ea839f..71b232bdb2d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/StringConverter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/StringConverter.java @@ -1,8 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** - * A {@link StringConverter} translates a textual representation - * to an instance of {@code T}. + * A {@link StringConverter} translates a textual representation to an instance of {@code T}. * * @param * @author Alexander Weigl diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Type.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Type.java index 968f00edc58..689e210d0ad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Type.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Type.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; /** diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ValueInjector.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ValueInjector.java index fa95bb358af..76b7c03ec36 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ValueInjector.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/ValueInjector.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import de.uka.ilkd.key.macros.scripts.ProofScriptCommand; @@ -22,36 +25,36 @@ public class ValueInjector { /** * A mapping between desired types and suitable @{@link StringConverter}. *

      - * Should be

      T --> StringConverter
      + * Should be + * + *
      +     * T --> StringConverter
      +     * 
      */ private Map converters = new HashMap<>(); /** - * Injects the given {@code arguments} in the {@code obj}. - * For more details see {@link #inject(ProofScriptCommand, Object, Map)} + * Injects the given {@code arguments} in the {@code obj}. For more details see + * {@link #inject(ProofScriptCommand, Object, Map)} * - * @param command a proof script command - * @param obj a parameter class with annotation + * @param command a proof script command + * @param obj a parameter class with annotation * @param arguments a non-null map of string pairs * @param an arbitrary type * @return the same object as {@code obj} - * @throws ArgumentRequiredException a required argument was not given in {@code arguments} - * @throws InjectionReflectionException an access on some reflection methods occurred + * @throws ArgumentRequiredException a required argument was not given in {@code arguments} + * @throws InjectionReflectionException an access on some reflection methods occurred * @throws NoSpecifiedConverterException unknown type for the current converter map - * @throws ConversionException an converter could not translate the given value in - * arguments + * @throws ConversionException an converter could not translate the given value in arguments */ - public static T injection(ProofScriptCommand command, - T obj, - Map arguments) - throws ArgumentRequiredException, InjectionReflectionException, - NoSpecifiedConverterException, ConversionException { + public static T injection(ProofScriptCommand command, T obj, + Map arguments) throws ArgumentRequiredException, + InjectionReflectionException, NoSpecifiedConverterException, ConversionException { return getInstance().inject(command, obj, arguments); } /** - * Returns the default instance of a {@link ValueInjector} - * Use with care. No multi-threading. + * Returns the default instance of a {@link ValueInjector} Use with care. No multi-threading. * * @return a static reference to the default converter. * @see #createDefault() @@ -64,8 +67,8 @@ public static ValueInjector getInstance() { } /** - * Returns a fresh instance of a {@link ValueInjector} with the support - * for basic primitive data types. + * Returns a fresh instance of a {@link ValueInjector} with the support for basic primitive data + * types. * * @return a fresh instance */ @@ -90,24 +93,23 @@ public static ValueInjector createDefault() { /** * Injects the converted version of the given {@code arguments} in the given {@code obj}. * - * @param command a proof script command - * @param obj a non-null instance of a parameter class (with annotation) + * @param command a proof script command + * @param obj a non-null instance of a parameter class (with annotation) * @param arguments a non-null string map - * @param type safety + * @param type safety * @return the same object as {@code obj} - * @throws ArgumentRequiredException a required argument was not given in {@code arguments} - * @throws InjectionReflectionException an access on some reflection methods occurred + * @throws ArgumentRequiredException a required argument was not given in {@code arguments} + * @throws InjectionReflectionException an access on some reflection methods occurred * @throws NoSpecifiedConverterException unknown type for the current converter map - * @throws ConversionException an converter could not translate the given value - * in arguments + * @throws ConversionException an converter could not translate the given value in arguments * @see Option * @see Flag */ public T inject(ProofScriptCommand command, T obj, Map arguments) throws ConversionException, InjectionReflectionException, NoSpecifiedConverterException, ArgumentRequiredException { - List meta = ArgumentsLifter - .inferScriptArguments(obj.getClass(), command); + List meta = + ArgumentsLifter.inferScriptArguments(obj.getClass(), command); List varArgs = new ArrayList<>(meta.size()); List usedKeys = new ArrayList<>(); @@ -154,30 +156,32 @@ private Map getStringMap(Object obj, ProofScriptArgument vara } private void injectIntoField(ProofScriptArgument meta, Map args, Object obj) - throws InjectionReflectionException, ArgumentRequiredException, - ConversionException, NoSpecifiedConverterException { + throws InjectionReflectionException, ArgumentRequiredException, ConversionException, + NoSpecifiedConverterException { final String val = args.get(meta.getName()); if (val == null) { if (meta.isRequired()) { throw new ArgumentRequiredException( - String.format("Argument %s:%s is required, but %s was given. " + - "For comamnd class: '%s'", + String.format( + "Argument %s:%s is required, but %s was given. " + + "For comamnd class: '%s'", meta.getName(), meta.getField().getType(), val, - meta.getCommand().getClass()), meta); + meta.getCommand().getClass()), + meta); } } else { Object value = convert(meta, val); try { - //if (meta.getType() != value.getClass()) - // throw new ConversionException("The typed returned '" + val.getClass() - // + "' from the converter mismatched with the + // if (meta.getType() != value.getClass()) + // throw new ConversionException("The typed returned '" + val.getClass() + // + "' from the converter mismatched with the // type of the field " + meta.getType(), meta); // FIXME: I had to add this, otherwise I would receive an illegal access exception. meta.getField().setAccessible(true); meta.getField().set(obj, value); } catch (IllegalAccessException e) { - throw new InjectionReflectionException("Could not inject values via reflection", - e, meta); + throw new InjectionReflectionException("Could not inject values via reflection", e, + meta); } } } @@ -186,15 +190,14 @@ private Object convert(ProofScriptArgument meta, String val) throws NoSpecifiedConverterException, ConversionException { StringConverter converter = getConverter(meta.getType()); if (converter == null) { - throw new NoSpecifiedConverterException("No converter registered for class: " + - meta.getField().getType(), meta); + throw new NoSpecifiedConverterException( + "No converter registered for class: " + meta.getField().getType(), meta); } try { return converter.convert(val); } catch (Exception e) { - throw new ConversionException( - String.format("Could not convert value %s to type %s", - val, meta.getField().getType()), e, meta); + throw new ConversionException(String.format("Could not convert value %s to type %s", + val, meta.getField().getType()), e, meta); } } @@ -202,8 +205,8 @@ private Object convert(ProofScriptArgument meta, String val) * Registers the given converter for the specified class. * * @param clazz a class - * @param conv a converter for the given class - * @param an arbitrary type + * @param conv a converter for the given class + * @param an arbitrary type */ public void addConverter(Class clazz, StringConverter conv) { converters.put(clazz, conv); @@ -213,7 +216,7 @@ public void addConverter(Class clazz, StringConverter conv) { * Finds a converter for the given class. * * @param clazz a non-null class - * @param an arbitrary type + * @param an arbitrary type * @return null or a suitable converter (registered) converter for the requested class. */ @SuppressWarnings("unchecked") diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Varargs.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Varargs.java index e322224e2d3..5c7cb3e2286 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Varargs.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/meta/Varargs.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.macros.scripts.meta; import java.lang.annotation.ElementType; @@ -13,5 +16,6 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Varargs { Class as() default String.class; + String prefix() default ""; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/package-info.java b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/package-info.java index 678b6efe949..232a2bf0b62 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/package-info.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/macros/scripts/package-info.java @@ -10,4 +10,4 @@ * @author Alexander Weigl * @version 1 (29.03.17) */ -package de.uka.ilkd.key.macros.scripts; \ No newline at end of file +package de.uka.ilkd.key.macros.scripts; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ChoiceInformation.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ChoiceInformation.java index 7942fba8f6b..4cd8a87cc77 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ChoiceInformation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ChoiceInformation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import de.uka.ilkd.key.logic.Choice; @@ -9,8 +12,8 @@ /** * A POJO representing the information on choices in ASTs. *

      - * Notion: A choice, e.g. {@code permission:on} contains a category {@code permission} - * and an option {@code on}. + * Notion: A choice, e.g. {@code permission:on} contains a category {@code permission} and an option + * {@code on}. * * @author Alexander Weigl * @version 1 (12/5/19) @@ -22,8 +25,8 @@ public class ChoiceInformation { private final Map> foundChoicesAndOptions = new HashMap<>(); /** - * This set contains categories were an options was activated. - * Helps to prevent double activation of contradictory options. + * This set contains categories were an options was activated. Helps to prevent double + * activation of contradictory options. */ private final HashSet activatedChoicesCategories = new LinkedHashSet<>(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/DebugKeyLexer.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/DebugKeyLexer.java index 447f8da75f6..96164c33ed4 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/DebugKeyLexer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/DebugKeyLexer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import org.antlr.v4.runtime.CharStreams; @@ -11,8 +14,7 @@ /** * This program is a little for debugging KeY Lexer. *

      - * You can start this problem via gradle: - * + * You can start this problem via gradle: *

        * gradle debugLexer
        * 
      @@ -44,15 +46,14 @@ public DebugKeyLexer(List files) { e.printStackTrace(stream); } return null; - }).filter(Objects::nonNull) - .collect(Collectors.toList()); + }).filter(Objects::nonNull).collect(Collectors.toList()); format = DEFAULT_FORMAT; } public static void main(String[] args) { if (args.length > 0) { - new DebugKeyLexer( - Arrays.stream(args).map(File::new).collect(Collectors.toList())).run(); + new DebugKeyLexer(Arrays.stream(args).map(File::new).collect(Collectors.toList())) + .run(); } else { try (BufferedReader input = new BufferedReader(new InputStreamReader(System.in))) { String tmp; @@ -64,8 +65,7 @@ public static void main(String[] args) { } else { break; } - } - while (true); + } while (true); } catch (IOException e) { e.printStackTrace(); } @@ -77,7 +77,8 @@ public static void debug(String content) { } public static void debug(KeYLexer lexer) { - DebugKeyLexer dkl = new DebugKeyLexer(System.out, DEFAULT_FORMAT, Collections.singleton(lexer)); + DebugKeyLexer dkl = + new DebugKeyLexer(System.out, DEFAULT_FORMAT, Collections.singleton(lexer)); dkl.run(); } @@ -90,12 +91,10 @@ private void run(KeYLexer toks) { Token t; do { t = toks.nextToken(); - stream.format(format, - toks.getLine(), - toks.getVocabulary().getSymbolicName(t.getType()), - toks._mode, - t.getText().replace("\n", "\\n")); - if (t.getType() == KeYLexer.ERROR_CHAR) stream.println("!!ERROR!!"); + stream.format(format, toks.getLine(), toks.getVocabulary().getSymbolicName(t.getType()), + toks._mode, t.getText().replace("\n", "\\n")); + if (t.getType() == KeYLexer.ERROR_CHAR) + stream.println("!!ERROR!!"); } while (t.getType() != CommonToken.EOF); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java index 35e8f9aab59..c2d1324f46e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import de.uka.ilkd.key.nparser.builder.BuilderHelpers; @@ -19,9 +22,8 @@ import java.net.URL; /** - * This is a monad around the parse tree. - * We use this class to hide the {@link org.antlr.v4.runtime.ParserRuleContext} - * from the rest of the Key system. + * This is a monad around the parse tree. We use this class to hide the + * {@link org.antlr.v4.runtime.ParserRuleContext} from the rest of the Key system. * *

      * To obtain an KeYAst use the {@link ParsingFacade#getParseRuleContext(KeyAst)}. @@ -52,24 +54,22 @@ public static class File extends KeyAst { super(ctx); } - public @Nullable - ProofSettings findProofSettings() { + public @Nullable ProofSettings findProofSettings() { ProofSettings settings = new ProofSettings(ProofSettings.DEFAULT_SETTINGS); if (ctx.decls() != null && ctx.decls().pref != null) { - String text = StringUtil.trim(ctx.decls().pref.s.getText(), '"') - .replace("\\\\:", ":"); + String text = + StringUtil.trim(ctx.decls().pref.s.getText(), '"').replace("\\\\:", ":"); settings.loadSettingsFromString(text); } return settings; } - public @Nullable - Triple findProofScript() { + public @Nullable Triple findProofScript() { if (ctx.problem() != null && ctx.problem().proofScript() != null) { KeYParser.ProofScriptContext pctx = ctx.problem().proofScript(); String text = pctx.ps.getText(); - return new Triple<>(StringUtil.trim(text, '"'), - pctx.ps.getLine(), pctx.ps.getCharPositionInLine()); + return new Triple<>(StringUtil.trim(text, '"'), pctx.ps.getLine(), + pctx.ps.getCharPositionInLine()); } return null; } @@ -100,8 +100,8 @@ public Token findProof() { } /** - * Extracts the decls and taclets into a string. - * This method is required for saving and loading proofs. + * Extracts the decls and taclets into a string. This method is required for saving and + * loading proofs. */ public String getProblemHeader() { final KeYParser.DeclsContext decls = ctx.decls(); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyIO.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyIO.java index 3d2e19801d5..5e1de137ffe 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyIO.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyIO.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import de.uka.ilkd.key.java.Services; @@ -32,8 +35,8 @@ import static de.uka.ilkd.key.nparser.ParsingFacade.parseFiles; /** - * This facade provides high level access to parse and - * interpret key files or input strings into declarations, proof, problem, terms. + * This facade provides high level access to parse and interpret key files or input strings into + * declarations, proof, problem, terms. *

      * This classes encapsulates the {@link Services}, {@link NamespaceSet} for {@link SchemaVariable}s. * It also modifies them during interpretation. @@ -74,8 +77,7 @@ public KeyIO() { * @return a valid term * @throws BuildingException if an unrecoverable error during construction or parsing happened */ - public @Nonnull - Term parseExpression(@Nonnull String expr) { + public @Nonnull Term parseExpression(@Nonnull String expr) { return parseExpression(CharStreams.fromString(expr)); } @@ -86,8 +88,7 @@ Term parseExpression(@Nonnull String expr) { * @return a valid term * @throws BuildingException if an unrecoverable error during construction or parsing happened */ - public @Nonnull - Term parseExpression(@Nonnull CharStream stream) { + public @Nonnull Term parseExpression(@Nonnull CharStream stream) { KeyAst.Term ctx = ParsingFacade.parseExpression(stream); ExpressionBuilder visitor = new ExpressionBuilder(services, nss); visitor.setAbbrevMap(abbrevMap); @@ -106,8 +107,7 @@ Term parseExpression(@Nonnull CharStream stream) { * @return a valid sequent * @throws BuildingException if an unrecoverable error during construction or parsing happened */ - public @Nonnull - Sequent parseSequence(@Nonnull CharStream stream) { + public @Nonnull Sequent parseSequence(@Nonnull CharStream stream) { KeyAst.Seq ctx = ParsingFacade.parseSequent(stream); ExpressionBuilder visitor = new ExpressionBuilder(services, nss); if (schemaNamespace != null) @@ -208,8 +208,8 @@ public List resetWarnings() { } /** - * Loading of complete KeY files into the given schema. - * Supports recursive loading, but does not provide support for Java and Java type informations. + * Loading of complete KeY files into the given schema. Supports recursive loading, but does not + * provide support for Java and Java type informations. *

      * Little sister of {@link ProblemInitializer}. */ @@ -233,7 +233,8 @@ public Namespace getSchemaNamespace() { } public List loadComplete() throws IOException { - if (ctx.isEmpty()) parseFile(); + if (ctx.isEmpty()) + parseFile(); loadDeclarations(); loadSndDegreeDeclarations(); activateLDTs(); @@ -246,7 +247,8 @@ public Loader activateLDTs() { } public ProblemFinder loadCompleteProblem() throws IOException { - if (ctx.isEmpty()) parseFile(); + if (ctx.isEmpty()) + parseFile(); loadDeclarations(); loadSndDegreeDeclarations(); activateLDTs(); @@ -255,7 +257,8 @@ public ProblemFinder loadCompleteProblem() throws IOException { } public Loader parseFile() throws IOException { - if (!ctx.isEmpty()) return this; + if (!ctx.isEmpty()) + return this; long start = System.currentTimeMillis(); if (resource != null) ctx = parseFiles(resource); @@ -308,14 +311,16 @@ public Loader loadSndDegreeDeclarations() { } public ProblemFinder loadProblem() { - if (ctx.isEmpty()) throw new IllegalStateException(); + if (ctx.isEmpty()) + throw new IllegalStateException(); ProblemFinder pf = new ProblemFinder(services, nss); ctx.get(0).accept(pf); return pf; } public List loadTaclets() { - if (ctx.isEmpty()) throw new IllegalStateException(); + if (ctx.isEmpty()) + throw new IllegalStateException(); List parsers = ctx.stream().map(it -> new TacletPBuilder(services, nss)) .collect(Collectors.toList()); long start = System.currentTimeMillis(); @@ -336,7 +341,7 @@ public List loadTaclets() { } public Term getProblem() { - //TODO weigl tbd + // TODO weigl tbd return null; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ParsingFacade.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ParsingFacade.java index 99b0d016897..a176aa4f636 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ParsingFacade.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ParsingFacade.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import de.uka.ilkd.key.nparser.builder.ChoiceFinder; @@ -24,7 +27,8 @@ /** * This facade provides low-level access to the ANTLR4 Parser and Lexer. *

      - * You should only use it if you need access to the parse trees instead of terms or taclet structure. + * You should only use it if you need access to the parse trees instead of terms or taclet + * structure. * * @author Alexander Weigl * @version 1 (19.08.19) @@ -32,12 +36,12 @@ public final class ParsingFacade { private static final Logger LOGGER = LoggerFactory.getLogger(ParsingFacade.class); - private ParsingFacade() { - } + private ParsingFacade() {} /** * Use this function to retrieve the {@link ParserRuleContext} inside and {@link KeyAst} object. - * The use of this method is discourage and should be avoided in all high level scenarios. + * The use of this method is discourage and should be avoided in all high level + * scenarios. * * @param ast a key ast object * @param parse tree type @@ -74,8 +78,7 @@ public static List parseFiles(URL url) throws IOException { * * @param ctxs non-null list */ - public static @Nonnull - ChoiceInformation getChoices(@Nonnull List ctxs) { + public static @Nonnull ChoiceInformation getChoices(@Nonnull List ctxs) { ChoiceInformation ci = new ChoiceInformation(); ChoiceFinder finder = new ChoiceFinder(ci); ctxs.forEach(it -> it.accept(finder)); @@ -100,14 +103,9 @@ public static KeYLexer createLexer(CharStream stream) { public static KeyAst.File parseFile(URL url) throws IOException { long start = System.currentTimeMillis(); try (BufferedInputStream is = new BufferedInputStream(url.openStream()); - ReadableByteChannel channel = Channels.newChannel(is)) { - CodePointCharStream stream = CharStreams.fromChannel( - channel, - Charset.defaultCharset(), - 4096, - CodingErrorAction.REPLACE, - url.toString(), - -1); + ReadableByteChannel channel = Channels.newChannel(is)) { + CodePointCharStream stream = CharStreams.fromChannel(channel, Charset.defaultCharset(), + 4096, CodingErrorAction.REPLACE, url.toString(), -1); return parseFile(stream); } finally { long stop = System.currentTimeMillis(); @@ -145,16 +143,15 @@ public static KeyAst.Seq parseSequent(CharStream stream) { } /** - * Translate a given context of a {@code string_value} grammar rule into a the literal value. - * In particular it truncates, and substitutes quote escapes {@code \"}. + * Translate a given context of a {@code string_value} grammar rule into a the literal value. In + * particular it truncates, and substitutes quote escapes {@code \"}. * * @param ctx non-null context * @return non-null string */ - public static @Nonnull - String getValueDocumentation(@Nonnull KeYParser.String_valueContext ctx) { - return ctx.getText().substring(1, ctx.getText().length() - 1) - .replace("\\\"", "\"") + public static @Nonnull String getValueDocumentation( + @Nonnull KeYParser.String_valueContext ctx) { + return ctx.getText().substring(1, ctx.getText().length() - 1).replace("\\\"", "\"") .replace("\\\\", "\\"); } @@ -177,6 +174,6 @@ public static String getValueDocumentation(@Nullable TerminalNode docComment) { return null; } String value = docComment.getText(); - return value.substring(3, value.length() - 2);//remove leading "/*!" and trailing "*/" + return value.substring(3, value.length() - 2);// remove leading "/*!" and trailing "*/" } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProblemInformation.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProblemInformation.java index d49b85b7a9f..6a3392f5248 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProblemInformation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProblemInformation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import javax.annotation.Nonnull; @@ -7,13 +10,12 @@ import java.util.List; /** - * This POJO represents the static information of a KeY problem. - * It can be extracted directly via {@link FindProblemInformation}, - * without any previous interpretation of the AST. + * This POJO represents the static information of a KeY problem. It can be extracted directly via + * {@link FindProblemInformation}, without any previous interpretation of the AST. *

      - * This class contains rather the raw information, e.g. classpaths are not completed with current working dir. - * Rather the values are provided as in the {@link KeyAst.File}. - * Further work may require, like in {@link KeYFile#readJavaPath()}. + * This class contains rather the raw information, e.g. classpaths are not completed with + * current working dir. Rather the values are provided as in the {@link KeyAst.File}. Further work + * may require, like in {@link KeYFile#readJavaPath()}. *

      * * @author weigl @@ -26,14 +28,14 @@ public class ProblemInformation { private final @Nonnull List classpath; /** - * Value of a "\chooseContract". If "\chooseContract" are mentioned in the file, - * but without a value, this field is non-null and empty. + * Value of a "\chooseContract". If "\chooseContract" are mentioned in the file, but without a + * value, this field is non-null and empty. */ private @Nullable String chooseContract; /** - * Value of a "\proofObligation". If "\proofObligation" are mentioned in the file, - * but without a value, this field is non-null and empty. + * Value of a "\proofObligation". If "\proofObligation" are mentioned in the file, but without a + * value, this field is non-null and empty. */ private @Nullable String proofObligation; diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofReplayer.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofReplayer.java index a9f271d3698..1d3d21ed80f 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofReplayer.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofReplayer.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser; import de.uka.ilkd.key.parser.Location; @@ -14,8 +17,8 @@ /** * A short little hack, but completely working and fast, for replaying proofs inside KeY files. *

      - * This class avoids using the {@link KeYParser} and building a parse tree. It uses only the {@link KeYLexer} - * to analyze the sexpr which described the applied taclet application. + * This class avoids using the {@link KeYParser} and building a parse tree. It uses only the + * {@link KeYLexer} to analyze the sexpr which described the applied taclet application. * * @author Alexander Weigl * @version 1 (12/5/19) @@ -25,7 +28,8 @@ public class ProofReplayer { /** * This map is for the translation between symbols in the sexpr and the corresponding proof tag. */ - private static final Map proofSymbolElementId = new LinkedHashMap<>(32); + private static final Map proofSymbolElementId = + new LinkedHashMap<>(32); static { for (IProofFileParser.ProofElementID id : IProofFileParser.ProofElementID.values()) { @@ -33,88 +37,86 @@ public class ProofReplayer { } } - private ProofReplayer() { - } + private ProofReplayer() {} /** - * Replays the proof represented by the expression given in the {@link CharStream} after the position of the - * {@code token}. + * Replays the proof represented by the expression given in the {@link CharStream} after the + * position of the {@code token}. * * @param token the "\proof" with in the input stream * @param input a valid input stream - * @param prl the proof replayer instance + * @param prl the proof replayer instance * @param source the source of the stream, used for producing exceptions with locations * @see #run(CharStream, IProofFileParser, int, URL) */ public static void run(@Nonnull Token token, CharStream input, IProofFileParser prl, - URL source) { + URL source) { input.seek(1 + token.getStopIndex()); // ends now on \proof| run(input, prl, token.getLine(), source); } /** - * Replays the proof behind the given {@code input}. - * This method uses the {@link KeYLexer} to lex input stream, and parse them manually - * by consuming the tokens. It singals to the given {@link IProofFileParser} at start or end of an expr. + * Replays the proof behind the given {@code input}. This method uses the {@link KeYLexer} to + * lex input stream, and parse them manually by consuming the tokens. It singals to the given + * {@link IProofFileParser} at start or end of an expr. * * Avoid the usage of a parser, avoids also the construction of an ASTs. * - * @param input a valid input stream - * @param prl the proof replayer interface + * @param input a valid input stream + * @param prl the proof replayer interface * @param startLine the starting of the sexpr needed for {@code prl} - * @param source the source of the stream, used for producing exceptions with locations + * @param source the source of the stream, used for producing exceptions with locations */ public static void run(CharStream input, IProofFileParser prl, final int startLine, - URL source) { + URL source) { KeYLexer lexer = ParsingFacade.createLexer(input); CommonTokenStream stream = new CommonTokenStream(lexer); - Stack stack = new Stack<>(); //currently open proof elements + Stack stack = new Stack<>(); // currently open proof + // elements Deque posStack = new ArrayDeque<>(); // stack of opened commands position while (true) { - int type = stream.LA(1); //current token type + int type = stream.LA(1); // current token type switch (type) { - case KeYLexer.LPAREN: - //expected "(" ["string"] - stream.consume(); //consume the "(" - Token idToken = stream.LT(1); // element id - IProofFileParser.ProofElementID cur = proofSymbolElementId.get(idToken.getText()); + case KeYLexer.LPAREN: + // expected "(" ["string"] + stream.consume(); // consume the "(" + Token idToken = stream.LT(1); // element id + IProofFileParser.ProofElementID cur = proofSymbolElementId.get(idToken.getText()); - if (cur == null) { - Location loc = new Location(source, idToken.getLine() + startLine - 1, + if (cur == null) { + Location loc = new Location(source, idToken.getLine() + startLine - 1, idToken.getCharPositionInLine() + 1); - throw new LocatableException("Unknown proof element: " + idToken.getText(), + throw new LocatableException("Unknown proof element: " + idToken.getText(), loc); - } - stream.consume(); + } + stream.consume(); - String arg = null; - int pos = idToken.getLine() + startLine; - if (stream.LA(1) == KeYLexer.STRING_LITERAL) { - //argument was given - arg = stream.LT(1).getText(); - arg = unescape(arg.substring(1, arg.length() - 1)); - stream.consume();//throw string away - } + String arg = null; + int pos = idToken.getLine() + startLine; + if (stream.LA(1) == KeYLexer.STRING_LITERAL) { + // argument was given + arg = stream.LT(1).getText(); + arg = unescape(arg.substring(1, arg.length() - 1)); + stream.consume();// throw string away + } - prl.beginExpr(cur, arg); - stack.push(cur); - posStack.push(pos); - break; - case KeYLexer.RPAREN: - prl.endExpr(stack.pop(), posStack.pop()); - stream.consume(); - break; - case KeYLexer.EOF: - return; - default: - stream.consume(); + prl.beginExpr(cur, arg); + stack.push(cur); + posStack.push(pos); + break; + case KeYLexer.RPAREN: + prl.endExpr(stack.pop(), posStack.pop()); + stream.consume(); + break; + case KeYLexer.EOF: + return; + default: + stream.consume(); } } } private static String unescape(String text) { - return text - .replace("\\\\", "\\") - .replace("\\\"", "\""); + return text.replace("\\\\", "\\").replace("\\\"", "\""); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java index 28423107d10..9ecd7c0a512 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/AbstractBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.nparser.KeYParserBaseVisitor; @@ -35,7 +38,8 @@ abstract class AbstractBuilder extends KeYParserBaseVisitor { * * @param ctx a (parser) rule context or null * @param object to be cast to - * @return if the ctx is null, this method returns, otherwise the result of the visit method is returned + * @return if the ctx is null, this method returns, otherwise the result of the visit method is + * returned */ @Nullable public T accept(@Nullable RuleContext ctx) { @@ -55,7 +59,8 @@ public T acceptnn(@Nullable RuleContext ctx) { @Override protected T aggregateResult(T aggregate, T nextResult) { - if (nextResult != null) return nextResult; + if (nextResult != null) + return nextResult; return aggregate; } @@ -68,27 +73,32 @@ protected T peek() { } protected T acceptFirst(Collection seq) { - if (seq.isEmpty()) return null; + if (seq.isEmpty()) + return null; return accept(seq.iterator().next()); } protected T pop() { - if (parameters == null) throw new IllegalStateException("Stack is empty"); + if (parameters == null) + throw new IllegalStateException("Stack is empty"); return (T) parameters.pop(); } protected void push(Object... obj) { - if (parameters == null) parameters = new ArrayDeque<>(); - for (Object a : obj) parameters.push(a); + if (parameters == null) + parameters = new ArrayDeque<>(); + for (Object a : obj) + parameters.push(a); } @Nullable protected T accept(@Nullable RuleContext ctx, Object... args) { - if (parameters == null) parameters = new ArrayDeque<>(); + if (parameters == null) + parameters = new ArrayDeque<>(); int stackSize = parameters.size(); push(args); T t = accept(ctx); - //Stack hygiene + // Stack hygiene while (parameters.size() > stackSize) { parameters.pop(); } @@ -109,23 +119,24 @@ protected List mapOf(Collection argument) { } protected void each(RuleContext... ctx) { - for (RuleContext c : ctx) accept(c); + for (RuleContext c : ctx) + accept(c); } protected void each(Collection argument) { - for (RuleContext c : argument) accept(c); + for (RuleContext c : argument) + accept(c); } - //endregion + // endregion protected List mapMapOf(List... ctxss) { - return Arrays.stream(ctxss) - .flatMap(it -> it.stream().map(a -> (T2) accept(a))) + return Arrays.stream(ctxss).flatMap(it -> it.stream().map(a -> (T2) accept(a))) .collect(Collectors.toList()); } - public @Nonnull - List getBuildingIssues() { - if (buildingIssues == null) buildingIssues = new LinkedList<>(); + public @Nonnull List getBuildingIssues() { + if (buildingIssues == null) + buildingIssues = new LinkedList<>(); return buildingIssues; } @@ -140,9 +151,9 @@ protected BuildingIssue addWarning(String description) { getBuildingIssues().add(be); return be; } - //endregion + // endregion - //region error handling + // region error handling /** * Throws a semanticError for the given ast node and message. @@ -163,5 +174,5 @@ protected void semanticError(ParserRuleContext ctx, String format, Object... arg protected void throwEx(Throwable e) { throw new BuildingException(e); } - //endregion + // endregion } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/BuilderHelpers.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/BuilderHelpers.java index 7cf907868b1..da64c1d9dda 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/BuilderHelpers.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/BuilderHelpers.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import org.antlr.v4.runtime.ParserRuleContext; @@ -10,15 +13,15 @@ */ public final class BuilderHelpers { public static String getPosition(@Nullable ParserRuleContext node) { - if (node == null) return " pos n/a"; + if (node == null) + return " pos n/a"; return getPosition(node.start); } public static String getPosition(@Nullable Token t) { - return t == null - ? " pos n/a" - : String.format(" %s:%d#%d", - t.getInputStream().getSourceName(), t.getLine(), t.getCharPositionInLine()); + return t == null ? " pos n/a" + : String.format(" %s:%d#%d", t.getInputStream().getSourceName(), t.getLine(), + t.getCharPositionInLine()); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ChoiceFinder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ChoiceFinder.java index 21e83e2bad8..5a8631e0c95 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ChoiceFinder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ChoiceFinder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.logic.Choice; @@ -10,8 +13,8 @@ import java.util.*; /** - * This visitor gathers the choice information in {@link de.uka.ilkd.key.nparser.KeyAst.File} - * and provide {@link ChoiceInformation}. + * This visitor gathers the choice information in {@link de.uka.ilkd.key.nparser.KeyAst.File} and + * provide {@link ChoiceInformation}. * * @author Alexander Weigl * @version 1 (28.10.19) @@ -54,9 +57,7 @@ public Object visitChoice(KeYParser.ChoiceContext ctx) { seq().put(category, new HashSet<>(options)); choiceInformation.setDefaultOption(category, options.get(0)); - options.forEach(it -> - choices().add(new Choice(it, category)) - ); + options.forEach(it -> choices().add(new Choice(it, category))); return null; } @@ -65,7 +66,8 @@ public Choice visitActivated_choice(KeYParser.Activated_choiceContext ctx) { String cat = ctx.cat.getText(); String ch = ctx.choice_.getText(); if (activatedChoicesCategories().contains(cat)) { - throw new IllegalArgumentException("You have already chosen a different option for " + cat); + throw new IllegalArgumentException( + "You have already chosen a different option for " + cat); } activatedChoicesCategories().add(cat); String name = cat + ":" + ch; @@ -73,7 +75,7 @@ public Choice visitActivated_choice(KeYParser.Activated_choiceContext ctx) { if (c == null) { c = new Choice(ch, cat); choices().add(c); - //weigl: hitted by several test caes: + // weigl: hitted by several test caes: // semanticError(ctx, "Choice %s not previously declared", name); } activatedChoices().add(c); @@ -85,7 +87,7 @@ public ChoiceInformation getChoiceInformation() { return choiceInformation; } - //region access functions + // region access functions private Set activatedChoices() { return choiceInformation.getActivatedChoices(); } @@ -105,5 +107,5 @@ private Namespace choices() { private Map> seq() { return choiceInformation.getFoundChoicesAndOptions(); } - //endregion + // endregion } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ContractsAndInvariantsFinder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ContractsAndInvariantsFinder.java index b9bf7b3ff42..5398190e145 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ContractsAndInvariantsFinder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ContractsAndInvariantsFinder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.Services; @@ -61,7 +64,7 @@ public Object visitContracts(KeYParser.ContractsContext ctx) { @Override public Object visitOne_contract(KeYParser.One_contractContext ctx) { String contractName = visitSimple_ident(ctx.contractName); - //for program variable declarations + // for program variable declarations Namespace oldProgVars = namespaces().programVariables(); namespaces().setProgramVariables(new Namespace<>(oldProgVars)); declarationBuilder.visitProg_var_decls(ctx.prog_var_decls()); @@ -75,7 +78,7 @@ public Object visitOne_contract(KeYParser.One_contractContext ctx) { } catch (ProofInputException e) { semanticError(ctx, e.getMessage()); } - //dump local program variable declarations + // dump local program variable declarations namespaces().setProgramVariables(oldProgVars); return null; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DeclarationBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DeclarationBuilder.java index 4a87a17cf24..99770e25940 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DeclarationBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DeclarationBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.Services; @@ -19,14 +22,13 @@ import java.util.Map; /** - * This visitor evaluates all basic (level 0) declarations. - * This includes: + * This visitor evaluates all basic (level 0) declarations. This includes: *

        - *
      • Option Declarations
      • - *
      • Sorts
      • - *
      • Program variables
      • - *
      • Schema variables
      • - *
      • Rulesets
      • + *
      • Option Declarations
      • + *
      • Sorts
      • + *
      • Program variables
      • + *
      • Schema variables
      • + *
      • Rulesets
      • *
      *

      * These information are registered into the given {@link NamespaceSet}. @@ -44,8 +46,7 @@ public DeclarationBuilder(Services services, NamespaceSet nss) { @Override public Object visitDecls(KeYParser.DeclsContext ctx) { - mapMapOf(ctx.option_decls(), ctx.options_choice(), - ctx.ruleset_decls(), ctx.sort_decls(), + mapMapOf(ctx.option_decls(), ctx.options_choice(), ctx.ruleset_decls(), ctx.sort_decls(), ctx.prog_var_decls(), ctx.schema_var_decls()); return null; } @@ -61,15 +62,14 @@ public Object visitProg_var_decls(KeYParser.Prog_var_declsContext ctx) { Named name = lookup(pvName); if (name != null) { // commented out as pv do not have unique name (at the moment) - // throw new AmbigiousDeclException(varName, getSourceName(), getLine(), getColumn()) - if (!(name instanceof ProgramVariable) || - !((ProgramVariable) name).getKeYJavaType().equals(kjt)) { - programVariables().add(new LocationVariable - (pvName, kjt)); + // throw new AmbigiousDeclException(varName, getSourceName(), getLine(), + // getColumn()) + if (!(name instanceof ProgramVariable) + || !((ProgramVariable) name).getKeYJavaType().equals(kjt)) { + programVariables().add(new LocationVariable(pvName, kjt)); } } else { - programVariables() - .add(new LocationVariable(pvName, kjt)); + programVariables().add(new LocationVariable(pvName, kjt)); } } } @@ -119,12 +119,10 @@ public Object visitOne_sort_decl(KeYParser.One_sort_declContext ctx) { String sortId = accept(idCtx); Name sortName = new Name(sortId); - ImmutableSet ext = - sortExt == null ? ImmutableSet.empty() : - DefaultImmutableSet.fromCollection(sortExt); - ImmutableSet oneOf = - sortOneOf == null ? ImmutableSet.empty() : - DefaultImmutableSet.fromCollection(sortOneOf); + ImmutableSet ext = sortExt == null ? ImmutableSet.empty() + : DefaultImmutableSet.fromCollection(sortExt); + ImmutableSet oneOf = sortOneOf == null ? ImmutableSet.empty() + : DefaultImmutableSet.fromCollection(sortOneOf); // attention: no expand to java.lang here! if (sorts().lookup(sortName) == null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DefaultBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DefaultBuilder.java index ab0aa2ec761..dc791797dab 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DefaultBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/DefaultBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.JavaInfo; @@ -24,10 +27,10 @@ import java.util.ResourceBundle; /** - * Helper class for are visitor that requires a namespaces and services. - * Also it provides the evaluation of some basic {@link ParserRuleContext}s. - * This builder provides lookup functions for the namespace set and also namespace for {@link SchemaVariable}. - * But it does not evaluate schemaVariables, or other declarations. + * Helper class for are visitor that requires a namespaces and services. Also it provides the + * evaluation of some basic {@link ParserRuleContext}s. This builder provides lookup functions for + * the namespace set and also namespace for {@link SchemaVariable}. But it does not evaluate + * schemaVariables, or other declarations. * * @author weigl * @version 1 @@ -35,7 +38,8 @@ public class DefaultBuilder extends AbstractBuilder { public static final String LIMIT_SUFFIX = "$lmtd"; - private static ResourceBundle bundle = ResourceBundle.getBundle("de.uka.ilkd.key.nparser.builder.resources"); + private static ResourceBundle bundle = + ResourceBundle.getBundle("de.uka.ilkd.key.nparser.builder.resources"); protected final Services services; protected final NamespaceSet nss; @@ -81,8 +85,8 @@ public String visitSimple_ident_dots(KeYParser.Simple_ident_dotsContext ctx) { } protected Named lookup(Name n) { - final Namespace[] lookups = { - programVariables(), variables(), schemaVariables(), functions()}; + final Namespace[] lookups = + { programVariables(), variables(), schemaVariables(), functions() }; return doLookup(n, lookups); } @@ -103,16 +107,13 @@ protected void unbindVars(Namespace orig) { namespaces().setVariables(orig); } - /*@Override - public Integer visitLocation_ident(KeYParser.Location_identContext ctx) { - var id = accept(ctx.simple_ident()); - if ("Location".equals(id)) { - return LOCATION_MODIFIER; - } else if (!"Location".equals(id)) { - semanticError(ctx, "%s Attribute of a Non Rigid Function can only be 'Location'", id); - } - return NORMAL_NONRIGID; - }*/ + /* + * @Override public Integer visitLocation_ident(KeYParser.Location_identContext ctx) { var id = + * accept(ctx.simple_ident()); if ("Location".equals(id)) { return LOCATION_MODIFIER; } else if + * (!"Location".equals(id)) { semanticError(ctx, + * "%s Attribute of a Non Rigid Function can only be 'Location'", id); } return NORMAL_NONRIGID; + * } + */ @Override public List visitArg_sorts_or_formula(KeYParser.Arg_sorts_or_formulaContext ctx) { @@ -127,29 +128,26 @@ public Sort visitArg_sorts_or_formula_helper(KeYParser.Arg_sorts_or_formula_help return (Sort) accept(ctx.sortId()); } - /*@Override - public Sort visitAny_sortId(KeYParser.Any_sortIdContext ctx) { - Pair p = accept(ctx.any_sortId_help()); - return toArraySort(p, ctx.EMPTYBRACKETS().size()); - }*/ + /* + * @Override public Sort visitAny_sortId(KeYParser.Any_sortIdContext ctx) { Pair p = + * accept(ctx.any_sortId_help()); return toArraySort(p, ctx.EMPTYBRACKETS().size()); } + */ /** - * looks up a function, (program) variable or static query of the - * given name varfunc_id and the argument terms args in the namespaces - * and java info. + * looks up a function, (program) variable or static query of the given name varfunc_id and the + * argument terms args in the namespaces and java info. * * @param varfuncName the String with the symbols name */ - protected Operator lookupVarfuncId(ParserRuleContext ctx, String varfuncName, String sortName, Sort sort) { + protected Operator lookupVarfuncId(ParserRuleContext ctx, String varfuncName, String sortName, + Sort sort) { Name name = new Name(varfuncName); - Operator[] operators = new Operator[]{ - schemaVariables().lookup(name), - variables().lookup(name), - programVariables().lookup(new ProgramElementName(varfuncName)), - functions().lookup(name), - AbstractTermTransformer.name2metaop(varfuncName), + Operator[] operators = + new Operator[] { schemaVariables().lookup(name), variables().lookup(name), + programVariables().lookup(new ProgramElementName(varfuncName)), + functions().lookup(name), AbstractTermTransformer.name2metaop(varfuncName), - }; + }; for (Operator op : operators) { if (op != null) { @@ -158,14 +156,13 @@ protected Operator lookupVarfuncId(ParserRuleContext ctx, String varfuncName, St } if (sort != null || sortName != null) { - Name fqName = new Name((sort != null ? sort.toString() : sortName) + "::" + varfuncName); - operators = new Operator[]{ - schemaVariables().lookup(fqName), - variables().lookup(fqName), - programVariables().lookup(new ProgramElementName(fqName.toString())), - functions().lookup(fqName), - AbstractTermTransformer.name2metaop(fqName.toString()) - }; + Name fqName = + new Name((sort != null ? sort.toString() : sortName) + "::" + varfuncName); + operators = + new Operator[] { schemaVariables().lookup(fqName), variables().lookup(fqName), + programVariables().lookup(new ProgramElementName(fqName.toString())), + functions().lookup(fqName), + AbstractTermTransformer.name2metaop(fqName.toString()) }; for (Operator op : operators) { if (op != null) { @@ -189,12 +186,8 @@ protected Operator lookupVarfuncId(ParserRuleContext ctx, String varfuncName, St public Sort toArraySort(Pair p, int numOfDimensions) { if (numOfDimensions != 0) { final JavaInfo ji = getJavaInfo(); - Sort sort = ArraySort.getArraySortForDim(p.first, - p.second, - numOfDimensions, - ji.objectSort(), - ji.cloneableSort(), - ji.serializableSort()); + Sort sort = ArraySort.getArraySortForDim(p.first, p.second, numOfDimensions, + ji.objectSort(), ji.cloneableSort(), ji.serializableSort()); Sort s = sort; do { final ArraySort as = (ArraySort) s; @@ -208,18 +201,18 @@ public Sort toArraySort(Pair p, int numOfDimensions) { } /** - * looks up and returns the sort of the given name or null if none has been found. - * If the sort is not found for the first time, the name is expanded with "java.lang." - * and the look up restarts + * looks up and returns the sort of the given name or null if none has been found. If the sort + * is not found for the first time, the name is expanded with "java.lang." and the look up + * restarts */ protected Sort lookupSort(String name) { Sort result = sorts().lookup(new Name(name)); if (result == null) { if (name.equals(NullSort.NAME.toString())) { - Sort objectSort - = sorts().lookup(new Name("java.lang.Object")); + Sort objectSort = sorts().lookup(new Name("java.lang.Object")); if (objectSort == null) { - semanticError(null, "Null sort cannot be used before java.lang.Object is declared"); + semanticError(null, + "Null sort cannot be used before java.lang.Object is declared"); } result = new NullSort(objectSort); sorts().add(result); @@ -295,7 +288,8 @@ public Object visitVarIds(KeYParser.VarIdsContext ctx) { @Override - public Object visitSimple_ident_dots_comma_list(KeYParser.Simple_ident_dots_comma_listContext ctx) { + public Object visitSimple_ident_dots_comma_list( + KeYParser.Simple_ident_dots_comma_listContext ctx) { return mapOf(ctx.simple_ident_dots()); } @@ -324,12 +318,12 @@ public List visitArg_sorts(KeYParser.Arg_sortsContext ctx) { @Override public Sort visitSortId(KeYParser.SortIdContext ctx) { String primitiveName = ctx.id.getText(); - //Special handling for byte, char, short, long: - //these are *not* sorts, but they are nevertheless valid - //prefixes for array sorts such as byte[], char[][][]. - //Thus, we consider them aliases for the "int" sort, and remember - //the corresponding Java type for the case that an array sort - //is being declared. + // Special handling for byte, char, short, long: + // these are *not* sorts, but they are nevertheless valid + // prefixes for array sorts such as byte[], char[][][]. + // Thus, we consider them aliases for the "int" sort, and remember + // the corresponding Java type for the case that an array sort + // is being declared. Type t = null; if (primitiveName.equals(PrimitiveType.JAVA_BYTE.getName())) { t = PrimitiveType.JAVA_BYTE; @@ -371,7 +365,7 @@ public KeYJavaType visitKeyjavatype(KeYParser.KeyjavatypeContext ctx) { } KeYJavaType kjt = getJavaInfo().getKeYJavaType(type); - //expand to "java.lang" + // expand to "java.lang" if (kjt == null) { try { String guess = "java.lang." + type; @@ -381,19 +375,18 @@ public KeYJavaType visitKeyjavatype(KeYParser.KeyjavatypeContext ctx) { } } - //arrays + // arrays if (kjt == null && array) { try { JavaBlock jb = getJavaInfo().readJavaBlock("{" + type + " k;}"); - kjt = ((VariableDeclaration) - ((StatementBlock) jb.program()).getChildAt(0)). - getTypeReference().getKeYJavaType(); + kjt = ((VariableDeclaration) ((StatementBlock) jb.program()).getChildAt(0)) + .getTypeReference().getKeYJavaType(); } catch (Exception e) { kjt = null; } } - //try as sort without Java type (neede e.g. for "Heap") + // try as sort without Java type (neede e.g. for "Heap") if (kjt == null) { Sort sort = lookupSort(type); if (sort != null) { diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java index 7acee0459e0..28865763310 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ExpressionBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.*; @@ -41,16 +44,16 @@ import java.util.stream.Collectors; /** - * This visitor creates expression from {@link de.uka.ilkd.key.nparser.KeyAst.Term}. - * You should use the facade {@link de.uka.ilkd.key.nparser.KeyIO#parseExpression(String)} - * for term parsing. + * This visitor creates expression from {@link de.uka.ilkd.key.nparser.KeyAst.Term}. You should use + * the facade {@link de.uka.ilkd.key.nparser.KeyIO#parseExpression(String)} for term parsing. * * @author weigl */ public class ExpressionBuilder extends DefaultBuilder { public static final Logger LOGGER = LoggerFactory.getLogger(ExpressionBuilder.class); - public static final String NO_HEAP_EXPRESSION_BEFORE_AT_EXCEPTION_MESSAGE = "Expecting select term before '@', not: "; + public static final String NO_HEAP_EXPRESSION_BEFORE_AT_EXCEPTION_MESSAGE = + "Expecting select term before '@', not: "; /** * The current abbreviation used for resolving "@name" terms. @@ -76,7 +79,8 @@ public ExpressionBuilder(Services services, NamespaceSet nss) { this(services, nss, new Namespace<>()); } - public ExpressionBuilder(Services services, NamespaceSet nss, Namespace schemaNamespace) { + public ExpressionBuilder(Services services, NamespaceSet nss, + Namespace schemaNamespace) { super(services, nss); setSchemaVariables(schemaNamespace); } @@ -84,8 +88,8 @@ public ExpressionBuilder(Services services, NamespaceSet nss, Namespace updateOrigin(getTermFactory().createTerm(operator, left, right), ctx)); + return capsulateTf(ctx, + () -> updateOrigin(getTermFactory().createTerm(operator, left, right), ctx)); } @Override @@ -216,8 +235,8 @@ public Term visitConjunction_term(KeYParser.Conjunction_termContext ctx) { t = binaryTerm(ctx, Junctor.AND, t, accept(c)); } return t; - //Term termR = accept(ctx.b); - //return binaryTerm(ctx, Junctor.AND, termL, termR); + // Term termR = accept(ctx.b); + // return binaryTerm(ctx, Junctor.AND, termL, termR); } @Override @@ -227,8 +246,8 @@ public Object visitUnary_minus_term(KeYParser.Unary_minus_termContext ctx) { if (ctx.MINUS() != null) { Operator Z = functions().lookup("Z"); if (result.op() == Z) { - //weigl: rewrite neg(Z(1(#)) to Z(neglit(1(#)) - // This mimics the old KeyParser behaviour. Unknown if necessary. + // weigl: rewrite neg(Z(1(#)) to Z(neglit(1(#)) + // This mimics the old KeyParser behaviour. Unknown if necessary. final Function neglit = functions().lookup("neglit"); final Term num = result.sub(0); return capsulateTf(ctx, () -> getTermFactory().createTerm(Z, @@ -244,7 +263,7 @@ public Object visitUnary_minus_term(KeYParser.Unary_minus_termContext ctx) { ldt = services.getTypeConverter().getIntegerLDT(); } Function op = ldt.getFunctionFor("-", MixFitInfo.Kind.PREFIX, services); - if(op == null) { + if (op == null) { semanticError(ctx, "Could not find function symbol 'neg' for sort '%s'.", sort); } return capsulateTf(ctx, () -> getTermFactory().createTerm(op, result)); @@ -260,8 +279,8 @@ public Term visitNegation_term(KeYParser.Negation_termContext ctx) { Term termL = accept(ctx.sub); if (ctx.NOT() != null) { return capsulateTf(ctx, () -> getTermFactory().createTerm(Junctor.NOT, termL)); - } - else return termL; + } else + return termL; } @Override @@ -280,7 +299,7 @@ public Object visitComparison_term(KeYParser.Comparison_termContext ctx) { Term termL = accept(ctx.a); Term termR = accept(ctx.b); - if(termR == null) { + if (termR == null) { return updateOrigin(termL, ctx); } return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); @@ -314,7 +333,7 @@ private Term binaryLDTSpecificTerm(ParserRuleContext ctx, String opname, Term la ldt = services.getTypeConverter().getIntegerLDT(); } Function op = ldt.getFunctionFor(opname, services); - if(op == null) { + if (op == null) { semanticError(ctx, "Could not find function symbol '%s' for sort '%s'.", opname, sort); } return binaryTerm(ctx, op, last, cur); @@ -339,7 +358,8 @@ public Object visitStrong_arith_term_1(KeYParser.Strong_arith_term_1Context ctx) @Override public Object visitStrong_arith_term_2(KeYParser.Strong_arith_term_2Context ctx) { Term termL = acceptnn(ctx.a); - if (ctx.b == null) return termL; + if (ctx.b == null) + return termL; Term termR = accept(ctx.b); return binaryLDTSpecificTerm(ctx, ctx.op.getText(), termL, termR); @@ -349,7 +369,8 @@ protected Term capsulateTf(ParserRuleContext ctx, Supplier termSupplier) { try { return termSupplier.get(); } catch (TermCreationException e) { - throw new BuildingException(ctx, String.format("Could not build term on: %s", ctx.getText()), e); + throw new BuildingException(ctx, + String.format("Could not build term on: %s", ctx.getText()), e); } } @@ -364,50 +385,36 @@ public Object visitBracket_term(KeYParser.Bracket_termContext ctx) { t = replaceHeap(t, accept(heap), heap); } } - if (ctx.attribute().isEmpty()) return t; + if (ctx.attribute().isEmpty()) + return t; return handleAttributes(t, ctx.attribute()); } - /*@Override - public String visitStaticAttributeOrQueryReference(KeYParser.StaticAttributeOrQueryReferenceContext ctx) { - //TODO weigl: this rule is a total grammar blower. - String attrReference = ctx.id.getText(); - for (int i = 0; i < ctx.EMPTYBRACKETS().size(); i++) { - attrReference += "[]"; - } - - /*KeYJavaType kjt = null; - kjt = getTypeByClassName(attrReference); - if (kjt == null) { - throwEx(new NotDeclException(input, "Class", attrReference)); - } - attrReference = kjt.getSort().name().toString(); - match(input, DOT, null); - attrReference += "::" + input.LT(1).getText(); - match(input, IDENT, null); - if(savedGuessing > -1) { - state.backtracking = savedGuessing; - savedGuessing = -1; - }*/ - // return attrReference; + /* + * @Override public String + * visitStaticAttributeOrQueryReference(KeYParser.StaticAttributeOrQueryReferenceContext ctx) { + * //TODO weigl: this rule is a total grammar blower. String attrReference = ctx.id.getText(); + * for (int i = 0; i < ctx.EMPTYBRACKETS().size(); i++) { attrReference += "[]"; } + * + * /*KeYJavaType kjt = null; kjt = getTypeByClassName(attrReference); if (kjt == null) { + * throwEx(new NotDeclException(input, "Class", attrReference)); } attrReference = + * kjt.getSort().name().toString(); match(input, DOT, null); attrReference += "::" + + * input.LT(1).getText(); match(input, IDENT, null); if(savedGuessing > -1) { state.backtracking + * = savedGuessing; savedGuessing = -1; } + */ + // return attrReference; // } - /*@Override - public Term visitStatic_attribute_suffix(KeYParser.Static_attribute_suffixContext ctx) { - Operator v = null; - String attributeName = accept(ctx.staticAttributeOrQueryReference()); - String className; - if (attributeName.indexOf(':') != -1) { - className = - attributeName.substring(0, attributeName.indexOf(':')); - } else { - className = - attributeName.substring(0, attributeName.lastIndexOf(".")); - } - v = getAttributeInPrefixSort(getTypeByClassName(className).getSort(), attributeName); - return createAttributeTerm(null, v, ctx); - } - */ + /* + * @Override public Term visitStatic_attribute_suffix(KeYParser.Static_attribute_suffixContext + * ctx) { Operator v = null; String attributeName = + * accept(ctx.staticAttributeOrQueryReference()); String className; if + * (attributeName.indexOf(':') != -1) { className = attributeName.substring(0, + * attributeName.indexOf(':')); } else { className = attributeName.substring(0, + * attributeName.lastIndexOf(".")); } v = + * getAttributeInPrefixSort(getTypeByClassName(className).getSort(), attributeName); return + * createAttributeTerm(null, v, ctx); } + */ private LogicVariable bindVar(String id, Sort s) { LogicVariable v = new LogicVariable(new Name(id), s); @@ -449,19 +456,16 @@ private Term toZNotation(String literal, Namespace functions) { private Term toZNotation(BigInteger bi, Namespace functions) { boolean negative = bi.signum() < 0; String s = bi.abs().toString(); - Term result = getTermFactory() - .createTerm(functions.lookup(new Name("#"))); + Term result = getTermFactory().createTerm(functions.lookup(new Name("#"))); for (int i = 0; i < s.length(); i++) - result = getTermFactory().createTerm( - functions.lookup(new Name(s.substring(i, i + 1))), result); + result = getTermFactory().createTerm(functions.lookup(new Name(s.substring(i, i + 1))), + result); if (negative) { - result = getTermFactory().createTerm( - functions.lookup(new Name("neglit")), result); + result = getTermFactory().createTerm(functions.lookup(new Name("neglit")), result); } - return getTermFactory().createTerm( - functions.lookup(new Name("Z")), result); + return getTermFactory().createTerm(functions.lookup(new Name("Z")), result); } @Override @@ -487,15 +491,13 @@ public Object visitTermorseq(KeYParser.TermorseqContext ctx) { if (head != null && ss != null) { // A sequent with only head in the antecedent. Semisequent ant = Semisequent.EMPTY_SEMISEQUENT; - ant = ant.insertFirst( - new SequentFormula(head)).semisequent(); + ant = ant.insertFirst(new SequentFormula(head)).semisequent(); return Sequent.createSequent(ant, ss); } if (head != null && s != null) { - // A sequent. Prepend head to the antecedent. + // A sequent. Prepend head to the antecedent. Semisequent newAnt = s.antecedent(); - newAnt = newAnt.insertFirst( - new SequentFormula(head)).semisequent(); + newAnt = newAnt.insertFirst(new SequentFormula(head)).semisequent(); return Sequent.createSequent(newAnt, s.succedent()); } if (ss != null) { @@ -535,11 +537,12 @@ private PairOfStringAndJavaBlock getJavaBlock(Token t) { try { try { - if (javaSchemaModeAllowed) {//TEST + if (javaSchemaModeAllowed) {// TEST SchemaJavaReader jr = new SchemaRecoder2KeY(services, nss); jr.setSVNamespace(schemaVariables()); try { - sjb.javaBlock = jr.readBlockWithProgramVariables(programVariables(), cleanJava); + sjb.javaBlock = + jr.readBlockWithProgramVariables(programVariables(), cleanJava); } catch (Exception e) { sjb.javaBlock = jr.readBlockWithEmptyContext(cleanJava); } @@ -584,17 +587,17 @@ public Term createAttributeTerm(Term prefix, Operator attribute, ParserRuleConte Term result = prefix; if (attribute instanceof SchemaVariable) { - /*if (!inSchemaMode()) { - semanticError(null, "Schemavariables may only occur inside taclets."); - }*/ + /* + * if (!inSchemaMode()) { semanticError(null, + * "Schemavariables may only occur inside taclets."); } + */ SchemaVariable sv = (SchemaVariable) attribute; if (sv.sort() instanceof ProgramSVSort || sv.sort() == AbstractTermTransformer.METASORT) { semanticError(null, "Cannot use schema variable " + sv + " as an attribute"); } result = getServices().getTermBuilder().select(sv.sort(), - getServices().getTermBuilder().getBaseHeap(), - prefix, + getServices().getTermBuilder().getBaseHeap(), prefix, capsulateTf(ctx, () -> getTermFactory().createTerm(attribute))); } else { if (attribute instanceof LogicVariable) { @@ -604,14 +607,12 @@ public Term createAttributeTerm(Term prefix, Operator attribute, ParserRuleConte result = capsulateTf(ctx, () -> getTermFactory().createTerm(attribute)); } else if (attribute == getServices().getJavaInfo().getArrayLength()) { Term finalResult = result; - result = capsulateTf(ctx, () -> getServices().getTermBuilder().dotLength(finalResult)); + result = capsulateTf(ctx, + () -> getServices().getTermBuilder().dotLength(finalResult)); } else { ProgramVariable pv = (ProgramVariable) attribute; - Function fieldSymbol - = getServices().getTypeConverter() - .getHeapLDT() - .getFieldSymbolForPV((LocationVariable) pv, - getServices()); + Function fieldSymbol = getServices().getTypeConverter().getHeapLDT() + .getFieldSymbolForPV((LocationVariable) pv, getServices()); if (pv.isStatic()) { result = getServices().getTermBuilder().staticDot(pv.sort(), fieldSymbol); } else { @@ -626,7 +627,7 @@ private Operator getAttributeInPrefixSort(Sort prefixSort, String attributeName) final JavaInfo javaInfo = getJavaInfo(); Operator result = schemaVariables().lookup(new Name(attributeName)); - //if (result == null) { + // if (result == null) { final boolean unambigousAttributeName = attributeName.indexOf(':') != -1; @@ -646,16 +647,20 @@ private Operator getAttributeInPrefixSort(Sort prefixSort, String attributeName) } else { final KeYJavaType prefixKJT = javaInfo.getKeYJavaType(prefixSort); if (prefixKJT == null) { - semanticError(null, "Could not find type '" + prefixSort + "'. Maybe mispelled or " + - "you use an array or object type in a .key-file with missing " + - "\\javaSource section."); + semanticError(null, + "Could not find type '" + prefixSort + "'. Maybe mispelled or " + + "you use an array or object type in a .key-file with missing " + + "\\javaSource section."); } - ProgramVariable var = javaInfo.getCanonicalFieldProgramVariable(attributeName, prefixKJT); + ProgramVariable var = + javaInfo.getCanonicalFieldProgramVariable(attributeName, prefixKJT); if (var == null) { - LogicVariable logicalvar = (LogicVariable) namespaces().variables().lookup(attributeName); + LogicVariable logicalvar = + (LogicVariable) namespaces().variables().lookup(attributeName); if (logicalvar == null) { - semanticError(null, "There is no attribute '%s' declared in type '%s' and no logical variable of that name.", + semanticError(null, + "There is no attribute '%s' declared in type '%s' and no logical variable of that name.", attributeName, prefixSort); } else { result = logicalvar; @@ -664,7 +669,7 @@ private Operator getAttributeInPrefixSort(Sort prefixSort, String attributeName) result = var; } } - //} + // } if (result == null && !("length".equals(attributeName))) { throwEx(new NotDeclException(null, "Attribute ", attributeName)); @@ -672,10 +677,9 @@ private Operator getAttributeInPrefixSort(Sort prefixSort, String attributeName) return result; } - /*@Override - public String visitAttrid(KeYParser.AttridContext ctx) { - return ctx.getText(); - }*/ + /* + * @Override public String visitAttrid(KeYParser.AttridContext ctx) { return ctx.getText(); } + */ private String unescapeString(String string) { char[] chars = string.toCharArray(); @@ -683,27 +687,27 @@ private String unescapeString(String string) { for (int i = 0; i < chars.length; i++) { if (chars[i] == '\\' && i < chars.length - 1) { switch (chars[++i]) { - case 'n': - sb.append("\n"); - break; - case 'f': - sb.append("\f"); - break; - case 'r': - sb.append("\r"); - break; - case 't': - sb.append("\t"); - break; - case 'b': - sb.append("\b"); - break; - case ':': - sb.append("\\:"); - break; // this is so in KeY ... - default: - sb.append(chars[i]); - break; // this more relaxed than before, \a becomes a ... + case 'n': + sb.append("\n"); + break; + case 'f': + sb.append("\f"); + break; + case 'r': + sb.append("\r"); + break; + case 't': + sb.append("\t"); + break; + case 'b': + sb.append("\b"); + break; + case ':': + sb.append("\\:"); + break; // this is so in KeY ... + default: + sb.append(chars[i]); + break; // this more relaxed than before, \a becomes a ... } } else { sb.append(chars[i]); @@ -715,8 +719,7 @@ private String unescapeString(String string) { @Override public Term visitString_literal(KeYParser.String_literalContext ctx) { String s = unescapeString(ctx.id.getText()); - return getServices().getTypeConverter() - .convertToLogicElement(new StringLiteral(s)); + return getServices().getTypeConverter().convertToLogicElement(new StringLiteral(s)); } @Override @@ -730,12 +733,10 @@ public Object visitCast_term(KeYParser.Cast_termContext ctx) { Sort objectSort = getServices().getJavaInfo().objectSort(); if (s == null) { semanticError(ctx, "Tried to cast to unknown type."); - } else if (objectSort != null - && !s.extendsTrans(objectSort) + } else if (objectSort != null && !s.extendsTrans(objectSort) && result.sort().extendsTrans(objectSort)) { - semanticError(ctx, "Illegal cast from " + result.sort() + - " to sort " + s + - ". Casts between primitive and reference types are not allowed. "); + semanticError(ctx, "Illegal cast from " + result.sort() + " to sort " + s + + ". Casts between primitive and reference types are not allowed. "); } assert s != null; SortDependingFunction castSymbol = s.getCastSymbol(getServices()); @@ -748,29 +749,17 @@ private void markHeapAsExplicit(Term a) { } /* - private Term createStaticAttributeOrMethod(JavaQuery jq, KeYParser.AccesstermContext ctx) { - final var kjt = jq.kjt; - String mn = jq.attributeNames; - if (jq.maybeAttr != null) { - ProgramVariable maybeAttr = getJavaInfo().getAttribute(mn, kjt); - if (maybeAttr != null) { - var op = getAttributeInPrefixSort(kjt.getSort(), mn); - return createAttributeTerm(null, op, ctx); - } - } else { - var suffix = ctx.atom_suffix(ctx.atom_suffix().size() - 1); - for (IProgramMethod pm : getJavaInfo().getAllProgramMethods(kjt)) { - if (pm != null && pm.isStatic() && pm.name().toString().equals(kjt.getFullName() + "::" + mn)) { - List arguments = mapOf(suffix.attribute_or_query_suffix().result.args.argument()); - Term[] args = arguments.toArray(new Term[0]); - return getJavaInfo().getStaticProgramMethodTerm(mn, args, kjt.getFullName()); - } - } - } - assert false; - return null; - } - */ + * private Term createStaticAttributeOrMethod(JavaQuery jq, KeYParser.AccesstermContext ctx) { + * final var kjt = jq.kjt; String mn = jq.attributeNames; if (jq.maybeAttr != null) { + * ProgramVariable maybeAttr = getJavaInfo().getAttribute(mn, kjt); if (maybeAttr != null) { var + * op = getAttributeInPrefixSort(kjt.getSort(), mn); return createAttributeTerm(null, op, ctx); + * } } else { var suffix = ctx.atom_suffix(ctx.atom_suffix().size() - 1); for (IProgramMethod pm + * : getJavaInfo().getAllProgramMethods(kjt)) { if (pm != null && pm.isStatic() && + * pm.name().toString().equals(kjt.getFullName() + "::" + mn)) { List arguments = + * mapOf(suffix.attribute_or_query_suffix().result.args.argument()); Term[] args = + * arguments.toArray(new Term[0]); return getJavaInfo().getStaticProgramMethodTerm(mn, args, + * kjt.getFullName()); } } } assert false; return null; } + */ @Override public Object visitBracket_access_heap_update(KeYParser.Bracket_access_heap_updateContext ctx) { @@ -810,18 +799,18 @@ public Object visitBracket_access_star(KeYParser.Bracket_access_starContext ctx) Term rangeFrom = toZNotation("0", functions()); Term lt = getServices().getTermBuilder().dotLength(reference); Term one = toZNotation("1", functions()); - Term rangeTo = getTermFactory().createTerm( - functions().lookup(new Name("sub")), lt, one); - //TODO construct + Term rangeTo = getTermFactory().createTerm(functions().lookup(new Name("sub")), lt, one); + // TODO construct return null; } @Override public Object visitBracket_access_indexrange(KeYParser.Bracket_access_indexrangeContext ctx) { - // | term LBRACKET indexTerm=term (DOTRANGE rangeTo=term)? RBRACKET #bracket_access_indexrange + // | term LBRACKET indexTerm=term (DOTRANGE rangeTo=term)? RBRACKET + // #bracket_access_indexrange Term term = pop(); boolean sequenceAccess = term.sort().name().toString().equalsIgnoreCase("seq"); - //boolean heapUpdate = reference.sort().name().toString().equalsIgnoreCase("Heap"); + // boolean heapUpdate = reference.sort().name().toString().equalsIgnoreCase("Heap"); if (sequenceAccess) { if (ctx.rangeTo != null) { @@ -830,7 +819,8 @@ public Object visitBracket_access_indexrange(KeYParser.Bracket_access_indexrange Term indexTerm = accept(ctx.indexTerm); assert indexTerm != null; if (!isIntTerm(indexTerm)) - semanticError(ctx, "Expecting term of sort %s as index of sequence %s, but found: %s", + semanticError(ctx, + "Expecting term of sort %s as index of sequence %s, but found: %s", IntegerLDT.NAME, term, indexTerm); return getServices().getTermBuilder().seqGet(Sort.ANY, term, indexTerm); } @@ -840,18 +830,23 @@ public Object visitBracket_access_indexrange(KeYParser.Bracket_access_indexrange Term rangeTo = accept(ctx.rangeTo); if (rangeTo != null) { if (quantifiedArrayGuard == null) { - semanticError(ctx, "Quantified array expressions are only allowed in locations."); + semanticError(ctx, + "Quantified array expressions are only allowed in locations."); } - LogicVariable indexVar = new LogicVariable(new Name("i"), - sorts().lookup(new Name("int"))); + LogicVariable indexVar = + new LogicVariable(new Name("i"), sorts().lookup(new Name("int"))); Term indexTerm = capsulateTf(ctx, () -> getTermFactory().createTerm(indexVar)); Function leq = functions().lookup(new Name("leq")); - Term fromTerm = capsulateTf(ctx, () -> getTermFactory().createTerm(leq, rangeFrom, indexTerm)); - Term toTerm = capsulateTf(ctx, () -> getTermFactory().createTerm(leq, indexTerm, rangeTo)); - Term guardTerm = capsulateTf(ctx, () -> getTermFactory().createTerm(Junctor.AND, fromTerm, toTerm)); - quantifiedArrayGuard = capsulateTf(ctx, () -> getTermFactory().createTerm(Junctor.AND, quantifiedArrayGuard, guardTerm)); - //TODO check quantifiedArrayGuard! + Term fromTerm = capsulateTf(ctx, + () -> getTermFactory().createTerm(leq, rangeFrom, indexTerm)); + Term toTerm = capsulateTf(ctx, + () -> getTermFactory().createTerm(leq, indexTerm, rangeTo)); + Term guardTerm = capsulateTf(ctx, + () -> getTermFactory().createTerm(Junctor.AND, fromTerm, toTerm)); + quantifiedArrayGuard = capsulateTf(ctx, () -> getTermFactory() + .createTerm(Junctor.AND, quantifiedArrayGuard, guardTerm)); + // TODO check quantifiedArrayGuard! } } Term indexTerm = accept(ctx.indexTerm); @@ -903,9 +898,8 @@ public TermLabel visitSingle_label(KeYParser.Single_labelContext ctx) { label = (TermLabel) var; } if (label == null) { - label = getServices().getProfile() - .getTermLabelManager() - .parseLabel(labelName, parameters, getServices()); + label = getServices().getProfile().getTermLabelManager().parseLabel(labelName, + parameters, getServices()); } } catch (Exception ex) { throw new BuildingException(ctx, ex); @@ -931,7 +925,8 @@ public Term visitIfThenElseTerm(KeYParser.IfThenElseTermContext ctx) { } Term thenT = (Term) ctx.thenT.accept(this); Term elseT = (Term) ctx.elseT.accept(this); - return capsulateTf(ctx, () -> getTermFactory().createTerm(IfThenElse.IF_THEN_ELSE, condF, thenT, elseT)); + return capsulateTf(ctx, + () -> getTermFactory().createTerm(IfThenElse.IF_THEN_ELSE, condF, thenT, elseT)); } @@ -946,12 +941,9 @@ public Object visitIfExThenElseTerm(KeYParser.IfExThenElseTermContext ctx) { Term thenT = accept(ctx.thenT); Term elseT = accept(ctx.elseT); - ImmutableArray exVarsArray - = new ImmutableArray<>(exVars); + ImmutableArray exVarsArray = new ImmutableArray<>(exVars); Term result = getTermFactory().createTerm(IfExThenElse.IF_EX_THEN_ELSE, - new Term[]{condF, thenT, elseT}, - exVarsArray, - null); + new Term[] { condF, thenT, elseT }, exVarsArray, null); unbindVars(orig); return result; } @@ -966,10 +958,8 @@ public Term visitQuantifierterm(KeYParser.QuantifiertermContext ctx) { op = Quantifier.EX; List vs = accept(ctx.bound_variables()); Term a1 = accept(ctx.sub); - Term a = getTermFactory().createTerm(op, - new ImmutableArray<>(a1), - new ImmutableArray<>(vs.toArray(new QuantifiableVariable[0])), - null); + Term a = getTermFactory().createTerm(op, new ImmutableArray<>(a1), + new ImmutableArray<>(vs.toArray(new QuantifiableVariable[0])), null); unbindVars(orig); return a; } @@ -1001,7 +991,8 @@ public Object visitSubstitution_term(KeYParser.Substitution_termContext ctx) { Term a1 = accept(ctx.replacement); Term a2 = oneOf(ctx.atom_prefix(), ctx.unary_formula()); try { - Term result = getServices().getTermBuilder().subst(op, (QuantifiableVariable) v, a1, a2); + Term result = + getServices().getTermBuilder().subst(op, (QuantifiableVariable) v, a1, a2); return result; } catch (Exception e) { throw new BuildingException(ctx, e); @@ -1013,15 +1004,15 @@ public Object visitSubstitution_term(KeYParser.Substitution_termContext ctx) { @Override public Object visitUpdate_term(KeYParser.Update_termContext ctx) { Term t = oneOf(ctx.atom_prefix(), ctx.unary_formula()); - if (ctx.u.isEmpty()) return t; + if (ctx.u.isEmpty()) + return t; Term u = accept(ctx.u); return getTermFactory().createTerm(UpdateApplication.UPDATE_APPLICATION, u, t); } public List visitBound_variables(KeYParser.Bound_variablesContext ctx) { List seq = ctx.one_bound_variable().stream() - .map(it -> (QuantifiableVariable) it.accept(this)) - .collect(Collectors.toList()); + .map(it -> (QuantifiableVariable) it.accept(this)).collect(Collectors.toList()); return seq; } @@ -1052,14 +1043,16 @@ public QuantifiableVariable visitOne_bound_variable(KeYParser.One_bound_variable @Override public Object visitModality_term(KeYParser.Modality_termContext ctx) { Term a1 = accept(ctx.sub); - if (ctx.MODALITY() == null) return a1; + if (ctx.MODALITY() == null) + return a1; PairOfStringAndJavaBlock sjb = getJavaBlock(ctx.MODALITY().getSymbol()); Operator op; if (sjb.opName.charAt(0) == '#') { - /*if (!inSchemaMode()) { - semanticError(ctx, "No schema elements allowed outside taclet declarations (" + sjb.opName + ")"); - }*/ + /* + * if (!inSchemaMode()) { semanticError(ctx, + * "No schema elements allowed outside taclet declarations (" + sjb.opName + ")"); } + */ op = schemaVariables().lookup(new Name(sjb.opName)); } else { op = Modality.getModality(sjb.opName); @@ -1068,7 +1061,8 @@ public Object visitModality_term(KeYParser.Modality_termContext ctx) { semanticError(ctx, "Unknown modal operator: " + sjb.opName); } - return capsulateTf(ctx, () -> getTermFactory().createTerm(op, new Term[]{a1}, null, sjb.javaBlock)); + return capsulateTf(ctx, + () -> getTermFactory().createTerm(op, new Term[] { a1 }, null, sjb.javaBlock)); } @Override @@ -1089,8 +1083,7 @@ public Object visitChar_literal(KeYParser.Char_literalContext ctx) { semanticError(ctx, "'" + s + "' is not a valid character."); } } - return getTermFactory().createTerm( - functions().lookup(new Name("C")), + return getTermFactory().createTerm(functions().lookup(new Name("C")), toZNotation("" + intVal, functions()).sub(0)); } @@ -1110,14 +1103,14 @@ public Object visitFuncpred_name(KeYParser.Funcpred_nameContext ctx) { List parts = mapOf(ctx.name.simple_ident()); String varfuncid = ctx.name.getText(); - if (ctx.name.INT_LITERAL() != null) {//number + if (ctx.name.INT_LITERAL() != null) {// number return toZNotation(ctx.name.INT_LITERAL().getText(), functions()); } assert parts != null && varfuncid != null; - boolean javaReference = parts.size() > 1 - && (isPackage(parts.get(0)) || isClass(parts.get(0))); + boolean javaReference = + parts.size() > 1 && (isPackage(parts.get(0)) || isClass(parts.get(0))); if (javaReference) { return splitJava(parts); @@ -1130,7 +1123,8 @@ public Object visitFuncpred_name(KeYParser.Funcpred_nameContext ctx) { Operator op; if (varfuncid.endsWith(LIMIT_SUFFIX)) { varfuncid = varfuncid.substring(0, varfuncid.length() - 5); - op = lookupVarfuncId(ctx, varfuncid, ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); + op = lookupVarfuncId(ctx, varfuncid, + ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); if (ObserverFunction.class.isAssignableFrom(op.getClass())) { op = getServices().getSpecificationRepository() .limitObs((ObserverFunction) op).first; @@ -1138,11 +1132,14 @@ public Object visitFuncpred_name(KeYParser.Funcpred_nameContext ctx) { semanticError(ctx, "Cannot can be limited: " + op); } } else { - String firstName = ctx.name.simple_ident().size() == 0 ? ctx.name.INT_LITERAL().getText() - : ctx.name.simple_ident(0).getText(); - op = lookupVarfuncId(ctx, firstName, ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); + String firstName = + ctx.name.simple_ident().size() == 0 ? ctx.name.INT_LITERAL().getText() + : ctx.name.simple_ident(0).getText(); + op = lookupVarfuncId(ctx, firstName, + ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); if (op instanceof ProgramVariable && ctx.name.simple_ident().size() > 1) { - List otherParts = ctx.name.simple_ident().subList(1, ctx.name.simple_ident().size()); + List otherParts = + ctx.name.simple_ident().subList(1, ctx.name.simple_ident().size()); ProgramVariable v = (ProgramVariable) op; Term tv = getServices().getTermFactory().createTerm(v); String memberName = otherParts.get(0).getText(); @@ -1151,7 +1148,8 @@ public Object visitFuncpred_name(KeYParser.Funcpred_nameContext ctx) { return getServices().getTermBuilder().seqLen(tv); } else { semanticError(ctx, - "There is no attribute '%s'for sequences (Seq), only 'length' is supported.", memberName); + "There is no attribute '%s'for sequences (Seq), only 'length' is supported.", + memberName); } } memberName = StringUtil.trim(memberName, "()"); @@ -1165,40 +1163,47 @@ public Object visitFuncpred_name(KeYParser.Funcpred_nameContext ctx) { private Term visitAccesstermAsJava(KeYParser.AccesstermContext ctx) { String firstName = accept(ctx.firstName); if (isPackage(firstName) || isClass(firstName)) { - //consume suffix as long as it is part of a java class or package + // consume suffix as long as it is part of a java class or package String javaPackage = isPackage(firstName) ? firstName : ""; boolean startWithPackage = isPackage(firstName); String javaClass = isClass(firstName) ? firstName : ""; int currentSuffix = 0; - //region split up package and class name - while (startWithPackage && ctx.attribute(currentSuffix) instanceof KeYParser.Attribute_simpleContext) { - KeYParser.Attribute_simpleContext a = (KeYParser.Attribute_simpleContext) ctx.attribute(currentSuffix); - if (a.heap != null) break; //No heap on java package allowed - @Nullable Object cur = accept(a.id); + // region split up package and class name + while (startWithPackage + && ctx.attribute(currentSuffix) instanceof KeYParser.Attribute_simpleContext) { + KeYParser.Attribute_simpleContext a = + (KeYParser.Attribute_simpleContext) ctx.attribute(currentSuffix); + if (a.heap != null) + break; // No heap on java package allowed + @Nullable + Object cur = accept(a.id); if (isPackage(javaPackage + "." + cur)) { javaPackage += "." + cur; currentSuffix++; - } else break; + } else + break; } while (ctx.attribute(currentSuffix) instanceof KeYParser.Attribute_simpleContext) { - KeYParser.Attribute_simpleContext a = (KeYParser.Attribute_simpleContext) ctx.attribute(currentSuffix); - if (a.heap != null) break; //No heap on java Class name allowed + KeYParser.Attribute_simpleContext a = + (KeYParser.Attribute_simpleContext) ctx.attribute(currentSuffix); + if (a.heap != null) + break; // No heap on java Class name allowed String cur = accept(a.id); String candidate = javaClass.isEmpty() ? cur : (javaClass + "." + cur); - if (isClass( - javaPackage + (javaPackage.isEmpty() ? "" : ".") + candidate)) { + if (isClass(javaPackage + (javaPackage.isEmpty() ? "" : ".") + candidate)) { javaClass = candidate; currentSuffix++; } else { break; } } - //endregion + // endregion - KeYJavaType kjt = getTypeByClassName(javaPackage + (javaPackage.isEmpty() ? "" : ".") + javaClass); + KeYJavaType kjt = getTypeByClassName( + javaPackage + (javaPackage.isEmpty() ? "" : ".") + javaClass); if (ctx.call() != null) { addWarning("Call of package or class"); @@ -1210,9 +1215,10 @@ private Term visitAccesstermAsJava(KeYParser.AccesstermContext ctx) { boolean isLast = i == ctx.attribute().size() - 1; if (attrib instanceof KeYParser.Attribute_simpleContext) { - KeYParser.Attribute_simpleContext simpleContext = (KeYParser.Attribute_simpleContext) attrib; + KeYParser.Attribute_simpleContext simpleContext = + (KeYParser.Attribute_simpleContext) attrib; boolean isCall = simpleContext.call() != null; - ParserRuleContext heap = simpleContext.heap; //TODO? + ParserRuleContext heap = simpleContext.heap; // TODO? String attributeName = accept(simpleContext.id); ProgramVariable maybeAttr = getJavaInfo().getAttribute(attributeName, kjt); if (maybeAttr != null) { @@ -1222,20 +1228,23 @@ private Term visitAccesstermAsJava(KeYParser.AccesstermContext ctx) { IProgramMethod pm = getStaticQuery(kjt, attributeName); if (pm != null) { Term[] args = visitArguments(simpleContext.call().argument_list()); - current = getJavaInfo().getStaticProgramMethodTerm(attributeName, args, kjt.getFullName()); + current = getJavaInfo().getStaticProgramMethodTerm(attributeName, args, + kjt.getFullName()); } else { semanticError(ctx, "Unknown java attribute: %s", attributeName); } - //TODO If not last attribute: + // TODO If not last attribute: addWarning(""); return current; } } else if (attrib instanceof KeYParser.Attribute_complexContext) { - KeYParser.Attribute_complexContext attrid = (KeYParser.Attribute_complexContext) attrib; + KeYParser.Attribute_complexContext attrid = + (KeYParser.Attribute_complexContext) attrib; String className = attrid.sort.getText(); String attributeName = attrid.id.getText(); Term[] args = visitArguments(attrid.call().argument_list()); - current = getServices().getJavaInfo().getStaticProgramMethodTerm(attributeName, args, className); + current = getServices().getJavaInfo().getStaticProgramMethodTerm(attributeName, + args, className); if (current == null) { final Sort sort = lookupSort(className); if (sort == null) { @@ -1243,13 +1252,13 @@ private Term visitAccesstermAsJava(KeYParser.AccesstermContext ctx) { } kjt = getServices().getJavaInfo().getKeYJavaType(sort); if (kjt == null) { - semanticError(ctx, "Found logic sort for " + className + - " but no corresponding java type!"); + semanticError(ctx, "Found logic sort for " + className + + " but no corresponding java type!"); } } return current; } else if (attrib instanceof KeYParser.Attribute_starContext) { - //TODO + // TODO } } return current; @@ -1278,7 +1287,8 @@ private Term handleAttributes(Term current, List att } return current; } else if (ctxSuffix instanceof KeYParser.Attribute_simpleContext) { - KeYParser.Attribute_simpleContext attrid = (KeYParser.Attribute_simpleContext) ctxSuffix; + KeYParser.Attribute_simpleContext attrid = + (KeYParser.Attribute_simpleContext) ctxSuffix; String memberName = attrid.id.getText(); Sort seqSort = lookupSort("Seq"); if (current.sort() == seqSort) { @@ -1295,11 +1305,14 @@ private Term handleAttributes(Term current, List att Term heap = accept(attrid.heap); if (isCall) { String classRef = current.sort().name().toString(); - KeYJavaType kjt = getTypeByClassName(classRef); //Why not direct use of Sort? - if (kjt == null) semanticError(ctxSuffix, "Could not find sort for %s", classRef); + KeYJavaType kjt = getTypeByClassName(classRef); // Why not direct use of + // Sort? + if (kjt == null) + semanticError(ctxSuffix, "Could not find sort for %s", classRef); assert kjt != null; classRef = kjt.getFullName(); - current = getServices().getJavaInfo().getProgramMethodTerm(current, memberName, sfxargs, classRef, true); + current = getServices().getJavaInfo().getProgramMethodTerm(current, + memberName, sfxargs, classRef, true); } else { Operator attr = getAttributeInPrefixSort(current.sort(), memberName); current = createAttributeTerm(current, attr, ctxSuffix); @@ -1309,18 +1322,21 @@ private Term handleAttributes(Term current, List att current = replaceHeap(current, heap, ctxSuffix); } } else if (ctxSuffix instanceof KeYParser.Attribute_complexContext) { - KeYParser.Attribute_complexContext attrid = (KeYParser.Attribute_complexContext) ctxSuffix; + KeYParser.Attribute_complexContext attrid = + (KeYParser.Attribute_complexContext) ctxSuffix; Term heap = accept(attrid.heap); String classRef = attrid.sort.getText(); String memberName = attrid.id.getText(); boolean isCall = attrid.call() != null; Term[] sfxargs = isCall ? visitArguments(attrid.call().argument_list()) : null; if (isCall) { - KeYJavaType kjt = getTypeByClassName(classRef); //Why not direct use of Sort? - if (kjt == null) semanticError(ctxSuffix, "Could not find sort for %s", classRef); + KeYJavaType kjt = getTypeByClassName(classRef); // Why not direct use of Sort? + if (kjt == null) + semanticError(ctxSuffix, "Could not find sort for %s", classRef); assert kjt != null; classRef = kjt.getFullName(); - current = getServices().getJavaInfo().getProgramMethodTerm(current, memberName, sfxargs, classRef, false); + current = getServices().getJavaInfo().getProgramMethodTerm(current, memberName, + sfxargs, classRef, false); } else { Operator op = getAttributeInPrefixSort(getTypeByClassName(classRef).getSort(), classRef + "::" + memberName); @@ -1334,7 +1350,9 @@ private Term handleAttributes(Term current, List att } KeYJavaType kjt = getServices().getJavaInfo().getKeYJavaType(sort); if (kjt == null) { - semanticError(ctxSuffix, "Found logic sort for %s but no corresponding java type!", classRef); + semanticError(ctxSuffix, + "Found logic sort for %s but no corresponding java type!", + classRef); } } if (heap != null) @@ -1355,9 +1373,10 @@ public T defaultOnException(T defaultValue, Supplier supplier) { @Override public Term visitAccessterm(KeYParser.AccesstermContext ctx) { Term t = visitAccesstermAsJava(ctx); - if (t != null) return t; + if (t != null) + return t; - //weigl: I am unsure if this is wise. + // weigl: I am unsure if this is wise. Sort sortId = defaultOnException(null, () -> accept(ctx.sortId())); String firstName = accept(ctx.simple_ident()); @@ -1367,8 +1386,7 @@ public Term visitAccessterm(KeYParser.AccesstermContext ctx) { if (ctx.call() != null) { orig = variables(); List bv = accept(ctx.call().boundVars); - boundVars = bv != null - ? new ImmutableArray<>(bv.toArray(new QuantifiableVariable[0])) + boundVars = bv != null ? new ImmutableArray<>(bv.toArray(new QuantifiableVariable[0])) : null; args = visitArguments(ctx.call().argument_list()); if (boundVars != null) { @@ -1383,7 +1401,8 @@ public Term visitAccessterm(KeYParser.AccesstermContext ctx) { op = UpdateJunctor.SKIP; } else if (firstName.endsWith(LIMIT_SUFFIX)) { firstName = firstName.substring(0, firstName.length() - 5); - op = lookupVarfuncId(ctx, firstName, ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); + op = lookupVarfuncId(ctx, firstName, + ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); if (ObserverFunction.class.isAssignableFrom(op.getClass())) { op = getServices().getSpecificationRepository() .limitObs((ObserverFunction) op).first; @@ -1391,7 +1410,8 @@ public Term visitAccessterm(KeYParser.AccesstermContext ctx) { semanticError(ctx, "Cannot can be limited: " + op); } } else { - op = lookupVarfuncId(ctx, firstName, ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); + op = lookupVarfuncId(ctx, firstName, + ctx.sortId() != null ? ctx.sortId().getText() : null, sortId); } Term current; @@ -1408,22 +1428,24 @@ public Term visitAccessterm(KeYParser.AccesstermContext ctx) { Term[] finalArgs = args; current = capsulateTf(ctx, () -> getTermFactory().createTerm(finalOp, finalArgs)); } else { - //sanity check + // sanity check assert op instanceof Function; for (int i = 0; i < args.length; i++) { if (i < op.arity() && !op.bindVarsAt(i)) { for (QuantifiableVariable qv : args[i].freeVars()) { if (boundVars.contains(qv)) { - semanticError(ctx, "Building function term " + op + " with bound variables failed: " - + "Variable " + qv + " must not occur free in subterm " + args[i]); + semanticError(ctx, "Building function term " + op + + " with bound variables failed: " + "Variable " + qv + + " must not occur free in subterm " + args[i]); } } } } ImmutableArray finalBoundVars = boundVars; - //create term + // create term Term[] finalArgs1 = args; - current = capsulateTf(ctx, () -> getTermFactory().createTerm(finalOp, finalArgs1, finalBoundVars, null)); + current = capsulateTf(ctx, () -> getTermFactory().createTerm(finalOp, finalArgs1, + finalBoundVars, null)); } } current = handleAttributes(current, ctx.attribute()); @@ -1465,29 +1487,28 @@ public Object visitInteger(KeYParser.IntegerContext ctx) { } private Term toZNotation(String number) { - return getTermFactory().createTerm( - functions().lookup(new Name("Z")), toNum(number)); + return getTermFactory().createTerm(functions().lookup(new Name("Z")), toNum(number)); } private Term toCNotation(String number) { - return getTermFactory().createTerm( - functions().lookup(new Name("C")), toNum(number)); + return getTermFactory().createTerm(functions().lookup(new Name("C")), toNum(number)); } private Term toFPNotation(String number) { - String decBitString = Integer.toUnsignedString(Float.floatToIntBits(Float.parseFloat(number))); - return getTermFactory().createTerm( - functions().lookup(new Name("FP")), - toNum(decBitString) - ); // toNum("0")); // soon to disappear + String decBitString = + Integer.toUnsignedString(Float.floatToIntBits(Float.parseFloat(number))); + return getTermFactory().createTerm(functions().lookup(new Name("FP")), toNum(decBitString)); // toNum("0")); + // // + // soon + // to + // disappear } private Term toDFPNotation(String number) { - String decBitString = Long.toUnsignedString(Double.doubleToLongBits(Double.parseDouble(number))); - return getTermFactory().createTerm( - functions().lookup(new Name("DFP")), - toNum(decBitString) - ); // toNum("0")); // soon to disappear + String decBitString = + Long.toUnsignedString(Double.doubleToLongBits(Double.parseDouble(number))); + return getTermFactory().createTerm(functions().lookup(new Name("DFP")), + toNum(decBitString)); // toNum("0")); // soon to disappear } private Term toNum(String number) { @@ -1496,18 +1517,19 @@ private Term toNum(String number) { if (negative) { s = number.substring(1, s.length()); } - if(s.startsWith("0x")) { + if (s.startsWith("0x")) { try { - BigInteger bi = new BigInteger(s.substring(2),16); + BigInteger bi = new BigInteger(s.substring(2), 16); s = bi.toString(); - } catch(NumberFormatException nfe) { + } catch (NumberFormatException nfe) { Debug.fail("Not a hexadecimal constant (BTW, this should not have happened)."); } } Term result = getTermFactory().createTerm(functions().lookup(new Name("#"))); - for(int i = 0; i vars) { final Iterator it = vars.iterator(); while (it.hasNext()) { result.append(it.next().getContainerType().getFullName()); - if (it.hasNext()) result.append(", "); + if (it.hasNext()) + result.append(", "); } return result.toString(); } @@ -1606,8 +1620,8 @@ private boolean isPackage(String name) { } protected boolean isHeapTerm(Term term) { - return term != null && term.sort() == - getServices().getTypeConverter().getHeapLDT().targetSort(); + return term != null + && term.sort() == getServices().getTypeConverter().getHeapLDT().targetSort(); } private boolean isSequenceTerm(Term reference) { @@ -1618,7 +1632,8 @@ private boolean isIntTerm(Term reference) { return reference.sort().name().equals(IntegerLDT.NAME); } - private ImmutableSet lookupOperatorSV(String opName, ImmutableSet modalities) { + private ImmutableSet lookupOperatorSV(String opName, + ImmutableSet modalities) { SchemaVariable sv = schemaVariables().lookup(new Name(opName)); if (sv == null || !(sv instanceof ModalOperatorSV)) { semanticError(null, "Schema variable " + opName + " not defined."); @@ -1633,8 +1648,8 @@ private boolean isImplicitHeap(Term t) { } /** - * Guard for {@link #replaceHeap0(Term, Term, ParserRuleContext)} - * to protect the double application of {@code @heap}. + * Guard for {@link #replaceHeap0(Term, Term, ParserRuleContext)} to protect the double + * application of {@code @heap}. * * @param term * @param heap @@ -1642,7 +1657,8 @@ private boolean isImplicitHeap(Term t) { * @return */ private Term replaceHeap(Term term, Term heap, ParserRuleContext ctx) { - if (explicitHeap.contains(term)) return term; + if (explicitHeap.contains(term)) + return term; Term t = replaceHeap0(term, heap, ctx); markHeapAsExplicit(t); return t; @@ -1651,14 +1667,17 @@ private Term replaceHeap(Term term, Term heap, ParserRuleContext ctx) { private Term replaceHeap0(Term term, Term heap, ParserRuleContext ctx) { if (isSelectTerm(term)) { if (!isImplicitHeap(term.sub(0))) { - //semanticError(null, "Expecting program variable heap as first argument of: %s", term); + // semanticError(null, "Expecting program variable heap as first argument of: %s", + // term); return term; } - Term[] params = new Term[]{heap, replaceHeap(term.sub(1), heap, ctx), term.sub(2)}; - return capsulateTf(ctx, () -> getServices().getTermFactory().createTerm(term.op(), params)); + Term[] params = new Term[] { heap, replaceHeap(term.sub(1), heap, ctx), term.sub(2) }; + return capsulateTf(ctx, + () -> getServices().getTermFactory().createTerm(term.op(), params)); } else if (term.op() instanceof ObserverFunction) { if (!isImplicitHeap(term.sub(0))) { - semanticError(null, "Expecting program variable heap as first argument of: %s", term); + semanticError(null, "Expecting program variable heap as first argument of: %s", + term); } Term[] params = new Term[term.arity()]; @@ -1668,7 +1687,8 @@ private Term replaceHeap0(Term term, Term heap, ParserRuleContext ctx) { params[i] = term.sub(i); } - return capsulateTf(ctx, () -> getServices().getTermFactory().createTerm(term.op(), params)); + return capsulateTf(ctx, + () -> getServices().getTermFactory().createTerm(term.op(), params)); } return term; @@ -1679,7 +1699,8 @@ private Term replaceHeap0(Term term, Term heap, ParserRuleContext ctx) { */ protected Term heapSelectionSuffix(Term term, Term heap, ParserRuleContext ctx) { if (!isHeapTerm(heap)) { - semanticError(null, "Expecting term of type Heap but sort is %s for term %s", heap.sort(), term); + semanticError(null, "Expecting term of type Heap but sort is %s for term %s", + heap.sort(), term); } Term result = replaceHeap(term, heap, ctx); return result; @@ -1721,9 +1742,8 @@ private JavaQuery splitJava(List parts) { final long packageEnd = i - 1; for (i = 0; i < parts.size(); i++) { String test = parts.stream() - //.skip(packageEnd) - .limit(i + packageEnd) - .collect(Collectors.joining(".")); + // .skip(packageEnd) + .limit(i + packageEnd).collect(Collectors.joining(".")); kjt = getTypeByClassName(test); if (kjt != null) { className = test; @@ -1746,22 +1766,16 @@ public AbbrevMap getAbbrevMap() { } private static class PairOfStringAndJavaBlock { - String opName; - JavaBlock javaBlock; -} + String opName; + JavaBlock javaBlock; + } - /*private boolean isStaticAttribute(String dotName) { - final JavaInfo javaInfo = getJavaInfo(); - String[] javaParts = splitJava(dotName); - KeYJavaType kjt = getTypeByClassName(javaParts[1]); - if (kjt != null) { - ProgramVariable maybeAttr = javaInfo.getAttribute(javaParts[2], kjt); - if (maybeAttr != null) { - return true; - } - } - return false; - }*/ + /* + * private boolean isStaticAttribute(String dotName) { final JavaInfo javaInfo = getJavaInfo(); + * String[] javaParts = splitJava(dotName); KeYJavaType kjt = getTypeByClassName(javaParts[1]); + * if (kjt != null) { ProgramVariable maybeAttr = javaInfo.getAttribute(javaParts[2], kjt); if + * (maybeAttr != null) { return true; } } return false; } + */ } @@ -1776,4 +1790,4 @@ class JavaQuery { this.attributeNames = attributeNames; this.kjt = kjt; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FindProblemInformation.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FindProblemInformation.java index 020c503b6b6..7728b4e2fad 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FindProblemInformation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FindProblemInformation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.nparser.KeYParser; @@ -16,8 +19,7 @@ * @see #getProblemInformation() */ public class FindProblemInformation extends AbstractBuilder { - private final @Nonnull - ProblemInformation information = new ProblemInformation(); + private final @Nonnull ProblemInformation information = new ProblemInformation(); @Override public Object visitFile(KeYParser.FileContext ctx) { @@ -30,8 +32,8 @@ public Object visitDecls(KeYParser.DeclsContext ctx) { information.setProfile(acceptFirst(ctx.profile())); information.setPreferences(acceptFirst(ctx.preferences())); information.setBootClassPath(acceptFirst(ctx.bootClassPath())); - ctx.classPaths().forEach(it -> - information.getClasspath().addAll(Objects.requireNonNull(accept(it)))); + ctx.classPaths().forEach( + it -> information.getClasspath().addAll(Objects.requireNonNull(accept(it)))); information.setJavaSource(acceptFirst(ctx.javaSource())); return null; } @@ -94,8 +96,7 @@ public String visitPreferences(KeYParser.PreferencesContext ctx) { /** * The found problem information. */ - public @Nonnull - ProblemInformation getProblemInformation() { + public @Nonnull ProblemInformation getProblemInformation() { return information; } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java index 95b04ed77ca..91a93f6c602 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/FunctionPredicateBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.Services; @@ -16,12 +19,11 @@ /** - * This visitor evaluates all secondary (level 1) declarations. - * This includes: + * This visitor evaluates all secondary (level 1) declarations. This includes: *
        - *
      • Predicates
      • - *
      • Functions
      • - *
      • Transformers
      • + *
      • Predicates
      • + *
      • Functions
      • + *
      • Transformers
      • *
      *

      * These information are registered into the given {@link NamespaceSet}. @@ -47,9 +49,10 @@ public Object visitDecls(KeYParser.DeclsContext ctx) { @Override public Object visitFunctionMetaData(KeYParser.FunctionMetaDataContext ctx) { - MixFitInfo.Kind kind = ctx.PREFIX() != null - ? MixFitInfo.Kind.PREFIX : ctx.INFIX() != null ? MixFitInfo.Kind.INFIX - : MixFitInfo.Kind.POSTFIX != null ? MixFitInfo.Kind.POSTFIX : MixFitInfo.Kind.SHORTCUT; + MixFitInfo.Kind kind = ctx.PREFIX() != null ? MixFitInfo.Kind.PREFIX + : ctx.INFIX() != null ? MixFitInfo.Kind.INFIX + : MixFitInfo.Kind.POSTFIX != null ? MixFitInfo.Kind.POSTFIX + : MixFitInfo.Kind.SHORTCUT; return new MixFitInfo(kind, ctx.op.getText()); } @@ -73,22 +76,16 @@ public Object visitPred_decl(KeYParser.Pred_declContext ctx) { Sort genSort = lookupSort(sortName); if (genSort instanceof GenericSort) { assert argSorts != null; - p = SortDependingFunction.createFirstInstance( - (GenericSort) genSort, - new Name(baseName), - Sort.FORMULA, - argSorts.toArray(new Sort[0]), - false); + p = SortDependingFunction.createFirstInstance((GenericSort) genSort, + new Name(baseName), Sort.FORMULA, argSorts.toArray(new Sort[0]), false); } } if (p == null) { assert argSorts != null; - p = new Function(new Name(pred_name), - Sort.FORMULA, - argSorts.toArray(new Sort[0]), - whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - false, mixFitInfo); + p = new Function(new Name(pred_name), Sort.FORMULA, argSorts.toArray(new Sort[0]), + whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), false, + mixFitInfo); } if (lookup(p.name()) == null) { @@ -120,21 +117,15 @@ public Object visitFunc_decl(KeYParser.Func_declContext ctx) { String baseName = func_name.substring(separatorIndex + 2); Sort genSort = lookupSort(sortName); if (genSort instanceof GenericSort) { - f = SortDependingFunction.createFirstInstance( - (GenericSort) genSort, - new Name(baseName), - retSort, - argSorts.toArray(new Sort[0]), - unique); + f = SortDependingFunction.createFirstInstance((GenericSort) genSort, + new Name(baseName), retSort, argSorts.toArray(new Sort[0]), unique); } } if (f == null) { - f = new Function(new Name(func_name), - retSort, - argSorts.toArray(new Sort[0]), - whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), - unique, mixFitInfo); + f = new Function(new Name(func_name), retSort, argSorts.toArray(new Sort[0]), + whereToBind == null ? null : whereToBind.toArray(new Boolean[0]), unique, + mixFitInfo); } if (lookup(f.name()) == null) { @@ -156,9 +147,8 @@ public Object visitTransform_decl(KeYParser.Transform_declContext ctx) { Sort retSort = (Sort) (ctx.FORMULA() != null ? Sort.FORMULA : accept(ctx.sortId())); String trans_name = accept(ctx.funcpred_name()); List argSorts = accept(ctx.arg_sorts_or_formula()); - Transformer t = new Transformer(new Name(trans_name), - retSort, - new ImmutableArray<>(argSorts)); + Transformer t = + new Transformer(new Name(trans_name), retSort, new ImmutableArray<>(argSorts)); if (lookup(t.name()) == null) { functions().add(t); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/IncludeFinder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/IncludeFinder.java index 8a7439e495f..e41c3d58379 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/IncludeFinder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/IncludeFinder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.nparser.KeYParser; @@ -53,7 +56,8 @@ private void addInclude(String filename, boolean relativePath) throws MalformedU filename += ".key"; if (relativePath) { - filename = filename.replace('/', File.separatorChar); // Not required for Windows, but whatsoever + filename = filename.replace('/', File.separatorChar); // Not required for Windows, but + // whatsoever filename = filename.replace('\\', File.separatorChar); // Special handling for Linux URL path = new URL(base.getProtocol(), base.getHost(), base.getPort(), basePath + "/" + filename); @@ -71,4 +75,4 @@ private void addInclude(String filename, boolean relativePath) throws MalformedU public Includes getIncludes() { return includes; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ProblemFinder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ProblemFinder.java index 97cc3d29779..218e563f763 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ProblemFinder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/ProblemFinder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import de.uka.ilkd.key.java.Services; @@ -9,8 +12,8 @@ import javax.annotation.Nullable; /** - * This visitor finds the problem information (problemTerm, choosedContract, and proofObligation) - * of a {@link de.uka.ilkd.key.nparser.KeyAst.File}. + * This visitor finds the problem information (problemTerm, choosedContract, and proofObligation) of + * a {@link de.uka.ilkd.key.nparser.KeyAst.File}. * * @author weigl */ @@ -39,14 +42,14 @@ public Term visitProblem(KeYParser.ProblemContext ctx) { if (ctx.CHOOSECONTRACT() != null) { if (ctx.chooseContract != null) chooseContract = ParsingFacade.getValueDocumentation(ctx.chooseContract); - //.replace("\\\\:", ":"); + // .replace("\\\\:", ":"); else chooseContract = ""; } if (ctx.PROOFOBLIGATION() != null) { if (ctx.proofObligation != null) proofObligation = ParsingFacade.getValueDocumentation(ctx.proofObligation); - //.replace("\\\\:", ":"); + // .replace("\\\\:", ":"); else proofObligation = ""; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/TacletPBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/TacletPBuilder.java index a3470b6bd9d..35b39cd57eb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/TacletPBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/builder/TacletPBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.builder; import antlr.RecognitionException; @@ -63,7 +66,7 @@ public TacletPBuilder(Services services, NamespaceSet nss) { } public TacletPBuilder(Services services, NamespaceSet namespaces, - HashMap> taclet2Builder) { + HashMap> taclet2Builder) { this(services, namespaces); this.taclet2Builder = taclet2Builder; } @@ -78,8 +81,10 @@ public Object visitDecls(KeYParser.DeclsContext ctx) { @Override public Object visitRulesOrAxioms(KeYParser.RulesOrAxiomsContext ctx) { enableJavaSchemaMode(); - if (ctx.RULES() != null) axiomMode = false; - if (ctx.AXIOMS() != null) axiomMode = true; + if (ctx.RULES() != null) + axiomMode = false; + if (ctx.AXIOMS() != null) + axiomMode = true; List choices = accept(ctx.choices); if (choices != null) { this.requiredChoices = ImmutableSet.fromCollection(choices); @@ -162,11 +167,12 @@ public Taclet visitTaclet(KeYParser.TacletContext ctx) { return r; } - // schema var decls + // schema var decls setSchemaVariables(new Namespace<>(schemaVariables())); mapOf(ctx.one_schema_var_decl()); - if (ctx.ifSeq != null) ifSeq = accept(ctx.ifSeq); + if (ctx.ifSeq != null) + ifSeq = accept(ctx.ifSeq); int applicationRestriction = RewriteTaclet.NONE; if (!ctx.SAMEUPDATELEVEL().isEmpty()) { @@ -181,7 +187,8 @@ public Taclet visitTaclet(KeYParser.TacletContext ctx) { if (!ctx.SUCCEDENTPOLARITY().isEmpty()) { applicationRestriction |= RewriteTaclet.SUCCEDENT_POLARITY; } - @Nullable Object find = accept(ctx.find); + @Nullable + Object find = accept(ctx.find); TacletBuilder b = createTacletBuilderFor(find, applicationRestriction, ctx); currentTBuilder.push(b); b.setIfSequent(ifSeq); @@ -226,11 +233,11 @@ public Object visitModifiers(KeYParser.ModifiersContext ctx) { rs.forEach(b::addRuleSet); } - if (ctx.DISPLAYNAME() != null) {//last entry + if (ctx.DISPLAYNAME() != null) {// last entry b.setDisplayName(accept(ctx.dname)); } - if (ctx.HELPTEXT() != null) { //last entry + if (ctx.HELPTEXT() != null) { // last entry b.setHelpText(accept(ctx.htext)); } @@ -248,8 +255,10 @@ public Object visitVarexp(KeYParser.VarexpContext ctx) { boolean negated = ctx.NOT_() != null; String name = ctx.varexpId().getText(); List arguments = ctx.varexp_argument(); - List suitableManipulators = TacletBuilderManipulators.getConditionBuildersFor(name); - List parameters = ctx.parameter.stream().map(Token::getText).collect(Collectors.toList()); + List suitableManipulators = + TacletBuilderManipulators.getConditionBuildersFor(name); + List parameters = + ctx.parameter.stream().map(Token::getText).collect(Collectors.toList()); boolean applied = false; Object[] argCache = new Object[arguments.size()]; for (TacletBuilderCommand manipulator : suitableManipulators) { @@ -260,19 +269,15 @@ public Object visitVarexp(KeYParser.VarexpContext ctx) { } if (!applied) { LOGGER.warn("Found name-matching conditions with following type signature:"); - suitableManipulators.forEach( - it -> LOGGER.warn(Arrays.toString(it.getArgumentTypes()))); + suitableManipulators.forEach(it -> LOGGER.warn(Arrays.toString(it.getArgumentTypes()))); LOGGER.warn("But you gave {} arguments.\n", arguments.size()); semanticError(ctx, "Could not apply the given variable condition: %s", ctx.getText()); } return null; } - private boolean applyManipulator( - boolean negated, - Object[] args, - TacletBuilderCommand manipulator, - List arguments, + private boolean applyManipulator(boolean negated, Object[] args, + TacletBuilderCommand manipulator, List arguments, List parameters) { assert args.length == arguments.size(); ArgumentType[] types = manipulator.getArgumentTypes(); @@ -290,27 +295,25 @@ private boolean applyManipulator( } } - private Object evaluateVarcondArgument( - ArgumentType expectedType, - Object prevValue, + private Object evaluateVarcondArgument(ArgumentType expectedType, Object prevValue, KeYParser.Varexp_argumentContext ctx) { if (prevValue != null && expectedType.clazz.isAssignableFrom(prevValue.getClass())) { - return prevValue; //previous value is of suitable type, we do not re-evaluate + return prevValue; // previous value is of suitable type, we do not re-evaluate } switch (expectedType) { - case TYPE_RESOLVER: - return buildTypeResolver(ctx); - case SORT: - return accept(ctx.sortId()); - case JAVA_TYPE: - return getOrCreateJavaType(ctx.sortId()); - case VARIABLE: - return varId(ctx, ctx.getText()); - case STRING: - return ctx.getText(); - case TERM: - return accept(ctx.term()); + case TYPE_RESOLVER: + return buildTypeResolver(ctx); + case SORT: + return accept(ctx.sortId()); + case JAVA_TYPE: + return getOrCreateJavaType(ctx.sortId()); + case VARIABLE: + return varId(ctx, ctx.getText()); + case STRING: + return ctx.getText(); + case TERM: + return accept(ctx.term()); } assert false; return null; @@ -318,7 +321,8 @@ private Object evaluateVarcondArgument( private KeYJavaType getOrCreateJavaType(KeYParser.SortIdContext sortId) { KeYJavaType t = getJavaInfo().getKeYJavaType(sortId.getText()); - if (t != null) return t; + if (t != null) + return t; return new KeYJavaType((Sort) accept(sortId)); } @@ -380,10 +384,14 @@ public Object visitGoalspec(KeYParser.GoalspecContext ctx) { ImmutableSLList addRList = ImmutableSLList.nil(); DefaultImmutableSet addpv = DefaultImmutableSet.nil(); - @Nullable Object rwObj = accept(ctx.replacewith()); - if (ctx.add() != null) addSeq = accept(ctx.add()); - if (ctx.addrules() != null) addRList = accept(ctx.addrules()); //modifies goalChoice - if (ctx.addprogvar() != null) addpv = accept(ctx.addprogvar()); + @Nullable + Object rwObj = accept(ctx.replacewith()); + if (ctx.add() != null) + addSeq = accept(ctx.add()); + if (ctx.addrules() != null) + addRList = accept(ctx.addrules()); // modifies goalChoice + if (ctx.addprogvar() != null) + addpv = accept(ctx.addprogvar()); addGoalTemplate(name, rwObj, addSeq, addRList, addpv, soc, ctx); return null; } @@ -416,31 +424,30 @@ public ImmutableList visitTacletlist(KeYParser.TacletlistContext ctx) { } @Nonnull - private TacletBuilder createTacletBuilderFor( - Object find, int applicationRestriction, ParserRuleContext ctx) { + private TacletBuilder createTacletBuilderFor(Object find, int applicationRestriction, + ParserRuleContext ctx) { if (find == null) { return new NoFindTacletBuilder(); } else if (find instanceof Term) { - return new RewriteTacletBuilder() - .setFind((Term) find) + return new RewriteTacletBuilder().setFind((Term) find) .setApplicationRestriction(applicationRestriction); } else if (find instanceof Sequent) { Sequent findSeq = (Sequent) find; if (findSeq.isEmpty()) { return new NoFindTacletBuilder(); - } else if (findSeq.antecedent().size() == 1 - && findSeq.succedent().size() == 0) { + } else if (findSeq.antecedent().size() == 1 && findSeq.succedent().size() == 0) { Term findFma = findSeq.antecedent().get(0).formula(); AntecTacletBuilder b = new AntecTacletBuilder(); b.setFind(findFma); - b.setIgnoreTopLevelUpdates((applicationRestriction & RewriteTaclet.IN_SEQUENT_STATE) == 0); + b.setIgnoreTopLevelUpdates( + (applicationRestriction & RewriteTaclet.IN_SEQUENT_STATE) == 0); return b; - } else if (findSeq.antecedent().size() == 0 - && findSeq.succedent().size() == 1) { + } else if (findSeq.antecedent().size() == 0 && findSeq.succedent().size() == 1) { Term findFma = findSeq.succedent().get(0).formula(); SuccTacletBuilder b = new SuccTacletBuilder(); b.setFind(findFma); - b.setIgnoreTopLevelUpdates((applicationRestriction & RewriteTaclet.IN_SEQUENT_STATE) == 0); + b.setIgnoreTopLevelUpdates( + (applicationRestriction & RewriteTaclet.IN_SEQUENT_STATE) == 0); return b; } else { semanticError(ctx, "Unknown find-sequent (perhaps null?):" + findSeq); @@ -453,13 +460,9 @@ private TacletBuilder createTacletBuilderFor( format("Could not find a suitable TacletBuilder for {0}", find)); } - private void addGoalTemplate(String id, - Object rwObj, - Sequent addSeq, - ImmutableList addRList, - ImmutableSet pvs, - @Nullable ImmutableSet soc, - ParserRuleContext ctx) { + private void addGoalTemplate(String id, Object rwObj, Sequent addSeq, + ImmutableList addRList, ImmutableSet pvs, + @Nullable ImmutableSet soc, ParserRuleContext ctx) { TacletBuilder b = peekTBuilder(); TacletGoalTemplate gt = null; if (rwObj == null) { @@ -469,35 +472,31 @@ private void addGoalTemplate(String id, if (b instanceof NoFindTacletBuilder) { // there is a replacewith without a find. throwEx(new RecognitionException("")); - } else if (b instanceof SuccTacletBuilder - || b instanceof AntecTacletBuilder) { + } else if (b instanceof SuccTacletBuilder || b instanceof AntecTacletBuilder) { if (rwObj instanceof Sequent) { - gt = new AntecSuccTacletGoalTemplate(addSeq, - addRList, - (Sequent) rwObj, - pvs); + gt = new AntecSuccTacletGoalTemplate(addSeq, addRList, (Sequent) rwObj, pvs); } else { - semanticError(ctx, //new UnfittingReplacewithException + semanticError(ctx, // new UnfittingReplacewithException "Replacewith in a Antec-or SuccTaclet has to contain a sequent (not a term)"); } } else if (b instanceof RewriteTacletBuilder) { if (rwObj instanceof Term) { - gt = new RewriteTacletGoalTemplate(addSeq, - addRList, - (Term) rwObj, - pvs); + gt = new RewriteTacletGoalTemplate(addSeq, addRList, (Term) rwObj, pvs); } else { - //throwEx(/new UnfittingReplacewithException - semanticError(ctx, "Replacewith in a RewriteTaclet has to contain a term (not a sequent)"); + // throwEx(/new UnfittingReplacewithException + semanticError(ctx, + "Replacewith in a RewriteTaclet has to contain a term (not a sequent)"); } } } if (gt == null) - throw new NullPointerException("Could not find a suitable goal template builder for: " + b.getClass()); + throw new NullPointerException( + "Could not find a suitable goal template builder for: " + b.getClass()); gt.setName(id); b.addTacletGoalTemplate(gt); - if (soc != null) b.addGoal2ChoicesMapping(gt, soc); + if (soc != null) + b.addGoal2ChoicesMapping(gt, soc); } @Override @@ -588,9 +587,8 @@ public Object visitOne_schema_var_decl(KeYParser.One_schema_var_declContext ctx) s = accept(ctx.sortId()); for (String id : ids) { - declareSchemaVariable(ctx, id, - s, makeVariableSV, makeSkolemTermSV, - makeTermLabelSV, mods); + declareSchemaVariable(ctx, id, s, makeVariableSV, makeSkolemTermSV, makeTermLabelSV, + mods); } return null; } @@ -601,7 +599,8 @@ public Object visitSchema_modifiers(KeYParser.Schema_modifiersContext ctx) { List ids = visitSimple_ident_comma_list(ctx.simple_ident_comma_list()); for (String id : ids) { if (!mods.addModifier(id)) - semanticError(ctx, "Illegal or unknown modifier in declaration of schema variable: %s", id); + semanticError(ctx, + "Illegal or unknown modifier in declaration of schema variable: %s", id); } return null; } @@ -611,47 +610,41 @@ public Object visitSchema_var_decls(KeYParser.Schema_var_declsContext ctx) { return this.mapOf(ctx.one_schema_var_decl()); } - protected void declareSchemaVariable( - ParserRuleContext ctx, - String name, Sort s, + protected void declareSchemaVariable(ParserRuleContext ctx, String name, Sort s, boolean makeVariableSV, boolean makeSkolemTermSV, boolean makeTermLabelSV, SchemaVariableModifierSet mods) { SchemaVariable v; if (s == Sort.FORMULA && !makeSkolemTermSV) { - v = SchemaVariableFactory.createFormulaSV(new Name(name), - mods.rigid()); + v = SchemaVariableFactory.createFormulaSV(new Name(name), mods.rigid()); } else if (s == Sort.UPDATE) { v = SchemaVariableFactory.createUpdateSV(new Name(name)); } else if (s instanceof ProgramSVSort) { - v = SchemaVariableFactory.createProgramSV( - new ProgramElementName(name), - (ProgramSVSort) s, - mods.list()); + v = SchemaVariableFactory.createProgramSV(new ProgramElementName(name), + (ProgramSVSort) s, mods.list()); } else { if (makeVariableSV) { - v = SchemaVariableFactory.createVariableSV - (new Name(name), s); + v = SchemaVariableFactory.createVariableSV(new Name(name), s); } else if (makeSkolemTermSV) { - v = SchemaVariableFactory.createSkolemTermSV(new Name(name), - s); + v = SchemaVariableFactory.createSkolemTermSV(new Name(name), s); } else if (makeTermLabelSV) { v = SchemaVariableFactory.createTermLabelSV(new Name(name)); } else { - v = SchemaVariableFactory.createTermSV( - new Name(name), - s, mods.rigid(), mods.strict()); + v = SchemaVariableFactory.createTermSV(new Name(name), s, mods.rigid(), + mods.strict()); } } if (variables().lookup(v.name()) != null) { - semanticError(null, "Schema variables shadows previous declared variable: %s.", v.name()); + semanticError(null, "Schema variables shadows previous declared variable: %s.", + v.name()); } if (schemaVariables().lookup(v.name()) != null) { SchemaVariable old = schemaVariables().lookup(v.name()); if (!old.sort().equals(v.sort())) semanticError(null, - "Schema variables clashes with previous declared schema variable: %s.", v.name()); + "Schema variables clashes with previous declared schema variable: %s.", + v.name()); LOGGER.error("Override: {} {}", old, v); } schemaVariables().add(v); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractConditionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractConditionBuilder.java index b5cf5e85171..3acbe86b071 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractConditionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractConditionBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import javax.annotation.Nonnull; @@ -6,10 +9,10 @@ * @author Alexander Weigl * @version 1 (12/9/19) */ -public abstract class AbstractConditionBuilder - extends AbstractTacletBuilderCommand +public abstract class AbstractConditionBuilder extends AbstractTacletBuilderCommand implements ConditionBuilder { - public AbstractConditionBuilder(@Nonnull String triggerName, @Nonnull ArgumentType... argumentsTypes) { + public AbstractConditionBuilder(@Nonnull String triggerName, + @Nonnull ArgumentType... argumentsTypes) { super(triggerName, argumentsTypes); } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractTacletBuilderCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractTacletBuilderCommand.java index f5d202b4132..fec1f8f6c6c 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractTacletBuilderCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/AbstractTacletBuilderCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import javax.annotation.Nonnull; @@ -13,13 +16,14 @@ public abstract class AbstractTacletBuilderCommand implements TacletBuilderComma private final @Nonnull ArgumentType[] argumentsTypes; /** - * Construct this class with the parameters for {@link #isSuitableFor(String)} and {@link #getArgumentTypes()}. + * Construct this class with the parameters for {@link #isSuitableFor(String)} and + * {@link #getArgumentTypes()}. * - * @param triggerName the name of this command. + * @param triggerName the name of this command. * @param argumentsTypes the argument type of this command. */ public AbstractTacletBuilderCommand(@Nonnull String triggerName, - @Nonnull ArgumentType... argumentsTypes) { + @Nonnull ArgumentType... argumentsTypes) { this.triggerName = triggerName; this.argumentsTypes = argumentsTypes; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ArgumentType.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ArgumentType.java index deb20d1ac3a..22f29c6d797 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ArgumentType.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ArgumentType.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -14,16 +17,12 @@ * @see TacletBuilderCommand */ public enum ArgumentType { - TYPE_RESOLVER(TypeResolver.class), - SORT(Sort.class), - TERM(Term.class), - JAVA_TYPE(KeYJavaType.class), - VARIABLE(ParsableVariable.class), - STRING(String.class); + TYPE_RESOLVER(TypeResolver.class), SORT(Sort.class), TERM(Term.class), JAVA_TYPE( + KeYJavaType.class), VARIABLE(ParsableVariable.class), STRING(String.class); public final Class clazz; ArgumentType(Class clazz) { this.clazz = clazz; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConditionBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConditionBuilder.java index afdc0848e08..40007ec3ef0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConditionBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConditionBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import de.uka.ilkd.key.rule.VariableCondition; @@ -13,11 +16,11 @@ */ public interface ConditionBuilder extends TacletBuilderCommand { /** - * Should construct a variable condition for the given arguments and parameters. - * The arguments are the adhering the type specified in {@link #getArgumentTypes()}. + * Should construct a variable condition for the given arguments and parameters. The arguments + * are the adhering the type specified in {@link #getArgumentTypes()}. *

      - * For a varcond {@code \varcond(\abc[p1,p2](a1, a2))} the arguments are a1 and a2, - * the parameters are p1 and p2. {@code negated} is true if {@code \not} is used. + * For a varcond {@code \varcond(\abc[p1,p2](a1, a2))} the arguments are a1 and a2, the + * parameters are p1 and p2. {@code negated} is true if {@code \not} is used. */ VariableCondition build(Object[] arguments, List parameters, boolean negated); @@ -27,7 +30,8 @@ public interface ConditionBuilder extends TacletBuilderCommand { * @see TacletBuilderCommand#apply(TacletBuilder, Object[], List, boolean) */ @Override - default void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated) { + default void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, + boolean negated) { VariableCondition condition = build(arguments, parameters, negated); tacletBuilder.addVariableCondition(condition); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConstructorBasedBuilder.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConstructorBasedBuilder.java index 2c33dd24047..a2a977a2404 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConstructorBasedBuilder.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/ConstructorBasedBuilder.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import de.uka.ilkd.key.rule.VariableCondition; @@ -11,11 +14,13 @@ public class ConstructorBasedBuilder extends AbstractConditionBuilder { private final Class clazz; private final boolean negationSupported; - public ConstructorBasedBuilder(String name, Class clazz, ArgumentType... types) { + public ConstructorBasedBuilder(String name, Class clazz, + ArgumentType... types) { this(name, lastArgumentOfFirstContructorIsBoolean(clazz), clazz, types); } - private static boolean lastArgumentOfFirstContructorIsBoolean(Class clazz) { + private static boolean lastArgumentOfFirstContructorIsBoolean( + Class clazz) { try { Class[] types = clazz.getConstructors()[0].getParameterTypes(); return types[types.length - 1] == Boolean.class @@ -25,7 +30,8 @@ private static boolean lastArgumentOfFirstContructorIsBoolean(Class clazz, ArgumentType... types) { + public ConstructorBasedBuilder(String name, boolean negationSupported, + Class clazz, ArgumentType... types) { super(name, types); this.clazz = clazz; this.negationSupported = negationSupported; @@ -46,9 +52,7 @@ public VariableCondition build(Object[] arguments, List parameters, bool for (Constructor constructor : clazz.getConstructors()) { try { return (VariableCondition) constructor.newInstance(args); - } catch (InstantiationException - | IllegalAccessException - | InvocationTargetException + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderCommand.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderCommand.java index 03bcac03d17..70059d2f470 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderCommand.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderCommand.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import de.uka.ilkd.key.rule.tacletbuilder.TacletBuilder; @@ -6,29 +9,29 @@ import java.util.List; /** - * This interface describes a commands that manipulate - * taclets during construction in the parser. + * This interface describes a commands that manipulate taclets during construction in the parser. *

      - * Currently, we use this interface to handle the construction - * of {@link de.uka.ilkd.key.rule.VariableCondition} ({@code \varcond}), - * but may be used in future for other facilities. + * Currently, we use this interface to handle the construction of + * {@link de.uka.ilkd.key.rule.VariableCondition} ({@code \varcond}), but may be used in future for + * other facilities. * * @author Alexander Weigl * @version 1 (12/9/19) */ public interface TacletBuilderCommand { /** - * Checks if this command is responsible for the given command name. - * For example, for {@code \varcond(\newType(t))} the name would be "newType". + * Checks if this command is responsible for the given command name. For example, for + * {@code \varcond(\newType(t))} the name would be "newType". */ boolean isSuitableFor(@Nonnull String name); /** - * Defines the amount and type of expected arguments. - * For example, if you want describe a sub-type test (instanceOf) - * you would need two sorts {@code new ArgumentType[]{SORT,SORT} } as arguments. + * Defines the amount and type of expected arguments. For example, if you want describe a + * sub-type test (instanceOf) you would need two sorts {@code new ArgumentType[]{SORT,SORT} } as + * arguments. *

      - * The parse guarantees, that the types are suitable, when calling {@link #apply(TacletBuilder, Object[], List, boolean)}. + * The parse guarantees, that the types are suitable, when calling + * {@link #apply(TacletBuilder, Object[], List, boolean)}. *

      * * @see ArgumentType @@ -38,10 +41,11 @@ public interface TacletBuilderCommand { /** * Applying this command on the given taclet builder. *

      - * During application, this method should alter, e.g., add a {@link de.uka.ilkd.key.rule.VariableCondition}, - * to the taclet builder. + * During application, this method should alter, e.g., add a + * {@link de.uka.ilkd.key.rule.VariableCondition}, to the taclet builder. *

      * The given arguments are well-typed for supplied {@link #getArgumentTypes()}. */ - void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated); + void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, + boolean negated); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderManipulators.java b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderManipulators.java index 3ade4aadc48..0a2c15d3e08 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderManipulators.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/nparser/varexp/TacletBuilderManipulators.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.nparser.varexp; import de.uka.ilkd.key.java.abstraction.KeYJavaType; @@ -22,13 +25,14 @@ import static de.uka.ilkd.key.rule.conditions.TypeComparisonCondition.Mode.*; /** - * This class manages the register of various factories for the different built-in {@link VariableCondition}s. + * This class manages the register of various factories for the different built-in + * {@link VariableCondition}s. * * @author Alexander Weigl * @version 1 (12/9/19) */ public class TacletBuilderManipulators { - //region Factories + // region Factories // Short cut for argument types private static final ArgumentType TR = TYPE_RESOLVER; private static final ArgumentType KJT = ArgumentType.JAVA_TYPE; @@ -46,90 +50,108 @@ public class TacletBuilderManipulators { /** * */ - public static final AbstractConditionBuilder ABSTRACT_OR_INTERFACE - = new ConstructorBasedBuilder("isAbstractOrInterface", AbstractOrInterfaceType.class, TR); + public static final AbstractConditionBuilder ABSTRACT_OR_INTERFACE = + new ConstructorBasedBuilder("isAbstractOrInterface", AbstractOrInterfaceType.class, TR); /** * */ - public static final AbstractConditionBuilder SAME = new AbstractConditionBuilder("same", TR, TR) { - @Override - public TypeComparisonCondition build(Object[] arguments, List parameters, boolean negated) { - return new TypeComparisonCondition((TypeResolver) arguments[0], - (TypeResolver) arguments[1], negated ? NOT_SAME : TypeComparisonCondition.Mode.SAME); - } - }; + public static final AbstractConditionBuilder SAME = + new AbstractConditionBuilder("same", TR, TR) { + @Override + public TypeComparisonCondition build(Object[] arguments, List parameters, + boolean negated) { + return new TypeComparisonCondition((TypeResolver) arguments[0], + (TypeResolver) arguments[1], + negated ? NOT_SAME : TypeComparisonCondition.Mode.SAME); + } + }; /** * */ - public static final AbstractConditionBuilder IS_SUBTYPE = new AbstractConditionBuilder("sub", TR, TR) { - @Override - public TypeComparisonCondition build(Object[] arguments, List parameters, boolean negated) { - return new TypeComparisonCondition((TypeResolver) arguments[0], - (TypeResolver) arguments[1], negated ? NOT_IS_SUBTYPE : TypeComparisonCondition.Mode.IS_SUBTYPE); - } - }; + public static final AbstractConditionBuilder IS_SUBTYPE = + new AbstractConditionBuilder("sub", TR, TR) { + @Override + public TypeComparisonCondition build(Object[] arguments, List parameters, + boolean negated) { + return new TypeComparisonCondition((TypeResolver) arguments[0], + (TypeResolver) arguments[1], + negated ? NOT_IS_SUBTYPE : TypeComparisonCondition.Mode.IS_SUBTYPE); + } + }; /** * */ - public static final AbstractConditionBuilder STRICT = new AbstractConditionBuilder("scrictSub", TR, TR) { - @Override - public boolean isSuitableFor(@Nonnull String name) { - if (super.isSuitableFor(name)) return true; - return "\\strict\\sub".equalsIgnoreCase(name); - } - - @Override - public TypeComparisonCondition build(Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - return new TypeComparisonCondition((TypeResolver) arguments[0], - (TypeResolver) arguments[1], STRICT_SUBTYPE); - } - }; + public static final AbstractConditionBuilder STRICT = + new AbstractConditionBuilder("scrictSub", TR, TR) { + @Override + public boolean isSuitableFor(@Nonnull String name) { + if (super.isSuitableFor(name)) + return true; + return "\\strict\\sub".equalsIgnoreCase(name); + } + + @Override + public TypeComparisonCondition build(Object[] arguments, List parameters, + boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + return new TypeComparisonCondition((TypeResolver) arguments[0], + (TypeResolver) arguments[1], STRICT_SUBTYPE); + } + }; /** * */ - public static final AbstractConditionBuilder DISJOINT_MODULO_NULL = new AbstractConditionBuilder( - "disjointModuloNull", TR, TR) { - @Override - public TypeComparisonCondition build(Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - return new TypeComparisonCondition((TypeResolver) arguments[0], - (TypeResolver) arguments[1], DISJOINTMODULONULL); - } - }; + public static final AbstractConditionBuilder DISJOINT_MODULO_NULL = + new AbstractConditionBuilder("disjointModuloNull", TR, TR) { + @Override + public TypeComparisonCondition build(Object[] arguments, List parameters, + boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + return new TypeComparisonCondition((TypeResolver) arguments[0], + (TypeResolver) arguments[1], DISJOINTMODULONULL); + } + }; /** * */ - public static final AbstractTacletBuilderCommand NEW_LABEL - = new ConstructorBasedBuilder("newLabel", NewJumpLabelCondition.class, SV); + public static final AbstractTacletBuilderCommand NEW_LABEL = + new ConstructorBasedBuilder("newLabel", NewJumpLabelCondition.class, SV); /** * */ - public static final AbstractTacletBuilderCommand NEW_JAVATYPE = new AbstractTacletBuilderCommand("new", SV, KJT) { - @Override - public void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - KeYJavaType kjt = (KeYJavaType) arguments[1]; - tacletBuilder.addVarsNew((SchemaVariable) arguments[0], kjt); - } - }; - - public static final AbstractTacletBuilderCommand NEW_VAR = new AbstractTacletBuilderCommand("new", SV, SORT) { - @Override - public void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - SchemaVariable sv = (SchemaVariable) arguments[0]; - Sort sort = (Sort) arguments[1]; - //TODO weigl tacletBuilder.addVarsNew(sv, sort); - } - }; + public static final AbstractTacletBuilderCommand NEW_JAVATYPE = + new AbstractTacletBuilderCommand("new", SV, KJT) { + @Override + public void apply(TacletBuilder tacletBuilder, Object[] arguments, + List parameters, boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + KeYJavaType kjt = (KeYJavaType) arguments[1]; + tacletBuilder.addVarsNew((SchemaVariable) arguments[0], kjt); + } + }; + + public static final AbstractTacletBuilderCommand NEW_VAR = + new AbstractTacletBuilderCommand("new", SV, SORT) { + @Override + public void apply(TacletBuilder tacletBuilder, Object[] arguments, + List parameters, boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + SchemaVariable sv = (SchemaVariable) arguments[0]; + Sort sort = (Sort) arguments[1]; + // TODO weigl tacletBuilder.addVarsNew(sv, sort); + } + }; static class NotFreeInTacletBuilderCommand extends AbstractTacletBuilderCommand { @@ -138,7 +160,8 @@ public NotFreeInTacletBuilderCommand(@Nonnull ArgumentType... argumentsTypes) { } @Override - public void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated) { + public void apply(TacletBuilder tacletBuilder, Object[] arguments, + List parameters, boolean negated) { SchemaVariable x = (SchemaVariable) arguments[0]; for (int i = 1; i < arguments.length; i++) { tacletBuilder.addVarsNotFreeIn(x, (SchemaVariable) arguments[i]); @@ -146,105 +169,118 @@ public void apply(TacletBuilder tacletBuilder, Object[] arguments, List tacletBuilderCommands = new ArrayList<>(32); - public static final AbstractTacletBuilderCommand NEW_TYPE_OF = new AbstractTacletBuilderCommand( - "newTypeOf", SV, SV) { - - @Override - public void apply(TacletBuilder tacletBuilder, Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - tacletBuilder.addVarsNew((SchemaVariable) arguments[0], (SchemaVariable) arguments[1]); - - } - }; - public static final AbstractTacletBuilderCommand NEW_DEPENDING_ON = new AbstractTacletBuilderCommand( - "newDependingOn", SV, SV) { - @Override - public void apply(TacletBuilder tb, Object[] arguments, List parameters, boolean negated) { - if (negated) throw new IllegalArgumentException("Negation is not supported"); - tb.addVarsNewDependingOn((SchemaVariable) arguments[0], - (SchemaVariable) arguments[1]); - } - }; - - public static final AbstractConditionBuilder FREE_LABEL_IN_VARIABLE - = new ConstructorBasedBuilder("freeLabelIn", FreeLabelInVariableCondition.class, SV, SV); - public static final AbstractConditionBuilder DIFFERENT - = new ConstructorBasedBuilder("different", DifferentInstantiationCondition.class, SV, SV); - public static final AbstractConditionBuilder FINAL - = new ConstructorBasedBuilder("final", FinalReferenceCondition.class, SV); - public static final AbstractConditionBuilder ENUM_CONST - = new ConstructorBasedBuilder("isEnumConst", EnumConstantCondition.class, SV); - public static final AbstractConditionBuilder LOCAL_VARIABLE - = new ConstructorBasedBuilder("isLocalVariable", LocalVariableCondition.class, SV); - public static final AbstractConditionBuilder ARRAY_LENGTH - = new ConstructorBasedBuilder("isArrayLength", ArrayLengthCondition.class, SV); - public static final AbstractConditionBuilder ARRAY - = new ConstructorBasedBuilder("isArray", ArrayTypeCondition.class, SV); - public static final AbstractConditionBuilder REFERENCE_ARRAY - = new AbstractConditionBuilder("isReferenceArray", SV) { - @Override - public VariableCondition build(Object[] arguments, List parameters, boolean negated) { - return new ArrayComponentTypeCondition((SchemaVariable) arguments[0], !negated); - } - }; - public static final AbstractConditionBuilder MAY_EXPAND_METHOD_2 - = new ConstructorBasedBuilder("mayExpandMethod", MayExpandMethodCondition.class, SV, SV); - public static final AbstractConditionBuilder MAY_EXPAND_METHOD_3 - = new ConstructorBasedBuilder("mayExpandMethod", MayExpandMethodCondition.class, SV, SV, SV); - public static final AbstractConditionBuilder STATIC_METHOD - = new ConstructorBasedBuilder("staticMethodReference", StaticMethodCondition.class, SV, SV, SV); - public static final AbstractConditionBuilder THIS_REFERENCE - = new ConstructorBasedBuilder("isThisReference", IsThisReference.class, SV); - public static final AbstractConditionBuilder REFERENCE - = new AbstractConditionBuilder("isReference", TR) { - @Override - public VariableCondition build(Object[] arguments, List parameters, boolean negated) { - final boolean non_null = parameters.contains("non_null"); - return new TypeCondition((TypeResolver) arguments[0], !negated, non_null); - } - }; - public static final AbstractConditionBuilder ENUM_TYPE - = new ConstructorBasedBuilder("reference", EnumTypeCondition.class, SV, SV, SV); - public static final AbstractConditionBuilder CONTAINS_ASSIGNMENT - = new ConstructorBasedBuilder("containsAssignment", ContainsAssignmentCondition.class, SV); - public static final AbstractConditionBuilder FIELD_TYPE - = new ConstructorBasedBuilder("fieldType", FieldTypeToSortCondition.class, SV, SORT); - public static final AbstractConditionBuilder STATIC_REFERENCE - = new ConstructorBasedBuilder("static", StaticReferenceCondition.class, SV); - public static final TacletBuilderCommand DIFFERENT_FIELDS - = new ConstructorBasedBuilder("differentFields", DifferentFields.class, SV, SV); - public static final AbstractConditionBuilder SAME_OBSERVER - = new ConstructorBasedBuilder("sameObserver", SameObserverCondition.class, PV, PV); - public static AbstractConditionBuilder applyUpdateOnRigid - = new ConstructorBasedBuilder("applyUpdateOnRigid", ApplyUpdateOnRigidCondition.class, USV, SV, SV); - public static final AbstractConditionBuilder DROP_EFFECTLESS_ELEMENTARIES - = new ConstructorBasedBuilder("dropEffectlessElementaries", - DropEffectlessElementariesCondition.class, USV, SV, SV); - public static final AbstractConditionBuilder SIMPLIFY_ITE_UPDATE - = new ConstructorBasedBuilder("simplifyIfThenElseUpdate", - SimplifyIfThenElseUpdateCondition.class, FSV, USV, USV, FSV, SV); - public static final AbstractConditionBuilder SUBFORMULAS - = new ConstructorBasedBuilder("subFormulas", SubFormulaCondition.class, FSV); - public static final AbstractConditionBuilder STATIC_FIELD - = new ConstructorBasedBuilder("isStaticField", StaticFieldCondition.class, FSV); - public static final AbstractConditionBuilder SUBFORMULA - = new ConstructorBasedBuilder("hasSubFormulas", SubFormulaCondition.class, FSV); - public static final TacletBuilderCommand DROP_EFFECTLESS_STORES - = new ConstructorBasedBuilder("dropEffectlessStores", DropEffectlessStoresCondition.class, TSV, TSV, TSV, TSV, TSV); - public static final AbstractConditionBuilder EQUAL_UNIQUE - = new ConstructorBasedBuilder("equalUnique", EqualUniqueCondition.class, TSV, TSV, FSV); - public static final AbstractConditionBuilder META_DISJOINT - = new ConstructorBasedBuilder("metaDisjoint", MetaDisjointCondition.class, TSV, TSV); - public static final AbstractConditionBuilder IS_OBSERVER - = new ConstructorBasedBuilder("isObserver", ObserverCondition.class, TSV, TSV); - public static final AbstractConditionBuilder CONSTANT = new ConstructorBasedBuilder("isConstant", ConstantCondition.class, ASV); + public static final AbstractTacletBuilderCommand NEW_TYPE_OF = + new AbstractTacletBuilderCommand("newTypeOf", SV, SV) { + + @Override + public void apply(TacletBuilder tacletBuilder, Object[] arguments, + List parameters, boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + tacletBuilder.addVarsNew((SchemaVariable) arguments[0], + (SchemaVariable) arguments[1]); + + } + }; + public static final AbstractTacletBuilderCommand NEW_DEPENDING_ON = + new AbstractTacletBuilderCommand("newDependingOn", SV, SV) { + @Override + public void apply(TacletBuilder tb, Object[] arguments, List parameters, + boolean negated) { + if (negated) + throw new IllegalArgumentException("Negation is not supported"); + tb.addVarsNewDependingOn((SchemaVariable) arguments[0], + (SchemaVariable) arguments[1]); + } + }; + + public static final AbstractConditionBuilder FREE_LABEL_IN_VARIABLE = + new ConstructorBasedBuilder("freeLabelIn", FreeLabelInVariableCondition.class, SV, SV); + public static final AbstractConditionBuilder DIFFERENT = + new ConstructorBasedBuilder("different", DifferentInstantiationCondition.class, SV, SV); + public static final AbstractConditionBuilder FINAL = + new ConstructorBasedBuilder("final", FinalReferenceCondition.class, SV); + public static final AbstractConditionBuilder ENUM_CONST = + new ConstructorBasedBuilder("isEnumConst", EnumConstantCondition.class, SV); + public static final AbstractConditionBuilder LOCAL_VARIABLE = + new ConstructorBasedBuilder("isLocalVariable", LocalVariableCondition.class, SV); + public static final AbstractConditionBuilder ARRAY_LENGTH = + new ConstructorBasedBuilder("isArrayLength", ArrayLengthCondition.class, SV); + public static final AbstractConditionBuilder ARRAY = + new ConstructorBasedBuilder("isArray", ArrayTypeCondition.class, SV); + public static final AbstractConditionBuilder REFERENCE_ARRAY = + new AbstractConditionBuilder("isReferenceArray", SV) { + @Override + public VariableCondition build(Object[] arguments, List parameters, + boolean negated) { + return new ArrayComponentTypeCondition((SchemaVariable) arguments[0], !negated); + } + }; + public static final AbstractConditionBuilder MAY_EXPAND_METHOD_2 = + new ConstructorBasedBuilder("mayExpandMethod", MayExpandMethodCondition.class, SV, SV); + public static final AbstractConditionBuilder MAY_EXPAND_METHOD_3 = new ConstructorBasedBuilder( + "mayExpandMethod", MayExpandMethodCondition.class, SV, SV, SV); + public static final AbstractConditionBuilder STATIC_METHOD = new ConstructorBasedBuilder( + "staticMethodReference", StaticMethodCondition.class, SV, SV, SV); + public static final AbstractConditionBuilder THIS_REFERENCE = + new ConstructorBasedBuilder("isThisReference", IsThisReference.class, SV); + public static final AbstractConditionBuilder REFERENCE = + new AbstractConditionBuilder("isReference", TR) { + @Override + public VariableCondition build(Object[] arguments, List parameters, + boolean negated) { + final boolean non_null = parameters.contains("non_null"); + return new TypeCondition((TypeResolver) arguments[0], !negated, non_null); + } + }; + public static final AbstractConditionBuilder ENUM_TYPE = + new ConstructorBasedBuilder("reference", EnumTypeCondition.class, SV, SV, SV); + public static final AbstractConditionBuilder CONTAINS_ASSIGNMENT = new ConstructorBasedBuilder( + "containsAssignment", ContainsAssignmentCondition.class, SV); + public static final AbstractConditionBuilder FIELD_TYPE = + new ConstructorBasedBuilder("fieldType", FieldTypeToSortCondition.class, SV, SORT); + public static final AbstractConditionBuilder STATIC_REFERENCE = + new ConstructorBasedBuilder("static", StaticReferenceCondition.class, SV); + public static final TacletBuilderCommand DIFFERENT_FIELDS = + new ConstructorBasedBuilder("differentFields", DifferentFields.class, SV, SV); + public static final AbstractConditionBuilder SAME_OBSERVER = + new ConstructorBasedBuilder("sameObserver", SameObserverCondition.class, PV, PV); + public static AbstractConditionBuilder applyUpdateOnRigid = new ConstructorBasedBuilder( + "applyUpdateOnRigid", ApplyUpdateOnRigidCondition.class, USV, SV, SV); + public static final AbstractConditionBuilder DROP_EFFECTLESS_ELEMENTARIES = + new ConstructorBasedBuilder("dropEffectlessElementaries", + DropEffectlessElementariesCondition.class, USV, SV, SV); + public static final AbstractConditionBuilder SIMPLIFY_ITE_UPDATE = + new ConstructorBasedBuilder("simplifyIfThenElseUpdate", + SimplifyIfThenElseUpdateCondition.class, FSV, USV, USV, FSV, SV); + public static final AbstractConditionBuilder SUBFORMULAS = + new ConstructorBasedBuilder("subFormulas", SubFormulaCondition.class, FSV); + public static final AbstractConditionBuilder STATIC_FIELD = + new ConstructorBasedBuilder("isStaticField", StaticFieldCondition.class, FSV); + public static final AbstractConditionBuilder SUBFORMULA = + new ConstructorBasedBuilder("hasSubFormulas", SubFormulaCondition.class, FSV); + public static final TacletBuilderCommand DROP_EFFECTLESS_STORES = new ConstructorBasedBuilder( + "dropEffectlessStores", DropEffectlessStoresCondition.class, TSV, TSV, TSV, TSV, TSV); + public static final AbstractConditionBuilder EQUAL_UNIQUE = + new ConstructorBasedBuilder("equalUnique", EqualUniqueCondition.class, TSV, TSV, FSV); + public static final AbstractConditionBuilder META_DISJOINT = + new ConstructorBasedBuilder("metaDisjoint", MetaDisjointCondition.class, TSV, TSV); + public static final AbstractConditionBuilder IS_OBSERVER = + new ConstructorBasedBuilder("isObserver", ObserverCondition.class, TSV, TSV); + public static final AbstractConditionBuilder CONSTANT = + new ConstructorBasedBuilder("isConstant", ConstantCondition.class, ASV); static class JavaTypeToSortConditionBuilder extends AbstractConditionBuilder { private final boolean elmen; @@ -255,82 +291,89 @@ public JavaTypeToSortConditionBuilder(@Nonnull String triggerName, boolean force } @Override - public VariableCondition build(Object[] arguments, List parameters, boolean negated) { + public VariableCondition build(Object[] arguments, List parameters, + boolean negated) { SchemaVariable v = (SchemaVariable) arguments[0]; Sort s = (Sort) arguments[1]; if (!(s instanceof GenericSort)) { throw new IllegalArgumentException("Generic sort is expected. Got: " + s); } else if (!JavaTypeToSortCondition.checkSortedSV(v)) { - throw new IllegalArgumentException("Expected schema variable of kind EXPRESSION or TYPE, but is " + v); + throw new IllegalArgumentException( + "Expected schema variable of kind EXPRESSION or TYPE, but is " + v); } else { return new JavaTypeToSortCondition(v, (GenericSort) s, this.elmen); } } } - public static final AbstractConditionBuilder HAS_SORT = new JavaTypeToSortConditionBuilder("hasSort", false); - public static final AbstractConditionBuilder HAS_ELEM_SORT = new JavaTypeToSortConditionBuilder("hasElementarySort", true); - - public static final AbstractConditionBuilder LABEL - = new ConstructorBasedBuilder("hasLabel", TermLabelCondition.class, TSV, S); - //endregion - public static final AbstractConditionBuilder STORE_TERM_IN = new AbstractConditionBuilder( - "storeTermIn", SV, T) { - @Override - public VariableCondition build(Object[] arguments, List parameters, boolean negated) { - return new StoreTermInCondition((SchemaVariable) arguments[0], (Term) arguments[1]); - } - }; - - public static final AbstractConditionBuilder STORE_STMT_IN = new ConstructorBasedBuilder( - "storeStmtIn", StoreStmtInCondition.class, SV, T); - public static final AbstractConditionBuilder HAS_INVARIANT - = new ConstructorBasedBuilder("\\hasInvariant", HasLoopInvariantCondition.class, PV, SV); - public static final AbstractConditionBuilder GET_INVARIANT - = new ConstructorBasedBuilder("\\getInvariant", LoopInvariantCondition.class, PV, SV, SV); - public static final AbstractConditionBuilder GET_FREE_INVARIANT - = new ConstructorBasedBuilder("\\getFreeInvariant", LoopFreeInvariantCondition.class, PV, SV, SV); - public static final AbstractConditionBuilder GET_VARIANT - = new AbstractConditionBuilder("\\getVariant", PV, SV) { - @Override - public VariableCondition build(Object[] arguments, List parameters, boolean negated) { - return new LoopVariantCondition((ProgramSV) arguments[0], (SchemaVariable) arguments[1]); - } - }; - public static final AbstractConditionBuilder IS_LABELED = new AbstractConditionBuilder("isLabeled", PV) { - @Override - public IsLabeledCondition build(Object[] arguments, List parameters, boolean negated) { - return new IsLabeledCondition((ProgramSV) arguments[0], negated); - } - }; + public static final AbstractConditionBuilder HAS_SORT = + new JavaTypeToSortConditionBuilder("hasSort", false); + public static final AbstractConditionBuilder HAS_ELEM_SORT = + new JavaTypeToSortConditionBuilder("hasElementarySort", true); + + public static final AbstractConditionBuilder LABEL = + new ConstructorBasedBuilder("hasLabel", TermLabelCondition.class, TSV, S); + // endregion + public static final AbstractConditionBuilder STORE_TERM_IN = + new AbstractConditionBuilder("storeTermIn", SV, T) { + @Override + public VariableCondition build(Object[] arguments, List parameters, + boolean negated) { + return new StoreTermInCondition((SchemaVariable) arguments[0], + (Term) arguments[1]); + } + }; + + public static final AbstractConditionBuilder STORE_STMT_IN = + new ConstructorBasedBuilder("storeStmtIn", StoreStmtInCondition.class, SV, T); + public static final AbstractConditionBuilder HAS_INVARIANT = + new ConstructorBasedBuilder("\\hasInvariant", HasLoopInvariantCondition.class, PV, SV); + public static final AbstractConditionBuilder GET_INVARIANT = + new ConstructorBasedBuilder("\\getInvariant", LoopInvariantCondition.class, PV, SV, SV); + public static final AbstractConditionBuilder GET_FREE_INVARIANT = new ConstructorBasedBuilder( + "\\getFreeInvariant", LoopFreeInvariantCondition.class, PV, SV, SV); + public static final AbstractConditionBuilder GET_VARIANT = + new AbstractConditionBuilder("\\getVariant", PV, SV) { + @Override + public VariableCondition build(Object[] arguments, List parameters, + boolean negated) { + return new LoopVariantCondition((ProgramSV) arguments[0], + (SchemaVariable) arguments[1]); + } + }; + public static final AbstractConditionBuilder IS_LABELED = + new AbstractConditionBuilder("isLabeled", PV) { + @Override + public IsLabeledCondition build(Object[] arguments, List parameters, + boolean negated) { + return new IsLabeledCondition((ProgramSV) arguments[0], negated); + } + }; public static final AbstractConditionBuilder IS_IN_STRICTFP = new ConstructorBasedBuilder("isInStrictFp", InStrictFp.class); - //region Registry + // region Registry static { - register(SAME_OBSERVER, SIMPLIFY_ITE_UPDATE, - ABSTRACT_OR_INTERFACE, SAME, IS_SUBTYPE, - STRICT, DISJOINT_MODULO_NULL, NEW_JAVATYPE, NEW_VAR, - FREE_1, FREE_2, FREE_3, FREE_4, FREE_5, NEW_TYPE_OF, NEW_DEPENDING_ON, - FREE_LABEL_IN_VARIABLE, DIFFERENT, FINAL, ENUM_CONST, - LOCAL_VARIABLE, ARRAY_LENGTH, ARRAY, REFERENCE_ARRAY, MAY_EXPAND_METHOD_2, - MAY_EXPAND_METHOD_3, STATIC_METHOD, THIS_REFERENCE, REFERENCE, + register(SAME_OBSERVER, SIMPLIFY_ITE_UPDATE, ABSTRACT_OR_INTERFACE, SAME, IS_SUBTYPE, + STRICT, DISJOINT_MODULO_NULL, NEW_JAVATYPE, NEW_VAR, FREE_1, FREE_2, FREE_3, FREE_4, + FREE_5, NEW_TYPE_OF, NEW_DEPENDING_ON, FREE_LABEL_IN_VARIABLE, DIFFERENT, FINAL, + ENUM_CONST, LOCAL_VARIABLE, ARRAY_LENGTH, ARRAY, REFERENCE_ARRAY, + MAY_EXPAND_METHOD_2, MAY_EXPAND_METHOD_3, STATIC_METHOD, THIS_REFERENCE, REFERENCE, ENUM_TYPE, CONTAINS_ASSIGNMENT, FIELD_TYPE, STATIC_REFERENCE, DIFFERENT_FIELDS, - SAME_OBSERVER, applyUpdateOnRigid, DROP_EFFECTLESS_ELEMENTARIES, SIMPLIFY_ITE_UPDATE, - SUBFORMULAS, STATIC_FIELD, SUBFORMULA, DROP_EFFECTLESS_STORES, EQUAL_UNIQUE, - META_DISJOINT, IS_OBSERVER, CONSTANT, HAS_SORT, LABEL, NEW_LABEL, HAS_ELEM_SORT, - IS_IN_STRICTFP - ); - register(STORE_TERM_IN, STORE_STMT_IN, HAS_INVARIANT, - GET_INVARIANT, GET_FREE_INVARIANT, GET_VARIANT, IS_LABELED); + SAME_OBSERVER, applyUpdateOnRigid, DROP_EFFECTLESS_ELEMENTARIES, + SIMPLIFY_ITE_UPDATE, SUBFORMULAS, STATIC_FIELD, SUBFORMULA, DROP_EFFECTLESS_STORES, + EQUAL_UNIQUE, META_DISJOINT, IS_OBSERVER, CONSTANT, HAS_SORT, LABEL, NEW_LABEL, + HAS_ELEM_SORT, IS_IN_STRICTFP); + register(STORE_TERM_IN, STORE_STMT_IN, HAS_INVARIANT, GET_INVARIANT, GET_FREE_INVARIANT, + GET_VARIANT, IS_LABELED); loadWithServiceLoader(); } /** - * Announce a {@link TacletBuilderCommand} for the use during the interpretation of asts. - * This affects every following interpretation of rule contextes - * in {@link de.uka.ilkd.key.nparser.builder.TacletPBuilder}. + * Announce a {@link TacletBuilderCommand} for the use during the interpretation of asts. This + * affects every following interpretation of rule contextes in + * {@link de.uka.ilkd.key.nparser.builder.TacletPBuilder}. */ public static void register(TacletBuilderCommand... cb) { for (TacletBuilderCommand a : cb) { @@ -346,10 +389,12 @@ public static void register(TacletBuilderCommand cb) { } /** - * Register all {@link TacletBuilderCommand} that are found via the Java's {@link ServiceLoader} facility. + * Register all {@link TacletBuilderCommand} that are found via the Java's {@link ServiceLoader} + * facility. */ public static void loadWithServiceLoader() { - ServiceLoader serviceLoader = ServiceLoader.load(TacletBuilderCommand.class); + ServiceLoader serviceLoader = + ServiceLoader.load(TacletBuilderCommand.class); serviceLoader.iterator().forEachRemaining(TacletBuilderManipulators::register); } @@ -366,7 +411,8 @@ public static List getConditionBuilders() { * @see TacletBuilderCommand#isSuitableFor(String) */ public static List getConditionBuildersFor(String name) { - return tacletBuilderCommands.stream().filter(it -> it.isSuitableFor(name)).collect(Collectors.toList()); + return tacletBuilderCommands.stream().filter(it -> it.isSuitableFor(name)) + .collect(Collectors.toList()); } - //endregion -} \ No newline at end of file + // endregion +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/AmbigiousDeclException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/AmbigiousDeclException.java index 512555e3321..b20f22659a8 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/AmbigiousDeclException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/AmbigiousDeclException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import org.antlr.runtime.RecognitionException; @@ -6,51 +9,48 @@ public class AmbigiousDeclException extends RecognitionException { /** - * + * */ private static final long serialVersionUID = 5836342271644427009L; String filename = "unknown"; String ambigious_symbol; Token t; - + public AmbigiousDeclException(String cat, Token t) { - this.ambigious_symbol = t.getText(); - this.filename = t.getFilename(); - this.line = t.getLine(); - this.charPositionInLine = t.getColumn(); + this.ambigious_symbol = t.getText(); + this.filename = t.getFilename(); + this.line = t.getLine(); + this.charPositionInLine = t.getColumn(); } - public AmbigiousDeclException(String ambigious_symbol, - String filename, - int line, - int column) { - this.filename = filename; - this.ambigious_symbol = ambigious_symbol; - this.line = line; - this.charPositionInLine = column; + public AmbigiousDeclException(String ambigious_symbol, String filename, int line, int column) { + this.filename = filename; + this.ambigious_symbol = ambigious_symbol; + this.line = line; + this.charPositionInLine = column; } + /** * Returns a clean error message (no line number/column information) + * * @deprecated */ @Deprecated - public String getErrorMessage () { - return getMessage(); + public String getErrorMessage() { + return getMessage(); } /** * Returns a clean error message (no line number/column information) */ - public String getMessage () - { - return "The name \'" + ambigious_symbol + "\' is already in use."; + public String getMessage() { + return "The name \'" + ambigious_symbol + "\' is already in use."; } - + /** * Returns a string representation of this exception. */ public String toString() { - return filename + "("+this.line+", "+this.charPositionInLine+"):\n" - + getMessage(); + return filename + "(" + this.line + ", " + this.charPositionInLine + "):\n" + getMessage(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/DefaultTermParser.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/DefaultTermParser.java index 671b7a88c22..c4bfe5f306d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/DefaultTermParser.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/DefaultTermParser.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.java.Services; @@ -25,91 +28,74 @@ * @author weigl * @deprecated Use the facade new KeyIO(services).parseTerm directly */ -@Deprecated//java11:(forRemoval = true, since = "2.8.0") +@Deprecated // java11:(forRemoval = true, since = "2.8.0") public final class DefaultTermParser { /** - * The method reads the input and parses a term with the - * specified namespaces. The method ensures, that the term has the - * specified sort. + * The method reads the input and parses a term with the specified namespaces. The method + * ensures, that the term has the specified sort. * * @param sort The expected sort of the term. * @return The parsed term of the specified sort. - * @throws ParserException The method throws a ParserException, if - * the input could not be parsed correctly or the term has an - * invalid sort. + * @throws ParserException The method throws a ParserException, if the input could not be parsed + * correctly or the term has an invalid sort. */ - public Term parse(Reader in, - Sort sort, - Services services, - Namespace var_ns, - Namespace func_ns, - Namespace sort_ns, - Namespace progVar_ns, - AbbrevMap scm) throws ParserException { - return parse(in, sort, services, - new NamespaceSet(var_ns, - func_ns, - sort_ns, - new Namespace<>(), - new Namespace<>(), - progVar_ns), - scm); + public Term parse(Reader in, Sort sort, Services services, + Namespace var_ns, Namespace func_ns, + Namespace sort_ns, Namespace progVar_ns, AbbrevMap scm) + throws ParserException { + return parse(in, sort, services, new NamespaceSet(var_ns, func_ns, sort_ns, + new Namespace<>(), new Namespace<>(), progVar_ns), scm); } /** - * The method reads the input and parses a term with the - * specified namespaces. The method ensures, that the term has the - * specified sort. + * The method reads the input and parses a term with the specified namespaces. The method + * ensures, that the term has the specified sort. * * @param sort The expected sort of the term; must not be null. * @return The parsed term of the specified sort. - * @throws ParserException The method throws a ParserException, if - * the input could not be parsed correctly or the term has an - * invalid sort. + * @throws ParserException The method throws a ParserException, if the input could not be parsed + * correctly or the term has an invalid sort. */ - public Term parse(Reader in, - Sort sort, - Services services, - NamespaceSet nss, - AbbrevMap scm) + public Term parse(Reader in, Sort sort, Services services, NamespaceSet nss, AbbrevMap scm) throws ParserException { KeyIO keyIO = new KeyIO(services, nss); keyIO.setAbbrevMap(scm); try { Term result = keyIO.parseExpression(CharStreams.fromReader(in)); if (sort != null && !result.sort().extendsTrans(sort)) - throw new ParserException("Expected sort " + sort + ", but parser returns sort " + result.sort() + ".", null); + throw new ParserException("Expected sort " + sort + ", but parser returns sort " + + result.sort() + ".", null); return result; } catch (RecognitionException re) { // problemParser cannot be null since exception is thrown during parsing. - //String message = parser.getErrorMessage(re); - throw new RuntimeException(re); //message, new Location(re)).initCause(re); + // String message = parser.getErrorMessage(re); + throw new RuntimeException(re); // message, new Location(re)).initCause(re); } catch (IOException tse) { throw new ParserException(tse.getMessage(), null).initCause(tse); } } /** - * The method reads the input and parses a sequent with the - * specified namespaces. + * The method reads the input and parses a sequent with the specified namespaces. * * @return the paresed String as Sequent Object - * @throws ParserException The method throws a ParserException, if - * the input could not be parsed correctly + * @throws ParserException The method throws a ParserException, if the input could not be parsed + * correctly */ public Sequent parseSeq(Reader in, Services services, NamespaceSet nss, AbbrevMap scm) throws ParserException { KeyIO keyIO = new KeyIO(services, nss); try { final Sequent seq = keyIO.parseSequence(CharStreams.fromReader(in)); - //p = new KeYParserF(ParserMode.TERM, new KeYLexerF(in, ""), new Recoder2KeY(services, nss), services, nss, scm); + // p = new KeYParserF(ParserMode.TERM, new KeYLexerF(in, ""), new Recoder2KeY(services, + // nss), services, nss, scm); return seq; } catch (RecognitionException re) { // problemParser cannot be null since exception is thrown during parsing. - //String message = p.getErrorMessage(re); - //throw new ParserException(message, new Location(re)); + // String message = p.getErrorMessage(re); + // throw new ParserException(message, new Location(re)); throw new RuntimeException(re); } catch (IOException tse) { throw new ParserException(tse.getMessage(), null); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/GenericSortException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/GenericSortException.java index 81a9f061c20..e7e60247f6b 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/GenericSortException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/GenericSortException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import org.antlr.runtime.RecognitionException; @@ -7,58 +10,55 @@ public class GenericSortException extends RecognitionException { /** - * + * */ private static final long serialVersionUID = 7887443025957191925L; String cat; String filename; - Sort sort; + Sort sort; String reason; - - public GenericSortException(String cat, String reason, - Sort sort, Token t, String filename) { - this.cat = cat; - this.reason = reason; - this.filename = filename; - this.sort = sort; - this.line = t.getLine(); - this.charPositionInLine = t.getColumn(); + + public GenericSortException(String cat, String reason, Sort sort, Token t, String filename) { + this.cat = cat; + this.reason = reason; + this.filename = filename; + this.sort = sort; + this.line = t.getLine(); + this.charPositionInLine = t.getColumn(); } - public GenericSortException(String cat, String reason, Sort sort, - String filename, int line, int column) { - this.cat = cat; - this.reason = reason; - this.filename = filename; - this.sort = sort; - this.line = line; - this.charPositionInLine = column; + public GenericSortException(String cat, String reason, Sort sort, String filename, int line, + int column) { + this.cat = cat; + this.reason = reason; + this.filename = filename; + this.sort = sort; + this.line = line; + this.charPositionInLine = column; } /** * Returns a clean error message (no line number/column information) + * * @deprecated */ @Deprecated - public String getErrorMessage () - { - return getMessage(); + public String getErrorMessage() { + return getMessage(); } /** * Returns a clean error message (no line number/column information) */ - public String getMessage () - { - String errmsg = cat+"\n "+sort+"\n"; - return errmsg + reason; + public String getMessage() { + String errmsg = cat + "\n " + sort + "\n"; + return errmsg + reason; } - + /** * Returns a string representation of this exception. */ public String toString() { - return filename+"("+this.line+", "+this.charPositionInLine+"): " - +getMessage(); + return filename + "(" + this.line + ", " + this.charPositionInLine + "): " + getMessage(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/IdDeclaration.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/IdDeclaration.java index 282afbff97b..dfd06e37797 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/IdDeclaration.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/IdDeclaration.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.logic.sort.Sort; @@ -6,20 +9,19 @@ public class IdDeclaration { private String name; - private Sort sort; + private Sort sort; - public IdDeclaration ( String p_name, - Sort p_sort ) { - name = p_name; - sort = p_sort; + public IdDeclaration(String p_name, Sort p_sort) { + name = p_name; + sort = p_sort; } - public String getName () { - return name; + public String getName() { + return name; } - public Sort getSort () { - return sort; + public Sort getSort() { + return sort; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/InvalidFindException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/InvalidFindException.java index f4b2c42f851..6d51556fcbb 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/InvalidFindException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/InvalidFindException.java @@ -1,29 +1,29 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import org.antlr.runtime.RecognitionException; -public class InvalidFindException - extends RecognitionException { - +public class InvalidFindException extends RecognitionException { + /** - * + * */ private static final long serialVersionUID = 1699188390606912785L; private String description; private String filename; - - public InvalidFindException(String description, - String filename, - int line, int column) { - this.filename = filename; - this.line = line; - this.charPositionInLine = column; - this.description = description; + + public InvalidFindException(String description, String filename, int line, int column) { + this.filename = filename; + this.line = line; + this.charPositionInLine = column; + this.description = description; } - + public String getMessage() { - return (this.filename != null ? this.filename : "") + - "("+this.line+", "+this.charPositionInLine+ "):" + description; - } - -} \ No newline at end of file + return (this.filename != null ? this.filename : "") + "(" + this.line + ", " + + this.charPositionInLine + "):" + description; + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/JavaParserException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/JavaParserException.java index c0cfb08c407..9bdc9730473 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/JavaParserException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/JavaParserException.java @@ -1,46 +1,49 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import antlr.Token; public class JavaParserException extends antlr.SemanticException { - + /** - * + * */ private static final long serialVersionUID = 3858933208298220420L; String cat; String filename; String jb; - public JavaParserException(String cat, Token t, String filename, - int lineOffset, int colOffset) { - super("JavaParser"); - this.cat = cat; - this.jb =t.getText(); - this.filename = filename; - this.line = (lineOffset>=0) ? t.getLine()+lineOffset : 0; - this.column = (colOffset>=0) ? t.getColumn()+colOffset : 0; + public JavaParserException(String cat, Token t, String filename, int lineOffset, + int colOffset) { + super("JavaParser"); + this.cat = cat; + this.jb = t.getText(); + this.filename = filename; + this.line = (lineOffset >= 0) ? t.getLine() + lineOffset : 0; + this.column = (colOffset >= 0) ? t.getColumn() + colOffset : 0; } - - public JavaParserException(Throwable e, Token t, String filename, - int lineOffset, int colOffset) { + + public JavaParserException(Throwable e, Token t, String filename, int lineOffset, + int colOffset) { this(e.getMessage(), t, filename, lineOffset, colOffset); initCause(e); } - + public JavaParserException(String cat, Token t, String filename) { - super("JavaParser"); - this.cat = cat; - this.jb = t.getText(); - this.filename = filename; - this.line = t.getLine(); - this.column = t.getColumn(); + super("JavaParser"); + this.cat = cat; + this.jb = t.getText(); + this.filename = filename; + this.line = t.getLine(); + this.column = t.getColumn(); } - public JavaParserException(String message){ - super(message); + public JavaParserException(String message) { + super(message); } public JavaParserException(Throwable e, Token t, String filename) { @@ -51,38 +54,36 @@ public JavaParserException(Throwable e, Token t, String filename) { public String getFilename() { return filename; } - + public int getLine() { - return line; + return line; } - + public int getColumn() { return column; - } + } /** * Returns a clean error message (no line number/column information) + * * @deprecated */ @Deprecated - public String getErrorMessage () - { - return getMessage(); + public String getErrorMessage() { + return getMessage(); } /** * Returns a clean error message (no line number/column information) */ - public String getMessage () - { - return cat; + public String getMessage() { + return cat; } - + /** * Returns a string representation of this exception. */ public String toString() { - return filename+"("+this.getLine()+", "+this.getColumn()+"): " - +getMessage(); + return filename + "(" + this.getLine() + ", " + this.getColumn() + "): " + getMessage(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/KeYSemanticException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/KeYSemanticException.java index 3014608e01b..3237fe6d719 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/KeYSemanticException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/KeYSemanticException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.util.parsing.HasLocation; @@ -10,7 +13,7 @@ public class KeYSemanticException extends RecognitionException implements HasLocation { private final String cat; private final String filename; - + public KeYSemanticException(String message) { this.cat = message; this.filename = ""; @@ -30,38 +33,38 @@ public KeYSemanticException(TokenStream input, String sourceName, Exception caus public String getFilename() { return filename; } - + public int getLine() { - return line; + return line; } - + public int getColumn() { return charPositionInLine; - } + } /** * Returns a clean error message (no line number/column information) + * * @deprecated */ @Deprecated - public String getErrorMessage () - { - return getMessage(); + public String getErrorMessage() { + return getMessage(); } /** * Returns a clean error message (no line number/column information) */ - public String getMessage () - { - return cat; + public String getMessage() { + return cat; } - + /** * Returns a string representation of this exception. */ public String toString() { - return String.format("%s(%d, %d): %s", filename, this.getLine(), this.getColumn(), getMessage()); + return String.format("%s(%d, %d): %s", filename, this.getLine(), this.getColumn(), + getMessage()); } @Nullable @@ -69,4 +72,4 @@ public String toString() { public Location getLocation() throws MalformedURLException { return new Location(getFilename(), getLine(), getColumn() + 1); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/Location.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/Location.java index d038ff30df7..ed1e081d7ed 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/Location.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/Location.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.proof.io.consistency.DiskFileRepo; @@ -11,14 +14,14 @@ import java.net.URL; -/** - * This class represents a location in a file. It consists of a - * filename, a line number and a column number. The filename may be - * null, if the file is unknown (e.g. standard input). The class is +/** + * This class represents a location in a file. It consists of a filename, a line number and a column + * number. The filename may be null, if the file is unknown (e.g. standard input). The class is * mainly used for parser exceptions. * - *

      Both line and column numbers are assumed to be 1-based. - * That is the first character is on line 1, column 1. + *

      + * Both line and column numbers are assumed to be 1-based. That is the first character is on line 1, + * column 1. * * @author Hubert Schmid */ @@ -40,6 +43,7 @@ public final class Location { /** * Legacy constructor for creating a new Location from a String denoting the file path and line * and column number, tries to convert the path given as String into a URL. + * * @param filename path to the resource of the Location * @param line line of the Location * @param column column of the Location @@ -53,6 +57,7 @@ public Location(String filename, int line, int column) throws MalformedURLExcept /** * Creates a new Location with the given resource location, line and column numbers. + * * @param url location of the resource * @param line line of the Location * @param column column of the Location @@ -64,9 +69,9 @@ public Location(URL url, int line, int column) { } /** - * This factory method can be used to create a Location for a RecognitionException. - * A possibly thrown MalformedURLException is caught and printed to debug output, - * null is returned instead. + * This factory method can be used to create a Location for a RecognitionException. A possibly + * thrown MalformedURLException is caught and printed to debug output, null is returned instead. + * * @param re the RecognitionException to create a Location for * @return the created Location or null if creation failed */ @@ -75,7 +80,8 @@ public static Location create(RecognitionException re) { // ANTLR starts lines in column 0, files in line 1. return new Location(re.input.getSourceName(), re.line, re.charPositionInLine + 1); } catch (MalformedURLException e) { - LOGGER.debug("Location could not be created from String: " + re.input.getSourceName(), e); + LOGGER.debug("Location could not be created from String: " + re.input.getSourceName(), + e); return null; } } @@ -107,4 +113,4 @@ public int getColumn() { public String toString() { return "[" + fileUrl + ":" + line + "," + column + "]"; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/NotDeclException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/NotDeclException.java index f9099ecfa7a..979e5c66a56 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/NotDeclException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/NotDeclException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import org.antlr.runtime.TokenStream; @@ -17,7 +20,7 @@ public NotDeclException(TokenStream input, String cat, String undeclared_symbol) * Returns a clean error message (no line number/column information) */ private static String getMessage(String cat, String undeclaredSymbol, String addtl) { - return cat + "\n\t" + undeclaredSymbol + "\n" + "not declared "+addtl; + return cat + "\n\t" + undeclaredSymbol + "\n" + "not declared " + addtl; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserConfig.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserConfig.java index f9186957206..3476f963ba9 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserConfig.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserConfig.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.java.JavaInfo; @@ -12,37 +15,35 @@ public class ParserConfig { private Services services; private NamespaceSet nss; - - public ParserConfig(Services services, - NamespaceSet nss) { - this.services = services; - this.nss = nss; + + public ParserConfig(Services services, NamespaceSet nss) { + this.services = services; + this.nss = nss; } public Services services() { - return services; + return services; } public NamespaceSet namespaces() { - return nss; + return nss; } public JavaInfo javaInfo() { - return services.getJavaInfo(); + return services.getJavaInfo(); } public KeYRecoderMapping keyRecoderMapping() { - return services.getJavaInfo().rec2key(); + return services.getJavaInfo().rec2key(); } public TypeConverter typeConverter() { - return services.getTypeConverter(); + return services.getTypeConverter(); } public KeYCrossReferenceServiceConfiguration serviceConfiguration() { - return services.getJavaInfo(). - getKeYProgModelInfo().getServConf(); + return services.getJavaInfo().getKeYProgModelInfo().getServConf(); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserException.java index 5761ac3fd84..0aae66d0f74 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserException.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; @@ -14,11 +17,10 @@ public final class ParserException extends Exception implements HasLocation { /* --- constructors --- */ /** - * @param message The error message. The message may be shown to - * the user and should be appropriately formated. - * @param location The location on which the error occured. The - * location may be null, if the location is unknown or the error - * is independent of a location. + * @param message The error message. The message may be shown to the user and should be + * appropriately formated. + * @param location The location on which the error occured. The location may be null, if the + * location is unknown or the error is independent of a location. */ public ParserException(String message, Location location) { super(message); @@ -46,4 +48,4 @@ public synchronized ParserException initCause(Throwable cause) { /* --- fields --- */ private final Location location; -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserMode.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserMode.java index 553fe5f93ce..62ce79a8637 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserMode.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/ParserMode.java @@ -1,16 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; /** * The mode in which the parser is currently running. - * - * The KeY parser goes over input files more than once. This enum is used to - * denote the mode of the current run. + * + * The KeY parser goes over input files more than once. This enum is used to denote the mode of the + * current run. */ public enum ParserMode { /** - * Only parse declarations. Used to read in sort, predicate and function - * declarations. + * Only parse declarations. Used to read in sort, predicate and function declarations. */ DECLARATION, @@ -21,7 +23,7 @@ public enum ParserMode { /** * Parse global declarations. - * + * * Apparently, this mode is only used in test case * {@link de.uka.ilkd.key.logic.TestClashFreeSubst}. */ @@ -29,9 +31,8 @@ public enum ParserMode { /** * Only parse taclet definitions. - * - * Used by - * {@link KeYParser#parseTaclet(String, de.uka.ilkd.key.java.Services)} + * + * Used by {@link KeYParser#parseTaclet(String, de.uka.ilkd.key.java.Services)} */ TACLET, @@ -42,10 +43,10 @@ public enum ParserMode { /** * Get the name of this parser mode. - * + * * @return the same as {@link #toString()} */ public String getName() { return toString(); } -} \ No newline at end of file +} 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..73c09233ec0 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 @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import de.uka.ilkd.key.java.reference.*; @@ -19,13 +22,10 @@ public final class ParserUtil { * The given token is used for positional information. */ 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 ArrayLengthReference - || expr instanceof UncollatedReferenceQualifier - || expr instanceof SuperReference) { + // weigl: I hope I catch them all. + if (expr instanceof VariableReference || expr instanceof ThisReference + || expr instanceof ArrayReference || expr instanceof ArrayLengthReference + || expr instanceof UncollatedReferenceQualifier || expr instanceof SuperReference) { return; } Location loc = new Location((URL) null, tok.beginLine, tok.beginColumn); diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/SchemaVariableModifierSet.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/SchemaVariableModifierSet.java index 44c46f66498..ed1e11c3e56 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/SchemaVariableModifierSet.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/SchemaVariableModifierSet.java @@ -1,70 +1,75 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; public abstract class SchemaVariableModifierSet { private boolean strict = false; - private boolean rigid = false; + private boolean rigid = false; private boolean list = false; - - + + public boolean rigid() { return rigid; } - - + + protected boolean rigidEnabled() { return false; } - - + + public boolean strict() { return strict; } - - + + protected boolean strictEnabled() { return false; } - + public boolean list() { - return list; + return list; } - - + + protected boolean listEnabled() { - return false; + return false; } - - + + /** - * @return true iff option is a valid modifier - * for the considered kind of schema variables + * @return true iff option is a valid modifier for the considered kind + * of schema variables */ public boolean addModifier(String option) { - if ( "strict".equals ( option ) ) { - return addStrict (); - } else if ( "rigid".equals ( option ) ) { - return addRigid (); + if ("strict".equals(option)) { + return addStrict(); + } else if ("rigid".equals(option)) { + return addRigid(); } else if ("list".equals(option)) { return addList(); } return false; } - + public boolean addRigid() { this.rigid = true; return rigidEnabled(); } + public boolean addStrict() { this.strict = true; return strictEnabled(); } + public boolean addList() { - this.list = true; - return listEnabled(); + this.list = true; + return listEnabled(); } public static class ProgramSV extends SchemaVariableModifierSet { @@ -73,13 +78,15 @@ protected boolean listEnabled() { } } - public static class TermSV extends SchemaVariableModifierSet { + public static class TermSV extends SchemaVariableModifierSet { protected boolean rigidEnabled() { return true; } + protected boolean strictEnabled() { return true; } + protected boolean listEnabled() { return true; } @@ -91,11 +98,15 @@ protected boolean rigidEnabled() { } } - public static class VariableSV extends SchemaVariableModifierSet {} + public static class VariableSV extends SchemaVariableModifierSet { + } - public static class SkolemTermSV extends SchemaVariableModifierSet {} + public static class SkolemTermSV extends SchemaVariableModifierSet { + } - public static class FreshProgVarSV extends SchemaVariableModifierSet {} + public static class FreshProgVarSV extends SchemaVariableModifierSet { + } - public static class TermLabelSV extends SchemaVariableModifierSet {} -} \ No newline at end of file + public static class TermLabelSV extends SchemaVariableModifierSet { + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/UnfittingReplacewithException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/UnfittingReplacewithException.java index f15447f4f7f..61cf08ca643 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/UnfittingReplacewithException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/UnfittingReplacewithException.java @@ -1,30 +1,31 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; import org.antlr.runtime.RecognitionException; -public class UnfittingReplacewithException - extends RecognitionException { - +public class UnfittingReplacewithException extends RecognitionException { + /** - * + * */ private static final long serialVersionUID = -497885048593588941L; private String description; private String filename; - - public UnfittingReplacewithException(String description, - String filename, - int line , int column) { - super(); - this.filename = filename; - this.line = line; - this.charPositionInLine = column; - this.description = description; + + public UnfittingReplacewithException(String description, String filename, int line, + int column) { + super(); + this.filename = filename; + this.line = line; + this.charPositionInLine = column; + this.description = description; } - + public String getMessage() { - return (filename != null ? filename + ":" : "") + description; - } - -} \ No newline at end of file + return (filename != null ? filename + ":" : "") + description; + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/parser/WarningException.java b/key/key.core/src/main/java/de/uka/ilkd/key/parser/WarningException.java index 577e71d8d21..4c16cffe27a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/parser/WarningException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/parser/WarningException.java @@ -1,24 +1,27 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.parser; public class WarningException extends antlr.ANTLRException { - /** - * + /** + * */ private static final long serialVersionUID = 3421160418830554998L; -private String errorStr=""; - - public WarningException(String errorStr) { - this.errorStr=errorStr; - } - - public String getMessage() { - return errorStr; - } - - - public String toString() { - return errorStr; - } - -} \ No newline at end of file + private String errorStr = ""; + + public WarningException(String errorStr) { + this.errorStr = errorStr; + } + + public String getMessage() { + return errorStr; + } + + + public String toString() { + return errorStr; + } + +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevException.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevException.java index bf5cebf55db..ecbe262957e 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevException.java @@ -1,15 +1,18 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; -public class AbbrevException extends Exception{ - - /** - * +public class AbbrevException extends Exception { + + /** + * */ private static final long serialVersionUID = 7602628448672131434L; protected boolean termused; - public AbbrevException(String message,boolean termused){ - super(message); - this.termused = termused; - } -} \ No newline at end of file + public AbbrevException(String message, boolean termused) { + super(message); + this.termused = termused; + } +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevMap.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevMap.java index a005498be80..922b1ddb801 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevMap.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/AbbrevMap.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import de.uka.ilkd.key.logic.Term; @@ -11,15 +14,13 @@ public class AbbrevMap { /** - * HashMaps used to store the mappings from Term to String, String to Term - * and Term to Enabled. + * HashMaps used to store the mappings from Term to String, String to Term and Term to Enabled. */ private HashMap termstring; private HashMap stringterm; /** - * Enabled is set true if a abbreviation should be used - * when printing the term. + * Enabled is set true if a abbreviation should be used when printing the term. */ private HashMap termenabled; @@ -35,22 +36,19 @@ public AbbrevMap() { /** * Associates a Term and its abbreviation in this map. * - * @param t a term + * @param t a term * @param abbreviation the abbreviation for of this term - * @param enabled true if the abbreviation should be used (e.g. when printing - * the term), false otherwise. + * @param enabled true if the abbreviation should be used (e.g. when printing the term), false + * otherwise. */ - public void put(Term t, String abbreviation, boolean enabled) - throws AbbrevException { + public void put(Term t, String abbreviation, boolean enabled) throws AbbrevException { AbbrevWrapper scw; if (containsTerm(t)) { - throw new AbbrevException( - "A abbreviation for " + t + " already exists", true); + throw new AbbrevException("A abbreviation for " + t + " already exists", true); } if (containsAbbreviation(abbreviation)) { - throw new AbbrevException("The abbreviation " + abbreviation - + " is already" + " in use for: " + getTerm(abbreviation), - false); + throw new AbbrevException("The abbreviation " + abbreviation + " is already" + + " in use for: " + getTerm(abbreviation), false); } scw = new AbbrevWrapper(t); termstring.put(scw, abbreviation); @@ -59,20 +57,17 @@ public void put(Term t, String abbreviation, boolean enabled) } /** - * Changes the abbreviation of t to abbreviation. If the AbbrevMap doesn't - * contain t nothing happens. + * Changes the abbreviation of t to abbreviation. If the AbbrevMap doesn't contain t nothing + * happens. * * @throws AbbrevException if the abbreviation is already in use. */ - public void changeAbbrev(Term t, String abbreviation) - throws AbbrevException { + public void changeAbbrev(Term t, String abbreviation) throws AbbrevException { if (containsTerm(t)) { AbbrevWrapper scw; if (containsAbbreviation(abbreviation)) { - throw new AbbrevException( - "The abbreviation " + abbreviation + " is already" - + " in use for: " + getTerm(abbreviation), - false); + throw new AbbrevException("The abbreviation " + abbreviation + " is already" + + " in use for: " + getTerm(abbreviation), false); } scw = new AbbrevWrapper(t); stringterm.remove(termstring.get(scw)); @@ -82,18 +77,16 @@ public void changeAbbrev(Term t, String abbreviation) } /** - * Changes the abbreviation abbreviation to t. If - * the AbbrevMap doesn't contain abbreviation nothing happens. + * Changes the abbreviation abbreviation to t. If the AbbrevMap + * doesn't contain abbreviation nothing happens. * * @throws AbbrevException If an abbreviation for t already exists. */ - public void changeAbbrev(String abbreviation, Term t, boolean enabled) - throws AbbrevException { + public void changeAbbrev(String abbreviation, Term t, boolean enabled) throws AbbrevException { if (containsAbbreviation(abbreviation)) { AbbrevWrapper scw; if (containsTerm(t)) { - throw new AbbrevException( - "A abbreviation for " + t + " already exists", true); + throw new AbbrevException("A abbreviation for " + t + " already exists", true); } scw = new AbbrevWrapper(t); stringterm.remove(termstring.get(scw)); @@ -118,8 +111,8 @@ public boolean containsTerm(Term t) { } /** - * Returns the term which is mapped to the abbreviation s, null if no term - * is mapped to the abbreviation. + * Returns the term which is mapped to the abbreviation s, null if no term is mapped to the + * abbreviation. */ public Term getTerm(String s) { var term = stringterm.get(s); @@ -127,16 +120,15 @@ public Term getTerm(String s) { } /** - * Returns the abbreviation mapped to the term t. Returns null if no - * abbreviation is mapped to t. + * Returns the abbreviation mapped to the term t. Returns null if no abbreviation is mapped to + * t. */ public String getAbbrev(Term t) { return "@" + termstring.get(new AbbrevWrapper(t)); } /** - * Returns true if the mapping is enabled, which means that the abbreviation - * may be used. + * Returns true if the mapping is enabled, which means that the abbreviation may be used. */ public boolean isEnabled(Term t) { Boolean b = termenabled.get(new AbbrevWrapper(t)); @@ -148,12 +140,11 @@ public boolean isEnabled(Term t) { /** * Sets the mapping of the term t to its abbreviation enabled or disabled * - * @param t a Term + * @param t a Term * @param enabled true if the abbreviation of t may be used. */ public void setEnabled(Term t, boolean enabled) { - termenabled.put(new AbbrevWrapper(t), - enabled ? Boolean.TRUE : Boolean.FALSE); + termenabled.put(new AbbrevWrapper(t), enabled ? Boolean.TRUE : Boolean.FALSE); } /** @@ -161,8 +152,7 @@ public void setEnabled(Term t, boolean enabled) { * Note, this will allocate a new data structure each time. */ public Collection> export() { - return termstring.entrySet().stream() - .map(e -> new Pair<>(e.getKey().t, e.getValue())) + return termstring.entrySet().stream().map(e -> new Pair<>(e.getKey().t, e.getValue())) .collect(Collectors.toList()); } @@ -194,4 +184,4 @@ public Term getTerm() { return t; } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/CharListNotation.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/CharListNotation.java index 3fde1c13a63..2d592c480cf 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/CharListNotation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/CharListNotation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import java.io.IOException; @@ -7,60 +10,61 @@ public final class CharListNotation extends Notation { public CharListNotation() { - super(130); + super(130); } @Override public void print(Term t, LogicPrinter sp) throws IOException { - if(sp.getNotationInfo().getAbbrevMap().isEnabled(t)) { - sp.printTerm(t); - } else { - try { - sp.printConstant(translateTerm(t)); - } catch (IllegalArgumentException exc) { - sp.printFunctionTerm(t); - } - } + if (sp.getNotationInfo().getAbbrevMap().isEnabled(t)) { + sp.printTerm(t); + } else { + try { + sp.printConstant(translateTerm(t)); + } catch (IllegalArgumentException exc) { + sp.printFunctionTerm(t); + } + } } private StringBuffer printlastfirst(Term t) { - if (t.op().arity()==0) { - return new StringBuffer(); - } else { - return printlastfirst(t.sub(0)).append(t.op().name().toString()); - } + if (t.op().arity() == 0) { + return new StringBuffer(); + } else { + return printlastfirst(t.sub(0)).append(t.op().name().toString()); + } } private String translateCharTerm(Term t) { - char charVal=0; - int intVal=0; - if (t.op().arity() == 0) - throw new IllegalArgumentException("Term is not a value!"); - String result = printlastfirst(t.sub(0)).toString(); - try { - intVal = Integer.parseInt(result); - charVal = (char)intVal; - if (intVal-charVal!=0) - throw new NumberFormatException(); //overflow! - - } catch (NumberFormatException ex) { - throw new IllegalArgumentException(result +" is not of type char"); - } - return ""+charVal; + char charVal = 0; + int intVal = 0; + if (t.op().arity() == 0) + throw new IllegalArgumentException("Term is not a value!"); + String result = printlastfirst(t.sub(0)).toString(); + try { + intVal = Integer.parseInt(result); + charVal = (char) intVal; + if (intVal - charVal != 0) + throw new NumberFormatException(); // overflow! + + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(result + " is not of type char"); + } + return "" + charVal; } - /** translates a term that represents a string literal into a string - * that is enclosed by quotation marks + /** + * translates a term that represents a string literal into a string that is enclosed by + * quotation marks */ private String translateTerm(Term t) { - final StringBuffer result = new StringBuffer(""); - Term term = t; - while (!term.op().name().toString().equals("clEmpty")){ - if (!term.op().name().toString().equals("clCons")) - throw new IllegalArgumentException("Term does not represent a String Literal!"); - result.append(translateCharTerm(term.sub(0))); - term = term.sub(1); - } - return "\""+result+"\""; + final StringBuffer result = new StringBuffer(""); + Term term = t; + while (!term.op().name().toString().equals("clEmpty")) { + if (!term.op().name().toString().equals("clCons")) + throw new IllegalArgumentException("Term does not represent a String Literal!"); + result.append(translateCharTerm(term.sub(0))); + term = term.sub(1); + } + return "\"" + result + "\""; } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/FieldPrinter.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/FieldPrinter.java index 94f92b93848..b8323307f31 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/FieldPrinter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/FieldPrinter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import de.uka.ilkd.key.java.JavaInfo; @@ -24,36 +27,31 @@ class FieldPrinter { } /** - * Determine the syntax in which a field constant is printed when associated - * with the object represented by {@code objectTerm} Default is the name of - * the field. In case the field is hidden by another field, the name of the - * field is preceeded by the corresponding class name. + * Determine the syntax in which a field constant is printed when associated with the object + * represented by {@code objectTerm} Default is the name of the field. In case the field is + * hidden by another field, the name of the field is preceeded by the corresponding class name. * - * Example default: object.field Example hidden field: - * object.(package.class::field) + * Example default: object.field Example hidden field: object.(package.class::field) * * Remark: This method is declared static because it is also used in method * {@link StorePrinter#printStoreOnFieldConstant(de.uka.ilkd.key.logic.Term, de.uka.ilkd.key.logic.Term, de.uka.ilkd.key.logic.Term, de.uka.ilkd.key.logic.Term, boolean) } */ - protected String getPrettySyntaxForFieldConstant(Term objectTerm, - Term fieldTerm) { + protected String getPrettySyntaxForFieldConstant(Term objectTerm, Term fieldTerm) { JavaInfo javaInfo = lp.services.getJavaInfo(); if (isCanonicField(objectTerm, fieldTerm, javaInfo)) { /* - * Class name can be omitted if the field is canonic, i.e. - * correct field can be determined without explicit mentioning - * of corresponding class name. + * Class name can be omitted if the field is canonic, i.e. correct field can be + * determined without explicit mentioning of corresponding class name. * * Example syntax: object.field */ return HeapLDT.getPrettyFieldName(fieldTerm.op()); } else { /* - * There is another field of the same name that would be selected - * if class name is omitted. In this case class name must be mentioned - * explicitly. + * There is another field of the same name that would be selected if class name is + * omitted. In this case class name must be mentioned explicitly. * * Example syntax: object.(package.class::field) */ @@ -62,18 +60,15 @@ protected String getPrettySyntaxForFieldConstant(Term objectTerm, } /* - * Determine whether class can be omitted when printing a field - * in a select term. A field can be omitted, if it is canonic for - * the associated object. + * Determine whether class can be omitted when printing a field in a select term. A field can be + * omitted, if it is canonic for the associated object. * - * For more information on canonic, see - * {@link de.uka.ilkd.key.java.JavaInfo#getCanonicalFieldProgramVariable(String,KeYJavaType)} + * For more information on canonic, see {@link + * de.uka.ilkd.key.java.JavaInfo#getCanonicalFieldProgramVariable(String,KeYJavaType)} * * (Kai Wallisch 09/2014) */ - private boolean isCanonicField(Term objectTerm, - Term fieldTerm, - JavaInfo javaInfo) { + private boolean isCanonicField(Term objectTerm, Term fieldTerm, JavaInfo javaInfo) { Sort sort = objectTerm.sort(); KeYJavaType kjt = javaInfo.getKeYJavaType(sort); String fieldName = HeapLDT.getPrettyFieldName(fieldTerm.op()); @@ -83,10 +78,9 @@ private boolean isCanonicField(Term objectTerm, } /* - * Compare originTypeAndName and pvTypeAndName based on their String - * representation. I did not find a better solution to this yet. - * But it seems to be standard, as it is done similary in method HeapLDT.getPrettyFieldName(). - * (Kai Wallisch 09/2014) + * Compare originTypeAndName and pvTypeAndName based on their String representation. I did + * not find a better solution to this yet. But it seems to be standard, as it is done + * similary in method HeapLDT.getPrettyFieldName(). (Kai Wallisch 09/2014) */ String[] originTypeAndName = fieldTerm.toString().split("::\\$"); assert originTypeAndName.length == 2; @@ -101,10 +95,8 @@ private boolean isCanonicField(Term objectTerm, * Determine whether a term is a constant function symbol of type field. */ protected static boolean isFieldConstant(Term fieldTerm, HeapLDT heapLDT) { - return fieldTerm.op() instanceof Function - && ((Function) fieldTerm.op()).isUnique() - && fieldTerm.sort() == heapLDT.getFieldSort() - && fieldTerm.arity() == 0 + return fieldTerm.op() instanceof Function && ((Function) fieldTerm.op()).isUnique() + && fieldTerm.sort() == heapLDT.getFieldSort() && fieldTerm.arity() == 0 && fieldTerm.boundVars().isEmpty(); } @@ -113,15 +105,15 @@ protected boolean isFieldConstant(Term fieldTerm) { } /** - * Find out whether a {@link Term} represents a field symbol, declared in a - * Java class. + * Find out whether a {@link Term} represents a field symbol, declared in a Java class. * * @return Returns true iff the given parameter represents a field constant. * @param fieldTerm The target field. */ - protected static boolean isJavaFieldConstant(Term fieldTerm, HeapLDT heapLDT, Services services) { + protected static boolean isJavaFieldConstant(Term fieldTerm, HeapLDT heapLDT, + Services services) { String name = fieldTerm.op().name().toString(); - if(name.contains("::$") && isFieldConstant(fieldTerm, heapLDT)) { + if (name.contains("::$") && isFieldConstant(fieldTerm, heapLDT)) { String pvName = name.replace("::$", "::"); try { return services.getJavaInfo().getAttribute(pvName) != null; @@ -139,8 +131,8 @@ protected boolean isJavaFieldConstant(Term fieldTerm) { } /* - * Determine whether the field constant is a generic object property. - * Those are surrounded by angle brackets, e.g. o. + * Determine whether the field constant is a generic object property. Those are surrounded by + * angle brackets, e.g. o. */ protected boolean isBuiltinObjectProperty(Term fieldTerm) { return fieldTerm.op().name().toString().contains("::<") @@ -148,9 +140,8 @@ protected boolean isBuiltinObjectProperty(Term fieldTerm) { } /* - * Determine whether a field constant is static. - * Field constants are considered static if reference object - * is null. + * Determine whether a field constant is static. Field constants are considered static if + * reference object is null. */ protected boolean isStaticFieldConstant(Term objectTerm, Term fieldTerm) { return objectTerm.equals(lp.services.getTermBuilder().NULL()) diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/HideSequentPrintFilter.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/HideSequentPrintFilter.java index d3131ac923d..b1c7f1bab7a 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/HideSequentPrintFilter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/HideSequentPrintFilter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import java.io.IOException; @@ -11,8 +14,8 @@ import de.uka.ilkd.key.pp.IdentitySequentPrintFilter.IdentityFilterEntry; /** - * This filter takes a search string and yields a sequent containing only - * sequent formulas that match the search. + * This filter takes a search string and yields a sequent containing only sequent formulas that + * match the search. * * @author jschiffl */ @@ -32,7 +35,7 @@ public HideSequentPrintFilter(SequentViewLogicPrinter lp, boolean regex) { protected void filterSequent() { Iterator it; - if(antec != null) { + if (antec != null) { // Result has already been computed. No need to recompute. return; } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/IdentitySequentPrintFilter.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/IdentitySequentPrintFilter.java index 267985eeb3a..28b0edd5930 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/IdentitySequentPrintFilter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/IdentitySequentPrintFilter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import org.key_project.util.collection.ImmutableList; @@ -28,8 +31,9 @@ protected SequentPrintFilterEntry filterFormula(SequentFormula sequentFormula) { } /** - * Get the formulas of the filtered antecedent and the constraints to use for - * instantiating metavariables when printing + * Get the formulas of the filtered antecedent and the constraints to use for instantiating + * metavariables when printing + * * @return the filtered antecedent */ public ImmutableList getFilteredAntec() { @@ -38,8 +42,9 @@ public ImmutableList getFilteredAntec() { } /** - * Get the formulas of the filtered succcedent and the constraints to use for - * instantiating metavariables when printing + * Get the formulas of the filtered succcedent and the constraints to use for instantiating + * metavariables when printing + * * @return the filtered succcedent */ public ImmutableList getFilteredSucc() { @@ -58,6 +63,7 @@ public static class IdentityFilterEntry implements SequentPrintFilterEntry { /** * constructor + * * @param originalFormula the original formula to be filtered */ IdentityFilterEntry(SequentFormula originalFormula) { @@ -66,6 +72,7 @@ public static class IdentityFilterEntry implements SequentPrintFilterEntry { /** * Formula to display + * * @return the original formula */ public SequentFormula getFilteredFormula() { @@ -74,6 +81,7 @@ public SequentFormula getFilteredFormula() { /** * Original formula from sequent + * * @return the original formula */ public SequentFormula getOriginalFormula() { @@ -81,4 +89,4 @@ public SequentFormula getOriginalFormula() { } } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/IllegalRegexException.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/IllegalRegexException.java index ad31a966d59..0046050d373 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/IllegalRegexException.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/IllegalRegexException.java @@ -1,8 +1,10 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; /** - * This exception is thrown when a String is expected be a valid - * regular expression, but is not. + * This exception is thrown when a String is expected be a valid regular expression, but is not. * * @author jschiffl */ @@ -12,9 +14,10 @@ public class IllegalRegexException extends Exception { /** * constructor + * * @param cause the cause of the exception */ public IllegalRegexException(Throwable cause) { super(cause); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/InitialPositionTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/InitialPositionTable.java index c3fbca66fbd..046f9bb072d 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/InitialPositionTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/InitialPositionTable.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import org.key_project.util.collection.ImmutableList; @@ -8,22 +11,20 @@ import de.uka.ilkd.key.logic.SequentFormula; /** - * An InitialPositionTable is a PositionTable that describes the - * beginning of the element/subelement relationship. Thus, an - * InitialPositionTable describes the information on where the - * {@link SequentFormula}e of a sequent are located. It is the root of the tree of - * PositionTables and may be asked for a PosInSequent for a given index - * position and a given Sequent. + * An InitialPositionTable is a PositionTable that describes the beginning of the element/subelement + * relationship. Thus, an InitialPositionTable describes the information on where the + * {@link SequentFormula}e of a sequent are located. It is the root of the tree of PositionTables + * and may be asked for a PosInSequent for a given index position and a given Sequent. * - *

      For simplicity, the an InitialPositionTable has only one row. - * The various constrained formulae of a sequent are located - * one level below. In other words the whole sequent is not - * represented by an empty position list but by the list [0]. + *

      + * For simplicity, the an InitialPositionTable has only one row. The various constrained formulae of + * a sequent are located one level below. In other words the whole sequent is not represented by an + * empty position list but by the list [0]. */ -public class InitialPositionTable extends PositionTable{ +public class InitialPositionTable extends PositionTable { private ImmutableList updateRanges = ImmutableSLList.nil(); - + /** Ranges of keywords */ private ImmutableList keywordRanges = ImmutableSLList.nil(); /** Ranges of java blocks */ @@ -33,68 +34,60 @@ public class InitialPositionTable extends PositionTable{ * creates a new Initial PositionTable. */ public InitialPositionTable() { - super(1); + super(1); } /** - * Returns the PosInSequent for a given char position in a - * sequent. - * @param index the char position that points to the wanted - * position in sequent - * @param filter the sequent print filter from that was used to - * print the sequent + * Returns the PosInSequent for a given char position in a sequent. + * + * @param index the char position that points to the wanted position in sequent + * @param filter the sequent print filter from that was used to print the sequent * */ - public PosInSequent getPosInSequent(int index, - SequentPrintFilter filter) { - if ( index < startPos[0] || index >= endPos[0]) { - return null; - } - - ImmutableList posList = pathForIndex(index); - - PosInSequent pis = getTopPIS(posList,filter); - - Range r = rangeForIndex(index); - pis.setBounds(r); - Range firstStatement - = firstStatementRangeForIndex(index); - if ( firstStatement!=null ) { - pis.setFirstJavaStatementRange(firstStatement); - } - return pis; + public PosInSequent getPosInSequent(int index, SequentPrintFilter filter) { + if (index < startPos[0] || index >= endPos[0]) { + return null; + } + + ImmutableList posList = pathForIndex(index); + + PosInSequent pis = getTopPIS(posList, filter); + + Range r = rangeForIndex(index); + pis.setBounds(r); + Range firstStatement = firstStatementRangeForIndex(index); + if (firstStatement != null) { + pis.setFirstJavaStatementRange(firstStatement); + } + return pis; } - /** Returns a PosInSequent for a given position list, - * but without filling in the bounds. It is assumed - * that this is the top level position table for a sequent. - * @param posList the position list that navigates through - * the position tables. - * @param filter the sequent print filter from that was used to - * print the sequent + /** + * Returns a PosInSequent for a given position list, but without filling in the bounds. It is + * assumed that this is the top level position table for a sequent. + * + * @param posList the position list that navigates through the position tables. + * @param filter the sequent print filter from that was used to print the sequent */ - private PosInSequent getTopPIS(ImmutableList posList, - SequentPrintFilter filter) { - if (posList.isEmpty() || posList.tail().isEmpty()) { - return PosInSequent.createSequentPos(); - } else { + private PosInSequent getTopPIS(ImmutableList posList, SequentPrintFilter filter) { + if (posList.isEmpty() || posList.tail().isEmpty()) { + return PosInSequent.createSequentPos(); + } else { return children[0].getSequentPIS(posList.tail(), filter); - } + } } /** - * Returns the path for a given PosInOccurrence. This is - * built up from the initial 0, the number of the - * SequentFormula in the sequent, the position in the - * constrained formula, and possibly inside a Metavariable - * instantiation. + * Returns the path for a given PosInOccurrence. This is built up from the initial 0, the number + * of the SequentFormula in the sequent, the position in the constrained formula, and possibly + * inside a Metavariable instantiation. + * * @param pio the given PosInOccurrence * @param filter the current filter * @return the path for the given pio */ - public ImmutableList pathForPosition(PosInOccurrence pio, - SequentPrintFilter filter) { + public ImmutableList pathForPosition(PosInOccurrence pio, SequentPrintFilter filter) { ImmutableList p = ImmutableSLList.nil(); p = prependPathInFormula(p, pio); int index = indexOfCfma(pio.sequentFormula(), filter); @@ -107,24 +100,23 @@ public ImmutableList pathForPosition(PosInOccurrence pio, } private ImmutableList prependPathInFormula(ImmutableList p, - PosInOccurrence pio) { - IntIterator pit = pio.posInTerm().reverseIterator(); - while (pit.hasNext()) { - p = p.prepend(Integer.valueOf(pit.next())); - } - return p; + PosInOccurrence pio) { + IntIterator pit = pio.posInTerm().reverseIterator(); + while (pit.hasNext()) { + p = p.prepend(Integer.valueOf(pit.next())); + } + return p; } /** - * Returns the index of the constrained formula in the sequent - * as printed. - * @param cfma the sequent formula + * Returns the index of the constrained formula in the sequent as printed. + * + * @param cfma the sequent formula * @param filter the current filter * @return the index of the given formula in the sequent as printed */ - private int indexOfCfma(SequentFormula cfma, - SequentPrintFilter filter) { + private int indexOfCfma(SequentFormula cfma, SequentPrintFilter filter) { ImmutableList list = filter.getFilteredAntec().append(filter.getFilteredSucc()); int k; @@ -137,46 +129,54 @@ private int indexOfCfma(SequentFormula cfma, } /** - * Returns the character range of the `lowest' subtable that - * includes index in its range. + * Returns the character range of the `lowest' subtable that includes index in its + * range. + * * @param index the character index to search for. */ public Range rangeForIndex(int index) { - return rangeForIndex(index,endPos[0]); + return rangeForIndex(index, endPos[0]); } - /** Returns the character range for the subtable indicated - * by the given integer list. + /** + * Returns the character range for the subtable indicated by the given integer list. */ public Range rangeForPath(ImmutableList path) { - return rangeForPath(path,endPos[0]); + return rangeForPath(path, endPos[0]); } + /** * Adds a range for a keyword to the keyword list. + * * @param r Range of keyword to be added */ public void addKeywordRange(Range r) { - keywordRanges = keywordRanges.prepend(r); + keywordRanges = keywordRanges.prepend(r); } + /** * @return ranges of keywords printed */ public Range[] getKeywordRanges() { - return keywordRanges.toArray(new Range[keywordRanges.size()]); + return keywordRanges.toArray(new Range[keywordRanges.size()]); } + /** * Adds a range for a java block to the java block list. + * * @param r Range of keyword to be added */ public void addJavaBlockRange(Range r) { - javaBlockRanges = javaBlockRanges.prepend(r); + javaBlockRanges = javaBlockRanges.prepend(r); } + /** * @return ranges of java blocks printed */ public Range[] getJavaBlockRanges() { - return javaBlockRanges.toArray(new Range[javaBlockRanges.size()]); + return javaBlockRanges.toArray(new Range[javaBlockRanges.size()]); } + public void addUpdateRange(Range r) { updateRanges = updateRanges.prepend(r); } @@ -184,4 +184,4 @@ public void addUpdateRange(Range r) { public Range[] getUpdateRanges() { return updateRanges.toArray(new Range[updateRanges.size()]); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/LogicPrinter.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/LogicPrinter.java index ed381db2d82..e83b625aaf0 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/LogicPrinter.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/LogicPrinter.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import de.uka.ilkd.key.control.TermLabelVisibilityManager; @@ -44,15 +47,14 @@ /** - * The front end for the Sequent pretty-printer. It prints a sequent and its - * parts and computes the PositionTable, which is needed for highlighting. + * The front end for the Sequent pretty-printer. It prints a sequent and its parts and computes the + * PositionTable, which is needed for highlighting. * *

      - * The actual layouting/formatting is done using the - * {@link de.uka.ilkd.key.util.pp.Layouter} class. The concrete syntax for - * operators is given by an instance of {@link NotationInfo}. The LogicPrinter - * is responsible for the concrete layout, e.g. how terms with infix - * operators are indented, and it binds the various needed components together. + * The actual layouting/formatting is done using the {@link de.uka.ilkd.key.util.pp.Layouter} class. + * The concrete syntax for operators is given by an instance of {@link NotationInfo}. The + * LogicPrinter is responsible for the concrete layout, e.g. how terms with infix operators + * are indented, and it binds the various needed components together. * * @see NotationInfo * @see Notation @@ -62,8 +64,7 @@ public class LogicPrinter { private static final Logger LOGGER = LoggerFactory.getLogger(LogicPrinter.class); /** - * The default and minimal value of the max. number of characters to put in one - * line + * The default and minimal value of the max. number of characters to put in one line */ public static final int DEFAULT_LINE_WIDTH = 55; @@ -115,20 +116,18 @@ private enum QuantifiableVariablePrintMode { } /** - * Creates a LogicPrinter. Sets the sequent to be printed, as well as a - * ProgramPrinter to print Java programs and a NotationInfo which determines the - * concrete syntax. + * Creates a LogicPrinter. Sets the sequent to be printed, as well as a ProgramPrinter to print + * Java programs and a NotationInfo which determines the concrete syntax. * - * @param prgPrinter the ProgramPrinter that pretty-prints Java programs + * @param prgPrinter the ProgramPrinter that pretty-prints Java programs * @param notationInfo the NotationInfo for the concrete syntax - * @param backend the Backend for the output - * @param services services. - * @param purePrint if true the PositionTable will not be calculated - * (simulates the behaviour of the former - * PureSequentPrinter) + * @param backend the Backend for the output + * @param services services. + * @param purePrint if true the PositionTable will not be calculated (simulates the behaviour of + * the former PureSequentPrinter) */ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Backend backend, - Services services, boolean purePrint) { + Services services, boolean purePrint) { this.backend = backend; this.layouter = new Layouter(backend, 2); this.prgPrinter = prgPrinter; @@ -141,13 +140,12 @@ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Backen } /** - * Creates a LogicPrinter. Sets the sequent to be printed, as well as a - * ProgramPrinter to print Java programs and a NotationInfo which determines the - * concrete syntax. + * Creates a LogicPrinter. Sets the sequent to be printed, as well as a ProgramPrinter to print + * Java programs and a NotationInfo which determines the concrete syntax. * - * @param prgPrinter the ProgramPrinter that pretty-prints Java programs + * @param prgPrinter the ProgramPrinter that pretty-prints Java programs * @param notationInfo the NotationInfo for the concrete syntax - * @param services The Services object + * @param services The Services object */ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Services services) { this(prgPrinter, notationInfo, new PosTableStringBackend(DEFAULT_LINE_WIDTH), services, @@ -155,19 +153,17 @@ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Servic } /** - * Creates a LogicPrinter. Sets the sequent to be printed, as well as a - * ProgramPrinter to print Java programs and a NotationInfo which determines the - * concrete syntax. + * Creates a LogicPrinter. Sets the sequent to be printed, as well as a ProgramPrinter to print + * Java programs and a NotationInfo which determines the concrete syntax. * - * @param prgPrinter the ProgramPrinter that pretty-prints Java programs + * @param prgPrinter the ProgramPrinter that pretty-prints Java programs * @param notationInfo the NotationInfo for the concrete syntax - * @param purePrint if true the PositionTable will not be calculated - * (simulates the behaviour of the former - * PureSequentPrinter) - * @param services the Services object + * @param purePrint if true the PositionTable will not be calculated (simulates the behaviour of + * the former PureSequentPrinter) + * @param services the Services object */ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Services services, - boolean purePrint) { + boolean purePrint) { this(prgPrinter, notationInfo, new PosTableStringBackend(DEFAULT_LINE_WIDTH), services, purePrint); } @@ -175,7 +171,7 @@ public LogicPrinter(ProgramPrinter prgPrinter, NotationInfo notationInfo, Servic /** * Converts a term to a string. * - * @param t a term. + * @param t a term. * @param services services. * @return the printed term. */ @@ -187,14 +183,14 @@ public static String quickPrintTerm(Term t, Services services) { /** * Converts a term to a string. * - * @param t a term. - * @param services services. + * @param t a term. + * @param services services. * @param usePrettyPrinting whether or not to use pretty-printing. * @param useUnicodeSymbols whether or not to use unicode symbols. * @return the printed term. */ public static String quickPrintTerm(Term t, Services services, boolean usePrettyPrinting, - boolean useUnicodeSymbols) { + boolean useUnicodeSymbols) { final NotationInfo ni = new NotationInfo(); if (services != null) { ni.refresh(services, usePrettyPrinting, useUnicodeSymbols); @@ -217,7 +213,7 @@ public static String quickPrintTerm(Term t, Services services, boolean usePretty /** * Converts a semisequent to a string. * - * @param s a semisequent. + * @param s a semisequent. * @param services services. * @return the printed semisequent. */ @@ -244,7 +240,7 @@ public static String quickPrintSemisequent(Semisequent s, Services services) { /** * Converts a sequent to a string. * - * @param s a sequent. + * @param s a sequent. * @param services services. * @return the printed sequent. */ @@ -272,8 +268,7 @@ public NotationInfo getNotationInfo() { } /** - * Resets the Backend, the Layouter and (if applicable) the ProgramPrinter of - * this Object. + * Resets the Backend, the Layouter and (if applicable) the ProgramPrinter of this Object. */ public void reset() { backend = new PosTableStringBackend(lineWidth); @@ -284,9 +279,8 @@ public void reset() { } /** - * sets the line width to the new value but does not reprint the - * sequent. The actual set line width is the maximum of - * {@link LogicPrinter#DEFAULT_LINE_WIDTH} and the given value + * sets the line width to the new value but does not reprint the sequent. The actual + * set line width is the maximum of {@link LogicPrinter#DEFAULT_LINE_WIDTH} and the given value * * @param lineWidth the max. number of character to put on one line * @return the actual set line width @@ -297,13 +291,12 @@ public int setLineWidth(int lineWidth) { } /** - * Reprints the sequent. This can be useful if settings like - * PresentationFeatures or abbreviations have changed. + * Reprints the sequent. This can be useful if settings like PresentationFeatures or + * abbreviations have changed. * - * @param filter The SequentPrintFilter for seq - * @param lineWidth the max. number of character to put on one line (the actual - * taken linewidth is the max of - * {@link LogicPrinter#DEFAULT_LINE_WIDTH} and the given value + * @param filter The SequentPrintFilter for seq + * @param lineWidth the max. number of character to put on one line (the actual taken linewidth + * is the max of {@link LogicPrinter#DEFAULT_LINE_WIDTH} and the given value */ public void update(SequentPrintFilter filter, int lineWidth) { setLineWidth(lineWidth); @@ -321,15 +314,14 @@ public void setInstantiation(SVInstantiations instantiations) { /** * Pretty-print a taclet. Line-breaks are taken care of. * - * @param taclet The Taclet to be pretty-printed. - * @param sv The instantiations of the SchemaVariables - * @param showWholeTaclet Should the find, varcond and heuristic part be - * pretty-printed? - * @param declareSchemaVars Should declarations for the schema variables used in - * the taclet be pretty-printed? + * @param taclet The Taclet to be pretty-printed. + * @param sv The instantiations of the SchemaVariables + * @param showWholeTaclet Should the find, varcond and heuristic part be pretty-printed? + * @param declareSchemaVars Should declarations for the schema variables used in the taclet be + * pretty-printed? */ public void printTaclet(Taclet taclet, SVInstantiations sv, boolean showWholeTaclet, - boolean declareSchemaVars) { + boolean declareSchemaVars) { instantiations = sv; quantifiableVariablePrintMode = QuantifiableVariablePrintMode.WITH_OUT_DECLARATION; try { @@ -376,8 +368,7 @@ public void printTaclet(Taclet taclet, SVInstantiations sv, boolean showWholeTac } /** - * Pretty-print a taclet. Line-breaks are taken care of. No instantiation is - * applied. + * Pretty-print a taclet. Line-breaks are taken care of. No instantiation is applied. * * @param taclet The Taclet to be pretty-printed. */ @@ -517,7 +508,7 @@ protected void printHeuristics(Taclet taclet) throws IOException { return; } layouter.brk().beginC(2).print("\\heuristics ("); - for (Iterator it = taclet.getRuleSets().iterator(); it.hasNext(); ) { + for (Iterator it = taclet.getRuleSets().iterator(); it.hasNext();) { layouter.brk(); RuleSet tgt = it.next(); printHeuristic(tgt); @@ -570,7 +561,7 @@ protected void printGoalTemplates(Taclet taclet) throws IOException { } for (final Iterator it = taclet.goalTemplates().reverse().iterator(); it - .hasNext(); ) { + .hasNext();) { printGoalTemplate(it.next()); if (it.hasNext()) { layouter.print(";"); @@ -618,7 +609,7 @@ protected void printGoalTemplate(TacletGoalTemplate tgt) throws IOException { protected void printRules(ImmutableList rules) throws IOException { layouter.brk().beginC(2).print("\\addrules ("); SVInstantiations svi = instantiations; - for (Iterator it = rules.iterator(); it.hasNext(); ) { + for (Iterator it = rules.iterator(); it.hasNext();) { layouter.brk(); Taclet t = it.next(); printTaclet(t, instantiations, true, false); @@ -629,7 +620,7 @@ protected void printRules(ImmutableList rules) throws IOException { protected void printAddProgVars(ImmutableSet apv) throws IOException { layouter.beginC(2).print("\\addprogvars ("); - for (Iterator it = apv.iterator(); it.hasNext(); ) { + for (Iterator it = apv.iterator(); it.hasNext();) { layouter.brk(); SchemaVariable tgt = it.next(); printSchemaVariable(tgt); @@ -678,8 +669,8 @@ public void printProgramElement(ProgramElement pe) throws IOException { } /** - * Pretty-Prints a ProgramVariable in the logic, not in Java blocks. Prints out - * the full (logic) name, so if A.b is private, it becomes a.A::b . + * Pretty-Prints a ProgramVariable in the logic, not in Java blocks. Prints out the full (logic) + * name, so if A.b is private, it becomes a.A::b . * * @param pv The ProgramVariable in the logic * @throws IOException @@ -766,10 +757,10 @@ public void printSequent(Sequent seq, boolean finalbreak) { } /** - * Pretty-print a sequent. The sequent arrow is rendered as =>. - * If the sequent doesn't fit in one line, a line break is inserted after each - * formula, the sequent arrow is on a line of its own, and formulae are indented - * w.r.t. the arrow. A line-break is printed after the Sequent. + * Pretty-print a sequent. The sequent arrow is rendered as =>. If the sequent + * doesn't fit in one line, a line break is inserted after each formula, the sequent arrow is on + * a line of its own, and formulae are indented w.r.t. the arrow. A line-break is printed after + * the Sequent. * * @param filter The SequentPrintFilter for seq */ @@ -780,11 +771,10 @@ public void printSequent(SequentPrintFilter filter) { } /** - * Pretty-print a sequent. The sequent arrow is rendered as =>. - * If the sequent doesn't fit in one line, a line break is inserted after each - * formula, the sequent arrow is on a line of its own, and formulae are indented - * w.r.t. the arrow. A line-break is printed after the Sequent. No filtering is - * done. + * Pretty-print a sequent. The sequent arrow is rendered as =>. If the sequent + * doesn't fit in one line, a line break is inserted after each formula, the sequent arrow is on + * a line of its own, and formulae are indented w.r.t. the arrow. A line-break is printed after + * the Sequent. No filtering is done. * * @param seq The Sequent to be pretty-printed */ @@ -826,8 +816,7 @@ public void printSemisequent(ImmutableList formulas) } /** - * Pretty-prints a constrained formula. The constraint "Constraint.BOTTOM" is - * suppressed + * Pretty-prints a constrained formula. The constraint "Constraint.BOTTOM" is suppressed * * @param cfma the constrained formula to be printed * @throws IOException if the formula cannot be printed. @@ -837,8 +826,8 @@ public void printConstrainedFormula(SequentFormula cfma) throws IOException { } /** - * Pretty-prints a term or formula. How it is rendered depends on the - * NotationInfo given to the constructor. + * Pretty-prints a term or formula. How it is rendered depends on the NotationInfo given to the + * constructor. * * @param t the Term to be printed * @throws IOException if the term cannot be printed. @@ -864,15 +853,14 @@ public void printTerm(Term t) throws IOException { } /** - * Determine the Set of labels that will be printed out for a specific - * {@link Term}. The class {@link SequentViewLogicPrinter} overrides this - * method. {@link TermLabel} visibility can be configured via GUI, see - * {@link de.uka.ilkd.key.gui.actions.TermLabelMenu}. Default is to print all - * TermLabels. + * Determine the Set of labels that will be printed out for a specific {@link Term}. The class + * {@link SequentViewLogicPrinter} overrides this method. {@link TermLabel} visibility can be + * configured via GUI, see {@link de.uka.ilkd.key.gui.actions.TermLabelMenu}. Default is to + * print all TermLabels. * * @param t {@link Term} whose visible {@link TermLabel}s will be determined. - * @return List of visible {@link TermLabel}s, i.e. labels that are - * syntactically added to a {@link Term} while printing. + * @return List of visible {@link TermLabel}s, i.e. labels that are syntactically added to a + * {@link Term} while printing. */ protected ImmutableArray getVisibleTermLabels(Term t) { return t.getLabels(); @@ -931,13 +919,12 @@ public void printTerm(ImmutableSet terms) throws IOException { } /** - * Pretty-prints a term or formula in the same block. How it is rendered depends - * on the NotationInfo given to the constructor. `In the same block' means that - * no extra indentation will be added if line breaks are necessary. A formula - * a & (b - * & c) would print a & b & c, omitting the - * redundant parentheses. The subformula b & c is printed using - * this method to get a layout of + * Pretty-prints a term or formula in the same block. How it is rendered depends on the + * NotationInfo given to the constructor. `In the same block' means that no extra indentation + * will be added if line breaks are necessary. A formula a & (b + * & c) would print a & b & c, omitting the redundant + * parentheses. The subformula b & c is printed using this method to get a + * layout of * *

            * a & b & c
      @@ -967,10 +954,9 @@ public void printTermContinuingBlock(Term t) throws IOException {
           }
       
           /**
      -     * Print a term in f(t1,...tn) style. If the operator has arity 0,
      -     * no parentheses are printed, i.e. f instead of f().
      -     * If the term doesn't fit on one line, t2...tn are aligned below
      -     * t1.
      +     * Print a term in f(t1,...tn) style. If the operator has arity 0, no parentheses
      +     * are printed, i.e. f instead of f(). If the term doesn't fit on one
      +     * line, t2...tn are aligned below t1.
            *
            * @param t the term to be printed.
            */
      @@ -1253,7 +1239,7 @@ public void printObserver(Term t, Term tacitHeap) throws IOException {
                           try {
                               boolean canonical = obs.isStatic() || ((obs instanceof IProgramMethod)
                                       && javaInfo.isCanonicalProgramMethod((IProgramMethod) obs,
      -                                keYJavaType));
      +                                        keYJavaType));
                               if (canonical) {
                                   p = fieldName;
                               } else {
      @@ -1397,13 +1383,13 @@ public void printElementOf(Term t, String symbol) throws IOException {
           }
       
           /**
      -     * Print a unary term in prefix style. For instance !a. No line
      -     * breaks are possible.
      +     * Print a unary term in prefix style. For instance !a. No line breaks are
      +     * possible.
            *
            * @param name the prefix operator
      -     * @param t    whole term
      -     * @param sub  the subterm to be printed
      -     * @param ass  the associativity for the subterm
      +     * @param t whole term
      +     * @param sub the subterm to be printed
      +     * @param ass the associativity for the subterm
            * @throws IOException if the term cannot be printed.
            */
           public void printPrefixTerm(String name, Term t, Term sub, int ass) throws IOException {
      @@ -1419,12 +1405,12 @@ public void printPrefixTerm(String name, Term t, Term sub, int ass) throws IOExc
           }
       
           /**
      -     * Print a unary term in postfix style. For instance t.a, where
      -     * .a is the postfix operator. No line breaks are possible.
      +     * Print a unary term in postfix style. For instance t.a, where .a is
      +     * the postfix operator. No line breaks are possible.
            *
            * @param name the postfix operator
      -     * @param t    the subterm to be printed
      -     * @param ass  the associativity for the subterm
      +     * @param t the subterm to be printed
      +     * @param ass the associativity for the subterm
            * @throws IOException if the term cannot be printed.
            */
           public void printPostfixTerm(Term t, int ass, String name) throws IOException {
      @@ -1435,8 +1421,8 @@ public void printPostfixTerm(Term t, int ass, String name) throws IOException {
       
           /**
            * Print a binary term in infix style. For instance p
      -     * & q, where & is the infix operator. If line
      -     * breaks are necessary, the format is like
      +     * & q, where & is the infix operator. If line breaks are necessary,
      +     * the format is like
            *
            * 
            * p & q
      @@ -1444,11 +1430,11 @@ public void printPostfixTerm(Term t, int ass, String name) throws IOException {
            * 

      * The subterms are printed using {@link #printTermContinuingBlock(Term)}. * - * @param l the left subterm - * @param assLeft associativity for left subterm - * @param name the infix operator - * @param t whole term - * @param r the right subterm + * @param l the left subterm + * @param assLeft associativity for left subterm + * @param name the infix operator + * @param t whole term + * @param r the right subterm * @param assRight associativity for right subterm * @throws IOException if the term cannot be printed. */ @@ -1465,16 +1451,16 @@ public void printInfixTerm(Term l, int assLeft, String name, Term t, Term r, int * {@link #printTermContinuingBlock(Term)} for the idea. Otherwise like * {@link #printInfixTerm(Term, int, String, Term, int)}. * - * @param l the left subterm - * @param assLeft associativity for left subterm - * @param name the infix operator - * @param t whole term - * @param r the right subterm + * @param l the left subterm + * @param assLeft associativity for left subterm + * @param name the infix operator + * @param t whole term + * @param r the right subterm * @param assRight associativity for right subterm * @throws IOException if the term cannot be printed. */ public void printInfixTermContinuingBlock(Term l, int assLeft, String name, Term t, Term r, - int assRight) throws IOException { + int assRight) throws IOException { boolean isKeyword = false; if (services != null) { LocSetLDT loc = services.getTypeConverter().getLocSetLDT(); @@ -1498,17 +1484,17 @@ public void printInfixTermContinuingBlock(Term l, int assLeft, String name, Term } /** - * Print a term with an update. This looks like {u} t. If line - * breaks are necessary, the format is + * Print a term with an update. This looks like {u} t. If line breaks are + * necessary, the format is * *

            * {u}
            *   t
            * 
      * - * @param l the left brace - * @param r the right brace - * @param t the update term + * @param l the left brace + * @param r the right brace + * @param t the update term * @param ass3 associativity for phi * @throws IOException if the term cannot be printed. */ @@ -1585,7 +1571,7 @@ public void printParallelUpdate(String separator, Term t, int ass) throws IOExce } private void printVariables(ImmutableArray vars, - QuantifiableVariablePrintMode mode) throws IOException { + QuantifiableVariablePrintMode mode) throws IOException { int size = vars.size(); for (int j = 0; j != size; j++) { final QuantifiableVariable v = vars.get(j); @@ -1655,24 +1641,24 @@ public void printIfThenElseTerm(Term t, String keyword) throws IOException { } /** - * Print a substitution term. This looks like {var/t}s. If line - * breaks are necessary, the format is + * Print a substitution term. This looks like {var/t}s. If line breaks are + * necessary, the format is * *
            * {var/t}
            *   s
            * 
      * - * @param l the String used as left brace symbol - * @param v the {@link QuantifiableVariable} to be substituted - * @param t the Term to be used as new value + * @param l the String used as left brace symbol + * @param v the {@link QuantifiableVariable} to be substituted + * @param t the Term to be used as new value * @param ass2 the int defining the associativity for the new value - * @param r the String used as right brace symbol - * @param phi the substituted term/formula + * @param r the String used as right brace symbol + * @param phi the substituted term/formula * @param ass3 the int defining the associativity for phi */ public void printSubstTerm(String l, QuantifiableVariable v, Term t, int ass2, String r, - Term phi, int ass3) throws IOException { + Term phi, int ass3) throws IOException { layouter.beginC(2).print(l); printVariables(new ImmutableArray<>(v), quantifiableVariablePrintMode); startTerm(2); @@ -1683,24 +1669,24 @@ public void printSubstTerm(String l, QuantifiableVariable v, Term t, int ass2, S } /** - * Print a quantified term. Normally, this looks like all x:s.phi. - * If line breaks are necessary, the format is + * Print a quantified term. Normally, this looks like all x:s.phi. If line breaks + * are necessary, the format is * *
            * all x:s.
            *   phi
            * 
      *

      - * Note that the parameter var has to contain the variable name - * with colon and sort. + * Note that the parameter var has to contain the variable name with colon and + * sort. * * @param name the name of the quantifier * @param vars the quantified variables (+colon and sort) - * @param phi the quantified formula - * @param ass associativity for phi + * @param phi the quantified formula + * @param ass associativity for phi */ public void printQuantifierTerm(String name, ImmutableArray vars, - Term phi, int ass) throws IOException { + Term phi, int ass) throws IOException { layouter.beginC(2); markStartKeyword(); layouter.print(name); @@ -1714,8 +1700,7 @@ public void printQuantifierTerm(String name, ImmutableArrays and marks it as - * a nullary term. + * Print a constant. This just prints the string s and marks it as a nullary term. * * @param s the constant */ @@ -1725,8 +1710,7 @@ public void printConstant(String s) throws IOException { } /** - * Print a constant. This just prints the string s and marks it as - * a nullary term. + * Print a constant. This just prints the string s and marks it as a nullary term. * * @param t constant as term to be printed * @param s name of the constant @@ -1749,9 +1733,9 @@ public void printConstant(Term t, String s) throws IOException { } /** - * Print a Java block. This is formatted using the ProgramPrinter given to the - * constructor. The result is indented according to the surrounding material. - * The first `executable' statement is marked for highlighting. + * Print a Java block. This is formatted using the ProgramPrinter given to the constructor. The + * result is indented according to the surrounding material. The first `executable' statement is + * marked for highlighting. * * @param j the Java block to be printed */ @@ -1774,15 +1758,14 @@ public void printJavaBlock(JavaBlock j) throws IOException { } /** - * Print a string marking a range as first statement. The range r - * indicates the `first statement' character range in string s. - * This is sent to the layouter by decomposing s into parts and - * using the appropriate {@link de.uka.ilkd.key.util.pp.Layouter#mark(Object)} - * calls. This solves the problem that the material in s might be - * further indented. + * Print a string marking a range as first statement. The range r indicates the + * `first statement' character range in string s. This is sent to the layouter by + * decomposing s into parts and using the appropriate + * {@link de.uka.ilkd.key.util.pp.Layouter#mark(Object)} calls. This solves the problem that the + * material in s might be further indented. * - * @param s the string containing a program - * @param r the range of the first statement + * @param s the string containing a program + * @param r the range of the first statement * @param keywords the ranges of the java keywords in this program */ private void printMarkingFirstStatement(String s, Range r, Range[] keywords) @@ -1821,8 +1804,8 @@ private void printMarkingFirstStatement(String s, Range r, Range[] keywords) if (keyword.start() >= iStart && keyword.end() <= iEnd) { int printed = startTotal + (firstTotal - firstStmt.length()); String beforeKeyword = firstStmt.substring(0, keyword.start() - printed); - String key = firstStmt.substring(keyword.start() - printed, - keyword.end() - printed); + String key = + firstStmt.substring(keyword.start() - printed, keyword.end() - printed); firstStmt = firstStmt.substring(keyword.end() - printed); printVerbatim(beforeKeyword); markStartKeyword(); @@ -1867,12 +1850,11 @@ private void printVerbatim(String s) throws IOException { } /** - * Print a DL modality formula. phi is the whole modality formula, - * not just the subformula inside the modality. Normally, this looks like - * <Program>psi, where psi = phi.sub(0). No line - * breaks are inserted, as the program itself is always broken. In case of a - * program modality with arity greater than 1, the subformulae are listed - * between parens, like <Program>(psi1,psi2) + * Print a DL modality formula. phi is the whole modality formula, not just the + * subformula inside the modality. Normally, this looks like <Program>psi, + * where psi = phi.sub(0). No line breaks are inserted, as the program itself is + * always broken. In case of a program modality with arity greater than 1, the subformulae are + * listed between parens, like <Program>(psi1,psi2) */ public void printModalityTerm(String left, JavaBlock jb, String right, Term phi, int ass) @@ -1882,8 +1864,8 @@ public void printModalityTerm(String left, JavaBlock jb, String right, Term phi, if (phi.op() instanceof ModalOperatorSV) { Object o = getInstantiations().getInstantiation((ModalOperatorSV) phi.op()); if (o == null) { - LOGGER.debug("PMT NO {} @[ {} ]@ is : {} @[{}]@ known", - phi, phi.op(), phi.getClass().getName(), phi.op().getClass().getName()); + LOGGER.debug("PMT NO {} @[ {} ]@ is : {} @[{}]@ known", phi, phi.op(), + phi.getClass().getName(), phi.op().getClass().getName()); } else { // logger.debug("Instantiation of " + phi + " @[" + phi.op() + "]@" + " is : " + // o + o.getClass().getName()); @@ -1931,8 +1913,8 @@ public void printModalityTerm(String left, JavaBlock jb, String right, Term phi, } /** - * Returns the pretty-printed sequent. This should only be called after a - * printSequent invocation returns. + * Returns the pretty-printed sequent. This should only be called after a printSequent + * invocation returns. * * @return the pretty-printed sequent. */ @@ -1947,8 +1929,8 @@ public String toString() { } /** - * Returns the pretty-printed sequent in a StringBuffer. This should only be - * called after a printSequent invocation returns. + * Returns the pretty-printed sequent in a StringBuffer. This should only be called after a + * printSequent invocation returns. * * @return the pretty-printed sequent. */ @@ -1974,9 +1956,9 @@ protected Layouter mark(MarkType type, int parameter) { } /** - * returns the PositionTable representing position information on the sequent of - * this LogicPrinter. Subclasses may overwrite this method with a null returning - * body if position information is not computed there. + * returns the PositionTable representing position information on the sequent of this + * LogicPrinter. Subclasses may overwrite this method with a null returning body if position + * information is not computed there. */ public PositionTable getPositionTable() { if (pure) { @@ -1986,9 +1968,9 @@ public PositionTable getPositionTable() { } /** - * returns the PositionTable representing position information on the sequent of - * this LogicPrinter. Subclasses may overwrite this method with a null returning - * body if position information is not computed there. + * returns the PositionTable representing position information on the sequent of this + * LogicPrinter. Subclasses may overwrite this method with a null returning body if position + * information is not computed there. */ public InitialPositionTable getInitialPositionTable() { if (pure) { @@ -2016,16 +1998,16 @@ protected Layouter getLayouter() { } /** - * Prints a subterm, if needed with parentheses. Each subterm has a Priority. If - * the priority is less than the associativity for that subterm fixed by the - * Notation/NotationInfo, parentheses are needed. + * Prints a subterm, if needed with parentheses. Each subterm has a Priority. If the priority is + * less than the associativity for that subterm fixed by the Notation/NotationInfo, parentheses + * are needed. * *

      * If prio and associativity are equal, the subterm is printed using - * {@link #printTermContinuingBlock(Term)}. This currently only makes a - * difference for infix operators. + * {@link #printTermContinuingBlock(Term)}. This currently only makes a difference for infix + * operators. * - * @param t the the subterm to print + * @param t the the subterm to print * @param ass the associativity for this subterm */ protected void maybeParens(Term t, int ass) throws IOException { @@ -2080,19 +2062,17 @@ private static enum MarkType { */ MARK_END_SUB, /** - * Mark the start of the first executable statement. Needed for PositionTable - * construction. + * Mark the start of the first executable statement. Needed for PositionTable construction. */ MARK_START_FIRST_STMT, /** - * Mark the end of the first executable statement. Needed for PositionTable - * construction. + * Mark the end of the first executable statement. Needed for PositionTable construction. */ MARK_END_FIRST_STMT, /** - * Mark the need for a ModalityPositionTable. The next startTerm mark will - * construct a ModalityPositionTable instead of the usual PositionTable. Needed - * for PositionTable construction. + * Mark the need for a ModalityPositionTable. The next startTerm mark will construct a + * ModalityPositionTable instead of the usual PositionTable. Needed for PositionTable + * construction. */ MARK_MODPOSTBL, /** @@ -2124,12 +2104,11 @@ private static enum MarkType { private final boolean createPositionTable = true; /** - * Called before a substring is printed that has its own entry in a position - * table. The method sends a mark to the layouter, which will make the backend - * set a start entry in posTbl, push a new StackEntry with the current posTbl - * and current pos on the stack and set the current pos to the length of the - * current string result. Subclasses may overwrite this method with an empty - * body if position information is not needed there. + * Called before a substring is printed that has its own entry in a position table. The method + * sends a mark to the layouter, which will make the backend set a start entry in posTbl, push a + * new StackEntry with the current posTbl and current pos on the stack and set the current pos + * to the length of the current string result. Subclasses may overwrite this method with an + * empty body if position information is not needed there. */ protected void markStartSub() { if (createPositionTable) { @@ -2147,11 +2126,10 @@ protected void markStartSub(int subterm) { } /** - * Called after a substring is printed that has its own entry in a position - * table. The backend will finishes the position table on the top of the stack - * and set the entry on the top of the stack to be the current position/position - * table. Subclasses may overwrite this method with an empty body if position - * information is not needed there. + * Called after a substring is printed that has its own entry in a position table. The backend + * will finishes the position table on the top of the stack and set the entry on the top of the + * stack to be the current position/position table. Subclasses may overwrite this method with an + * empty body if position information is not needed there. */ protected void markEndSub() { if (createPositionTable) { @@ -2196,10 +2174,9 @@ protected void markEndKeyword() { } /** - * Start a term with subterms. The backend will set the current posTbl to a - * newly created position table with the given number of rows. Subclasses may - * overwrite this method with an empty body if position information is not - * needed there. + * Start a term with subterms. The backend will set the current posTbl to a newly created + * position table with the given number of rows. Subclasses may overwrite this method with an + * empty body if position information is not needed there. * * @param size the number of rows of the new position table */ @@ -2210,12 +2187,11 @@ protected void startTerm(int size) { } /** - * returns true if an attribute term shall be printed in short form. In opposite - * to the other printInShortForm methods it takes care of meta variable - * instantiations + * returns true if an attribute term shall be printed in short form. In opposite to the other + * printInShortForm methods it takes care of meta variable instantiations * * @param attributeProgramName the String of the attribute's program name - * @param t the Term used as reference prefix + * @param t the Term used as reference prefix * @return true if an attribute term shall be printed in short form. */ public boolean printInShortForm(String attributeProgramName, Term t) { @@ -2225,12 +2201,11 @@ public boolean printInShortForm(String attributeProgramName, Term t) { } /** - * tests if the program name together with the prefix sort determines the - * attribute in a unique way + * tests if the program name together with the prefix sort determines the attribute in a unique + * way * * @param programName the String denoting the program name of the attribute - * @param sort the ObjectSort in whose reachable hierarchy we test for - * uniqueness + * @param sort the ObjectSort in whose reachable hierarchy we test for uniqueness * @return true if the attribute is uniquely determined */ public boolean printInShortForm(String programName, Sort sort) { @@ -2249,50 +2224,50 @@ public static String escapeHTML(String text, boolean escapeWhitespace) { for (int i = 0, sz = text.length(); i < sz; i++) { char c = text.charAt(i); switch (c) { - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '&': - sb.append("&"); - break; - case '\"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - case '(': - sb.append("("); - break; - case ')': - sb.append(")"); - break; - case '#': - sb.append("#"); - break; - case '+': - sb.append("+"); - break; - case '-': - sb.append("-"); - break; - case '%': - sb.append("%"); - break; - case ';': - sb.append(";"); - break; - case '\n': - sb.append(escapeWhitespace ? "
      " : c); - break; - case ' ': - sb.append(escapeWhitespace ? " " : c); - break; - default: - sb.append(c); + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '&': + sb.append("&"); + break; + case '\"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + case '(': + sb.append("("); + break; + case ')': + sb.append(")"); + break; + case '#': + sb.append("#"); + break; + case '+': + sb.append("+"); + break; + case '-': + sb.append("-"); + break; + case '%': + sb.append("%"); + break; + case ';': + sb.append(";"); + break; + case '\n': + sb.append(escapeWhitespace ? "
      " : c); + break; + case ' ': + sb.append(escapeWhitespace ? " " : c); + break; + default: + sb.append(c); } } @@ -2300,13 +2275,12 @@ public static String escapeHTML(String text, boolean escapeWhitespace) { } /** - * tests if the program name together with the prefix sort determines the - * attribute in a unique way + * tests if the program name together with the prefix sort determines the attribute in a unique + * way * * @param programName the String denoting the program name of the attribute - * @param sort the ObjectSort specifying the hierarchy where to test for - * uniqueness - * @param services the Services class used to access the type hierarchy + * @param sort the ObjectSort specifying the hierarchy where to test for uniqueness + * @param services the Services class used to access the type hierarchy * @return true if the attribute is uniquely determined */ public static boolean printInShortForm(String programName, Sort sort, Services services) { @@ -2319,8 +2293,8 @@ public static boolean printInShortForm(String programName, Sort sort, Services s } /** - * Utility class for stack entries containing the position table and the - * position of the start of the subterm in the result. + * Utility class for stack entries containing the position table and the position of the start + * of the subterm in the result. */ private static class StackEntry { @@ -2343,11 +2317,10 @@ int pos() { } /** - * A {@link de.uka.ilkd.key.util.pp.Backend} which puts its result in a - * StringBuffer and builds a PositionTable. Position table construction is done - * using the {@link de.uka.ilkd.key.util.pp.Layouter#mark(Object)} facility of - * the layouter with the various static MARK_ objects declared - * {@link LogicPrinter}. + * A {@link de.uka.ilkd.key.util.pp.Backend} which puts its result in a StringBuffer and builds + * a PositionTable. Position table construction is done using the + * {@link de.uka.ilkd.key.util.pp.Layouter#mark(Object)} facility of the layouter with the + * various static MARK_ objects declared {@link LogicPrinter}. */ private static class PosTableStringBackend extends StringBackend { @@ -2377,8 +2350,8 @@ private static class PosTableStringBackend extends StringBackend { private boolean need_modPosTable = false; /** - * These two remember the range corresponding to the first executable statement - * in a JavaBlock + * These two remember the range corresponding to the first executable statement in a + * JavaBlock */ private int firstStmtStart; private Range firstStmtRange; @@ -2452,73 +2425,73 @@ public void mark(Object o) { // MU refactored this using enums which makes it a little less ugly // and more flexible. switch (markType) { - case MARK_START_SUB: - if (parameter == -1) { - // no parameter means subterms in normal order - posTbl.setStart(count() - pos); - } else { - // parameter means a particular subterm has been chosen - posTbl.setStart(parameter, count() - pos); - } - stack.push(new StackEntry(posTbl, pos)); - pos = count(); - break; - - case MARK_END_SUB: - StackEntry se = stack.peek(); - stack.pop(); - pos = se.pos(); - se.posTbl().setEnd(count() - pos, posTbl); - posTbl = se.posTbl(); - break; - - case MARK_MODPOSTBL: - need_modPosTable = true; - break; - - case MARK_START_TERM: - // This is sent by startTerm - int rows = parameter; - if (need_modPosTable) { - posTbl = new ModalityPositionTable(rows); - } else { - posTbl = new PositionTable(rows); - } - need_modPosTable = false; - break; - - case MARK_START_FIRST_STMT: - firstStmtStart = count() - pos; - break; - - case MARK_END_FIRST_STMT: - firstStmtRange = new Range(firstStmtStart, count() - pos); - ((ModalityPositionTable) posTbl).setFirstStatementRange(firstStmtRange); - break; - - case MARK_START_UPDATE: - updateStarts.push(count()); - break; - - case MARK_END_UPDATE: - int updateStart = updateStarts.pop(); - initPosTbl.addUpdateRange(new Range(updateStart, count())); - break; - case MARK_START_KEYWORD: - keywordStarts.push(count()); - break; - case MARK_END_KEYWORD: - initPosTbl.addKeywordRange(new Range(keywordStarts.pop(), count())); - break; - case MARK_START_JAVABLOCK: - javaBlockStarts.push(count()); - break; - case MARK_END_JAVABLOCK: - initPosTbl.addJavaBlockRange(new Range(javaBlockStarts.pop(), count())); - break; - - default: - LOGGER.error("Unexpected LogicPrinter mark: {}", markType); + case MARK_START_SUB: + if (parameter == -1) { + // no parameter means subterms in normal order + posTbl.setStart(count() - pos); + } else { + // parameter means a particular subterm has been chosen + posTbl.setStart(parameter, count() - pos); + } + stack.push(new StackEntry(posTbl, pos)); + pos = count(); + break; + + case MARK_END_SUB: + StackEntry se = stack.peek(); + stack.pop(); + pos = se.pos(); + se.posTbl().setEnd(count() - pos, posTbl); + posTbl = se.posTbl(); + break; + + case MARK_MODPOSTBL: + need_modPosTable = true; + break; + + case MARK_START_TERM: + // This is sent by startTerm + int rows = parameter; + if (need_modPosTable) { + posTbl = new ModalityPositionTable(rows); + } else { + posTbl = new PositionTable(rows); + } + need_modPosTable = false; + break; + + case MARK_START_FIRST_STMT: + firstStmtStart = count() - pos; + break; + + case MARK_END_FIRST_STMT: + firstStmtRange = new Range(firstStmtStart, count() - pos); + ((ModalityPositionTable) posTbl).setFirstStatementRange(firstStmtRange); + break; + + case MARK_START_UPDATE: + updateStarts.push(count()); + break; + + case MARK_END_UPDATE: + int updateStart = updateStarts.pop(); + initPosTbl.addUpdateRange(new Range(updateStart, count())); + break; + case MARK_START_KEYWORD: + keywordStarts.push(count()); + break; + case MARK_END_KEYWORD: + initPosTbl.addKeywordRange(new Range(keywordStarts.pop(), count())); + break; + case MARK_START_JAVABLOCK: + javaBlockStarts.push(count()); + break; + case MARK_END_JAVABLOCK: + initPosTbl.addJavaBlockRange(new Range(javaBlockStarts.pop(), count())); + break; + + default: + LOGGER.error("Unexpected LogicPrinter mark: {}", markType); } } } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/ModalityPositionTable.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/ModalityPositionTable.java index 6332a90d322..3e6f0633a25 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/ModalityPositionTable.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/ModalityPositionTable.java @@ -1,27 +1,29 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; /** - * This is a position table for program modality formulae. In - * addition to the usual tables, it can store a range of character - * positions for the first statement in the Java block. + * This is a position table for program modality formulae. In addition to the usual tables, it can + * store a range of character positions for the first statement in the Java block. */ public class ModalityPositionTable extends PositionTable { public ModalityPositionTable(int rows) { - super(rows); + super(rows); } private Range firstStatementRange = null; - - - public void setFirstStatementRange(Range r){ - firstStatementRange = r; + + + public void setFirstStatementRange(Range r) { + firstStatementRange = r; } - - - public Range getFirstStatementRange(){ - return new Range(firstStatementRange); + + + public Range getFirstStatementRange() { + return new Range(firstStatementRange); } -} \ No newline at end of file +} diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/Notation.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/Notation.java index 7c5ae9e8fa6..6f08a0982db 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/Notation.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/Notation.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import de.uka.ilkd.key.java.ProgramElement; @@ -17,83 +20,79 @@ import java.util.Iterator; /** - * Encapsulate the concrete syntax used to print a term. The {@link - * NotationInfo} class associates a Notation with every {@link - * de.uka.ilkd.key.logic.op.Operator}. The various inner classes of this class - * represent different kinds of concrete syntax, like prefix, infix, postfix, - * function style, attribute style, etc. + * Encapsulate the concrete syntax used to print a term. The {@link NotationInfo} class associates a + * Notation with every {@link de.uka.ilkd.key.logic.op.Operator}. The various inner classes of this + * class represent different kinds of concrete syntax, like prefix, infix, postfix, function style, + * attribute style, etc. */ public abstract class Notation { - private static final Logger LOGGER = LoggerFactory.getLogger(Notation.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Notation.class); /** - * The priority of this operator in the given concrete syntax. This is - * used to determine whether parentheses are required around a subterm. + * The priority of this operator in the given concrete syntax. This is used to determine whether + * parentheses are required around a subterm. */ private final int priority; /** Create a Notation with a given priority. */ protected Notation(int priority) { - this.priority = priority; + this.priority = priority; } /** get the priority of the term */ public final int getPriority() { - return priority; + return priority; } /** - * Print a term to a {@link LogicPrinter}. Concrete subclasses override - * this to call one of the printXYZTerm of - * {@link LogicPrinter}, which do the layout. + * Print a term to a {@link LogicPrinter}. Concrete subclasses override this to call one of the + * printXYZTerm of {@link LogicPrinter}, which do the layout. */ public abstract void print(Term t, LogicPrinter sp) throws IOException; /** * Print a term without beginning a new block. See - * {@link LogicPrinter#printTermContinuingBlock(Term)}for the idea - * behind this. The standard implementation just delegates to - * {@link #print(Term,LogicPrinter)} + * {@link LogicPrinter#printTermContinuingBlock(Term)}for the idea behind this. The standard + * implementation just delegates to {@link #print(Term,LogicPrinter)} */ - public void printContinuingBlock(Term t, LogicPrinter sp) - throws IOException { - print(t, sp); + public void printContinuingBlock(Term t, LogicPrinter sp) throws IOException { + print(t, sp); } - - + + /** * The standard concrete syntax for constants like true and false. */ public static final class Constant extends Notation { - private final String name; + private final String name; - public Constant(String name, int prio) { - super(prio); - this.name = name; - } + public Constant(String name, int prio) { + super(prio); + this.name = name; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printConstant(t, name); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printConstant(t, name); + } } /** * The standard concrete syntax for prefix operators. */ public static final class Prefix extends Notation { - private final String name; - private final int ass; + private final String name; + private final int ass; - public Prefix(String name, int prio, int ass) { - super(prio); - this.name = name; - this.ass = ass; - } + public Prefix(String name, int prio, int ass) { + super(prio); + this.name = name; + this.ass = ass; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printPrefixTerm(name, t, t.sub(0), ass); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printPrefixTerm(name, t, t.sub(0), ass); + } } @@ -101,234 +100,227 @@ public void print(Term t, LogicPrinter sp) throws IOException { * The standard concrete syntax for infix operators. */ public static final class Infix extends Notation { - private final String name; - private final int assLeft, assRight; + private final String name; + private final int assLeft, assRight; - public Infix(String name, int prio, int assLeft, int assRight) { - super(prio); - this.name = name; - this.assLeft = assLeft; - this.assRight = assRight; - } + public Infix(String name, int prio, int assLeft, int assRight) { + super(prio); + this.name = name; + this.assLeft = assLeft; + this.assRight = assRight; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printInfixTerm(t.sub(0), assLeft, name, t, t.sub(1), assRight); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printInfixTerm(t.sub(0), assLeft, name, t, t.sub(1), assRight); + } - /** + /** * Print a term without beginning a new block. This calls the * {@link LogicPrinter#printTermContinuingBlock(Term)} method. */ - public void printContinuingBlock(Term t, LogicPrinter sp) - throws IOException { - sp.printInfixTermContinuingBlock(t.sub(0), assLeft, name, t, t.sub(1), assRight); - } + public void printContinuingBlock(Term t, LogicPrinter sp) throws IOException { + sp.printInfixTermContinuingBlock(t.sub(0), assLeft, name, t, t.sub(1), assRight); + } } - + public static final class LabelNotation extends Notation { - + private final String left; private final String right; - + public LabelNotation(String beginLabel, String endLabel, int prio) { super(prio); left = beginLabel; right = endLabel; } - + public void print(Term t, LogicPrinter sp) throws IOException { sp.printLabels(t, left, right); } } - + /** * The standard concrete syntax for quantifiers. */ public static final class Quantifier extends Notation { - private final String name; - private final int ass; + private final String name; + private final int ass; - public Quantifier(String name, int prio, int ass) { - super(prio); - this.name = name; - this.ass = ass; - } + public Quantifier(String name, int prio, int ass) { + super(prio); + this.name = name; + this.ass = ass; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printQuantifierTerm(name, t.varsBoundHere(0), t.sub(0), ass); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printQuantifierTerm(name, t.varsBoundHere(0), t.sub(0), ass); + } } - + /** * The standard concrete syntax for DL modalities box and diamond. */ public static final class ModalityNotation extends Notation { - private final String left, right; + private final String left, right; - private final int ass; + private final int ass; - public ModalityNotation(String left, String right, int prio, int ass) { - super(prio); - this.left = left; - this.right = right; - this.ass = ass; - } + public ModalityNotation(String left, String right, int prio, int ass) { + super(prio); + this.left = left; + this.right = right; + this.ass = ass; + } - public void print(Term t, LogicPrinter sp) throws IOException { - assert t.op() instanceof Modality; - assert t.javaBlock() != null; - sp.printModalityTerm(left, t.javaBlock(), right, t, ass); - } + public void print(Term t, LogicPrinter sp) throws IOException { + assert t.op() instanceof Modality; + assert t.javaBlock() != null; + sp.printModalityTerm(left, t.javaBlock(), right, t, ass); + } } - + /** - * The concrete syntax for DL modalities represented with a - * SchemaVariable. + * The concrete syntax for DL modalities represented with a SchemaVariable. */ public static final class ModalSVNotation extends Notation { - private final int ass; + private final int ass; - public ModalSVNotation(int prio, int ass) { - super(prio); - this.ass = ass; - } + public ModalSVNotation(int prio, int ass) { + super(prio); + this.ass = ass; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printModalityTerm("\\modality{" + t.op().name().toString() - + "}", t.javaBlock(), "\\endmodality", t, ass); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printModalityTerm("\\modality{" + t.op().name().toString() + "}", t.javaBlock(), + "\\endmodality", t, ass); + } } - + /** * The standard concrete syntax for update application. */ public static final class UpdateApplicationNotation extends Notation { - public UpdateApplicationNotation() { - super(115); - } + public UpdateApplicationNotation() { + super(115); + } - public void print(Term t, LogicPrinter sp) throws IOException { - assert t.op() == UpdateApplication.UPDATE_APPLICATION; - final Operator targetOp = UpdateApplication.getTarget(t).op(); - final int assTarget - = (t.sort() == Sort.FORMULA - ? (targetOp.arity() == 1 ? 60 : 85) - : 110); + public void print(Term t, LogicPrinter sp) throws IOException { + assert t.op() == UpdateApplication.UPDATE_APPLICATION; + final Operator targetOp = UpdateApplication.getTarget(t).op(); + final int assTarget = + (t.sort() == Sort.FORMULA ? (targetOp.arity() == 1 ? 60 : 85) : 110); - sp.printUpdateApplicationTerm("{", "}", t, assTarget); - } + sp.printUpdateApplicationTerm("{", "}", t, assTarget); + } } - - + + /** * The standard concrete syntax for elementary updates. */ public static final class ElementaryUpdateNotation extends Notation { - public ElementaryUpdateNotation() { - super(150); - } + public ElementaryUpdateNotation() { + super(150); + } + + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printElementaryUpdate(":=", t, 0); + } + } + - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printElementaryUpdate(":=", t, 0); - } - } - - /** - * The standard concrete syntax for parallel updates + * The standard concrete syntax for parallel updates */ public static final class ParallelUpdateNotation extends Notation { - public ParallelUpdateNotation() { - super(100); - } - - public void print(Term t, LogicPrinter sp) throws IOException { - assert t.op() == UpdateJunctor.PARALLEL_UPDATE; - - sp.printParallelUpdate("||", t, 10); - } - } - - + public ParallelUpdateNotation() { + super(100); + } + + public void print(Term t, LogicPrinter sp) throws IOException { + assert t.op() == UpdateJunctor.PARALLEL_UPDATE; + + sp.printParallelUpdate("||", t, 10); + } + } + + /** - * The standard concrete syntax for substitution terms. - */ + * The standard concrete syntax for substitution terms. + */ public static final class Subst extends Notation { - public Subst() { - super(120); - } - - public void print(Term t, LogicPrinter sp) throws IOException { - QuantifiableVariable v = instQV(t, sp, 1); - final int assTarget = (t.sort() == Sort.FORMULA ? (t.sub(1) - .op() == Equality.EQUALS ? 75 : 60) : 110); - sp.printSubstTerm("{\\subst ", v, t.sub(0), 0, "}", t.sub(1), - assTarget); - } - - private QuantifiableVariable instQV(Term t, LogicPrinter sp, int subTerm) { - QuantifiableVariable v = t.varsBoundHere(subTerm).get(0); - - if (v instanceof SchemaVariable) { - Object object = (sp.getInstantiations() - .getInstantiation((SchemaVariable) v)); - if (object != null) { - Debug.assertTrue(object instanceof Term); - Debug - .assertTrue(((Term) object).op() instanceof QuantifiableVariable); - v = (QuantifiableVariable) (((Term) object).op()); - } - } - return v; - } - } - - + public Subst() { + super(120); + } + + public void print(Term t, LogicPrinter sp) throws IOException { + QuantifiableVariable v = instQV(t, sp, 1); + final int assTarget = + (t.sort() == Sort.FORMULA ? (t.sub(1).op() == Equality.EQUALS ? 75 : 60) : 110); + sp.printSubstTerm("{\\subst ", v, t.sub(0), 0, "}", t.sub(1), assTarget); + } + + private QuantifiableVariable instQV(Term t, LogicPrinter sp, int subTerm) { + QuantifiableVariable v = t.varsBoundHere(subTerm).get(0); + + if (v instanceof SchemaVariable) { + Object object = (sp.getInstantiations().getInstantiation((SchemaVariable) v)); + if (object != null) { + Debug.assertTrue(object instanceof Term); + Debug.assertTrue(((Term) object).op() instanceof QuantifiableVariable); + v = (QuantifiableVariable) (((Term) object).op()); + } + } + return v; + } + } + + /** * The standard concrete syntax for function and predicate terms. */ public static final class FunctionNotation extends Notation { - public FunctionNotation() { - super(130); - } + public FunctionNotation() { + super(130); + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printFunctionTerm(t); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printFunctionTerm(t); + } } - + /** * The standard concrete syntax for casts. */ public static final class CastFunction extends Notation { - final String pre, post; + final String pre, post; - final int ass; + final int ass; - public CastFunction(String pre, String post, int prio, int ass) { - super(prio); - this.pre = pre; - this.post = post; - this.ass = ass; - } + public CastFunction(String pre, String post, int prio, int ass) { + super(prio); + this.pre = pre; + this.post = post; + this.ass = ass; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printCast(pre, post, t, ass); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printCast(pre, post, t, ass); + } } - + /** * The standard concrete syntax for observer function terms. @@ -408,249 +400,242 @@ public void printEmbeddedHeap(Term t, LogicPrinter sp) throws IOException { * The standard concrete syntax for length. */ public static final class Postfix extends Notation { - + private final String postfix; - - public Postfix(String postfix) { - super(130); - this.postfix = postfix; - } - - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printPostfix(t,postfix); - } - } - - + + public Postfix(String postfix) { + super(130); + this.postfix = postfix; + } + + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printPostfix(t, postfix); + } + } + + /** * The standard concrete syntax for singleton sets. */ public static final class SingletonNotation extends Notation { - public SingletonNotation() { - super(130); - } + public SingletonNotation() { + super(130); + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printSingleton(t); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printSingleton(t); + } } - + /** * The standard concrete syntax for the element of operator. */ public static final class ElementOfNotation extends Notation { private String symbol; - public ElementOfNotation() { - super(130); - } - - public ElementOfNotation(String symbol){ - this(); - this.symbol = symbol; - } - - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printElementOf(t, symbol); - } - } - - - + public ElementOfNotation() { + super(130); + } + + public ElementOfNotation(String symbol) { + this(); + this.symbol = symbol; + } + + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printElementOf(t, symbol); + } + } + + + /** * The standard concrete syntax for set comprehension. */ - - + + /** - * The standard concrete syntax for conditional terms - * if (phi) (t1) (t2). + * The standard concrete syntax for conditional terms if (phi) (t1) (t2). */ public static final class IfThenElse extends Notation { - private final String keyword; + private final String keyword; - public IfThenElse(int priority, String keyw) { - super(priority); - keyword = keyw; - } + public IfThenElse(int priority, String keyw) { + super(priority); + keyword = keyw; + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printIfThenElseTerm(t, keyword); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printIfThenElseTerm(t, keyword); + } } - + /** * The standard concrete syntax for all kinds of variables. */ public static class VariableNotation extends Notation { - public VariableNotation() { - super(1000); - } - - public void print(Term t, LogicPrinter sp) throws IOException { - if (t.op() instanceof ProgramVariable) { - sp - .printConstant(t.op().name().toString().replaceAll( - "::", ".")); - } else { - LOGGER.debug("Unknown variable type"); - sp.printConstant(t.op().name().toString()); - } - } - } - - + public VariableNotation() { + super(1000); + } + + public void print(Term t, LogicPrinter sp) throws IOException { + if (t.op() instanceof ProgramVariable) { + sp.printConstant(t.op().name().toString().replaceAll("::", ".")); + } else { + LOGGER.debug("Unknown variable type"); + sp.printConstant(t.op().name().toString()); + } + } + } + + public static final class SchemaVariableNotation extends VariableNotation { - @SuppressWarnings("unchecked") - public void print(Term t, LogicPrinter sp) throws IOException { - // logger.debug("SSV: " + t+ " [" + t.op() + "]"); - Debug.assertTrue(t.op() instanceof SchemaVariable); - Object o = sp.getInstantiations().getInstantiation( - (SchemaVariable) (t.op())); - if (o == null) { - // logger.debug("Instantiation of " + t+ " [" + t.op() + "]" + " + @SuppressWarnings("unchecked") + public void print(Term t, LogicPrinter sp) throws IOException { + // logger.debug("SSV: " + t+ " [" + t.op() + "]"); + Debug.assertTrue(t.op() instanceof SchemaVariable); + Object o = sp.getInstantiations().getInstantiation((SchemaVariable) (t.op())); + if (o == null) { + // logger.debug("Instantiation of " + t+ " [" + t.op() + "]" + " // not known."); - sp.printConstant(t.op().name().toString()); - } else { - if (o instanceof ProgramElement) { - // logger.debug(t.toString() + " [" + t.op() + "]" + " - // is a ProgramElement."); - sp.printProgramElement((ProgramElement) o); - } else { - // logger.debug("Instantiation of " + t+ " [" + t.op() + - // "]" + " known."); - if (o instanceof ImmutableList) { - final Iterator it = ((ImmutableList) o) - .iterator(); - sp.getLayouter().print("{"); - while (it.hasNext()) { - final Object next = it.next(); - if (next instanceof Term) { - sp.printTerm((Term) o); - } else { - sp.printConstant(o.toString()); - } - if (it.hasNext()) { - sp.getLayouter().print(","); - } - } - sp.getLayouter().print("}"); - } else { - Debug.assertTrue(o instanceof Term); - sp.printTerm((Term) o); - } - } - } - } - } - - + sp.printConstant(t.op().name().toString()); + } else { + if (o instanceof ProgramElement) { + // logger.debug(t.toString() + " [" + t.op() + "]" + " + // is a ProgramElement."); + sp.printProgramElement((ProgramElement) o); + } else { + // logger.debug("Instantiation of " + t+ " [" + t.op() + + // "]" + " known."); + if (o instanceof ImmutableList) { + final Iterator it = ((ImmutableList) o).iterator(); + sp.getLayouter().print("{"); + while (it.hasNext()) { + final Object next = it.next(); + if (next instanceof Term) { + sp.printTerm((Term) o); + } else { + sp.printConstant(o.toString()); + } + if (it.hasNext()) { + sp.getLayouter().print(","); + } + } + sp.getLayouter().print("}"); + } else { + Debug.assertTrue(o instanceof Term); + sp.printTerm((Term) o); + } + } + } + } + } + + /** - * The standard concrete syntax for the number literal indicator `Z'. - * This is only used in the `Pretty&Untrue' syntax. + * The standard concrete syntax for the number literal indicator `Z'. This is only used in the + * `Pretty&Untrue' syntax. */ static final class NumLiteral extends Notation { - public NumLiteral() { - super(120); - } - - public static String printNumberTerm(Term numberTerm) { - Term t = numberTerm; - - // skip number symbol /as this method may be called - // e.g. by char literal we do not fail if the first is - // not the number symbol - if (t.op().name().equals(IntegerLDT.NUMBERS_NAME)) { - t = t.sub(0); - } - - final StringBuffer number = new StringBuffer(); - int offset = 0; - - if (t.op().name().toString().equals( - IntegerLDT.NEGATIVE_LITERAL_STRING)) { - number.append("-"); - t = t.sub(0); - offset = 1; - } - - do { - final String opName = t.op().name() + ""; - - if (t.arity() != 1 - || (opName.length() != 1 || !Character.isDigit(opName - .charAt(0)))) { - return null; // not a number - } else { - number.insert(offset, opName); - } - t = t.sub(0); - } while (t.arity() != 0); - - return number.toString(); - } - - public void print(Term t, LogicPrinter sp) throws IOException { - final String number = printNumberTerm(t); - if (number != null) { - sp.printConstant(number); - } else { - sp.printFunctionTerm(t); - } - } - } - + public NumLiteral() { + super(120); + } + + public static String printNumberTerm(Term numberTerm) { + Term t = numberTerm; + + // skip number symbol /as this method may be called + // e.g. by char literal we do not fail if the first is + // not the number symbol + if (t.op().name().equals(IntegerLDT.NUMBERS_NAME)) { + t = t.sub(0); + } + + final StringBuffer number = new StringBuffer(); + int offset = 0; + + if (t.op().name().toString().equals(IntegerLDT.NEGATIVE_LITERAL_STRING)) { + number.append("-"); + t = t.sub(0); + offset = 1; + } + + do { + final String opName = t.op().name() + ""; + + if (t.arity() != 1 + || (opName.length() != 1 || !Character.isDigit(opName.charAt(0)))) { + return null; // not a number + } else { + number.insert(offset, opName); + } + t = t.sub(0); + } while (t.arity() != 0); + + return number.toString(); + } + + public void print(Term t, LogicPrinter sp) throws IOException { + final String number = printNumberTerm(t); + if (number != null) { + sp.printConstant(number); + } else { + sp.printFunctionTerm(t); + } + } + } + /** * The standard concrete syntax for the character literal indicator `C'. */ static final class CharLiteral extends Notation { - private static final Logger LOGGER = LoggerFactory.getLogger(CharLiteral.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CharLiteral.class); - public CharLiteral() { - super(1000); - } + public CharLiteral() { + super(1000); + } - private static String printCharTerm(Term t) { + private static String printCharTerm(Term t) { - char charVal = 0; - int intVal = 0; + char charVal = 0; + int intVal = 0; - String result = NumLiteral.printNumberTerm(t.sub(0)); + String result = NumLiteral.printNumberTerm(t.sub(0)); - if (result == null) { - return null; - } + if (result == null) { + return null; + } - try { - intVal = Integer.parseInt(result); - charVal = (char) intVal; - if (intVal - charVal != 0) - throw new NumberFormatException(); // overflow! + try { + intVal = Integer.parseInt(result); + charVal = (char) intVal; + if (intVal - charVal != 0) + throw new NumberFormatException(); // overflow! - } catch (NumberFormatException ex) { - LOGGER.error("Oops. {} is not of type char", result); - return null; - } + } catch (NumberFormatException ex) { + LOGGER.error("Oops. {} is not of type char", result); + return null; + } - return ("'" + charVal) + "'"; - } + return ("'" + charVal) + "'"; + } - public void print(Term t, LogicPrinter sp) throws IOException { - final String charString = printCharTerm(t); - if (charString != null) { - sp.printConstant(charString); - } else { - sp.printFunctionTerm(t); - } - } + public void print(Term t, LogicPrinter sp) throws IOException { + final String charString = printCharTerm(t); + if (charString != null) { + sp.printConstant(charString); + } else { + sp.printFunctionTerm(t); + } + } } - - /** + + /** * The standard concrete syntax for the float literal indicator `FP'. */ static final class FloatLiteral extends Notation { @@ -672,10 +657,10 @@ public static String printFloatTerm(Term floatTerm) { float f = Float.intBitsToFloat(bits); if (Float.isNaN(f)) { return "floatNaN"; - } else if (f == Float.POSITIVE_INFINITY) { - return "floatInf"; - } else if (f == Float.NEGATIVE_INFINITY) { - return "-floatInf"; + } else if (f == Float.POSITIVE_INFINITY) { + return "floatInf"; + } else if (f == Float.NEGATIVE_INFINITY) { + return "-floatInf"; } else { return f + "f"; } @@ -689,8 +674,8 @@ private static int extractValue(Term t) { return 0; } else { int digit = Integer.parseInt(t.op().name().toString()); - int result = digit + 10 * extractValue(t.sub(0)); - return result; + int result = digit + 10 * extractValue(t.sub(0)); + return result; } } @@ -724,9 +709,9 @@ public static String printDoubleTerm(Term doubleTerm) { if (Double.isNaN(f)) { return "floatNaN"; } else if (f == Double.POSITIVE_INFINITY) { - return "doubleInf"; - } else if (f == Double.NEGATIVE_INFINITY) { - return "-doubleInf"; + return "doubleInf"; + } else if (f == Double.NEGATIVE_INFINITY) { + return "-doubleInf"; } else { return f + "d"; } @@ -753,26 +738,26 @@ public void print(Term t, LogicPrinter sp) throws IOException { } } } - + /** * The standard concrete syntax for sequence singletons. */ public static final class SeqSingletonNotation extends Notation { final String lDelimiter; - final String rDelimiter; + final String rDelimiter; - public SeqSingletonNotation(String lDelimiter, String rDelimiter) { - super(130); + public SeqSingletonNotation(String lDelimiter, String rDelimiter) { + super(130); this.lDelimiter = lDelimiter; this.rDelimiter = rDelimiter; - } + } - public void print(Term t, LogicPrinter sp) throws IOException { - sp.printSeqSingleton(t, lDelimiter, rDelimiter); - } + public void print(Term t, LogicPrinter sp) throws IOException { + sp.printSeqSingleton(t, lDelimiter, rDelimiter); + } } - + public static final class SeqConcatNotation extends Notation { private final Function seqSingleton; @@ -780,27 +765,25 @@ public static final class SeqConcatNotation extends Notation { private final Function charLiteral; - public SeqConcatNotation(Function seqConcat, Function seqSingleton, Function charLiteral) { + public SeqConcatNotation(Function seqConcat, Function seqSingleton, Function charLiteral) { super(130); this.seqConcat = seqConcat; this.seqSingleton = seqSingleton; this.charLiteral = charLiteral; } - + private String printStringTerm(Term t) { String result = "\""; Term term = t; while (term.op().arity() == 2) { - result = result - + CharLiteral.printCharTerm(term.sub(0).sub(0)).charAt(1); - term = term.sub(1); + result = result + CharLiteral.printCharTerm(term.sub(0).sub(0)).charAt(1); + term = term.sub(1); } - result = result - + CharLiteral.printCharTerm(term.sub(0)).charAt(1); + result = result + CharLiteral.printCharTerm(term.sub(0)).charAt(1); return (result + "\""); } - + @Override public void print(Term t, LogicPrinter sp) throws IOException { if (isCharLiteralSequence(t)) { @@ -808,9 +791,9 @@ public void print(Term t, LogicPrinter sp) throws IOException { try { sLit = printStringTerm(t); } catch (Exception e) { - sp.printFunctionTerm(t); + sp.printFunctionTerm(t); return; - } + } sp.printConstant(sLit); } else { sp.printFunctionTerm(t); @@ -818,10 +801,10 @@ public void print(Term t, LogicPrinter sp) throws IOException { } - private boolean isCharLiteralSequence(Term t) { + private boolean isCharLiteralSequence(Term t) { if (t.op() == seqConcat && isCharLiteralSequenceHelp(t.sub(0))) { return isCharLiteralSequenceHelp(t.sub(1)) || isCharLiteralSequence(t.sub(1)); - } + } return false; } @@ -831,13 +814,12 @@ private boolean isCharLiteralSequenceHelp(Term t) { } } - + public static final class SeqGetNotation extends Notation { public SeqGetNotation() { /* - * Not sure what value to choose here. - * (Kai Wallisch 10/2014) + * Not sure what value to choose here. (Kai Wallisch 10/2014) */ super(130); } diff --git a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java index a7d8146b153..901e3c56076 100644 --- a/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java +++ b/key/key.core/src/main/java/de/uka/ilkd/key/pp/NotationInfo.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed by the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0 */ package de.uka.ilkd.key.pp; import java.util.HashMap; @@ -14,75 +17,58 @@ /** *

      - * Stores the mapping from operators to {@link Notation}s. Each - * {@link Notation} represents the concrete syntax for some - * {@link de.uka.ilkd.key.logic.op.Operator}. The {@link LogicPrinter} - * asks the NotationInfo to find out which Notation to use for a given term. + * Stores the mapping from operators to {@link Notation}s. Each {@link Notation} represents the + * concrete syntax for some {@link de.uka.ilkd.key.logic.op.Operator}. The {@link LogicPrinter} asks + * the NotationInfo to find out which Notation to use for a given term. *

      - * The Notation associated with an operator might change. New Notations can - * be added. + * The Notation associated with an operator might change. New Notations can be added. * *

      - * The next lines describe a general rule how to determine priorities and - * associativities: + * The next lines describe a general rule how to determine priorities and associativities: * - * One thing we need to know from the pretty printer: - * Given a term t containg s as proper subterm. - * Then s is printed in parentheses when the priority of the - * top level symbol of s is strict less than the associativity of the - * position where s occurs. For example: - *

      - * Let the priority of AND be 30 and the associativities for each - * of its subterms be 40; ORs priority is 20 and the associativites are - * both 30 then - *

      • formula (p & q) | r is pretty printed as p & q | r - * as the priority of & is 30 which is (greater or) equal than the - * associativity of ORs left subterm which is 30.
      • - *
      • In contrast the formula p & (q | r) is pretty printed as - * p & (q | r) as the priority of OR is 20 which is less than - * the associativity of ANDs left subterm, which is 40.
      • - *
      + * One thing we need to know from the pretty printer: Given a term t containg s as + * proper subterm. Then s is printed in parentheses when the priority of the top level + * symbol of s is strict less than the associativity of the position where s + * occurs. For example: + *

      + * Let the priority of AND be 30 and the associativities for each of its subterms + * be 40; ORs priority is 20 and the associativites are both 30 then + *

        + *
      • formula (p & q) | r is pretty printed as p & q | r as the priority of & is + * 30 which is (greater or) equal than the associativity of ORs left subterm which is + * 30.
      • + *
      • In contrast the formula p & (q | r) is pretty printed as p & (q | r) as the + * priority of OR is 20 which is less than the associativity of ANDs left subterm, + * which is 40.
      • + *
      * * A general rule to determine the correct priority and associativity is to use: * - * Grammar rules whose derivation delivers a syntactical correct logic term should follow - * a standard numbering scheme, which is used as indicator for priorities and associativites, - * e.g. - * by simply reading the grammar rule - *
      term60 ::= term70 (IMP term70)?
      - * we get the priority of IMP, which is 60. The associativities - * of IMPs subterms are not much more difficult to determine, namely - * the left subterm has associativity 70 and in this case its the same - * for the right subterm (70). - *

      - * There are exceptional cases for - *