From 7342cbd84182b16090415769529168705ba6c90a Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 23 Apr 2024 11:36:27 +0200 Subject: [PATCH 01/10] Removal of Quadruple.java --- .../merge/procedures/MergeByIfThenElse.java | 44 ++++----- .../procedures/MergeIfThenElseAntecedent.java | 3 +- .../java/de/uka/ilkd/key/util/Quadruple.java | 35 -------- .../key_project/slicing/RuleStatistics.java | 22 +++-- .../slicing/ui/RuleStatisticsDialog.java | 90 ++++++++----------- 5 files changed, 77 insertions(+), 117 deletions(-) delete mode 100644 key.core/src/main/java/de/uka/ilkd/key/util/Quadruple.java diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java index 2ad185845f0..538e1dd3865 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java @@ -12,7 +12,6 @@ import de.uka.ilkd.key.logic.op.LocationVariable; import de.uka.ilkd.key.rule.merge.MergeProcedure; import de.uka.ilkd.key.rule.merge.MergeRule; -import de.uka.ilkd.key.util.Quadruple; import de.uka.ilkd.key.util.mergerule.SymbolicExecutionState; import org.key_project.util.collection.DefaultImmutableSet; @@ -108,7 +107,7 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, Term cond, ifForm, elseForm; if (distinguishingFormula == null) { - Quadruple distFormAndRightSidesForITEUpd = + DistanceFormRightSide distFormAndRightSidesForITEUpd = createDistFormAndRightSidesForITEUpd(state1, state2, ifTerm, elseTerm, services); cond = distFormAndRightSidesForITEUpd.first(); @@ -136,18 +135,18 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * the discriminating condition, the second and third elements are the respective parts for the * if and else branch. * - * @param v Variable to return the update for. - * @param state1 First state to evaluate. - * @param state2 Second state to evaluate. + * @param v Variable to return the update for. + * @param state1 First state to evaluate. + * @param state2 Second state to evaluate. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first - * component). + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first + * component). */ - static Quadruple createDistFormAndRightSidesForITEUpd( + static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( LocationVariable v, SymbolicExecutionState state1, SymbolicExecutionState state2, Services services) { @@ -178,19 +177,19 @@ static Quadruple createDistFormAndRightSidesForITEUpd * the triple is the discriminating condition, the second and third elements are the respective * parts for the if and else branch. * - * @param state1 First state to evaluate. - * @param state2 Second state to evaluate. - * @param ifTerm The if term. + * @param state1 First state to evaluate. + * @param state2 Second state to evaluate. + * @param ifTerm The if term. * @param elseTerm The else term. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first - * component). + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first + * component). */ - static Quadruple createDistFormAndRightSidesForITEUpd( + static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( SymbolicExecutionState state1, SymbolicExecutionState state2, Term ifTerm, Term elseTerm, Services services) { @@ -246,7 +245,7 @@ static Quadruple createDistFormAndRightSidesForITEUpd distinguishingFormula = trySimplify(services.getProof(), distinguishingFormula, true, SIMPLIFICATION_TIMEOUT_MS); - return new Quadruple<>(distinguishingFormula, + return new DistanceFormRightSide(distinguishingFormula, commuteSides ? elseTerm : ifTerm, commuteSides ? ifTerm : elseTerm, commuteSides); } @@ -255,4 +254,7 @@ static Quadruple createDistFormAndRightSidesForITEUpd public String toString() { return DISPLAY_NAME; } + + public record DistanceFormRightSide(Term first, Term second, Term third, boolean fourth) { + } } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java index 18d456f3509..ca4c9edc55c 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java @@ -11,7 +11,6 @@ import de.uka.ilkd.key.logic.op.JFunction; import de.uka.ilkd.key.rule.merge.MergeProcedure; import de.uka.ilkd.key.rule.merge.MergeRule; -import de.uka.ilkd.key.util.Quadruple; import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; import de.uka.ilkd.key.util.mergerule.SymbolicExecutionState; @@ -103,7 +102,7 @@ private static ImmutableSet getIfThenElseConstraints(Term constrained, Ter ImmutableSet result = DefaultImmutableSet.nil(); if (distinguishingFormula == null) { - final Quadruple distFormAndRightSidesForITEUpd = + final MergeByIfThenElse.DistanceFormRightSide distFormAndRightSidesForITEUpd = MergeByIfThenElse.createDistFormAndRightSidesForITEUpd(state1, state2, ifTerm, elseTerm, services); diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/Quadruple.java b/key.core/src/main/java/de/uka/ilkd/key/util/Quadruple.java deleted file mode 100644 index 3a18b0a7558..00000000000 --- a/key.core/src/main/java/de/uka/ilkd/key/util/Quadruple.java +++ /dev/null @@ -1,35 +0,0 @@ -/* This file is part of KeY - https://key-project.org - * KeY is licensed under the GNU General Public License Version 2 - * SPDX-License-Identifier: GPL-2.0-only */ -package de.uka.ilkd.key.util; - -import java.util.Comparator; - -/** - * Simple 4-tuple data object. - * - * @param type of first element - * @param type of second element - * @param type of third element - * @param type of fourth element - * @author Dominic Scheurer - */ -public record Quadruple(T1 first, T2 second, T3 third, T4 fourth) { - - /** - * Constructs a comparator for a {@link Quadruple} with arbitrary comparable arguments. - */ - public static , T2 extends Comparable, - T3 extends Comparable, T4 extends Comparable> - Comparator> getComparator() { - Comparator> t1 = Comparator.comparing(it -> it.first); - Comparator> t2 = Comparator.comparing(it -> it.second); - Comparator> t3 = Comparator.comparing(it -> it.third); - Comparator> t4 = Comparator.comparing(it -> it.fourth); - return t1.thenComparing(t2).thenComparing(t3).thenComparing(t4); - } - - public String toString() { - return "(" + first + ", " + second + ", " + third + ", " + fourth + ")"; - } -} diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java index 2a2ee3d8ddb..f011f4e5601 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java @@ -3,16 +3,15 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.slicing; +import de.uka.ilkd.key.rule.Rule; +import de.uka.ilkd.key.util.Triple; + import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import de.uka.ilkd.key.rule.Rule; -import de.uka.ilkd.key.util.Quadruple; -import de.uka.ilkd.key.util.Triple; - /** * Simple data object to store a mapping of rules to various counters. * @@ -83,10 +82,9 @@ public void addInitialUselessApplication(Rule rule, boolean branches) { * @param comparator custom comparator * @return list of rule names + counters */ - public List> sortBy( - Comparator> comparator) { + public List sortBy(Comparator comparator) { return map.entrySet().stream() - .map(entry -> new Quadruple<>(entry.getKey(), entry.getValue().first, + .map(entry -> new RuleStatisticEntry(entry.getKey(), entry.getValue().first, entry.getValue().second, entry.getValue().third)) .sorted(comparator) .collect(Collectors.toList()); @@ -99,4 +97,14 @@ public List> sortBy( public boolean branches(String rule) { return ruleBranched.get(rule); } + + /** + * Usage statistic of a rule. + * @param ruleName + * @param numberOfApplications + * @param numberOfUselessApplications + * @param numberOfInitialUselessApplications + */ + public record RuleStatisticEntry(String ruleName, int numberOfApplications, int numberOfUselessApplications, int numberOfInitialUselessApplications) { + } } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java b/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java index 9358166f5cb..ab4b78c1394 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java @@ -3,20 +3,19 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.slicing.ui; -import java.awt.*; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.util.*; -import java.util.List; -import javax.swing.*; - import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.configuration.Config; -import de.uka.ilkd.key.util.Quadruple; - import org.key_project.slicing.RuleStatistics; +import org.key_project.slicing.RuleStatistics.RuleStatisticEntry; import org.key_project.slicing.analysis.AnalysisResults; +import javax.swing.*; +import java.awt.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.List; +import java.util.*; + /** * Dialog that displays the results of the dependency analysis algorithm. * @@ -59,7 +58,7 @@ private void createUI(Window window) { statisticsPane.setBackground(MainWindow.getInstance().getBackground()); statisticsPane.setSize(new Dimension(10, 360)); statisticsPane.setPreferredSize( - new Dimension(statisticsPane.getPreferredSize().width + 15, 360)); + new Dimension(statisticsPane.getPreferredSize().width + 15, 360)); JScrollPane scrollPane = new JScrollPane(statisticsPane); scrollPane.setBorder(BorderFactory.createEmptyBorder()); @@ -67,7 +66,7 @@ private void createUI(Window window) { Font myFont = UIManager.getFont(Config.KEY_FONT_PROOF_TREE); if (myFont != null) { statisticsPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, - Boolean.TRUE); + Boolean.TRUE); statisticsPane.setFont(myFont); } @@ -78,18 +77,17 @@ private void createUI(Window window) { int w = 50 + Math.max( - scrollPane.getPreferredSize().width, - buttonPane.getPreferredSize().width); + scrollPane.getPreferredSize().width, + buttonPane.getPreferredSize().width); int h = scrollPane.getPreferredSize().height + buttonPane.getPreferredSize().height + 100; setSize(w, h); statisticsPane.setText(genTable( - statistics.sortBy( - Comparator - .comparing((Quadruple it) -> it.second()) - .reversed()))); + statistics.sortBy( + Comparator.comparing(RuleStatisticEntry::numberOfApplications) + .reversed()))); statisticsPane.setCaretPosition(0); setLocationRelativeTo(window); } @@ -111,37 +109,25 @@ private JPanel constructButtonPanel(JEditorPane statisticsPane) { JButton sortButton1 = new JButton("Sort by name"); sortButton1.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy(Comparator.comparing(Quadruple::first)))); + statistics.sortBy(Comparator.comparing(RuleStatisticEntry::ruleName)))); statisticsPane.setCaretPosition(0); }); JButton sortButton2 = new JButton("Sort by total"); sortButton2.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy( - Comparator - .comparing( - (Quadruple it) -> it.second()) - .reversed()))); + statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfApplications).reversed()))); statisticsPane.setCaretPosition(0); }); JButton sortButton3 = new JButton("Sort by useless"); sortButton3.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy( - Comparator - .comparing( - (Quadruple it) -> it.third()) - .reversed()))); + statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfUselessApplications).reversed()))); statisticsPane.setCaretPosition(0); }); JButton sortButton4 = new JButton("Sort by initial useless"); sortButton4.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy( - Comparator - .comparing( - (Quadruple it) -> it.fourth()) - .reversed()))); + statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfInitialUselessApplications).reversed()))); statisticsPane.setCaretPosition(0); }); @@ -170,37 +156,37 @@ public void keyTyped(KeyEvent e) { * @param rules statistics on rule apps (see {@link RuleStatistics}) * @return HTML */ - private String genTable(List> rules) { + private String genTable(List rules) { List columns = List.of("Rule name", "Total applications", "Useless applications", - "Initial useless applications"); + "Initial useless applications"); List> rows = new ArrayList<>(); // summary row int uniqueRules = rules.size(); - int totalSteps = rules.stream().mapToInt(Quadruple::second).sum(); - int uselessSteps = rules.stream().mapToInt(Quadruple::third).sum(); - int initialUseless = rules.stream().mapToInt(Quadruple::fourth).sum(); + int totalSteps = rules.stream().mapToInt(RuleStatisticEntry::numberOfApplications).sum(); + int uselessSteps = rules.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); + int initialUseless = rules.stream().mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); rows.add(List.of(String.format("(all %d rules)", uniqueRules), Integer.toString(totalSteps), - Integer.toString(uselessSteps), Integer.toString(initialUseless))); + Integer.toString(uselessSteps), Integer.toString(initialUseless))); // next summary row - List> rulesBranching = - rules.stream().filter(it -> statistics.branches(it.first())).toList(); + List rulesBranching = + rules.stream().filter(it -> statistics.branches(it.ruleName())).toList(); int uniqueRules2 = rulesBranching.size(); - totalSteps = rulesBranching.stream().mapToInt(Quadruple::second).sum(); - uselessSteps = rulesBranching.stream().mapToInt(Quadruple::third).sum(); - initialUseless = rulesBranching.stream().mapToInt(Quadruple::fourth).sum(); + totalSteps = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfApplications).sum(); + uselessSteps = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); + initialUseless = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); rows.add(List.of(String.format("(%d branching rules)", uniqueRules2), - Integer.toString(totalSteps), Integer.toString(uselessSteps), - Integer.toString(initialUseless))); + Integer.toString(totalSteps), Integer.toString(uselessSteps), + Integer.toString(initialUseless))); rules.forEach(a -> { - String name = a.first(); - Integer all = a.second(); - Integer useless = a.third(); - Integer iua = a.fourth(); + String name = a.ruleName(); + Integer all = a.numberOfApplications(); + Integer useless = a.numberOfUselessApplications(); + Integer iua = a.numberOfInitialUselessApplications(); rows.add(List.of(name, all.toString(), useless.toString(), iua.toString())); }); - return HtmlFactory.generateTable(columns, new boolean[] { false, false, false, false }, - Optional.of(new String[] { null, "right", "right", "right" }), rows, null); + return HtmlFactory.generateTable(columns, new boolean[]{false, false, false, false}, + Optional.of(new String[]{null, "right", "right", "right"}), rows, null); } } From ec83987cb9659ed8add8f21910effd2ee75402ad Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 23 Apr 2024 12:28:08 +0200 Subject: [PATCH 02/10] Removal of the Triple class --- .../rule/AbstractSideProofRule.java | 6 +- .../rule/ModalitySideProofRule.java | 35 +-- .../rule/QuerySideProofRule.java | 21 +- .../util/SymbolicExecutionSideProofUtil.java | 132 ++++---- .../uka/ilkd/key/control/KeYEnvironment.java | 10 +- .../java/de/uka/ilkd/key/nparser/KeyAst.java | 11 +- .../key/proof/init/KeYUserProblemFile.java | 15 +- .../key/proof/io/AbstractProblemLoader.java | 100 +++--- .../proof/io/IntermediateProofReplayer.java | 26 +- .../proof/mgt/SpecificationRepository.java | 294 ++++++++---------- .../uka/ilkd/key/rule/WhileInvariantRule.java | 108 +++---- .../de/uka/ilkd/key/rule/merge/MergeRule.java | 43 +-- .../ilkd/key/speclang/ContractFactory.java | 12 +- .../pretranslation/TextualJMLSpecCase.java | 7 +- .../jml/translation/JMLSpecFactory.java | 3 +- .../de/uka/ilkd/key/speclang/njml/JmlIO.java | 9 +- .../key/speclang/njml/JmlTermFactory.java | 4 +- .../njml/TranslatedDependencyContract.java | 12 + .../StrategySettingsDefinition.java | 17 +- .../java/de/uka/ilkd/key/util/Triple.java | 62 ---- .../key/util/mergerule/MergeRuleUtils.java | 9 +- .../SymbolicExecutionStateWithProgCnt.java | 8 +- .../uka/ilkd/key/logic/TestLocalSymbols.java | 2 +- .../key/proof/proverules/ProveRulesTest.java | 4 +- .../key/proof/runallproofs/ProveTest.java | 3 +- .../performance/DataRecordingTestFile.java | 6 +- .../proofcollection/TestFile.java | 13 +- .../ilkd/key/gui/StrategySelectionView.java | 13 +- .../key/gui/WindowUserInterfaceControl.java | 6 +- .../key/gui/proofdiff/ProofDifference.java | 23 +- .../key_project/slicing/RuleStatistics.java | 36 ++- .../slicing/graph/DependencyGraph.java | 11 +- .../slicing/ui/ShowNodeInfoAction.java | 21 +- 33 files changed, 492 insertions(+), 590 deletions(-) create mode 100644 key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java delete mode 100644 key.core/src/main/java/de/uka/ilkd/key/util/Triple.java diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java index b4f25f305e1..1cdbd787f8f 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java @@ -25,7 +25,6 @@ import de.uka.ilkd.key.rule.BuiltInRule; import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionSideProofUtil; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.logic.sort.Sort; @@ -87,7 +86,7 @@ protected JFunction createResultFunction(Services services, Sort sort) { * @return The found result {@link Term} and the conditions. * @throws ProofInputException Occurred Exception. */ - protected List, Node>> computeResultsAndConditions(Services services, + protected List computeResultsAndConditions(Services services, Goal goal, ProofEnvironment sideProofEnvironment, Sequent sequentToProve, JFunction newPredicate) throws ProofInputException { return SymbolicExecutionSideProofUtil.computeResultsAndConditions(services, goal.proof(), @@ -134,4 +133,7 @@ protected static SequentFormula replace(PosInOccurrence pio, Term newTerm, Servi public boolean isApplicableOnSubTerms() { return false; } + + public record ResultsAndCondition(Term result, Set conditions, Node node) { + } } diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java index 6c1fc13fb94..9023be377d2 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java @@ -3,36 +3,23 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.symbolic_execution.rule; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.PosInOccurrence; -import de.uka.ilkd.key.logic.Sequent; -import de.uka.ilkd.key.logic.SequentFormula; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.TermBuilder; -import de.uka.ilkd.key.logic.TermServices; +import de.uka.ilkd.key.logic.*; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.mgt.ProofEnvironment; -import de.uka.ilkd.key.rule.BuiltInRule; -import de.uka.ilkd.key.rule.DefaultBuiltInRuleApp; -import de.uka.ilkd.key.rule.IBuiltInRuleApp; -import de.uka.ilkd.key.rule.RuleAbortException; -import de.uka.ilkd.key.rule.RuleApp; +import de.uka.ilkd.key.rule.*; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionSideProofUtil; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; -import de.uka.ilkd.key.util.Triple; - +import org.jspecify.annotations.NonNull; import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.Pair; -import org.jspecify.annotations.NonNull; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; /** *

@@ -181,7 +168,7 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { .addFormula(new SequentFormula(newModalityWithUpdatesTerm), false, false) .sequent(); // Compute results and their conditions - List, Node>> conditionsAndResultsMap = + List conditionsAndResultsMap = computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, newPredicate); // Create new single goal in which the query is replaced by the possible results @@ -190,10 +177,10 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { 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); + for (ResultsAndCondition conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.conditions()); + Term resultEqualityTerm = varFirst ? tb.equals(conditionsAndResult.result(), otherTerm) + : tb.equals(otherTerm, conditionsAndResult.result()); Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, resultEqualityTerm) : tb.and(conditionTerm, resultEqualityTerm); resultTerms.add(resultTerm); diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java index 2f00a4a8941..21dd88702da 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java @@ -4,7 +4,6 @@ package de.uka.ilkd.key.symbolic_execution.rule; import java.util.List; -import java.util.Set; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.PIOPathIterator; @@ -16,7 +15,6 @@ import de.uka.ilkd.key.logic.TermServices; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.mgt.ProofEnvironment; import de.uka.ilkd.key.rule.BuiltInRule; import de.uka.ilkd.key.rule.DefaultBuiltInRuleApp; @@ -25,7 +23,6 @@ import de.uka.ilkd.key.rule.RuleAbortException; import de.uka.ilkd.key.rule.RuleApp; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionSideProofUtil; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.logic.sort.Sort; @@ -228,7 +225,7 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { sequentToProve = sequentToProve.addFormula(new SequentFormula(newTerm), false, false).sequent(); // Compute results and their conditions - List, Node>> conditionsAndResultsMap = + List conditionsAndResultsMap = computeResultsAndConditions(services, goal, sideProofEnv, sequentToProve, newPredicate); // Create new single goal in which the query is replaced by the possible results @@ -237,10 +234,10 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { 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); + for (ResultsAndCondition conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.conditions()); + Term newEqualityTerm = varFirst ? tb.equals(varTerm, conditionsAndResult.result()) + : tb.equals(conditionsAndResult.result(), varTerm); Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, newEqualityTerm) : tb.and(conditionTerm, newEqualityTerm); if (queryConditionTerm != null) { @@ -256,11 +253,11 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { tb.equals(resultFunctionTerm, varTerm), services), pio.isInAntec(), false); - for (Triple, Node> conditionsAndResult : conditionsAndResultsMap) { - Term conditionTerm = tb.and(conditionsAndResult.second); + for (ResultsAndCondition conditionsAndResult : conditionsAndResultsMap) { + Term conditionTerm = tb.and(conditionsAndResult.conditions()); Term resultTerm = tb.imp(conditionTerm, - varFirst ? tb.equals(resultFunctionTerm, conditionsAndResult.first) - : tb.equals(conditionsAndResult.first, resultFunctionTerm)); + varFirst ? tb.equals(resultFunctionTerm, conditionsAndResult.result()) + : tb.equals(conditionsAndResult.result(), resultFunctionTerm)); resultGoal.addFormula(new SequentFormula(resultTerm), true, false); } } diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java index 766547c958c..f26b338c655 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java @@ -3,8 +3,6 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.symbolic_execution.util; -import java.util.*; - import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.ldt.HeapLDT; @@ -32,10 +30,9 @@ import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.symbolic_execution.profile.SimplifyTermProfile; import de.uka.ilkd.key.symbolic_execution.profile.SymbolicExecutionJavaProfile; +import de.uka.ilkd.key.symbolic_execution.rule.AbstractSideProofRule.ResultsAndCondition; import de.uka.ilkd.key.util.ProofStarter; import de.uka.ilkd.key.util.SideProofUtil; -import de.uka.ilkd.key.util.Triple; - import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; @@ -43,6 +40,8 @@ import org.key_project.util.collection.Pair; import org.key_project.util.java.CollectionUtil; +import java.util.*; + /** * Provides utility methods for side proofs. * @@ -65,7 +64,7 @@ private SymbolicExecutionSideProofUtil() { * @return The general initial {@link Sequent}. */ public static Sequent computeGeneralSequentToProve(Sequent goalSequent, - SequentFormula currentSF) { + SequentFormula currentSF) { Sequent sequentToProve = Sequent.EMPTY_SEQUENT; for (SequentFormula sf : goalSequent.antecedent()) { if (sf != currentSF) { @@ -106,12 +105,12 @@ public static Sequent computeGeneralSequentToProve(Sequent goalSequent, * @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 { + 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); + methodTreatment, loopTreatment, queryTreatment, splittingOption); try { // Extract results and conditions from side proof List> conditionsAndResultsMap = new LinkedList<>(); @@ -169,21 +168,21 @@ public static List> computeResults(Services services, Proof pro * @return The found result {@link Term} and the conditions. * @throws ProofInputException Occurred Exception. */ - public static List, Node>> computeResultsAndConditions(Services services, + public static List 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); + methodTreatment, loopTreatment, queryTreatment, splittingOption); try { // Extract relevant things Set relevantThingsInSequentToProve = - extractRelevantThings(info.getProof().getServices(), sequentToProve); + extractRelevantThings(info.getProof().getServices(), sequentToProve); // Extract results and conditions from side proof - List, Node>> conditionsAndResultsMap = - new LinkedList<>(); + List conditionsAndResultsMap = new LinkedList<>(); for (Goal resultGoal : info.getProof().openGoals()) { if (SymbolicExecutionUtil.hasApplicableRules(resultGoal)) { throw new IllegalStateException("Not all applicable rules are applied."); @@ -196,18 +195,18 @@ public static List, Node>> computeResultsAndConditions(Se if (newPredicateIsSequentFormula) { if (Operator.opEquals(sf.formula().op(), operator)) { throw new IllegalStateException( - "Result predicate found in antecedent."); + "Result predicate found in antecedent."); } else { Term constructedResult = - constructResultIfContained(services, sf, operator); + constructResultIfContained(services, sf, operator); if (constructedResult != null) { throw new IllegalStateException( - "Result predicate found in antecedent."); + "Result predicate found in antecedent."); } } } if (!isIrrelevantCondition(services, sequentToProve, - relevantThingsInSequentToProve, sf)) { + relevantThingsInSequentToProve, sf)) { if (resultConditions.add(sf.formula()) && addNamesToServices) { addNewNamesToNamespace(services, sf.formula()); } @@ -218,7 +217,7 @@ public static List, Node>> computeResultsAndConditions(Se if (Operator.opEquals(sf.formula().op(), operator)) { if (result != null) { throw new IllegalStateException( - "Result predicate found multiple times in succedent."); + "Result predicate found multiple times in succedent."); } result = sf.formula().sub(0); } @@ -227,14 +226,14 @@ public static List, Node>> computeResultsAndConditions(Se if (constructedResult != null) { if (result != null) { throw new IllegalStateException( - "Result predicate found multiple times in succedent."); + "Result predicate found multiple times in succedent."); } result = constructedResult; } } if (result == null) { if (!isIrrelevantCondition(services, sequentToProve, - relevantThingsInSequentToProve, sf)) { + relevantThingsInSequentToProve, sf)) { if (resultConditions.add(services.getTermBuilder().not(sf.formula())) && addNamesToServices) { addNewNamesToNamespace(services, sf.formula()); @@ -245,8 +244,7 @@ public static List, Node>> computeResultsAndConditions(Se if (result == null) { result = services.getTermBuilder().ff(); } - conditionsAndResultsMap.add( - new Triple<>(result, resultConditions, resultGoal.node())); + conditionsAndResultsMap.add(new ResultsAndCondition(result, resultConditions, resultGoal.node())); } return conditionsAndResultsMap; } finally { @@ -255,12 +253,12 @@ public static List, Node>> computeResultsAndConditions(Se } private static Term constructResultIfContained(Services services, SequentFormula sf, - Operator operator) { + Operator operator) { return constructResultIfContained(services, sf.formula(), operator); } private static Term constructResultIfContained(Services services, Term term, - Operator operator) { + Operator operator) { if (Operator.opEquals(term.op(), operator)) { return term.sub(0); } else { @@ -280,8 +278,8 @@ private static Term constructResultIfContained(Services services, Term term, } } result = services.getTermFactory().createTerm(term.op(), - new ImmutableArray<>(newSubs), term.boundVars(), - term.getLabels()); + new ImmutableArray<>(newSubs), term.boundVars(), + term.getLabels()); } return result; } @@ -289,7 +287,7 @@ private static Term constructResultIfContained(Services services, Term term, private static boolean isOperatorASequentFormula(Sequent sequent, final Operator operator) { return CollectionUtil.search(sequent, - element -> Operator.opEquals(element.formula().op(), operator)) != null; + element -> Operator.opEquals(element.formula().op(), operator)) != null; } /** @@ -303,14 +301,11 @@ 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 JFunction) { - functions.add((JFunction) visited.op()); - } else if (visited.op() instanceof IProgramVariable) { - progVars.add((IProgramVariable) visited.op()); - } + term.execPreOrder((DefaultVisitor) visited -> { + if (visited.op() instanceof JFunction) { + functions.add((JFunction) visited.op()); + } else if (visited.op() instanceof IProgramVariable) { + progVars.add((IProgramVariable) visited.op()); } }); } @@ -382,15 +377,12 @@ public boolean isContainsModalityOrQuery() { * @return The found relevant things. */ public static Set extractRelevantThings(final Services services, - Sequent sequentToProve) { + 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()); - } + sf.formula().execPreOrder((DefaultVisitor) visited -> { + if (isRelevantThing(services, visited)) { + result.add(visited.op()); } }); } @@ -437,7 +429,7 @@ private static boolean isRelevantThing(Services services, Term term) { * {@link SequentFormula} is not a relevant condition. */ public static boolean isIrrelevantCondition(Services services, Sequent initialSequent, - Set relevantThingsInSequentToProve, SequentFormula sf) { + Set relevantThingsInSequentToProve, SequentFormula sf) { return initialSequent.antecedent().contains(sf) || initialSequent.succedent().contains(sf) || containsModalityOrQuery(sf) // isInOrOfAntecedent(initialSequent, sf) || || containsIrrelevantThings(services, sf, relevantThingsInSequentToProve); @@ -481,9 +473,9 @@ public static boolean isIrrelevantCondition(Services services, Sequent initialSe * {@link SequentFormula} contains no irrelevant things. */ public static boolean containsIrrelevantThings(Services services, SequentFormula sf, - Set relevantThings) { + Set relevantThings) { ContainsIrrelevantThingsVisitor visitor = - new ContainsIrrelevantThingsVisitor(services, relevantThings); + new ContainsIrrelevantThingsVisitor(services, relevantThings); sf.formula().execPostOrder(visitor); return visitor.isContainsIrrelevantThings(); } @@ -558,11 +550,11 @@ public boolean isContainsIrrelevantThings() { * @throws ProofInputException Occurred Exception */ public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, Sequent sequentToProve) + ProofEnvironment sideProofEnvironment, Sequent sequentToProve) throws ProofInputException { return startSideProof(proof, sideProofEnvironment, sequentToProve, - StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_OFF); + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_OFF); } /** @@ -575,12 +567,12 @@ public static ApplyStrategyInfo startSideProof(Proof proof, * @throws ProofInputException Occurred Exception */ public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, Sequent sequentToProve, String methodTreatment, - String loopTreatment, String queryTreatment, String splittingOption) + 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); + splittingOption); } /** @@ -594,7 +586,7 @@ public static ApplyStrategyInfo startSideProof(Proof proof, * @throws ProofInputException Occurred Exception. */ public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, String proofName) throws ProofInputException { + Sequent sequentToProve, String proofName) throws ProofInputException { return SideProofUtil.createSideProof(sideProofEnvironment, sequentToProve, proofName); } @@ -607,8 +599,8 @@ public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment * @return The site proof result. */ public static ApplyStrategyInfo startSideProof(Proof proof, ProofStarter starter, - String methodTreatment, String loopTreatment, String queryTreatment, - String splittingOption) { + String methodTreatment, String loopTreatment, String queryTreatment, + String splittingOption) { assert starter != null; starter.setMaxRuleApplications(10000); StrategyProperties sp = proof != null && !proof.isDisposed() @@ -621,7 +613,7 @@ public static ApplyStrategyInfo startSideProof(Proof proof, ProofStarter starter sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, queryTreatment); sp.setProperty(StrategyProperties.SPLITTING_OPTIONS_KEY, splittingOption); sp.setProperty(StrategyProperties.QUANTIFIERS_OPTIONS_KEY, - StrategyProperties.QUANTIFIERS_NON_SPLITTING); + StrategyProperties.QUANTIFIERS_NON_SPLITTING); starter.setStrategyProperties(sp); // Execute proof in the current thread return starter.start(); @@ -668,8 +660,8 @@ public static Term extractOperatorTerm(ApplyStrategyInfo info, Operator operator 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."); + "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); @@ -723,11 +715,11 @@ public static Term extractOperatorTerm(Node node, final Operator operator) { * {@link Proof} but with its own {@link OneStepSimplifier} instance. */ public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier(final Proof source, - final boolean useSimplifyTermProfile) { + final boolean useSimplifyTermProfile) { assert source != null; assert !source.isDisposed(); return cloneProofEnvironmentWithOwnOneStepSimplifier(source.getInitConfig(), - useSimplifyTermProfile); + useSimplifyTermProfile); } /** @@ -753,13 +745,13 @@ protected ImmutableList computeTermLabelConfiguration() Profile sourceProfile = sourceInitConfig.getProfile(); if (sourceProfile instanceof SymbolicExecutionJavaProfile) { ImmutableList result = - super.computeTermLabelConfiguration(); + super.computeTermLabelConfiguration(); // Make sure that the term labels of symbolic execution are also supported // by the new environment. result = result.prepend(SymbolicExecutionJavaProfile .getSymbolicExecutionTermLabelConfigurations( - SymbolicExecutionJavaProfile - .isTruthValueEvaluationEnabled(sourceInitConfig))); + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); return result; } else { return super.computeTermLabelConfiguration(); @@ -773,13 +765,13 @@ protected ImmutableList computeTermLabelConfiguration() Profile sourceProfile = sourceInitConfig.getProfile(); if (sourceProfile instanceof SymbolicExecutionJavaProfile) { ImmutableList result = - super.computeTermLabelConfiguration(); + super.computeTermLabelConfiguration(); // Make sure that the term labels of symbolic execution are also supported // by the new environment. result = result.prepend(SymbolicExecutionJavaProfile .getSymbolicExecutionTermLabelConfigurations( - SymbolicExecutionJavaProfile - .isTruthValueEvaluationEnabled(sourceInitConfig))); + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); return result; } else { return super.computeTermLabelConfiguration(); @@ -789,7 +781,7 @@ protected ImmutableList computeTermLabelConfiguration() } // Create new InitConfig final InitConfig initConfig = - new InitConfig(sourceInitConfig.getServices().copy(profile, false)); + 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 @@ -801,14 +793,14 @@ protected ImmutableList computeTermLabelConfiguration() : null; initConfig.setSettings(clonedSettings); initConfig.setTaclet2Builder( - (HashMap>) sourceInitConfig.getTaclet2Builder() - .clone()); + (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)); + sourceJustiInfo.getJustification(taclet)); } for (BuiltInRule rule : initConfig.builtInRules()) { RuleJustification origJusti = sourceJustiInfo.getJustification(rule); diff --git a/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java b/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java index 7e502b50096..23a70913479 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java +++ b/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java @@ -10,7 +10,7 @@ import de.uka.ilkd.key.java.JavaInfo; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.init.InitConfig; import de.uka.ilkd.key.proof.init.Profile; @@ -21,7 +21,7 @@ import de.uka.ilkd.key.proof.io.ProblemLoaderException; import de.uka.ilkd.key.proof.mgt.SpecificationRepository; -import org.key_project.util.collection.Pair; +import org.jspecify.annotations.Nullable; /** * Instances of this class are used to collect and access all relevant information for verification @@ -48,7 +48,7 @@ public class KeYEnvironment { /** * An optional field denoting a script contained in the proof file. */ - private final Pair proofScript; + private final @Nullable ProofScriptEntry proofScript; /** * Indicates that this {@link KeYEnvironment} is disposed. @@ -77,7 +77,7 @@ public KeYEnvironment(U ui, InitConfig initConfig) { * @param initConfig The loaded project. */ public KeYEnvironment(U ui, InitConfig initConfig, Proof loadedProof, - Pair proofScript, ReplayResult replayResult) { + @Nullable ProofScriptEntry proofScript, ReplayResult replayResult) { this.ui = ui; this.initConfig = initConfig; this.loadedProof = loadedProof; @@ -317,7 +317,7 @@ public boolean isDisposed() { return disposed; } - public Pair getProofScript() { + public @Nullable ProofScriptEntry getProofScript() { return proofScript; } } diff --git a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java index 9eb702a8327..2f6215b5ca9 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java +++ b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java @@ -3,9 +3,11 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.nparser; +import java.net.URI; import java.net.URL; import java.util.List; +import de.uka.ilkd.key.java.Position; import de.uka.ilkd.key.nparser.builder.BuilderHelpers; import de.uka.ilkd.key.nparser.builder.ChoiceFinder; import de.uka.ilkd.key.nparser.builder.FindProblemInformation; @@ -15,7 +17,6 @@ import de.uka.ilkd.key.settings.Configuration; import de.uka.ilkd.key.settings.ProofSettings; import de.uka.ilkd.key.speclang.njml.JmlParser; -import de.uka.ilkd.key.util.Triple; import org.key_project.util.java.StringUtil; @@ -84,12 +85,14 @@ public static class File extends KeyAst { return settings; } - public @Nullable Triple findProofScript() { + public @Nullable ProofScriptEntry findProofScript(URI url) { if (ctx.problem() != null && ctx.problem().proofScript() != null) { KeYParser.ProofScriptContext pctx = ctx.problem().proofScript(); + Location location = new Location(url, + Position.newOneBased(pctx.ps.getLine(), pctx.ps.getCharPositionInLine())); + String text = pctx.ps.getText(); - return new Triple<>(StringUtil.trim(text, '"'), pctx.ps.getLine(), - pctx.ps.getCharPositionInLine()); + return new ProofScriptEntry(StringUtil.trim(text, '"'), location); } return null; } diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java index cd394dee308..89e20a76793 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java @@ -5,14 +5,12 @@ import java.io.File; import java.io.IOException; +import java.net.URI; import java.net.URISyntaxException; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.logic.Sequent; -import de.uka.ilkd.key.nparser.ChoiceInformation; -import de.uka.ilkd.key.nparser.KeyAst; -import de.uka.ilkd.key.nparser.ProblemInformation; -import de.uka.ilkd.key.nparser.ProofReplayer; +import de.uka.ilkd.key.nparser.*; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.ProofAggregate; import de.uka.ilkd.key.proof.io.IProofFileParser; @@ -23,8 +21,8 @@ import de.uka.ilkd.key.speclang.PositionedString; import de.uka.ilkd.key.speclang.SLEnvInput; import de.uka.ilkd.key.util.ProgressMonitor; -import de.uka.ilkd.key.util.Triple; +import org.jspecify.annotations.Nullable; import org.key_project.util.collection.DefaultImmutableSet; import org.key_project.util.collection.ImmutableSet; @@ -175,11 +173,12 @@ public boolean implies(ProofOblInput po) { public boolean hasProofScript() { - return getParseContext().findProofScript() != null; + return readProofScript() != null; } - public Triple readProofScript() { - return getParseContext().findProofScript(); + public @Nullable ProofScriptEntry readProofScript() { + URI url = getInitialFile().toURI(); + return getParseContext().findProofScript(url); } /** diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index 84cdbaf5706..b0671244d8d 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -17,7 +17,7 @@ import de.uka.ilkd.key.java.Position; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.nparser.KeYLexer; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.ProofAggregate; @@ -36,15 +36,30 @@ import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.util.ExceptionHandlerException; -import de.uka.ilkd.key.util.Triple; - +import org.antlr.runtime.MismatchedTokenException; +import org.jspecify.annotations.Nullable; import org.key_project.util.collection.Pair; import org.key_project.util.java.IOUtil; import org.antlr.runtime.MismatchedTokenException; +import org.key_project.util.reflection.ClassLoaderUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipFile; + /** *

* This class provides the basic functionality to load something in KeY. The loading process is done @@ -197,7 +212,7 @@ public boolean hasErrors() { // format: (expected, found) mismatchErrors = new HashMap<>(); mismatchErrors.put(new Pair<>(KeYLexer.SEMI, KeYLexer.COMMA), - "there may be only one declaration per line"); + "there may be only one declaration per line"); missedErrors = new HashMap<>(); missedErrors.put(KeYLexer.RPAREN, "closing parenthesis"); @@ -223,19 +238,19 @@ public boolean hasErrors() { * the loaded {@link InitConfig}. */ public AbstractProblemLoader(File file, List classPath, File bootClassPath, - List includes, Profile profileOfNewProofs, boolean forceNewProfileOfNewProofs, - ProblemLoaderControl control, - boolean askUiToSelectAProofObligationIfNotDefinedByLoadedFile, - Properties poPropertiesToForce) { + List includes, Profile profileOfNewProofs, boolean forceNewProfileOfNewProofs, + ProblemLoaderControl control, + boolean askUiToSelectAProofObligationIfNotDefinedByLoadedFile, + Properties poPropertiesToForce) { this.file = file; this.classPath = classPath; this.bootClassPath = bootClassPath; this.control = control; this.profileOfNewProofs = - profileOfNewProofs != null ? profileOfNewProofs : AbstractProfile.getDefaultProfile(); + profileOfNewProofs != null ? profileOfNewProofs : AbstractProfile.getDefaultProfile(); this.forceNewProfileOfNewProofs = forceNewProfileOfNewProofs; this.askUiToSelectAProofObligationIfNotDefinedByLoadedFile = - askUiToSelectAProofObligationIfNotDefinedByLoadedFile; + askUiToSelectAProofObligationIfNotDefinedByLoadedFile; this.poPropertiesToForce = poPropertiesToForce; this.includes = includes; } @@ -303,14 +318,14 @@ protected void loadEnvironment() throws ProofInputException, IOException { LOGGER.info("Loading environment from " + file); envInput = createEnvInput(fileRepo); LOGGER.debug( - "Environment load took " + PerfScope.formatTime(System.nanoTime() - timeBeforeEnv)); + "Environment load took " + PerfScope.formatTime(System.nanoTime() - timeBeforeEnv)); problemInitializer = createProblemInitializer(fileRepo); var beforeInitConfig = System.nanoTime(); LOGGER.info("Creating init config"); initConfig = createInitConfig(); initConfig.setFileRepo(fileRepo); LOGGER.debug( - "Init config took " + PerfScope.formatTime(System.nanoTime() - beforeInitConfig)); + "Init config took " + PerfScope.formatTime(System.nanoTime() - beforeInitConfig)); if (!problemInitializer.getWarnings().isEmpty() && !ignoreWarnings) { control.reportWarnings(problemInitializer.getWarnings()); } @@ -376,18 +391,18 @@ protected ProblemLoaderException recoverParserErrorMessage(Exception e) { final String readable = missedErrors.get(mte.expecting); final String token = readable == null ? "token id " + mte.expecting : readable; final String msg = "Syntax error: missing " + token - + (occurrence == null ? "" : " at " + occurrence.getText()) + " statement (" - + mte.input.getSourceName() + ":" + mte.line + ")"; + + (occurrence == null ? "" : " at " + occurrence.getText()) + " statement (" + + mte.input.getSourceName() + ":" + mte.line + ")"; return new ProblemLoaderException(this, msg, mte); // TODO other ANTLR exceptions } else { final org.antlr.runtime.MismatchedTokenException mte = - (MismatchedTokenException) c0; + (MismatchedTokenException) c0; final String genericMsg = "expected " + mte.expecting + ", but found " + mte.c; final String readable = - mismatchErrors.get(new Pair<>(mte.expecting, mte.c)); + mismatchErrors.get(new Pair<>(mte.expecting, mte.c)); final String msg = "Syntax error: " + (readable == null ? genericMsg : readable) - + " (" + mte.input.getSourceName() + ":" + mte.line + ")"; + + " (" + mte.input.getSourceName() + ":" + mte.line + ")"; return new ProblemLoaderException(this, msg, mte); } } @@ -436,7 +451,7 @@ protected EnvInput createEnvInput(FileRepo fileRepo) throws IOException { ret = new SLEnvInput(".", classPath, bootClassPath, profileOfNewProofs, includes); } else { ret = new SLEnvInput(file.getParentFile().getAbsolutePath(), classPath, - bootClassPath, profileOfNewProofs, includes); + bootClassPath, profileOfNewProofs, includes); } ret.setJavaFile(file.getAbsolutePath()); ret.setIgnoreOtherJavaFiles(loadSingleJavaFile); @@ -496,26 +511,26 @@ protected EnvInput createEnvInput(FileRepo fileRepo) throws IOException { Path unzippedProof = tmpDir.resolve(proofFilename.toPath()); return new KeYUserProblemFile(unzippedProof.toString(), unzippedProof.toFile(), - fileRepo, control, profileOfNewProofs, false); + fileRepo, control, profileOfNewProofs, false); } else if (filename.endsWith(".key") || filename.endsWith(".proof") || filename.endsWith(".proof.gz")) { // KeY problem specification or saved proof return new KeYUserProblemFile(filename, file, fileRepo, control, profileOfNewProofs, - filename.endsWith(".proof.gz")); + filename.endsWith(".proof.gz")); } else if (file.isDirectory()) { // directory containing java sources, probably enriched // by specifications return new SLEnvInput(file.getPath(), classPath, bootClassPath, profileOfNewProofs, - includes); + includes); } else { if (filename.lastIndexOf('.') != -1) { throw new IllegalArgumentException("Unsupported file extension '" - + filename.substring(filename.lastIndexOf('.')) + "' of read-in file " - + filename + ". Allowed extensions are: .key, .proof, .java or " - + "complete directories."); + + filename.substring(filename.lastIndexOf('.')) + "' of read-in file " + + filename + ". Allowed extensions are: .key, .proof, .java or " + + "complete directories."); } else { throw new FileNotFoundException( - "File or directory\n\t " + filename + "\n not found."); + "File or directory\n\t " + filename + "\n not found."); } } } @@ -637,7 +652,7 @@ private LoadedPOContainer loadByChosenContract(String chooseContract) { protected ProofAggregate createProof(LoadedPOContainer poContainer) throws ProofInputException { ProofAggregate proofList = - problemInitializer.startProver(initConfig, poContainer.getProofOblInput()); + problemInitializer.startProver(initConfig, poContainer.getProofOblInput()); for (Proof p : proofList.getProofs()) { // register proof @@ -661,26 +676,17 @@ public boolean hasProofScript() { return false; } - public Pair readProofScript() throws ProofInputException { + public @Nullable ProofScriptEntry readProofScript() throws ProofInputException { assert envInput instanceof KeYUserProblemFile; KeYUserProblemFile kupf = (KeYUserProblemFile) envInput; - - Triple script = kupf.readProofScript(); - URI url = kupf.getInitialFile().toURI(); - Location location = new Location(url, Position.newOneBased(script.second, script.third)); - - return new Pair<>(script.first, location); + return kupf.readProofScript(); } - public Pair getProofScript() throws ProblemLoaderException { - if (hasProofScript()) { - try { - return readProofScript(); - } catch (ProofInputException e) { - throw new ProblemLoaderException(this, e); - } - } else { - return null; + public @Nullable ProofScriptEntry getProofScript() throws ProblemLoaderException { + try { + return readProofScript(); + } catch (ProofInputException e) { + throw new ProblemLoaderException(this, e); } } @@ -701,7 +707,7 @@ private ReplayResult replayProof(Proof proof) { assert envInput instanceof KeYUserProblemFile; IntermediatePresentationProofFileParser parser = - new IntermediatePresentationProofFileParser(proof); + new IntermediatePresentationProofFileParser(proof); problemInitializer.tryReadProof(parser, (KeYUserProblemFile) envInput); parserResult = parser.getResult(); @@ -712,14 +718,14 @@ private ReplayResult replayProof(Proof proof) { // able to load proofs that used it even if the user has currently // turned OSS off. StrategyProperties newProps = - proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); newProps.setProperty(StrategyProperties.OSS_OPTIONS_KEY, StrategyProperties.OSS_ON); Strategy.updateStrategySettings(proof, newProps); OneStepSimplifier.refreshOSS(proof); replayer = new IntermediateProofReplayer(this, proof, parserResult); replayResult = - replayer.replay(problemInitializer.getListener(), problemInitializer.getProgMon()); + replayer.replay(problemInitializer.getListener(), problemInitializer.getProgMon()); lastTouchedNode = replayResult.getLastSelectedGoal() != null ? replayResult.getLastSelectedGoal().node() @@ -740,13 +746,13 @@ private ReplayResult replayProof(Proof proof) { } status += (status.isEmpty() ? "Proof replayed successfully." : "\n\n") + (replayResult != null ? replayResult.getStatus() - : "Error while loading proof."); + : "Error while loading proof."); if (replayResult != null) { errors.addAll(replayResult.getErrors()); } StrategyProperties newProps = - proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); newProps.setProperty(StrategyProperties.OSS_OPTIONS_KEY, ossStatus); Strategy.updateStrategySettings(proof, newProps); OneStepSimplifier.refreshOSS(proof); diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java index b40ef0409c1..3a3084f921a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java @@ -48,7 +48,6 @@ import de.uka.ilkd.key.speclang.Contract; import de.uka.ilkd.key.speclang.OperationContract; import de.uka.ilkd.key.util.ProgressMonitor; -import de.uka.ilkd.key.util.Triple; import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; import org.key_project.logic.Name; @@ -112,9 +111,10 @@ public class IntermediateProofReplayer { private final LinkedList> queue = new LinkedList<>(); + public record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third){} + /** Maps join node IDs to previously seen join partners */ - private final HashMap>> joinPartnerNodes = - new HashMap<>(); + private final HashMap> joinPartnerNodes = new HashMap<>(); /** The current open goal */ private Goal currGoal = null; @@ -264,8 +264,8 @@ public Result replay(ProblemInitializer.ProblemInitializerListener listener, (BuiltInAppIntermediate) currInterm.getIntermediateRuleApp(); if (appInterm instanceof MergeAppIntermediate joinAppInterm) { - HashSet> partnerNodesInfo = - joinPartnerNodes.get(((MergeAppIntermediate) appInterm).getId()); + HashSet partnerNodesInfo = + joinPartnerNodes.get(((MergeAppIntermediate) appInterm).getId()); if (partnerNodesInfo == null || partnerNodesInfo.size() < joinAppInterm.getNrPartners()) { @@ -309,7 +309,7 @@ public Result replay(ProblemInitializer.ProblemInitializerListener listener, } // Now add children of partner nodes - for (Triple partnerNodeInfo : partnerNodesInfo) { + for (PartnerNode partnerNodeInfo : partnerNodesInfo) { Iterator children = partnerNodeInfo.first.childrenIterator(); LinkedList intermChildren = @@ -327,11 +327,11 @@ public Result replay(ProblemInitializer.ProblemInitializerListener listener, } } else if (appInterm instanceof MergePartnerAppIntermediate joinPartnerApp) { // Register this partner node - HashSet> partnerNodeInfo = + HashSet partnerNodeInfo = joinPartnerNodes.computeIfAbsent(joinPartnerApp.getMergeNodeId(), k -> new HashSet<>()); - partnerNodeInfo.add(new Triple<>( + partnerNodeInfo.add(new PartnerNode( currNode, PosInOccurrence.findInSequent(currGoal.sequent(), appInterm.getPosInfo().first, appInterm.getPosInfo().second), @@ -713,7 +713,7 @@ private IBuiltInRuleApp constructBuiltinApp(BuiltInAppIntermediate currInterm, G */ private MergeRuleBuiltInRuleApp instantiateJoinApp(final MergeAppIntermediate joinAppInterm, final Node currNode, - final Set> partnerNodesInfo, + final HashSet partnerNodesInfo, final Services services) throws SkipSMTRuleException, BuiltInConstructionException { final MergeRuleBuiltInRuleApp joinApp = (MergeRuleBuiltInRuleApp) constructBuiltinApp(joinAppInterm, currGoal); @@ -802,14 +802,14 @@ private MergeRuleBuiltInRuleApp instantiateJoinApp(final MergeAppIntermediate jo } ImmutableList joinPartners = ImmutableSLList.nil(); - for (Triple partnerNodeInfo : partnerNodesInfo) { + for (PartnerNode partnerNodeInfo : partnerNodesInfo) { - final Triple ownSEState = + var ownSEState = sequentToSETriple(currNode, joinApp.posInOccurrence(), services); - final Triple partnerSEState = + var partnerSEState = sequentToSETriple(partnerNodeInfo.first, partnerNodeInfo.second, services); - assert ownSEState.third.equals(partnerSEState.third) + assert ownSEState.third().equals(partnerSEState.third()) : "Cannot merge incompatible program counters"; joinPartners = joinPartners.append( diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java index ac8404f0b4e..41c90dcf3fc 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java @@ -3,11 +3,6 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.proof.mgt; -import java.net.URI; -import java.util.*; -import java.util.Map.Entry; -import java.util.function.UnaryOperator; - import de.uka.ilkd.key.java.JavaInfo; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.Statement; @@ -34,20 +29,18 @@ import de.uka.ilkd.key.speclang.jml.translation.ProgramVariableCollection; import de.uka.ilkd.key.speclang.translation.SLTranslationException; import de.uka.ilkd.key.util.MiscTools; -import de.uka.ilkd.key.util.Triple; - +import org.jspecify.annotations.Nullable; import org.key_project.logic.Name; import org.key_project.logic.sort.Sort; -import org.key_project.util.collection.DefaultImmutableSet; -import org.key_project.util.collection.ImmutableList; -import org.key_project.util.collection.ImmutableSLList; -import org.key_project.util.collection.ImmutableSet; -import org.key_project.util.collection.Pair; - -import org.jspecify.annotations.Nullable; +import org.key_project.util.collection.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.net.URI; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.UnaryOperator; + /** * Central storage for all specification elements, such as contracts, class axioms, and loop * invariants. Provides methods for adding such elements to the repository, and for retrieving them @@ -68,38 +61,29 @@ public final class SpecificationRepository { private final ContractFactory cf; private final Map, ImmutableSet> contracts = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map, ImmutableSet> operationContracts = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map, ImmutableSet> wdChecks = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map contractsByName = new LinkedHashMap<>(); - private final Map> contractTargets = - new LinkedHashMap<>(); + private final Map> contractTargets = new LinkedHashMap<>(); private final Map> invs = new LinkedHashMap<>(); private final Map> axioms = new LinkedHashMap<>(); - private final Map> initiallyClauses = - new LinkedHashMap<>(); + private final Map> initiallyClauses = new LinkedHashMap<>(); private final Map> proofs = new LinkedHashMap<>(); - private final Map, LoopSpecification> loopInvs = - new LinkedHashMap<>(); - private final Map, ImmutableSet> blockContracts = - new LinkedHashMap<>(); - private final Map, ImmutableSet> loopContracts = - new LinkedHashMap<>(); + private final Map, LoopSpecification> loopInvs = new LinkedHashMap<>(); + private final Map> blockContracts = new LinkedHashMap<>(); + private final Map> loopContracts = new LinkedHashMap<>(); + /** * A map which relates each loop statement its starting line number and set of loop contracts. */ - private final Map, ImmutableSet> loopContractsOnLoops = - new LinkedHashMap<>(); - private final Map> mergeContracts = - new LinkedHashMap<>(); - private final Map unlimitedToLimited = - new LinkedHashMap<>(); - private final Map limitedToUnlimited = - new LinkedHashMap<>(); - private final Map> unlimitedToLimitTaclets = - new LinkedHashMap<>(); + private final Map, ImmutableSet> loopContractsOnLoops = new LinkedHashMap<>(); + private final Map> mergeContracts = new LinkedHashMap<>(); + private final Map unlimitedToLimited = new LinkedHashMap<>(); + private final Map limitedToUnlimited = new LinkedHashMap<>(); + private final Map> unlimitedToLimitTaclets = new LinkedHashMap<>(); /** *

@@ -114,13 +98,13 @@ public final class SpecificationRepository { *

*/ private final Map> allClassAxiomsCache = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Services services; private final TermBuilder tb; private final Map contractCounters = - new de.uka.ilkd.key.util.LinkedHashMap<>(); + new de.uka.ilkd.key.util.LinkedHashMap<>(); public SpecificationRepository(Services services) { this.services = services; @@ -147,7 +131,7 @@ private static String getUniqueNameForObserver(IObserverFunction obs) { } private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, - IObserverFunction unlimited, TermServices services) { + IObserverFunction unlimited, TermServices services) { final TermBuilder tb = services.getTermBuilder(); assert limited.arity() == unlimited.arity(); @@ -155,7 +139,7 @@ private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, final Term[] subs = new Term[limited.arity()]; for (int i = 0; i < subs.length; i++) { final TermSV argSV = SchemaVariableFactory.createTermSV(new Name("t" + i), - limited.argSort(i), false, false); + limited.argSort(i), false, false); subs[i] = tb.var(argSV); } final Term limitedTerm = tb.func(limited, subs); @@ -165,14 +149,14 @@ private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, final RewriteTacletBuilder tacletBuilder = new RewriteTacletBuilder<>(); tacletBuilder.setFind(limitedTerm); tacletBuilder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(Sequent.EMPTY_SEQUENT, - ImmutableSLList.nil(), unlimitedTerm)); + ImmutableSLList.nil(), unlimitedTerm)); tacletBuilder.setName( - MiscTools.toValidTacletName("unlimit " + getUniqueNameForObserver(unlimited))); + MiscTools.toValidTacletName("unlimit " + getUniqueNameForObserver(unlimited))); return tacletBuilder.getTaclet(); } private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, - IObserverFunction unlimited, TermServices services) { + IObserverFunction unlimited, TermServices services) { assert limited.arity() == unlimited.arity(); final TermBuilder tb = services.getTermBuilder(); @@ -180,7 +164,7 @@ private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, final Term[] subs = new Term[limited.arity()]; for (int i = 0; i < subs.length; i++) { final TermSV argSV = SchemaVariableFactory.createTermSV(new Name("t" + i), - limited.argSort(i), false, false); + limited.argSort(i), false, false); subs[i] = tb.var(argSV); } final Term limitedTerm = tb.func(limited, subs); @@ -191,12 +175,12 @@ private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, tacletBuilder.setFind(tb.func(unlimited, subs)); final SequentFormula cf = new SequentFormula(tb.equals(limitedTerm, unlimitedTerm)); final Sequent addedSeq = - Sequent.createAnteSequent(Semisequent.EMPTY_SEMISEQUENT.insertFirst(cf).semisequent()); + Sequent.createAnteSequent(Semisequent.EMPTY_SEMISEQUENT.insertFirst(cf).semisequent()); tacletBuilder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(addedSeq, - ImmutableSLList.nil(), tb.func(unlimited, subs))); + ImmutableSLList.nil(), tb.func(unlimited, subs))); tacletBuilder.setApplicationRestriction(RewriteTaclet.IN_SEQUENT_STATE); tacletBuilder.setName( - MiscTools.toValidTacletName("limit " + getUniqueNameForObserver(unlimited))); + MiscTools.toValidTacletName("limit " + getUniqueNameForObserver(unlimited))); tacletBuilder.addRuleSet(new RuleSet(new Name("limitObserver"))); return tacletBuilder.getTaclet(); @@ -227,8 +211,9 @@ private IObserverFunction getCanonicalFormForKJT(IObserverFunction obs, KeYJavaT final String name = pm.getMethodDeclaration().getName(); final int numParams = pm.getParameterDeclarationCount(); final ImmutableList candidatePMs = - services.getJavaInfo().getAllProgramMethods(kjt); - outer: for (IProgramMethod candidatePM : candidatePMs) { + services.getJavaInfo().getAllProgramMethods(kjt); + outer: + for (IProgramMethod candidatePM : candidatePMs) { if (candidatePM.getMethodDeclaration().getName().equals(name) && candidatePM.getParameterDeclarationCount() == numParams) { for (int i = 0; i < numParams; i++) { @@ -255,7 +240,7 @@ private IObserverFunction getCanonicalFormForKJT(IObserverFunction obs, KeYJavaT } private ImmutableSet> getOverridingMethods(KeYJavaType kjt, - IProgramMethod pm) { + IProgramMethod pm) { ImmutableList> result = ImmutableSLList.nil(); // static methods and constructors are not overriden @@ -275,7 +260,7 @@ private ImmutableSet> getOverridingMethods( } public ImmutableSet> getOverridingTargets(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { if (target instanceof IProgramMethod) { return getOverridingMethods(kjt, (IProgramMethod) target); } else { @@ -366,19 +351,19 @@ assert getCanonicalFormForKJT(contract.getTarget(), contract.getKJT()) private void registerContract(Contract contract) { final Pair target = - new Pair<>(contract.getKJT(), contract.getTarget()); + new Pair<>(contract.getKJT(), contract.getTarget()); registerContract(contract, target); } private void registerContract(Contract contract, - final ImmutableSet> targets) { + final ImmutableSet> targets) { for (Pair impl : targets) { registerContract(contract, impl); } } private void registerContract(Contract contract, - Pair targetPair) { + Pair targetPair) { LOGGER.trace("Contract registered {}", contract); if (!WellDefinednessCheck.isOn() && contract instanceof WellDefinednessCheck) { return; @@ -391,30 +376,30 @@ private void registerContract(Contract contract, : "Tried to add a contract with a non-unique name: " + name; assert !name.contains(CONTRACT_COMBINATION_MARKER) : "Tried to add a contract with a name containing the" + " reserved character " - + CONTRACT_COMBINATION_MARKER + ": " + name; + + CONTRACT_COMBINATION_MARKER + ": " + name; assert contract.id() != Contract.INVALID_ID : "Tried to add a contract with an invalid id!"; contracts.put(targetPair, getContracts(targetKJT, targetMethod).add(contract)); if (contract instanceof FunctionalOperationContract) { operationContracts.put(new Pair<>(targetKJT, (IProgramMethod) targetMethod), - getOperationContracts(targetKJT, (IProgramMethod) targetMethod) - .add((FunctionalOperationContract) contract)); + getOperationContracts(targetKJT, (IProgramMethod) targetMethod) + .add((FunctionalOperationContract) contract)); // Create new well-definedness check final MethodWellDefinedness mwd = - new MethodWellDefinedness((FunctionalOperationContract) contract, services); + new MethodWellDefinedness((FunctionalOperationContract) contract, services); registerContract(mwd); } else if (contract instanceof DependencyContract && contract.getOrigVars().atPres.isEmpty() && targetMethod.getContainerType() - .equals(services.getJavaInfo().getJavaLangObject())) { + .equals(services.getJavaInfo().getJavaLangObject())) { // Create or extend a well-definedness check for a class invariant final Term deps = - contract.getAccessible(services.getTypeConverter().getHeapLDT().getHeap()); + contract.getAccessible(services.getTypeConverter().getHeapLDT().getHeap()); final Term mby = contract.getMby(); final String invName = "JML model class invariant in " + targetKJT.getName(); final ClassInvariant inv = new ClassInvariantImpl(invName, invName, targetKJT, - contract.getVisibility(), tb.tt(), contract.getOrigVars().self); + contract.getVisibility(), tb.tt(), contract.getOrigVars().self); ClassWellDefinedness cwd = - new ClassWellDefinedness(inv, targetMethod, deps, mby, services); + new ClassWellDefinedness(inv, targetMethod, deps, mby, services); final ImmutableSet cwds = getWdClassChecks(targetKJT); if (!cwds.isEmpty()) { assert cwds.size() == 1; @@ -428,9 +413,9 @@ private void registerContract(Contract contract, && contract.getOrigVars().atPres.isEmpty()) { // Create or extend a well-definedness check for a model field MethodWellDefinedness mwd = - new MethodWellDefinedness((DependencyContract) contract, services); + new MethodWellDefinedness((DependencyContract) contract, services); final ImmutableSet mwds = - getWdMethodChecks(targetKJT, targetMethod); + getWdMethodChecks(targetKJT, targetMethod); if (!mwds.isEmpty()) { assert mwds.size() == 1; final MethodWellDefinedness oldMwd = mwds.iterator().next(); @@ -456,12 +441,12 @@ private void unregisterContract(Contract contract) { contracts.put(tp, contracts.get(tp).remove(contract)); if (contract instanceof FunctionalOperationContract) { final Pair tp2 = - new Pair<>(tp.first, (IProgramMethod) tp.second); + new Pair<>(tp.first, (IProgramMethod) tp.second); operationContracts.put(tp2, - operationContracts.get(tp2).remove((FunctionalOperationContract) contract)); + operationContracts.get(tp2).remove((FunctionalOperationContract) contract)); if (!getWdChecks(contract.getKJT(), contract.getTarget()).isEmpty()) { ImmutableSet wdcs = - getWdChecks(contract.getKJT(), contract.getTarget()); + getWdChecks(contract.getKJT(), contract.getTarget()); for (WellDefinednessCheck wdc : wdcs) { if (wdc instanceof MethodWellDefinedness && ((MethodWellDefinedness) wdc).getMethodContract().equals(contract)) { @@ -493,7 +478,7 @@ private void createContractsFromInitiallyClause(InitiallyClause inv, KeYJavaType if (!JMLInfoExtractor.isHelper(pm)) { final ImmutableSet oldContracts = getContracts(kjt, pm); ImmutableSet oldFuncContracts = - DefaultImmutableSet.nil(); + DefaultImmutableSet.nil(); for (Contract old : oldContracts) { if (old instanceof FunctionalOperationContract) { oldFuncContracts = oldFuncContracts.add((FunctionalOperationContract) old); @@ -545,7 +530,7 @@ private static ImmutableSet removeWdChecks(ImmutableSet cont */ private void registerWdCheck(WellDefinednessCheck check) { ImmutableSet checks = - getWdChecks(check.getKJT(), check.getTarget()).add(check); + getWdChecks(check.getKJT(), check.getTarget()).add(check); wdChecks.put(new Pair<>(check.getKJT(), check.getTarget()), checks); } @@ -557,7 +542,7 @@ private void registerWdCheck(WellDefinednessCheck check) { */ private void unregisterWdCheck(WellDefinednessCheck check) { wdChecks.put(new Pair<>(check.getKJT(), check.getTarget()), - getWdChecks(check.getKJT(), check.getTarget()).remove(check)); + getWdChecks(check.getKJT(), check.getTarget()).remove(check)); } /** @@ -578,7 +563,7 @@ private ImmutableSet getWdChecks(KeYJavaType kjt) { * Returns all registered (atomic) well-definedness checks for the passed target and kjt. */ private ImmutableSet getWdChecks(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { assert kjt != null; assert target != null; target = getCanonicalFormForKJT(target, kjt); @@ -618,7 +603,7 @@ private ImmutableSet getWdMethodChecks(KeYJavaType kjt) { * Returns all registered (atomic) well-definedness method checks for the passed target and kjt. */ private ImmutableSet getWdMethodChecks(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { assert kjt != null; assert target != null; ImmutableSet result = DefaultImmutableSet.nil(); @@ -653,7 +638,7 @@ private ImmutableSet getWdClassChecks(KeYJavaType kjt) { */ @SuppressWarnings("unchecked") private void mapValueSets(Map> map, - UnaryOperator op, Services services) { + UnaryOperator op, Services services) { for (Entry> entry : map.entrySet()) { final K key = entry.getKey(); final ImmutableSet oldSet = entry.getValue(); @@ -684,7 +669,7 @@ private void mapValueSets(Map void mapValues(Map map, - UnaryOperator op, Services services) { + UnaryOperator op, Services services) { for (Entry entry : map.entrySet()) { final K key = entry.getKey(); final V oldContract = entry.getValue(); @@ -740,10 +725,10 @@ public ImmutableSet getAllContracts() { */ public ImmutableSet getContracts(KeYJavaType kjt, IObserverFunction target) { target = - getCanonicalFormForKJT(Objects.requireNonNull(target), Objects.requireNonNull(kjt)); + getCanonicalFormForKJT(Objects.requireNonNull(target), Objects.requireNonNull(kjt)); final Pair pair = new Pair<>(kjt, target); final ImmutableSet result = - WellDefinednessCheck.isOn() ? contracts.get(pair) : removeWdChecks(contracts.get(pair)); + WellDefinednessCheck.isOn() ? contracts.get(pair) : removeWdChecks(contracts.get(pair)); return result == null ? DefaultImmutableSet.nil() : result; } @@ -751,7 +736,7 @@ public ImmutableSet getContracts(KeYJavaType kjt, IObserverFunction ta * Returns all registered (atomic) operation contracts for the passed operation. */ public ImmutableSet getOperationContracts(KeYJavaType kjt, - IProgramMethod pm) { + IProgramMethod pm) { pm = (IProgramMethod) getCanonicalFormForKJT(pm, kjt); final Pair pair = new Pair<>(kjt, pm); final ImmutableSet result = operationContracts.get(pair); @@ -763,14 +748,14 @@ public ImmutableSet getOperationContracts(KeYJavaTy * the passed modality. */ public ImmutableSet getOperationContracts(KeYJavaType kjt, - IProgramMethod pm, Modality.JavaModalityKind modalityKind) { + IProgramMethod pm, Modality.JavaModalityKind modalityKind) { ImmutableSet result = getOperationContracts(kjt, pm); final boolean transactionModality = - modalityKind.transaction(); + modalityKind.transaction(); final Modality.JavaModalityKind matchModality = transactionModality ? ((modalityKind == Modality.JavaModalityKind.DIA_TRANSACTION) - ? Modality.JavaModalityKind.DIA - : Modality.JavaModalityKind.BOX) + ? Modality.JavaModalityKind.DIA + : Modality.JavaModalityKind.BOX) : modalityKind; for (FunctionalOperationContract contract : result) { if (!contract.getModalityKind().equals(matchModality) @@ -797,7 +782,7 @@ public Contract getContractByName(String name) { ImmutableSet baseContracts = DefaultImmutableSet.nil(); for (String baseName : baseNames) { FunctionalOperationContract baseContract = - (FunctionalOperationContract) contractsByName.get(baseName); + (FunctionalOperationContract) contractsByName.get(baseName); if (baseContract == null) { return null; } @@ -814,7 +799,7 @@ public Contract getContractByName(String name) { public ImmutableSet getInheritedContracts(Contract contract) { ImmutableSet result = DefaultImmutableSet.nil().add(contract); final ImmutableSet> subs = - getOverridingTargets(contract.getKJT(), contract.getTarget()); + getOverridingTargets(contract.getKJT(), contract.getTarget()); for (Pair sub : subs) { for (Contract subContract : getContracts(sub.first, sub.second)) { if (subContract.id() == contract.id()) { @@ -854,13 +839,13 @@ public void addContract(Contract contract) { // register and inherit final ImmutableSet> impls = - getOverridingTargets(contract.getKJT(), contract.getTarget()) - .add(new Pair<>(contract.getKJT(), contract.getTarget())); + getOverridingTargets(contract.getKJT(), contract.getTarget()) + .add(new Pair<>(contract.getKJT(), contract.getTarget())); registerContract(contract, impls); if (!contractTargets.get(contract.getKJT()).contains(contract.getTarget())) { throw new IllegalStateException( - "target " + contract.getTarget() + " missing for contract " + contract); + "target " + contract.getTarget() + " missing for contract " + contract); } } @@ -893,7 +878,7 @@ public FunctionalOperationContract combineOperationContracts( // sort contracts alphabetically (for determinism) FunctionalOperationContract[] contractsArray = - toCombine.toArray(new FunctionalOperationContract[toCombine.size()]); + toCombine.toArray(new FunctionalOperationContract[toCombine.size()]); Arrays.sort(contractsArray, Comparator.comparing(SpecificationElement::getName)); return cf.union(contractsArray); @@ -940,7 +925,7 @@ public void addClassInvariant(ClassInvariant inv) { ClassWellDefinedness cwd = cwds.iterator().next(); unregisterContract(cwd); cwd = cwd.combine(new ClassWellDefinedness(inv, cwd.getTarget(), null, null, services), - services); + services); registerContract(cwd); } @@ -956,13 +941,13 @@ public void addClassInvariant(ClassInvariant inv) { for (KeYJavaType sub : subs) { ClassInvariant subInv = inv.setKJT(sub); final IObserverFunction subTarget = - subInv.isStatic() ? services.getJavaInfo().getStaticInv(sub) - : services.getJavaInfo().getInv(); + subInv.isStatic() ? services.getJavaInfo().getStaticInv(sub) + : services.getJavaInfo().getInv(); invs.put(sub, getClassInvariants(sub).add(subInv)); final ImmutableSet subCwds = getWdClassChecks(sub); if (subCwds.isEmpty()) { registerContract( - new ClassWellDefinedness(subInv, subTarget, null, null, services)); + new ClassWellDefinedness(subInv, subTarget, null, null, services)); } else { for (ClassWellDefinedness cwd : subCwds) { unregisterContract(cwd); @@ -995,7 +980,7 @@ public void createContractsFromInitiallyClauses() throws SLTranslationException createContractsFromInitiallyClause(inv, kjt); if (VisibilityModifier.allowsInheritance(inv.getVisibility())) { final ImmutableList subs = - services.getJavaInfo().getAllSubtypes(kjt); + services.getJavaInfo().getAllSubtypes(kjt); for (KeYJavaType sub : subs) { createContractsFromInitiallyClause(inv, sub); } @@ -1077,7 +1062,7 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { staticInvDef = tb.and(staticInvDef, inv.getInv(null, services)); } else { freeStaticInvDef = - tb.and(freeStaticInvDef, inv.getInv(selfVar, services)); + tb.and(freeStaticInvDef, inv.getInv(selfVar, services)); } } } @@ -1085,9 +1070,9 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { invDef = tb.tf().createTerm(Equality.EQV, tb.inv(tb.var(selfVar)), invDef); staticInvDef = tb.tf().createTerm(Equality.EQV, tb.staticInv(kjt), staticInvDef); freeInvDef = tb.tf().createTerm(Equality.EQV, - tb.invFree(tb.var(selfVar)), freeInvDef); + tb.invFree(tb.var(selfVar)), freeInvDef); freeStaticInvDef = tb.tf().createTerm(Equality.EQV, - tb.staticInvFree(kjt), freeStaticInvDef); + tb.staticInvFree(kjt), freeStaticInvDef); final IObserverFunction invSymbol = services.getJavaInfo().getInv(); final IObserverFunction staticInvSymbol = services.getJavaInfo().getStaticInv(kjt); @@ -1096,24 +1081,24 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { .getStaticInvFree(kjt); final ClassAxiom invRepresentsAxiom = - new RepresentsAxiom("Class invariant axiom for " + kjt.getFullName(), invSymbol, - kjt, new Private(), null, invDef, selfVar, ImmutableSLList.nil(), null); + new RepresentsAxiom("Class invariant axiom for " + kjt.getFullName(), invSymbol, + kjt, new Private(), null, invDef, selfVar, ImmutableSLList.nil(), null); result = result.add(invRepresentsAxiom); final ClassAxiom staticInvRepresentsAxiom = new RepresentsAxiom( - "Static class invariant axiom for " + kjt.getFullName(), staticInvSymbol, kjt, - new Private(), null, staticInvDef, null, ImmutableSLList.nil(), null); + "Static class invariant axiom for " + kjt.getFullName(), staticInvSymbol, kjt, + new Private(), null, staticInvDef, null, ImmutableSLList.nil(), null); result = result.add(staticInvRepresentsAxiom); final ClassAxiom invFreeRepresentsAxiom = new RepresentsAxiom( - "Free class invariant axiom for " + kjt.getFullName(), freeInvSymbol, kjt, - new Private(), null, freeInvDef, selfVar, ImmutableSLList.nil(), null); + "Free class invariant axiom for " + kjt.getFullName(), freeInvSymbol, kjt, + new Private(), null, freeInvDef, selfVar, ImmutableSLList.nil(), null); result = result.add(invFreeRepresentsAxiom); final ClassAxiom staticFreeInvRepresentsAxiom = new RepresentsAxiom( - "Free static class invariant axiom for " + kjt.getFullName(), - freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, - ImmutableSLList.nil(), null); + "Free static class invariant axiom for " + kjt.getFullName(), + freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, + ImmutableSLList.nil(), null); result = result.add(staticFreeInvRepresentsAxiom); } @@ -1129,7 +1114,7 @@ freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, } final ClassAxiom queryAxiom = new QueryAxiom("Query axiom for " + pm.getName() - + "_" + sb + " in " + selfKjt.getFullName(), pm, selfKjt); + + "_" + sb + " in " + selfKjt.getFullName(), pm, selfKjt); result = result.add(queryAxiom); } } @@ -1158,7 +1143,7 @@ private ImmutableSet getModelMethodAxioms() { List heaps = HeapContext.getModifiableHeaps(services, false); for (LocationVariable heap : heaps) { atPreVars.put(heap, - tb.atPreVar(heap.name().toString(), heap.sort(), false)); + tb.atPreVar(heap.name().toString(), heap.sort(), false)); } LocationVariable resultVar = tb.resultVar(pm, false); @@ -1167,10 +1152,10 @@ private ImmutableSet getModelMethodAxioms() { // We need to construct an inheritance chain of contracts // starting at the bottom ImmutableList lookupContracts = - ImmutableSLList.nil(); + ImmutableSLList.nil(); ImmutableSet cs = getOperationContracts(kjt, pm); ImmutableList superTypes = - services.getJavaInfo().getAllSupertypes(kjt); + services.getJavaInfo().getAllSupertypes(kjt); for (KeYJavaType superType : superTypes) { for (FunctionalOperationContract fop : cs) { if (fop.getSpecifiedIn().equals(superType)) { @@ -1180,9 +1165,9 @@ private ImmutableSet getModelMethodAxioms() { } for (FunctionalOperationContract fop : lookupContracts) { Term representsFromContract = fop.getRepresentsAxiom(heaps.get(0), selfVar, - paramVars, tb.resultVar(pm, false), atPreVars, services); + paramVars, tb.resultVar(pm, false), atPreVars, services); Term preContract = - fop.getPre(heaps, selfVar, paramVars, atPreVars, services); + fop.getPre(heaps, selfVar, paramVars, atPreVars, services); if (preContract == null) { preContract = tb.tt(); } @@ -1194,11 +1179,11 @@ private ImmutableSet getModelMethodAxioms() { // (pm.isProtected() ? new Protected() : // (pm.isPublic() ? new Public() : null)); final ClassAxiom modelMethodRepresentsAxiom = - new RepresentsAxiom( - "Definition axiom for " + pm.getName() + " in " - + kjt.getFullName(), - pm, kjt, new Private(), preContract, representsFromContract, - selfVar, paramVars, atPreVars); + new RepresentsAxiom( + "Definition axiom for " + pm.getName() + " in " + + kjt.getFullName(), + pm, kjt, new Private(), preContract, representsFromContract, + selfVar, paramVars, atPreVars); result = result.add(modelMethodRepresentsAxiom); break; } @@ -1208,24 +1193,24 @@ pm, kjt, new Private(), preContract, representsFromContract, continue; } Term preFromContract = - fop.getPre(heaps, selfVar, paramVars, atPreVars, services); + fop.getPre(heaps, selfVar, paramVars, atPreVars, services); Term freePreFromContract = - fop.getFreePre(heaps, selfVar, paramVars, atPreVars, services); + fop.getFreePre(heaps, selfVar, paramVars, atPreVars, services); Term postFromContract = fop.getPost(heaps, selfVar, paramVars, resultVar, - null, atPreVars, services); + null, atPreVars, services); Term freePostFromContract = fop.getFreePost(heaps, selfVar, paramVars, - resultVar, null, atPreVars, services); + resultVar, null, atPreVars, services); if (preFromContract != null && ((postFromContract != null && postFromContract != tb.tt()) - || (freePostFromContract != null - && freePostFromContract != tb.tt()))) { + || (freePostFromContract != null + && freePostFromContract != tb.tt()))) { Term mbyFromContract = - fop.hasMby() ? fop.getMby(selfVar, paramVars, services) : null; + fop.hasMby() ? fop.getMby(selfVar, paramVars, services) : null; final ClassAxiom modelMethodContractAxiom = new ContractAxiom( - "Contract axiom for " + pm.getName() + " in " + kjt.getName(), pm, - kjt, new Private(), preFromContract, freePreFromContract, - postFromContract, freePostFromContract, mbyFromContract, atPreVars, - selfVar, resultVar, paramVars); + "Contract axiom for " + pm.getName() + " in " + kjt.getName(), pm, + kjt, new Private(), preFromContract, freePreFromContract, + postFromContract, freePostFromContract, mbyFromContract, atPreVars, + selfVar, resultVar, paramVars); result = result.add(modelMethodContractAxiom); } } @@ -1326,7 +1311,7 @@ public ImmutableSet getProofs(Contract atomicContract) { */ public ImmutableSet getProofs(KeYJavaType kjt, IObserverFunction target) { final ImmutableSet> targets = - getOverridingTargets(kjt, target).add(new Pair<>(kjt, target)); + getOverridingTargets(kjt, target).add(new Pair<>(kjt, target)); ImmutableSet result = DefaultImmutableSet.nil(); for (Map.Entry> entry : proofs.entrySet()) { final ProofOblInput po = entry.getKey(); @@ -1334,7 +1319,7 @@ public ImmutableSet getProofs(KeYJavaType kjt, IObserverFunction target) if (po instanceof ContractPO) { final Contract contract = ((ContractPO) po).getContract(); final Pair pair = - new Pair<>(contract.getKJT(), contract.getTarget()); + new Pair<>(contract.getKJT(), contract.getTarget()); if (targets.contains(pair)) { result = result.union(sop); } @@ -1493,8 +1478,7 @@ public void addLoopInvariant(final LoopSpecification inv) { * @return all block contracts for the specified block. */ public ImmutableSet getBlockContracts(StatementBlock block) { - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b = new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); final ImmutableSet contracts = blockContracts.get(b); if (contracts == null) { return DefaultImmutableSet.nil(); @@ -1510,8 +1494,7 @@ public ImmutableSet getBlockContracts(StatementBlock block) { * @return all loop contracts for the specified block. */ public ImmutableSet getLoopContracts(StatementBlock block) { - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b = new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); final ImmutableSet contracts = loopContracts.get(b); if (contracts == null) { return DefaultImmutableSet.nil(); @@ -1552,7 +1535,7 @@ public ImmutableSet getMergeContracts(MergePointStatement mps) { * @param modalityKind the given modality. */ public ImmutableSet getBlockContracts(final StatementBlock block, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getBlockContracts(block); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (BlockContract contract : result) { @@ -1565,7 +1548,7 @@ public ImmutableSet getBlockContracts(final StatementBlock block, } public ImmutableSet getLoopContracts(final StatementBlock block, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getLoopContracts(block); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (LoopContract contract : result) { @@ -1585,7 +1568,7 @@ public ImmutableSet getLoopContracts(final StatementBlock block, * @return the set of resulting loop statements. */ public ImmutableSet getLoopContracts(final LoopStatement loop, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getLoopContracts(loop); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (LoopContract contract : result) { @@ -1615,8 +1598,7 @@ public void addBlockContract(final BlockContract contract) { */ public void addBlockContract(final BlockContract contract, boolean addFunctionalContract) { final StatementBlock block = contract.getBlock(); - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b =new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); blockContracts.put(b, getBlockContracts(block).add(contract)); if (addFunctionalContract) { @@ -1637,11 +1619,9 @@ public void addBlockContract(final BlockContract contract, boolean addFunctional */ public void removeBlockContract(final BlockContract contract) { final StatementBlock block = contract.getBlock(); - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b = new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); - ImmutableSet set = blockContracts.get(b); - blockContracts.put(b, set.remove(contract)); + blockContracts.compute(b, (k, set) -> set.remove(contract)); } /** @@ -1663,13 +1643,12 @@ public void addLoopContract(final LoopContract contract) { public void addLoopContract(final LoopContract contract, boolean addFunctionalContract) { if (contract.isOnBlock()) { final StatementBlock block = contract.getBlock(); - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b = new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); loopContracts.put(b, getLoopContracts(block).add(contract)); } else { final LoopStatement loop = contract.getLoop(); final Pair b = - new Pair<>(loop, loop.getStartPosition().line()); + new Pair<>(loop, loop.getStartPosition().line()); loopContractsOnLoops.put(b, getLoopContracts(loop).add(contract)); } @@ -1696,18 +1675,15 @@ public void addLoopContract(final LoopContract contract, boolean addFunctionalCo public void removeLoopContract(final LoopContract contract) { if (contract.isOnBlock()) { final StatementBlock block = contract.getBlock(); - final Triple b = - new Triple<>(block, block.getParentClass(), block.getStartPosition().line()); + var b =new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); - ImmutableSet set = loopContracts.get(b); - loopContracts.put(b, set.remove(contract)); + loopContracts.compute(b, (k, set) -> set.remove(contract)); } else { final LoopStatement loop = contract.getLoop(); final Pair b = - new Pair<>(loop, loop.getStartPosition().line()); + new Pair<>(loop, loop.getStartPosition().line()); - ImmutableSet set = loopContractsOnLoops.get(b); - loopContractsOnLoops.put(b, set.remove(contract)); + loopContractsOnLoops.compute(b, (k, set) -> set.remove(contract)); } } @@ -1771,11 +1747,11 @@ public Pair> limitObs(IObserverFunction if (limited == null) { final String baseName = - ((ProgramElementName) obs.name()).getProgramName() + LIMIT_SUFFIX; + ((ProgramElementName) obs.name()).getProgramName() + LIMIT_SUFFIX; final Sort heapSort = services.getTypeConverter().getHeapLDT().targetSort(); limited = new ObserverFunction(baseName, obs.sort(), obs.getType(), heapSort, - obs.getContainerType(), obs.isStatic(), obs.getParamTypes(), - obs.getHeapCount(services), obs.getStateCount()); + obs.getContainerType(), obs.isStatic(), obs.getParamTypes(), + obs.getHeapCount(services), obs.getStateCount()); unlimitedToLimited.put(obs, limited); limitedToUnlimited.put(limited, obs); @@ -1889,7 +1865,7 @@ public JmlStatementSpec addStatementSpec(Statement statement, JmlStatementSpec s public record JmlStatementSpec( ProgramVariableCollection vars, ImmutableList terms - ){ + ) { /** * Retrieve a term * @param index a index to the list of {@code terms}. @@ -1943,5 +1919,11 @@ public JmlStatementSpec updateVariables(Map atPres, Serv newTerms); } } + + private record BlockContractKey(StatementBlock block, URI file, Integer pos) { + } + + private record LoopContractKey(StatementBlock block, URI file, Integer pos) { + } // endregion } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java index 4ed438b1b8a..680730a0880 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java @@ -52,7 +52,6 @@ import de.uka.ilkd.key.speclang.LoopWellDefinedness; import de.uka.ilkd.key.speclang.WellDefinednessCheck; import de.uka.ilkd.key.util.MiscTools; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableArray; @@ -163,10 +162,9 @@ private static InfFlowData prepareSetUpOfInfFlowValidityGoal(final Goal infFlowG final Taclet informationFlowInvariantApp = ifInvariantBuilder.buildTaclet(infFlowGoal); // return information flow data - InfFlowData infFlowData = new InfFlowData(instantiationVars, guardAtPre, guardAtPost, + return new InfFlowData(instantiationVars, guardAtPre, guardAtPost, guardJb, guardTerm, localOutTerms, localOutsAtPre, localOutsAtPost, updates, loopInvApplPredTerm, informationFlowInvariantApp); - return infFlowData; } @@ -221,9 +219,7 @@ private static Instantiation instantiate(final LoopInvariantBuiltInRuleApp app, services.getSpecificationRepository().addLoopInvariant(spec); // cache and return result - final Instantiation result = - new Instantiation(u, progPost, loop, spec, selfTerm, innermostExecutionContext); - return result; + return new Instantiation(u, progPost, loop, spec, selfTerm, innermostExecutionContext); } private static Term createLocalAnonUpdate(ImmutableSet localOuts, @@ -294,8 +290,7 @@ private static Term buildAtPostVar(Term varTerm, String suffix, Services service final LocationVariable varAtPostVar = new LocationVariable(new ProgramElementName(name), resultType); register(varAtPostVar, services); - final Term varAtPost = tb.var(varAtPostVar); - return varAtPost; + return tb.var(varAtPostVar); } private static Term buildBeforeVar(Term varTerm, Services services) { @@ -310,8 +305,7 @@ private static Term buildBeforeVar(Term varTerm, Services services) { final LocationVariable varAtPreVar = new LocationVariable(new ProgramElementName(name), resultType); register(varAtPreVar, services); - final Term varAtPre = tb.var(varAtPreVar); - return varAtPre; + return tb.var(varAtPreVar); } private static Term buildAfterVar(Term varTerm, Services services) { @@ -326,8 +320,7 @@ private static Term buildAfterVar(Term varTerm, Services services) { final LocationVariable varAtPostVar = new LocationVariable(new ProgramElementName(name), resultType); register(varAtPostVar, services); - final Term varAtPost = tb.var(varAtPostVar); - return varAtPost; + return tb.var(varAtPostVar); } private static ImmutableList buildLocalOutsAtPre(ImmutableList varTerms, @@ -540,8 +533,7 @@ private Term bodyTerm(TermLabelState termLabelState, Services services, RuleApp this, bodyGoal, FULL_INVARIANT_TERM_HINT, null); Term bodyTerm = wir.transform(termLabelState, this, ruleApp, bodyGoal, applicationSequent, ruleApp.posInOccurrence(), inst.progPost, fullInvariant, svInst, services); - final Term guardTrueBody = tb.imp(tb.box(guardJb, guardTrueTerm), bodyTerm); - return guardTrueBody; + return tb.imp(tb.box(guardJb, guardTrueTerm), bodyTerm); } @@ -569,13 +561,12 @@ private Term useCaseFormula(TermLabelState termLabelState, Services services, Ru Term restPsi = tb.prog(modality.kind(), useJavaBlock, inst.progPost.sub(0), instantiateLabels); - Term guardFalseRestPsi = tb.box(guardJb, tb.imp(guardFalseTerm, restPsi)); - return guardFalseRestPsi; + return tb.box(guardJb, tb.imp(guardFalseTerm, restPsi)); } - private Triple prepareGuard(final Instantiation inst, - final KeYJavaType booleanKJT, LoopInvariantBuiltInRuleApp loopRuleApp, - final TermServices services) { + private Guard prepareGuard(final Instantiation inst, + final KeYJavaType booleanKJT, LoopInvariantBuiltInRuleApp loopRuleApp, + final TermServices services) { final TermBuilder tb = services.getTermBuilder(); final ProgramElementName guardVarName = new ProgramElementName(tb.newName("b")); final LocationVariable guardVar = new LocationVariable(guardVarName, booleanKJT); @@ -592,9 +583,11 @@ private Triple prepareGuard(final Instantiation inst, JavaBlock.createJavaBlock(new StatementBlock(guardVarMethodFrame)); final Term guardTrueTerm = tb.equals(tb.var(guardVar), tb.TRUE()); final Term guardFalseTerm = tb.equals(tb.var(guardVar), tb.FALSE()); - return new Triple<>(guardJb, guardTrueTerm, guardFalseTerm); + return new Guard(guardJb, guardTrueTerm, guardFalseTerm); } + private record Guard(JavaBlock first, Term second, Term third) {} + private void prepareInvInitiallyValidBranch(TermLabelState termLabelState, Services services, RuleApp ruleApp, Instantiation inst, final Term invTerm, Term reachableState, Goal initGoal) { @@ -752,7 +745,7 @@ private void setupWdGoal(final Goal goal, final LoopSpecification inv, final Ter final Term variantPO = variantPair.second; // prepare guard - final Triple guardStuff = + final Guard guardStuff = prepareGuard(inst, booleanKJT, loopRuleApp, services); final JavaBlock guardJb = guardStuff.first; final Term guardTrueTerm = guardStuff.second; @@ -995,48 +988,39 @@ public AnonUpdateData(Term anonUpdate, Term loopHeap, Term loopHeapAtPre, Term a } } - private static final class InfFlowData { - public final ProofObligationVars symbExecVars; - public final Term guardAtPre; - public final Term guardAtPost; - public final JavaBlock guardJb; - public final Term guardTerm; - public final ImmutableList localOuts; - public final ImmutableList localOutsAtPre; - public final ImmutableList localOutsAtPost; - public final Pair updates; - public final Term applPredTerm; - public final Taclet infFlowApp; - - private InfFlowData(ProofObligationVars symbExecVars, Term guardAtPre, Term guardAtPost, - JavaBlock guardJb, Term guardTerm, ImmutableList localOuts, - ImmutableList localOutsAtPre, ImmutableList localOutsAtPost, - Pair updates, Term applPredTerm, Taclet infFlowApp) { - this.symbExecVars = symbExecVars; - this.guardAtPre = guardAtPre; - this.guardAtPost = guardAtPost; - this.guardJb = guardJb; - this.guardTerm = guardTerm; - this.localOuts = localOuts; - this.localOutsAtPre = localOutsAtPre; - this.localOutsAtPost = localOutsAtPost; - this.updates = updates; - this.infFlowApp = infFlowApp; - this.applPredTerm = applPredTerm; - - assert symbExecVars != null; - assert guardAtPre != null; - assert guardAtPost != null; - assert guardJb != null; - assert guardTerm != null; - assert localOuts != null; - assert localOutsAtPre != null; - assert localOutsAtPost != null; - assert updates != null; - assert applPredTerm != null; - assert infFlowApp != null; + private record InfFlowData(ProofObligationVars symbExecVars, Term guardAtPre, Term guardAtPost, JavaBlock guardJb, + Term guardTerm, ImmutableList localOuts, ImmutableList localOutsAtPre, + ImmutableList localOutsAtPost, Pair updates, Term applPredTerm, + Taclet infFlowApp) { + private InfFlowData(ProofObligationVars symbExecVars, Term guardAtPre, Term guardAtPost, + JavaBlock guardJb, Term guardTerm, ImmutableList localOuts, + ImmutableList localOutsAtPre, ImmutableList localOutsAtPost, + Pair updates, Term applPredTerm, Taclet infFlowApp) { + this.symbExecVars = symbExecVars; + this.guardAtPre = guardAtPre; + this.guardAtPost = guardAtPost; + this.guardJb = guardJb; + this.guardTerm = guardTerm; + this.localOuts = localOuts; + this.localOutsAtPre = localOutsAtPre; + this.localOutsAtPost = localOutsAtPost; + this.updates = updates; + this.infFlowApp = infFlowApp; + this.applPredTerm = applPredTerm; + + assert symbExecVars != null; + assert guardAtPre != null; + assert guardAtPost != null; + assert guardJb != null; + assert guardTerm != null; + assert localOuts != null; + assert localOutsAtPre != null; + assert localOutsAtPost != null; + assert updates != null; + assert applPredTerm != null; + assert infFlowApp != null; + } } - } /** * {@inheritDoc} diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java index 3fb35b67e79..8c46e8163cf 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java @@ -32,7 +32,6 @@ import de.uka.ilkd.key.rule.merge.procedures.MergeTotalWeakening; import de.uka.ilkd.key.rule.merge.procedures.MergeWithLatticeAbstraction; import de.uka.ilkd.key.rule.merge.procedures.MergeWithPredicateAbstraction; -import de.uka.ilkd.key.util.Triple; import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; import de.uka.ilkd.key.util.mergerule.SymbolicExecutionState; import de.uka.ilkd.key.util.mergerule.SymbolicExecutionStateWithProgCnt; @@ -166,7 +165,7 @@ public String toString() { // The merge loop SymbolicExecutionState mergedState = - new SymbolicExecutionState(thisSEState.first, thisSEState.second, newGoal.node()); + new SymbolicExecutionState(thisSEState.first(), thisSEState.second(), newGoal.node()); LinkedHashSet newNames = new LinkedHashSet<>(); LinkedHashSet sideConditionsToProve = new LinkedHashSet<>(); HashMap mergePartnerNodesToStates = new HashMap<>(); @@ -183,8 +182,8 @@ public String toString() { mergePartnerNodesToStates.put(state.getCorrespondingNode(), state); - Triple, LinkedHashSet> mergeResult = - mergeStates(mergeRule, mergedState, state, thisSEState.third, + MergeStateEntry mergeResult = + mergeStates(mergeRule, mergedState, state, thisSEState.third(), mergeRuleApp.getDistinguishingFormula(), services); newNames.addAll(mergeResult.second); sideConditionsToProve.addAll(mergeResult.third); @@ -207,7 +206,7 @@ public String toString() { for (MergePartner mergePartner : mergePartners) { closeMergePartnerGoal(newGoal.node(), mergePartner.getGoal(), mergePartner.getPio(), mergedState, mergePartnerNodesToStates.get(mergePartner.getGoal().node()), - thisSEState.third, newNames); + thisSEState.third(), newNames); } // Delete previous sequents @@ -240,7 +239,7 @@ public String toString() { } // Add new succedent (symbolic state & program counter) - final Term succedentFormula = tb.apply(mergedState.first, thisSEState.third); + final Term succedentFormula = tb.apply(mergedState.first, thisSEState.third()); final SequentFormula newSuccedent = new SequentFormula(succedentFormula); newGoal.addFormula(newSuccedent, new PosInOccurrence(newSuccedent, PosInTerm.getTopLevel(), false)); @@ -258,7 +257,7 @@ public String toString() { } // Add new goals for side conditions that have to be proven - if (sideConditionsToProve.size() > 0) { + if (!sideConditionsToProve.isEmpty()) { final Iterator sideCondIt = sideConditionsToProve.iterator(); int i = 0; @@ -292,22 +291,22 @@ public String toString() { * The programCounter must be the same in both states, so it is supplied * separately. *

- * + *

* Override this method for special merge procedures. * - * @param mergeRule The merge procedure to use for the merge. - * @param state1 First state to merge. - * @param state2 Second state to merge. - * @param programCounter The formula \<{ ... }\> phi consisting of the common program - * counter and the post condition. + * @param mergeRule The merge procedure to use for the merge. + * @param state1 First state to merge. + * @param state2 Second state to merge. + * @param programCounter The formula \<{ ... }\> phi consisting of the common program + * counter and the post condition. * @param distinguishingFormula The user-specified distinguishing formula. May be null (for - * automatic generation). - * @param services The services object. + * automatic generation). + * @param services The services object. * @return A new merged SE state (U*,C*) which is a weakening of the original states. */ @SuppressWarnings("unused") /* For deactivated equiv check */ - protected Triple, LinkedHashSet> mergeStates( + protected MergeStateEntry mergeStates( MergeProcedure mergeRule, SymbolicExecutionState state1, SymbolicExecutionState state2, Term programCounter, Term distinguishingFormula, Services services) { @@ -438,7 +437,7 @@ protected Triple, LinkedHashSet( + return new MergeStateEntry( new SymbolicExecutionState(newSymbolicState, newAdditionalConstraints == null ? newPathCondition : tb.and(newPathCondition, @@ -648,7 +647,7 @@ public static boolean isOfAdmissibleForm(Goal goal, PosInOccurrence pio, return false; } - return !doMergePartnerCheck || findPotentialMergePartners(goal, pio).size() > 0; + return !doMergePartnerCheck || !findPotentialMergePartners(goal, pio).isEmpty(); } @@ -676,7 +675,7 @@ public static ImmutableList findPotentialMergePartners(Goal goal, final ImmutableList allGoals = services.getProof().openGoals(); - final Triple ownSEState = sequentToSETriple(goal.node(), pio, services); + final SymbolicExecutionStateWithProgCnt ownSEState = sequentToSETriple(goal.node(), pio, services); // Find potential partners -- for which isApplicable is true and // they have the same program counter (and post condition). @@ -692,10 +691,10 @@ public static ImmutableList findPotentialMergePartners(Goal goal, final PosInOccurrence gPio = new PosInOccurrence(f, pit, false); if (isOfAdmissibleForm(g, gPio, false)) { - final Triple partnerSEState = + final SymbolicExecutionStateWithProgCnt partnerSEState = sequentToSETriple(g.node(), gPio, services); - if (ownSEState.third.equals(partnerSEState.third)) { + if (ownSEState.third().equals(partnerSEState.third())) { potentialPartners = potentialPartners.prepend(new MergePartner(g, gPio)); @@ -714,4 +713,6 @@ public interface MergeRuleProgressListener { void signalProgress(int progress); } + public record MergeStateEntry(SymbolicExecutionState first, LinkedHashSet second, + LinkedHashSet third) {} } diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java index a524843a1b7..09c03fe98b4 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java @@ -16,9 +16,9 @@ import de.uka.ilkd.key.proof.OpReplacer; import de.uka.ilkd.key.speclang.jml.translation.JMLSpecFactory; import de.uka.ilkd.key.speclang.jml.translation.ProgramVariableCollection; +import de.uka.ilkd.key.speclang.njml.TranslatedDependencyContract; import de.uka.ilkd.key.speclang.translation.SLTranslationException; import de.uka.ilkd.key.util.InfFlowSpec; -import de.uka.ilkd.key.util.Triple; import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; @@ -192,22 +192,22 @@ public DependencyContract dep(KeYJavaType containerType, IObserverFunction pm, } public DependencyContract dep(KeYJavaType kjt, LocationVariable targetHeap, - Triple dep, LocationVariable selfVar) { - final ImmutableList paramVars = tb.paramVars(dep.first, false); - assert (selfVar == null) == dep.first.isStatic(); + TranslatedDependencyContract dep, LocationVariable selfVar) { + final ImmutableList paramVars = tb.paramVars(dep.first(), false); + assert (selfVar == null) == dep.first().isStatic(); Map pres = new LinkedHashMap<>(); pres.put(services.getTypeConverter().getHeapLDT().getHeap(), selfVar == null ? tb.tt() : tb.inv(tb.var(selfVar))); Map accessibles = new LinkedHashMap<>(); for (final LocationVariable heap : HeapContext.getModifiableHeaps(services, false)) { if (heap == targetHeap) { - accessibles.put(heap, dep.second); + accessibles.put(heap, dep.second()); } else { accessibles.put(heap, tb.allLocs()); } } // TODO: insert static invariant?? - return dep(kjt, dep.first, dep.first.getContainerType(), pres, dep.third, accessibles, + return dep(kjt, dep.first(), dep.first().getContainerType(), pres, dep.third(), accessibles, selfVar, paramVars, null, null); } diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java index 83db0781c77..51a1f6b8315 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java @@ -10,7 +10,6 @@ import de.uka.ilkd.key.ldt.HeapLDT; import de.uka.ilkd.key.speclang.njml.LabeledParserRuleContext; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableList; @@ -205,9 +204,11 @@ public void addRequires(LabeledParserRuleContext label) { addClause(REQUIRES, label); } - public Triple[] getAbbreviations() { + public record Abbreviation(LabeledParserRuleContext first, LabeledParserRuleContext second, LabeledParserRuleContext thrid){} + + public Abbreviation[] getAbbreviations() { /* weigl: prepare for future use of generated abbreviations from JML specifications */ - return new Triple[0]; + return new Abbreviation[0]; } public ImmutableList getInfFlowSpecs() { diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java index 5c65044189b..a08ba75e23d 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java @@ -46,7 +46,6 @@ import de.uka.ilkd.key.speclang.translation.SLWarningException; import de.uka.ilkd.key.util.InfFlowSpec; import de.uka.ilkd.key.util.MiscTools; -import de.uka.ilkd.key.util.Triple; import de.uka.ilkd.key.util.mergerule.MergeParamsSpec; import org.key_project.logic.Name; @@ -899,7 +898,7 @@ public String generateName(IProgramMethod pm, TextualJMLSpecCase textualSpecCase } public String generateName(IProgramMethod pm, Behavior originalBehavior, String customName) { - return ((!(customName == null) && customName.length() > 0) ? customName + return ((!(customName == null) && !customName.isEmpty()) ? customName : getContractName(pm, originalBehavior)); } diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java index effb006af91..25746f99d3a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java @@ -18,7 +18,6 @@ import de.uka.ilkd.key.speclang.jml.translation.Context; import de.uka.ilkd.key.speclang.translation.SLExpression; import de.uka.ilkd.key.util.InfFlowSpec; -import de.uka.ilkd.key.util.Triple; import de.uka.ilkd.key.util.mergerule.MergeParamsSpec; import org.key_project.util.collection.ImmutableList; @@ -295,9 +294,8 @@ public InfFlowSpec translateInfFlow(LabeledParserRuleContext expr) { * @throws ClassCastException if the {@code ctx} is not suitable */ @SuppressWarnings("unchecked") - public Triple translateDependencyContract( - ParserRuleContext ctx) { - return (Triple) interpret(ctx); + public TranslatedDependencyContract translateDependencyContract(ParserRuleContext ctx) { + return (TranslatedDependencyContract) interpret(ctx); } /** @@ -307,8 +305,7 @@ public Triple translateDependencyContract( * * @throws ClassCastException if the {@code ctx} is not suitable */ - public Triple translateDependencyContract( - LabeledParserRuleContext ctx) { + public TranslatedDependencyContract translateDependencyContract(LabeledParserRuleContext ctx) { return translateDependencyContract(ctx.first); } // endregion diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java index 968913112a5..d6513a40daa 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java @@ -27,7 +27,6 @@ import de.uka.ilkd.key.speclang.translation.SLExpression; import de.uka.ilkd.key.speclang.translation.SLTranslationException; import de.uka.ilkd.key.util.MiscTools; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.logic.Named; @@ -1030,8 +1029,7 @@ public Pair represents(SLExpression lhs, Term t) { return new Pair<>((IObserverFunction) lhs.getTerm().op(), t); } - public Triple depends(SLExpression lhs, Term rhs, - SLExpression mby) { + public TranslatedDependencyContract depends(SLExpression lhs, Term rhs, SLExpression mby) { LocationVariable heap = services.getTypeConverter().getHeapLDT().getHeap(); if (!lhs.isTerm()) { diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java new file mode 100644 index 00000000000..983d03b0f7f --- /dev/null +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java @@ -0,0 +1,12 @@ +package de.uka.ilkd.key.speclang.njml; + +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.IObserverFunction; + +/** + * + * @author Alexander Weigl + * @version 1 (23.04.24) + */ +public record TranslatedDependencyContract(IObserverFunction first, Term second, Term third) { +} diff --git a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java index db1c5c7b10f..5e1ba42bb90 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java +++ b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java @@ -9,7 +9,6 @@ import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyFactory; import de.uka.ilkd.key.strategy.StrategyProperties; -import de.uka.ilkd.key.util.Triple; import org.key_project.util.collection.ImmutableArray; @@ -36,8 +35,9 @@ * @see StrategyPropertyValueDefinition */ public class StrategySettingsDefinition { + public record StategySettingEntry(String name, int order, IDefaultStrategyPropertiesFactory factory){} - private static final ArrayList> STD_FURTHER_DEFAULTS; + private static final ArrayList STD_FURTHER_DEFAULTS; /** * Defines if a user interface control is shown to edit {@link StrategySettings#getMaxSteps()}. @@ -74,14 +74,13 @@ public class StrategySettingsDefinition { * Further default settings, for example suitable for simplification. Consists of triples * (DEFAULT_NAME, MAX_RULE_APPS, PROPERTIES). */ - private final ArrayList> furtherDefaults; + private final ArrayList furtherDefaults; static { - STD_FURTHER_DEFAULTS = - new ArrayList<>(); + STD_FURTHER_DEFAULTS = new ArrayList<>(); // Java verification standard preset (tested in TimSort case study) - STD_FURTHER_DEFAULTS.add(new Triple<>( + STD_FURTHER_DEFAULTS.add(new StategySettingEntry( "Java verif. std.", 7000, () -> { final StrategyProperties newProps = IDefaultStrategyPropertiesFactory.DEFAULT_FACTORY @@ -124,7 +123,7 @@ public class StrategySettingsDefinition { })); // Simplification preset - STD_FURTHER_DEFAULTS.add(new Triple<>( + STD_FURTHER_DEFAULTS.add(new StategySettingEntry( "Simplification", 5000, () -> { final StrategyProperties newProps = IDefaultStrategyPropertiesFactory.DEFAULT_FACTORY @@ -197,7 +196,7 @@ public StrategySettingsDefinition(String propertiesTitle, public StrategySettingsDefinition(boolean showMaxRuleApplications, String maxRuleApplicationsLabel, int defaultMaxRuleApplications, String propertiesTitle, IDefaultStrategyPropertiesFactory defaultPropertiesFactory, - ArrayList> furtherDefaults, + ArrayList furtherDefaults, AbstractStrategyPropertyDefinition... properties) { assert defaultPropertiesFactory != null; this.showMaxRuleApplications = showMaxRuleApplications; @@ -272,7 +271,7 @@ public IDefaultStrategyPropertiesFactory getDefaultPropertiesFactory() { /** * @return Further default settings, e.g. for simplification. */ - public ArrayList> getFurtherDefaults() { + public ArrayList getFurtherDefaults() { return furtherDefaults; } diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/Triple.java b/key.core/src/main/java/de/uka/ilkd/key/util/Triple.java deleted file mode 100644 index aec99618b43..00000000000 --- a/key.core/src/main/java/de/uka/ilkd/key/util/Triple.java +++ /dev/null @@ -1,62 +0,0 @@ -/* This file is part of KeY - https://key-project.org - * KeY is licensed under the GNU General Public License Version 2 - * SPDX-License-Identifier: GPL-2.0-only */ -package de.uka.ilkd.key.util; - - -import java.util.Objects; - -/** - * Simple value object to hold three values. - * - * @param type of first element - * @param type of second element - * @param type of third element - */ -public class Triple { - /** - * First element. - */ - public final T1 first; - /** - * Second element. - */ - public final T2 second; - /** - * Third element. - */ - public final T3 third; - - - /** - * Construct a new triple containing the provided values. - * - * @param first first element - * @param second second element - * @param third third element - */ - public Triple(T1 first, T2 second, T3 third) { - this.first = first; - this.second = second; - this.third = third; - } - - - public String toString() { - return "(" + first + ", " + second + ", " + third + ")"; - } - - - public boolean equals(Object o) { - if (!(o instanceof Triple p)) { - return false; - } - return Objects.equals(first, p.first) && Objects.equals(second, p.second) - && Objects.equals(third, p.third); - } - - - public int hashCode() { - return Objects.hash(first, second, third); - } -} diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java index 4d3fe3dfc6d..b318d10e027 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java +++ b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java @@ -32,7 +32,6 @@ import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.util.ProofStarter; import de.uka.ilkd.key.util.SideProofUtil; -import de.uka.ilkd.key.util.Triple; import org.key_project.logic.Name; import org.key_project.logic.Named; @@ -653,7 +652,7 @@ public static JavaBlock getJavaBlockRecursive(Term term) { return JavaBlock.EMPTY_JAVABLOCK; } - if (term.subs().size() == 0 || !term.javaBlock().isEmpty()) { + if (term.subs().isEmpty() || !term.javaBlock().isEmpty()) { return term.javaBlock(); } else { for (Term sub : term.subs()) { @@ -1099,11 +1098,11 @@ public static ImmutableList sequentsToSEPairs( final Node node = sequentInfo.getGoal().node(); final Services services = sequentInfo.getGoal().proof().getServices(); - Triple partnerSEState = + SymbolicExecutionStateWithProgCnt partnerSEState = sequentToSETriple(node, sequentInfo.getPio(), services); result = result.prepend( - new SymbolicExecutionState(partnerSEState.first, partnerSEState.second, node)); + new SymbolicExecutionState(partnerSEState.first(), partnerSEState.second(), node)); } return result; @@ -1378,7 +1377,7 @@ public static LocationVariable rename(Name newName, LocationVariable lv) { */ private static Term joinListToAndTerm(ImmutableList formulae, Services services) { - if (formulae.size() == 0) { + if (formulae.isEmpty()) { return services.getTermBuilder().tt(); } else if (formulae.size() == 1) { return formulae.head().formula(); diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java index 6aa291423f9..f4ec6a50bd3 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java +++ b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java @@ -7,7 +7,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.pp.LogicPrinter; import de.uka.ilkd.key.proof.Node; -import de.uka.ilkd.key.util.Triple; +import org.jspecify.annotations.Nullable; /** * A symbolic execution state with program counter is a triple of a symbolic state in form of a @@ -17,10 +17,8 @@ * * @author Dominic Scheurer */ -public class SymbolicExecutionStateWithProgCnt extends Triple { - - private Node correspondingNode = null; - +public record SymbolicExecutionStateWithProgCnt(Term first, Term second, Term third, + @Nullable Node correspondingNode) { /** * @param symbolicState The symbolic state (parallel update). * @param pathCondition The path condition (formula). diff --git a/key.core/src/test/java/de/uka/ilkd/key/logic/TestLocalSymbols.java b/key.core/src/test/java/de/uka/ilkd/key/logic/TestLocalSymbols.java index 00c2b3ffa33..69234d167b4 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/logic/TestLocalSymbols.java +++ b/key.core/src/test/java/de/uka/ilkd/key/logic/TestLocalSymbols.java @@ -127,7 +127,7 @@ public void testDoubleInstantiation() throws Exception { KeYEnvironment env = loadProof("doubleSkolem.key"); Proof proof = env.getLoadedProof(); - String script = env.getProofScript().first; + String script = env.getProofScript().script(); ProofScriptEngine pse = new ProofScriptEngine(script, new Location(null, Position.newOneBased(1, 1))); diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java b/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java index 94864222674..f186080c594 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java @@ -68,9 +68,9 @@ public void loadTacletProof(String tacletName, Taclet taclet, File proofFile) th KeYEnvironment env = KeYEnvironment.load(proofFile); Proof proof = env.getLoadedProof(); - Pair script = env.getProofScript(); + var script = env.getProofScript(); if (script != null) { - ProofScriptEngine pse = new ProofScriptEngine(script.first, script.second); + ProofScriptEngine pse = new ProofScriptEngine(script.script(), script.location()); pse.execute(env.getUi(), proof); } diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java index dba91626680..8966026c803 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java @@ -10,6 +10,7 @@ import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.KeYEnvironment; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.parser.Location; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.io.AbstractProblemLoader; @@ -197,7 +198,7 @@ private void autoMode(KeYEnvironment env, Proof loa /* * has resemblances with KeYEnvironment.load ... */ - private Pair, Pair> load( + private Pair, ProofScriptEntry> load( File keyFile) throws ProblemLoaderException { KeYEnvironment env = KeYEnvironment.load(keyFile); return new Pair<>(env, env.getProofScript()); diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java index 3617cbc09c9..d7aa7c78ee0 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java @@ -8,7 +8,7 @@ import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.KeYEnvironment; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.runallproofs.proofcollection.ProofCollectionSettings; import de.uka.ilkd.key.proof.runallproofs.proofcollection.TestFile; @@ -17,8 +17,6 @@ import de.uka.ilkd.key.prover.impl.ApplyStrategyInfo; import de.uka.ilkd.key.strategy.Strategy; -import org.key_project.util.collection.Pair; - class DataRecordingTestFile extends TestFile { public final ProfilingDirectories directories; @@ -30,7 +28,7 @@ public DataRecordingTestFile(TestProperty testProperty, String path, @Override protected void autoMode(KeYEnvironment env, Proof loadedProof, - Pair script) throws Exception { + ProofScriptEntry script) throws Exception { // Run KeY prover. if (script == null) { DataRecordingStrategy strategy = new DataRecordingStrategy(loadedProof, this); diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java index e8a476b06e7..25d5dedd8fc 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java @@ -13,7 +13,7 @@ import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.KeYEnvironment; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.io.AbstractProblemLoader.ReplayResult; import de.uka.ilkd.key.proof.io.ProblemLoaderException; @@ -161,10 +161,9 @@ public TestResult runKey() throws Exception { boolean success; try { // Initialize KeY environment and load proof. - Pair, Pair> pair = - load(keyFile); + var pair = load(keyFile); env = pair.first; - Pair script = pair.second; + ProofScriptEntry script = pair.second; loadedProof = env.getLoadedProof(); ReplayResult replayResult; @@ -263,14 +262,14 @@ protected void reload(boolean verbose, File proofFile, Proof loadedProof, boolea * want to use a different strategy. */ protected void autoMode(KeYEnvironment env, Proof loadedProof, - Pair script) throws Exception { + ProofScriptEntry script) throws Exception { // Run KeY prover. if (script == null) { // auto mode env.getProofControl().startAndWaitForAutoMode(loadedProof); } else { // ... script - ProofScriptEngine pse = new ProofScriptEngine(script.first, script.second); + ProofScriptEngine pse = new ProofScriptEngine(script.script(), script.location()); pse.execute(env.getUi(), env.getLoadedProof()); } } @@ -278,7 +277,7 @@ protected void autoMode(KeYEnvironment env, Proof l /* * has resemblances with KeYEnvironment.load ... */ - private Pair, Pair> load( + private Pair, ProofScriptEntry> load( File keyFile) throws ProblemLoaderException { KeYEnvironment env = KeYEnvironment.load(keyFile); return new Pair<>(env, env.getProofScript()); diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java index ca11ccaa58e..b17ae902c0b 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java @@ -25,7 +25,6 @@ import de.uka.ilkd.key.strategy.StrategyFactory; import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.strategy.definition.*; -import de.uka.ilkd.key.util.Triple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -405,9 +404,8 @@ private JPanel createDefaultPanel(StrategySelectionComponents components) { existingPredefs[0] = "Defaults"; int i = 1; - for (Triple furtherDefault : DEFINITION - .getFurtherDefaults()) { - existingPredefs[i] = furtherDefault.first; + for (StrategySettingsDefinition.StategySettingEntry furtherDefault : DEFINITION.getFurtherDefaults()) { + existingPredefs[i] = furtherDefault.name(); i++; } @@ -425,10 +423,9 @@ private JPanel createDefaultPanel(StrategySelectionComponents components) { newProps = DEFINITION.getDefaultPropertiesFactory().createDefaultStrategyProperties(); } else { - Triple chosenDefault = - DEFINITION.getFurtherDefaults().get(selIndex - 1); - newMaxSteps = chosenDefault.second; - newProps = chosenDefault.third.createDefaultStrategyProperties(); + var chosenDefault = DEFINITION.getFurtherDefaults().get(selIndex - 1); + newMaxSteps = chosenDefault.order(); + newProps = chosenDefault.factory().createDefaultStrategyProperties(); } mediator.getSelectedProof().getSettings().getStrategySettings() diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java index fa0578538d8..fc159628784 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java @@ -23,7 +23,7 @@ import de.uka.ilkd.key.gui.notification.events.NotificationEvent; import de.uka.ilkd.key.macros.ProofMacro; import de.uka.ilkd.key.macros.ProofMacroFinishedInfo; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.ProofAggregate; @@ -222,11 +222,11 @@ private void taskFinishedInternal(TaskFinishedInfo info) { KeYMediator mediator = mainWindow.getMediator(); mediator.getNotationInfo().refresh(mediator.getServices()); if (problemLoader.hasProofScript()) { - Pair scriptAndLoc; + ProofScriptEntry scriptAndLoc; try { scriptAndLoc = problemLoader.readProofScript(); ProofScriptWorker psw = new ProofScriptWorker(mainWindow.getMediator(), - scriptAndLoc.first, scriptAndLoc.second); + scriptAndLoc.script(), scriptAndLoc.location()); psw.init(); psw.execute(); } catch (ProofInputException e) { diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java index abcbed2365a..02385e81654 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java @@ -12,7 +12,6 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.pp.LogicPrinter; import de.uka.ilkd.key.proof.Node; -import de.uka.ilkd.key.util.Triple; /** * @author Alexander Weigl @@ -84,31 +83,33 @@ static String findAndPopNearestMatch(String l, List right) { return current; } + public record QueueEntry(int idxLeft, int idxRight, int distance){} + static List findPairs(List left, List right) { List pairs = new ArrayList<>(left.size() + right.size()); int initCap = Math.max(8, Math.max(left.size() * right.size(), Math.max(left.size(), right.size()))); - PriorityQueue> queue = - new PriorityQueue<>(initCap, Comparator.comparingInt((t) -> t.third)); + PriorityQueue queue = + new PriorityQueue<>(initCap, Comparator.comparingInt(QueueEntry::distance)); for (int i = 0; i < left.size(); i++) { for (int j = 0; j < right.size(); j++) { - queue.add(new Triple<>(i, j, Levensthein.calculate(left.get(i), right.get(j)))); + queue.add(new QueueEntry(i, j, Levensthein.calculate(left.get(i), right.get(j)))); } } boolean[] matchedLeft = new boolean[left.size()]; boolean[] matchedRight = new boolean[right.size()]; while (!queue.isEmpty()) { - Triple t = queue.poll(); + QueueEntry t = queue.poll(); /* * if(t.third>=THRESHOLD) { break; } */ - if (!matchedLeft[t.first] && !matchedRight[t.second]) { - String l = left.get(t.first); - String r = right.get(t.second); - pairs.add(new Matching(l, r, t.third)); - matchedLeft[t.first] = true; - matchedRight[t.second] = true; + if (!matchedLeft[t.idxLeft] && !matchedRight[t.idxRight]) { + String l = left.get(t.idxLeft); + String r = right.get(t.idxRight); + pairs.add(new Matching(l, r, t.distance)); + matchedLeft[t.idxLeft] = true; + matchedRight[t.idxRight] = true; } } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java index f011f4e5601..30ada1c137a 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java @@ -4,7 +4,6 @@ package org.key_project.slicing; import de.uka.ilkd.key.rule.Rule; -import de.uka.ilkd.key.util.Triple; import java.util.Comparator; import java.util.HashMap; @@ -23,7 +22,7 @@ public class RuleStatistics { * that used this rule and didn't contribute to the proof ("useless" proof steps), and the * number of "useless" proof steps that initiate a chain of further (useless) proof steps. */ - private final Map> map = new HashMap<>(); + private final Map map = new HashMap<>(); /** * Mapping of rule name to whether this rule introduces new proof branches. */ @@ -39,9 +38,9 @@ public void addApplication(Rule rule, boolean branches) { String name = rule.displayName(); ruleBranched.put(name, branches); - Triple entry = - map.computeIfAbsent(name, it -> new Triple<>(0, 0, 0)); - map.put(name, new Triple<>(entry.first + 1, entry.second, entry.third)); + StatisticEntry entry = + map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications, entry.numberOfInitialUselessApplications)); } /** @@ -54,9 +53,9 @@ public void addUselessApplication(Rule rule, boolean branches) { String name = rule.displayName(); ruleBranched.put(name, branches); - Triple entry = - map.computeIfAbsent(name, it -> new Triple<>(0, 0, 0)); - map.put(name, new Triple<>(entry.first + 1, entry.second + 1, entry.third)); + StatisticEntry entry = + map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications)); } /** @@ -69,9 +68,9 @@ public void addInitialUselessApplication(Rule rule, boolean branches) { String name = rule.displayName(); ruleBranched.put(name, branches); - Triple entry = - map.computeIfAbsent(name, it -> new Triple<>(0, 0, 0)); - map.put(name, new Triple<>(entry.first + 1, entry.second + 1, entry.third + 1)); + StatisticEntry entry = + map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications + 1)); } /** @@ -84,8 +83,8 @@ public void addInitialUselessApplication(Rule rule, boolean branches) { */ public List sortBy(Comparator comparator) { return map.entrySet().stream() - .map(entry -> new RuleStatisticEntry(entry.getKey(), entry.getValue().first, - entry.getValue().second, entry.getValue().third)) + .map(entry -> new RuleStatisticEntry(entry.getKey(), entry.getValue().numberOfApplications, + entry.getValue().numberOfUselessApplications, entry.getValue().numberOfInitialUselessApplications)) .sorted(comparator) .collect(Collectors.toList()); } @@ -100,6 +99,9 @@ public boolean branches(String rule) { /** * Usage statistic of a rule. + *

+ * TODO weigl: refactoring task, combine {@link RuleStatisticEntry} with {@link StatisticEntry} to avoid repetition. + * * @param ruleName * @param numberOfApplications * @param numberOfUselessApplications @@ -107,4 +109,12 @@ public boolean branches(String rule) { */ public record RuleStatisticEntry(String ruleName, int numberOfApplications, int numberOfUselessApplications, int numberOfInitialUselessApplications) { } + + /** + * Usage statistic of a rule. + * @param numberOfApplications + * @param numberOfUselessApplications + * @param numberOfInitialUselessApplications + */ + public record StatisticEntry(int numberOfApplications, int numberOfUselessApplications, int numberOfInitialUselessApplications){} } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java index 02f109322a2..320c5d43756 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java @@ -11,7 +11,6 @@ import de.uka.ilkd.key.proof.BranchLocation; import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.Proof; -import de.uka.ilkd.key.util.Triple; import org.key_project.slicing.DependencyNodeData; import org.key_project.slicing.DependencyTracker; @@ -120,16 +119,18 @@ public Stream incomingEdgesOf(GraphNode node) { return graph.incomingEdgesOf(node).stream().map(AnnotatedEdge::getProofStep); } + public record IncomingEdge(Node first, GraphNode second, AnnotatedEdge third){} + /** * @param node a graph node * @return the incoming (graph edges, graph sources) of that node */ - public Stream> incomingGraphEdgesOf(GraphNode node) { + public Stream incomingGraphEdgesOf(GraphNode node) { if (!graph.containsVertex(node)) { return Stream.of(); } return graph.incomingEdgesOf(node).stream() - .map(edge -> new Triple<>(edge.getProofStep(), graph.getEdgeSource(edge), edge)); + .map(edge -> new IncomingEdge(edge.getProofStep(), graph.getEdgeSource(edge), edge)); } /** @@ -147,12 +148,12 @@ public Stream outgoingEdgesOf(GraphNode node) { * @param node a graph node * @return the outgoing (graph edges, graph targets) of that node */ - public Stream> outgoingGraphEdgesOf(GraphNode node) { + public Stream outgoingGraphEdgesOf(GraphNode node) { if (!graph.containsVertex(node)) { return Stream.of(); } return graph.outgoingEdgesOf(node).stream() - .map(edge -> new Triple<>(edge.getProofStep(), graph.getEdgeTarget(edge), edge)); + .map(edge -> new IncomingEdge(edge.getProofStep(), graph.getEdgeTarget(edge), edge)); } /** diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java b/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java index 1066b77a47d..320042ea01b 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java @@ -15,11 +15,12 @@ import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.uka.ilkd.key.proof.Node; -import de.uka.ilkd.key.util.Triple; import org.key_project.slicing.DependencyTracker; import org.key_project.slicing.analysis.AnalysisResults; import org.key_project.slicing.graph.AnnotatedEdge; +import org.key_project.slicing.graph.DependencyGraph; +import org.key_project.slicing.graph.DependencyGraph.IncomingEdge; import org.key_project.slicing.graph.GraphNode; import org.key_project.util.collection.Pair; @@ -72,17 +73,17 @@ private void showDialog(Window parentWindow) { List graphNodes = new ArrayList<>(); List proofSteps = new ArrayList<>(); AnalysisResults analysisResults = tracker.getAnalysisResults(); - Function, Collection> nodeToTableRow = n -> { - proofSteps.add(n.first); - graphNodes.add(n.second); - var ruleName = n.first.getAppliedRuleApp().rule().displayName(); + Function> nodeToTableRow = n -> { + proofSteps.add(n.first()); + graphNodes.add(n.second()); + var ruleName = n.first().getAppliedRuleApp().rule().displayName(); return List.of( - Integer.toString(n.first.serialNr()), - analysisResults != null && !analysisResults.usefulSteps.contains(n.first) + Integer.toString(n.first().serialNr()), + analysisResults != null && !analysisResults.usefulSteps.contains(n.first()) ? "" + ruleName + "" : ruleName, - n.third.replacesInputNode() ? "yes" : "no", - n.second.toString(false, false)); + n.third().replacesInputNode() ? "yes" : "no", + n.second().toString(false, false)); }; var idxFactory = new IndexFactory(); @@ -99,7 +100,7 @@ private void showDialog(Window parentWindow) { HtmlFactory.generateTable(headers2, clickable, Optional.empty(), outgoing, idxFactory); var useful = analysisResults != null ? tracker.getDependencyGraph().outgoingGraphEdgesOf(node) - .filter(t -> analysisResults.usefulSteps.contains(t.first)).count() + .filter(t -> analysisResults.usefulSteps.contains(t.first())).count() : -1; var extraInfo = useful != -1 ? "

" + useful + " useful rule apps

" : ""; var previousDerivations = 0; From 6079909eff96bc0b589b8be071ddaf6838e4a7b2 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 23 Apr 2024 22:30:45 +0200 Subject: [PATCH 03/10] fix compile errors --- .../rule/ModalitySideProofRule.java | 15 +- .../rule/QuerySideProofRule.java | 5 +- .../util/SymbolicExecutionSideProofUtil.java | 102 +++---- .../uka/ilkd/key/control/KeYEnvironment.java | 2 +- .../java/de/uka/ilkd/key/nparser/KeyAst.java | 2 +- .../key/proof/init/KeYUserProblemFile.java | 2 +- .../key/proof/io/AbstractProblemLoader.java | 90 +++--- .../proof/io/IntermediateProofReplayer.java | 8 +- .../proof/mgt/SpecificationRepository.java | 266 ++++++++++-------- .../uka/ilkd/key/rule/WhileInvariantRule.java | 4 +- .../de/uka/ilkd/key/rule/merge/MergeRule.java | 30 +- .../merge/procedures/MergeByIfThenElse.java | 32 +-- .../pretranslation/TextualJMLSpecCase.java | 4 +- .../jml/translation/JMLSpecFactory.java | 17 +- .../key/speclang/njml/JmlTermFactory.java | 2 +- .../njml/TranslatedDependencyContract.java | 5 +- .../StrategySettingsDefinition.java | 3 +- .../key/util/mergerule/MergeRuleUtils.java | 5 +- .../SymbolicExecutionStateWithProgCnt.java | 42 +-- .../key/proof/proverules/ProveRulesTest.java | 2 - .../key/proof/runallproofs/ProveTest.java | 9 +- .../performance/DataRecordingTestFile.java | 2 +- .../proofcollection/TestFile.java | 2 +- .../ilkd/key/gui/StrategySelectionView.java | 3 +- .../key/gui/proofdiff/ProofDifference.java | 2 +- .../key/ui/ConsoleUserInterfaceControl.java | 21 +- .../key_project/slicing/RuleStatistics.java | 29 +- .../slicing/analysis/DependencyAnalyzer.java | 6 +- .../slicing/graph/DependencyGraph.java | 39 ++- .../slicing/ui/RuleStatisticsDialog.java | 70 +++-- .../slicing/ui/ShowNodeInfoAction.java | 22 +- .../slicing/DependencyGraphTest.java | 8 +- 32 files changed, 447 insertions(+), 404 deletions(-) diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java index 9023be377d2..18f87c546f0 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ModalitySideProofRule.java @@ -3,6 +3,10 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.symbolic_execution.rule; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.*; import de.uka.ilkd.key.logic.op.*; @@ -11,15 +15,13 @@ import de.uka.ilkd.key.rule.*; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionSideProofUtil; import de.uka.ilkd.key.symbolic_execution.util.SymbolicExecutionUtil; -import org.jspecify.annotations.NonNull; + import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.Pair; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import org.jspecify.annotations.NonNull; /** *

@@ -179,8 +181,9 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { Set resultTerms = new LinkedHashSet<>(); for (ResultsAndCondition conditionsAndResult : conditionsAndResultsMap) { Term conditionTerm = tb.and(conditionsAndResult.conditions()); - Term resultEqualityTerm = varFirst ? tb.equals(conditionsAndResult.result(), otherTerm) - : tb.equals(otherTerm, conditionsAndResult.result()); + Term resultEqualityTerm = + varFirst ? tb.equals(conditionsAndResult.result(), otherTerm) + : tb.equals(otherTerm, conditionsAndResult.result()); Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, resultEqualityTerm) : tb.and(conditionTerm, resultEqualityTerm); resultTerms.add(resultTerm); diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java index 21dd88702da..a4bfda8eab7 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/QuerySideProofRule.java @@ -236,8 +236,9 @@ public IBuiltInRuleApp createApp(PosInOccurrence pos, TermServices services) { if (pio.isTopLevel() || queryConditionTerm != null) { for (ResultsAndCondition conditionsAndResult : conditionsAndResultsMap) { Term conditionTerm = tb.and(conditionsAndResult.conditions()); - Term newEqualityTerm = varFirst ? tb.equals(varTerm, conditionsAndResult.result()) - : tb.equals(conditionsAndResult.result(), varTerm); + Term newEqualityTerm = + varFirst ? tb.equals(varTerm, conditionsAndResult.result()) + : tb.equals(conditionsAndResult.result(), varTerm); Term resultTerm = pio.isInAntec() ? tb.imp(conditionTerm, newEqualityTerm) : tb.and(conditionTerm, newEqualityTerm); if (queryConditionTerm != null) { diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java index f26b338c655..3a4fb926956 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java @@ -3,6 +3,8 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.symbolic_execution.util; +import java.util.*; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.abstraction.KeYJavaType; import de.uka.ilkd.key.ldt.HeapLDT; @@ -33,6 +35,7 @@ import de.uka.ilkd.key.symbolic_execution.rule.AbstractSideProofRule.ResultsAndCondition; import de.uka.ilkd.key.util.ProofStarter; import de.uka.ilkd.key.util.SideProofUtil; + import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableArray; import org.key_project.util.collection.ImmutableList; @@ -40,8 +43,6 @@ import org.key_project.util.collection.Pair; import org.key_project.util.java.CollectionUtil; -import java.util.*; - /** * Provides utility methods for side proofs. * @@ -64,7 +65,7 @@ private SymbolicExecutionSideProofUtil() { * @return The general initial {@link Sequent}. */ public static Sequent computeGeneralSequentToProve(Sequent goalSequent, - SequentFormula currentSF) { + SequentFormula currentSF) { Sequent sequentToProve = Sequent.EMPTY_SEQUENT; for (SequentFormula sf : goalSequent.antecedent()) { if (sf != currentSF) { @@ -105,12 +106,12 @@ public static Sequent computeGeneralSequentToProve(Sequent goalSequent, * @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 { + 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); + methodTreatment, loopTreatment, queryTreatment, splittingOption); try { // Extract results and conditions from side proof List> conditionsAndResultsMap = new LinkedList<>(); @@ -176,11 +177,11 @@ public static List computeResultsAndConditions( throws ProofInputException { // Execute side proof ApplyStrategyInfo info = startSideProof(proof, sideProofEnvironment, sequentToProve, - methodTreatment, loopTreatment, queryTreatment, splittingOption); + methodTreatment, loopTreatment, queryTreatment, splittingOption); try { // Extract relevant things Set relevantThingsInSequentToProve = - extractRelevantThings(info.getProof().getServices(), sequentToProve); + extractRelevantThings(info.getProof().getServices(), sequentToProve); // Extract results and conditions from side proof List conditionsAndResultsMap = new LinkedList<>(); for (Goal resultGoal : info.getProof().openGoals()) { @@ -195,18 +196,18 @@ public static List computeResultsAndConditions( if (newPredicateIsSequentFormula) { if (Operator.opEquals(sf.formula().op(), operator)) { throw new IllegalStateException( - "Result predicate found in antecedent."); + "Result predicate found in antecedent."); } else { Term constructedResult = - constructResultIfContained(services, sf, operator); + constructResultIfContained(services, sf, operator); if (constructedResult != null) { throw new IllegalStateException( - "Result predicate found in antecedent."); + "Result predicate found in antecedent."); } } } if (!isIrrelevantCondition(services, sequentToProve, - relevantThingsInSequentToProve, sf)) { + relevantThingsInSequentToProve, sf)) { if (resultConditions.add(sf.formula()) && addNamesToServices) { addNewNamesToNamespace(services, sf.formula()); } @@ -217,7 +218,7 @@ public static List computeResultsAndConditions( if (Operator.opEquals(sf.formula().op(), operator)) { if (result != null) { throw new IllegalStateException( - "Result predicate found multiple times in succedent."); + "Result predicate found multiple times in succedent."); } result = sf.formula().sub(0); } @@ -226,14 +227,14 @@ public static List computeResultsAndConditions( if (constructedResult != null) { if (result != null) { throw new IllegalStateException( - "Result predicate found multiple times in succedent."); + "Result predicate found multiple times in succedent."); } result = constructedResult; } } if (result == null) { if (!isIrrelevantCondition(services, sequentToProve, - relevantThingsInSequentToProve, sf)) { + relevantThingsInSequentToProve, sf)) { if (resultConditions.add(services.getTermBuilder().not(sf.formula())) && addNamesToServices) { addNewNamesToNamespace(services, sf.formula()); @@ -244,7 +245,8 @@ public static List computeResultsAndConditions( if (result == null) { result = services.getTermBuilder().ff(); } - conditionsAndResultsMap.add(new ResultsAndCondition(result, resultConditions, resultGoal.node())); + conditionsAndResultsMap + .add(new ResultsAndCondition(result, resultConditions, resultGoal.node())); } return conditionsAndResultsMap; } finally { @@ -253,12 +255,12 @@ public static List computeResultsAndConditions( } private static Term constructResultIfContained(Services services, SequentFormula sf, - Operator operator) { + Operator operator) { return constructResultIfContained(services, sf.formula(), operator); } private static Term constructResultIfContained(Services services, Term term, - Operator operator) { + Operator operator) { if (Operator.opEquals(term.op(), operator)) { return term.sub(0); } else { @@ -278,8 +280,8 @@ private static Term constructResultIfContained(Services services, Term term, } } result = services.getTermFactory().createTerm(term.op(), - new ImmutableArray<>(newSubs), term.boundVars(), - term.getLabels()); + new ImmutableArray<>(newSubs), term.boundVars(), + term.getLabels()); } return result; } @@ -287,7 +289,7 @@ private static Term constructResultIfContained(Services services, Term term, private static boolean isOperatorASequentFormula(Sequent sequent, final Operator operator) { return CollectionUtil.search(sequent, - element -> Operator.opEquals(element.formula().op(), operator)) != null; + element -> Operator.opEquals(element.formula().op(), operator)) != null; } /** @@ -377,7 +379,7 @@ public boolean isContainsModalityOrQuery() { * @return The found relevant things. */ public static Set extractRelevantThings(final Services services, - Sequent sequentToProve) { + Sequent sequentToProve) { final Set result = new HashSet<>(); for (SequentFormula sf : sequentToProve) { sf.formula().execPreOrder((DefaultVisitor) visited -> { @@ -429,7 +431,7 @@ private static boolean isRelevantThing(Services services, Term term) { * {@link SequentFormula} is not a relevant condition. */ public static boolean isIrrelevantCondition(Services services, Sequent initialSequent, - Set relevantThingsInSequentToProve, SequentFormula sf) { + Set relevantThingsInSequentToProve, SequentFormula sf) { return initialSequent.antecedent().contains(sf) || initialSequent.succedent().contains(sf) || containsModalityOrQuery(sf) // isInOrOfAntecedent(initialSequent, sf) || || containsIrrelevantThings(services, sf, relevantThingsInSequentToProve); @@ -473,9 +475,9 @@ public static boolean isIrrelevantCondition(Services services, Sequent initialSe * {@link SequentFormula} contains no irrelevant things. */ public static boolean containsIrrelevantThings(Services services, SequentFormula sf, - Set relevantThings) { + Set relevantThings) { ContainsIrrelevantThingsVisitor visitor = - new ContainsIrrelevantThingsVisitor(services, relevantThings); + new ContainsIrrelevantThingsVisitor(services, relevantThings); sf.formula().execPostOrder(visitor); return visitor.isContainsIrrelevantThings(); } @@ -550,11 +552,11 @@ public boolean isContainsIrrelevantThings() { * @throws ProofInputException Occurred Exception */ public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, Sequent sequentToProve) + ProofEnvironment sideProofEnvironment, Sequent sequentToProve) throws ProofInputException { return startSideProof(proof, sideProofEnvironment, sequentToProve, - StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, - StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_OFF); + StrategyProperties.METHOD_NONE, StrategyProperties.LOOP_NONE, + StrategyProperties.QUERY_OFF, StrategyProperties.SPLITTING_OFF); } /** @@ -567,12 +569,12 @@ public static ApplyStrategyInfo startSideProof(Proof proof, * @throws ProofInputException Occurred Exception */ public static ApplyStrategyInfo startSideProof(Proof proof, - ProofEnvironment sideProofEnvironment, Sequent sequentToProve, String methodTreatment, - String loopTreatment, String queryTreatment, String splittingOption) + 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); + splittingOption); } /** @@ -586,7 +588,7 @@ public static ApplyStrategyInfo startSideProof(Proof proof, * @throws ProofInputException Occurred Exception. */ public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment, - Sequent sequentToProve, String proofName) throws ProofInputException { + Sequent sequentToProve, String proofName) throws ProofInputException { return SideProofUtil.createSideProof(sideProofEnvironment, sequentToProve, proofName); } @@ -599,8 +601,8 @@ public static ProofStarter createSideProof(ProofEnvironment sideProofEnvironment * @return The site proof result. */ public static ApplyStrategyInfo startSideProof(Proof proof, ProofStarter starter, - String methodTreatment, String loopTreatment, String queryTreatment, - String splittingOption) { + String methodTreatment, String loopTreatment, String queryTreatment, + String splittingOption) { assert starter != null; starter.setMaxRuleApplications(10000); StrategyProperties sp = proof != null && !proof.isDisposed() @@ -613,7 +615,7 @@ public static ApplyStrategyInfo startSideProof(Proof proof, ProofStarter starter sp.setProperty(StrategyProperties.QUERY_OPTIONS_KEY, queryTreatment); sp.setProperty(StrategyProperties.SPLITTING_OPTIONS_KEY, splittingOption); sp.setProperty(StrategyProperties.QUANTIFIERS_OPTIONS_KEY, - StrategyProperties.QUANTIFIERS_NON_SPLITTING); + StrategyProperties.QUANTIFIERS_NON_SPLITTING); starter.setStrategyProperties(sp); // Execute proof in the current thread return starter.start(); @@ -660,8 +662,8 @@ public static Term extractOperatorTerm(ApplyStrategyInfo info, Operator operator 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."); + "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); @@ -715,11 +717,11 @@ public static Term extractOperatorTerm(Node node, final Operator operator) { * {@link Proof} but with its own {@link OneStepSimplifier} instance. */ public static ProofEnvironment cloneProofEnvironmentWithOwnOneStepSimplifier(final Proof source, - final boolean useSimplifyTermProfile) { + final boolean useSimplifyTermProfile) { assert source != null; assert !source.isDisposed(); return cloneProofEnvironmentWithOwnOneStepSimplifier(source.getInitConfig(), - useSimplifyTermProfile); + useSimplifyTermProfile); } /** @@ -745,13 +747,13 @@ protected ImmutableList computeTermLabelConfiguration() Profile sourceProfile = sourceInitConfig.getProfile(); if (sourceProfile instanceof SymbolicExecutionJavaProfile) { ImmutableList result = - super.computeTermLabelConfiguration(); + super.computeTermLabelConfiguration(); // Make sure that the term labels of symbolic execution are also supported // by the new environment. result = result.prepend(SymbolicExecutionJavaProfile .getSymbolicExecutionTermLabelConfigurations( - SymbolicExecutionJavaProfile - .isTruthValueEvaluationEnabled(sourceInitConfig))); + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); return result; } else { return super.computeTermLabelConfiguration(); @@ -765,13 +767,13 @@ protected ImmutableList computeTermLabelConfiguration() Profile sourceProfile = sourceInitConfig.getProfile(); if (sourceProfile instanceof SymbolicExecutionJavaProfile) { ImmutableList result = - super.computeTermLabelConfiguration(); + super.computeTermLabelConfiguration(); // Make sure that the term labels of symbolic execution are also supported // by the new environment. result = result.prepend(SymbolicExecutionJavaProfile .getSymbolicExecutionTermLabelConfigurations( - SymbolicExecutionJavaProfile - .isTruthValueEvaluationEnabled(sourceInitConfig))); + SymbolicExecutionJavaProfile + .isTruthValueEvaluationEnabled(sourceInitConfig))); return result; } else { return super.computeTermLabelConfiguration(); @@ -781,7 +783,7 @@ protected ImmutableList computeTermLabelConfiguration() } // Create new InitConfig final InitConfig initConfig = - new InitConfig(sourceInitConfig.getServices().copy(profile, false)); + 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 @@ -793,14 +795,14 @@ protected ImmutableList computeTermLabelConfiguration() : null; initConfig.setSettings(clonedSettings); initConfig.setTaclet2Builder( - (HashMap>) sourceInitConfig.getTaclet2Builder() - .clone()); + (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)); + sourceJustiInfo.getJustification(taclet)); } for (BuiltInRule rule : initConfig.builtInRules()) { RuleJustification origJusti = sourceJustiInfo.getJustification(rule); diff --git a/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java b/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java index 23a70913479..bc34b6eaf8a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java +++ b/key.core/src/main/java/de/uka/ilkd/key/control/KeYEnvironment.java @@ -77,7 +77,7 @@ public KeYEnvironment(U ui, InitConfig initConfig) { * @param initConfig The loaded project. */ public KeYEnvironment(U ui, InitConfig initConfig, Proof loadedProof, - @Nullable ProofScriptEntry proofScript, ReplayResult replayResult) { + @Nullable ProofScriptEntry proofScript, ReplayResult replayResult) { this.ui = ui; this.initConfig = initConfig; this.loadedProof = loadedProof; diff --git a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java index 2f6215b5ca9..25b9e8ecac0 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java +++ b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java @@ -89,7 +89,7 @@ public static class File extends KeyAst { if (ctx.problem() != null && ctx.problem().proofScript() != null) { KeYParser.ProofScriptContext pctx = ctx.problem().proofScript(); Location location = new Location(url, - Position.newOneBased(pctx.ps.getLine(), pctx.ps.getCharPositionInLine())); + Position.newOneBased(pctx.ps.getLine(), pctx.ps.getCharPositionInLine())); String text = pctx.ps.getText(); return new ProofScriptEntry(StringUtil.trim(text, '"'), location); diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java index 89e20a76793..fcf5c100944 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java @@ -22,13 +22,13 @@ import de.uka.ilkd.key.speclang.SLEnvInput; import de.uka.ilkd.key.util.ProgressMonitor; -import org.jspecify.annotations.Nullable; import org.key_project.util.collection.DefaultImmutableSet; import org.key_project.util.collection.ImmutableSet; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; /** diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index b0671244d8d..65bc6b3304a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -15,6 +15,20 @@ import java.util.zip.ZipFile; import de.uka.ilkd.key.java.Position; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.ZipFile; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.nparser.KeYLexer; import de.uka.ilkd.key.nparser.ProofScriptEntry; @@ -36,30 +50,18 @@ import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.util.ExceptionHandlerException; -import org.antlr.runtime.MismatchedTokenException; -import org.jspecify.annotations.Nullable; + import org.key_project.util.collection.Pair; import org.key_project.util.java.IOUtil; import org.antlr.runtime.MismatchedTokenException; import org.key_project.util.reflection.ClassLoaderUtil; + +import org.antlr.runtime.MismatchedTokenException; +import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -import java.nio.file.*; -import java.util.*; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.zip.ZipFile; - /** *

* This class provides the basic functionality to load something in KeY. The loading process is done @@ -212,7 +214,7 @@ public boolean hasErrors() { // format: (expected, found) mismatchErrors = new HashMap<>(); mismatchErrors.put(new Pair<>(KeYLexer.SEMI, KeYLexer.COMMA), - "there may be only one declaration per line"); + "there may be only one declaration per line"); missedErrors = new HashMap<>(); missedErrors.put(KeYLexer.RPAREN, "closing parenthesis"); @@ -238,19 +240,19 @@ public boolean hasErrors() { * the loaded {@link InitConfig}. */ public AbstractProblemLoader(File file, List classPath, File bootClassPath, - List includes, Profile profileOfNewProofs, boolean forceNewProfileOfNewProofs, - ProblemLoaderControl control, - boolean askUiToSelectAProofObligationIfNotDefinedByLoadedFile, - Properties poPropertiesToForce) { + List includes, Profile profileOfNewProofs, boolean forceNewProfileOfNewProofs, + ProblemLoaderControl control, + boolean askUiToSelectAProofObligationIfNotDefinedByLoadedFile, + Properties poPropertiesToForce) { this.file = file; this.classPath = classPath; this.bootClassPath = bootClassPath; this.control = control; this.profileOfNewProofs = - profileOfNewProofs != null ? profileOfNewProofs : AbstractProfile.getDefaultProfile(); + profileOfNewProofs != null ? profileOfNewProofs : AbstractProfile.getDefaultProfile(); this.forceNewProfileOfNewProofs = forceNewProfileOfNewProofs; this.askUiToSelectAProofObligationIfNotDefinedByLoadedFile = - askUiToSelectAProofObligationIfNotDefinedByLoadedFile; + askUiToSelectAProofObligationIfNotDefinedByLoadedFile; this.poPropertiesToForce = poPropertiesToForce; this.includes = includes; } @@ -318,14 +320,14 @@ protected void loadEnvironment() throws ProofInputException, IOException { LOGGER.info("Loading environment from " + file); envInput = createEnvInput(fileRepo); LOGGER.debug( - "Environment load took " + PerfScope.formatTime(System.nanoTime() - timeBeforeEnv)); + "Environment load took " + PerfScope.formatTime(System.nanoTime() - timeBeforeEnv)); problemInitializer = createProblemInitializer(fileRepo); var beforeInitConfig = System.nanoTime(); LOGGER.info("Creating init config"); initConfig = createInitConfig(); initConfig.setFileRepo(fileRepo); LOGGER.debug( - "Init config took " + PerfScope.formatTime(System.nanoTime() - beforeInitConfig)); + "Init config took " + PerfScope.formatTime(System.nanoTime() - beforeInitConfig)); if (!problemInitializer.getWarnings().isEmpty() && !ignoreWarnings) { control.reportWarnings(problemInitializer.getWarnings()); } @@ -391,18 +393,18 @@ protected ProblemLoaderException recoverParserErrorMessage(Exception e) { final String readable = missedErrors.get(mte.expecting); final String token = readable == null ? "token id " + mte.expecting : readable; final String msg = "Syntax error: missing " + token - + (occurrence == null ? "" : " at " + occurrence.getText()) + " statement (" - + mte.input.getSourceName() + ":" + mte.line + ")"; + + (occurrence == null ? "" : " at " + occurrence.getText()) + " statement (" + + mte.input.getSourceName() + ":" + mte.line + ")"; return new ProblemLoaderException(this, msg, mte); // TODO other ANTLR exceptions } else { final org.antlr.runtime.MismatchedTokenException mte = - (MismatchedTokenException) c0; + (MismatchedTokenException) c0; final String genericMsg = "expected " + mte.expecting + ", but found " + mte.c; final String readable = - mismatchErrors.get(new Pair<>(mte.expecting, mte.c)); + mismatchErrors.get(new Pair<>(mte.expecting, mte.c)); final String msg = "Syntax error: " + (readable == null ? genericMsg : readable) - + " (" + mte.input.getSourceName() + ":" + mte.line + ")"; + + " (" + mte.input.getSourceName() + ":" + mte.line + ")"; return new ProblemLoaderException(this, msg, mte); } } @@ -451,7 +453,7 @@ protected EnvInput createEnvInput(FileRepo fileRepo) throws IOException { ret = new SLEnvInput(".", classPath, bootClassPath, profileOfNewProofs, includes); } else { ret = new SLEnvInput(file.getParentFile().getAbsolutePath(), classPath, - bootClassPath, profileOfNewProofs, includes); + bootClassPath, profileOfNewProofs, includes); } ret.setJavaFile(file.getAbsolutePath()); ret.setIgnoreOtherJavaFiles(loadSingleJavaFile); @@ -511,26 +513,26 @@ protected EnvInput createEnvInput(FileRepo fileRepo) throws IOException { Path unzippedProof = tmpDir.resolve(proofFilename.toPath()); return new KeYUserProblemFile(unzippedProof.toString(), unzippedProof.toFile(), - fileRepo, control, profileOfNewProofs, false); + fileRepo, control, profileOfNewProofs, false); } else if (filename.endsWith(".key") || filename.endsWith(".proof") || filename.endsWith(".proof.gz")) { // KeY problem specification or saved proof return new KeYUserProblemFile(filename, file, fileRepo, control, profileOfNewProofs, - filename.endsWith(".proof.gz")); + filename.endsWith(".proof.gz")); } else if (file.isDirectory()) { // directory containing java sources, probably enriched // by specifications return new SLEnvInput(file.getPath(), classPath, bootClassPath, profileOfNewProofs, - includes); + includes); } else { if (filename.lastIndexOf('.') != -1) { throw new IllegalArgumentException("Unsupported file extension '" - + filename.substring(filename.lastIndexOf('.')) + "' of read-in file " - + filename + ". Allowed extensions are: .key, .proof, .java or " - + "complete directories."); + + filename.substring(filename.lastIndexOf('.')) + "' of read-in file " + + filename + ". Allowed extensions are: .key, .proof, .java or " + + "complete directories."); } else { throw new FileNotFoundException( - "File or directory\n\t " + filename + "\n not found."); + "File or directory\n\t " + filename + "\n not found."); } } } @@ -652,7 +654,7 @@ private LoadedPOContainer loadByChosenContract(String chooseContract) { protected ProofAggregate createProof(LoadedPOContainer poContainer) throws ProofInputException { ProofAggregate proofList = - problemInitializer.startProver(initConfig, poContainer.getProofOblInput()); + problemInitializer.startProver(initConfig, poContainer.getProofOblInput()); for (Proof p : proofList.getProofs()) { // register proof @@ -707,7 +709,7 @@ private ReplayResult replayProof(Proof proof) { assert envInput instanceof KeYUserProblemFile; IntermediatePresentationProofFileParser parser = - new IntermediatePresentationProofFileParser(proof); + new IntermediatePresentationProofFileParser(proof); problemInitializer.tryReadProof(parser, (KeYUserProblemFile) envInput); parserResult = parser.getResult(); @@ -718,14 +720,14 @@ private ReplayResult replayProof(Proof proof) { // able to load proofs that used it even if the user has currently // turned OSS off. StrategyProperties newProps = - proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); newProps.setProperty(StrategyProperties.OSS_OPTIONS_KEY, StrategyProperties.OSS_ON); Strategy.updateStrategySettings(proof, newProps); OneStepSimplifier.refreshOSS(proof); replayer = new IntermediateProofReplayer(this, proof, parserResult); replayResult = - replayer.replay(problemInitializer.getListener(), problemInitializer.getProgMon()); + replayer.replay(problemInitializer.getListener(), problemInitializer.getProgMon()); lastTouchedNode = replayResult.getLastSelectedGoal() != null ? replayResult.getLastSelectedGoal().node() @@ -746,13 +748,13 @@ private ReplayResult replayProof(Proof proof) { } status += (status.isEmpty() ? "Proof replayed successfully." : "\n\n") + (replayResult != null ? replayResult.getStatus() - : "Error while loading proof."); + : "Error while loading proof."); if (replayResult != null) { errors.addAll(replayResult.getErrors()); } StrategyProperties newProps = - proof.getSettings().getStrategySettings().getActiveStrategyProperties(); + proof.getSettings().getStrategySettings().getActiveStrategyProperties(); newProps.setProperty(StrategyProperties.OSS_OPTIONS_KEY, ossStatus); Strategy.updateStrategySettings(proof, newProps); OneStepSimplifier.refreshOSS(proof); diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java index 3a3084f921a..fe601ce9f33 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java @@ -111,7 +111,7 @@ public class IntermediateProofReplayer { private final LinkedList> queue = new LinkedList<>(); - public record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third){} + public record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third) {} /** Maps join node IDs to previously seen join partners */ private final HashMap> joinPartnerNodes = new HashMap<>(); @@ -265,7 +265,7 @@ public Result replay(ProblemInitializer.ProblemInitializerListener listener, if (appInterm instanceof MergeAppIntermediate joinAppInterm) { HashSet partnerNodesInfo = - joinPartnerNodes.get(((MergeAppIntermediate) appInterm).getId()); + joinPartnerNodes.get(((MergeAppIntermediate) appInterm).getId()); if (partnerNodesInfo == null || partnerNodesInfo.size() < joinAppInterm.getNrPartners()) { @@ -804,12 +804,12 @@ private MergeRuleBuiltInRuleApp instantiateJoinApp(final MergeAppIntermediate jo ImmutableList joinPartners = ImmutableSLList.nil(); for (PartnerNode partnerNodeInfo : partnerNodesInfo) { - var ownSEState = + var ownSEState = sequentToSETriple(currNode, joinApp.posInOccurrence(), services); var partnerSEState = sequentToSETriple(partnerNodeInfo.first, partnerNodeInfo.second, services); - assert ownSEState.third().equals(partnerSEState.third()) + assert ownSEState.programCounter().equals(partnerSEState.programCounter()) : "Cannot merge incompatible program counters"; joinPartners = joinPartners.append( diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java index 41c90dcf3fc..95b4a37b93d 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/SpecificationRepository.java @@ -3,6 +3,11 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.proof.mgt; +import java.net.URI; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.UnaryOperator; + import de.uka.ilkd.key.java.JavaInfo; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.java.Statement; @@ -29,18 +34,15 @@ import de.uka.ilkd.key.speclang.jml.translation.ProgramVariableCollection; import de.uka.ilkd.key.speclang.translation.SLTranslationException; import de.uka.ilkd.key.util.MiscTools; -import org.jspecify.annotations.Nullable; + import org.key_project.logic.Name; import org.key_project.logic.sort.Sort; import org.key_project.util.collection.*; + +import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.net.URI; -import java.util.*; -import java.util.Map.Entry; -import java.util.function.UnaryOperator; - /** * Central storage for all specification elements, such as contracts, class axioms, and loop * invariants. Provides methods for adding such elements to the repository, and for retrieving them @@ -61,29 +63,39 @@ public final class SpecificationRepository { private final ContractFactory cf; private final Map, ImmutableSet> contracts = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map, ImmutableSet> operationContracts = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map, ImmutableSet> wdChecks = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Map contractsByName = new LinkedHashMap<>(); - private final Map> contractTargets = new LinkedHashMap<>(); + private final Map> contractTargets = + new LinkedHashMap<>(); private final Map> invs = new LinkedHashMap<>(); private final Map> axioms = new LinkedHashMap<>(); - private final Map> initiallyClauses = new LinkedHashMap<>(); + private final Map> initiallyClauses = + new LinkedHashMap<>(); private final Map> proofs = new LinkedHashMap<>(); - private final Map, LoopSpecification> loopInvs = new LinkedHashMap<>(); - private final Map> blockContracts = new LinkedHashMap<>(); - private final Map> loopContracts = new LinkedHashMap<>(); + private final Map, LoopSpecification> loopInvs = + new LinkedHashMap<>(); + private final Map> blockContracts = + new LinkedHashMap<>(); + private final Map> loopContracts = + new LinkedHashMap<>(); /** * A map which relates each loop statement its starting line number and set of loop contracts. */ - private final Map, ImmutableSet> loopContractsOnLoops = new LinkedHashMap<>(); - private final Map> mergeContracts = new LinkedHashMap<>(); - private final Map unlimitedToLimited = new LinkedHashMap<>(); - private final Map limitedToUnlimited = new LinkedHashMap<>(); - private final Map> unlimitedToLimitTaclets = new LinkedHashMap<>(); + private final Map, ImmutableSet> loopContractsOnLoops = + new LinkedHashMap<>(); + private final Map> mergeContracts = + new LinkedHashMap<>(); + private final Map unlimitedToLimited = + new LinkedHashMap<>(); + private final Map limitedToUnlimited = + new LinkedHashMap<>(); + private final Map> unlimitedToLimitTaclets = + new LinkedHashMap<>(); /** *

@@ -98,13 +110,13 @@ public final class SpecificationRepository { *

*/ private final Map> allClassAxiomsCache = - new LinkedHashMap<>(); + new LinkedHashMap<>(); private final Services services; private final TermBuilder tb; private final Map contractCounters = - new de.uka.ilkd.key.util.LinkedHashMap<>(); + new de.uka.ilkd.key.util.LinkedHashMap<>(); public SpecificationRepository(Services services) { this.services = services; @@ -131,7 +143,7 @@ private static String getUniqueNameForObserver(IObserverFunction obs) { } private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, - IObserverFunction unlimited, TermServices services) { + IObserverFunction unlimited, TermServices services) { final TermBuilder tb = services.getTermBuilder(); assert limited.arity() == unlimited.arity(); @@ -139,7 +151,7 @@ private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, final Term[] subs = new Term[limited.arity()]; for (int i = 0; i < subs.length; i++) { final TermSV argSV = SchemaVariableFactory.createTermSV(new Name("t" + i), - limited.argSort(i), false, false); + limited.argSort(i), false, false); subs[i] = tb.var(argSV); } final Term limitedTerm = tb.func(limited, subs); @@ -149,14 +161,14 @@ private static Taclet getLimitedToUnlimitedTaclet(IObserverFunction limited, final RewriteTacletBuilder tacletBuilder = new RewriteTacletBuilder<>(); tacletBuilder.setFind(limitedTerm); tacletBuilder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(Sequent.EMPTY_SEQUENT, - ImmutableSLList.nil(), unlimitedTerm)); + ImmutableSLList.nil(), unlimitedTerm)); tacletBuilder.setName( - MiscTools.toValidTacletName("unlimit " + getUniqueNameForObserver(unlimited))); + MiscTools.toValidTacletName("unlimit " + getUniqueNameForObserver(unlimited))); return tacletBuilder.getTaclet(); } private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, - IObserverFunction unlimited, TermServices services) { + IObserverFunction unlimited, TermServices services) { assert limited.arity() == unlimited.arity(); final TermBuilder tb = services.getTermBuilder(); @@ -164,7 +176,7 @@ private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, final Term[] subs = new Term[limited.arity()]; for (int i = 0; i < subs.length; i++) { final TermSV argSV = SchemaVariableFactory.createTermSV(new Name("t" + i), - limited.argSort(i), false, false); + limited.argSort(i), false, false); subs[i] = tb.var(argSV); } final Term limitedTerm = tb.func(limited, subs); @@ -175,12 +187,12 @@ private static Taclet getUnlimitedToLimitedTaclet(IObserverFunction limited, tacletBuilder.setFind(tb.func(unlimited, subs)); final SequentFormula cf = new SequentFormula(tb.equals(limitedTerm, unlimitedTerm)); final Sequent addedSeq = - Sequent.createAnteSequent(Semisequent.EMPTY_SEMISEQUENT.insertFirst(cf).semisequent()); + Sequent.createAnteSequent(Semisequent.EMPTY_SEMISEQUENT.insertFirst(cf).semisequent()); tacletBuilder.addTacletGoalTemplate(new RewriteTacletGoalTemplate(addedSeq, - ImmutableSLList.nil(), tb.func(unlimited, subs))); + ImmutableSLList.nil(), tb.func(unlimited, subs))); tacletBuilder.setApplicationRestriction(RewriteTaclet.IN_SEQUENT_STATE); tacletBuilder.setName( - MiscTools.toValidTacletName("limit " + getUniqueNameForObserver(unlimited))); + MiscTools.toValidTacletName("limit " + getUniqueNameForObserver(unlimited))); tacletBuilder.addRuleSet(new RuleSet(new Name("limitObserver"))); return tacletBuilder.getTaclet(); @@ -211,9 +223,8 @@ private IObserverFunction getCanonicalFormForKJT(IObserverFunction obs, KeYJavaT final String name = pm.getMethodDeclaration().getName(); final int numParams = pm.getParameterDeclarationCount(); final ImmutableList candidatePMs = - services.getJavaInfo().getAllProgramMethods(kjt); - outer: - for (IProgramMethod candidatePM : candidatePMs) { + services.getJavaInfo().getAllProgramMethods(kjt); + outer: for (IProgramMethod candidatePM : candidatePMs) { if (candidatePM.getMethodDeclaration().getName().equals(name) && candidatePM.getParameterDeclarationCount() == numParams) { for (int i = 0; i < numParams; i++) { @@ -240,7 +251,7 @@ private IObserverFunction getCanonicalFormForKJT(IObserverFunction obs, KeYJavaT } private ImmutableSet> getOverridingMethods(KeYJavaType kjt, - IProgramMethod pm) { + IProgramMethod pm) { ImmutableList> result = ImmutableSLList.nil(); // static methods and constructors are not overriden @@ -260,7 +271,7 @@ private ImmutableSet> getOverridingMethods( } public ImmutableSet> getOverridingTargets(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { if (target instanceof IProgramMethod) { return getOverridingMethods(kjt, (IProgramMethod) target); } else { @@ -351,19 +362,19 @@ assert getCanonicalFormForKJT(contract.getTarget(), contract.getKJT()) private void registerContract(Contract contract) { final Pair target = - new Pair<>(contract.getKJT(), contract.getTarget()); + new Pair<>(contract.getKJT(), contract.getTarget()); registerContract(contract, target); } private void registerContract(Contract contract, - final ImmutableSet> targets) { + final ImmutableSet> targets) { for (Pair impl : targets) { registerContract(contract, impl); } } private void registerContract(Contract contract, - Pair targetPair) { + Pair targetPair) { LOGGER.trace("Contract registered {}", contract); if (!WellDefinednessCheck.isOn() && contract instanceof WellDefinednessCheck) { return; @@ -376,30 +387,30 @@ private void registerContract(Contract contract, : "Tried to add a contract with a non-unique name: " + name; assert !name.contains(CONTRACT_COMBINATION_MARKER) : "Tried to add a contract with a name containing the" + " reserved character " - + CONTRACT_COMBINATION_MARKER + ": " + name; + + CONTRACT_COMBINATION_MARKER + ": " + name; assert contract.id() != Contract.INVALID_ID : "Tried to add a contract with an invalid id!"; contracts.put(targetPair, getContracts(targetKJT, targetMethod).add(contract)); if (contract instanceof FunctionalOperationContract) { operationContracts.put(new Pair<>(targetKJT, (IProgramMethod) targetMethod), - getOperationContracts(targetKJT, (IProgramMethod) targetMethod) - .add((FunctionalOperationContract) contract)); + getOperationContracts(targetKJT, (IProgramMethod) targetMethod) + .add((FunctionalOperationContract) contract)); // Create new well-definedness check final MethodWellDefinedness mwd = - new MethodWellDefinedness((FunctionalOperationContract) contract, services); + new MethodWellDefinedness((FunctionalOperationContract) contract, services); registerContract(mwd); } else if (contract instanceof DependencyContract && contract.getOrigVars().atPres.isEmpty() && targetMethod.getContainerType() - .equals(services.getJavaInfo().getJavaLangObject())) { + .equals(services.getJavaInfo().getJavaLangObject())) { // Create or extend a well-definedness check for a class invariant final Term deps = - contract.getAccessible(services.getTypeConverter().getHeapLDT().getHeap()); + contract.getAccessible(services.getTypeConverter().getHeapLDT().getHeap()); final Term mby = contract.getMby(); final String invName = "JML model class invariant in " + targetKJT.getName(); final ClassInvariant inv = new ClassInvariantImpl(invName, invName, targetKJT, - contract.getVisibility(), tb.tt(), contract.getOrigVars().self); + contract.getVisibility(), tb.tt(), contract.getOrigVars().self); ClassWellDefinedness cwd = - new ClassWellDefinedness(inv, targetMethod, deps, mby, services); + new ClassWellDefinedness(inv, targetMethod, deps, mby, services); final ImmutableSet cwds = getWdClassChecks(targetKJT); if (!cwds.isEmpty()) { assert cwds.size() == 1; @@ -413,9 +424,9 @@ private void registerContract(Contract contract, && contract.getOrigVars().atPres.isEmpty()) { // Create or extend a well-definedness check for a model field MethodWellDefinedness mwd = - new MethodWellDefinedness((DependencyContract) contract, services); + new MethodWellDefinedness((DependencyContract) contract, services); final ImmutableSet mwds = - getWdMethodChecks(targetKJT, targetMethod); + getWdMethodChecks(targetKJT, targetMethod); if (!mwds.isEmpty()) { assert mwds.size() == 1; final MethodWellDefinedness oldMwd = mwds.iterator().next(); @@ -441,12 +452,12 @@ private void unregisterContract(Contract contract) { contracts.put(tp, contracts.get(tp).remove(contract)); if (contract instanceof FunctionalOperationContract) { final Pair tp2 = - new Pair<>(tp.first, (IProgramMethod) tp.second); + new Pair<>(tp.first, (IProgramMethod) tp.second); operationContracts.put(tp2, - operationContracts.get(tp2).remove((FunctionalOperationContract) contract)); + operationContracts.get(tp2).remove((FunctionalOperationContract) contract)); if (!getWdChecks(contract.getKJT(), contract.getTarget()).isEmpty()) { ImmutableSet wdcs = - getWdChecks(contract.getKJT(), contract.getTarget()); + getWdChecks(contract.getKJT(), contract.getTarget()); for (WellDefinednessCheck wdc : wdcs) { if (wdc instanceof MethodWellDefinedness && ((MethodWellDefinedness) wdc).getMethodContract().equals(contract)) { @@ -478,7 +489,7 @@ private void createContractsFromInitiallyClause(InitiallyClause inv, KeYJavaType if (!JMLInfoExtractor.isHelper(pm)) { final ImmutableSet oldContracts = getContracts(kjt, pm); ImmutableSet oldFuncContracts = - DefaultImmutableSet.nil(); + DefaultImmutableSet.nil(); for (Contract old : oldContracts) { if (old instanceof FunctionalOperationContract) { oldFuncContracts = oldFuncContracts.add((FunctionalOperationContract) old); @@ -530,7 +541,7 @@ private static ImmutableSet removeWdChecks(ImmutableSet cont */ private void registerWdCheck(WellDefinednessCheck check) { ImmutableSet checks = - getWdChecks(check.getKJT(), check.getTarget()).add(check); + getWdChecks(check.getKJT(), check.getTarget()).add(check); wdChecks.put(new Pair<>(check.getKJT(), check.getTarget()), checks); } @@ -542,7 +553,7 @@ private void registerWdCheck(WellDefinednessCheck check) { */ private void unregisterWdCheck(WellDefinednessCheck check) { wdChecks.put(new Pair<>(check.getKJT(), check.getTarget()), - getWdChecks(check.getKJT(), check.getTarget()).remove(check)); + getWdChecks(check.getKJT(), check.getTarget()).remove(check)); } /** @@ -563,7 +574,7 @@ private ImmutableSet getWdChecks(KeYJavaType kjt) { * Returns all registered (atomic) well-definedness checks for the passed target and kjt. */ private ImmutableSet getWdChecks(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { assert kjt != null; assert target != null; target = getCanonicalFormForKJT(target, kjt); @@ -603,7 +614,7 @@ private ImmutableSet getWdMethodChecks(KeYJavaType kjt) { * Returns all registered (atomic) well-definedness method checks for the passed target and kjt. */ private ImmutableSet getWdMethodChecks(KeYJavaType kjt, - IObserverFunction target) { + IObserverFunction target) { assert kjt != null; assert target != null; ImmutableSet result = DefaultImmutableSet.nil(); @@ -638,7 +649,7 @@ private ImmutableSet getWdClassChecks(KeYJavaType kjt) { */ @SuppressWarnings("unchecked") private void mapValueSets(Map> map, - UnaryOperator op, Services services) { + UnaryOperator op, Services services) { for (Entry> entry : map.entrySet()) { final K key = entry.getKey(); final ImmutableSet oldSet = entry.getValue(); @@ -669,7 +680,7 @@ private void mapValueSets(Map void mapValues(Map map, - UnaryOperator op, Services services) { + UnaryOperator op, Services services) { for (Entry entry : map.entrySet()) { final K key = entry.getKey(); final V oldContract = entry.getValue(); @@ -725,10 +736,10 @@ public ImmutableSet getAllContracts() { */ public ImmutableSet getContracts(KeYJavaType kjt, IObserverFunction target) { target = - getCanonicalFormForKJT(Objects.requireNonNull(target), Objects.requireNonNull(kjt)); + getCanonicalFormForKJT(Objects.requireNonNull(target), Objects.requireNonNull(kjt)); final Pair pair = new Pair<>(kjt, target); final ImmutableSet result = - WellDefinednessCheck.isOn() ? contracts.get(pair) : removeWdChecks(contracts.get(pair)); + WellDefinednessCheck.isOn() ? contracts.get(pair) : removeWdChecks(contracts.get(pair)); return result == null ? DefaultImmutableSet.nil() : result; } @@ -736,7 +747,7 @@ public ImmutableSet getContracts(KeYJavaType kjt, IObserverFunction ta * Returns all registered (atomic) operation contracts for the passed operation. */ public ImmutableSet getOperationContracts(KeYJavaType kjt, - IProgramMethod pm) { + IProgramMethod pm) { pm = (IProgramMethod) getCanonicalFormForKJT(pm, kjt); final Pair pair = new Pair<>(kjt, pm); final ImmutableSet result = operationContracts.get(pair); @@ -748,14 +759,14 @@ public ImmutableSet getOperationContracts(KeYJavaTy * the passed modality. */ public ImmutableSet getOperationContracts(KeYJavaType kjt, - IProgramMethod pm, Modality.JavaModalityKind modalityKind) { + IProgramMethod pm, Modality.JavaModalityKind modalityKind) { ImmutableSet result = getOperationContracts(kjt, pm); final boolean transactionModality = - modalityKind.transaction(); + modalityKind.transaction(); final Modality.JavaModalityKind matchModality = transactionModality ? ((modalityKind == Modality.JavaModalityKind.DIA_TRANSACTION) - ? Modality.JavaModalityKind.DIA - : Modality.JavaModalityKind.BOX) + ? Modality.JavaModalityKind.DIA + : Modality.JavaModalityKind.BOX) : modalityKind; for (FunctionalOperationContract contract : result) { if (!contract.getModalityKind().equals(matchModality) @@ -782,7 +793,7 @@ public Contract getContractByName(String name) { ImmutableSet baseContracts = DefaultImmutableSet.nil(); for (String baseName : baseNames) { FunctionalOperationContract baseContract = - (FunctionalOperationContract) contractsByName.get(baseName); + (FunctionalOperationContract) contractsByName.get(baseName); if (baseContract == null) { return null; } @@ -799,7 +810,7 @@ public Contract getContractByName(String name) { public ImmutableSet getInheritedContracts(Contract contract) { ImmutableSet result = DefaultImmutableSet.nil().add(contract); final ImmutableSet> subs = - getOverridingTargets(contract.getKJT(), contract.getTarget()); + getOverridingTargets(contract.getKJT(), contract.getTarget()); for (Pair sub : subs) { for (Contract subContract : getContracts(sub.first, sub.second)) { if (subContract.id() == contract.id()) { @@ -839,13 +850,13 @@ public void addContract(Contract contract) { // register and inherit final ImmutableSet> impls = - getOverridingTargets(contract.getKJT(), contract.getTarget()) - .add(new Pair<>(contract.getKJT(), contract.getTarget())); + getOverridingTargets(contract.getKJT(), contract.getTarget()) + .add(new Pair<>(contract.getKJT(), contract.getTarget())); registerContract(contract, impls); if (!contractTargets.get(contract.getKJT()).contains(contract.getTarget())) { throw new IllegalStateException( - "target " + contract.getTarget() + " missing for contract " + contract); + "target " + contract.getTarget() + " missing for contract " + contract); } } @@ -878,7 +889,7 @@ public FunctionalOperationContract combineOperationContracts( // sort contracts alphabetically (for determinism) FunctionalOperationContract[] contractsArray = - toCombine.toArray(new FunctionalOperationContract[toCombine.size()]); + toCombine.toArray(new FunctionalOperationContract[toCombine.size()]); Arrays.sort(contractsArray, Comparator.comparing(SpecificationElement::getName)); return cf.union(contractsArray); @@ -925,7 +936,7 @@ public void addClassInvariant(ClassInvariant inv) { ClassWellDefinedness cwd = cwds.iterator().next(); unregisterContract(cwd); cwd = cwd.combine(new ClassWellDefinedness(inv, cwd.getTarget(), null, null, services), - services); + services); registerContract(cwd); } @@ -941,13 +952,13 @@ public void addClassInvariant(ClassInvariant inv) { for (KeYJavaType sub : subs) { ClassInvariant subInv = inv.setKJT(sub); final IObserverFunction subTarget = - subInv.isStatic() ? services.getJavaInfo().getStaticInv(sub) - : services.getJavaInfo().getInv(); + subInv.isStatic() ? services.getJavaInfo().getStaticInv(sub) + : services.getJavaInfo().getInv(); invs.put(sub, getClassInvariants(sub).add(subInv)); final ImmutableSet subCwds = getWdClassChecks(sub); if (subCwds.isEmpty()) { registerContract( - new ClassWellDefinedness(subInv, subTarget, null, null, services)); + new ClassWellDefinedness(subInv, subTarget, null, null, services)); } else { for (ClassWellDefinedness cwd : subCwds) { unregisterContract(cwd); @@ -980,7 +991,7 @@ public void createContractsFromInitiallyClauses() throws SLTranslationException createContractsFromInitiallyClause(inv, kjt); if (VisibilityModifier.allowsInheritance(inv.getVisibility())) { final ImmutableList subs = - services.getJavaInfo().getAllSubtypes(kjt); + services.getJavaInfo().getAllSubtypes(kjt); for (KeYJavaType sub : subs) { createContractsFromInitiallyClause(inv, sub); } @@ -1062,7 +1073,7 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { staticInvDef = tb.and(staticInvDef, inv.getInv(null, services)); } else { freeStaticInvDef = - tb.and(freeStaticInvDef, inv.getInv(selfVar, services)); + tb.and(freeStaticInvDef, inv.getInv(selfVar, services)); } } } @@ -1070,9 +1081,9 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { invDef = tb.tf().createTerm(Equality.EQV, tb.inv(tb.var(selfVar)), invDef); staticInvDef = tb.tf().createTerm(Equality.EQV, tb.staticInv(kjt), staticInvDef); freeInvDef = tb.tf().createTerm(Equality.EQV, - tb.invFree(tb.var(selfVar)), freeInvDef); + tb.invFree(tb.var(selfVar)), freeInvDef); freeStaticInvDef = tb.tf().createTerm(Equality.EQV, - tb.staticInvFree(kjt), freeStaticInvDef); + tb.staticInvFree(kjt), freeStaticInvDef); final IObserverFunction invSymbol = services.getJavaInfo().getInv(); final IObserverFunction staticInvSymbol = services.getJavaInfo().getStaticInv(kjt); @@ -1081,24 +1092,24 @@ public ImmutableSet getClassAxioms(KeYJavaType selfKjt) { .getStaticInvFree(kjt); final ClassAxiom invRepresentsAxiom = - new RepresentsAxiom("Class invariant axiom for " + kjt.getFullName(), invSymbol, - kjt, new Private(), null, invDef, selfVar, ImmutableSLList.nil(), null); + new RepresentsAxiom("Class invariant axiom for " + kjt.getFullName(), invSymbol, + kjt, new Private(), null, invDef, selfVar, ImmutableSLList.nil(), null); result = result.add(invRepresentsAxiom); final ClassAxiom staticInvRepresentsAxiom = new RepresentsAxiom( - "Static class invariant axiom for " + kjt.getFullName(), staticInvSymbol, kjt, - new Private(), null, staticInvDef, null, ImmutableSLList.nil(), null); + "Static class invariant axiom for " + kjt.getFullName(), staticInvSymbol, kjt, + new Private(), null, staticInvDef, null, ImmutableSLList.nil(), null); result = result.add(staticInvRepresentsAxiom); final ClassAxiom invFreeRepresentsAxiom = new RepresentsAxiom( - "Free class invariant axiom for " + kjt.getFullName(), freeInvSymbol, kjt, - new Private(), null, freeInvDef, selfVar, ImmutableSLList.nil(), null); + "Free class invariant axiom for " + kjt.getFullName(), freeInvSymbol, kjt, + new Private(), null, freeInvDef, selfVar, ImmutableSLList.nil(), null); result = result.add(invFreeRepresentsAxiom); final ClassAxiom staticFreeInvRepresentsAxiom = new RepresentsAxiom( - "Free static class invariant axiom for " + kjt.getFullName(), - freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, - ImmutableSLList.nil(), null); + "Free static class invariant axiom for " + kjt.getFullName(), + freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, + ImmutableSLList.nil(), null); result = result.add(staticFreeInvRepresentsAxiom); } @@ -1114,7 +1125,7 @@ freeStaticInvSymbol, kjt, new Private(), null, freeStaticInvDef, null, } final ClassAxiom queryAxiom = new QueryAxiom("Query axiom for " + pm.getName() - + "_" + sb + " in " + selfKjt.getFullName(), pm, selfKjt); + + "_" + sb + " in " + selfKjt.getFullName(), pm, selfKjt); result = result.add(queryAxiom); } } @@ -1143,7 +1154,7 @@ private ImmutableSet getModelMethodAxioms() { List heaps = HeapContext.getModifiableHeaps(services, false); for (LocationVariable heap : heaps) { atPreVars.put(heap, - tb.atPreVar(heap.name().toString(), heap.sort(), false)); + tb.atPreVar(heap.name().toString(), heap.sort(), false)); } LocationVariable resultVar = tb.resultVar(pm, false); @@ -1152,10 +1163,10 @@ private ImmutableSet getModelMethodAxioms() { // We need to construct an inheritance chain of contracts // starting at the bottom ImmutableList lookupContracts = - ImmutableSLList.nil(); + ImmutableSLList.nil(); ImmutableSet cs = getOperationContracts(kjt, pm); ImmutableList superTypes = - services.getJavaInfo().getAllSupertypes(kjt); + services.getJavaInfo().getAllSupertypes(kjt); for (KeYJavaType superType : superTypes) { for (FunctionalOperationContract fop : cs) { if (fop.getSpecifiedIn().equals(superType)) { @@ -1165,9 +1176,9 @@ private ImmutableSet getModelMethodAxioms() { } for (FunctionalOperationContract fop : lookupContracts) { Term representsFromContract = fop.getRepresentsAxiom(heaps.get(0), selfVar, - paramVars, tb.resultVar(pm, false), atPreVars, services); + paramVars, tb.resultVar(pm, false), atPreVars, services); Term preContract = - fop.getPre(heaps, selfVar, paramVars, atPreVars, services); + fop.getPre(heaps, selfVar, paramVars, atPreVars, services); if (preContract == null) { preContract = tb.tt(); } @@ -1179,11 +1190,11 @@ private ImmutableSet getModelMethodAxioms() { // (pm.isProtected() ? new Protected() : // (pm.isPublic() ? new Public() : null)); final ClassAxiom modelMethodRepresentsAxiom = - new RepresentsAxiom( - "Definition axiom for " + pm.getName() + " in " - + kjt.getFullName(), - pm, kjt, new Private(), preContract, representsFromContract, - selfVar, paramVars, atPreVars); + new RepresentsAxiom( + "Definition axiom for " + pm.getName() + " in " + + kjt.getFullName(), + pm, kjt, new Private(), preContract, representsFromContract, + selfVar, paramVars, atPreVars); result = result.add(modelMethodRepresentsAxiom); break; } @@ -1193,24 +1204,24 @@ pm, kjt, new Private(), preContract, representsFromContract, continue; } Term preFromContract = - fop.getPre(heaps, selfVar, paramVars, atPreVars, services); + fop.getPre(heaps, selfVar, paramVars, atPreVars, services); Term freePreFromContract = - fop.getFreePre(heaps, selfVar, paramVars, atPreVars, services); + fop.getFreePre(heaps, selfVar, paramVars, atPreVars, services); Term postFromContract = fop.getPost(heaps, selfVar, paramVars, resultVar, - null, atPreVars, services); + null, atPreVars, services); Term freePostFromContract = fop.getFreePost(heaps, selfVar, paramVars, - resultVar, null, atPreVars, services); + resultVar, null, atPreVars, services); if (preFromContract != null && ((postFromContract != null && postFromContract != tb.tt()) - || (freePostFromContract != null - && freePostFromContract != tb.tt()))) { + || (freePostFromContract != null + && freePostFromContract != tb.tt()))) { Term mbyFromContract = - fop.hasMby() ? fop.getMby(selfVar, paramVars, services) : null; + fop.hasMby() ? fop.getMby(selfVar, paramVars, services) : null; final ClassAxiom modelMethodContractAxiom = new ContractAxiom( - "Contract axiom for " + pm.getName() + " in " + kjt.getName(), pm, - kjt, new Private(), preFromContract, freePreFromContract, - postFromContract, freePostFromContract, mbyFromContract, atPreVars, - selfVar, resultVar, paramVars); + "Contract axiom for " + pm.getName() + " in " + kjt.getName(), pm, + kjt, new Private(), preFromContract, freePreFromContract, + postFromContract, freePostFromContract, mbyFromContract, atPreVars, + selfVar, resultVar, paramVars); result = result.add(modelMethodContractAxiom); } } @@ -1311,7 +1322,7 @@ public ImmutableSet getProofs(Contract atomicContract) { */ public ImmutableSet getProofs(KeYJavaType kjt, IObserverFunction target) { final ImmutableSet> targets = - getOverridingTargets(kjt, target).add(new Pair<>(kjt, target)); + getOverridingTargets(kjt, target).add(new Pair<>(kjt, target)); ImmutableSet result = DefaultImmutableSet.nil(); for (Map.Entry> entry : proofs.entrySet()) { final ProofOblInput po = entry.getKey(); @@ -1319,7 +1330,7 @@ public ImmutableSet getProofs(KeYJavaType kjt, IObserverFunction target) if (po instanceof ContractPO) { final Contract contract = ((ContractPO) po).getContract(); final Pair pair = - new Pair<>(contract.getKJT(), contract.getTarget()); + new Pair<>(contract.getKJT(), contract.getTarget()); if (targets.contains(pair)) { result = result.union(sop); } @@ -1478,7 +1489,8 @@ public void addLoopInvariant(final LoopSpecification inv) { * @return all block contracts for the specified block. */ public ImmutableSet getBlockContracts(StatementBlock block) { - var b = new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); + var b = + new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); final ImmutableSet contracts = blockContracts.get(b); if (contracts == null) { return DefaultImmutableSet.nil(); @@ -1535,7 +1547,7 @@ public ImmutableSet getMergeContracts(MergePointStatement mps) { * @param modalityKind the given modality. */ public ImmutableSet getBlockContracts(final StatementBlock block, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getBlockContracts(block); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (BlockContract contract : result) { @@ -1548,7 +1560,7 @@ public ImmutableSet getBlockContracts(final StatementBlock block, } public ImmutableSet getLoopContracts(final StatementBlock block, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getLoopContracts(block); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (LoopContract contract : result) { @@ -1568,7 +1580,7 @@ public ImmutableSet getLoopContracts(final StatementBlock block, * @return the set of resulting loop statements. */ public ImmutableSet getLoopContracts(final LoopStatement loop, - final Modality.JavaModalityKind modalityKind) { + final Modality.JavaModalityKind modalityKind) { ImmutableSet result = getLoopContracts(loop); final Modality.JavaModalityKind matchModality = getMatchModalityKind(modalityKind); for (LoopContract contract : result) { @@ -1598,7 +1610,8 @@ public void addBlockContract(final BlockContract contract) { */ public void addBlockContract(final BlockContract contract, boolean addFunctionalContract) { final StatementBlock block = contract.getBlock(); - var b =new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); + var b = + new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); blockContracts.put(b, getBlockContracts(block).add(contract)); if (addFunctionalContract) { @@ -1619,7 +1632,8 @@ public void addBlockContract(final BlockContract contract, boolean addFunctional */ public void removeBlockContract(final BlockContract contract) { final StatementBlock block = contract.getBlock(); - var b = new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); + var b = + new BlockContractKey(block, block.getParentClass(), block.getStartPosition().line()); blockContracts.compute(b, (k, set) -> set.remove(contract)); } @@ -1643,12 +1657,13 @@ public void addLoopContract(final LoopContract contract) { public void addLoopContract(final LoopContract contract, boolean addFunctionalContract) { if (contract.isOnBlock()) { final StatementBlock block = contract.getBlock(); - var b = new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); + var b = + new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); loopContracts.put(b, getLoopContracts(block).add(contract)); } else { final LoopStatement loop = contract.getLoop(); final Pair b = - new Pair<>(loop, loop.getStartPosition().line()); + new Pair<>(loop, loop.getStartPosition().line()); loopContractsOnLoops.put(b, getLoopContracts(loop).add(contract)); } @@ -1675,13 +1690,14 @@ public void addLoopContract(final LoopContract contract, boolean addFunctionalCo public void removeLoopContract(final LoopContract contract) { if (contract.isOnBlock()) { final StatementBlock block = contract.getBlock(); - var b =new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); + var b = + new LoopContractKey(block, block.getParentClass(), block.getStartPosition().line()); loopContracts.compute(b, (k, set) -> set.remove(contract)); } else { final LoopStatement loop = contract.getLoop(); final Pair b = - new Pair<>(loop, loop.getStartPosition().line()); + new Pair<>(loop, loop.getStartPosition().line()); loopContractsOnLoops.compute(b, (k, set) -> set.remove(contract)); } @@ -1747,11 +1763,11 @@ public Pair> limitObs(IObserverFunction if (limited == null) { final String baseName = - ((ProgramElementName) obs.name()).getProgramName() + LIMIT_SUFFIX; + ((ProgramElementName) obs.name()).getProgramName() + LIMIT_SUFFIX; final Sort heapSort = services.getTypeConverter().getHeapLDT().targetSort(); limited = new ObserverFunction(baseName, obs.sort(), obs.getType(), heapSort, - obs.getContainerType(), obs.isStatic(), obs.getParamTypes(), - obs.getHeapCount(services), obs.getStateCount()); + obs.getContainerType(), obs.isStatic(), obs.getParamTypes(), + obs.getHeapCount(services), obs.getStateCount()); unlimitedToLimited.put(obs, limited); limitedToUnlimited.put(limited, obs); diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java index 680730a0880..dd3d38b097f 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java @@ -565,8 +565,8 @@ private Term useCaseFormula(TermLabelState termLabelState, Services services, Ru } private Guard prepareGuard(final Instantiation inst, - final KeYJavaType booleanKJT, LoopInvariantBuiltInRuleApp loopRuleApp, - final TermServices services) { + final KeYJavaType booleanKJT, LoopInvariantBuiltInRuleApp loopRuleApp, + final TermServices services) { final TermBuilder tb = services.getTermBuilder(); final ProgramElementName guardVarName = new ProgramElementName(tb.newName("b")); final LocationVariable guardVar = new LocationVariable(guardVarName, booleanKJT); diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java index 8c46e8163cf..029765a474f 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java @@ -165,7 +165,8 @@ public String toString() { // The merge loop SymbolicExecutionState mergedState = - new SymbolicExecutionState(thisSEState.first(), thisSEState.second(), newGoal.node()); + new SymbolicExecutionState(thisSEState.symbolicState(), thisSEState.pathCondition(), + newGoal.node()); LinkedHashSet newNames = new LinkedHashSet<>(); LinkedHashSet sideConditionsToProve = new LinkedHashSet<>(); HashMap mergePartnerNodesToStates = new HashMap<>(); @@ -183,7 +184,7 @@ public String toString() { mergePartnerNodesToStates.put(state.getCorrespondingNode(), state); MergeStateEntry mergeResult = - mergeStates(mergeRule, mergedState, state, thisSEState.third(), + mergeStates(mergeRule, mergedState, state, thisSEState.programCounter(), mergeRuleApp.getDistinguishingFormula(), services); newNames.addAll(mergeResult.second); sideConditionsToProve.addAll(mergeResult.third); @@ -206,7 +207,7 @@ public String toString() { for (MergePartner mergePartner : mergePartners) { closeMergePartnerGoal(newGoal.node(), mergePartner.getGoal(), mergePartner.getPio(), mergedState, mergePartnerNodesToStates.get(mergePartner.getGoal().node()), - thisSEState.third(), newNames); + thisSEState.programCounter(), newNames); } // Delete previous sequents @@ -239,7 +240,7 @@ public String toString() { } // Add new succedent (symbolic state & program counter) - final Term succedentFormula = tb.apply(mergedState.first, thisSEState.third()); + final Term succedentFormula = tb.apply(mergedState.first, thisSEState.programCounter()); final SequentFormula newSuccedent = new SequentFormula(succedentFormula); newGoal.addFormula(newSuccedent, new PosInOccurrence(newSuccedent, PosInTerm.getTopLevel(), false)); @@ -294,14 +295,14 @@ public String toString() { *

* Override this method for special merge procedures. * - * @param mergeRule The merge procedure to use for the merge. - * @param state1 First state to merge. - * @param state2 Second state to merge. - * @param programCounter The formula \<{ ... }\> phi consisting of the common program - * counter and the post condition. + * @param mergeRule The merge procedure to use for the merge. + * @param state1 First state to merge. + * @param state2 Second state to merge. + * @param programCounter The formula \<{ ... }\> phi consisting of the common program + * counter and the post condition. * @param distinguishingFormula The user-specified distinguishing formula. May be null (for - * automatic generation). - * @param services The services object. + * automatic generation). + * @param services The services object. * @return A new merged SE state (U*,C*) which is a weakening of the original states. */ @SuppressWarnings("unused") @@ -675,7 +676,8 @@ public static ImmutableList findPotentialMergePartners(Goal goal, final ImmutableList allGoals = services.getProof().openGoals(); - final SymbolicExecutionStateWithProgCnt ownSEState = sequentToSETriple(goal.node(), pio, services); + final SymbolicExecutionStateWithProgCnt ownSEState = + sequentToSETriple(goal.node(), pio, services); // Find potential partners -- for which isApplicable is true and // they have the same program counter (and post condition). @@ -694,7 +696,7 @@ public static ImmutableList findPotentialMergePartners(Goal goal, final SymbolicExecutionStateWithProgCnt partnerSEState = sequentToSETriple(g.node(), gPio, services); - if (ownSEState.third().equals(partnerSEState.third())) { + if (ownSEState.programCounter().equals(partnerSEState.programCounter())) { potentialPartners = potentialPartners.prepend(new MergePartner(g, gPio)); @@ -714,5 +716,5 @@ public interface MergeRuleProgressListener { } public record MergeStateEntry(SymbolicExecutionState first, LinkedHashSet second, - LinkedHashSet third) {} + LinkedHashSet third) {} } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java index 538e1dd3865..2591e2e9b72 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java @@ -135,16 +135,16 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * the discriminating condition, the second and third elements are the respective parts for the * if and else branch. * - * @param v Variable to return the update for. - * @param state1 First state to evaluate. - * @param state2 Second state to evaluate. + * @param v Variable to return the update for. + * @param state1 First state to evaluate. + * @param state2 Second state to evaluate. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first - * component). + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first + * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( LocationVariable v, SymbolicExecutionState state1, SymbolicExecutionState state2, @@ -177,17 +177,17 @@ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( * the triple is the discriminating condition, the second and third elements are the respective * parts for the if and else branch. * - * @param state1 First state to evaluate. - * @param state2 Second state to evaluate. - * @param ifTerm The if term. + * @param state1 First state to evaluate. + * @param state2 Second state to evaluate. + * @param ifTerm The if term. * @param elseTerm The else term. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first - * component). + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first + * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( SymbolicExecutionState state1, SymbolicExecutionState state2, Term ifTerm, diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java index 51a1f6b8315..2c9430af2b6 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java @@ -204,7 +204,9 @@ public void addRequires(LabeledParserRuleContext label) { addClause(REQUIRES, label); } - public record Abbreviation(LabeledParserRuleContext first, LabeledParserRuleContext second, LabeledParserRuleContext thrid){} + public record Abbreviation(LabeledParserRuleContext typeName, + LabeledParserRuleContext abbrevName, + LabeledParserRuleContext abbreviatedTerm) {} public Abbreviation[] getAbbreviations() { /* weigl: prepare for future use of generated abbreviations from JML specifications */ diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java index a08ba75e23d..e1f4e5837f2 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java @@ -605,12 +605,11 @@ private void translateAssignable(Context context, ProgramVariableCollection prog */ private ImmutableList registerAbbreviationVariables(TextualJMLSpecCase textualSpecCase, Context context, ProgramVariableCollection progVars, ContractClauses clauses) { - for (Triple abbrv : textualSpecCase - .getAbbreviations()) { + for (TextualJMLSpecCase.Abbreviation abbrv : textualSpecCase.getAbbreviations()) { final KeYJavaType abbrKJT = - services.getJavaInfo().getKeYJavaType(abbrv.first.first.getText()); + services.getJavaInfo().getKeYJavaType(abbrv.typeName().first.getText()); final ProgramElementName abbrVarName = - new ProgramElementName(abbrv.second.first.getText()); + new ProgramElementName(abbrv.abbrevName().first.getText()); final LocationVariable abbrVar = new LocationVariable(abbrVarName, abbrKJT, true, true); assert abbrVar.isGhost() : "specification parameter not ghost"; services.getNamespaces().programVariables().addSafely(abbrVar); @@ -619,7 +618,7 @@ private ImmutableList registerAbbreviationVariables(TextualJMLSpecCase tex // parameter Term rhs = new JmlIO(services).context(context).parameters(progVars.paramVars) .atPres(progVars.atPres).atBefore(progVars.atBefores) - .translateTerm(abbrv.third); + .translateTerm(abbrv.abbreviatedTerm()); clauses.abbreviations = clauses.abbreviations.append(tb.elementary(tb.var(abbrVar), rhs)); } @@ -1232,9 +1231,8 @@ public Contract createJMLDependencyContract(KeYJavaType kjt, LocationVariable ta var context = Context.inClass(kjt, false, tb); // translateToTerm expression - Triple dep = - new JmlIO(services).context(context).translateDependencyContract(originalDep); - return cf.dep(kjt, targetHeap, dep, dep.first.isStatic() ? null : context.selfVar()); + var dep = new JmlIO(services).context(context).translateDependencyContract(originalDep); + return cf.dep(kjt, targetHeap, dep, dep.first().isStatic() ? null : context.selfVar()); } public Contract createJMLDependencyContract(KeYJavaType kjt, TextualJMLDepends textualDep) { @@ -1507,8 +1505,7 @@ public void translateJmlAssertCondition(final JmlAssert jmlAssert, final IProgra } public @Nullable String checkSetStatementAssignee(Term assignee) { - if (assignee.op() instanceof LocationVariable) { - var variable = (LocationVariable) assignee.op(); + if (assignee.op() instanceof LocationVariable variable) { if (variable.isGhost()) { return null; } else { diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java index d6513a40daa..903d5ee7b4b 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java @@ -1048,7 +1048,7 @@ public TranslatedDependencyContract depends(SLExpression lhs, Term rhs, SLExpres + ", given" + lhs.getTerm().sub(0).op()); } - return new Triple<>((IObserverFunction) lhs.getTerm().op(), rhs, + return new TranslatedDependencyContract((IObserverFunction) lhs.getTerm().op(), rhs, mby == null ? null : mby.getTerm()); } diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java index 983d03b0f7f..122148732ad 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java @@ -1,3 +1,6 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed under the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.speclang.njml; import de.uka.ilkd.key.logic.Term; @@ -5,7 +8,7 @@ /** * - * @author Alexander Weigl + * @author Alexander Weigl * @version 1 (23.04.24) */ public record TranslatedDependencyContract(IObserverFunction first, Term second, Term third) { diff --git a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java index 5e1ba42bb90..fe7bd9b75a6 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java +++ b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java @@ -35,7 +35,8 @@ * @see StrategyPropertyValueDefinition */ public class StrategySettingsDefinition { - public record StategySettingEntry(String name, int order, IDefaultStrategyPropertiesFactory factory){} + public record StategySettingEntry(String name, int order, + IDefaultStrategyPropertiesFactory factory) {} private static final ArrayList STD_FURTHER_DEFAULTS; diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java index b318d10e027..332988a3461 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java +++ b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/MergeRuleUtils.java @@ -1031,7 +1031,7 @@ public static SymbolicExecutionState sequentToSEPair(Node node, PosInOccurrence SymbolicExecutionStateWithProgCnt triple = sequentToSETriple(node, pio, services); - return new SymbolicExecutionState(triple.first, triple.second, node); + return new SymbolicExecutionState(triple.symbolicState(), triple.pathCondition(), node); } /** @@ -1102,7 +1102,8 @@ public static ImmutableList sequentsToSEPairs( sequentToSETriple(node, sequentInfo.getPio(), services); result = result.prepend( - new SymbolicExecutionState(partnerSEState.first(), partnerSEState.second(), node)); + new SymbolicExecutionState(partnerSEState.symbolicState(), + partnerSEState.pathCondition(), node)); } return result; diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java index f4ec6a50bd3..ea86a015579 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java +++ b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java @@ -7,6 +7,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.pp.LogicPrinter; import de.uka.ilkd.key.proof.Node; + import org.jspecify.annotations.Nullable; /** @@ -14,10 +15,14 @@ * parallel update, a path condition in form of a JavaDL formula, and a program counter in form of a * JavaDL formula with non-empty Java Block (and a possible post condition as first, and only, sub * term). - * + * @param symbolicState The symbolic state (parallel update). + * @param pathCondition The path condition (formula). + * @param programCounter The program counter: Formula with non-empty Java block and post + * condition as only sub term. + * @param correspondingNode The node corresponding to this SE state. * @author Dominic Scheurer */ -public record SymbolicExecutionStateWithProgCnt(Term first, Term second, Term third, +public record SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, Term programCounter, @Nullable Node correspondingNode) { /** * @param symbolicState The symbolic state (parallel update). @@ -25,43 +30,31 @@ public record SymbolicExecutionStateWithProgCnt(Term first, Term second, Term th * @param programCounter The program counter: Formula with non-empty Java block and post * condition as only sub term. */ - public SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, - Term programCounter) { - super(symbolicState, pathCondition, programCounter); + public SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, Term programCounter) { + this(symbolicState, pathCondition, programCounter, null); } - /** - * @param symbolicState The symbolic state (parallel update). - * @param pathCondition The path condition (formula). - * @param programCounter The program counter: Formula with non-empty Java block and post - * condition as only sub term. - * @param correspondingNode The node corresponding to this SE state. - */ - public SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, - Term programCounter, Node correspondingNode) { - this(symbolicState, pathCondition, programCounter); - this.correspondingNode = correspondingNode; - } + /** * @return The symbolic state. */ public Term getSymbolicState() { - return first; + return symbolicState; } /** * @return The path condition. */ public Term getPathCondition() { - return second; + return pathCondition; } /** * @return The program counter (and post condition). */ public Term getProgramCounter() { - return third; + return programCounter; } /** @@ -71,18 +64,11 @@ public Node getCorrespondingNode() { return correspondingNode; } - /** - * @param correspondingNode The node corresponding to this SE state. - */ - public void setCorrespondingNode(Node correspondingNode) { - this.correspondingNode = correspondingNode; - } - /** * @return The corresponding SE state (without the program counter). */ public SymbolicExecutionState toSymbolicExecutionState() { - return new SymbolicExecutionState(first, second); + return new SymbolicExecutionState(symbolicState, pathCondition); } @Override diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java b/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java index f186080c594..c71823dc978 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/proverules/ProveRulesTest.java @@ -10,7 +10,6 @@ import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.KeYEnvironment; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; -import de.uka.ilkd.key.parser.Location; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.init.Profile; import de.uka.ilkd.key.proof.io.ProblemLoaderException; @@ -19,7 +18,6 @@ import de.uka.ilkd.key.util.HelperClassForTests; import de.uka.ilkd.key.util.LinkedHashMap; -import org.key_project.util.collection.Pair; import org.key_project.util.helper.FindResources; import org.junit.jupiter.api.DynamicTest; diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java index 8966026c803..87d614a794b 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/ProveTest.java @@ -11,7 +11,6 @@ import de.uka.ilkd.key.control.KeYEnvironment; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; import de.uka.ilkd.key.nparser.ProofScriptEntry; -import de.uka.ilkd.key.parser.Location; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.io.AbstractProblemLoader; import de.uka.ilkd.key.proof.io.ProblemLoaderException; @@ -104,12 +103,12 @@ private void runKey(String file, TestProperty testProperty) throws Exception { try { LOGGER.info("({}) Start proving", caseId); // Initialize KeY environment and load proof. - Pair, Pair> pair = + Pair, ProofScriptEntry> pair = load(keyFile); LOGGER.info("({}) Proving done", caseId); env = pair.first; - Pair script = pair.second; + ProofScriptEntry script = pair.second; loadedProof = env.getLoadedProof(); AbstractProblemLoader.ReplayResult replayResult = env.getReplayResult(); @@ -183,14 +182,14 @@ private void reload(File proofFile, Proof loadedProof) throws Exception { * want to use a different strategy. */ private void autoMode(KeYEnvironment env, Proof loadedProof, - Pair script) throws Exception { + ProofScriptEntry script) throws Exception { // Run KeY prover. if (script == null) { // auto mode env.getProofControl().startAndWaitForAutoMode(loadedProof); } else { // ... script - ProofScriptEngine pse = new ProofScriptEngine(script.first, script.second); + ProofScriptEngine pse = new ProofScriptEngine(script.script(), script.location()); pse.execute(env.getUi(), env.getLoadedProof()); } } diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java index d7aa7c78ee0..c48a8afeb85 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/performance/DataRecordingTestFile.java @@ -28,7 +28,7 @@ public DataRecordingTestFile(TestProperty testProperty, String path, @Override protected void autoMode(KeYEnvironment env, Proof loadedProof, - ProofScriptEntry script) throws Exception { + ProofScriptEntry script) throws Exception { // Run KeY prover. if (script == null) { DataRecordingStrategy strategy = new DataRecordingStrategy(loadedProof, this); diff --git a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java index 25d5dedd8fc..af762f4e45a 100644 --- a/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java +++ b/key.core/src/test/java/de/uka/ilkd/key/proof/runallproofs/proofcollection/TestFile.java @@ -262,7 +262,7 @@ protected void reload(boolean verbose, File proofFile, Proof loadedProof, boolea * want to use a different strategy. */ protected void autoMode(KeYEnvironment env, Proof loadedProof, - ProofScriptEntry script) throws Exception { + ProofScriptEntry script) throws Exception { // Run KeY prover. if (script == null) { // auto mode diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java index b17ae902c0b..0925b8cb48f 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java @@ -404,7 +404,8 @@ private JPanel createDefaultPanel(StrategySelectionComponents components) { existingPredefs[0] = "Defaults"; int i = 1; - for (StrategySettingsDefinition.StategySettingEntry furtherDefault : DEFINITION.getFurtherDefaults()) { + for (StrategySettingsDefinition.StategySettingEntry furtherDefault : DEFINITION + .getFurtherDefaults()) { existingPredefs[i] = furtherDefault.name(); i++; } diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java index 02385e81654..619100c08ea 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java @@ -83,7 +83,7 @@ static String findAndPopNearestMatch(String l, List right) { return current; } - public record QueueEntry(int idxLeft, int idxRight, int distance){} + public record QueueEntry(int idxLeft, int idxRight, int distance) {} static List findPairs(List left, List right) { List pairs = new ArrayList<>(left.size() + right.size()); diff --git a/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java b/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java index c0cf68fe6c7..d0d7781110d 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java @@ -20,7 +20,7 @@ import de.uka.ilkd.key.macros.ProofMacroFinishedInfo; import de.uka.ilkd.key.macros.SkipMacro; import de.uka.ilkd.key.macros.scripts.ProofScriptEngine; -import de.uka.ilkd.key.parser.Location; +import de.uka.ilkd.key.nparser.ProofScriptEntry; import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.ProofAggregate; @@ -44,7 +44,6 @@ import org.key_project.util.collection.ImmutableList; import org.key_project.util.collection.ImmutableSLList; import org.key_project.util.collection.ImmutableSet; -import org.key_project.util.collection.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -159,13 +158,17 @@ public void taskFinished(TaskFinishedInfo info) { ProblemLoader problemLoader = (ProblemLoader) info.getSource(); if (problemLoader.hasProofScript()) { try { - Pair script = problemLoader.readProofScript(); - ProofScriptEngine pse = new ProofScriptEngine(script.first, script.second); - this.taskStarted(new DefaultTaskStartedInfo(TaskKind.Macro, "Script started", 0)); - pse.execute(this, proof); - // The start and end messages are fake to persuade the system ... - // All this here should refactored anyway ... - this.taskFinished(new ProofMacroFinishedInfo(new SkipMacro(), proof)); + ProofScriptEntry script = problemLoader.readProofScript(); + if (script != null) { + ProofScriptEngine pse = + new ProofScriptEngine(script.script(), script.location()); + this.taskStarted( + new DefaultTaskStartedInfo(TaskKind.Macro, "Script started", 0)); + pse.execute(this, proof); + // The start and end messages are fake to persuade the system ... + // All this here should refactored anyway ... + this.taskFinished(new ProofMacroFinishedInfo(new SkipMacro(), proof)); + } } catch (Exception e) { LOGGER.debug("", e); System.exit(-1); diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java index 30ada1c137a..95d7ebc8509 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/RuleStatistics.java @@ -3,14 +3,14 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.slicing; -import de.uka.ilkd.key.rule.Rule; - import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import de.uka.ilkd.key.rule.Rule; + /** * Simple data object to store a mapping of rules to various counters. * @@ -40,7 +40,8 @@ public void addApplication(Rule rule, boolean branches) { StatisticEntry entry = map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); - map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications, entry.numberOfInitialUselessApplications)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, + entry.numberOfUselessApplications, entry.numberOfInitialUselessApplications)); } /** @@ -55,7 +56,8 @@ public void addUselessApplication(Rule rule, boolean branches) { StatisticEntry entry = map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); - map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, + entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications)); } /** @@ -70,7 +72,8 @@ public void addInitialUselessApplication(Rule rule, boolean branches) { StatisticEntry entry = map.computeIfAbsent(name, it -> new StatisticEntry(0, 0, 0)); - map.put(name, new StatisticEntry(entry.numberOfApplications + 1, entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications + 1)); + map.put(name, new StatisticEntry(entry.numberOfApplications + 1, + entry.numberOfUselessApplications + 1, entry.numberOfInitialUselessApplications + 1)); } /** @@ -83,8 +86,10 @@ public void addInitialUselessApplication(Rule rule, boolean branches) { */ public List sortBy(Comparator comparator) { return map.entrySet().stream() - .map(entry -> new RuleStatisticEntry(entry.getKey(), entry.getValue().numberOfApplications, - entry.getValue().numberOfUselessApplications, entry.getValue().numberOfInitialUselessApplications)) + .map(entry -> new RuleStatisticEntry(entry.getKey(), + entry.getValue().numberOfApplications, + entry.getValue().numberOfUselessApplications, + entry.getValue().numberOfInitialUselessApplications)) .sorted(comparator) .collect(Collectors.toList()); } @@ -100,21 +105,25 @@ public boolean branches(String rule) { /** * Usage statistic of a rule. *

- * TODO weigl: refactoring task, combine {@link RuleStatisticEntry} with {@link StatisticEntry} to avoid repetition. + * TODO weigl: refactoring task, combine {@link RuleStatisticEntry} with {@link StatisticEntry} + * to avoid repetition. * * @param ruleName * @param numberOfApplications * @param numberOfUselessApplications * @param numberOfInitialUselessApplications */ - public record RuleStatisticEntry(String ruleName, int numberOfApplications, int numberOfUselessApplications, int numberOfInitialUselessApplications) { + public record RuleStatisticEntry(String ruleName, int numberOfApplications, + int numberOfUselessApplications, int numberOfInitialUselessApplications) { } /** * Usage statistic of a rule. + * * @param numberOfApplications * @param numberOfUselessApplications * @param numberOfInitialUselessApplications */ - public record StatisticEntry(int numberOfApplications, int numberOfUselessApplications, int numberOfInitialUselessApplications){} + public record StatisticEntry(int numberOfApplications, int numberOfUselessApplications, + int numberOfInitialUselessApplications) {} } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/analysis/DependencyAnalyzer.java b/keyext.slicing/src/main/java/org/key_project/slicing/analysis/DependencyAnalyzer.java index f01a9de6985..df768c0f273 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/analysis/DependencyAnalyzer.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/analysis/DependencyAnalyzer.java @@ -444,7 +444,7 @@ private void deduplicateRuleApps() { // (for obvious reasons, we don't care about origin labels here -> wrapper) Map, Set> foundDupes = new HashMap<>(); graph.outgoingGraphEdgesOf(node).forEach(t -> { - Node proofNode = t.first; + Node proofNode = t.fromNode(); // this analysis algorithm does not support proofs with State Merging if (proofNode.getAppliedRuleApp() instanceof MergeRuleBuiltInRuleApp @@ -465,7 +465,7 @@ private void deduplicateRuleApps() { } // Only try to deduplicate the addition of new formulas. // It is unlikely that two closed goals are derived using the same formula. - GraphNode produced = t.second; + GraphNode produced = t.toNode(); if (!(produced instanceof TrackedFormula)) { return; } @@ -473,7 +473,7 @@ private void deduplicateRuleApps() { .computeIfAbsent( new EqualsModProofIrrelevancyWrapper<>(proofNode.getAppliedRuleApp()), _a -> new LinkedHashSet<>()) - .add(t.third.getProofStep()); + .add(t.annotation().getProofStep()); }); // scan dupes, try to find a set of mergable rule applications diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java index 320c5d43756..3e4dd6b7851 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java @@ -119,18 +119,26 @@ public Stream incomingEdgesOf(GraphNode node) { return graph.incomingEdgesOf(node).stream().map(AnnotatedEdge::getProofStep); } - public record IncomingEdge(Node first, GraphNode second, AnnotatedEdge third){} + /** + * Represents an edge in the dependency graph. + * + * @param fromNode the outgoing node of the edge + * @param toNode the incoming node of the edge + * @param annotation annotation associated to the edge + */ + public record Edge(Node fromNode, GraphNode toNode, AnnotatedEdge annotation) {} /** * @param node a graph node * @return the incoming (graph edges, graph sources) of that node */ - public Stream incomingGraphEdgesOf(GraphNode node) { + public Stream incomingGraphEdgesOf(GraphNode node) { if (!graph.containsVertex(node)) { return Stream.of(); } return graph.incomingEdgesOf(node).stream() - .map(edge -> new IncomingEdge(edge.getProofStep(), graph.getEdgeSource(edge), edge)); + .map( + edge -> new Edge(edge.getProofStep(), graph.getEdgeSource(edge), edge)); } /** @@ -148,12 +156,13 @@ public Stream outgoingEdgesOf(GraphNode node) { * @param node a graph node * @return the outgoing (graph edges, graph targets) of that node */ - public Stream outgoingGraphEdgesOf(GraphNode node) { + public Stream outgoingGraphEdgesOf(GraphNode node) { if (!graph.containsVertex(node)) { return Stream.of(); } return graph.outgoingEdgesOf(node).stream() - .map(edge -> new IncomingEdge(edge.getProofStep(), graph.getEdgeTarget(edge), edge)); + .map( + edge -> new Edge(edge.getProofStep(), graph.getEdgeTarget(edge), edge)); } /** @@ -281,7 +290,7 @@ public Stream inputsConsumedBy(Node proofStep) { * @return the outgoing edges of that node */ public Stream edgesUsing(GraphNode node) { - return outgoingGraphEdgesOf(node).map(it -> it.third); + return outgoingGraphEdgesOf(node).map(it -> it.annotation); } /** @@ -290,8 +299,8 @@ public Stream edgesUsing(GraphNode node) { */ public Stream edgesConsuming(GraphNode node) { return outgoingGraphEdgesOf(node) - .filter(it -> it.third.replacesInputNode()) - .map(it -> it.third); + .filter(it -> it.annotation.replacesInputNode()) + .map(it -> it.annotation); } /** @@ -300,7 +309,7 @@ public Stream edgesConsuming(GraphNode node) { */ public Stream edgesProducing(GraphNode node) { return incomingGraphEdgesOf(node) - .map(it -> it.third); + .map(it -> it.annotation); } /** @@ -393,12 +402,12 @@ public DependencyGraph removeChains() { // whose hyperedge should not connect more nodes // (otherwise we cannot remove the edge without // making the graph inconsistent) - Node startNode = incoming.get(0).first; + Node startNode = incoming.get(0).fromNode; if (edgesOf(startNode).size() != 1) { continue; } - GraphNode startGraphNode = incoming.get(0).second; - AnnotatedEdge edge = incoming.get(0).third; + GraphNode startGraphNode = incoming.get(0).toNode; + AnnotatedEdge edge = incoming.get(0).annotation; // get real initial node // (in case of repeated shortenings) @@ -412,9 +421,9 @@ public DependencyGraph removeChains() { // whose hyperedge should not connect more nodes // (otherwise we cannot remove the edge without // making the graph inconsistent) - Node endNode = outgoing.get(0).first; - GraphNode endGraphNode = outgoing.get(0).second; - var edge2 = outgoing.get(0).third; + Node endNode = outgoing.get(0).fromNode; + GraphNode endGraphNode = outgoing.get(0).toNode; + var edge2 = outgoing.get(0).annotation; if (edgesOf(endNode).size() != 1) { continue; } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java b/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java index ab4b78c1394..ca39d883a20 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/ui/RuleStatisticsDialog.java @@ -3,19 +3,20 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.slicing.ui; +import java.awt.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.*; +import java.util.List; +import javax.swing.*; + import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.configuration.Config; + import org.key_project.slicing.RuleStatistics; import org.key_project.slicing.RuleStatistics.RuleStatisticEntry; import org.key_project.slicing.analysis.AnalysisResults; -import javax.swing.*; -import java.awt.*; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.util.List; -import java.util.*; - /** * Dialog that displays the results of the dependency analysis algorithm. * @@ -58,7 +59,7 @@ private void createUI(Window window) { statisticsPane.setBackground(MainWindow.getInstance().getBackground()); statisticsPane.setSize(new Dimension(10, 360)); statisticsPane.setPreferredSize( - new Dimension(statisticsPane.getPreferredSize().width + 15, 360)); + new Dimension(statisticsPane.getPreferredSize().width + 15, 360)); JScrollPane scrollPane = new JScrollPane(statisticsPane); scrollPane.setBorder(BorderFactory.createEmptyBorder()); @@ -66,7 +67,7 @@ private void createUI(Window window) { Font myFont = UIManager.getFont(Config.KEY_FONT_PROOF_TREE); if (myFont != null) { statisticsPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, - Boolean.TRUE); + Boolean.TRUE); statisticsPane.setFont(myFont); } @@ -77,17 +78,17 @@ private void createUI(Window window) { int w = 50 + Math.max( - scrollPane.getPreferredSize().width, - buttonPane.getPreferredSize().width); + scrollPane.getPreferredSize().width, + buttonPane.getPreferredSize().width); int h = scrollPane.getPreferredSize().height + buttonPane.getPreferredSize().height + 100; setSize(w, h); statisticsPane.setText(genTable( - statistics.sortBy( - Comparator.comparing(RuleStatisticEntry::numberOfApplications) - .reversed()))); + statistics.sortBy( + Comparator.comparing(RuleStatisticEntry::numberOfApplications) + .reversed()))); statisticsPane.setCaretPosition(0); setLocationRelativeTo(window); } @@ -109,25 +110,29 @@ private JPanel constructButtonPanel(JEditorPane statisticsPane) { JButton sortButton1 = new JButton("Sort by name"); sortButton1.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy(Comparator.comparing(RuleStatisticEntry::ruleName)))); + statistics.sortBy(Comparator.comparing(RuleStatisticEntry::ruleName)))); statisticsPane.setCaretPosition(0); }); JButton sortButton2 = new JButton("Sort by total"); sortButton2.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfApplications).reversed()))); + statistics.sortBy( + Comparator.comparing(RuleStatisticEntry::numberOfApplications).reversed()))); statisticsPane.setCaretPosition(0); }); JButton sortButton3 = new JButton("Sort by useless"); sortButton3.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfUselessApplications).reversed()))); + statistics.sortBy(Comparator + .comparing(RuleStatisticEntry::numberOfUselessApplications).reversed()))); statisticsPane.setCaretPosition(0); }); JButton sortButton4 = new JButton("Sort by initial useless"); sortButton4.addActionListener(event -> { statisticsPane.setText(genTable( - statistics.sortBy(Comparator.comparing(RuleStatisticEntry::numberOfInitialUselessApplications).reversed()))); + statistics.sortBy( + Comparator.comparing(RuleStatisticEntry::numberOfInitialUselessApplications) + .reversed()))); statisticsPane.setCaretPosition(0); }); @@ -158,26 +163,31 @@ public void keyTyped(KeyEvent e) { */ private String genTable(List rules) { List columns = List.of("Rule name", "Total applications", "Useless applications", - "Initial useless applications"); + "Initial useless applications"); List> rows = new ArrayList<>(); // summary row int uniqueRules = rules.size(); int totalSteps = rules.stream().mapToInt(RuleStatisticEntry::numberOfApplications).sum(); - int uselessSteps = rules.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); - int initialUseless = rules.stream().mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); + int uselessSteps = + rules.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); + int initialUseless = + rules.stream().mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); rows.add(List.of(String.format("(all %d rules)", uniqueRules), Integer.toString(totalSteps), - Integer.toString(uselessSteps), Integer.toString(initialUseless))); + Integer.toString(uselessSteps), Integer.toString(initialUseless))); // next summary row List rulesBranching = - rules.stream().filter(it -> statistics.branches(it.ruleName())).toList(); + rules.stream().filter(it -> statistics.branches(it.ruleName())).toList(); int uniqueRules2 = rulesBranching.size(); - totalSteps = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfApplications).sum(); - uselessSteps = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); - initialUseless = rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); + totalSteps = + rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfApplications).sum(); + uselessSteps = + rulesBranching.stream().mapToInt(RuleStatisticEntry::numberOfUselessApplications).sum(); + initialUseless = rulesBranching.stream() + .mapToInt(RuleStatisticEntry::numberOfInitialUselessApplications).sum(); rows.add(List.of(String.format("(%d branching rules)", uniqueRules2), - Integer.toString(totalSteps), Integer.toString(uselessSteps), - Integer.toString(initialUseless))); + Integer.toString(totalSteps), Integer.toString(uselessSteps), + Integer.toString(initialUseless))); rules.forEach(a -> { String name = a.ruleName(); Integer all = a.numberOfApplications(); @@ -186,7 +196,7 @@ private String genTable(List rules) { rows.add(List.of(name, all.toString(), useless.toString(), iua.toString())); }); - return HtmlFactory.generateTable(columns, new boolean[]{false, false, false, false}, - Optional.of(new String[]{null, "right", "right", "right"}), rows, null); + return HtmlFactory.generateTable(columns, new boolean[] { false, false, false, false }, + Optional.of(new String[] { null, "right", "right", "right" }), rows, null); } } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java b/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java index 320042ea01b..930ea88a5b8 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/ui/ShowNodeInfoAction.java @@ -18,9 +18,7 @@ import org.key_project.slicing.DependencyTracker; import org.key_project.slicing.analysis.AnalysisResults; -import org.key_project.slicing.graph.AnnotatedEdge; -import org.key_project.slicing.graph.DependencyGraph; -import org.key_project.slicing.graph.DependencyGraph.IncomingEdge; +import org.key_project.slicing.graph.DependencyGraph.Edge; import org.key_project.slicing.graph.GraphNode; import org.key_project.util.collection.Pair; @@ -73,17 +71,17 @@ private void showDialog(Window parentWindow) { List graphNodes = new ArrayList<>(); List proofSteps = new ArrayList<>(); AnalysisResults analysisResults = tracker.getAnalysisResults(); - Function> nodeToTableRow = n -> { - proofSteps.add(n.first()); - graphNodes.add(n.second()); - var ruleName = n.first().getAppliedRuleApp().rule().displayName(); + Function> nodeToTableRow = n -> { + proofSteps.add(n.fromNode()); + graphNodes.add(n.toNode()); + var ruleName = n.fromNode().getAppliedRuleApp().rule().displayName(); return List.of( - Integer.toString(n.first().serialNr()), - analysisResults != null && !analysisResults.usefulSteps.contains(n.first()) + Integer.toString(n.fromNode().serialNr()), + analysisResults != null && !analysisResults.usefulSteps.contains(n.fromNode()) ? "" + ruleName + "" : ruleName, - n.third().replacesInputNode() ? "yes" : "no", - n.second().toString(false, false)); + n.annotation().replacesInputNode() ? "yes" : "no", + n.toNode().toString(false, false)); }; var idxFactory = new IndexFactory(); @@ -100,7 +98,7 @@ private void showDialog(Window parentWindow) { HtmlFactory.generateTable(headers2, clickable, Optional.empty(), outgoing, idxFactory); var useful = analysisResults != null ? tracker.getDependencyGraph().outgoingGraphEdgesOf(node) - .filter(t -> analysisResults.usefulSteps.contains(t.first())).count() + .filter(t -> analysisResults.usefulSteps.contains(t.fromNode())).count() : -1; var extraInfo = useful != -1 ? "

" + useful + " useful rule apps

" : ""; var previousDerivations = 0; diff --git a/keyext.slicing/src/test/java/org/key_project/slicing/DependencyGraphTest.java b/keyext.slicing/src/test/java/org/key_project/slicing/DependencyGraphTest.java index f2b7adc37ff..2b2769523ea 100644 --- a/keyext.slicing/src/test/java/org/key_project/slicing/DependencyGraphTest.java +++ b/keyext.slicing/src/test/java/org/key_project/slicing/DependencyGraphTest.java @@ -58,14 +58,14 @@ void basicTest() { var incomingClosedGoal = graph.incomingGraphEdgesOf(closedGoal).toList(); assertEquals(1, incomingClosedGoal.size()); - assertEquals(formB, incomingClosedGoal.get(0).second); + assertEquals(formB, incomingClosedGoal.get(0).toNode()); var incomingFormB = graph.incomingGraphEdgesOf(formB).toList(); assertEquals(2, incomingFormB.size()); - if (incomingFormB.get(0).second.equals(formA)) { - assertEquals(formC, incomingFormB.get(1).second); + if (incomingFormB.get(0).toNode().equals(formA)) { + assertEquals(formC, incomingFormB.get(1).toNode()); } else { - assertEquals(formA, incomingFormB.get(1).second); + assertEquals(formA, incomingFormB.get(1).toNode()); } assertTrue(graph.containsNode(formA)); From 3c1766584adf9d4f1e375b4abbe159bfba2eff70 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Wed, 24 Apr 2024 12:24:50 +0200 Subject: [PATCH 04/10] forgot ProofScriptEntry --- .../de/uka/ilkd/key/nparser/ProofScriptEntry.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java diff --git a/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java b/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java new file mode 100644 index 00000000000..1f76632362a --- /dev/null +++ b/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java @@ -0,0 +1,12 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed under the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0-only */ +package de.uka.ilkd.key.nparser; + +/** + * + * @author Alexander Weigl + * @version 1 (23.04.24) + */ +public record ProofScriptEntry(String script, de.uka.ilkd.key.parser.Location location) { +} From 8c620c6e51c63a1662933856c68848b80b135c9f Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 24 May 2024 11:16:26 +0200 Subject: [PATCH 05/10] fix compile errors due to merging --- .../src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java index 09c03fe98b4..a83ab68f267 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java @@ -192,7 +192,7 @@ public DependencyContract dep(KeYJavaType containerType, IObserverFunction pm, } public DependencyContract dep(KeYJavaType kjt, LocationVariable targetHeap, - TranslatedDependencyContract dep, LocationVariable selfVar) { + TranslatedDependencyContract dep, LocationVariable selfVar) { final ImmutableList paramVars = tb.paramVars(dep.first(), false); assert (selfVar == null) == dep.first().isStatic(); Map pres = new LinkedHashMap<>(); From 8e8b377417c008e8b5f74497869fa43375de2904 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Fri, 24 May 2024 11:23:32 +0200 Subject: [PATCH 06/10] fix error in expecting proof script if there is none --- .../java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index 65bc6b3304a..63bb8bb667e 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -679,12 +679,14 @@ public boolean hasProofScript() { } public @Nullable ProofScriptEntry readProofScript() throws ProofInputException { - assert envInput instanceof KeYUserProblemFile; KeYUserProblemFile kupf = (KeYUserProblemFile) envInput; return kupf.readProofScript(); } public @Nullable ProofScriptEntry getProofScript() throws ProblemLoaderException { + if (!hasProofScript()) { + return null; + } try { return readProofScript(); } catch (ProofInputException e) { From 101e28164d737a601eccfaaab3543d8ff4b32ec5 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 23 Nov 2024 17:10:02 +0100 Subject: [PATCH 07/10] reformat fix finalize() deprecation --- .../key/proof/io/AbstractProblemLoader.java | 19 ------------------- .../key/proof/mgt/ProofCorrectnessMgt.java | 8 -------- .../ilkd/key/gui/nodeviews/SequentView.java | 11 ----------- .../ilkd/key/gui/prooftree/ProofTreeView.java | 4 +--- 4 files changed, 1 insertion(+), 41 deletions(-) diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index 63bb8bb667e..95abdfc90ee 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -6,22 +6,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.URI; -import java.nio.file.*; -import java.util.*; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.util.zip.ZipFile; - -import de.uka.ilkd.key.java.Position; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.function.Consumer; @@ -54,9 +38,6 @@ import org.key_project.util.collection.Pair; import org.key_project.util.java.IOUtil; -import org.antlr.runtime.MismatchedTokenException; -import org.key_project.util.reflection.ClassLoaderUtil; - import org.antlr.runtime.MismatchedTokenException; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/ProofCorrectnessMgt.java b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/ProofCorrectnessMgt.java index 9e6b585c458..5a56e9992d1 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/ProofCorrectnessMgt.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/mgt/ProofCorrectnessMgt.java @@ -266,14 +266,6 @@ public ProofStatus getStatus() { return proofStatus; } - @Override - protected void finalize() throws Throwable { - removeProofListener(); - super.finalize(); - } - - - // ------------------------------------------------------------------------- // inner classes // ------------------------------------------------------------------------- diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/nodeviews/SequentView.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/nodeviews/SequentView.java index 8dd79d96681..c617b595e6a 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/nodeviews/SequentView.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/nodeviews/SequentView.java @@ -242,11 +242,6 @@ public void removeNotify() { unregisterListener(); } - @Override - protected void finalize() { - dispose(); - } - /** * Dispose this SequentView. * Before calling this method, the view should be removed from the UI. @@ -257,12 +252,6 @@ public void dispose() { printer = null; } catch (Throwable e) { mainWindow.notify(new GeneralFailureEvent(e.getMessage())); - } finally { - try { - super.finalize(); - } catch (Throwable e) { - mainWindow.notify(new GeneralFailureEvent(e.getMessage())); - } } } diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/prooftree/ProofTreeView.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/prooftree/ProofTreeView.java index 45fe758240f..8b5c4718711 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/prooftree/ProofTreeView.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/prooftree/ProofTreeView.java @@ -327,9 +327,7 @@ public void setExpandOSSNodes(boolean expandOSSNodes) { this.expandOSSNodes = expandOSSNodes; } - @Override - protected void finalize() throws Throwable { - super.finalize(); + protected void dispose() throws Throwable { Config.DEFAULT.removeConfigChangeListener(configChangeListener); NodeInfoVisualizer.removeListener(nodeInfoVisListener); } From a2178712c0be85b727e577c85405e3a6be9ded2b Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 23 Nov 2024 18:09:47 +0100 Subject: [PATCH 08/10] add javadoc --- .../key/symbolic_execution/rule/AbstractSideProofRule.java | 6 ++++++ .../java/org/key_project/slicing/graph/DependencyGraph.java | 3 +++ 2 files changed, 9 insertions(+) diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java index 1cdbd787f8f..59aa45ed064 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java @@ -134,6 +134,12 @@ public boolean isApplicableOnSubTerms() { return false; } + /** + * + * @param result + * @param conditions + * @param node + */ public record ResultsAndCondition(Term result, Set conditions, Node node) { } } diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java index 3e4dd6b7851..b912e1462f7 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java @@ -129,6 +129,7 @@ public Stream incomingEdgesOf(GraphNode node) { public record Edge(Node fromNode, GraphNode toNode, AnnotatedEdge annotation) {} /** + * Returns the incoming edges of the given node. * @param node a graph node * @return the incoming (graph edges, graph sources) of that node */ @@ -153,6 +154,8 @@ public Stream outgoingEdgesOf(GraphNode node) { } /** + * Returns the outgoing edges of the given node. + * * @param node a graph node * @return the outgoing (graph edges, graph targets) of that node */ From f658d4f581c62cbbb93612526eb9b353551a0501 Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Sat, 23 Nov 2024 18:10:51 +0100 Subject: [PATCH 09/10] add javadoc --- .../java/de/uka/ilkd/key/nparser/KeyAst.java | 10 +++ .../ilkd/key/nparser/ProofScriptEntry.java | 9 ++- .../key/proof/init/KeYUserProblemFile.java | 11 +++ .../key/proof/io/AbstractProblemLoader.java | 21 +++--- .../proof/io/IntermediateProofReplayer.java | 2 +- .../de/uka/ilkd/key/rule/merge/MergeRule.java | 40 ++++++----- .../merge/procedures/MergeByIfThenElse.java | 67 ++++++++++++++----- .../procedures/MergeIfThenElseAntecedent.java | 8 +-- .../ilkd/key/speclang/ContractFactory.java | 10 +-- .../pretranslation/TextualJMLSpecCase.java | 8 +++ .../jml/translation/JMLSpecFactory.java | 3 +- .../de/uka/ilkd/key/speclang/njml/JmlIO.java | 2 + .../key/speclang/njml/JmlTermFactory.java | 9 +++ .../njml/TranslatedDependencyContract.java | 3 +- .../StrategySettingsDefinition.java | 21 ++++-- .../SymbolicExecutionStateWithProgCnt.java | 12 ---- .../ilkd/key/gui/StrategySelectionView.java | 2 +- .../key/gui/WindowUserInterfaceControl.java | 17 ++--- .../key/gui/proofdiff/ProofDifference.java | 11 ++- .../slicing/graph/DependencyGraph.java | 1 + 20 files changed, 180 insertions(+), 87 deletions(-) diff --git a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java index 25b9e8ecac0..095e3ca921a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java +++ b/key.core/src/main/java/de/uka/ilkd/key/nparser/KeyAst.java @@ -85,6 +85,16 @@ public static class File extends KeyAst { return settings; } + /** + * Returns the a {@link ProofScriptEntry} from the underlying AST if an {@code \proofscript} + * entry is present. + * The {@code url} is used as the source of input and might be later used for error message, + * or including + * other files. + * + * @param url location pointing to the source of the AST + * @return a {@link ProofScriptEntry} if {@code \proofscript} is present + */ public @Nullable ProofScriptEntry findProofScript(URI url) { if (ctx.problem() != null && ctx.problem().proofScript() != null) { KeYParser.ProofScriptContext pctx = ctx.problem().proofScript(); diff --git a/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java b/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java index 1f76632362a..18120539a39 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java +++ b/key.core/src/main/java/de/uka/ilkd/key/nparser/ProofScriptEntry.java @@ -3,10 +3,17 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.nparser; +import de.uka.ilkd.key.parser.Location; + +import org.jspecify.annotations.NonNull; + /** + * This struct encapsulate the information of a proofscript found in key files. * + * @param script the content of the script + * @param location location of the content * @author Alexander Weigl * @version 1 (23.04.24) */ -public record ProofScriptEntry(String script, de.uka.ilkd.key.parser.Location location) { +public record ProofScriptEntry(@NonNull String script, @NonNull Location location) { } diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java index fcf5c100944..2cd7f1a89da 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/init/KeYUserProblemFile.java @@ -172,10 +172,21 @@ public boolean implies(ProofOblInput po) { } + /** + * True iff a {@link ProofScriptEntry} is present + * + * @see #readProofScript() + */ public boolean hasProofScript() { return readProofScript() != null; } + /** + * Returns the {@link ProofScriptEntry} in this resource + * + * @return {@link ProofScriptEntry} if present otherwise null + * @see KeyAst.File#findProofScript(URI) + */ public @Nullable ProofScriptEntry readProofScript() { URI url = getInitialFile().toURI(); return getParseContext().findProofScript(url); diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index 95abdfc90ee..1f6a4ab237b 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -260,7 +260,6 @@ public final void load() throws Exception { * * @param callbackProofLoaded optional callback, called when the proof is loaded but not yet * replayed - * * @throws ProofInputException Occurred Exception. * @throws IOException Occurred Exception. * @throws ProblemLoaderException Occurred Exception. @@ -659,20 +658,22 @@ public boolean hasProofScript() { return false; } - public @Nullable ProofScriptEntry readProofScript() throws ProofInputException { - KeYUserProblemFile kupf = (KeYUserProblemFile) envInput; - return kupf.readProofScript(); + /** + * same as {@link #getProofScript()} + */ + public @Nullable ProofScriptEntry readProofScript() { + return getProofScript(); } - public @Nullable ProofScriptEntry getProofScript() throws ProblemLoaderException { + /** + * Returns a {@link ProofScriptEntry} if {@code \proofscript} is given with the problem. + */ + public @Nullable ProofScriptEntry getProofScript() { if (!hasProofScript()) { return null; } - try { - return readProofScript(); - } catch (ProofInputException e) { - throw new ProblemLoaderException(this, e); - } + KeYUserProblemFile kupf = (KeYUserProblemFile) envInput; + return kupf.readProofScript(); } private ReplayResult replayProof(Proof proof) { diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java index fe601ce9f33..0c462055bae 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java @@ -111,7 +111,7 @@ public class IntermediateProofReplayer { private final LinkedList> queue = new LinkedList<>(); - public record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third) {} + private record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third) {} /** Maps join node IDs to previously seen join partners */ private final HashMap> joinPartnerNodes = new HashMap<>(); diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java index 029765a474f..18c7bace46a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java @@ -62,16 +62,15 @@ * Base for implementing merge rules. Extend this class, implement method mergeValuesInStates(...) * and register in class JavaProfile. *

- * + *

* The rule is applicable if the chosen subterm has the form { x := v || ... } PHI and there are * potential merge candidates. *

- * + *

* Any rule application returned will be incomplete; completion is handled by * de.uka.ilkd.key.gui.mergerule.MergeRuleCompletion. * * @author Dominic Scheurer - * * @see MergeRuleUtils * @see MergeTotalWeakening * @see MergeByIfThenElse @@ -95,7 +94,7 @@ public class MergeRule implements BuiltInRule { /** * Thresholds the maximum depth of right sides in updates for which an equivalence proof is * started. - * + *

* We skip the check for equal valuation of this variable if the depth threshold is exceeded by * one of the right sides. Experiments show a very big time overhead from a depth of about 8-10 * on, or sometimes even earlier. @@ -186,10 +185,10 @@ public String toString() { MergeStateEntry mergeResult = mergeStates(mergeRule, mergedState, state, thisSEState.programCounter(), mergeRuleApp.getDistinguishingFormula(), services); - newNames.addAll(mergeResult.second); - sideConditionsToProve.addAll(mergeResult.third); + newNames.addAll(mergeResult.newIntroducedNames); + sideConditionsToProve.addAll(mergeResult.sideConditionsToProve); - mergedState = mergeResult.first; + mergedState = mergeResult.newSymbolicState; mergedState.setCorrespondingNode(newGoal.node()); } @@ -378,7 +377,7 @@ protected MergeStateEntry mergeStates( if (proofClosed) { - // Arbitrary choice: Take value of first state if + // Arbitrary choice: Take value of distinguishingFormula state if // this does not equal the program variable itself if (!rightSide1.equals(tb.var(v))) { newElementaryUpdates = @@ -451,14 +450,14 @@ protected MergeStateEntry mergeStates( * Merges two heaps in a zip-like procedure. The fallback is an if-then-else construct that is * tried to be shifted as far inwards as possible. *

- * + *

* Override this method for specialized heap merge procedures. * * @param heapVar The heap variable for which the values should be merged. - * @param heap1 The first heap term. - * @param heap2 The second heap term. - * @param state1 SE state for the first heap term. - * @param state2 SE state for the second heap term + * @param heap1 The distinguishingFormula heap term. + * @param heap2 The ifTerm heap term. + * @param state1 SE state for the distinguishingFormula heap term. + * @param state2 SE state for the ifTerm heap term * @param services The services object. * @param distinguishingFormula The user-specified distinguishing formula. May be null (for * automatic generation). @@ -715,6 +714,17 @@ public interface MergeRuleProgressListener { void signalProgress(int progress); } - public record MergeStateEntry(SymbolicExecutionState first, LinkedHashSet second, - LinkedHashSet third) {} + /** + * Represents the result for merging to states. + * + * @param newSymbolicState the new state + * @param newIntroducedNames newly introduced names + * @param sideConditionsToProve side condition required for merging + * @see #mergeStates(MergeProcedure, SymbolicExecutionState, SymbolicExecutionState, Term, Term, + * Services) + */ + public record MergeStateEntry(SymbolicExecutionState newSymbolicState, + LinkedHashSet newIntroducedNames, + LinkedHashSet sideConditionsToProve) { + } } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java index 2591e2e9b72..6e15c1a32b8 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java @@ -110,9 +110,9 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, DistanceFormRightSide distFormAndRightSidesForITEUpd = createDistFormAndRightSidesForITEUpd(state1, state2, ifTerm, elseTerm, services); - cond = distFormAndRightSidesForITEUpd.first(); - ifForm = distFormAndRightSidesForITEUpd.second(); - elseForm = distFormAndRightSidesForITEUpd.third(); + cond = distFormAndRightSidesForITEUpd.distinguishingFormula(); + ifForm = distFormAndRightSidesForITEUpd.ifTerm(); + elseForm = distFormAndRightSidesForITEUpd.elseTerm(); } else { cond = distinguishingFormula; ifForm = ifTerm; @@ -131,8 +131,10 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * { v := \if (c1) \then (t1) \else (t2) }, where c1 is the path condition of * state1. However, the method also tries an optimization: The path condition c2 of state2 could * be used if it is shorter than c1. Moreover, equal parts of c1 and c2 could be omitted, since - * the condition shall only distinguish between the states. The first element of the triple is - * the discriminating condition, the second and third elements are the respective parts for the + * the condition shall only distinguish between the states. The distinguishingFormula element of + * the triple is + * the discriminating condition, the ifTerm and elseTerm elements are the respective parts for + * the * if and else branch. * * @param v Variable to return the update for. @@ -140,10 +142,14 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * @param state2 Second state to evaluate. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first + * { v := \if (distinguishingFormula) \then (ifTerm) \else (elseTerm) }, + * where distinguishingFormula, ifTerm + * and elseTerm are the respective components of the returned triple. The sideCommuted + * component + * indicates whether the path condition of the distinguishingFormula (sideCommuted + * component = false) or the + * ifTerm (sideCommuted component = true) state was used as a basis for the condition + * (distinguishingFormula * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( @@ -168,13 +174,16 @@ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( } /** - * Creates the input for an if-then-else update. The elements of the resulting quadruple can be + * Creates the input for an if-then-else update. The elements of the resulting + * {@link DistanceFormRightSide} can be * used to construct an elementary update corresponding to * { v := \if (c1) \then (ifTerm) \else (elseTerm) }, where c1 is the path * condition of state1. However, the method also tries an optimization: The path condition c2 of * state2 could be used if it is shorter than c1. Moreover, equal parts of c1 and c2 could be - * omitted, since the condition shall only distinguish between the states. The first element of - * the triple is the discriminating condition, the second and third elements are the respective + * omitted, since the condition shall only distinguish between the states. The + * distinguishingFormula element of + * the triple is the discriminating condition, the ifTerm and elseTerm elements are the + * respective * parts for the if and else branch. * * @param state1 First state to evaluate. @@ -183,10 +192,14 @@ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( * @param elseTerm The else term. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (first) \then (second) \else (third) }, where first, second - * and third are the respective components of the returned triple. The fourth component - * indicates whether the path condition of the first (fourth component = false) or the - * second (fourth component = true) state was used as a basis for the condition (first + * { v := \if (distinguishingFormula) \then (ifTerm) \else (elseTerm) }, + * where distinguishingFormula, ifTerm + * and elseTerm are the respective components of the returned triple. The sideCommuted + * component + * indicates whether the path condition of the distinguishingFormula (sideCommuted + * component = false) or the + * ifTerm (sideCommuted component = true) state was used as a basis for the condition + * (distinguishingFormula * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( @@ -255,6 +268,26 @@ public String toString() { return DISPLAY_NAME; } - public record DistanceFormRightSide(Term first, Term second, Term third, boolean fourth) { + /** + * Represents the distance between formulas for an if-then-else update. + * Input to construct an elementary update like + * { v := \if (distinguishingFormula) \then (ifTerm) \else (elseTerm) }, where + * distinguishingFormula, ifTerm + * and elseTerm are the respective components of the returned triple. The sideCommuted component + * indicates whether the path condition of the distinguishingFormula (sideCommuted component = + * false) or the + * ifTerm (sideCommuted component = true) state was used as a basis for the condition + * (distinguishingFormula + * component). + * + * @param distinguishingFormula a formula + * @param ifTerm a term + * @param elseTerm a term + * @param sideCommuted true if ifTerm and elseTerm have been swapped. + * @see #createDistFormAndRightSidesForITEUpd(SymbolicExecutionState, SymbolicExecutionState, + * Term, Term, Services) + */ + public record DistanceFormRightSide(Term distinguishingFormula, Term ifTerm, Term elseTerm, + boolean sideCommuted) { } } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java index ca4c9edc55c..a403f227f4a 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeIfThenElseAntecedent.java @@ -106,10 +106,10 @@ private static ImmutableSet getIfThenElseConstraints(Term constrained, Ter MergeByIfThenElse.createDistFormAndRightSidesForITEUpd(state1, state2, ifTerm, elseTerm, services); - final Term cond = distFormAndRightSidesForITEUpd.first(); - final Term ifForm = distFormAndRightSidesForITEUpd.second(); - final Term elseForm = distFormAndRightSidesForITEUpd.third(); - final boolean isSwapped = distFormAndRightSidesForITEUpd.fourth(); + final Term cond = distFormAndRightSidesForITEUpd.distinguishingFormula(); + final Term ifForm = distFormAndRightSidesForITEUpd.ifTerm(); + final Term elseForm = distFormAndRightSidesForITEUpd.elseTerm(); + final boolean isSwapped = distFormAndRightSidesForITEUpd.sideCommuted(); final Term varEqualsIfForm = tb.equals(constrained, ifForm); final Term varEqualsElseForm = tb.equals(constrained, elseForm); diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java index a83ab68f267..83058d0b741 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/ContractFactory.java @@ -193,21 +193,23 @@ public DependencyContract dep(KeYJavaType containerType, IObserverFunction pm, public DependencyContract dep(KeYJavaType kjt, LocationVariable targetHeap, TranslatedDependencyContract dep, LocationVariable selfVar) { - final ImmutableList paramVars = tb.paramVars(dep.first(), false); - assert (selfVar == null) == dep.first().isStatic(); + final ImmutableList paramVars = + tb.paramVars(dep.observerFunction(), false); + assert (selfVar == null) == dep.observerFunction().isStatic(); Map pres = new LinkedHashMap<>(); pres.put(services.getTypeConverter().getHeapLDT().getHeap(), selfVar == null ? tb.tt() : tb.inv(tb.var(selfVar))); Map accessibles = new LinkedHashMap<>(); for (final LocationVariable heap : HeapContext.getModifiableHeaps(services, false)) { if (heap == targetHeap) { - accessibles.put(heap, dep.second()); + accessibles.put(heap, dep.rhs()); } else { accessibles.put(heap, tb.allLocs()); } } // TODO: insert static invariant?? - return dep(kjt, dep.first(), dep.first().getContainerType(), pres, dep.third(), accessibles, + return dep(kjt, dep.observerFunction(), dep.observerFunction().getContainerType(), pres, + dep.mby(), accessibles, selfVar, paramVars, null, null); } diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java index 2c9430af2b6..f7ed59b9f03 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/pretranslation/TextualJMLSpecCase.java @@ -204,6 +204,14 @@ public void addRequires(LabeledParserRuleContext label) { addClause(REQUIRES, label); } + /** + * An abbreviation is a short-name for a term. Currently unused during the JML translation. + * A relict from older days ({@link #getAbbreviations()}. + * + * @param typeName name of the type + * @param abbrevName the short-representation of the term + * @param abbreviatedTerm the term to be abbreviated. + */ public record Abbreviation(LabeledParserRuleContext typeName, LabeledParserRuleContext abbrevName, LabeledParserRuleContext abbreviatedTerm) {} diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java index e1f4e5837f2..e0d09d6821c 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java @@ -1232,7 +1232,8 @@ public Contract createJMLDependencyContract(KeYJavaType kjt, LocationVariable ta // translateToTerm expression var dep = new JmlIO(services).context(context).translateDependencyContract(originalDep); - return cf.dep(kjt, targetHeap, dep, dep.first().isStatic() ? null : context.selfVar()); + return cf.dep(kjt, targetHeap, dep, + dep.observerFunction().isStatic() ? null : context.selfVar()); } public Contract createJMLDependencyContract(KeYJavaType kjt, TextualJMLDepends textualDep) { diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java index 25746f99d3a..3fdab8fa401 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlIO.java @@ -303,6 +303,8 @@ public TranslatedDependencyContract translateDependencyContract(ParserRuleContex *

* Note (weigl): No label is currently attached. * + * @param ctx a context + * @return {@link #translateDependencyContract(ParserRuleContext)} * @throws ClassCastException if the {@code ctx} is not suitable */ public TranslatedDependencyContract translateDependencyContract(LabeledParserRuleContext ctx) { diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java index 903d5ee7b4b..baedf9d073c 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/JmlTermFactory.java @@ -1029,6 +1029,15 @@ public Pair represents(SLExpression lhs, Term t) { return new Pair<>((IObserverFunction) lhs.getTerm().op(), t); } + /** + * Translates the dependency clause ({@code accessible rhs := mby \measured_by mby}) into a + * dependency contract. + * + * @param lhs left-hand side of the clause + * @param rhs right-hand side of the clause + * @param mby measured by term, can be omitted + * @return {@link TranslatedDependencyContract} + */ public TranslatedDependencyContract depends(SLExpression lhs, Term rhs, SLExpression mby) { LocationVariable heap = services.getTypeConverter().getHeapLDT().getHeap(); diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java index 122148732ad..5e3582459b4 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/njml/TranslatedDependencyContract.java @@ -7,9 +7,10 @@ import de.uka.ilkd.key.logic.op.IObserverFunction; /** + * The information obtain from an JML accessible clause. * * @author Alexander Weigl * @version 1 (23.04.24) */ -public record TranslatedDependencyContract(IObserverFunction first, Term second, Term third) { +public record TranslatedDependencyContract(IObserverFunction observerFunction, Term rhs, Term mby) { } diff --git a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java index fe7bd9b75a6..a15f94f9ecc 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java +++ b/key.core/src/main/java/de/uka/ilkd/key/strategy/definition/StrategySettingsDefinition.java @@ -35,10 +35,17 @@ * @see StrategyPropertyValueDefinition */ public class StrategySettingsDefinition { - public record StategySettingEntry(String name, int order, + /** + * This class represents an attribute in the strategy settings. + * + * @param name name of the attribute + * @param order precedence for sorting + * @param factory factory for creating new settings + */ + public record StrategySettingEntry(String name, int order, IDefaultStrategyPropertiesFactory factory) {} - private static final ArrayList STD_FURTHER_DEFAULTS; + private static final ArrayList STD_FURTHER_DEFAULTS; /** * Defines if a user interface control is shown to edit {@link StrategySettings#getMaxSteps()}. @@ -75,13 +82,13 @@ public record StategySettingEntry(String name, int order, * Further default settings, for example suitable for simplification. Consists of triples * (DEFAULT_NAME, MAX_RULE_APPS, PROPERTIES). */ - private final ArrayList furtherDefaults; + private final ArrayList furtherDefaults; static { STD_FURTHER_DEFAULTS = new ArrayList<>(); // Java verification standard preset (tested in TimSort case study) - STD_FURTHER_DEFAULTS.add(new StategySettingEntry( + STD_FURTHER_DEFAULTS.add(new StrategySettingEntry( "Java verif. std.", 7000, () -> { final StrategyProperties newProps = IDefaultStrategyPropertiesFactory.DEFAULT_FACTORY @@ -124,7 +131,7 @@ public record StategySettingEntry(String name, int order, })); // Simplification preset - STD_FURTHER_DEFAULTS.add(new StategySettingEntry( + STD_FURTHER_DEFAULTS.add(new StrategySettingEntry( "Simplification", 5000, () -> { final StrategyProperties newProps = IDefaultStrategyPropertiesFactory.DEFAULT_FACTORY @@ -197,7 +204,7 @@ public StrategySettingsDefinition(String propertiesTitle, public StrategySettingsDefinition(boolean showMaxRuleApplications, String maxRuleApplicationsLabel, int defaultMaxRuleApplications, String propertiesTitle, IDefaultStrategyPropertiesFactory defaultPropertiesFactory, - ArrayList furtherDefaults, + ArrayList furtherDefaults, AbstractStrategyPropertyDefinition... properties) { assert defaultPropertiesFactory != null; this.showMaxRuleApplications = showMaxRuleApplications; @@ -272,7 +279,7 @@ public IDefaultStrategyPropertiesFactory getDefaultPropertiesFactory() { /** * @return Further default settings, e.g. for simplification. */ - public ArrayList getFurtherDefaults() { + public ArrayList getFurtherDefaults() { return furtherDefaults; } diff --git a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java index ea86a015579..b8c04ecece2 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java +++ b/key.core/src/main/java/de/uka/ilkd/key/util/mergerule/SymbolicExecutionStateWithProgCnt.java @@ -24,18 +24,6 @@ */ public record SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, Term programCounter, @Nullable Node correspondingNode) { - /** - * @param symbolicState The symbolic state (parallel update). - * @param pathCondition The path condition (formula). - * @param programCounter The program counter: Formula with non-empty Java block and post - * condition as only sub term. - */ - public SymbolicExecutionStateWithProgCnt(Term symbolicState, Term pathCondition, Term programCounter) { - this(symbolicState, pathCondition, programCounter, null); - } - - - /** * @return The symbolic state. */ diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java index 0925b8cb48f..9a833bd94eb 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/StrategySelectionView.java @@ -404,7 +404,7 @@ private JPanel createDefaultPanel(StrategySelectionComponents components) { existingPredefs[0] = "Defaults"; int i = 1; - for (StrategySettingsDefinition.StategySettingEntry furtherDefault : DEFINITION + for (StrategySettingsDefinition.StrategySettingEntry furtherDefault : DEFINITION .getFurtherDefaults()) { existingPredefs[i] = furtherDefault.name(); i++; diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java index fc159628784..49dab944115 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java @@ -221,17 +221,12 @@ private void taskFinishedInternal(TaskFinishedInfo info) { } else { KeYMediator mediator = mainWindow.getMediator(); mediator.getNotationInfo().refresh(mediator.getServices()); - if (problemLoader.hasProofScript()) { - ProofScriptEntry scriptAndLoc; - try { - scriptAndLoc = problemLoader.readProofScript(); - ProofScriptWorker psw = new ProofScriptWorker(mainWindow.getMediator(), - scriptAndLoc.script(), scriptAndLoc.location()); - psw.init(); - psw.execute(); - } catch (ProofInputException e) { - LOGGER.warn("Failed to load proof", e); - } + ProofScriptEntry scriptAndLoc = problemLoader.readProofScript(); + if (scriptAndLoc != null) { + ProofScriptWorker psw = new ProofScriptWorker(mainWindow.getMediator(), + scriptAndLoc.script(), scriptAndLoc.location()); + psw.init(); + psw.execute(); } else if (macroChosen()) { applyMacro(); } diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java index 619100c08ea..73bca44ed19 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/proofdiff/ProofDifference.java @@ -83,7 +83,14 @@ static String findAndPopNearestMatch(String l, List right) { return current; } - public record QueueEntry(int idxLeft, int idxRight, int distance) {} + /** + * Entry in the search queue. + * + * @param idxLeft index of the left candidate + * @param idxRight index of the right candidate + * @param distance measure of difference between candidates + */ + private record QueueEntry(int idxLeft, int idxRight, int distance) {} static List findPairs(List left, List right) { List pairs = new ArrayList<>(left.size() + right.size()); @@ -102,7 +109,7 @@ static List findPairs(List left, List right) { while (!queue.isEmpty()) { QueueEntry t = queue.poll(); /* - * if(t.third>=THRESHOLD) { break; } + * if(t.elseTerm>=THRESHOLD) { break; } */ if (!matchedLeft[t.idxLeft] && !matchedRight[t.idxRight]) { String l = left.get(t.idxLeft); diff --git a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java index b912e1462f7..220bcc22a3d 100644 --- a/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java +++ b/keyext.slicing/src/main/java/org/key_project/slicing/graph/DependencyGraph.java @@ -130,6 +130,7 @@ public record Edge(Node fromNode, GraphNode toNode, AnnotatedEdge annotation) {} /** * Returns the incoming edges of the given node. + * * @param node a graph node * @return the incoming (graph edges, graph sources) of that node */ From 7c41529f32daf49a7eb6035e60ab5051c4c71bae Mon Sep 17 00:00:00 2001 From: Alexander Weigl Date: Tue, 3 Dec 2024 23:53:41 +0100 Subject: [PATCH 10/10] resolve reviewer requests --- .../rule/AbstractSideProofRule.java | 10 ------ .../rule/ResultsAndCondition.java | 19 ++++++++++ .../util/SymbolicExecutionSideProofUtil.java | 2 +- .../key/proof/io/AbstractProblemLoader.java | 7 ---- .../proof/io/IntermediateProofReplayer.java | 21 +++++++---- .../uka/ilkd/key/rule/WhileInvariantRule.java | 15 +++++--- .../de/uka/ilkd/key/rule/merge/MergeRule.java | 12 +++---- .../merge/procedures/MergeByIfThenElse.java | 36 +++++++------------ .../jml/translation/JMLSpecFactory.java | 3 +- .../key/gui/WindowUserInterfaceControl.java | 2 +- .../key/ui/ConsoleUserInterfaceControl.java | 2 +- 11 files changed, 68 insertions(+), 61 deletions(-) create mode 100644 key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ResultsAndCondition.java diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java index 59aa45ed064..e9178d692a2 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/AbstractSideProofRule.java @@ -6,7 +6,6 @@ import java.util.Deque; import java.util.LinkedList; import java.util.List; -import java.util.Set; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; @@ -18,7 +17,6 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.JFunction; import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.init.ProofInputException; import de.uka.ilkd.key.proof.mgt.ProofEnvironment; @@ -134,12 +132,4 @@ public boolean isApplicableOnSubTerms() { return false; } - /** - * - * @param result - * @param conditions - * @param node - */ - public record ResultsAndCondition(Term result, Set conditions, Node node) { - } } diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ResultsAndCondition.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ResultsAndCondition.java new file mode 100644 index 00000000000..9a14b9852cb --- /dev/null +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/rule/ResultsAndCondition.java @@ -0,0 +1,19 @@ +/* This file is part of KeY - https://key-project.org + * KeY is licensed under the GNU General Public License Version 2 + * SPDX-License-Identifier: GPL-2.0-only */ +package de.uka.ilkd.key.symbolic_execution.rule; + +import java.util.Set; + +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.proof.Node; + +/** + * The return value of a side proof. + * + * @param result a term representing the result (first formula of succedent) + * @param conditions formulas of the antecedent + * @param node the final node of the side proof + */ +public record ResultsAndCondition(Term result, Set conditions, Node node) { +} diff --git a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java index 3a4fb926956..079bf2aed6b 100644 --- a/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java +++ b/key.core.symbolic_execution/src/main/java/de/uka/ilkd/key/symbolic_execution/util/SymbolicExecutionSideProofUtil.java @@ -32,7 +32,7 @@ import de.uka.ilkd.key.strategy.StrategyProperties; import de.uka.ilkd.key.symbolic_execution.profile.SimplifyTermProfile; import de.uka.ilkd.key.symbolic_execution.profile.SymbolicExecutionJavaProfile; -import de.uka.ilkd.key.symbolic_execution.rule.AbstractSideProofRule.ResultsAndCondition; +import de.uka.ilkd.key.symbolic_execution.rule.ResultsAndCondition; import de.uka.ilkd.key.util.ProofStarter; import de.uka.ilkd.key.util.SideProofUtil; diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java index 1f6a4ab237b..a7d6c940c57 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/AbstractProblemLoader.java @@ -658,13 +658,6 @@ public boolean hasProofScript() { return false; } - /** - * same as {@link #getProofScript()} - */ - public @Nullable ProofScriptEntry readProofScript() { - return getProofScript(); - } - /** * Returns a {@link ProofScriptEntry} if {@code \proofscript} is given with the problem. */ diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java index 0c462055bae..7dce2562e06 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/io/IntermediateProofReplayer.java @@ -49,6 +49,7 @@ import de.uka.ilkd.key.speclang.OperationContract; import de.uka.ilkd.key.util.ProgressMonitor; import de.uka.ilkd.key.util.mergerule.MergeRuleUtils; +import de.uka.ilkd.key.util.mergerule.SymbolicExecutionStateWithProgCnt; import org.key_project.logic.Name; import org.key_project.logic.Named; @@ -111,7 +112,15 @@ public class IntermediateProofReplayer { private final LinkedList> queue = new LinkedList<>(); - private record PartnerNode(Node first, PosInOccurrence second, NodeIntermediate third) {} + /** + * Used by the node merging during the proof replay. + * + * @param node the other node to be merged with + * @param pio pio of ??? (ask Dominic Steinhöfel) + * @param intermediate representation of the node during the replay + * @see MergePartnerAppIntermediate + */ + private record PartnerNode(Node node, PosInOccurrence pio, NodeIntermediate intermediate) {} /** Maps join node IDs to previously seen join partners */ private final HashMap> joinPartnerNodes = new HashMap<>(); @@ -311,9 +320,9 @@ public Result replay(ProblemInitializer.ProblemInitializerListener listener, // Now add children of partner nodes for (PartnerNode partnerNodeInfo : partnerNodesInfo) { Iterator children = - partnerNodeInfo.first.childrenIterator(); + partnerNodeInfo.node.childrenIterator(); LinkedList intermChildren = - partnerNodeInfo.third.getChildren(); + partnerNodeInfo.intermediate.getChildren(); addChildren(children, intermChildren); } @@ -804,16 +813,16 @@ private MergeRuleBuiltInRuleApp instantiateJoinApp(final MergeAppIntermediate jo ImmutableList joinPartners = ImmutableSLList.nil(); for (PartnerNode partnerNodeInfo : partnerNodesInfo) { - var ownSEState = + SymbolicExecutionStateWithProgCnt ownSEState = sequentToSETriple(currNode, joinApp.posInOccurrence(), services); var partnerSEState = - sequentToSETriple(partnerNodeInfo.first, partnerNodeInfo.second, services); + sequentToSETriple(partnerNodeInfo.node, partnerNodeInfo.pio, services); assert ownSEState.programCounter().equals(partnerSEState.programCounter()) : "Cannot merge incompatible program counters"; joinPartners = joinPartners.append( - new MergePartner(proof.getOpenGoal(partnerNodeInfo.first), partnerNodeInfo.second)); + new MergePartner(proof.getOpenGoal(partnerNodeInfo.node), partnerNodeInfo.pio)); } joinApp.setMergeNode(currNode); diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java index dd3d38b097f..217965523f0 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/WhileInvariantRule.java @@ -586,7 +586,14 @@ private Guard prepareGuard(final Instantiation inst, return new Guard(guardJb, guardTrueTerm, guardFalseTerm); } - private record Guard(JavaBlock first, Term second, Term third) {} + /** + * Represents a {@code javaBlock} which is executed if the {@code trueTerm} is true. + * + * @param javaBlock a block of java code + * @param trueTerm a boolean term + * @param falseTerm the negation (at least semantically) of {@code trueTerm} + */ + private record Guard(JavaBlock javaBlock, Term trueTerm, Term falseTerm) {} private void prepareInvInitiallyValidBranch(TermLabelState termLabelState, Services services, RuleApp ruleApp, Instantiation inst, final Term invTerm, Term reachableState, @@ -747,9 +754,9 @@ private void setupWdGoal(final Goal goal, final LoopSpecification inv, final Ter // prepare guard final Guard guardStuff = prepareGuard(inst, booleanKJT, loopRuleApp, services); - final JavaBlock guardJb = guardStuff.first; - final Term guardTrueTerm = guardStuff.second; - final Term guardFalseTerm = guardStuff.third; + final JavaBlock guardJb = guardStuff.javaBlock; + final Term guardTrueTerm = guardStuff.trueTerm; + final Term guardFalseTerm = guardStuff.falseTerm; Term beforeLoopUpdate = null; diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java index 18c7bace46a..b7a0cd56ab4 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/MergeRule.java @@ -454,13 +454,13 @@ protected MergeStateEntry mergeStates( * Override this method for specialized heap merge procedures. * * @param heapVar The heap variable for which the values should be merged. - * @param heap1 The distinguishingFormula heap term. - * @param heap2 The ifTerm heap term. - * @param state1 SE state for the distinguishingFormula heap term. - * @param state2 SE state for the ifTerm heap term + * @param heap1 The first heap term. + * @param heap2 The second heap term. + * @param state1 SE state for the first heap term. + * @param state2 SE state for the second heap term * @param services The services object. - * @param distinguishingFormula The user-specified distinguishing formula. May be null (for - * automatic generation). + * @param distinguishingFormula The user-specified distinguishing formula. + * Maybe null (for automatic generation). * @return A merged heap term. */ protected ValuesMergeResult mergeHeaps(final MergeProcedure mergeRule, diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java index 6e15c1a32b8..d9b85da0719 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/merge/procedures/MergeByIfThenElse.java @@ -131,10 +131,8 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * { v := \if (c1) \then (t1) \else (t2) }, where c1 is the path condition of * state1. However, the method also tries an optimization: The path condition c2 of state2 could * be used if it is shorter than c1. Moreover, equal parts of c1 and c2 could be omitted, since - * the condition shall only distinguish between the states. The distinguishingFormula element of - * the triple is - * the discriminating condition, the ifTerm and elseTerm elements are the respective parts for - * the + * the condition shall only distinguish between the states. The first element of the triple is + * the discriminating condition, the second and third elements are the respective parts for the * if and else branch. * * @param v Variable to return the update for. @@ -142,14 +140,10 @@ public static Term createIfThenElseTerm(final SymbolicExecutionState state1, * @param state2 Second state to evaluate. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (distinguishingFormula) \then (ifTerm) \else (elseTerm) }, - * where distinguishingFormula, ifTerm - * and elseTerm are the respective components of the returned triple. The sideCommuted - * component - * indicates whether the path condition of the distinguishingFormula (sideCommuted - * component = false) or the - * ifTerm (sideCommuted component = true) state was used as a basis for the condition - * (distinguishingFormula + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( @@ -180,10 +174,8 @@ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( * { v := \if (c1) \then (ifTerm) \else (elseTerm) }, where c1 is the path * condition of state1. However, the method also tries an optimization: The path condition c2 of * state2 could be used if it is shorter than c1. Moreover, equal parts of c1 and c2 could be - * omitted, since the condition shall only distinguish between the states. The - * distinguishingFormula element of - * the triple is the discriminating condition, the ifTerm and elseTerm elements are the - * respective + * omitted, since the condition shall only distinguish between the states. The first element of + * the triple is the discriminating condition, the second and third elements are the respective * parts for the if and else branch. * * @param state1 First state to evaluate. @@ -192,14 +184,10 @@ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( * @param elseTerm The else term. * @param services The services object. * @return Input to construct an elementary update like - * { v := \if (distinguishingFormula) \then (ifTerm) \else (elseTerm) }, - * where distinguishingFormula, ifTerm - * and elseTerm are the respective components of the returned triple. The sideCommuted - * component - * indicates whether the path condition of the distinguishingFormula (sideCommuted - * component = false) or the - * ifTerm (sideCommuted component = true) state was used as a basis for the condition - * (distinguishingFormula + * { v := \if (first) \then (second) \else (third) }, where first, second + * and third are the respective components of the returned triple. The fourth component + * indicates whether the path condition of the first (fourth component = false) or the + * second (fourth component = true) state was used as a basis for the condition (first * component). */ static DistanceFormRightSide createDistFormAndRightSidesForITEUpd( diff --git a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java index e0d09d6821c..64696bfbaed 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java +++ b/key.core/src/main/java/de/uka/ilkd/key/speclang/jml/translation/JMLSpecFactory.java @@ -1231,7 +1231,8 @@ public Contract createJMLDependencyContract(KeYJavaType kjt, LocationVariable ta var context = Context.inClass(kjt, false, tb); // translateToTerm expression - var dep = new JmlIO(services).context(context).translateDependencyContract(originalDep); + TranslatedDependencyContract dep = + new JmlIO(services).context(context).translateDependencyContract(originalDep); return cf.dep(kjt, targetHeap, dep, dep.observerFunction().isStatic() ? null : context.selfVar()); } diff --git a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java index 49dab944115..33dbfeed86a 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/gui/WindowUserInterfaceControl.java @@ -221,7 +221,7 @@ private void taskFinishedInternal(TaskFinishedInfo info) { } else { KeYMediator mediator = mainWindow.getMediator(); mediator.getNotationInfo().refresh(mediator.getServices()); - ProofScriptEntry scriptAndLoc = problemLoader.readProofScript(); + ProofScriptEntry scriptAndLoc = problemLoader.getProofScript(); if (scriptAndLoc != null) { ProofScriptWorker psw = new ProofScriptWorker(mainWindow.getMediator(), scriptAndLoc.script(), scriptAndLoc.location()); diff --git a/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java b/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java index d0d7781110d..8edea689cd6 100644 --- a/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java +++ b/key.ui/src/main/java/de/uka/ilkd/key/ui/ConsoleUserInterfaceControl.java @@ -158,7 +158,7 @@ public void taskFinished(TaskFinishedInfo info) { ProblemLoader problemLoader = (ProblemLoader) info.getSource(); if (problemLoader.hasProofScript()) { try { - ProofScriptEntry script = problemLoader.readProofScript(); + ProofScriptEntry script = problemLoader.getProofScript(); if (script != null) { ProofScriptEngine pse = new ProofScriptEngine(script.script(), script.location());