From f0785bc0b6c10c2c66a24a19a29494c3776c7edd Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Jan 2024 12:53:57 +0100 Subject: [PATCH 001/248] moved isabelle translation to submodule clone of key --- key.ui/build.gradle | 1 + keyext.isabelletranslation/build.gradle | 6 + .../IsabelleTranslationExtension.java | 49 +++ .../IsabelleTranslator.java | 358 ++++++++++++++++++ .../TranslationAction.java | 59 +++ .../TranslationOptionsPanel.java | 32 ++ ...ilkd.key.gui.extension.api.KeYGuiExtension | 1 + settings.gradle | 1 + 8 files changed, 507 insertions(+) create mode 100644 keyext.isabelletranslation/build.gradle create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java create mode 100644 keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension diff --git a/key.ui/build.gradle b/key.ui/build.gradle index ea66e0b38ab..4662585fd1d 100644 --- a/key.ui/build.gradle +++ b/key.ui/build.gradle @@ -32,6 +32,7 @@ dependencies { runtimeOnly project(":keyext.exploration") runtimeOnly project(":keyext.slicing") runtimeOnly project(":keyext.proofmanagement") + runtimeOnly project(":keyext.isabelletranslation") } task createExamplesZip(type: Zip) { diff --git a/keyext.isabelletranslation/build.gradle b/keyext.isabelletranslation/build.gradle new file mode 100644 index 00000000000..7d79bffb33f --- /dev/null +++ b/keyext.isabelletranslation/build.gradle @@ -0,0 +1,6 @@ +description "Translate" + +dependencies { + implementation project(':key.core') + implementation project(':key.ui') +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java new file mode 100644 index 00000000000..85a3bbfbdba --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -0,0 +1,49 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.extension.api.ContextMenuAdapter; +import de.uka.ilkd.key.gui.extension.api.ContextMenuKind; +import de.uka.ilkd.key.gui.extension.api.KeYGuiExtension; +import de.uka.ilkd.key.gui.settings.SettingsProvider; +import de.uka.ilkd.key.logic.PosInOccurrence; +import de.uka.ilkd.key.pp.PosInSequent; +import de.uka.ilkd.key.proof.Node; +import de.uka.ilkd.key.proof.Proof; +import org.jspecify.annotations.NonNull; + +import javax.swing.*; +import java.util.ArrayList; +import java.util.List; + +@KeYGuiExtension.Info(name = "Translation", optional = true, + experimental = true) +public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu { + + @Override + public SettingsProvider getSettings() { + return new TranslationOptionsPanel(); + } + + + /** + * The context menu adapter used by the extension. + */ + private final ContextMenuAdapter adapter = new ContextMenuAdapter() { + @Override + public List getContextActions( + KeYMediator mediator, ContextMenuKind kind, PosInSequent pos) { + if (pos.getPosInOccurrence() != null) { + return List.of(); + } + List list = new ArrayList<>(); + list.add(new TranslationAction(MainWindow.getInstance())); + return list; + } + }; + + @Override + public @NonNull List getContextActions(@NonNull KeYMediator mediator, @NonNull ContextMenuKind kind, @NonNull Object underlyingObject) { + return adapter.getContextActions(mediator, kind, underlyingObject); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java new file mode 100644 index 00000000000..7674e81e044 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -0,0 +1,358 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Sequent; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.*; +import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.IllegalFormulaException; +import de.uka.ilkd.key.util.Debug; +import org.key_project.util.collection.ImmutableArray; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import static de.uka.ilkd.key.smt.SMTProblem.sequentToTerm; + +public class IsabelleTranslator { + + private final HashMap usedSorts = new HashMap<>(); + + private final HashMap usedFunctions = new HashMap<>(); + + private final HashMap usedPredicates = new HashMap<>(); + + private static final StringBuilder INTSTRING = new StringBuilder("Int"); + + private static final StringBuilder BOOL = new StringBuilder("bool"); + + private static final String GAP = " "; + + private static final StringBuilder FALSESTRING = new StringBuilder("False"); + + private static final StringBuilder TRUESTRING = new StringBuilder("True"); + + private static final StringBuilder ALLSTRING = new StringBuilder("\\"); + + private static final StringBuilder EXISTSTRING = new StringBuilder("\\"); + + private static final StringBuilder ANDSTRING = new StringBuilder("\\"); + + private static final StringBuilder ORSTRING = new StringBuilder("\\"); + + private static final StringBuilder NOTSTRING = new StringBuilder("\\"); + + private static final StringBuilder EQSTRING = new StringBuilder("="); + + private static final StringBuilder IMPLYSTRING = new StringBuilder("-->"); + + private static final StringBuilder PLUSSTRING = new StringBuilder("+"); + + private static final StringBuilder MINUSSTRING = new StringBuilder("-"); + + private static final StringBuilder MULTSTRING = new StringBuilder("*"); + + private static final StringBuilder DIVSTRING = new StringBuilder("div"); + + private static final StringBuilder LTSTRING = new StringBuilder("<"); + + private static final StringBuilder GTSTRING = new StringBuilder(">"); + + private static final StringBuilder LEQSTRING = new StringBuilder("<="); + + private static final StringBuilder GEQSTRING = new StringBuilder(">="); + + private static final StringBuilder NULLSTRING = new StringBuilder("null"); + + private static final StringBuilder NULLSORTSTRING = new StringBuilder("NULLSORT"); + + private static final StringBuilder LOGICALIFTHENELSE = new StringBuilder("ite"); + + private static final StringBuilder TERMIFTHENELSE = new StringBuilder("ite"); + + private static final StringBuilder DISTINCT = new StringBuilder("distinct"); + + public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { + Term problem = sequentToTerm(sequent, services); + // TODO find correct values + StringBuilder hb = buildCompleteText(translateTerm(problem, new ArrayList<>(), services), new ArrayList<>()); + return hb; + } + + protected StringBuilder buildCompleteText(StringBuilder formula, ArrayList types) { + //TODO ensure usedSorts etc have the right values? + StringBuilder result = new StringBuilder(); + result.append("theory Translation imports Main begin").append(System.lineSeparator()); + + result.append(getSortDeclarations()); + + result.append("locale varsAndFunctions =").append(System.lineSeparator()); + //TODO additional types of JFOL hierarchy and assumptions + result.append(getNullLocale()); + + result.append(getFunctionDeclarations()); + result.append(getPredicateDeclarations()); + result.append(getFreeVariableDeclarations()); + + result.append("begin").append(System.lineSeparator()); + + result.append("theorem solve: \""); + result.append(formula).append("\""); + result.append(System.lineSeparator()); + + return result.append("end").append(System.lineSeparator()).append("end"); + } + + private StringBuilder getNullLocale() { + //TODO handle null correctly. Probably null != undefined (Isabelle) + StringBuilder result = new StringBuilder(); + result.append("fixes null::'a").append(System.lineSeparator()); + result.append("assumes null_undef: \"null = undefined\"").append(System.lineSeparator()); + return result; + } + + private StringBuilder getFunctionDeclarations() { + StringBuilder declarations = new StringBuilder(); + for (Function fun : usedFunctions.keySet()) { + declarations.append(getFunctionDeclaration(fun)).append(System.lineSeparator()); + } + return declarations; + } + + private StringBuilder getFunctionDeclaration(Function fun) { + //TODO duplicate handling? Isabelle function handling? + StringBuilder result = new StringBuilder(); + result.append("fixes "); + result.append(usedFunctions.get(fun)); + result.append(":: \""); + for (Sort sort : fun.argSorts()) { + result.append(translateSort(sort)).append("=>"); + } + result.append(translateSort(fun.sort())).append("\""); + return result; + } + + private StringBuilder getPredicateDeclarations() { + StringBuilder declarations = new StringBuilder(); + for (Function fun : usedPredicates.keySet()) { + declarations.append(getPredicateDeclaration(fun)).append(System.lineSeparator()); + } + return declarations; + } + + private StringBuilder getPredicateDeclaration(Function fun) { + //TODO duplicate handling? Isabelle function handling? + StringBuilder result = new StringBuilder(); + result.append("fixes "); + result.append(usedPredicates.get(fun)); + result.append(":: \""); + for (Sort sort : fun.argSorts()) { + result.append(translateSort(sort)).append("=>"); + } + result.append(BOOL).append("\""); + return result; + } + + private StringBuilder getFreeVariableDeclarations() { + //TODO implement + return new StringBuilder(); + } + + + private StringBuilder getSortDeclarations() { + StringBuilder declaration = new StringBuilder(); + for (Sort sort : usedSorts.keySet()) { + declaration.append(getSortDeclaration(sort)); + } + return declaration; + } + + private StringBuilder getSortDeclaration(Sort sort) { + StringBuilder result = new StringBuilder(); + return result.append("typedecl ").append(usedSorts.get(sort)).append(System.lineSeparator()); + } + + private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) { + Operator op = term.op(); + + if (op == Junctor.IMP) { + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); + return translateImplication(arg1, arg2); + } else if (op == Junctor.AND) { + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); + return translateAnd(arg1, arg2); + } else if (op == Junctor.OR) { + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); + return translateLogicalOr(arg1, arg2); + } else if (op == Junctor.NOT) { + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + return translateNot(arg1); + } else if (op == Junctor.TRUE) { + return translateLogicalTrue(); + } else if (op == Junctor.FALSE) { + return translateLogicalFalse(); + } else if (op == Equality.EQUALS) { + //TODO type hierarchy and cast handling + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); + return translateObjectEqual(arg1, arg2); + } else if (op instanceof Function fun) { + ArrayList args = new ArrayList<>(); + for (int i = 0; i < op.arity(); i++) { + args.add(translateTerm(term.sub(i), quantifiedVariables, services)); + } + if (fun.sort() == Sort.FORMULA) { + return translatePredicate(fun, args); + } + //TODO binding functions??? + return translateFunction(fun, args); + } else if ((op instanceof LogicVariable) || (op instanceof ProgramVariable)) { + //TODO handle Logic and Program variables differently? + //TODO quantified variables handling + ParsableVariable var = (ParsableVariable) op; + if (quantifiedVariables.contains(op)) { + return translateVariable(var); + } else { + return translateVariable(var); + } + } else if (op == Quantifier.ALL) { + ImmutableArray vars = term.varsBoundHere(0); + Debug.assertTrue(vars.size() == 1); + + QuantifiableVariable var = vars.get(0); + + quantifiedVariables.add(var); + + StringBuilder qv = this.translateVariable(var); + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + return this.translateLogicalAll(qv, arg1); + } else if (op == Quantifier.EX) { + ImmutableArray vars = term.varsBoundHere(0); + Debug.assertTrue(vars.size() == 1); + + QuantifiableVariable var = vars.get(0); + + quantifiedVariables.add(var); + + StringBuilder qv = this.translateVariable(var); + StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); + return this.translateLogicalExists(qv, arg1); + } + //TODO translation of other types + return new StringBuilder(); + } + + private StringBuilder translateLogicalFalse() { + return FALSESTRING; + } + + private StringBuilder translateLogicalTrue() { + return TRUESTRING; + } + + private StringBuilder translateObjectEqual(StringBuilder arg1, StringBuilder arg2) { + StringBuilder result = new StringBuilder(); + return surroundBrackets(result.append(arg1).append(EQSTRING).append(arg2)); + } + + private StringBuilder translateLogicalOr(StringBuilder arg1, StringBuilder arg2) { + StringBuilder toReturn = new StringBuilder(); + return surroundBrackets(toReturn.append(arg1).append(ORSTRING).append(arg2)); + } + + private StringBuilder translateLogicalExists(StringBuilder qv, StringBuilder arg1) { + StringBuilder result = new StringBuilder(); + result.append(EXISTSTRING); + result.append(qv).append(". "); + result.append(arg1); + return surroundBrackets(result); + } + + private StringBuilder translateSort(Sort sort) { + StringBuilder result = new StringBuilder(); + if (usedSorts.containsKey(sort)) { + return usedSorts.get(sort); + } + //TODO prevent unintentional translation into Isabelle types + //TODO prevent duplicates? + usedSorts.put(sort, new StringBuilder(sort.name().toString())); + return result.append(sort.name().toString()); + } + + private StringBuilder translateLogicalAll(StringBuilder qv, StringBuilder arg1) { + StringBuilder result = new StringBuilder(); + result.append(ALLSTRING); + result.append(qv).append(". "); + result.append(arg1); + return surroundBrackets(result); + } + + private StringBuilder translatePredicate(Function fun, ArrayList args) { + if (!usedPredicates.containsKey(fun)) { + //TODO avoid conflicts + StringBuilder funName = new StringBuilder(fun.name().toString()); + usedPredicates.put(fun, funName); + } + return buildFunction(usedPredicates.get(fun), args); + } + + private StringBuilder buildFunction(StringBuilder name, ArrayList args) { + StringBuilder toReturn = new StringBuilder(); + if (args.isEmpty()) { + toReturn.append(name); + } else { + toReturn.append("("); + toReturn.append(name).append(" "); + + for (StringBuilder arg : args) { + toReturn.append(arg).append(" "); + } + toReturn.append(")"); + } + return toReturn; + } + + private StringBuilder surroundBrackets(StringBuilder sb) { + return new StringBuilder("(").append(sb).append(")"); + } + + private StringBuilder translateAnd(StringBuilder arg1, StringBuilder arg2) { + StringBuilder toReturn = new StringBuilder(); + return surroundBrackets(toReturn.append(arg1).append(ANDSTRING).append(arg2)); + } + + private StringBuilder translateFunction(Function fun, ArrayList args) { + if (!usedFunctions.containsKey(fun)) { + //TODO avoid conflicts + StringBuilder funName = new StringBuilder(fun.name().toString()); + usedFunctions.put(fun, funName); + } + return buildFunction(usedFunctions.get(fun), args); + } + + private StringBuilder translateVariable(ParsableVariable var) { + //TODO Prevent Duplicates? + StringBuilder result = new StringBuilder(); + return surroundBrackets(result.append(var.name().toString()).append("::").append(translateSort(var.sort()))); + } + + private StringBuilder translateNot(StringBuilder arg1) { + StringBuilder toReturn = new StringBuilder(); + return surroundBrackets(toReturn.append(NOTSTRING).append(arg1)); + } + + private StringBuilder translateImplication(StringBuilder arg1, StringBuilder arg2) { + StringBuilder toReturn = new StringBuilder(); + return surroundBrackets(toReturn.append(arg1).append(IMPLYSTRING).append(arg2)); + } + + protected StringBuilder translateComment(int newLines, String comment) { + StringBuilder buffer = new StringBuilder(); + buffer.append("\n".repeat(Math.max(0, newLines))); + return buffer.append(GAP + "; ").append(comment); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java new file mode 100644 index 00000000000..8a905065ff5 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -0,0 +1,59 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.uka.ilkd.key.macros.SMTPreparationMacro; +import de.uka.ilkd.key.proof.Goal; +import de.uka.ilkd.key.proof.Proof; +import de.uka.ilkd.key.smt.IllegalFormulaException; +import org.key_project.util.collection.ImmutableList; + +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class TranslationAction extends MainWindowAction { + public TranslationAction(MainWindow mainWindow) { + super(mainWindow); + setName("Translate to Isabelle"); + } + + @Override + public void actionPerformed(ActionEvent e) { + System.out.println("Translation Action"); + KeYMediator mediator = getMediator(); + Proof currentProof = mediator.getSelectedProof(); + ImmutableList goals = ImmutableList.of(mediator.getSelectedGoal()); + + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(currentProof, goals, null)) { + try { + smtMacro.applyTo(mediator.getUI(), currentProof, goals, null, null); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + + generateTranslation(); + } + + private void generateTranslation() { + IsabelleTranslator translator = new IsabelleTranslator(); + KeYMediator mediator = getMediator(); + try { + //TODO let user choose where to save file? + String path = "Translation.thy"; + StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent(), mediator.getServices()); + + try { + Files.write(Paths.get(path), translation.toString().getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } catch (IllegalFormulaException e) { + throw new RuntimeException(e); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java new file mode 100644 index 00000000000..83f397df94e --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java @@ -0,0 +1,32 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.settings.SettingsPanel; +import de.uka.ilkd.key.gui.settings.SettingsProvider; + +import javax.swing.*; + +public class TranslationOptionsPanel extends SettingsPanel implements SettingsProvider { + private static final long serialVersionUID = -2170118134719823425L; + + public TranslationOptionsPanel() { + setHeaderText(getDescription()); + } + + @Override + public String getDescription() { + return "Translate"; + } + + @Override + public JPanel getPanel(MainWindow window) { + return this; + } + + @Override + public void applySettings(MainWindow window) { + } +} diff --git a/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension new file mode 100644 index 00000000000..289dacddb4d --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension @@ -0,0 +1 @@ +de.uka.ilkd.key.gui.isabelletranslation.IsabelleTranslationExtension \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index e71fc368308..441d784d378 100644 --- a/settings.gradle +++ b/settings.gradle @@ -13,3 +13,4 @@ include 'keyext.ui.testgen' include 'keyext.proofmanagement' include 'keyext.exploration' include 'keyext.slicing' +include 'keyext.isabelletranslation' From 0957a15d4029fc6eca6f2f691fb7875f5d538666 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Jan 2024 12:56:34 +0100 Subject: [PATCH 002/248] Removed SMT Macro from TranslationAction --- .../isabelletranslation/TranslationAction.java | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 8a905065ff5..7e56273ef6f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -3,11 +3,7 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; -import de.uka.ilkd.key.macros.SMTPreparationMacro; -import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.smt.IllegalFormulaException; -import org.key_project.util.collection.ImmutableList; import java.awt.event.ActionEvent; import java.io.IOException; @@ -23,18 +19,6 @@ public TranslationAction(MainWindow mainWindow) { @Override public void actionPerformed(ActionEvent e) { System.out.println("Translation Action"); - KeYMediator mediator = getMediator(); - Proof currentProof = mediator.getSelectedProof(); - ImmutableList goals = ImmutableList.of(mediator.getSelectedGoal()); - - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - if (smtMacro.canApplyTo(currentProof, goals, null)) { - try { - smtMacro.applyTo(mediator.getUI(), currentProof, goals, null, null); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - } generateTranslation(); } From 2c9ad4e0af398ae8b92cde632873963531fc6cf3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Jan 2024 13:10:27 +0100 Subject: [PATCH 003/248] Now saves translation file to homepath. Also uses Logger for messages in TranslationAction --- .../gui/isabelletranslation/TranslationAction.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 7e56273ef6f..0d73288103f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -4,6 +4,8 @@ import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.uka.ilkd.key.smt.IllegalFormulaException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.awt.event.ActionEvent; import java.io.IOException; @@ -11,6 +13,9 @@ import java.nio.file.Paths; public class TranslationAction extends MainWindowAction { + + private static final Logger LOGGER = LoggerFactory.getLogger(TranslationAction.class); + public TranslationAction(MainWindow mainWindow) { super(mainWindow); setName("Translate to Isabelle"); @@ -18,7 +23,7 @@ public TranslationAction(MainWindow mainWindow) { @Override public void actionPerformed(ActionEvent e) { - System.out.println("Translation Action"); + LOGGER.info("Translation Action"); generateTranslation(); } @@ -28,11 +33,11 @@ private void generateTranslation() { KeYMediator mediator = getMediator(); try { //TODO let user choose where to save file? - String path = "Translation.thy"; + String path = System.getProperty("user.home") + "\\Translation.thy"; StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent(), mediator.getServices()); - try { Files.write(Paths.get(path), translation.toString().getBytes()); + LOGGER.info("Saved to: " + path); } catch (IOException e) { throw new RuntimeException(e); } From 0b4d42dacdd3dd17c39d846c1a1a971caa707bff Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Jan 2024 13:49:45 +0100 Subject: [PATCH 004/248] Now throws IllegalFormulaException when translating unimplemented parts of translation --- .../IllegalFormulaException.java | 15 +++++++++++++++ .../IsabelleTranslationExtension.java | 3 --- .../isabelletranslation/IsabelleTranslator.java | 5 ++--- .../isabelletranslation/TranslationAction.java | 3 ++- 4 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java new file mode 100644 index 00000000000..d6281bd391f --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java @@ -0,0 +1,15 @@ +/* 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.gui.isabelletranslation; + +public class IllegalFormulaException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + + IllegalFormulaException(String msg) { + super(msg); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index 85a3bbfbdba..2ba0524467e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -6,10 +6,7 @@ import de.uka.ilkd.key.gui.extension.api.ContextMenuKind; import de.uka.ilkd.key.gui.extension.api.KeYGuiExtension; import de.uka.ilkd.key.gui.settings.SettingsProvider; -import de.uka.ilkd.key.logic.PosInOccurrence; import de.uka.ilkd.key.pp.PosInSequent; -import de.uka.ilkd.key.proof.Node; -import de.uka.ilkd.key.proof.Proof; import org.jspecify.annotations.NonNull; import javax.swing.*; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 7674e81e044..0e75cdf31df 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -5,7 +5,6 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.logic.sort.Sort; -import de.uka.ilkd.key.smt.IllegalFormulaException; import de.uka.ilkd.key.util.Debug; import org.key_project.util.collection.ImmutableArray; @@ -173,7 +172,7 @@ private StringBuilder getSortDeclaration(Sort sort) { return result.append("typedecl ").append(usedSorts.get(sort)).append(System.lineSeparator()); } - private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) { + private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) throws IllegalFormulaException { Operator op = term.op(); if (op == Junctor.IMP) { @@ -243,7 +242,7 @@ private StringBuilder translateTerm(Term term, List quanti return this.translateLogicalExists(qv, arg1); } //TODO translation of other types - return new StringBuilder(); + throw new IllegalFormulaException(""); } private StringBuilder translateLogicalFalse() { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 0d73288103f..ef25fe236f1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -3,7 +3,6 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; -import de.uka.ilkd.key.smt.IllegalFormulaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,9 +38,11 @@ private void generateTranslation() { Files.write(Paths.get(path), translation.toString().getBytes()); LOGGER.info("Saved to: " + path); } catch (IOException e) { + //TODO handle exception throw new RuntimeException(e); } } catch (IllegalFormulaException e) { + //TODO output alert to user throw new RuntimeException(e); } } From 47efaf6083e65dd6791546db8b87510773571f33 Mon Sep 17 00:00:00 2001 From: 7thHope Date: Thu, 25 Jan 2024 13:47:50 +0100 Subject: [PATCH 005/248] temp --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 0e75cdf31df..5cdab8bedb8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -104,10 +104,9 @@ protected StringBuilder buildCompleteText(StringBuilder formula, ArrayList Date: Sun, 28 Jan 2024 23:02:48 +0100 Subject: [PATCH 006/248] Added temporary mechanisms for handling isabelle intrinsic functions --- .../IsabelleTranslator.java | 32 ++++++++++++++++--- .../TranslationAction.java | 2 +- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 5cdab8bedb8..bce2b9307e1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -1,10 +1,13 @@ package de.uka.ilkd.key.gui.isabelletranslation; import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.IntegerLDT; +import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Sequent; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.logic.sort.SortImpl; import de.uka.ilkd.key.util.Debug; import org.key_project.util.collection.ImmutableArray; @@ -22,6 +25,10 @@ public class IsabelleTranslator { private final HashMap usedPredicates = new HashMap<>(); + private final HashMap intrinsicSorts = new HashMap<>(); + + private final HashMap intrinsicFunctions = new HashMap<>(); + private static final StringBuilder INTSTRING = new StringBuilder("Int"); private static final StringBuilder BOOL = new StringBuilder("bool"); @@ -72,6 +79,21 @@ public class IsabelleTranslator { private static final StringBuilder DISTINCT = new StringBuilder("distinct"); + private static final Sort BOOL_SORT = new SortImpl(new Name("boolean")); + + public IsabelleTranslator(Services services) { + //TODO add intrinsic sorts and functions that shouldnt be overridden + IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + + intrinsicSorts.put(integerLDT.targetSort(), new StringBuilder("int")); + intrinsicSorts.put(BOOL_SORT, new StringBuilder("bool")); + + intrinsicFunctions.put(integerLDT.getAdd(), PLUSSTRING); + intrinsicFunctions.put(integerLDT.getSub(), MINUSSTRING); + intrinsicFunctions.put(integerLDT.getMul(), MULTSTRING); + intrinsicFunctions.put(integerLDT.getDiv(), DIVSTRING); + } + public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { Term problem = sequentToTerm(sequent, services); // TODO find correct values @@ -113,7 +135,8 @@ private StringBuilder getNullLocale() { private StringBuilder getFunctionDeclarations() { StringBuilder declarations = new StringBuilder(); for (Function fun : usedFunctions.keySet()) { - declarations.append(getFunctionDeclaration(fun)).append(System.lineSeparator()); + if (!intrinsicFunctions.containsKey(fun)) + declarations.append(getFunctionDeclaration(fun)).append(System.lineSeparator()); } return declarations; } @@ -161,7 +184,8 @@ private StringBuilder getFreeVariableDeclarations() { private StringBuilder getSortDeclarations() { StringBuilder declaration = new StringBuilder(); for (Sort sort : usedSorts.keySet()) { - declaration.append(getSortDeclaration(sort)); + if (!intrinsicSorts.containsKey(sort)) + declaration.append(getSortDeclaration(sort)); } return declaration; } @@ -303,8 +327,8 @@ private StringBuilder buildFunction(StringBuilder name, ArrayList if (args.isEmpty()) { toReturn.append(name); } else { - toReturn.append("("); - toReturn.append(name).append(" "); + toReturn.append("(("); + toReturn.append(name).append(") "); for (StringBuilder arg : args) { toReturn.append(arg).append(" "); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index ef25fe236f1..1580767e853 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -28,8 +28,8 @@ public void actionPerformed(ActionEvent e) { } private void generateTranslation() { - IsabelleTranslator translator = new IsabelleTranslator(); KeYMediator mediator = getMediator(); + IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); try { //TODO let user choose where to save file? String path = System.getProperty("user.home") + "\\Translation.thy"; From 04409253dc6da054e2b4f958edc9f469cf5f9460 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 2 Mar 2024 14:56:05 +0100 Subject: [PATCH 007/248] Started adding handlers for translation --- .../isabelletranslation/IsabelleHandler.java | 120 ++++++++++++++++++ .../IsabelleMasterHandler.java | 108 ++++++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java new file mode 100644 index 00000000000..c3cc5237ef2 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java @@ -0,0 +1,120 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.Properties; + +/** + * General interface for routines that translate particular KeY data structures to SMT. + *

+ * SMT handlers are loaded via a {@link java.util.ServiceLoader}. + *

+ * To implement a new handler, implement this interface and add the classname to a file that + * ServiceLoader reads for SMTHandler. + * + *

Procedure

+ *

+ * SMT handlers are created using the default constructor without parameters They are always used + * within the same proof, but possibly for several proof obligations. + *

+ * After creation, the {@link #init(IsabelleMasterHandler, Services, Properties, String[])} method is called + * that injects the {@link Services} object belonging to the proof. + *

+ * During translation, an SMT handler can be asked via {@link #canHandle(Term)} if it can translate + * a term into smt. + *

+ * If it returns true, the method {@link #handle(IsabelleMasterHandler, Term)} will be called which returns + * the SMT result in form of an + * + * @author Mattias Ulbrich + * @author Jonas Schiffl + */ +public interface IsabelleHandler { + + /** + * An enumeration of the possible answers of an handler to the {@link #canHandle(Term)} method. + */ + enum Capability { + /** + * This indicates that the handler cannot translate a term + */ + UNABLE, + /** + * This indicates that the handler can translate a term + */ + YES_THIS_INSTANCE, + /** + * This indicates that the handler can translate any term with the same operator + */ + YES_THIS_OPERATOR + } + + /** + * Initialise this handler. + *

+ * This method is only called once after creation and before any other method is called. + *

+ * This method may also allocate additional resources that it needs for translation. + * + * @param masterHandler the MasterHandler coordinating the other handlers (including the one at + * hand) + * @param services the non-null services object which is relevant for this handler + * @param handlerSnippets the snippets loaded for this handler, null if no snippet property file + * is available for this handler + * @param handlerOptions arbitrary options for the handler to take into account + * @throws IOException if resources cannot be read. + */ + void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, + String[] handlerOptions) throws IOException; + + /** + * Query if this handler can translate a term. + *

+ * Test if this particular term can be translated. Usually this requires checking whether the + * toplevel operator of the term is in the list of supported operators, but the handler can also + * choose to use other aspects of the term to decide. + * + * @param term a non-null term to translate + * @return {@link Capability#YES_THIS_OPERATOR} if this handler can successfully translate any + * term with the same toplevel operator, {@link Capability#YES_THIS_INSTANCE} if this + * handler can successfully translate this particular term, {@link Capability#UNABLE} if + * this handler cannot deal with the term. + */ + default Capability canHandle(Term term) { + return canHandle(term.op()) ? Capability.YES_THIS_OPERATOR : Capability.UNABLE; + } + + /** + * Query if this handler can translate an operator. + *

+ * Test if this handler can translate any term with the given argument top level operator. + * + * @param op a non-null operator to translate + * @return true if this handler can successfully translate all terms with op as toplevel + * operator + */ + boolean canHandle(Operator op); + + /** + * Translate the given term into an SMT SExpression. + *

+ * This method will only be called if {@link #canHandle(Term)} returned true for the same term + * argument. + *

+ * The translation may add to the set of assumptions and declarations using corresponding calls + * to the {@link IsabelleMasterHandler} that it receives. + * + * @param trans the non-null master handler to which it belongs + * @param term the non-null term to translate + * @return an SExpr representing the term + * @throws SMTTranslationException if the translation fails unexpectedly. + */ + StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException; +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java new file mode 100644 index 00000000000..ba52b12a50f --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -0,0 +1,108 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.sort.Sort; + +import java.io.IOException; +import java.util.*; + +public class IsabelleMasterHandler { + + private final List exceptions = new ArrayList<>(); + + private final List handlers; + + private final List constDeclarations = new ArrayList<>(); + + + private final Set knownSymbols = new HashSet<>(); + + /** + * A list of untranslatable values + */ + private final Map unknownValues = new HashMap<>(); + + private final Set sorts = new HashSet<>(); + + private final Map handlerMap = new IdentityHashMap<>(); + + /** + * Create a new handler with the default set of smt handlers. + * + * @param services non-null services + * @param handlerNames fully qualified class names of the handlers to use. If empty, all + * available handlers are used. + * @param handlerOptions arbitrary String options for the handlers to process + * @throws IOException if the handlers cannot be loaded + */ + public IsabelleMasterHandler(Services services, String[] handlerNames, + String[] handlerOptions) throws IOException { + //TODO efficient loading of handlers. See MasterHandler in SMT + ArrayList handlers = new ArrayList<>(); + //TODO add handlers + this.handlers = handlers; + } + + public StringBuilder translate(Term problem) { + try { + IsabelleHandler cached = handlerMap.get(problem.op()); + if (cached != null) { + // There is a handler that promised to handle this operator ... + return cached.handle(this, problem); + } + + for (IsabelleHandler isabelleHandler : handlers) { + IsabelleHandler.Capability response = isabelleHandler.canHandle(problem); + switch (response) { + case YES_THIS_INSTANCE -> { + // handle this but do not cache. + return isabelleHandler.handle(this, problem); + } + case YES_THIS_OPERATOR -> { + // handle it and cache it for future instances of the op. + handlerMap.put(problem.op(), isabelleHandler); + return isabelleHandler.handle(this, problem); + } + } + } + + return handleAsUnknownValue(problem); + } catch (Exception ex) { + exceptions.add(ex); + return handleAsUnknownValue(problem); + } + } + + /** + * If no handler can handle a term, it is taken care of here. + * + * @param problem the problematic term + * @return a generic translation as unknown value + */ + private StringBuilder handleAsUnknownValue(Term problem) { + if (unknownValues.containsKey(problem)) { + return unknownValues.get(problem); + } + int number = unknownValues.size(); + StringBuilder translation; + StringBuilder abbr = new StringBuilder("unknown_" + number); + var freeVars = problem.freeVars(); + if (freeVars.isEmpty()) { + // simple case: unknown value does not depend on anything else + StringBuilder e = new StringBuilder("consts" + System.lineSeparator() + abbr + "::Any"); + addConstDeclaration(e); + translation = abbr; + } else { + // unknown value depends on quantified variables + //TODO implement this + } + unknownValues.put(problem, abbr); + return null; + } + + void addConstDeclaration(StringBuilder decl) { + constDeclarations.add(decl); + } +} From 6f7367a82c3c8750c74a30647fd9a1897fb7baf4 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 2 Mar 2024 15:07:52 +0100 Subject: [PATCH 008/248] Added LogicalVariableHandler --- .../IsabelleMasterHandler.java | 9 +++++ .../LogicalVariableHandler.java | 39 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index ba52b12a50f..d939c5580f8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -105,4 +105,13 @@ private StringBuilder handleAsUnknownValue(Term problem) { void addConstDeclaration(StringBuilder decl) { constDeclarations.add(decl); } + + boolean isKnownSort(Sort s) { + return sorts.contains(s); + } + + StringBuilder createSortDecl(Sort sort) { + //TODO IMPLEMENT + return new StringBuilder(); + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java new file mode 100644 index 00000000000..bb91fbbea4a --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -0,0 +1,39 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.LogicVariable; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.sort.Sort; + +import java.util.Properties; + +public class LogicalVariableHandler implements IsabelleHandler { + + static final String VAR_PREFIX = "var_"; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { + + } + + @Override + public boolean canHandle(Operator op) { + return op instanceof LogicVariable; + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { + Sort sort = term.sort(); + if (!trans.isKnownSort(sort)) { + trans.createSortDecl(sort); + } + return makeVarRef(term.toString(), sort); + } + + public StringBuilder makeVarRef(String name, Sort sort) { + StringBuilder result = new StringBuilder("("); + result.append(VAR_PREFIX).append(name).append("::").append(sort.name()).append(")"); + return result; + } +} From 5ed77c6396d0433da915e2729bbdfc892b670c60 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 2 Mar 2024 15:29:24 +0100 Subject: [PATCH 009/248] Added BooleanOpHandler --- .../isabelletranslation/BooleanOpHandler.java | 58 +++++++++++++++++++ .../IsabelleMasterHandler.java | 15 +++++ 2 files changed, 73 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java new file mode 100644 index 00000000000..fc60c517a21 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -0,0 +1,58 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.BooleanLDT; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Equality; +import de.uka.ilkd.key.logic.op.Junctor; +import de.uka.ilkd.key.logic.op.Operator; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class BooleanOpHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + + { + supportedOperators.put(Junctor.AND, new StringBuilder("\\and")); + supportedOperators.put(Junctor.OR, new StringBuilder("\\or")); + supportedOperators.put(Junctor.IMP, new StringBuilder("-->")); + supportedOperators.put(Junctor.NOT, new StringBuilder("\\not")); + supportedOperators.put(Junctor.FALSE, new StringBuilder("False")); + supportedOperators.put(Junctor.TRUE, new StringBuilder("True")); + supportedOperators.put(Equality.EQV, new StringBuilder("<-->")); + } + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { + BooleanLDT ldt = services.getTypeConverter().getBooleanLDT(); + Operator logicFalse = ldt.getFalseConst(); + supportedOperators.put(logicFalse, new StringBuilder("False")); + + Operator logicTrue = ldt.getTrueConst(); + supportedOperators.put(logicTrue, new StringBuilder("True")); + //TODO add boolean declarations + masterHandler.addSort(ldt.targetSort()); + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { + List children = trans.translate(term.subs()); + StringBuilder result = new StringBuilder(); + Operator op = term.op(); + result.append("((").append(supportedOperators.get(op)).append(")"); + for (StringBuilder child : children) { + result.append(child); + } + result.append(")"); + return result; + } + +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index d939c5580f8..c401735d2ab 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -75,6 +75,14 @@ public StringBuilder translate(Term problem) { } } + public List translate(Iterable terms) { + List result = new LinkedList<>(); + for (Term term : terms) { + result.add(translate(term)); + } + return result; + } + /** * If no handler can handle a term, it is taken care of here. * @@ -114,4 +122,11 @@ StringBuilder createSortDecl(Sort sort) { //TODO IMPLEMENT return new StringBuilder(); } + + boolean addSort(Sort sort) { + if (!isKnownSort(sort)) { + sorts.add(sort); + } + return false; + } } From ac9c2bcd126d17711f5eaaf0b46038358ce7059c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 2 Mar 2024 16:12:23 +0100 Subject: [PATCH 010/248] Added UninterpretedSymbolsHandler Translation now uses IsabelleMasterHandler --- .../isabelletranslation/BooleanOpHandler.java | 8 +-- .../IsabelleMasterHandler.java | 22 +++++- .../IsabelleTranslator.java | 9 ++- .../UninterpretedSymbolsHandler.java | 69 +++++++++++++++++++ 4 files changed, 102 insertions(+), 6 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java index fc60c517a21..2239af6b3ac 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -16,10 +16,10 @@ public class BooleanOpHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); { - supportedOperators.put(Junctor.AND, new StringBuilder("\\and")); - supportedOperators.put(Junctor.OR, new StringBuilder("\\or")); + supportedOperators.put(Junctor.AND, new StringBuilder("\\")); + supportedOperators.put(Junctor.OR, new StringBuilder("\\")); supportedOperators.put(Junctor.IMP, new StringBuilder("-->")); - supportedOperators.put(Junctor.NOT, new StringBuilder("\\not")); + supportedOperators.put(Junctor.NOT, new StringBuilder("Not")); supportedOperators.put(Junctor.FALSE, new StringBuilder("False")); supportedOperators.put(Junctor.TRUE, new StringBuilder("True")); supportedOperators.put(Equality.EQV, new StringBuilder("<-->")); @@ -49,7 +49,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Operator op = term.op(); result.append("((").append(supportedOperators.get(op)).append(")"); for (StringBuilder child : children) { - result.append(child); + result.append(" ").append(child); } result.append(")"); return result; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index c401735d2ab..d7a23dc0fa6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -4,6 +4,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.newsmt2.SExpr; import java.io.IOException; import java.util.*; @@ -17,7 +18,7 @@ public class IsabelleMasterHandler { private final List constDeclarations = new ArrayList<>(); - private final Set knownSymbols = new HashSet<>(); + private final Set knownSymbols = new HashSet<>(); /** * A list of untranslatable values @@ -41,7 +42,15 @@ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { //TODO efficient loading of handlers. See MasterHandler in SMT ArrayList handlers = new ArrayList<>(); + BooleanOpHandler booleanOpHandler = new BooleanOpHandler(); + booleanOpHandler.init(this, services, null, handlerOptions); + + LogicalVariableHandler logicalVariableHandler = new LogicalVariableHandler(); + logicalVariableHandler.init(this, services, null, handlerOptions); //TODO add handlers + handlers.add(booleanOpHandler); + handlers.add(logicalVariableHandler); + handlers.add(new UninterpretedSymbolsHandler()); this.handlers = handlers; } @@ -129,4 +138,15 @@ boolean addSort(Sort sort) { } return false; } + + boolean isKnownSymbol(String name) { + return knownSymbols.contains(name); + } + + public void addDeclaration(SExpr sExpr) { + } + + public void addKnownSymbol(String name) { + knownSymbols.add(name); + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index bce2b9307e1..89bbec35086 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -11,6 +11,7 @@ import de.uka.ilkd.key.util.Debug; import org.key_project.util.collection.ImmutableArray; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -97,7 +98,13 @@ public IsabelleTranslator(Services services) { public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { Term problem = sequentToTerm(sequent, services); // TODO find correct values - StringBuilder hb = buildCompleteText(translateTerm(problem, new ArrayList<>(), services), new ArrayList<>()); + IsabelleMasterHandler masterHandler; + try { + masterHandler = new IsabelleMasterHandler(services, new String[0], new String[0]); + } catch (IOException e) { + throw new RuntimeException(e); + } + StringBuilder hb = buildCompleteText(masterHandler.translate(problem), new ArrayList<>()); return hb; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java new file mode 100644 index 00000000000..dbb7bde6fe1 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -0,0 +1,69 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.ProgramVariable; +import de.uka.ilkd.key.logic.op.SortedOperator; +import de.uka.ilkd.key.smt.SMTTranslationException; +import de.uka.ilkd.key.smt.newsmt2.HandlerUtil; + +import java.util.List; +import java.util.Properties; + +/** + * This handler is a fallback handler that introduces a new uninterpreted function symbol with + * prefix "u_". + *

+ * According declarations are added. + */ +public class UninterpretedSymbolsHandler implements IsabelleHandler { + + public final static String PREFIX = "var_"; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, + String[] handlerOptions) { + } + + @Override + public boolean canHandle(Operator op) { + return (op instanceof Function && !bindsVars(op)) || op instanceof ProgramVariable; + } + + /* + * return true if op binds in at least one argument. + */ + private static boolean bindsVars(Operator op) { + for (int i = 0; i < op.arity(); i++) { + if (op.bindVarsAt(i)) { + return true; + } + } + return false; + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + SortedOperator op = (SortedOperator) term.op(); + String name = PREFIX + op.name().toString(); + if (!trans.isKnownSymbol(name)) { + trans.addDeclaration(HandlerUtil.funDeclaration(op, name)); + trans.addKnownSymbol(name); + } + + List children = trans.translate(term.subs()); + StringBuilder result = new StringBuilder("("); + result.append(name); + for (StringBuilder child : children) { + result.append(" ").append(child); + } + result.append(")"); + return result; + } + +} From 5b87e7c62939c597eebd1f9be621e7ac50f32208 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 2 Mar 2024 22:57:45 +0100 Subject: [PATCH 011/248] Added handlers for integers --- .../isabelletranslation/IntegerOpHandler.java | 69 +++++++++++++++++++ .../IsabelleMasterHandler.java | 14 ++++ .../NumberConstantsHandler.java | 49 +++++++++++++ .../PolymorphicHandler.java | 58 ++++++++++++++++ 4 files changed, 190 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java new file mode 100644 index 00000000000..fc697948992 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -0,0 +1,69 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.IntegerLDT; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * This SMT translation handler takes care of integer expressions. + *

+ * This includes the unary and binary integer operations and relational operations. + * + * @author Jonas Schiffl + */ +public class IntegerOpHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + private IntegerLDT integerLDT; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, + String[] handlerOptions) { + supportedOperators.clear(); + this.integerLDT = services.getTypeConverter().getIntegerLDT(); + + supportedOperators.put(integerLDT.getAdd(), "+"); + supportedOperators.put(integerLDT.getMul(), "*"); + supportedOperators.put(integerLDT.getSub(), "-"); + supportedOperators.put(integerLDT.getDiv(), "euclDiv"); + supportedOperators.put(integerLDT.getMod(), "euclMod"); + supportedOperators.put(integerLDT.getNeg(), "-"); + + supportedOperators.put(integerLDT.getLessOrEquals(), "<="); + supportedOperators.put(integerLDT.getLessThan(), "<"); + supportedOperators.put(integerLDT.getGreaterOrEquals(), ">="); + supportedOperators.put(integerLDT.getGreaterThan(), ">"); + + //TODO add jArithmetics locale declaration + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + List children = trans.translate(term.subs()); + Operator op = term.op(); + + StringBuilder result = new StringBuilder(); + result.append("(("); + result.append(supportedOperators.get(op)); + result.append(")"); + for (StringBuilder child : children) { + result.append(" ").append(child); + } + result.append(")"); + return result; + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index d7a23dc0fa6..9a04393a543 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -47,9 +47,23 @@ public IsabelleMasterHandler(Services services, String[] handlerNames, LogicalVariableHandler logicalVariableHandler = new LogicalVariableHandler(); logicalVariableHandler.init(this, services, null, handlerOptions); + + IntegerOpHandler integerOpHandler = new IntegerOpHandler(); + integerOpHandler.init(this, services, null, handlerOptions); + + NumberConstantsHandler numberConstantsHandler = new NumberConstantsHandler(); + numberConstantsHandler.init(this, services, null, handlerOptions); + + PolymorphicHandler polymorphicHandler = new PolymorphicHandler(); + polymorphicHandler.init(this, services, null, handlerOptions); //TODO add handlers handlers.add(booleanOpHandler); handlers.add(logicalVariableHandler); + handlers.add(integerOpHandler); + handlers.add(numberConstantsHandler); + handlers.add(polymorphicHandler); + + handlers.add(new UninterpretedSymbolsHandler()); this.handlers = handlers; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java new file mode 100644 index 00000000000..3ee96f8db4f --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java @@ -0,0 +1,49 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.AbstractTermTransformer; +import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.Operator; + +import java.util.Properties; + +/** + * This handler is responsible to render number constants Z(3(2(1(#)))) as "123". + *

+ * TODO Should that also do character constants (C) with the same machinery? + */ +public class NumberConstantsHandler implements IsabelleHandler { + + private Function numberSymbol; + private Services services; + private Function negNumberSign; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, + String[] handlerOptions) { + this.services = services; + numberSymbol = services.getTypeConverter().getIntegerLDT().getNumberSymbol(); + negNumberSign = services.getTypeConverter().getIntegerLDT().getNegativeNumberSign(); + } + + @Override + public boolean canHandle(Operator op) { + return op == numberSymbol; + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { + if (term.sub(0).op() == negNumberSign) { + String s = AbstractTermTransformer.convertToDecimalString(term, services); + return new StringBuilder("(-").append(s).append("::int)"); + } else { + String string = AbstractTermTransformer.convertToDecimalString(term, services); + return new StringBuilder("(").append(string).append("::int)"); + } + } + +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java new file mode 100644 index 00000000000..31d166c7427 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java @@ -0,0 +1,58 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Equality; +import de.uka.ilkd.key.logic.op.IfThenElse; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.util.List; +import java.util.Properties; + +/** + * This handler treats polymorphic symbols, in particular if-then-else and equals. + * + * @author Jonas Schiffl + */ +public class PolymorphicHandler implements IsabelleHandler { + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, + String[] handlerOptions) { + // nothing to be done + // there are also no snippets. + } + + @Override + public boolean canHandle(Operator op) { + return op == Equality.EQUALS || op == IfThenElse.IF_THEN_ELSE; + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + Operator op = term.op(); + StringBuilder result; + if (op == Equality.EQUALS) { + List children = trans.translate(term.subs()); + result = new StringBuilder("("); + result.append(children.get(0)).append("=").append(children.get(1)).append(")"); + return result; + } + + if (op == IfThenElse.IF_THEN_ELSE) { + List children = trans.translate(term.subs()); + result = new StringBuilder("(if ("); + result.append(children.get(0)).append(") then "); + result.append(children.get(1)).append(" else "); + result.append(children.get(2)).append(")"); + return result; + } + + throw new Error("unreachable"); + } + +} From 2bf6cfa87d21484f1be6b1aea0bf71100ba76354 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 00:48:19 +0100 Subject: [PATCH 012/248] Preambles and handlers are now loaded from property files --- .../IsabelleHandlerServices.java | 251 ++++++++++++++++++ .../IsabelleMasterHandler.java | 44 ++- .../IsabelleTranslator.java | 8 +- .../UninterpretedSymbolsHandler.java | 3 +- .../UninterpretedSymbolsHandler.preamble.xml | 207 +++++++++++++++ .../isabelletranslation/defaultHandlers.txt | 7 + 6 files changed, 489 insertions(+), 31 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java create mode 100644 keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml create mode 100644 keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java new file mode 100644 index 00000000000..d400a49a204 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java @@ -0,0 +1,251 @@ +/* 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.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import org.jspecify.annotations.NonNull; +import org.key_project.util.Streams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +/** + * This class provides some infrastructure to the smt translation process. + *

+ * In particular, it collects the preamble and the snippets for the handlers such that they need not + * be read from disk multiple times. + *

+ * This class is a singleton. + * + * @author Mattias Ulbrich + * @author Alicia Appelhagen (load handlers from handler names array instead of ServiceLoader) + */ +public class IsabelleHandlerServices { + + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleHandlerServices.class); + + /** + * A .txt file containing a default handler list to load via + * {@link #getTemplateHandlers(String[])} if that method's parameter is an empty handlerNames + * array. + */ + private static final String DEFAULT_HANDLERS = "defaultHandlers.txt"; + + /** + * Singleton instance + */ + private static IsabelleHandlerServices theInstance; + + /** + * A map from template handler objects to their smt2 snippets. + *

+ * Before removing the ServiceLoader from #getOriginalHandlers, an IdentityHashMap was used + * here. Since the removal of the ServiceLoader leads to snippetMap being modified even after + * creation, concurrent modification by different solver threads becomes possible. Hence, either + * every access to snippetMap needs to be synchronized or it needs to be a ConcurrentHashMap - + * which is not an IdentityHashMap anymore. This should not be a problem as the SMTHandlers + * don't override equals(). + */ + private final Map snippetMap = new ConcurrentHashMap<>(); + + // preamble is volatile since sonarcube tells me the synchronisation scheme + // for loading would be broken otherwise. (MU 2021) + /** + * The smt2 preamble + */ + private volatile String preamble; + + /** + * lock for synchronisation + */ + private final Object handlerModificationLock = new Object(); + + /** + * Get the instance of this singleton. + * + * @return non-null instance of this class. Always the same. + */ + public static IsabelleHandlerServices getInstance() { + if (theInstance == null) { + theInstance = new IsabelleHandlerServices(); + } + return theInstance; + } + + /** + * Load the original/template SMTHandler instances (from the snippetMap) of all handlers + * specified as arguments. Add fresh handlers to the snippetMap and load the snippets that + * belong to these instances if that has not happened yet for any object of a given handler + * class. + * + * Caution: Do not call this method too often since it may add to the static map of + * instances to snippets. + *

+ * It would be a good idea to call this method (at most) once for each solver type with a custom + * array of handler names. + *

+ * An empty handlerNames list leads to the usage of the handlers defined by defaultHandlers.txt. + * + * @param handlerNames a non-null list of non-null strings with class names (s. above) + * @return a fresh collection containing only the original SMTHandlers from the snippetMap's key + * set that match the given handler names. The collection's order matches that of the + * names as well. + * @throws IOException if loading the snippet Properties for a handler class fails + */ + public Collection getTemplateHandlers(String[] handlerNames) throws IOException { + // If handlerNames is empty, use default handlerNames list. + if (handlerNames.length == 0) { + InputStream stream = IsabelleHandlerServices.class.getResourceAsStream(DEFAULT_HANDLERS); + BufferedReader reader = + new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + handlerNames = reader.lines().toArray(String[]::new); + } + Collection result = new LinkedList<>(); + for (String name : handlerNames) { + try { + Class handlerClass = (Class) Class.forName(name); + if (findHandler(handlerClass, result)) { + continue; + } + synchronized (handlerModificationLock) { + /* + * Make sure that each handler is added to the template handlers (keyset of + * snippetMap) at most once and that every thread waits for the result. Also, + * every search access on smtProperties should be synchronized in order to avoid + * concurrent modification. + */ + if (!findHandler(handlerClass, result)) { + IsabelleHandler handler = handlerClass.getConstructor().newInstance(); + result.add(handler); + Properties handlerSnippets = loadSnippets(handlerClass); + if (handlerSnippets != null) { + snippetMap.put(handler, handlerSnippets); + } + } + } + } catch (ClassNotFoundException e) { + LOGGER.warn(String.format("Could not load IsabelleHandler:%s%s", System.lineSeparator(), + e.getMessage())); + } catch (NoSuchMethodException | InvocationTargetException | InstantiationException + | IllegalAccessException e) { + LOGGER.warn(String.format("Could not create IsabelleHandler:%s%s", + System.lineSeparator(), e.getMessage())); + } + } + // TODO make sure that the order of handlers in result is the same as the order + // of their names in the name array + return result; + } + + // Search for a handler of the given class in the snippetMap and if it exists, add it to + // the result collection. + private boolean findHandler(Class clazz, Collection result) { + Optional handler = + snippetMap.keySet().stream().filter(h -> h.getClass().equals(clazz)).findFirst(); + if (handler.isPresent()) { + if (!result.contains(handler.get())) { + result.add(handler.get()); + } + return true; + } + return false; + } + + /** + * Get a copy of freshly created {@link IsabelleHandler}s by cloning the reference handlers. They can + * be used to translate problems to SMT. + * + * @param services passed on to the handlers for initialisation + * @param handlerNames the fully classified class names of the SMTHandlers to be used If this is + * empty or null, all existing handlers will be used. + * @param handlerOptions arbitrary String options for the SMTHandlers + * @param mh passed on to the handlers for initialisation + * @return a freshly created list of freshly created handlers + * @throws IOException if the resources cannot be read + */ + + public List getFreshHandlers(Services services, @NonNull String[] handlerNames, + String[] handlerOptions, IsabelleMasterHandler mh) throws IOException { + + List result = new ArrayList<>(); + + // Possibly problematic: snippetMap may be modified by another thread while + // calling snippetMap.get(handler) + // -> concurrent modification? + for (IsabelleHandler handler : getTemplateHandlers(handlerNames)) { + // After getOriginalHandlers(handlerNames), snippets for all handlers are + try { + IsabelleHandler copy = handler.getClass().getConstructor().newInstance(); + /* + * Either use that synchronized block or make snippetMap a ConcurrentHashMap: + * Properties snippet; synchronized (handlerModificationLock) { // Avoid concurrent + * modification of the snippetMap while accessing it. snippet = + * snippetMap.get(handler); } + */ + copy.init(mh, services, snippetMap.get(handler), handlerOptions); + result.add(copy); + } catch (Exception e) { + throw new IOException(e); + } + } + + return result; + } + + /** + * Look up the resource for the snippets of a particular smt handler class. They must be in the + * same package and have the name of the class with ".preamble.xml" attached. + * + * @param aClass class reference for localisation + * @return freshly created property object, null if the resource does not exist + * @throws IOException may be thrown during reading of the resource + */ + private static Properties loadSnippets(Class aClass) throws IOException { + String resourceName = aClass.getSimpleName() + ".preamble.xml"; + URL resource = aClass.getResource(resourceName); + if (resource != null) { + Properties snippets = new Properties(); + try (InputStream is = resource.openStream()) { + snippets.loadFromXML(is); + } + return snippets; + } + return null; + } + + /** + * There is a fixed SMT2lib preamble first sent to the solver. + *

+ * Get this preamble. + * + * @return a non-null string, always the same + */ + public String getPreamble() { + try { + if (preamble == null) { + synchronized (handlerModificationLock) { + if (preamble == null) { + // make sure this is only ever read once and everyone + // waits for it. + preamble = Streams.toString( + IsabelleHandlerServices.class.getResourceAsStream("preamble.smt2")); + } + } + } + return preamble; + } catch (IOException e) { + // the caller cannot really deal with exceptions ... + throw new RuntimeException(e); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 9a04393a543..5487770c032 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -4,7 +4,6 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.sort.Sort; -import de.uka.ilkd.key.smt.newsmt2.SExpr; import java.io.IOException; import java.util.*; @@ -15,6 +14,8 @@ public class IsabelleMasterHandler { private final List handlers; + private final List preambles = new ArrayList<>(); + private final List constDeclarations = new ArrayList<>(); @@ -41,30 +42,7 @@ public class IsabelleMasterHandler { public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { //TODO efficient loading of handlers. See MasterHandler in SMT - ArrayList handlers = new ArrayList<>(); - BooleanOpHandler booleanOpHandler = new BooleanOpHandler(); - booleanOpHandler.init(this, services, null, handlerOptions); - - LogicalVariableHandler logicalVariableHandler = new LogicalVariableHandler(); - logicalVariableHandler.init(this, services, null, handlerOptions); - - IntegerOpHandler integerOpHandler = new IntegerOpHandler(); - integerOpHandler.init(this, services, null, handlerOptions); - - NumberConstantsHandler numberConstantsHandler = new NumberConstantsHandler(); - numberConstantsHandler.init(this, services, null, handlerOptions); - - PolymorphicHandler polymorphicHandler = new PolymorphicHandler(); - polymorphicHandler.init(this, services, null, handlerOptions); - //TODO add handlers - handlers.add(booleanOpHandler); - handlers.add(logicalVariableHandler); - handlers.add(integerOpHandler); - handlers.add(numberConstantsHandler); - handlers.add(polymorphicHandler); - - - handlers.add(new UninterpretedSymbolsHandler()); + List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); this.handlers = handlers; } @@ -157,10 +135,24 @@ boolean isKnownSymbol(String name) { return knownSymbols.contains(name); } - public void addDeclaration(SExpr sExpr) { + public void addPreamble(StringBuilder stringBuilder) { + preambles.add(stringBuilder); + } + + public List getPreambles() { + return preambles; } public void addKnownSymbol(String name) { knownSymbols.add(name); } + + public void addPreambles(Properties handlerSnippets) { + for (Map.Entry entry : handlerSnippets.entrySet()) { + String key = (String) entry.getKey(); + if (key.endsWith(".preamble")) { + addPreamble(new StringBuilder((String) entry.getValue())); + } + } + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 89bbec35086..52c4a5e7aa6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -104,20 +104,22 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) } catch (IOException e) { throw new RuntimeException(e); } - StringBuilder hb = buildCompleteText(masterHandler.translate(problem), new ArrayList<>()); + StringBuilder hb = buildCompleteText(masterHandler.translate(problem), new ArrayList<>(), masterHandler); return hb; } - protected StringBuilder buildCompleteText(StringBuilder formula, ArrayList types) { + protected StringBuilder buildCompleteText(StringBuilder formula, ArrayList types, IsabelleMasterHandler masterHandler) { //TODO ensure usedSorts etc have the right values? StringBuilder result = new StringBuilder(); result.append("theory Translation imports Main begin").append(System.lineSeparator()); result.append(getSortDeclarations()); + for (StringBuilder preamble : masterHandler.getPreambles()) { + result.append(preamble); + } result.append("locale varsAndFunctions =").append(System.lineSeparator()); //TODO additional types of JFOL hierarchy and assumptions - result.append(getNullLocale()); result.append(getFunctionDeclarations()); result.append(getPredicateDeclarations()); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index dbb7bde6fe1..780e4123df6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -10,7 +10,6 @@ import de.uka.ilkd.key.logic.op.ProgramVariable; import de.uka.ilkd.key.logic.op.SortedOperator; import de.uka.ilkd.key.smt.SMTTranslationException; -import de.uka.ilkd.key.smt.newsmt2.HandlerUtil; import java.util.List; import java.util.Properties; @@ -28,6 +27,7 @@ public class UninterpretedSymbolsHandler implements IsabelleHandler { @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { + masterHandler.addPreambles(handlerSnippets); } @Override @@ -52,7 +52,6 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr SortedOperator op = (SortedOperator) term.op(); String name = PREFIX + op.name().toString(); if (!trans.isKnownSymbol(name)) { - trans.addDeclaration(HandlerUtil.funDeclaration(op, name)); trans.addKnownSymbol(name); } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml new file mode 100644 index 00000000000..dfd115e999b --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -0,0 +1,207 @@ + + + + +General preamble + +declare [[coercion_enabled]] +declare [[coercion_map image]] + + +typedecl Any + + +consts +int_subset_inAny::"Any set" +int2Any::"int\<Rightarrow>Any" +Any2int::"Any\<Rightarrow>int" + +axiomatization where int_sub_Any:"type_definition int2Any Any2int (int_subset_inAny)" +declare [[coercion int2Any]] + + +consts +bool_Image::"Any set" +bool2Any::"bool\<Rightarrow>Any" +Any2bool::"Any\<Rightarrow>bool" + +axiomatization where bool_sub_Any:"type_definition bool2Any Any2bool (bool_Image)" +declare [[coercion bool2Any]] + +consts +bottom::"Any" + +specification (bottom) "bottom = bottom" + by simp + +typedef (overloaded) Bottom = "{bottom}" + morphisms Bottom_to_Any Any_to_Bottom + by simp + +declare [[coercion Bottom_to_Any]] + + + + +consts +Object_UNIV::"Any set" + + +specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::Any set)" "bottom:Object_UNIV" + by auto + +lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::Any set) \<and> bottom:Object_UNIV" + by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) + + +typedef Object = "Object_UNIV" + morphisms Object_to_Any Any_to_Object + using Object_UNIV_specification by auto + +declare [[coercion Object_to_Any]] + +lemma Object_subset_Any:"(UNIV::Object set) \<subseteq> (UNIV::Any set)" + by simp + +lemma bottom_in_Object:"bottom \<in> (UNIV::Object set)" + using Object_UNIV_specification + using type_definition.Rep_range type_definition_Object by blast + +typedecl Field +(* "TODO: implement Field type" *) + +typedef LocSet = "UNIV::(Object \<times> Field) set set" + by simp + +declare [[coercion Rep_LocSet]] + +consts +LocSet_Image::"Any set" +LocSet2Any::"LocSet\<Rightarrow>Any" +Any2LocSet::"Any\<Rightarrow>LocSet" + +axiomatization where LocSet_sub_Any:"type_definition LocSet2Any Any2LocSet LocSet_Image" + +declare [[coercion LocSet2Any]] + +typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> Any) set" + by simp + +declare [[coercion Rep_Heap]] + +consts +Heap_Image::"Any set" +Heap2Any::"Heap\<Rightarrow>Any" +Any2Heap::"Any\<Rightarrow>Heap" + +axiomatization where Heap_sub_Any:"type_definition Heap2Any Any2Heap Heap_Image" + +declare [[coercion Heap2Any]] + +class Any = + fixes to_Any::"'a\<Rightarrow>Any" + fixes cast::"Any\<Rightarrow>'a" + fixes exact_instance::"'a\<Rightarrow>bool" + + +instantiation Any::Any +begin +definition "to_Any_Any \<equiv> (id::Any\<Rightarrow>Any)" +definition "cast_Any \<equiv> (id::Any\<Rightarrow>Any)" +instance by standard +end + + + +instantiation int::Any +begin +definition "to_Any_int \<equiv> int2Any" +definition "cast_int \<equiv> Any2int" +instance by standard +end + +instantiation bool::Any +begin +definition "to_Any_bool \<equiv> bool2Any" +definition "cast_bool \<equiv> Any2bool" +instance by standard +end + +instantiation LocSet::Any +begin +definition "to_Any_LocSet \<equiv> LocSet2Any" +definition "cast_LocSet \<equiv> Any2LocSet" +instance by standard +end + +class Object = Any + +instantiation Object::Object +begin +definition "cast_Object \<equiv> Any_to_Object" +definition "to_Any_Object \<equiv> Object_to_Any" +instance by standard +end + +typedef (overloaded) Null = "{bottom}" + morphisms Null_to_Any Any_to_Null + by simp + +declare [[coercion Null_to_Any]] + +lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast + +lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" + using bottom_Null_set bottom_in_Object by auto + +definition "null \<equiv> Any_to_Null bottom" + +instantiation Null::Object +begin +definition "to_Any_Null \<equiv> Null_to_Any" +definition "cast_Null \<equiv> Any_to_Null" +instance by standard +end + +abbreviation "Null_to_Object\<equiv>Any_to_Object \<circ> Null_to_Any" + +declare [[coercion Null_to_Object]] + +consts +select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::Any)" +store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>Any\<Rightarrow>Heap" +create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" +anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" +wellFormed::"Heap\<Rightarrow>bool" +created::"Field" +locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" + +definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" + +section \<open>select Axioms\<close> +axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (Any_to_Object x) else (select h o2 f2))" +and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_Any obj)\<noteq>null) \<and> f=created) then cast (Any_to_Object True) else select h o2 f)" +and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" + + +section \<open>wellFormed Axioms\<close> +axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" +and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" +and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" + +definition instance_All_useSet::"Any\<Rightarrow>('a::Any) set\<Rightarrow>bool" + where "instance_All_useSet x y \<equiv> x : image to_Any y" + +definition instance_All_useRep::"Any\<Rightarrow>'a::Any\<Rightarrow>bool" + where "instance_All_useRep x y \<equiv> \<exists>z::'a. to_Any z = x" + +definition instance_All_UnivRep::"Any\<Rightarrow>'a::Any\<Rightarrow>bool" + where "instance_All_UnivRep x y \<equiv> x : image to_Any (UNIV::'a set)" + +abbreviation instance_All_useSet2::"Any\<Rightarrow>Any set\<Rightarrow>bool" + where "instance_All_useSet2 x y \<equiv> x : y" + + + + diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt new file mode 100644 index 00000000000..438e96d2045 --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -0,0 +1,7 @@ +de.uka.ilkd.key.gui.isabelletranslation.BooleanOpHandler +de.uka.ilkd.key.gui.isabelletranslation.PolymorphicHandler +de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler +de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler +de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler +de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler +de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From 904a5dc88636cbc799cf105ea3477b88443d3b20 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 12:31:00 +0100 Subject: [PATCH 013/248] Now adds locales to Translation like jArithmetics --- .../isabelletranslation/IntegerOpHandler.java | 2 +- .../IsabelleMasterHandler.java | 14 +- .../IsabelleTranslator.java | 38 +-- .../UninterpretedSymbolsHandler.java | 2 +- .../IntegerOpHandler.preamble.xml | 251 ++++++++++++++++++ .../UninterpretedSymbolsHandler.preamble.xml | 4 +- 6 files changed, 290 insertions(+), 21 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index fc697948992..7269cb9b918 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -43,7 +43,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert supportedOperators.put(integerLDT.getGreaterOrEquals(), ">="); supportedOperators.put(integerLDT.getGreaterThan(), ">"); - //TODO add jArithmetics locale declaration + masterHandler.addPreamblesLocales(handlerSnippets); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 5487770c032..2871e80f599 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -29,6 +29,7 @@ public class IsabelleMasterHandler { private final Set sorts = new HashSet<>(); private final Map handlerMap = new IdentityHashMap<>(); + private final List locales = new ArrayList<>(); /** * Create a new handler with the default set of smt handlers. @@ -147,12 +148,23 @@ public void addKnownSymbol(String name) { knownSymbols.add(name); } - public void addPreambles(Properties handlerSnippets) { + public void addPreamblesLocales(Properties handlerSnippets) { for (Map.Entry entry : handlerSnippets.entrySet()) { String key = (String) entry.getKey(); if (key.endsWith(".preamble")) { addPreamble(new StringBuilder((String) entry.getValue())); } + if (key.endsWith(".locale")) { + addLocale(new StringBuilder((String) entry.getValue())); + } } } + + public void addLocale(StringBuilder stringBuilder) { + locales.add(stringBuilder); + } + + public List getLocales() { + return locales; + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 52c4a5e7aa6..a7595362950 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -82,6 +82,8 @@ public class IsabelleTranslator { private static final Sort BOOL_SORT = new SortImpl(new Name("boolean")); + private static final String LINE_ENDING = "\n"; + public IsabelleTranslator(Services services) { //TODO add intrinsic sorts and functions that shouldnt be overridden IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); @@ -104,40 +106,46 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) } catch (IOException e) { throw new RuntimeException(e); } - StringBuilder hb = buildCompleteText(masterHandler.translate(problem), new ArrayList<>(), masterHandler); - return hb; - } + StringBuilder formula = masterHandler.translate(problem); - protected StringBuilder buildCompleteText(StringBuilder formula, ArrayList types, IsabelleMasterHandler masterHandler) { - //TODO ensure usedSorts etc have the right values? StringBuilder result = new StringBuilder(); - result.append("theory Translation imports Main begin").append(System.lineSeparator()); + result.append("theory Translation imports Main begin").append(LINE_ENDING); result.append(getSortDeclarations()); for (StringBuilder preamble : masterHandler.getPreambles()) { - result.append(preamble); + result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); + } + + result.append("locale varsAndFunctions"); + List locales = masterHandler.getLocales(); + + if (!locales.isEmpty()) { + result.append(" = "); + result.append(locales.remove(0)); + } + for (StringBuilder locale : locales) { + result.append(" + ").append(locale); } - result.append("locale varsAndFunctions =").append(System.lineSeparator()); //TODO additional types of JFOL hierarchy and assumptions result.append(getFunctionDeclarations()); result.append(getPredicateDeclarations()); result.append(getFreeVariableDeclarations()); - result.append("begin").append(System.lineSeparator()); + result.append("begin").append(LINE_ENDING); result.append("theorem solve: \""); result.append(formula).append("\""); - result.append(System.lineSeparator()); + result.append(LINE_ENDING); - return result.append("end").append(System.lineSeparator()).append("end"); + return result.append("end").append(LINE_ENDING).append("end"); } private StringBuilder getNullLocale() { //TODO handle null correctly StringBuilder result = new StringBuilder(); - result.append("fixes null::'a").append(System.lineSeparator()); + result.append("fixes null::'a").append(LINE_ENDING); return result; } @@ -145,7 +153,7 @@ private StringBuilder getFunctionDeclarations() { StringBuilder declarations = new StringBuilder(); for (Function fun : usedFunctions.keySet()) { if (!intrinsicFunctions.containsKey(fun)) - declarations.append(getFunctionDeclaration(fun)).append(System.lineSeparator()); + declarations.append(getFunctionDeclaration(fun)).append(LINE_ENDING); } return declarations; } @@ -166,7 +174,7 @@ private StringBuilder getFunctionDeclaration(Function fun) { private StringBuilder getPredicateDeclarations() { StringBuilder declarations = new StringBuilder(); for (Function fun : usedPredicates.keySet()) { - declarations.append(getPredicateDeclaration(fun)).append(System.lineSeparator()); + declarations.append(getPredicateDeclaration(fun)).append(LINE_ENDING); } return declarations; } @@ -201,7 +209,7 @@ private StringBuilder getSortDeclarations() { private StringBuilder getSortDeclaration(Sort sort) { StringBuilder result = new StringBuilder(); - return result.append("typedecl ").append(usedSorts.get(sort)).append(System.lineSeparator()); + return result.append("typedecl ").append(usedSorts.get(sort)).append(LINE_ENDING); } private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) throws IllegalFormulaException { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 780e4123df6..1c0400707f4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -27,7 +27,7 @@ public class UninterpretedSymbolsHandler implements IsabelleHandler { @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { - masterHandler.addPreambles(handlerSnippets); + masterHandler.addPreamblesLocales(handlerSnippets); } @Override diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml new file mode 100644 index 00000000000..d08d36f37b2 --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml @@ -0,0 +1,251 @@ + + + + +General preamble + + locale jArithmetics = + fixes jDiv::"int\<Rightarrow>int\<Rightarrow>int" + assumes jDiv_def [simp]: "b\<noteq>0 \<Longrightarrow> jDiv a b = +(if ((a\<le>0 \<and> b<0) \<or> (a\<ge>0 \<and> b>0) \<or> (b dvd a)) then (a div b) +else ((a div b) + 1))" + +fixes euclMod::"int\<Rightarrow>int\<Rightarrow>int" +assumes eucl_Mod_def [simp]: "l\<noteq>0 \<Longrightarrow> euclMod k l = (if (k mod l < 0) then ((k mod l) + abs(l)) +else (k mod l))" + +fixes div_nonzero::"int\<Rightarrow>int\<Rightarrow>int" +assumes div_nonzero_def [simp]: "b\<noteq>0 \<Longrightarrow> div_nonzero a b = a div b" +begin + +definition int_HALFRANGE::int where [simp, intro]:"int_HALFRANGE=2^31" +definition int_RANGE::int where [simp, intro]:"int_RANGE=2^32" +definition int_MIN::int where [simp, intro]:"int_MIN=-(2^31)" + +lemma jDiv_spec_requirement: + fixes a::int + fixes b::int + assumes "b\<noteq>0" + shows "abs(jDiv a b * b) \<le> abs(a) \<and> abs(a) < abs(jDiv a b * b) + abs(b)" +proof - + have "abs(jDiv a b * b) + abs(b) \<equiv> abs(jDiv a b) * abs(b) + abs(b)" + by (simp add: abs_mult) + also have "... \<equiv> (abs(jDiv a b) + 1) * abs(b)" + by algebra + finally have dist_jDiv_largest: "abs(jDiv a b * b) + abs(b) \<equiv> abs((abs(jDiv a b) + 1) * b)" + by (simp add: abs_mult) + consider (is_Div) "(a\<ge>0 \<and> b>0) \<or> (a\<le>0) \<and> (b<0) \<or> (b dvd a)" | (not_Div) "(a<0\<and>b>0 \<or> a>0\<and>b<0) \<and> \<not>(b dvd a)" using assms by linarith + then show ?thesis + proof cases + case is_Div + then have jDiv_eq_div: "jDiv a b = a div b" using assms by auto + consider (b_dvd_a) "b dvd a" | (both_pos) "(a>0 \<and> b>0)" | (both_neg) "(a<0) \<and> (b<0)" using is_Div by (metis dvd_0_right leD linorder_neqE_linordered_idom) + then show ?thesis + proof cases + case (b_dvd_a) + then have "a div b * b = a" using assms by simp + then show ?thesis by (simp add: assms jDiv_eq_div) + next + case (both_pos) + then have "abs(a div b * b) \<le> abs(a) \<equiv> a div b * b \<le> a" + by (simp add:pos_imp_zdiv_nonneg_iff) + also + have "... \<equiv> a div b * b \<le> a div b * b + a mod b" using both_pos by simp + also + have "... \<equiv> 0 \<le> a mod b" using both_pos by linarith + finally + have req:"abs(jDiv a b * b) \<le> abs(a)" + by (simp add: both_pos jDiv_eq_div) + have "a mod b < abs(b)" using both_pos by auto + then have "a < a div b * b + abs(b)" + by (metis add.commute add_less_cancel_right mod_mult_div_eq mult.commute) + then have largest:"abs(a) < abs(jDiv a b * b) + abs(b)" using both_pos by auto + then show ?thesis using req largest by blast + next + case (both_neg) + then have "abs(a div b * b) \<le> abs (a) \<equiv> -(a div b * b) \<le> -a" + by (simp add: div_int_pos_iff mult_nonneg_nonpos) + also + have "... \<equiv> a div b * b \<ge> a div b * b + a mod b" by simp + also + have "... \<equiv> 0 \<ge> a mod b" by linarith + finally + have req:"abs(jDiv a b * b) \<le> abs(a)" + by (simp add: both_neg jDiv_eq_div) + have "abs(a) < abs(jDiv a b * b) + abs(b) \<equiv> -((a div b * b) + a mod b) < abs(a div b * b) - b" using both_neg by simp + also have "... \<equiv> -((a div b * b) + a mod b) < -(a div b * b) - b" using both_neg by (simp add: div_int_pos_iff mult_nonneg_nonpos) + also have "... \<equiv> (a div b * b) + a mod b > (a div b * b) + b" by linarith + also have "... \<equiv> a mod b > b" by linarith + finally have largest:"abs(a) < abs(jDiv a b * b) + abs(b)" using both_neg neg_mod_bound by blast + then show ?thesis using req largest by blast + qed + next + case not_Div + then have jDiv_eq_divplus: "jDiv a b = (a div b) + 1" using assms by auto + then have "abs(jDiv a b * b) \<le> abs(a) \<equiv> abs(a div b * b + b) \<le> abs(a div b * b + a mod b)" + by (simp add: distrib_left mult.commute) + consider (b_neg) "b<0\<and>a>0" | (b_pos) "b>0\<and>a<0" using assms not_Div by linarith + then show ?thesis + proof cases + case (b_neg) + then have quotient_neg:"a div b < 0" + by (simp add: neg_imp_zdiv_neg_iff) + then have abs_jDiv:"abs((jDiv a b) * b) = (a div b + 1) * b" using b_neg jDiv_eq_divplus + by (simp add: mult_nonpos_nonpos) + then have "abs(jDiv a b * b) \<le> abs(a) \<equiv> (a div b + 1) * b \<le> a div b * b + a mod b" + by (simp add: abs_of_pos b_neg jDiv_eq_divplus) + also have "... \<equiv> a div b * b + b \<le> a div b * b + a mod b" + by (simp add: distrib_left mult.commute) + also have "... \<equiv> b \<le> a mod b" + by linarith + finally have requirement:"abs(jDiv a b * b) \<le> abs(a)" using b_neg neg_mod_bound order_less_imp_le + by blast + + have mod_le_zero:"a mod b < 0" using mod_eq_0_iff_dvd not_Div b_neg neg_mod_sign + by (metis linorder_not_less verit_la_disequality) + + have "abs(a) < abs(jDiv a b * b) + abs(b) \<equiv> a < ((a div b + 1) * b) + abs(b)" using jDiv_eq_divplus b_neg abs_jDiv + by simp + also have "... \<equiv> a < a div b * b + b + abs b" + by (simp add: distrib_left mult.commute) + also have "... \<equiv> a < a div b * b" using b_neg abs_of_neg + by simp + also have "... \<equiv> a div b * b + a mod b < a div b * b" using mult_div_mod_eq + by simp + also have "... \<equiv> a mod b < 0" + by linarith + finally have largest:"abs(a) < abs(jDiv a b * b) + abs(b)" using mod_le_zero + by blast + + show ?thesis using requirement largest by blast + next + case (b_pos) + then have "a div b < 0" + by (simp add: pos_imp_zdiv_neg_iff) + then have abs_jDiv:"abs((jDiv a b) * b) = -((a div b + 1) * b)" using b_pos jDiv_eq_divplus + by (simp add: mult_le_0_iff) + then have "abs(jDiv a b * b) \<le> abs(a) \<equiv> -((a div b + 1) * b) \<le> -(a div b * b + a mod b)" + by (simp add: abs_of_neg b_pos jDiv_eq_divplus) + also have "... \<equiv> (a div b + 1) * b \<ge> a div b * b + a mod b" + by simp + also have "... \<equiv> a div b * b + b \<ge> a div b * b + a mod b" + by (simp add: distrib_left mult.commute abs_of_neg b_pos jDiv_eq_divplus) + also have "... \<equiv> b \<ge> a mod b" by linarith + finally have requirement:"abs(jDiv a b * b) \<le> abs(a)" using b_pos pos_mod_bound order_less_imp_le + by blast + + have mod_greater_zero:"a mod b > 0" using mod_eq_0_iff_dvd not_Div + by (metis b_pos mod_int_pos_iff order_antisym_conv verit_comp_simplify1(3)) + + have "abs(a) < abs(jDiv a b * b) + abs(b) \<equiv> -a < -((a div b + 1) * b) + abs(b)" using jDiv_eq_divplus b_pos abs_jDiv + by simp + also have "... \<equiv> -a < -(a div b * b) - b + abs b" + by (simp add: distrib_left mult.commute) + also have "... \<equiv> a > a div b * b" using b_pos abs_of_pos + by simp + also have "... \<equiv> a div b * b + a mod b > a div b * b" using mult_div_mod_eq + by simp + also have "... \<equiv> a mod b > 0" + by linarith + finally have largest:"abs(a) < abs(jDiv a b * b) + abs(b)" + using mod_greater_zero by blast + + show ?thesis using requirement largest by blast + qed + qed +qed + +fun jMod::"int\<Rightarrow>int\<Rightarrow>int" where +"jMod a b = a - (jDiv a b)*b" + +lemma jMod_jDiv_eq: + fixes a::int + fixes b::int + assumes "b\<noteq>0" + shows "a = (jDiv a b)*b + jMod a b" + by simp + +fun moduloInt::"int\<Rightarrow>int" + where "moduloInt a = int_MIN + ((int_HALFRANGE + a) mod (int_RANGE))" + +fun jAdd::"int\<Rightarrow>int\<Rightarrow>int" + where "jAdd a b = moduloInt (a+b)" + +fun jSub:: "int\<Rightarrow>int\<Rightarrow>int" where + "jSub a b = moduloInt (a-b)" + +fun jMul:: "int\<Rightarrow>int\<Rightarrow>int" where + "jMul a b = moduloInt (a*b)" + +lemma euclMod_spec: + fixes a::int + fixes b::int + assumes "b\<noteq>0" + shows "0\<le>euclMod a b \<and> euclMod a b < abs(b)" +proof - + consider (mod_neg) "a mod b < 0" | (mod_nonneg) "a mod b\<ge>0" by linarith + then show ?thesis + proof cases + case (mod_neg) + then have "0\<le>euclMod a b \<and> euclMod a b < abs(b) \<equiv> 0\<le>a mod b + abs(b) \<and> a mod b + abs(b) < abs(b)" using assms + by auto + also have "... \<equiv> -abs(b)\<le>a mod b \<and> a mod b + abs(b) < abs(b)" + by linarith + also have "... \<equiv> abs(b) \<ge> abs(a mod b) \<and> a mod b + abs(b) < abs(b)" + using mod_neg by linarith + also have "... \<equiv> a mod b + abs(b) < abs(b)" + by (simp add: abs_mod_less assms dual_order.order_iff_strict) + finally show ?thesis + using mod_neg by auto + next + case (mod_nonneg) + then have "0\<le>euclMod a b \<and> euclMod a b < abs(b) \<equiv> 0\<le>a mod b \<and> a mod b < abs(b)" using assms + by auto + + then show ?thesis + by (metis abs_mod_less abs_of_nonneg assms mod_nonneg) + qed +qed + +fun euclDiv::"int\<Rightarrow>int\<Rightarrow>int" where +"(euclDiv k l) = (k - euclMod k l) div l" + +lemma euclMod_euclDiv_eq: + fixes a::int + fixes b::int + assumes "b\<noteq>0" + shows "a = euclDiv a b * b + euclMod a b" +proof - + consider (mod_le0) "a mod b<0" | (mod_geq0) "a mod b\<ge>0" by linarith + then show ?thesis +proof cases + case mod_le0 + then have "euclMod a b = a mod b + abs(b)" using assms + by simp + then have "euclMod a b = a - ((a div b) * b) + abs(b)" + by (metis minus_div_mult_eq_mod) + then have "(euclDiv a b) = (a div b * b) div b - (abs(b)) div b" + by simp + then have "euclDiv a b = (a div b) - sgn(b)" + by (metis div_by_0 linordered_idom_class.abs_sgn nonzero_mult_div_cancel_left nonzero_mult_div_cancel_right sgn_0) + then have "euclDiv a b * b = (a div b)*b - abs b" + by (metis linordered_idom_class.abs_sgn mult.commute right_diff_distrib') + then show ?thesis using assms + by auto +next + case mod_geq0 + then have euclMod_eq_mod:"euclMod a b = a mod b" using assms + by simp + then have "euclDiv a b = a div b" + by (simp add: minus_mod_eq_mult_div) + then show ?thesis using euclMod_eq_mod + by auto + qed +qed +end + + + +jArithmetics + + diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index dfd115e999b..e63489c2ca3 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -201,7 +201,5 @@ definition instance_All_UnivRep::"Any\<Rightarrow>'a::Any\<Rightarrow&g abbreviation instance_All_useSet2::"Any\<Rightarrow>Any set\<Rightarrow>bool" where "instance_All_useSet2 x y \<equiv> x : y" - - - + From 3dab8bd07fcde99307248593da5fe5b03d12f234 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 13:04:44 +0100 Subject: [PATCH 014/248] Added QuantifierHandler --- .../LogicalVariableHandler.java | 2 +- .../QuantifierHandler.java | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java index bb91fbbea4a..7326b81bd32 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -31,7 +31,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) { return makeVarRef(term.toString(), sort); } - public StringBuilder makeVarRef(String name, Sort sort) { + public static StringBuilder makeVarRef(String name, Sort sort) { StringBuilder result = new StringBuilder("("); result.append(VAR_PREFIX).append(name).append("::").append(sort.name()).append(")"); return result; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java new file mode 100644 index 00000000000..394fc147c7c --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java @@ -0,0 +1,44 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.QuantifiableVariable; +import de.uka.ilkd.key.logic.op.Quantifier; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class QuantifierHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + private Services services; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + supportedOperators.put(Quantifier.ALL, "\\"); + supportedOperators.put(Quantifier.EX, "\\"); + + this.services = services; + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + StringBuilder result = new StringBuilder("("); + result.append(supportedOperators.get(term.op())); + for (QuantifiableVariable bv : term.boundVars()) { + result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), bv.sort())); + } + result.append(". ("); + result.append(trans.translate(term.sub(0))).append("))"); + return result; + } + +} \ No newline at end of file From 9dbc6906b9140a7ab50cefbd04964c8ded758136 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 13:07:15 +0100 Subject: [PATCH 015/248] Fixed negative numbers getting two neg signs --- .../gui/isabelletranslation/NumberConstantsHandler.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java index 3ee96f8db4f..dc95f25f71d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java @@ -37,13 +37,8 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) { - if (term.sub(0).op() == negNumberSign) { - String s = AbstractTermTransformer.convertToDecimalString(term, services); - return new StringBuilder("(-").append(s).append("::int)"); - } else { - String string = AbstractTermTransformer.convertToDecimalString(term, services); - return new StringBuilder("(").append(string).append("::int)"); - } + String string = AbstractTermTransformer.convertToDecimalString(term, services); + return new StringBuilder("(").append(string).append("::int)"); } } From 15472281f993b8208a130060d56b87949bf9d7d4 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 13:19:28 +0100 Subject: [PATCH 016/248] Fixed negative numbers getting two neg signs --- .../key/gui/isabelletranslation/NumberConstantsHandler.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java index dc95f25f71d..083881883a6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java @@ -20,14 +20,12 @@ public class NumberConstantsHandler implements IsabelleHandler { private Function numberSymbol; private Services services; - private Function negNumberSign; @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { this.services = services; numberSymbol = services.getTypeConverter().getIntegerLDT().getNumberSymbol(); - negNumberSign = services.getTypeConverter().getIntegerLDT().getNegativeNumberSign(); } @Override From 2498b62f270ea7c8c12b73d8bb80a20b2e43567a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 17:59:45 +0100 Subject: [PATCH 017/248] Now create typedef for all sorts in sequent --- .../isabelletranslation/BooleanOpHandler.java | 2 +- .../isabelletranslation/IntegerOpHandler.java | 1 + .../IsabelleMasterHandler.java | 87 +++++++----- .../IsabelleTranslator.java | 66 ++++++++- .../LogicalVariableHandler.java | 2 +- .../QuantifierHandler.java | 7 +- .../UninterpretedSymbolsHandler.java | 19 ++- .../IntegerOpHandler.preamble.xml | 10 +- .../UninterpretedSymbolsHandler.preamble.xml | 133 +++++++++--------- 9 files changed, 212 insertions(+), 115 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java index 2239af6b3ac..a47a50770a6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -34,7 +34,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Operator logicTrue = ldt.getTrueConst(); supportedOperators.put(logicTrue, new StringBuilder("True")); //TODO add boolean declarations - masterHandler.addSort(ldt.targetSort()); + masterHandler.addPredefinedSort(ldt.targetSort()); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index 7269cb9b918..363b644aecb 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -44,6 +44,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert supportedOperators.put(integerLDT.getGreaterThan(), ">"); masterHandler.addPreamblesLocales(handlerSnippets); + masterHandler.addPredefinedSort(integerLDT.targetSort()); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 2871e80f599..d8470096014 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -16,21 +16,20 @@ public class IsabelleMasterHandler { private final List preambles = new ArrayList<>(); - private final List constDeclarations = new ArrayList<>(); - - - private final Set knownSymbols = new HashSet<>(); - /** * A list of untranslatable values */ - private final Map unknownValues = new HashMap<>(); + private final Map unknownValues = new HashMap<>(); + + private final Set predefinedSorts = new HashSet<>(); - private final Set sorts = new HashSet<>(); + private final Set extraSorts = new HashSet<>(); private final Map handlerMap = new IdentityHashMap<>(); private final List locales = new ArrayList<>(); + private final List constDeclarations = new ArrayList<>(); + /** * Create a new handler with the default set of smt handlers. * @@ -44,6 +43,8 @@ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { //TODO efficient loading of handlers. See MasterHandler in SMT List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); + predefinedSorts.add(Sort.ANY); + predefinedSorts.add(Sort.FORMULA); this.handlers = handlers; } @@ -101,54 +102,55 @@ private StringBuilder handleAsUnknownValue(Term problem) { var freeVars = problem.freeVars(); if (freeVars.isEmpty()) { // simple case: unknown value does not depend on anything else - StringBuilder e = new StringBuilder("consts" + System.lineSeparator() + abbr + "::Any"); - addConstDeclaration(e); - translation = abbr; } else { // unknown value depends on quantified variables //TODO implement this } - unknownValues.put(problem, abbr); + unknownValues.put(problem.op(), abbr); return null; } - void addConstDeclaration(StringBuilder decl) { + private void addConstDeclaration(Term term) { + StringBuilder decl = new StringBuilder(); + assert unknownValues.get(term.op()) != null; + decl.append("fixes "); + decl.append(unknownValues.get(term.op())); + decl.append("::\""); + for (Term sub : term.subs()) { + if (!isKnownSort(sub.sort())) { + addSort(sub.sort()); + } + decl.append(sub.sort().name().toString()).append("=>"); + } + decl.append((term.sort() == Sort.FORMULA ? "bool" : term.sort().name().toString())); + decl.append("\""); constDeclarations.add(decl); } - boolean isKnownSort(Sort s) { - return sorts.contains(s); + boolean isKnownSymbol(Term term) { + return unknownValues.containsKey(term.op()); } - StringBuilder createSortDecl(Sort sort) { - //TODO IMPLEMENT - return new StringBuilder(); + boolean isKnownSort(Sort s) { + return (predefinedSorts.contains(s) || extraSorts.contains(s)); } - boolean addSort(Sort sort) { + void addSort(Sort sort) { if (!isKnownSort(sort)) { - sorts.add(sort); + extraSorts.add(sort); } - return false; - } - - boolean isKnownSymbol(String name) { - return knownSymbols.contains(name); } - public void addPreamble(StringBuilder stringBuilder) { + void addPreamble(StringBuilder stringBuilder) { preambles.add(stringBuilder); } - public List getPreambles() { + List getPreambles() { return preambles; } - public void addKnownSymbol(String name) { - knownSymbols.add(name); - } - public void addPreamblesLocales(Properties handlerSnippets) { + void addPreamblesLocales(Properties handlerSnippets) { for (Map.Entry entry : handlerSnippets.entrySet()) { String key = (String) entry.getKey(); if (key.endsWith(".preamble")) { @@ -160,11 +162,32 @@ public void addPreamblesLocales(Properties handlerSnippets) { } } - public void addLocale(StringBuilder stringBuilder) { + void addLocale(StringBuilder stringBuilder) { locales.add(stringBuilder); } - public List getLocales() { + List getLocales() { return locales; } + + void addPredefinedSort(Sort s) { + predefinedSorts.add(s); + } + + Set getExtraSorts() { + return extraSorts; + } + + void addKnownSymbol(Term term, StringBuilder s) { + unknownValues.put(term.op(), s); + addConstDeclaration(term); + } + + StringBuilder getKnownSymbol(Term term) { + return unknownValues.get(term.op()); + } + + List getConstDeclarations() { + return constDeclarations; + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a7595362950..5e1491d233e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -116,22 +116,69 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } + for (Sort sort : masterHandler.getExtraSorts()) { + String sortName = sort.name().toString(); + String UNIV = sortName + "_UNIV"; + + result.append("lemma ex_").append(UNIV).append(":"); + result.append(getUnivSpec(services, sort, "{bottom}")).append(LINE_ENDING); + result.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); + + + result.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); + result.append(LINE_ENDING); + + result.append("specification (").append(UNIV).append(") "); + result.append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); + result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); + result.append(LINE_ENDING); + + String UNIV_spec_lemma_name = UNIV + "_specification"; + result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); + result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def UNIV_I subset_UNIV verit_sko_ex_indirect)").append(LINE_ENDING); + result.append(LINE_ENDING); + + result.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); + String repName = sortName + "2any"; + String absName = "any2" + sortName; + + result.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); + result.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); + + result.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + + result.append("lemma ").append(sortName).append("_type_specification[simp]:").append(getUnivSpec(services, sort, "(UNIV::" + sortName + " set)")).append(LINE_ENDING); + result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); + result.append(LINE_ENDING).append(LINE_ENDING); + } + result.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); + boolean locale_empty = true; + if (!locales.isEmpty()) { result.append(" = "); result.append(locales.remove(0)); + locale_empty = false; } for (StringBuilder locale : locales) { result.append(" + ").append(locale); } - //TODO additional types of JFOL hierarchy and assumptions + List constDecls = masterHandler.getConstDeclarations(); + if (!constDecls.isEmpty() && locale_empty) { + result.append(" = "); + result.append(locales.remove(0)); + locale_empty = false; + } else if (!locale_empty) { + result.append(" + ").append(LINE_ENDING); + } + for (StringBuilder constDecl : constDecls) { + result.append(LINE_ENDING).append(constDecl); + } + result.append(LINE_ENDING); - result.append(getFunctionDeclarations()); - result.append(getPredicateDeclarations()); - result.append(getFreeVariableDeclarations()); result.append("begin").append(LINE_ENDING); @@ -142,6 +189,17 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) return result.append("end").append(LINE_ENDING).append("end"); } + private static String getUnivSpec(Services services, Sort sort, String insert) { + List parentSortNames = sort.extendsSorts(services).stream().map(Sort::name).map(Name::toString).toList(); + StringBuilder univSpec = new StringBuilder(); + univSpec.append("\"").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(0)).append(" set)"); + for (int i = 1; i < parentSortNames.size(); i++) { + univSpec.append(" \\ ").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(i)).append(" set)"); + } + univSpec.append(" \\ bottom \\ ").append(insert).append("\""); + return univSpec.toString(); + } + private StringBuilder getNullLocale() { //TODO handle null correctly StringBuilder result = new StringBuilder(); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java index 7326b81bd32..24bdc338395 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -26,7 +26,7 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Sort sort = term.sort(); if (!trans.isKnownSort(sort)) { - trans.createSortDecl(sort); + trans.addSort(sort); } return makeVarRef(term.toString(), sort); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java index 394fc147c7c..79c0476f183 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java @@ -5,6 +5,7 @@ import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.op.QuantifiableVariable; import de.uka.ilkd.key.logic.op.Quantifier; +import de.uka.ilkd.key.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; @@ -34,7 +35,11 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr StringBuilder result = new StringBuilder("("); result.append(supportedOperators.get(term.op())); for (QuantifiableVariable bv : term.boundVars()) { - result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), bv.sort())); + Sort sort = bv.sort(); + result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), sort)); + if (!trans.isKnownSort(sort)) { + trans.addSort(sort); + } } result.append(". ("); result.append(trans.translate(term.sub(0))).append("))"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 1c0400707f4..9272ed11380 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -4,11 +4,14 @@ package de.uka.ilkd.key.gui.isabelletranslation; import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Function; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.op.ProgramVariable; import de.uka.ilkd.key.logic.op.SortedOperator; +import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.logic.sort.SortImpl; import de.uka.ilkd.key.smt.SMTTranslationException; import java.util.List; @@ -28,6 +31,12 @@ public class UninterpretedSymbolsHandler implements IsabelleHandler { public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { masterHandler.addPreamblesLocales(handlerSnippets); + masterHandler.addPredefinedSort(Sort.ANY); + masterHandler.addPredefinedSort(new SortImpl(new Name("Object"))); + masterHandler.addPredefinedSort(new SortImpl(new Name("Null"))); + masterHandler.addPredefinedSort(new SortImpl(new Name("Heap"))); + masterHandler.addPredefinedSort(new SortImpl(new Name("LocSet"))); + masterHandler.addPredefinedSort(new SortImpl(new Name("Field"))); } @Override @@ -50,17 +59,21 @@ private static boolean bindsVars(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { SortedOperator op = (SortedOperator) term.op(); - String name = PREFIX + op.name().toString(); - if (!trans.isKnownSymbol(name)) { - trans.addKnownSymbol(name); + if (!trans.isKnownSymbol(term)) { + trans.addKnownSymbol(term, new StringBuilder(PREFIX + op.name().toString())); } + String name = trans.getKnownSymbol(term).toString(); List children = trans.translate(term.subs()); StringBuilder result = new StringBuilder("("); result.append(name); for (StringBuilder child : children) { result.append(" ").append(child); } + Sort sort = op.sort(); + if (!trans.isKnownSort(sort)) { + trans.addSort(sort); + } result.append(")"); return result; } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml index d08d36f37b2..50ad4d650dd 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml @@ -3,8 +3,8 @@ General preamble - - locale jArithmetics = + +locale jArithmetics = fixes jDiv::"int\<Rightarrow>int\<Rightarrow>int" assumes jDiv_def [simp]: "b\<noteq>0 \<Longrightarrow> jDiv a b = (if ((a\<le>0 \<and> b<0) \<or> (a\<ge>0 \<and> b>0) \<or> (b dvd a)) then (a div b) @@ -243,9 +243,9 @@ next qed qed end - + - + jArithmetics - + diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index e63489c2ca3..495cdee0d57 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -8,59 +8,59 @@ declare [[coercion_enabled]] declare [[coercion_map image]] -typedecl Any +typedecl any consts -int_subset_inAny::"Any set" -int2Any::"int\<Rightarrow>Any" -Any2int::"Any\<Rightarrow>int" +int_subset_inany::"any set" +int2any::"int\<Rightarrow>any" +any2int::"any\<Rightarrow>int" -axiomatization where int_sub_Any:"type_definition int2Any Any2int (int_subset_inAny)" -declare [[coercion int2Any]] +axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" +declare [[coercion int2any]] consts -bool_Image::"Any set" -bool2Any::"bool\<Rightarrow>Any" -Any2bool::"Any\<Rightarrow>bool" +bool_Image::"any set" +bool2any::"bool\<Rightarrow>any" +any2bool::"any\<Rightarrow>bool" -axiomatization where bool_sub_Any:"type_definition bool2Any Any2bool (bool_Image)" -declare [[coercion bool2Any]] +axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" +declare [[coercion bool2any]] consts -bottom::"Any" +bottom::"any" specification (bottom) "bottom = bottom" by simp typedef (overloaded) Bottom = "{bottom}" - morphisms Bottom_to_Any Any_to_Bottom + morphisms Bottom_to_any any_to_Bottom by simp -declare [[coercion Bottom_to_Any]] +declare [[coercion Bottom_to_any]] consts -Object_UNIV::"Any set" +Object_UNIV::"any set" -specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::Any set)" "bottom:Object_UNIV" +specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" by auto -lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::Any set) \<and> bottom:Object_UNIV" +lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) typedef Object = "Object_UNIV" - morphisms Object_to_Any Any_to_Object + morphisms Object_to_any any_to_Object using Object_UNIV_specification by auto -declare [[coercion Object_to_Any]] +declare [[coercion Object_to_any]] -lemma Object_subset_Any:"(UNIV::Object set) \<subseteq> (UNIV::Any set)" +lemma Object_subset_any:"(UNIV::Object set) \<subseteq> (UNIV::any set)" by simp lemma bottom_in_Object:"bottom \<in> (UNIV::Object set)" @@ -76,78 +76,78 @@ typedef LocSet = "UNIV::(Object \<times> Field) set set" declare [[coercion Rep_LocSet]] consts -LocSet_Image::"Any set" -LocSet2Any::"LocSet\<Rightarrow>Any" -Any2LocSet::"Any\<Rightarrow>LocSet" +LocSet_Image::"any set" +LocSet2any::"LocSet\<Rightarrow>any" +any2LocSet::"any\<Rightarrow>LocSet" -axiomatization where LocSet_sub_Any:"type_definition LocSet2Any Any2LocSet LocSet_Image" +axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" -declare [[coercion LocSet2Any]] +declare [[coercion LocSet2any]] -typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> Any) set" +typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" by simp declare [[coercion Rep_Heap]] consts -Heap_Image::"Any set" -Heap2Any::"Heap\<Rightarrow>Any" -Any2Heap::"Any\<Rightarrow>Heap" +Heap_Image::"any set" +Heap2any::"Heap\<Rightarrow>any" +any2Heap::"any\<Rightarrow>Heap" -axiomatization where Heap_sub_Any:"type_definition Heap2Any Any2Heap Heap_Image" +axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -declare [[coercion Heap2Any]] +declare [[coercion Heap2any]] -class Any = - fixes to_Any::"'a\<Rightarrow>Any" - fixes cast::"Any\<Rightarrow>'a" +class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" fixes exact_instance::"'a\<Rightarrow>bool" -instantiation Any::Any +instantiation any::any begin -definition "to_Any_Any \<equiv> (id::Any\<Rightarrow>Any)" -definition "cast_Any \<equiv> (id::Any\<Rightarrow>Any)" +definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" +definition "cast_any \<equiv> (id::any\<Rightarrow>any)" instance by standard end -instantiation int::Any +instantiation int::any begin -definition "to_Any_int \<equiv> int2Any" -definition "cast_int \<equiv> Any2int" +definition "to_any_int \<equiv> int2any" +definition "cast_int \<equiv> any2int" instance by standard end -instantiation bool::Any +instantiation bool::any begin -definition "to_Any_bool \<equiv> bool2Any" -definition "cast_bool \<equiv> Any2bool" +definition "to_any_bool \<equiv> bool2any" +definition "cast_bool \<equiv> any2bool" instance by standard end -instantiation LocSet::Any +instantiation LocSet::any begin -definition "to_Any_LocSet \<equiv> LocSet2Any" -definition "cast_LocSet \<equiv> Any2LocSet" +definition "to_any_LocSet \<equiv> LocSet2any" +definition "cast_LocSet \<equiv> any2LocSet" instance by standard end -class Object = Any +class Object = any instantiation Object::Object begin -definition "cast_Object \<equiv> Any_to_Object" -definition "to_Any_Object \<equiv> Object_to_Any" +definition "cast_Object \<equiv> any_to_Object" +definition "to_any_Object \<equiv> Object_to_any" instance by standard end typedef (overloaded) Null = "{bottom}" - morphisms Null_to_Any Any_to_Null + morphisms Null_to_any any_to_Null by simp -declare [[coercion Null_to_Any]] +declare [[coercion Null_to_any]] lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" using type_definition.Rep_range type_definition_Null by blast @@ -155,22 +155,22 @@ lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" using bottom_Null_set bottom_in_Object by auto -definition "null \<equiv> Any_to_Null bottom" +definition "null \<equiv> any_to_Null bottom" instantiation Null::Object begin -definition "to_Any_Null \<equiv> Null_to_Any" -definition "cast_Null \<equiv> Any_to_Null" +definition "to_any_Null \<equiv> Null_to_any" +definition "cast_Null \<equiv> any_to_Null" instance by standard end -abbreviation "Null_to_Object\<equiv>Any_to_Object \<circ> Null_to_Any" +abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" declare [[coercion Null_to_Object]] consts -select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::Any)" -store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>Any\<Rightarrow>Heap" +select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" +store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" wellFormed::"Heap\<Rightarrow>bool" @@ -180,8 +180,8 @@ locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" section \<open>select Axioms\<close> -axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (Any_to_Object x) else (select h o2 f2))" -and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_Any obj)\<noteq>null) \<and> f=created) then cast (Any_to_Object True) else select h o2 f)" +axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" +and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_Object True) else select h o2 f)" and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" @@ -190,16 +190,13 @@ axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrigh and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" -definition instance_All_useSet::"Any\<Rightarrow>('a::Any) set\<Rightarrow>bool" - where "instance_All_useSet x y \<equiv> x : image to_Any y" +definition instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" + where "instance_All_useSet x y \<equiv> x : image to_any y" -definition instance_All_useRep::"Any\<Rightarrow>'a::Any\<Rightarrow>bool" - where "instance_All_useRep x y \<equiv> \<exists>z::'a. to_Any z = x" +definition instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_useRep x y \<equiv> \<exists>z::'a. to_any z = x" -definition instance_All_UnivRep::"Any\<Rightarrow>'a::Any\<Rightarrow>bool" - where "instance_All_UnivRep x y \<equiv> x : image to_Any (UNIV::'a set)" - -abbreviation instance_All_useSet2::"Any\<Rightarrow>Any set\<Rightarrow>bool" - where "instance_All_useSet2 x y \<equiv> x : y" +definition instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_UnivRep x y \<equiv> x : image to_any (UNIV::'a set)" From 2876c25d9f09528b18c298683e2461fd469d4937 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 18:37:17 +0100 Subject: [PATCH 018/248] Removed some unused fields and methods in IsabelleTranslator --- .../IsabelleTranslator.java | 104 +----------------- 1 file changed, 1 insertion(+), 103 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 5e1491d233e..759ad0ac6a4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -7,7 +7,6 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.*; import de.uka.ilkd.key.logic.sort.Sort; -import de.uka.ilkd.key.logic.sort.SortImpl; import de.uka.ilkd.key.util.Debug; import org.key_project.util.collection.ImmutableArray; @@ -26,16 +25,6 @@ public class IsabelleTranslator { private final HashMap usedPredicates = new HashMap<>(); - private final HashMap intrinsicSorts = new HashMap<>(); - - private final HashMap intrinsicFunctions = new HashMap<>(); - - private static final StringBuilder INTSTRING = new StringBuilder("Int"); - - private static final StringBuilder BOOL = new StringBuilder("bool"); - - private static final String GAP = " "; - private static final StringBuilder FALSESTRING = new StringBuilder("False"); private static final StringBuilder TRUESTRING = new StringBuilder("True"); @@ -54,47 +43,12 @@ public class IsabelleTranslator { private static final StringBuilder IMPLYSTRING = new StringBuilder("-->"); - private static final StringBuilder PLUSSTRING = new StringBuilder("+"); - - private static final StringBuilder MINUSSTRING = new StringBuilder("-"); - - private static final StringBuilder MULTSTRING = new StringBuilder("*"); - - private static final StringBuilder DIVSTRING = new StringBuilder("div"); - - private static final StringBuilder LTSTRING = new StringBuilder("<"); - - private static final StringBuilder GTSTRING = new StringBuilder(">"); - - private static final StringBuilder LEQSTRING = new StringBuilder("<="); - - private static final StringBuilder GEQSTRING = new StringBuilder(">="); - - private static final StringBuilder NULLSTRING = new StringBuilder("null"); - - private static final StringBuilder NULLSORTSTRING = new StringBuilder("NULLSORT"); - - private static final StringBuilder LOGICALIFTHENELSE = new StringBuilder("ite"); - - private static final StringBuilder TERMIFTHENELSE = new StringBuilder("ite"); - - private static final StringBuilder DISTINCT = new StringBuilder("distinct"); - - private static final Sort BOOL_SORT = new SortImpl(new Name("boolean")); private static final String LINE_ENDING = "\n"; public IsabelleTranslator(Services services) { //TODO add intrinsic sorts and functions that shouldnt be overridden IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); - - intrinsicSorts.put(integerLDT.targetSort(), new StringBuilder("int")); - intrinsicSorts.put(BOOL_SORT, new StringBuilder("bool")); - - intrinsicFunctions.put(integerLDT.getAdd(), PLUSSTRING); - intrinsicFunctions.put(integerLDT.getSub(), MINUSSTRING); - intrinsicFunctions.put(integerLDT.getMul(), MULTSTRING); - intrinsicFunctions.put(integerLDT.getDiv(), DIVSTRING); } public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { @@ -110,8 +64,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) StringBuilder result = new StringBuilder(); result.append("theory Translation imports Main begin").append(LINE_ENDING); - - result.append(getSortDeclarations()); + for (StringBuilder preamble : masterHandler.getPreambles()) { result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } @@ -207,14 +160,6 @@ private StringBuilder getNullLocale() { return result; } - private StringBuilder getFunctionDeclarations() { - StringBuilder declarations = new StringBuilder(); - for (Function fun : usedFunctions.keySet()) { - if (!intrinsicFunctions.containsKey(fun)) - declarations.append(getFunctionDeclaration(fun)).append(LINE_ENDING); - } - return declarations; - } private StringBuilder getFunctionDeclaration(Function fun) { //TODO duplicate handling? Isabelle function handling? @@ -229,47 +174,6 @@ private StringBuilder getFunctionDeclaration(Function fun) { return result; } - private StringBuilder getPredicateDeclarations() { - StringBuilder declarations = new StringBuilder(); - for (Function fun : usedPredicates.keySet()) { - declarations.append(getPredicateDeclaration(fun)).append(LINE_ENDING); - } - return declarations; - } - - private StringBuilder getPredicateDeclaration(Function fun) { - //TODO duplicate handling? Isabelle function handling? - StringBuilder result = new StringBuilder(); - result.append("fixes "); - result.append(usedPredicates.get(fun)); - result.append(":: \""); - for (Sort sort : fun.argSorts()) { - result.append(translateSort(sort)).append("=>"); - } - result.append(BOOL).append("\""); - return result; - } - - private StringBuilder getFreeVariableDeclarations() { - //TODO implement - return new StringBuilder(); - } - - - private StringBuilder getSortDeclarations() { - StringBuilder declaration = new StringBuilder(); - for (Sort sort : usedSorts.keySet()) { - if (!intrinsicSorts.containsKey(sort)) - declaration.append(getSortDeclaration(sort)); - } - return declaration; - } - - private StringBuilder getSortDeclaration(Sort sort) { - StringBuilder result = new StringBuilder(); - return result.append("typedecl ").append(usedSorts.get(sort)).append(LINE_ENDING); - } - private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) throws IllegalFormulaException { Operator op = term.op(); @@ -446,10 +350,4 @@ private StringBuilder translateImplication(StringBuilder arg1, StringBuilder arg StringBuilder toReturn = new StringBuilder(); return surroundBrackets(toReturn.append(arg1).append(IMPLYSTRING).append(arg2)); } - - protected StringBuilder translateComment(int newLines, String comment) { - StringBuilder buffer = new StringBuilder(); - buffer.append("\n".repeat(Math.max(0, newLines))); - return buffer.append(GAP + "; ").append(comment); - } } From ece38420b4b0e717601bbced3c1d19190c60feb4 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 20:10:57 +0100 Subject: [PATCH 019/248] Added correct predefined sorts in UninterpretedSymbolsHandler --- .../UninterpretedSymbolsHandler.java | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 9272ed11380..6faffe3d19d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -4,6 +4,8 @@ package de.uka.ilkd.key.gui.isabelletranslation; import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.HeapLDT; +import de.uka.ilkd.key.ldt.LocSetLDT; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Function; @@ -32,11 +34,14 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert String[] handlerOptions) { masterHandler.addPreamblesLocales(handlerSnippets); masterHandler.addPredefinedSort(Sort.ANY); - masterHandler.addPredefinedSort(new SortImpl(new Name("Object"))); - masterHandler.addPredefinedSort(new SortImpl(new Name("Null"))); - masterHandler.addPredefinedSort(new SortImpl(new Name("Heap"))); - masterHandler.addPredefinedSort(new SortImpl(new Name("LocSet"))); - masterHandler.addPredefinedSort(new SortImpl(new Name("Field"))); + + HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); + masterHandler.addPredefinedSort(new SortImpl(new Name("java.lang.Object"))); + masterHandler.addPredefinedSort(new SortImpl(new Name("java.lang.Null"))); + masterHandler.addPredefinedSort(heapLDT.targetSort()); + masterHandler.addPredefinedSort(locSetLDT.targetSort()); + masterHandler.addPredefinedSort(heapLDT.getFieldSort()); } @Override From 80b7f270f1f5d4323cfafe765d6fe5f0bec6ffc1 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 21:21:25 +0100 Subject: [PATCH 020/248] removed unused translation parts and added class instantiation for extra sorts --- .../IsabelleTranslator.java | 216 ++---------------- 1 file changed, 13 insertions(+), 203 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 759ad0ac6a4..ab72787be93 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -5,13 +5,10 @@ import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Sequent; import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.*; +import de.uka.ilkd.key.logic.op.Function; import de.uka.ilkd.key.logic.sort.Sort; -import de.uka.ilkd.key.util.Debug; -import org.key_project.util.collection.ImmutableArray; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -64,7 +61,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) StringBuilder result = new StringBuilder(); result.append("theory Translation imports Main begin").append(LINE_ENDING); - + for (StringBuilder preamble : masterHandler.getPreambles()) { result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } @@ -72,6 +69,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) for (Sort sort : masterHandler.getExtraSorts()) { String sortName = sort.name().toString(); String UNIV = sortName + "_UNIV"; + //TODO ensure that parent sorts are already known or not included result.append("lemma ex_").append(UNIV).append(":"); result.append(getUnivSpec(services, sort, "{bottom}")).append(LINE_ENDING); @@ -86,6 +84,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING); + //TODO needs other lemmata String UNIV_spec_lemma_name = UNIV + "_specification"; result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def UNIV_I subset_UNIV verit_sko_ex_indirect)").append(LINE_ENDING); @@ -103,6 +102,15 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("lemma ").append(sortName).append("_type_specification[simp]:").append(getUnivSpec(services, sort, "(UNIV::" + sortName + " set)")).append(LINE_ENDING); result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING).append(LINE_ENDING); + + result.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); + result.append("begin").append(LINE_ENDING); + result.append("definition \"to_any_").append(sortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); + result.append("definition \"cast_").append(sortName).append(" \\ ").append(absName).append("\"").append(LINE_ENDING); + result.append("instance by standard").append(LINE_ENDING); + result.append("end").append(LINE_ENDING); + + result.append(LINE_ENDING).append(LINE_ENDING); } result.append("locale varsAndFunctions"); @@ -152,202 +160,4 @@ private static String getUnivSpec(Services services, Sort sort, String insert) { univSpec.append(" \\ bottom \\ ").append(insert).append("\""); return univSpec.toString(); } - - private StringBuilder getNullLocale() { - //TODO handle null correctly - StringBuilder result = new StringBuilder(); - result.append("fixes null::'a").append(LINE_ENDING); - return result; - } - - - private StringBuilder getFunctionDeclaration(Function fun) { - //TODO duplicate handling? Isabelle function handling? - StringBuilder result = new StringBuilder(); - result.append("fixes "); - result.append(usedFunctions.get(fun)); - result.append(":: \""); - for (Sort sort : fun.argSorts()) { - result.append(translateSort(sort)).append("=>"); - } - result.append(translateSort(fun.sort())).append("\""); - return result; - } - - private StringBuilder translateTerm(Term term, List quantifiedVariables, Services services) throws IllegalFormulaException { - Operator op = term.op(); - - if (op == Junctor.IMP) { - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); - return translateImplication(arg1, arg2); - } else if (op == Junctor.AND) { - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); - return translateAnd(arg1, arg2); - } else if (op == Junctor.OR) { - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); - return translateLogicalOr(arg1, arg2); - } else if (op == Junctor.NOT) { - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - return translateNot(arg1); - } else if (op == Junctor.TRUE) { - return translateLogicalTrue(); - } else if (op == Junctor.FALSE) { - return translateLogicalFalse(); - } else if (op == Equality.EQUALS) { - //TODO type hierarchy and cast handling - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - StringBuilder arg2 = translateTerm(term.sub(1), quantifiedVariables, services); - return translateObjectEqual(arg1, arg2); - } else if (op instanceof Function fun) { - ArrayList args = new ArrayList<>(); - for (int i = 0; i < op.arity(); i++) { - args.add(translateTerm(term.sub(i), quantifiedVariables, services)); - } - if (fun.sort() == Sort.FORMULA) { - return translatePredicate(fun, args); - } - //TODO binding functions??? - return translateFunction(fun, args); - } else if ((op instanceof LogicVariable) || (op instanceof ProgramVariable)) { - //TODO handle Logic and Program variables differently? - //TODO quantified variables handling - ParsableVariable var = (ParsableVariable) op; - if (quantifiedVariables.contains(op)) { - return translateVariable(var); - } else { - return translateVariable(var); - } - } else if (op == Quantifier.ALL) { - ImmutableArray vars = term.varsBoundHere(0); - Debug.assertTrue(vars.size() == 1); - - QuantifiableVariable var = vars.get(0); - - quantifiedVariables.add(var); - - StringBuilder qv = this.translateVariable(var); - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - return this.translateLogicalAll(qv, arg1); - } else if (op == Quantifier.EX) { - ImmutableArray vars = term.varsBoundHere(0); - Debug.assertTrue(vars.size() == 1); - - QuantifiableVariable var = vars.get(0); - - quantifiedVariables.add(var); - - StringBuilder qv = this.translateVariable(var); - StringBuilder arg1 = translateTerm(term.sub(0), quantifiedVariables, services); - return this.translateLogicalExists(qv, arg1); - } - //TODO translation of other types - throw new IllegalFormulaException(""); - } - - private StringBuilder translateLogicalFalse() { - return FALSESTRING; - } - - private StringBuilder translateLogicalTrue() { - return TRUESTRING; - } - - private StringBuilder translateObjectEqual(StringBuilder arg1, StringBuilder arg2) { - StringBuilder result = new StringBuilder(); - return surroundBrackets(result.append(arg1).append(EQSTRING).append(arg2)); - } - - private StringBuilder translateLogicalOr(StringBuilder arg1, StringBuilder arg2) { - StringBuilder toReturn = new StringBuilder(); - return surroundBrackets(toReturn.append(arg1).append(ORSTRING).append(arg2)); - } - - private StringBuilder translateLogicalExists(StringBuilder qv, StringBuilder arg1) { - StringBuilder result = new StringBuilder(); - result.append(EXISTSTRING); - result.append(qv).append(". "); - result.append(arg1); - return surroundBrackets(result); - } - - private StringBuilder translateSort(Sort sort) { - StringBuilder result = new StringBuilder(); - if (usedSorts.containsKey(sort)) { - return usedSorts.get(sort); - } - //TODO prevent unintentional translation into Isabelle types - //TODO prevent duplicates? - usedSorts.put(sort, new StringBuilder(sort.name().toString())); - return result.append(sort.name().toString()); - } - - private StringBuilder translateLogicalAll(StringBuilder qv, StringBuilder arg1) { - StringBuilder result = new StringBuilder(); - result.append(ALLSTRING); - result.append(qv).append(". "); - result.append(arg1); - return surroundBrackets(result); - } - - private StringBuilder translatePredicate(Function fun, ArrayList args) { - if (!usedPredicates.containsKey(fun)) { - //TODO avoid conflicts - StringBuilder funName = new StringBuilder(fun.name().toString()); - usedPredicates.put(fun, funName); - } - return buildFunction(usedPredicates.get(fun), args); - } - - private StringBuilder buildFunction(StringBuilder name, ArrayList args) { - StringBuilder toReturn = new StringBuilder(); - if (args.isEmpty()) { - toReturn.append(name); - } else { - toReturn.append("(("); - toReturn.append(name).append(") "); - - for (StringBuilder arg : args) { - toReturn.append(arg).append(" "); - } - toReturn.append(")"); - } - return toReturn; - } - - private StringBuilder surroundBrackets(StringBuilder sb) { - return new StringBuilder("(").append(sb).append(")"); - } - - private StringBuilder translateAnd(StringBuilder arg1, StringBuilder arg2) { - StringBuilder toReturn = new StringBuilder(); - return surroundBrackets(toReturn.append(arg1).append(ANDSTRING).append(arg2)); - } - - private StringBuilder translateFunction(Function fun, ArrayList args) { - if (!usedFunctions.containsKey(fun)) { - //TODO avoid conflicts - StringBuilder funName = new StringBuilder(fun.name().toString()); - usedFunctions.put(fun, funName); - } - return buildFunction(usedFunctions.get(fun), args); - } - - private StringBuilder translateVariable(ParsableVariable var) { - //TODO Prevent Duplicates? - StringBuilder result = new StringBuilder(); - return surroundBrackets(result.append(var.name().toString()).append("::").append(translateSort(var.sort()))); - } - - private StringBuilder translateNot(StringBuilder arg1) { - StringBuilder toReturn = new StringBuilder(); - return surroundBrackets(toReturn.append(NOTSTRING).append(arg1)); - } - - private StringBuilder translateImplication(StringBuilder arg1, StringBuilder arg2) { - StringBuilder toReturn = new StringBuilder(); - return surroundBrackets(toReturn.append(arg1).append(IMPLYSTRING).append(arg2)); - } } From 223fb93155557ec43ba3338d6475ba94d4a0772d Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 3 Mar 2024 21:30:25 +0100 Subject: [PATCH 021/248] changed some instanceall functions in preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 495cdee0d57..4d080c8cad6 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -190,13 +190,13 @@ axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrigh and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" -definition instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" - where "instance_All_useSet x y \<equiv> x : image to_any y" +fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" + where "instance_All_useSet x y = (to_any x : image to_any y)" -definition instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_useRep x y \<equiv> \<exists>z::'a. to_any z = x" +fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" -definition instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_UnivRep x y \<equiv> x : image to_any (UNIV::'a set)" +fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" From 0abb4a12f6ea39788d32bccd580529b3de3d5f2e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 5 Mar 2024 14:08:36 +0100 Subject: [PATCH 022/248] corrected predefined sorts --- .../isabelletranslation/UninterpretedSymbolsHandler.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 6faffe3d19d..53a21ed2162 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -7,13 +7,13 @@ import de.uka.ilkd.key.ldt.HeapLDT; import de.uka.ilkd.key.ldt.LocSetLDT; import de.uka.ilkd.key.logic.Name; +import de.uka.ilkd.key.logic.Namespace; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Function; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.op.ProgramVariable; import de.uka.ilkd.key.logic.op.SortedOperator; import de.uka.ilkd.key.logic.sort.Sort; -import de.uka.ilkd.key.logic.sort.SortImpl; import de.uka.ilkd.key.smt.SMTTranslationException; import java.util.List; @@ -37,8 +37,11 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); - masterHandler.addPredefinedSort(new SortImpl(new Name("java.lang.Object"))); - masterHandler.addPredefinedSort(new SortImpl(new Name("java.lang.Null"))); + + Namespace sorts = services.getNamespaces().sorts(); + masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object"))); + masterHandler.addPredefinedSort(sorts.lookup(new Name("Null"))); + masterHandler.addPredefinedSort(sorts.lookup(new Name("Field"))); masterHandler.addPredefinedSort(heapLDT.targetSort()); masterHandler.addPredefinedSort(locSetLDT.targetSort()); masterHandler.addPredefinedSort(heapLDT.getFieldSort()); From 9017582ce6d71b53386053670566a0e45365130f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 5 Mar 2024 14:59:47 +0100 Subject: [PATCH 023/248] added length to preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 290 +++++++++--------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 4d080c8cad6..09c7a96fc7e 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -2,201 +2,201 @@ -General preamble + General preamble -declare [[coercion_enabled]] -declare [[coercion_map image]] + declare [[coercion_enabled]] + declare [[coercion_map image]] -typedecl any + typedecl any -consts -int_subset_inany::"any set" -int2any::"int\<Rightarrow>any" -any2int::"any\<Rightarrow>int" + consts + int_subset_inany::"any set" + int2any::"int\<Rightarrow>any" + any2int::"any\<Rightarrow>int" -axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" -declare [[coercion int2any]] + axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" + declare [[coercion int2any]] -consts -bool_Image::"any set" -bool2any::"bool\<Rightarrow>any" -any2bool::"any\<Rightarrow>bool" + consts + bool_Image::"any set" + bool2any::"bool\<Rightarrow>any" + any2bool::"any\<Rightarrow>bool" -axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" -declare [[coercion bool2any]] + axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" + declare [[coercion bool2any]] -consts -bottom::"any" + consts + bottom::"any" -specification (bottom) "bottom = bottom" - by simp + specification (bottom) "bottom = bottom" + by simp -typedef (overloaded) Bottom = "{bottom}" - morphisms Bottom_to_any any_to_Bottom - by simp + consts + Object_UNIV::"any set" -declare [[coercion Bottom_to_any]] + specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" + by auto + lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" + by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) -consts -Object_UNIV::"any set" + typedef Object = "Object_UNIV"+ + morphisms Object_to_any any_to_Object + using Object_UNIV_specification by auto + declare [[coercion Object_to_any]] -specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" - by auto + lemma Object_subset_any[simp]:"(UNIV::Object set) \<subseteq> (UNIV::any set)" + by simp -lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" - by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) + lemma bottom_in_Object[simp]:"bottom \<in> (UNIV::Object set)" + using Object_UNIV_specification + using type_definition.Rep_range type_definition_Object by blast + typedecl Field + (* "TODO: implement Field type" *) -typedef Object = "Object_UNIV" - morphisms Object_to_any any_to_Object - using Object_UNIV_specification by auto + typedef LocSet = "UNIV::(Object \<times> Field) set set" + by simp -declare [[coercion Object_to_any]] + declare [[coercion Rep_LocSet]] -lemma Object_subset_any:"(UNIV::Object set) \<subseteq> (UNIV::any set)" - by simp + consts + LocSet_Image::"any set" + LocSet2any::"LocSet\<Rightarrow>any" + any2LocSet::"any\<Rightarrow>LocSet" -lemma bottom_in_Object:"bottom \<in> (UNIV::Object set)" - using Object_UNIV_specification - using type_definition.Rep_range type_definition_Object by blast + axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" -typedecl Field -(* "TODO: implement Field type" *) + declare [[coercion LocSet2any]] -typedef LocSet = "UNIV::(Object \<times> Field) set set" - by simp + typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp -declare [[coercion Rep_LocSet]] + declare [[coercion Rep_Heap]] -consts -LocSet_Image::"any set" -LocSet2any::"LocSet\<Rightarrow>any" -any2LocSet::"any\<Rightarrow>LocSet" + consts + Heap_Image::"any set" + Heap2any::"Heap\<Rightarrow>any" + any2Heap::"any\<Rightarrow>Heap" -axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" + axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -declare [[coercion LocSet2any]] + declare [[coercion Heap2any]] -typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp + class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" + fixes exact_instance::"'a\<Rightarrow>bool" -declare [[coercion Rep_Heap]] -consts -Heap_Image::"any set" -Heap2any::"Heap\<Rightarrow>any" -any2Heap::"any\<Rightarrow>Heap" + instantiation any::any + begin + definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" + definition "cast_any \<equiv> (id::any\<Rightarrow>any)" + instance by standard + end -axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -declare [[coercion Heap2any]] + instantiation int::any + begin + definition "to_any_int \<equiv> int2any" + definition "cast_int \<equiv> any2int" + instance by standard + end -class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" - fixes exact_instance::"'a\<Rightarrow>bool" + instantiation bool::any + begin + definition "to_any_bool \<equiv> bool2any" + definition "cast_bool \<equiv> any2bool" + instance by standard + end + instantiation LocSet::any + begin + definition "to_any_LocSet \<equiv> LocSet2any" + definition "cast_LocSet \<equiv> any2LocSet" + instance by standard + end -instantiation any::any -begin -definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" -definition "cast_any \<equiv> (id::any\<Rightarrow>any)" -instance by standard -end + class Object = any + instantiation Object::Object + begin + definition "cast_Object \<equiv> any_to_Object" + definition "to_any_Object \<equiv> Object_to_any" + instance by standard + end + typedef (overloaded) Null = "{bottom}" + morphisms Null_to_any any_to_Null + by simp -instantiation int::any -begin -definition "to_any_int \<equiv> int2any" -definition "cast_int \<equiv> any2int" -instance by standard -end + declare [[coercion Null_to_any]] -instantiation bool::any -begin -definition "to_any_bool \<equiv> bool2any" -definition "cast_bool \<equiv> any2bool" -instance by standard -end + lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast -instantiation LocSet::any -begin -definition "to_any_LocSet \<equiv> LocSet2any" -definition "cast_LocSet \<equiv> any2LocSet" -instance by standard -end + lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" + using bottom_Null_set bottom_in_Object by auto -class Object = any + definition "null \<equiv> any_to_Null bottom" -instantiation Object::Object -begin -definition "cast_Object \<equiv> any_to_Object" -definition "to_any_Object \<equiv> Object_to_any" -instance by standard -end + instantiation Null::Object + begin + definition "to_any_Null \<equiv> Null_to_any" + definition "cast_Null \<equiv> any_to_Null" + instance by standard + end -typedef (overloaded) Null = "{bottom}" - morphisms Null_to_any any_to_Null - by simp + abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" -declare [[coercion Null_to_any]] + declare [[coercion Null_to_Object]] -lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast + consts + select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" + store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" + create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" + anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" + wellFormed::"Heap\<Rightarrow>bool" + created::"Field" + locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" + length::"Object=>int" -lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" - using bottom_Null_set bottom_in_Object by auto + axiomatization where "length obj \<geq> 0" -definition "null \<equiv> any_to_Null bottom" + definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> + obj\<noteq>null}" -instantiation Null::Object -begin -definition "to_any_Null \<equiv> Null_to_any" -definition "cast_Null \<equiv> any_to_Null" -instance by standard -end - -abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" - -declare [[coercion Null_to_Object]] - -consts -select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" -store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" -create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" -anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" -wellFormed::"Heap\<Rightarrow>bool" -created::"Field" -locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" - -definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" - -section \<open>select Axioms\<close> -axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" -and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_Object True) else select h o2 f)" -and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" - - -section \<open>wellFormed Axioms\<close> -axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" -and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" -and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" - -fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" - where "instance_All_useSet x y = (to_any x : image to_any y)" - -fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" - -fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" - + section \<open>select Axioms\<close> + axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> + f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" + and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) + \<and> f=created) then cast (any_to_Object True) else select h o2 f)" + and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, + f):unusedLocs(h)) then select h' obj f else select h obj f)" + + + section \<open>wellFormed Axioms\<close> + axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null + \<or> ((select h (select h obj f) created)::bool)" + and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj + f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" + and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> + instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" + + fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" + where "instance_All_useSet x y = (to_any x : image to_any y)" + + fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" + + fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" + From 0e78f3fedbebb15675f4504cfff931e980155ae8 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 5 Mar 2024 18:53:19 +0100 Subject: [PATCH 024/248] field handler v1 --- .../gui/isabelletranslation/FieldHandler.java | 52 +++++++++++++++++++ .../UninterpretedSymbolsHandler.java | 2 - .../isabelletranslation/defaultHandlers.txt | 1 + 3 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java new file mode 100644 index 00000000000..9cbff09c01a --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -0,0 +1,52 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Name; +import de.uka.ilkd.key.logic.Namespace; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.Collection; +import java.util.HashSet; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class FieldHandler implements IsabelleHandler { + private final Collection predefinedFields = new HashSet(); + + private Sort fieldSort; + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + fieldSort = services.getNamespaces().sorts().lookup("Field"); + predefinedFields.add("created"); + + Namespace sorts = services.getNamespaces().sorts(); + masterHandler.addPredefinedSort(sorts.lookup(new Name("Field"))); + } + + @Override + public boolean canHandle(Operator op) { + return (op instanceof Function && ((Function) op).sort() == fieldSort); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + if (!trans.isKnownSymbol(term)) { + Operator op = term.op(); + Matcher m = Pattern.compile("\\<(.*?)\\>").matcher(op.name().toString()); + assert m.find(); + String fieldName = m.group(1); + if (predefinedFields.contains(fieldName)) { + return new StringBuilder(fieldName); + } + trans.addKnownSymbol(term, new StringBuilder(fieldName)); + } + return trans.getKnownSymbol(term); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 53a21ed2162..6a0f92121b3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -41,10 +41,8 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Namespace sorts = services.getNamespaces().sorts(); masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object"))); masterHandler.addPredefinedSort(sorts.lookup(new Name("Null"))); - masterHandler.addPredefinedSort(sorts.lookup(new Name("Field"))); masterHandler.addPredefinedSort(heapLDT.targetSort()); masterHandler.addPredefinedSort(locSetLDT.targetSort()); - masterHandler.addPredefinedSort(heapLDT.getFieldSort()); } @Override diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index 438e96d2045..2097c12f4fd 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -4,4 +4,5 @@ de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler +de.uka.ilkd.key.gui.isabelletranslation.FieldHandler de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From e01b85f7f74af0dfbad28be30335ab0149a77f0c Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 5 Mar 2024 19:54:39 +0100 Subject: [PATCH 025/248] fix indentation --- .../UninterpretedSymbolsHandler.preamble.xml | 290 +++++++++--------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 09c7a96fc7e..8490356936d 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -2,201 +2,201 @@ - General preamble +General preamble - declare [[coercion_enabled]] - declare [[coercion_map image]] +declare [[coercion_enabled]] +declare [[coercion_map image]] - typedecl any +typedecl any - consts - int_subset_inany::"any set" - int2any::"int\<Rightarrow>any" - any2int::"any\<Rightarrow>int" +consts +int_subset_inany::"any set" +int2any::"int\<Rightarrow>any" +any2int::"any\<Rightarrow>int" - axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" - declare [[coercion int2any]] +axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" +declare [[coercion int2any]] - consts - bool_Image::"any set" - bool2any::"bool\<Rightarrow>any" - any2bool::"any\<Rightarrow>bool" +consts +bool_Image::"any set" +bool2any::"bool\<Rightarrow>any" +any2bool::"any\<Rightarrow>bool" - axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" - declare [[coercion bool2any]] +axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" +declare [[coercion bool2any]] - consts - bottom::"any" +consts +bottom::"any" - specification (bottom) "bottom = bottom" - by simp +specification (bottom) "bottom = bottom" + by simp - consts - Object_UNIV::"any set" +typedef (overloaded) Bottom = "{bottom}" + morphisms Bottom_to_any any_to_Bottom + by simp +declare [[coercion Bottom_to_any]] - specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" - by auto - lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" - by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) - typedef Object = "Object_UNIV"+ - morphisms Object_to_any any_to_Object - using Object_UNIV_specification by auto +consts +Object_UNIV::"any set" - declare [[coercion Object_to_any]] - lemma Object_subset_any[simp]:"(UNIV::Object set) \<subseteq> (UNIV::any set)" - by simp +specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" + by auto - lemma bottom_in_Object[simp]:"bottom \<in> (UNIV::Object set)" - using Object_UNIV_specification - using type_definition.Rep_range type_definition_Object by blast +lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" + by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) - typedecl Field - (* "TODO: implement Field type" *) - typedef LocSet = "UNIV::(Object \<times> Field) set set" - by simp +typedef Object = "Object_UNIV" + morphisms Object_to_any any_to_Object + using Object_UNIV_specification by auto - declare [[coercion Rep_LocSet]] +declare [[coercion Object_to_any]] - consts - LocSet_Image::"any set" - LocSet2any::"LocSet\<Rightarrow>any" - any2LocSet::"any\<Rightarrow>LocSet" +lemma Object_subset_any[simp]:"(UNIV::Object set) \<subseteq> (UNIV::any set)" + by simp - axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" +lemma bottom_in_Object[simp] :"bottom \<in> (UNIV::Object set)" + using Object_UNIV_specification + using type_definition.Rep_range type_definition_Object by blast - declare [[coercion LocSet2any]] +typedecl Field +(* "TODO: implement Field type" *) - typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp +typedef LocSet = "UNIV::(Object \<times> Field) set set" + by simp - declare [[coercion Rep_Heap]] +declare [[coercion Rep_LocSet]] - consts - Heap_Image::"any set" - Heap2any::"Heap\<Rightarrow>any" - any2Heap::"any\<Rightarrow>Heap" +consts +LocSet_Image::"any set" +LocSet2any::"LocSet\<Rightarrow>any" +any2LocSet::"any\<Rightarrow>LocSet" - axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" +axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" - declare [[coercion Heap2any]] +declare [[coercion LocSet2any]] - class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" - fixes exact_instance::"'a\<Rightarrow>bool" +typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp +declare [[coercion Rep_Heap]] - instantiation any::any - begin - definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" - definition "cast_any \<equiv> (id::any\<Rightarrow>any)" - instance by standard - end +consts +Heap_Image::"any set" +Heap2any::"Heap\<Rightarrow>any" +any2Heap::"any\<Rightarrow>Heap" +axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" - instantiation int::any - begin - definition "to_any_int \<equiv> int2any" - definition "cast_int \<equiv> any2int" - instance by standard - end +declare [[coercion Heap2any]] - instantiation bool::any - begin - definition "to_any_bool \<equiv> bool2any" - definition "cast_bool \<equiv> any2bool" - instance by standard - end +class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" + fixes exact_instance::"'a\<Rightarrow>bool" - instantiation LocSet::any - begin - definition "to_any_LocSet \<equiv> LocSet2any" - definition "cast_LocSet \<equiv> any2LocSet" - instance by standard - end - class Object = any +instantiation any::any +begin +definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" +definition "cast_any \<equiv> (id::any\<Rightarrow>any)" +instance by standard +end - instantiation Object::Object - begin - definition "cast_Object \<equiv> any_to_Object" - definition "to_any_Object \<equiv> Object_to_any" - instance by standard - end - typedef (overloaded) Null = "{bottom}" - morphisms Null_to_any any_to_Null - by simp - declare [[coercion Null_to_any]] +instantiation int::any +begin +definition "to_any_int \<equiv> int2any" +definition "cast_int \<equiv> any2int" +instance by standard +end - lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast +instantiation bool::any +begin +definition "to_any_bool \<equiv> bool2any" +definition "cast_bool \<equiv> any2bool" +instance by standard +end - lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" - using bottom_Null_set bottom_in_Object by auto +instantiation LocSet::any +begin +definition "to_any_LocSet \<equiv> LocSet2any" +definition "cast_LocSet \<equiv> any2LocSet" +instance by standard +end - definition "null \<equiv> any_to_Null bottom" +class Object = any - instantiation Null::Object - begin - definition "to_any_Null \<equiv> Null_to_any" - definition "cast_Null \<equiv> any_to_Null" - instance by standard - end +instantiation Object::Object +begin +definition "cast_Object \<equiv> any_to_Object" +definition "to_any_Object \<equiv> Object_to_any" +instance by standard +end - abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" +typedef (overloaded) Null = "{bottom}" + morphisms Null_to_any any_to_Null + by simp - declare [[coercion Null_to_Object]] +declare [[coercion Null_to_any]] - consts - select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" - store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" - create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" - anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" - wellFormed::"Heap\<Rightarrow>bool" - created::"Field" - locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" - length::"Object=>int" +lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast - axiomatization where "length obj \<geq> 0" +lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" + using bottom_Null_set bottom_in_Object by auto - definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> - obj\<noteq>null}" +definition "null \<equiv> any_to_Null bottom" - section \<open>select Axioms\<close> - axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> - f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" - and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) - \<and> f=created) then cast (any_to_Object True) else select h o2 f)" - and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, - f):unusedLocs(h)) then select h' obj f else select h obj f)" - - - section \<open>wellFormed Axioms\<close> - axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null - \<or> ((select h (select h obj f) created)::bool)" - and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj - f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" - and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> - instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" - - fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" - where "instance_All_useSet x y = (to_any x : image to_any y)" - - fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" - - fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" - +instantiation Null::Object +begin +definition "to_any_Null \<equiv> Null_to_any" +definition "cast_Null \<equiv> any_to_Null" +instance by standard +end + +abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" + +declare [[coercion Null_to_Object]] + +consts +select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" +store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" +create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" +anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" +wellFormed::"Heap\<Rightarrow>bool" +created::"Field" +locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" + +definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" + +section \<open>select Axioms\<close> +axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" +and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_Object True) else select h o2 f)" +and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" + + +section \<open>wellFormed Axioms\<close> +axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" +and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" +and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" + +fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" + where "instance_All_useSet x y = (to_any x : image to_any y)" + +fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" + +fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" + where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" + From d356980085a5732a03190306ca0019bccdc9750c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 15:14:33 +0100 Subject: [PATCH 026/248] redundant escape in regex --- .../de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 9cbff09c01a..89fc87b67eb 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -39,7 +39,7 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { if (!trans.isKnownSymbol(term)) { Operator op = term.op(); - Matcher m = Pattern.compile("\\<(.*?)\\>").matcher(op.name().toString()); + Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); assert m.find(); String fieldName = m.group(1); if (predefinedFields.contains(fieldName)) { From ff01f54978a9332e253230411cf6a923041b0e08 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 15:37:42 +0100 Subject: [PATCH 027/248] added SortDependingFunctionHandler --- .../gui/isabelletranslation/FieldHandler.java | 6 ++- .../SortDependingFunctionHandler.java | 40 +++++++++++++++++++ .../UninterpretedSymbolsHandler.java | 4 ++ .../isabelletranslation/defaultHandlers.txt | 1 + 4 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 89fc87b67eb..ae269e726b8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -17,7 +17,7 @@ import java.util.regex.Pattern; public class FieldHandler implements IsabelleHandler { - private final Collection predefinedFields = new HashSet(); + private final Collection predefinedFields = new HashSet(); private Sort fieldSort; @@ -40,7 +40,9 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr if (!trans.isKnownSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - assert m.find(); + if (!m.find()) { + throw new SMTTranslationException("couldn't translate field: " + op.name()); + } String fieldName = m.group(1); if (predefinedFields.contains(fieldName)) { return new StringBuilder(fieldName); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java new file mode 100644 index 00000000000..88ddebd2a84 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java @@ -0,0 +1,40 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.SortDependingFunction; +import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.Properties; + +import static de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler.getFunctionWithSignature; + +public class SortDependingFunctionHandler implements IsabelleHandler { + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + + } + + @Override + public boolean canHandle(Operator op) { + return (op instanceof SortDependingFunction); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + assert term.op() instanceof SortDependingFunction; + SortDependingFunction op = (SortDependingFunction) term.op(); + Sort dependentSort = op.getSortDependingOn(); + + if (!trans.isKnownSort(op.getSortDependingOn())) { + trans.addSort(dependentSort); + } + + String name = op.name().toString().split("::")[1]; + return getFunctionWithSignature(trans, term, op, name); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 6a0f92121b3..beb76702cd2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -70,6 +70,10 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } String name = trans.getKnownSymbol(term).toString(); + return getFunctionWithSignature(trans, term, op, name); + } + + static StringBuilder getFunctionWithSignature(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { List children = trans.translate(term.subs()); StringBuilder result = new StringBuilder("("); result.append(name); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index 2097c12f4fd..da14fd80671 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -5,4 +5,5 @@ de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler de.uka.ilkd.key.gui.isabelletranslation.FieldHandler +de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From dc147ed657e245dd839fdd1e1be803399119dd6e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 21:48:25 +0100 Subject: [PATCH 028/248] added DefinedSymbolsHandler fixed bugs in FieldHandler SortDependingHandler --- .../DefinedSymbolsHandler.java | 61 +++++++++++++++++++ .../gui/isabelletranslation/FieldHandler.java | 20 +++--- .../SortDependingFunctionHandler.java | 10 ++- .../UninterpretedSymbolsHandler.java | 6 +- .../isabelletranslation/defaultHandlers.txt | 1 + 5 files changed, 85 insertions(+), 13 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java new file mode 100644 index 00000000000..c0e471c5146 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -0,0 +1,61 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Namespace; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.SortDependingFunction; +import de.uka.ilkd.key.logic.op.SortedOperator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class DefinedSymbolsHandler implements IsabelleHandler { + Map supportedOperators = new HashMap<>(); + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + Namespace functionNamespace = services.getNamespaces().functions(); + Map definedFunctions = new HashMap<>(); + definedFunctions.put("null", "null"); + definedFunctions.put("length", "length"); + definedFunctions.put("wellFormed", "wellFormed"); + + Map definedSortDependingFunctions = new HashMap<>(); + definedSortDependingFunctions.put("select", "select"); + definedSortDependingFunctions.put("cast", "cast"); + definedSortDependingFunctions.put("instance", "instance"); + definedSortDependingFunctions.put("exactInstance", "exactInstance"); + + for (String name : definedFunctions.keySet()) { + Function function = functionNamespace.lookup(name); + if (function != null) + supportedOperators.put(function, definedFunctions.get(name)); + } + + for (Function function : functionNamespace.elements()) { + if (!(function instanceof SortDependingFunction)) + continue; + String funName = function.name().toString().split("::")[1]; + for (String name : definedSortDependingFunctions.keySet()) { + if (funName.equals(name)) { + supportedOperators.put(function, definedSortDependingFunctions.get(name)); + } + } + } + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + return UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (SortedOperator) term.op(), supportedOperators.get(term.op())); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index ae269e726b8..05cae3c1241 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -39,15 +39,19 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { if (!trans.isKnownSymbol(term)) { Operator op = term.op(); - Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - if (!m.find()) { - throw new SMTTranslationException("couldn't translate field: " + op.name()); + if (op.name().toString().equals("arr")) { + trans.addKnownSymbol(term, UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (Function) term.op(), "arr")); + } else { + Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); + if (!m.find()) { + throw new SMTTranslationException("couldn't translate field: " + op.name()); + } + String fieldName = m.group(1); + if (predefinedFields.contains(fieldName)) { + return new StringBuilder(fieldName); + } + trans.addKnownSymbol(term, new StringBuilder(fieldName)); } - String fieldName = m.group(1); - if (predefinedFields.contains(fieldName)) { - return new StringBuilder(fieldName); - } - trans.addKnownSymbol(term, new StringBuilder(fieldName)); } return trans.getKnownSymbol(term); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java index 88ddebd2a84..4853d5321bf 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java @@ -10,9 +10,10 @@ import java.io.IOException; import java.util.Properties; -import static de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler.getFunctionWithSignature; +import static de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler.getFunctionTranslation; public class SortDependingFunctionHandler implements IsabelleHandler { + private final String PREFIX = "var_"; @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { @@ -34,7 +35,10 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr trans.addSort(dependentSort); } - String name = op.name().toString().split("::")[1]; - return getFunctionWithSignature(trans, term, op, name); + String name = PREFIX + op.name().toString().split("::")[1]; + if (!trans.isKnownSymbol(term)) { + trans.addKnownSymbol(term, new StringBuilder(name)); + } + return getFunctionTranslation(trans, term, op, name); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index beb76702cd2..20031dbd668 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -70,13 +70,15 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } String name = trans.getKnownSymbol(term).toString(); - return getFunctionWithSignature(trans, term, op, name); + name.replace("::", "_"); + return getFunctionTranslation(trans, term, op, name); } - static StringBuilder getFunctionWithSignature(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { + static StringBuilder getFunctionTranslation(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { List children = trans.translate(term.subs()); StringBuilder result = new StringBuilder("("); result.append(name); + for (StringBuilder child : children) { result.append(" ").append(child); } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index da14fd80671..e490d6fca86 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -1,3 +1,4 @@ +de.uka.ilkd.key.gui.isabelletranslation.DefinedSymbolsHandler de.uka.ilkd.key.gui.isabelletranslation.BooleanOpHandler de.uka.ilkd.key.gui.isabelletranslation.PolymorphicHandler de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler From d9f8fe94974aff1531be095f37f9daa4ec98445c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 23:21:14 +0100 Subject: [PATCH 029/248] added comments improved lemmata for sort declarations Removed faulty arr function translation --- .../gui/isabelletranslation/FieldHandler.java | 20 ++++++++----------- .../IsabelleTranslator.java | 7 ++++++- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 05cae3c1241..ae269e726b8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -39,19 +39,15 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { if (!trans.isKnownSymbol(term)) { Operator op = term.op(); - if (op.name().toString().equals("arr")) { - trans.addKnownSymbol(term, UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (Function) term.op(), "arr")); - } else { - Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - if (!m.find()) { - throw new SMTTranslationException("couldn't translate field: " + op.name()); - } - String fieldName = m.group(1); - if (predefinedFields.contains(fieldName)) { - return new StringBuilder(fieldName); - } - trans.addKnownSymbol(term, new StringBuilder(fieldName)); + Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); + if (!m.find()) { + throw new SMTTranslationException("couldn't translate field: " + op.name()); } + String fieldName = m.group(1); + if (predefinedFields.contains(fieldName)) { + return new StringBuilder(fieldName); + } + trans.addKnownSymbol(term, new StringBuilder(fieldName)); } return trans.getKnownSymbol(term); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index ab72787be93..dca9d9481a8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -71,6 +71,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) String UNIV = sortName + "_UNIV"; //TODO ensure that parent sorts are already known or not included + result.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); result.append("lemma ex_").append(UNIV).append(":"); result.append(getUnivSpec(services, sort, "{bottom}")).append(LINE_ENDING); result.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); @@ -87,7 +88,11 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) //TODO needs other lemmata String UNIV_spec_lemma_name = UNIV + "_specification"; result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); - result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def UNIV_I subset_UNIV verit_sko_ex_indirect)").append(LINE_ENDING); + result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex subset_iff_psubset_eq"); + for (String parent : sort.extendsSorts(services).stream().map(Sort::name).map(Name::toString).toList()) { + result.append(" ").append("bottom_in_").append(parent); + } + result.append(")").append(LINE_ENDING); result.append(LINE_ENDING); result.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); From 50f894950d449f5d43446f252b1c006206166a13 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 23:25:38 +0100 Subject: [PATCH 030/248] ensured fieldhandler only handles field constants --- .../de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index ae269e726b8..bd6c35d0d00 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -17,7 +17,7 @@ import java.util.regex.Pattern; public class FieldHandler implements IsabelleHandler { - private final Collection predefinedFields = new HashSet(); + private final Collection predefinedFields = new HashSet<>(); private Sort fieldSort; @@ -32,7 +32,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert @Override public boolean canHandle(Operator op) { - return (op instanceof Function && ((Function) op).sort() == fieldSort); + return (op instanceof Function && ((Function) op).sort() == fieldSort && op.arity() == 0); } @Override From 29f1a1db7aa5a0a36dc95c9553dc7d042bb194ae Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 23:28:48 +0100 Subject: [PATCH 031/248] handleAsUnkownValue now functions better --- .../key/gui/isabelletranslation/IsabelleMasterHandler.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index d8470096014..5c2ae385a74 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -98,7 +98,7 @@ private StringBuilder handleAsUnknownValue(Term problem) { } int number = unknownValues.size(); StringBuilder translation; - StringBuilder abbr = new StringBuilder("unknown_" + number); + StringBuilder abbr = new StringBuilder("unknown_" + problem.op().name().toString()); var freeVars = problem.freeVars(); if (freeVars.isEmpty()) { // simple case: unknown value does not depend on anything else @@ -107,7 +107,7 @@ private StringBuilder handleAsUnknownValue(Term problem) { //TODO implement this } unknownValues.put(problem.op(), abbr); - return null; + return abbr; } private void addConstDeclaration(Term term) { From 96de5f0ad2366047143b636d494b7694412da3ce Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 6 Mar 2024 23:33:12 +0100 Subject: [PATCH 032/248] slight preamble changes and changed translation for eqv --- .../ilkd/key/gui/isabelletranslation/BooleanOpHandler.java | 2 +- .../UninterpretedSymbolsHandler.preamble.xml | 6 +----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java index a47a50770a6..1120380a04e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -22,7 +22,7 @@ public class BooleanOpHandler implements IsabelleHandler { supportedOperators.put(Junctor.NOT, new StringBuilder("Not")); supportedOperators.put(Junctor.FALSE, new StringBuilder("False")); supportedOperators.put(Junctor.TRUE, new StringBuilder("True")); - supportedOperators.put(Equality.EQV, new StringBuilder("<-->")); + supportedOperators.put(Equality.EQV, new StringBuilder("\\")); } @Override diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 8490356936d..9bcd743d921 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -34,13 +34,9 @@ bottom::"any" specification (bottom) "bottom = bottom" by simp -typedef (overloaded) Bottom = "{bottom}" - morphisms Bottom_to_any any_to_Bottom +lemma bottom_in_any:"bottom \<in> (UNIV::any set)" by simp -declare [[coercion Bottom_to_any]] - - consts From 763732ce9b3626a431a37024f9574d4949e42e1f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 00:37:35 +0100 Subject: [PATCH 033/248] renamed Object to java_lang_Object in preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 9bcd743d921..56bb76cd01d 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -40,33 +40,33 @@ lemma bottom_in_any:"bottom \<in> (UNIV::any set)" consts -Object_UNIV::"any set" +java_lang_Object_UNIV::"any set" -specification (Object_UNIV) "Object_UNIV \<subseteq> (UNIV::any set)" "bottom:Object_UNIV" +specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" "bottom:java_lang_Object_UNIV" by auto -lemma Object_UNIV_specification:"Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:Object_UNIV" - by (metis (mono_tags, lifting) Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) +lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:java_lang_Object_UNIV" + by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) -typedef Object = "Object_UNIV" - morphisms Object_to_any any_to_Object - using Object_UNIV_specification by auto +typedef java_lang_Object = "java_lang_Object_UNIV" + morphisms java_lang_Object_to_any any_to_java_lang_Object + using java_lang_Object_UNIV_specification by auto -declare [[coercion Object_to_any]] +declare [[coercion java_lang_Object_to_any]] -lemma Object_subset_any[simp]:"(UNIV::Object set) \<subseteq> (UNIV::any set)" +lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" by simp -lemma bottom_in_Object[simp] :"bottom \<in> (UNIV::Object set)" - using Object_UNIV_specification - using type_definition.Rep_range type_definition_Object by blast +lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" + using java_lang_Object_UNIV_specification + using type_definition.Rep_range type_definition_java_lang_Object by blast typedecl Field (* "TODO: implement Field type" *) -typedef LocSet = "UNIV::(Object \<times> Field) set set" +typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" by simp declare [[coercion Rep_LocSet]] @@ -80,7 +80,7 @@ axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSe declare [[coercion LocSet2any]] -typedef Heap = "UNIV::(Object \<Rightarrow> Field \<Rightarrow> any) set" +typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" by simp declare [[coercion Rep_Heap]] @@ -130,12 +130,12 @@ definition "cast_LocSet \<equiv> any2LocSet" instance by standard end -class Object = any +class java_lang_Object = any -instantiation Object::Object +instantiation java_lang_Object::java_lang_Object begin -definition "cast_Object \<equiv> any_to_Object" -definition "to_any_Object \<equiv> Object_to_any" +definition "cast_java_lang_Object \<equiv> any_to_java_lang_Object" +definition "to_any_java_lang_Object \<equiv> java_lang_Object_to_any" instance by standard end @@ -148,43 +148,43 @@ declare [[coercion Null_to_any]] lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" using type_definition.Rep_range type_definition_Null by blast -lemma Null_sub_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::Object set)" - using bottom_Null_set bottom_in_Object by auto +lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" + using bottom_Null_set bottom_in_java_lang_Object by auto definition "null \<equiv> any_to_Null bottom" -instantiation Null::Object +instantiation Null::java_lang_Object begin definition "to_any_Null \<equiv> Null_to_any" definition "cast_Null \<equiv> any_to_Null" instance by standard end -abbreviation "Null_to_Object\<equiv>any_to_Object \<circ> Null_to_any" +abbreviation "Null_to_java_lang_Object\<equiv>any_to_java_lang_Object \<circ> Null_to_any" -declare [[coercion Null_to_Object]] +declare [[coercion Null_to_java_lang_Object]] consts -select::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>('a::any)" -store::"Heap\<Rightarrow>Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" -create::"Heap\<Rightarrow>Object\<Rightarrow>Heap" +select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>('a::any)" +store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" +create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" wellFormed::"Heap\<Rightarrow>bool" created::"Field" -locEps::"(Object \<times> Field \<times> LocSet) \<Rightarrow> bool" +locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" -definition "unusedLocs (h::Heap) \<equiv> {((obj::Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" +definition "unusedLocs (h::Heap) \<equiv> {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" section \<open>select Axioms\<close> -axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_Object x) else (select h o2 f2))" -and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_Object True) else select h o2 f)" +axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_java_lang_Object x) else (select h o2 f2))" +and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((java_lang_Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_java_lang_Object True) else select h o2 f)" and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" section \<open>wellFormed Axioms\<close> -axiomatization where onlyCreatedObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" -and onlyCreatedObjectsAreInLocSets:"wellFormed h \<and> ((o2::Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_Object null=o2 \<or> ((select h o2 created)::bool)" -and wellFormedStoreObject:"wellFormed h \<and> ((x::Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" +axiomatization where onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" +and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" +and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" where "instance_All_useSet x y = (to_any x : image to_any y)" From e69ae64c7832ab9ea93dc32cf406bc43c4f706fa Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 00:38:14 +0100 Subject: [PATCH 034/248] ensure illegal chars in name are not translated in UninterpretedSymbolsHandler --- .../gui/isabelletranslation/UninterpretedSymbolsHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 20031dbd668..1c0a5b97906 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -70,8 +70,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } String name = trans.getKnownSymbol(term).toString(); - name.replace("::", "_"); - return getFunctionTranslation(trans, term, op, name); + return getFunctionTranslation(trans, term, op, name.replace("::", "_").replace(".", "_")); } static StringBuilder getFunctionTranslation(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { From 984b1d7a41119ab69ec25cac5f1f99c6c85d3cef Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 00:39:25 +0100 Subject: [PATCH 035/248] now looks for sorts parents only among given sorts (and any, Object) Translates sorts without using illegal chars also handling exceptions from IsabelleMasterHandler --- .../IsabelleMasterHandler.java | 14 ++- .../IsabelleTranslator.java | 94 ++++++++++--------- .../LogicalVariableHandler.java | 2 +- 3 files changed, 64 insertions(+), 46 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 5c2ae385a74..05afdc53d92 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -93,8 +93,8 @@ public List translate(Iterable terms) { * @return a generic translation as unknown value */ private StringBuilder handleAsUnknownValue(Term problem) { - if (unknownValues.containsKey(problem)) { - return unknownValues.get(problem); + if (unknownValues.containsKey(problem.op())) { + return unknownValues.get(problem.op()); } int number = unknownValues.size(); StringBuilder translation; @@ -120,7 +120,7 @@ private void addConstDeclaration(Term term) { if (!isKnownSort(sub.sort())) { addSort(sub.sort()); } - decl.append(sub.sort().name().toString()).append("=>"); + decl.append(IsabelleTranslator.getSortName(sub.sort())).append("=>"); } decl.append((term.sort() == Sort.FORMULA ? "bool" : term.sort().name().toString())); decl.append("\""); @@ -190,4 +190,12 @@ StringBuilder getKnownSymbol(Term term) { List getConstDeclarations() { return constDeclarations; } + + Collection getPredefinedSorts() { + return predefinedSorts; + } + + List getExceptions() { + return exceptions; + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index dca9d9481a8..9a3c5b8b057 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -1,51 +1,20 @@ package de.uka.ilkd.key.gui.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.IntegerLDT; -import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Sequent; import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; import de.uka.ilkd.key.logic.sort.Sort; import java.io.IOException; -import java.util.HashMap; -import java.util.List; +import java.util.*; import static de.uka.ilkd.key.smt.SMTProblem.sequentToTerm; public class IsabelleTranslator { - private final HashMap usedSorts = new HashMap<>(); - - private final HashMap usedFunctions = new HashMap<>(); - - private final HashMap usedPredicates = new HashMap<>(); - - private static final StringBuilder FALSESTRING = new StringBuilder("False"); - - private static final StringBuilder TRUESTRING = new StringBuilder("True"); - - private static final StringBuilder ALLSTRING = new StringBuilder("\\"); - - private static final StringBuilder EXISTSTRING = new StringBuilder("\\"); - - private static final StringBuilder ANDSTRING = new StringBuilder("\\"); - - private static final StringBuilder ORSTRING = new StringBuilder("\\"); - - private static final StringBuilder NOTSTRING = new StringBuilder("\\"); - - private static final StringBuilder EQSTRING = new StringBuilder("="); - - private static final StringBuilder IMPLYSTRING = new StringBuilder("-->"); - - private static final String LINE_ENDING = "\n"; public IsabelleTranslator(Services services) { - //TODO add intrinsic sorts and functions that shouldnt be overridden - IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); } public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { @@ -57,6 +26,15 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) } catch (IOException e) { throw new RuntimeException(e); } + List exceptions = masterHandler.getExceptions(); + if (!exceptions.isEmpty()) { + StringBuilder message = new StringBuilder(); + for (Throwable t : exceptions) { + message.append(t.getMessage()).append(System.lineSeparator()); + } + throw new RuntimeException(message.toString()); + } + StringBuilder formula = masterHandler.translate(problem); StringBuilder result = new StringBuilder(); @@ -66,14 +44,19 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } - for (Sort sort : masterHandler.getExtraSorts()) { - String sortName = sort.name().toString(); + Set extraParentsToCheck = new HashSet<>(); + extraParentsToCheck.add(Sort.ANY); + extraParentsToCheck.add(services.getNamespaces().sorts().lookup("java.lang.Object")); + + Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), extraParentsToCheck); + for (Sort sort : sortParentsMap.keySet()) { + String sortName = getSortName(sort); String UNIV = sortName + "_UNIV"; //TODO ensure that parent sorts are already known or not included result.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); result.append("lemma ex_").append(UNIV).append(":"); - result.append(getUnivSpec(services, sort, "{bottom}")).append(LINE_ENDING); + result.append(getUnivSpec(sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); result.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); @@ -81,16 +64,16 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING); result.append("specification (").append(UNIV).append(") "); - result.append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); + result.append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING); //TODO needs other lemmata String UNIV_spec_lemma_name = UNIV + "_specification"; - result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(services, sort, UNIV)).append(LINE_ENDING); + result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex subset_iff_psubset_eq"); - for (String parent : sort.extendsSorts(services).stream().map(Sort::name).map(Name::toString).toList()) { - result.append(" ").append("bottom_in_").append(parent); + for (String parentName : sortParentsMap.get(sort).stream().map(IsabelleTranslator::getSortName).toList()) { + result.append(" ").append("bottom_in_").append(parentName); } result.append(")").append(LINE_ENDING); result.append(LINE_ENDING); @@ -104,7 +87,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); - result.append("lemma ").append(sortName).append("_type_specification[simp]:").append(getUnivSpec(services, sort, "(UNIV::" + sortName + " set)")).append(LINE_ENDING); + result.append("lemma ").append(sortName).append("_type_specification[simp]:").append(getUnivSpec(sortParentsMap.get(sort), "(UNIV::" + sortName + " set)")).append(LINE_ENDING); result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING).append(LINE_ENDING); @@ -155,9 +138,17 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) return result.append("end").append(LINE_ENDING).append("end"); } - private static String getUnivSpec(Services services, Sort sort, String insert) { - List parentSortNames = sort.extendsSorts(services).stream().map(Sort::name).map(Name::toString).toList(); + static String getSortName(Sort sort) { + String name = sort.name().toString(); + return name.replace("[]", "arr").replace(".", "_"); + } + + private static String getUnivSpec(Set parents, String insert) { + List parentSortNames = new ArrayList<>(parents.stream().map(IsabelleTranslator::getSortName).toList()); StringBuilder univSpec = new StringBuilder(); + if (parentSortNames.isEmpty()) { + parentSortNames.add("any"); + } univSpec.append("\"").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(0)).append(" set)"); for (int i = 1; i < parentSortNames.size(); i++) { univSpec.append(" \\ ").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(i)).append(" set)"); @@ -165,4 +156,23 @@ private static String getUnivSpec(Services services, Sort sort, String insert) { univSpec.append(" \\ bottom \\ ").append(insert).append("\""); return univSpec.toString(); } + + private static Map> getSortsParents(Set sorts, Set outsideParents) { + HashMap> result = new HashMap<>(); + for (Sort sort : sorts) { + Set parents = new HashSet<>(); + for (Sort sort2 : sorts) { + if (!sort.equals(sort2) && sort.extendsTrans(sort2)) { + parents.add(sort2); + } + } + for (Sort sort2 : outsideParents) { + if (!sort.equals(sort2) && sort.extendsTrans(sort2)) { + parents.add(sort2); + } + } + result.put(sort, parents); + } + return result; + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java index 24bdc338395..f90e08a7c40 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -33,7 +33,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) { public static StringBuilder makeVarRef(String name, Sort sort) { StringBuilder result = new StringBuilder("("); - result.append(VAR_PREFIX).append(name).append("::").append(sort.name()).append(")"); + result.append(VAR_PREFIX).append(name).append("::").append(IsabelleTranslator.getSortName(sort)).append(")"); return result; } } From 24d52e37e66a6c59f58232a5343eb202447b68e3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 00:52:55 +0100 Subject: [PATCH 036/248] fixed some remaining illegal sort names --- .../key/gui/isabelletranslation/IsabelleMasterHandler.java | 2 +- .../key/gui/isabelletranslation/IsabelleTranslator.java | 6 +----- .../isabelletranslation/UninterpretedSymbolsHandler.java | 5 +++-- 3 files changed, 5 insertions(+), 8 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 05afdc53d92..56ab8b8632b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -122,7 +122,7 @@ private void addConstDeclaration(Term term) { } decl.append(IsabelleTranslator.getSortName(sub.sort())).append("=>"); } - decl.append((term.sort() == Sort.FORMULA ? "bool" : term.sort().name().toString())); + decl.append((term.sort() == Sort.FORMULA ? "bool" : IsabelleTranslator.getSortName(term.sort()))); decl.append("\""); constDeclarations.add(decl); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 9a3c5b8b057..2688a9e890b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -71,11 +71,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) //TODO needs other lemmata String UNIV_spec_lemma_name = UNIV + "_specification"; result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex subset_iff_psubset_eq"); - for (String parentName : sortParentsMap.get(sort).stream().map(IsabelleTranslator::getSortName).toList()) { - result.append(" ").append("bottom_in_").append(parentName); - } - result.append(")").append(LINE_ENDING); + result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); result.append(LINE_ENDING); result.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 1c0a5b97906..d6bd44cde00 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -66,11 +66,12 @@ private static boolean bindsVars(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { SortedOperator op = (SortedOperator) term.op(); if (!trans.isKnownSymbol(term)) { - trans.addKnownSymbol(term, new StringBuilder(PREFIX + op.name().toString())); + String name = PREFIX + op.name().toString(); + trans.addKnownSymbol(term, new StringBuilder(name.replace("::", "_").replace(".", "_"))); } String name = trans.getKnownSymbol(term).toString(); - return getFunctionTranslation(trans, term, op, name.replace("::", "_").replace(".", "_")); + return getFunctionTranslation(trans, term, op, name); } static StringBuilder getFunctionTranslation(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { From fa94d5fa3f635a70e5a05aa24c0a014fba188484 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:02:56 +0100 Subject: [PATCH 037/248] preamble change so all rep abs have the same format --- .../UninterpretedSymbolsHandler.preamble.xml | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 56bb76cd01d..e66e73f4e2a 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -51,10 +51,10 @@ lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq&g typedef java_lang_Object = "java_lang_Object_UNIV" - morphisms java_lang_Object_to_any any_to_java_lang_Object + morphisms java_lang_Object2any any2java_lang_Object using java_lang_Object_UNIV_specification by auto -declare [[coercion java_lang_Object_to_any]] +declare [[coercion java_lang_Object2any]] lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" by simp @@ -134,16 +134,16 @@ class java_lang_Object = any instantiation java_lang_Object::java_lang_Object begin -definition "cast_java_lang_Object \<equiv> any_to_java_lang_Object" -definition "to_any_java_lang_Object \<equiv> java_lang_Object_to_any" +definition "cast_java_lang_Object \<equiv> any2java_lang_Object" +definition "to_any_java_lang_Object \<equiv> java_lang_Object2any" instance by standard end typedef (overloaded) Null = "{bottom}" - morphisms Null_to_any any_to_Null + morphisms Null2any any2Null by simp -declare [[coercion Null_to_any]] +declare [[coercion Null2any]] lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" using type_definition.Rep_range type_definition_Null by blast @@ -151,18 +151,18 @@ lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" using bottom_Null_set bottom_in_java_lang_Object by auto -definition "null \<equiv> any_to_Null bottom" +definition "null \<equiv> any2Null bottom" instantiation Null::java_lang_Object begin -definition "to_any_Null \<equiv> Null_to_any" -definition "cast_Null \<equiv> any_to_Null" +definition "to_any_Null \<equiv> Null2any" +definition "cast_Null \<equiv> any2Null" instance by standard end -abbreviation "Null_to_java_lang_Object\<equiv>any_to_java_lang_Object \<circ> Null_to_any" +abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" -declare [[coercion Null_to_java_lang_Object]] +declare [[coercion Null2java_lang_Object]] consts select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>('a::any)" @@ -176,14 +176,14 @@ locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Righ definition "unusedLocs (h::Heap) \<equiv> {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" section \<open>select Axioms\<close> -axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any_to_java_lang_Object x) else (select h o2 f2))" -and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((java_lang_Object_to_any obj)\<noteq>null) \<and> f=created) then cast (any_to_java_lang_Object True) else select h o2 f)" +axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any2java_lang_Object x) else (select h o2 f2))" +and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((java_lang_Object2any obj)\<noteq>null) \<and> f=created) then cast (any2java_lang_Object True) else select h o2 f)" and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" section \<open>wellFormed Axioms\<close> axiomatization where onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" -and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null_to_java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" +and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" From bd3aa86d5bad189cff4cc95d08f5ec1938ea7bce Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:08:14 +0100 Subject: [PATCH 038/248] added coercions to parent types --- .../isabelletranslation/IsabelleTranslator.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 2688a9e890b..b9e14d30546 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -52,7 +52,6 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) for (Sort sort : sortParentsMap.keySet()) { String sortName = getSortName(sort); String UNIV = sortName + "_UNIV"; - //TODO ensure that parent sorts are already known or not included result.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); result.append("lemma ex_").append(UNIV).append(":"); @@ -68,7 +67,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING); - //TODO needs other lemmata + String UNIV_spec_lemma_name = UNIV + "_specification"; result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); @@ -87,6 +86,18 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING).append(LINE_ENDING); + for (Sort parentSort : sortParentsMap.get(sort)) { + if (parentSort == Sort.ANY) { + continue; + } + String parentSortName = getSortName(parentSort); + String parentSortInj = sortName + "2" + parentSortName; + result.append(LINE_ENDING).append("abbreviation \"").append(parentSortInj).append(" \\ "); + result.append("any2").append(parentSortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); + + result.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); + } + result.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); result.append("begin").append(LINE_ENDING); result.append("definition \"to_any_").append(sortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); From 97a5f93e12b8c926f623fc05e5c202813b18d10e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:10:05 +0100 Subject: [PATCH 039/248] added length function and axiom to preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index e66e73f4e2a..48c3cf1f755 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -172,6 +172,9 @@ anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>He wellFormed::"Heap\<Rightarrow>bool" created::"Field" locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" +length::"java_lang_Object\<Rightarrow>int" + +axiomatization "length obj \<ge> 0" definition "unusedLocs (h::Heap) \<equiv> {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" From ffb7f297b7ccbac198f6f7eed815446f6aaf02d1 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:14:35 +0100 Subject: [PATCH 040/248] formatting integers.locale --- .../key/gui/isabelletranslation/IntegerOpHandler.preamble.xml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml index 50ad4d650dd..ddad9487440 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml @@ -245,7 +245,5 @@ qed end - -jArithmetics - + jArithmetics From 69126d34403e91bdfb7e725393367e4c9d511efd Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:19:51 +0100 Subject: [PATCH 041/248] fix length axiom --- .../UninterpretedSymbolsHandler.preamble.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 48c3cf1f755..16ccec398e3 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -174,7 +174,7 @@ created::"Field" locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" length::"java_lang_Object\<Rightarrow>int" -axiomatization "length obj \<ge> 0" +axiomatization where length_nonneg[simp]:"length obj \<ge> 0" definition "unusedLocs (h::Heap) \<equiv> {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" From 17baf331e3432b27eda41425fd7538d2c599cfc7 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 01:19:58 +0100 Subject: [PATCH 042/248] locale formatting --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index b9e14d30546..c79c8de9d8c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -140,7 +140,8 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("theorem solve: \""); result.append(formula).append("\""); - result.append(LINE_ENDING); + result.append(LINE_ENDING).append(LINE_ENDING); + result.append("(* Solve here *)").append(LINE_ENDING); return result.append("end").append(LINE_ENDING).append("end"); } From fb8ccbcd5b82c39af0dc866730dac926b91b787d Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 12:25:09 +0100 Subject: [PATCH 043/248] accounted for 2nd field syntax --- .../de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index bd6c35d0d00..4f3235fb5e6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -41,7 +41,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); if (!m.find()) { - throw new SMTTranslationException("couldn't translate field: " + op.name()); + return new StringBuilder(op.name().toString().replace("::$", "_")); } String fieldName = m.group(1); if (predefinedFields.contains(fieldName)) { From 962aa3af5ec29a99b8973c6a97ff6889819d795f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 18:00:30 +0100 Subject: [PATCH 044/248] added ObserverFunctionHandler --- .../ObserverFunctionHandler.java | 39 +++++++++++++++++++ .../isabelletranslation/defaultHandlers.txt | 1 + 2 files changed, 40 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java new file mode 100644 index 00000000000..acc7e42d440 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -0,0 +1,39 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.ObserverFunction; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.SortedOperator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ObserverFunctionHandler implements IsabelleHandler { + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + + } + + @Override + public boolean canHandle(Operator op) { + return (op instanceof ObserverFunction); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + if (!trans.isKnownSymbol(term)) { + Operator op = term.op(); + Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); + if (!m.find()) { + throw new SMTTranslationException("Couldn't translate ObserverFunction: " + op.name().toString()); + } + String functionName = m.group(1); + trans.addKnownSymbol(term, new StringBuilder(functionName)); + } + return UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (SortedOperator) term.op(), trans.getKnownSymbol(term).toString()); + } +} diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index e490d6fca86..c0062db8ab8 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -6,5 +6,6 @@ de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler de.uka.ilkd.key.gui.isabelletranslation.FieldHandler +de.uka.ilkd.key.gui.isabelletranslation.ObserverFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From 525014625a3cf7b764ccebaf329677485ee63b85 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 19:03:42 +0100 Subject: [PATCH 045/248] added BSumHandler for bounded sums --- .../gui/isabelletranslation/BSumHandler.java | 48 +++++++++++++++++++ .../isabelletranslation/IntegerOpHandler.java | 3 +- .../isabelletranslation/defaultHandlers.txt | 1 + 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java new file mode 100644 index 00000000000..ec2a499cc9a --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java @@ -0,0 +1,48 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.IntegerLDT; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.QuantifiableVariable; +import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class BSumHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + supportedOperators.clear(); + IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + + supportedOperators.put(integerLDT.getBsum(), "\\"); + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + StringBuilder result = new StringBuilder("("); + result.append(supportedOperators.get(term.op())); + for (QuantifiableVariable bv : term.boundVars()) { + Sort sort = bv.sort(); + result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), sort)); + if (!trans.isKnownSort(sort)) { + trans.addSort(sort); + } + } + result.append("="); + result.append(trans.translate(term.sub(0))).append("..").append(trans.translate(term.sub(1))).append("-1. "); + result.append(trans.translate(term.sub(2))).append(")"); + return result; + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index 363b644aecb..7dfe5fcda9a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -23,13 +23,12 @@ */ public class IntegerOpHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); - private IntegerLDT integerLDT; @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { supportedOperators.clear(); - this.integerLDT = services.getTypeConverter().getIntegerLDT(); + IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); supportedOperators.put(integerLDT.getAdd(), "+"); supportedOperators.put(integerLDT.getMul(), "*"); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index c0062db8ab8..6fee436890a 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -5,6 +5,7 @@ de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler +de.uka.ilkd.key.gui.isabelletranslation.BSumHandler de.uka.ilkd.key.gui.isabelletranslation.FieldHandler de.uka.ilkd.key.gui.isabelletranslation.ObserverFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler From 2f66287e3a8d87346902588fcc45b3a5e4eacce5 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 7 Mar 2024 19:32:37 +0100 Subject: [PATCH 046/248] translation now translates antecedents as assumptions of a theorem --- .../IsabelleTranslator.java | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index c79c8de9d8c..d7062b1ecd1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -2,14 +2,13 @@ import de.uka.ilkd.key.java.Services; 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.sort.Sort; import java.io.IOException; import java.util.*; -import static de.uka.ilkd.key.smt.SMTProblem.sequentToTerm; - public class IsabelleTranslator { private static final String LINE_ENDING = "\n"; @@ -18,7 +17,8 @@ public IsabelleTranslator(Services services) { } public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { - Term problem = sequentToTerm(sequent, services); + List antecedents = sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); + List succedents = sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); // TODO find correct values IsabelleMasterHandler masterHandler; try { @@ -26,6 +26,9 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) } catch (IOException e) { throw new RuntimeException(e); } + List antecedentTranslations = antecedents.stream().map(masterHandler::translate).toList(); + List succedentTranslations = new ArrayList<>(succedents.stream().map(masterHandler::translate).toList()); + List exceptions = masterHandler.getExceptions(); if (!exceptions.isEmpty()) { StringBuilder message = new StringBuilder(); @@ -35,8 +38,6 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) throw new RuntimeException(message.toString()); } - StringBuilder formula = masterHandler.translate(problem); - StringBuilder result = new StringBuilder(); result.append("theory Translation imports Main begin").append(LINE_ENDING); @@ -138,8 +139,19 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("begin").append(LINE_ENDING); - result.append("theorem solve: \""); - result.append(formula).append("\""); + result.append("theorem solve: "); + for (int i = 0; i < antecedentTranslations.size(); i++) { + StringBuilder antecedentFormula = antecedentTranslations.get(i); + result.append(LINE_ENDING).append("assumes antecedent_").append(i).append(":\"").append(antecedentFormula).append("\""); + } + result.append(LINE_ENDING); + result.append("shows \"").append(succedentTranslations.get(0)); + for (int i = 1; i < succedentTranslations.size(); i++) { + + StringBuilder succedentFormula = succedentTranslations.get(i); + result.append(LINE_ENDING).append("\\").append(succedentFormula); + } + result.append("\""); result.append(LINE_ENDING).append(LINE_ENDING); result.append("(* Solve here *)").append(LINE_ENDING); From f23d9a8e33d4db89b79ee5a93ac29ecfec3c8322 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 8 Mar 2024 13:17:18 +0100 Subject: [PATCH 047/248] now throws exception when encountering unknown values --- .gitlab-ci.yml | 17 ++++++++++------- .../IsabelleMasterHandler.java | 3 ++- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 1740353ad95..f018e29b86c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -16,7 +16,7 @@ cache: key: ${CI_COMMIT_REF_SLUG} variables: - GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=2 -Dorg.gradle.configureondemand=true" + GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=2 -Dorg.gradle.configureondemand=true" GIT_DEPTH: 0 before_script: @@ -24,12 +24,15 @@ before_script: # - echo "$CI_BUILD_NAME, $CI_BUILD_REF_NAME $CI_BUILD_STAGE" # debug - export GRADLE_USER_HOME=`pwd`/.gradle - export SONAR_SCANNER_OPTS="-Xmx8G" + - sudo add-apt-repository ppa:cwchien/gradle + - sudo apt-get update + - sudo apt upgrade gradle stages: - - primary - - secondary - - ternary - - deploy + - primary + - secondary + - ternary + - deploy compile:classes: stage: primary @@ -45,7 +48,7 @@ compile:classes: - .gradle compile:testClasses: - dependencies: ["compile:classes"] + dependencies: [ "compile:classes" ] stage: secondary image: wadoon/key-test-docker:jdk17 script: @@ -59,7 +62,7 @@ compile:testClasses: - .gradle sonarqube: - dependencies: ["compile:testClasses"] + dependencies: [ "compile:testClasses" ] stage: ternary image: wadoon/key-test-docker:jdk17 allow_failure: true diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 56ab8b8632b..345e9e1ce37 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -4,6 +4,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; import java.util.*; @@ -70,7 +71,7 @@ public StringBuilder translate(Term problem) { } } } - + exceptions.add(new SMTTranslationException("Couldn't translate: \"" + problem.op().name().toString() + "\"")); return handleAsUnknownValue(problem); } catch (Exception ex) { exceptions.add(ex); From 6c1df63608b901fb2f88c887f3d092f9960f6b5e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 8 Mar 2024 13:20:15 +0100 Subject: [PATCH 048/248] fixing pipeline --- .gitlab-ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f018e29b86c..03d5c96a98e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -24,9 +24,9 @@ before_script: # - echo "$CI_BUILD_NAME, $CI_BUILD_REF_NAME $CI_BUILD_STAGE" # debug - export GRADLE_USER_HOME=`pwd`/.gradle - export SONAR_SCANNER_OPTS="-Xmx8G" - - sudo add-apt-repository ppa:cwchien/gradle - - sudo apt-get update - - sudo apt upgrade gradle + - add-apt-repository ppa:cwchien/gradle + - apt-get update + - apt upgrade gradle stages: - primary From 3e4af591c0ec2dfb9ed3b2a27e443e7571e11970 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 8 Mar 2024 13:39:34 +0100 Subject: [PATCH 049/248] revert pipeline changes --- .gitlab-ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 03d5c96a98e..f018e29b86c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -24,9 +24,9 @@ before_script: # - echo "$CI_BUILD_NAME, $CI_BUILD_REF_NAME $CI_BUILD_STAGE" # debug - export GRADLE_USER_HOME=`pwd`/.gradle - export SONAR_SCANNER_OPTS="-Xmx8G" - - add-apt-repository ppa:cwchien/gradle - - apt-get update - - apt upgrade gradle + - sudo add-apt-repository ppa:cwchien/gradle + - sudo apt-get update + - sudo apt upgrade gradle stages: - primary From 381c8eaae0900452a0143b6b8ec2d36d7a7fbce0 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 9 Mar 2024 15:18:22 +0100 Subject: [PATCH 050/248] ensured FieldHandler fixes unknown fields --- .../uka/ilkd/key/gui/isabelletranslation/FieldHandler.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 4f3235fb5e6..e592af08479 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -40,10 +40,10 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr if (!trans.isKnownSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - if (!m.find()) { - return new StringBuilder(op.name().toString().replace("::$", "_")); + String fieldName = op.name().toString().replace("::$", "_"); + if (m.find()) { + fieldName = m.group(1); } - String fieldName = m.group(1); if (predefinedFields.contains(fieldName)) { return new StringBuilder(fieldName); } From 67b084967bcae9859cec56ac0af665a7f6590185 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 9 Mar 2024 16:17:30 +0100 Subject: [PATCH 051/248] changed sort name translations to better account for predefined sorts. Also add types to sortdependingfunction references --- .../gui/isabelletranslation/BSumHandler.java | 4 +- .../isabelletranslation/BooleanOpHandler.java | 2 +- .../DefinedSymbolsHandler.java | 6 ++- .../gui/isabelletranslation/FieldHandler.java | 2 +- .../isabelletranslation/IntegerOpHandler.java | 2 +- .../IsabelleMasterHandler.java | 41 ++++++++++++------- .../IsabelleTranslator.java | 29 +++++-------- .../LogicalVariableHandler.java | 8 ++-- .../ObserverFunctionHandler.java | 2 +- .../QuantifierHandler.java | 4 +- .../SortDependingFunctionHandler.java | 27 ++++++++---- .../UninterpretedSymbolsHandler.java | 16 ++++---- 12 files changed, 80 insertions(+), 63 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java index ec2a499cc9a..52542186bca 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java @@ -35,9 +35,9 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr result.append(supportedOperators.get(term.op())); for (QuantifiableVariable bv : term.boundVars()) { Sort sort = bv.sort(); - result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), sort)); + result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); if (!trans.isKnownSort(sort)) { - trans.addSort(sort); + trans.addGenericSort(sort); } } result.append("="); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java index 1120380a04e..d98aa7af8aa 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -34,7 +34,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Operator logicTrue = ldt.getTrueConst(); supportedOperators.put(logicTrue, new StringBuilder("True")); //TODO add boolean declarations - masterHandler.addPredefinedSort(ldt.targetSort()); + masterHandler.addPredefinedSort(ldt.targetSort(), "bool"); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index c0e471c5146..32dd4f9adc9 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -56,6 +56,10 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { - return UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (SortedOperator) term.op(), supportedOperators.get(term.op())); + if (term.op() instanceof SortDependingFunction) { + return SortDependingFunctionHandler.getSortDependingFunctionRef(trans, term, (SortDependingFunction) term.op(), + supportedOperators.get(term.op())); + } + return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), supportedOperators.get(term.op())); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index e592af08479..efd86ecd99a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -27,7 +27,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert predefinedFields.add("created"); Namespace sorts = services.getNamespaces().sorts(); - masterHandler.addPredefinedSort(sorts.lookup(new Name("Field"))); + masterHandler.addPredefinedSort(sorts.lookup(new Name("Field")), "Field"); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index 7dfe5fcda9a..14236a485d8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -43,7 +43,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert supportedOperators.put(integerLDT.getGreaterThan(), ">"); masterHandler.addPreamblesLocales(handlerSnippets); - masterHandler.addPredefinedSort(integerLDT.targetSort()); + masterHandler.addPredefinedSort(integerLDT.targetSort(), "int"); } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 345e9e1ce37..d299638c80f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -22,9 +22,9 @@ public class IsabelleMasterHandler { */ private final Map unknownValues = new HashMap<>(); - private final Set predefinedSorts = new HashSet<>(); + private final Map predefinedSorts = new HashMap<>(); - private final Set extraSorts = new HashSet<>(); + private final Map extraSorts = new HashMap<>(); private final Map handlerMap = new IdentityHashMap<>(); private final List locales = new ArrayList<>(); @@ -44,8 +44,8 @@ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { //TODO efficient loading of handlers. See MasterHandler in SMT List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); - predefinedSorts.add(Sort.ANY); - predefinedSorts.add(Sort.FORMULA); + predefinedSorts.put(Sort.ANY, new StringBuilder("any")); + predefinedSorts.put(Sort.FORMULA, new StringBuilder("bool")); this.handlers = handlers; } @@ -117,13 +117,14 @@ private void addConstDeclaration(Term term) { decl.append("fixes "); decl.append(unknownValues.get(term.op())); decl.append("::\""); + for (Term sub : term.subs()) { if (!isKnownSort(sub.sort())) { - addSort(sub.sort()); + addGenericSort(sub.sort()); } - decl.append(IsabelleTranslator.getSortName(sub.sort())).append("=>"); + decl.append(translateSortName(sub.sort())).append("=>"); } - decl.append((term.sort() == Sort.FORMULA ? "bool" : IsabelleTranslator.getSortName(term.sort()))); + decl.append((translateSortName(term.sort()))); decl.append("\""); constDeclarations.add(decl); } @@ -133,12 +134,12 @@ boolean isKnownSymbol(Term term) { } boolean isKnownSort(Sort s) { - return (predefinedSorts.contains(s) || extraSorts.contains(s)); + return (predefinedSorts.containsKey(s) || extraSorts.containsKey(s)); } - void addSort(Sort sort) { + void addGenericSort(Sort sort) { if (!isKnownSort(sort)) { - extraSorts.add(sort); + extraSorts.put(sort, new StringBuilder(sort.name().toString().replace("[]", "arr").replace(".", "_"))); } } @@ -150,6 +151,16 @@ List getPreambles() { return preambles; } + String translateSortName(Sort sort) { + if (!isKnownSort(sort)) { + addGenericSort(sort); + } + if (predefinedSorts.containsKey(sort)) { + return predefinedSorts.get(sort).toString(); + } + return extraSorts.get(sort).toString(); + } + void addPreamblesLocales(Properties handlerSnippets) { for (Map.Entry entry : handlerSnippets.entrySet()) { @@ -171,12 +182,12 @@ List getLocales() { return locales; } - void addPredefinedSort(Sort s) { - predefinedSorts.add(s); + void addPredefinedSort(Sort s, String name) { + predefinedSorts.put(s, new StringBuilder(name)); } Set getExtraSorts() { - return extraSorts; + return extraSorts.keySet(); } void addKnownSymbol(Term term, StringBuilder s) { @@ -192,8 +203,8 @@ List getConstDeclarations() { return constDeclarations; } - Collection getPredefinedSorts() { - return predefinedSorts; + Set getPredefinedSorts() { + return predefinedSorts.keySet(); } List getExceptions() { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index d7062b1ecd1..d8e0f2cc853 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -45,18 +45,14 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } - Set extraParentsToCheck = new HashSet<>(); - extraParentsToCheck.add(Sort.ANY); - extraParentsToCheck.add(services.getNamespaces().sorts().lookup("java.lang.Object")); - - Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), extraParentsToCheck); + Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); for (Sort sort : sortParentsMap.keySet()) { - String sortName = getSortName(sort); + String sortName = masterHandler.translateSortName(sort); String UNIV = sortName + "_UNIV"; result.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); result.append("lemma ex_").append(UNIV).append(":"); - result.append(getUnivSpec(sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); + result.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); result.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); @@ -64,13 +60,13 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING); result.append("specification (").append(UNIV).append(") "); - result.append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + result.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING); String UNIV_spec_lemma_name = UNIV + "_specification"; - result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); result.append(LINE_ENDING); @@ -83,7 +79,9 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); - result.append("lemma ").append(sortName).append("_type_specification[simp]:").append(getUnivSpec(sortParentsMap.get(sort), "(UNIV::" + sortName + " set)")).append(LINE_ENDING); + result.append("lemma ").append(sortName).append("_type_specification[simp]:") + .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "(UNIV::" + sortName + " set)")) + .append(LINE_ENDING); result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING).append(LINE_ENDING); @@ -91,7 +89,7 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) if (parentSort == Sort.ANY) { continue; } - String parentSortName = getSortName(parentSort); + String parentSortName = masterHandler.translateSortName(parentSort); String parentSortInj = sortName + "2" + parentSortName; result.append(LINE_ENDING).append("abbreviation \"").append(parentSortInj).append(" \\ "); result.append("any2").append(parentSortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); @@ -158,13 +156,8 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) return result.append("end").append(LINE_ENDING).append("end"); } - static String getSortName(Sort sort) { - String name = sort.name().toString(); - return name.replace("[]", "arr").replace(".", "_"); - } - - private static String getUnivSpec(Set parents, String insert) { - List parentSortNames = new ArrayList<>(parents.stream().map(IsabelleTranslator::getSortName).toList()); + private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { + List parentSortNames = new ArrayList<>(parents.stream().map(masterHandler::translateSortName).toList()); StringBuilder univSpec = new StringBuilder(); if (parentSortNames.isEmpty()) { parentSortNames.add("any"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java index f90e08a7c40..0a1340cc76e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -26,14 +26,14 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Sort sort = term.sort(); if (!trans.isKnownSort(sort)) { - trans.addSort(sort); + trans.addGenericSort(sort); } - return makeVarRef(term.toString(), sort); + return makeVarRef(trans, term.toString(), sort); } - public static StringBuilder makeVarRef(String name, Sort sort) { + public static StringBuilder makeVarRef(IsabelleMasterHandler trans, String name, Sort sort) { StringBuilder result = new StringBuilder("("); - result.append(VAR_PREFIX).append(name).append("::").append(IsabelleTranslator.getSortName(sort)).append(")"); + result.append(VAR_PREFIX).append(name).append("::").append(trans.translateSortName(sort)).append(")"); return result; } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index acc7e42d440..af20515e5cd 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -34,6 +34,6 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr String functionName = m.group(1); trans.addKnownSymbol(term, new StringBuilder(functionName)); } - return UninterpretedSymbolsHandler.getFunctionTranslation(trans, term, (SortedOperator) term.op(), trans.getKnownSymbol(term).toString()); + return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), trans.getKnownSymbol(term).toString()); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java index 79c0476f183..a807f0a2bbb 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java @@ -36,9 +36,9 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr result.append(supportedOperators.get(term.op())); for (QuantifiableVariable bv : term.boundVars()) { Sort sort = bv.sort(); - result.append(" ").append(LogicalVariableHandler.makeVarRef(bv.name().toString(), sort)); + result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); if (!trans.isKnownSort(sort)) { - trans.addSort(sort); + trans.addGenericSort(sort); } } result.append(". ("); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java index 4853d5321bf..c10af0abc6e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java @@ -9,11 +9,9 @@ import java.io.IOException; import java.util.Properties; - -import static de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler.getFunctionTranslation; +import java.util.stream.Collectors; public class SortDependingFunctionHandler implements IsabelleHandler { - private final String PREFIX = "var_"; @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { @@ -31,14 +29,25 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr SortDependingFunction op = (SortDependingFunction) term.op(); Sort dependentSort = op.getSortDependingOn(); - if (!trans.isKnownSort(op.getSortDependingOn())) { - trans.addSort(dependentSort); + if (!trans.isKnownSort(dependentSort)) { + trans.addGenericSort(dependentSort); } - - String name = PREFIX + op.name().toString().split("::")[1]; + StringBuilder name; if (!trans.isKnownSymbol(term)) { - trans.addKnownSymbol(term, new StringBuilder(name)); + name = LogicalVariableHandler.makeVarRef(trans, op.name().toString().split("::")[1], dependentSort); + trans.addKnownSymbol(term, name); + } else { + name = trans.getKnownSymbol(term); } - return getFunctionTranslation(trans, term, op, name); + + return getSortDependingFunctionRef(trans, term, op, name.toString()); + } + + static StringBuilder getSortDependingFunctionRef(IsabelleMasterHandler trans, Term term, SortDependingFunction op, String name) { + Sort dependentSort = op.getSortDependingOn(); + StringBuilder ref = new StringBuilder("(").append(name).append("::"); + String parameterTypesDecl = op.argSorts().stream().map(trans::translateSortName).collect(Collectors.joining("=>")); + ref.append(parameterTypesDecl).append("=>").append(trans.translateSortName(dependentSort)).append(")"); + return UninterpretedSymbolsHandler.getFunctionRef(trans, term, op, ref.toString()); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index d6bd44cde00..dbbcfd99cc4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -33,16 +33,16 @@ public class UninterpretedSymbolsHandler implements IsabelleHandler { public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { masterHandler.addPreamblesLocales(handlerSnippets); - masterHandler.addPredefinedSort(Sort.ANY); + masterHandler.addPredefinedSort(Sort.ANY, "any"); HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); Namespace sorts = services.getNamespaces().sorts(); - masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object"))); - masterHandler.addPredefinedSort(sorts.lookup(new Name("Null"))); - masterHandler.addPredefinedSort(heapLDT.targetSort()); - masterHandler.addPredefinedSort(locSetLDT.targetSort()); + masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object")), "java_lang_Object"); + masterHandler.addPredefinedSort(sorts.lookup(new Name("Null")), "Null"); + masterHandler.addPredefinedSort(heapLDT.targetSort(), "Heap"); + masterHandler.addPredefinedSort(locSetLDT.targetSort(), "LocSet"); } @Override @@ -71,10 +71,10 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } String name = trans.getKnownSymbol(term).toString(); - return getFunctionTranslation(trans, term, op, name); + return getFunctionRef(trans, term, op, name); } - static StringBuilder getFunctionTranslation(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { + static StringBuilder getFunctionRef(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { List children = trans.translate(term.subs()); StringBuilder result = new StringBuilder("("); result.append(name); @@ -84,7 +84,7 @@ static StringBuilder getFunctionTranslation(IsabelleMasterHandler trans, Term te } Sort sort = op.sort(); if (!trans.isKnownSort(sort)) { - trans.addSort(sort); + trans.addGenericSort(sort); } result.append(")"); return result; From bf211e68b6e9b140b0816f6072cf3c9ace55c198 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 9 Mar 2024 23:35:48 +0100 Subject: [PATCH 052/248] changed any type class instantiations to use fun instead of definition. --- .../IsabelleTranslator.java | 10 +++- .../UninterpretedSymbolsHandler.preamble.xml | 48 ++++++++----------- 2 files changed, 27 insertions(+), 31 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index d8e0f2cc853..8504bc298ec 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -99,8 +99,14 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); result.append("begin").append(LINE_ENDING); - result.append("definition \"to_any_").append(sortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); - result.append("definition \"cast_").append(sortName).append(" \\ ").append(absName).append("\"").append(LINE_ENDING); + String to_any_fun_Name = "to_any_" + sortName; + result.append("fun ").append(to_any_fun_Name) + .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") + .append(LINE_ENDING); + String cast_fun_Name = "cast_" + sortName; + result.append("fun ").append(cast_fun_Name) + .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") + .append(LINE_ENDING); result.append("instance by standard").append(LINE_ENDING); result.append("end").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 16ccec398e3..e20198333f6 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -64,7 +64,6 @@ lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Obj using type_definition.Rep_range type_definition_java_lang_Object by blast typedecl Field -(* "TODO: implement Field type" *) typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" by simp @@ -100,10 +99,11 @@ class any = fixes exact_instance::"'a\<Rightarrow>bool" + instantiation any::any begin -definition "to_any_any \<equiv> (id::any\<Rightarrow>any)" -definition "cast_any \<equiv> (id::any\<Rightarrow>any)" +fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" +fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" instance by standard end @@ -111,22 +111,22 @@ end instantiation int::any begin -definition "to_any_int \<equiv> int2any" -definition "cast_int \<equiv> any2int" +fun to_any_int where "to_any_int x = int2any x" +fun cast_int where "cast_int x = any2int x" instance by standard end instantiation bool::any begin -definition "to_any_bool \<equiv> bool2any" -definition "cast_bool \<equiv> any2bool" +fun to_any_bool where "to_any_bool x = bool2any x" +fun cast_bool where "cast_bool x = any2bool x" instance by standard end instantiation LocSet::any begin -definition "to_any_LocSet \<equiv> LocSet2any" -definition "cast_LocSet \<equiv> any2LocSet" +fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" +fun cast_LocSet where "cast_LocSet x = any2LocSet x" instance by standard end @@ -134,8 +134,8 @@ class java_lang_Object = any instantiation java_lang_Object::java_lang_Object begin -definition "cast_java_lang_Object \<equiv> any2java_lang_Object" -definition "to_any_java_lang_Object \<equiv> java_lang_Object2any" +fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" +fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" instance by standard end @@ -155,8 +155,8 @@ definition "null \<equiv> any2Null bottom" instantiation Null::java_lang_Object begin -definition "to_any_Null \<equiv> Null2any" -definition "cast_Null \<equiv> any2Null" +fun to_any_Null where "to_any_Null (x::Null) = Null2any x" +fun cast_Null where "cast_Null x = any2Null x" instance by standard end @@ -165,23 +165,19 @@ abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ& declare [[coercion Null2java_lang_Object]] consts -select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>('a::any)" store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" wellFormed::"Heap\<Rightarrow>bool" created::"Field" locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" -length::"java_lang_Object\<Rightarrow>int" +obj_length::"java_lang_Object\<Rightarrow>int" -axiomatization where length_nonneg[simp]:"length obj \<ge> 0" +axiomatization where length_nonneg[simp]:"obj_length obj \<ge> 0" -definition "unusedLocs (h::Heap) \<equiv> {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" +fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" -section \<open>select Axioms\<close> -axiomatization where selectOfStore:"select (store h obj f x) o2 f2 \<equiv> (if (obj = o2 \<and> f=f2 \<and> f\<noteq>created) then cast (any2java_lang_Object x) else (select h o2 f2))" -and selectOfCreate:"select (create h obj) o2 f \<equiv> (if (obj=o2 \<and> ((java_lang_Object2any obj)\<noteq>null) \<and> f=created) then cast (any2java_lang_Object True) else select h o2 f)" -and selectOfAnon:"select (anon h s h') obj f \<equiv> (if ((((obj, f):s)\<and>(f\<noteq>created))\<or>(obj, f):unusedLocs(h)) then select h' obj f else select h obj f)" +fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where "select h obj f = cast (h obj f)" section \<open>wellFormed Axioms\<close> @@ -189,13 +185,7 @@ axiomatization where onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \&l and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" -fun instance_All_useSet::"any\<Rightarrow>('a::any) set\<Rightarrow>bool" - where "instance_All_useSet x y = (to_any x : image to_any y)" - -fun instance_All_useRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_useRep x y = (\<exists>z::'a. to_any z = x)" - -fun instance_All_UnivRep::"any\<Rightarrow>'a::any\<Rightarrow>bool" - where "instance_All_UnivRep x y = (x : image to_any (UNIV::'a set))" +fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" + where "instanceof x y = (x : image to_any y)" From 6b67f3db94fde7ac38af4f21c899563bb844001a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 00:15:29 +0100 Subject: [PATCH 053/248] fix error in sort depending functions --- .../gui/isabelletranslation/SortDependingFunctionHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java index c10af0abc6e..9d6a9b5c01d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java @@ -44,10 +44,9 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } static StringBuilder getSortDependingFunctionRef(IsabelleMasterHandler trans, Term term, SortDependingFunction op, String name) { - Sort dependentSort = op.getSortDependingOn(); StringBuilder ref = new StringBuilder("(").append(name).append("::"); String parameterTypesDecl = op.argSorts().stream().map(trans::translateSortName).collect(Collectors.joining("=>")); - ref.append(parameterTypesDecl).append("=>").append(trans.translateSortName(dependentSort)).append(")"); + ref.append(parameterTypesDecl).append("=>").append(trans.translateSortName(op.sort())).append(")"); return UninterpretedSymbolsHandler.getFunctionRef(trans, term, op, ref.toString()); } } From 6a8c37b11395b1e6c4139ef4585e24476726fd46 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 00:16:12 +0100 Subject: [PATCH 054/248] added axiomatizations for function symbols in preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 263 +++++++++--------- 1 file changed, 135 insertions(+), 128 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index e20198333f6..efbb1a82326 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -2,190 +2,197 @@ -General preamble + General preamble -declare [[coercion_enabled]] -declare [[coercion_map image]] + declare [[coercion_enabled]] + declare [[coercion_map image]] -typedecl any + typedecl any -consts -int_subset_inany::"any set" -int2any::"int\<Rightarrow>any" -any2int::"any\<Rightarrow>int" + consts + int_subset_inany::"any set" + int2any::"int\<Rightarrow>any" + any2int::"any\<Rightarrow>int" -axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" -declare [[coercion int2any]] + axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" + declare [[coercion int2any]] -consts -bool_Image::"any set" -bool2any::"bool\<Rightarrow>any" -any2bool::"any\<Rightarrow>bool" + consts + bool_Image::"any set" + bool2any::"bool\<Rightarrow>any" + any2bool::"any\<Rightarrow>bool" -axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" -declare [[coercion bool2any]] + axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" + declare [[coercion bool2any]] -consts -bottom::"any" + consts + bottom::"any" -specification (bottom) "bottom = bottom" - by simp + specification (bottom) "bottom = bottom" + by simp -lemma bottom_in_any:"bottom \<in> (UNIV::any set)" - by simp + lemma bottom_in_any:"bottom \<in> (UNIV::any set)" + by simp + consts + java_lang_Object_UNIV::"any set" -consts -java_lang_Object_UNIV::"any set" + specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" + "bottom:java_lang_Object_UNIV" + by auto -specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" "bottom:java_lang_Object_UNIV" - by auto + lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> + bottom:java_lang_Object_UNIV" + by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) -lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> bottom:java_lang_Object_UNIV" - by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) + typedef java_lang_Object = "java_lang_Object_UNIV" + morphisms java_lang_Object2any any2java_lang_Object + using java_lang_Object_UNIV_specification by auto -typedef java_lang_Object = "java_lang_Object_UNIV" - morphisms java_lang_Object2any any2java_lang_Object - using java_lang_Object_UNIV_specification by auto + declare [[coercion java_lang_Object2any]] -declare [[coercion java_lang_Object2any]] + lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" + by simp -lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" - by simp + lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" + using java_lang_Object_UNIV_specification + using type_definition.Rep_range type_definition_java_lang_Object by blast -lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" - using java_lang_Object_UNIV_specification - using type_definition.Rep_range type_definition_java_lang_Object by blast + typedecl Field -typedecl Field + typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" + by simp -typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" - by simp + declare [[coercion Rep_LocSet]] -declare [[coercion Rep_LocSet]] + consts + LocSet_Image::"any set" + LocSet2any::"LocSet\<Rightarrow>any" + any2LocSet::"any\<Rightarrow>LocSet" -consts -LocSet_Image::"any set" -LocSet2any::"LocSet\<Rightarrow>any" -any2LocSet::"any\<Rightarrow>LocSet" + axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" -axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" + declare [[coercion LocSet2any]] -declare [[coercion LocSet2any]] + typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp -typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp + declare [[coercion Rep_Heap]] -declare [[coercion Rep_Heap]] + consts + Heap_Image::"any set" + Heap2any::"Heap\<Rightarrow>any" + any2Heap::"any\<Rightarrow>Heap" -consts -Heap_Image::"any set" -Heap2any::"Heap\<Rightarrow>any" -any2Heap::"any\<Rightarrow>Heap" + axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" + declare [[coercion Heap2any]] -declare [[coercion Heap2any]] + class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" + fixes exact_instance::"'a\<Rightarrow>bool" -class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" - fixes exact_instance::"'a\<Rightarrow>bool" + instantiation any::any + begin + fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" + fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" + instance by standard + end -instantiation any::any -begin -fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" -fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" -instance by standard -end + instantiation int::any + begin + fun to_any_int where "to_any_int x = int2any x" + fun cast_int where "cast_int x = any2int x" + instance by standard + end + instantiation bool::any + begin + fun to_any_bool where "to_any_bool x = bool2any x" + fun cast_bool where "cast_bool x = any2bool x" + instance by standard + end + instantiation LocSet::any + begin + fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" + fun cast_LocSet where "cast_LocSet x = any2LocSet x" + instance by standard + end -instantiation int::any -begin -fun to_any_int where "to_any_int x = int2any x" -fun cast_int where "cast_int x = any2int x" -instance by standard -end + class java_lang_Object = any -instantiation bool::any -begin -fun to_any_bool where "to_any_bool x = bool2any x" -fun cast_bool where "cast_bool x = any2bool x" -instance by standard -end + instantiation java_lang_Object::java_lang_Object + begin + fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" + fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" + instance by standard + end -instantiation LocSet::any -begin -fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" -fun cast_LocSet where "cast_LocSet x = any2LocSet x" -instance by standard -end + typedef (overloaded) Null = "{bottom}" + morphisms Null2any any2Null + by simp -class java_lang_Object = any + declare [[coercion Null2any]] -instantiation java_lang_Object::java_lang_Object -begin -fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" -fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" -instance by standard -end + lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast -typedef (overloaded) Null = "{bottom}" - morphisms Null2any any2Null - by simp + lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" + using bottom_Null_set bottom_in_java_lang_Object by auto -declare [[coercion Null2any]] + definition "null \<equiv> any2Null bottom" -lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast + instantiation Null::java_lang_Object + begin + fun to_any_Null where "to_any_Null (x::Null) = Null2any x" + fun cast_Null where "cast_Null x = any2Null x" + instance by standard + end -lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" - using bottom_Null_set bottom_in_java_lang_Object by auto + abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" -definition "null \<equiv> any2Null bottom" + declare [[coercion Null2java_lang_Object]] -instantiation Null::java_lang_Object -begin -fun to_any_Null where "to_any_Null (x::Null) = Null2any x" -fun cast_Null where "cast_Null x = any2Null x" -instance by standard -end + consts + store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" + create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" + anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" + created::"Field" + locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" -abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" + axiomatization arr::"int\<Rightarrow>Field" where arr_inject:"(arr x = arr y) = (x = y)" -declare [[coercion Null2java_lang_Object]] + axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> + 0" -consts -store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" -create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" -anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" -wellFormed::"Heap\<Rightarrow>bool" -created::"Field" -locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" -obj_length::"java_lang_Object\<Rightarrow>int" + fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> + obj\<noteq>null}" -axiomatization where length_nonneg[simp]:"obj_length obj \<ge> 0" + fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where + "select h obj f = cast (h obj f)" -fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" -fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where "select h obj f = cast (h obj f)" + section \<open>wellFormed Axioms\<close> + axiomatization wellFormed::"Heap\<Rightarrow>bool" where + onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> + ((select h (select h obj f) created)::bool)" + and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select + h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 + created)::bool)" + and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select + h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" - -section \<open>wellFormed Axioms\<close> -axiomatization where onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" -and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" -and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" - -fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" - where "instanceof x y = (x : image to_any y)" - + fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" + where "instanceof x y = (x : image to_any y)" + From 110d020a1a8726091113d930b16c33f89b131941 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 00:17:37 +0100 Subject: [PATCH 055/248] adjusted translation name for length of objects --- .../ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 32dd4f9adc9..46edcdf811c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -22,7 +22,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Namespace functionNamespace = services.getNamespaces().functions(); Map definedFunctions = new HashMap<>(); definedFunctions.put("null", "null"); - definedFunctions.put("length", "length"); + definedFunctions.put("length", "obj_length"); definedFunctions.put("wellFormed", "wellFormed"); Map definedSortDependingFunctions = new HashMap<>(); From 918d951854cf61dc5556162bbd0ee3977f2a5bef Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 00:32:39 +0100 Subject: [PATCH 056/248] fixed bug where translation crashes on non open goals --- .../gui/isabelletranslation/IsabelleTranslationExtension.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index 2ba0524467e..d9985e38462 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -30,7 +30,7 @@ public SettingsProvider getSettings() { @Override public List getContextActions( KeYMediator mediator, ContextMenuKind kind, PosInSequent pos) { - if (pos.getPosInOccurrence() != null) { + if (pos.getPosInOccurrence() != null || mediator.getSelectedGoal() == null) { return List.of(); } List list = new ArrayList<>(); From 7a18eb9a883e858e3250e2abf2eb37900da8662f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 00:34:40 +0100 Subject: [PATCH 057/248] add arr function to defined symbols --- .../ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 46edcdf811c..7e0c9a76207 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -23,6 +23,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Map definedFunctions = new HashMap<>(); definedFunctions.put("null", "null"); definedFunctions.put("length", "obj_length"); + definedFunctions.put("arr", "arr"); definedFunctions.put("wellFormed", "wellFormed"); Map definedSortDependingFunctions = new HashMap<>(); From e3cdbadfe327fa20cc624c5e85bb42a689bd4726 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 16:39:37 +0100 Subject: [PATCH 058/248] added LocSet function definitions --- .../DefinedSymbolsHandler.java | 14 + .../UninterpretedSymbolsHandler.preamble.xml | 279 +++++++++--------- 2 files changed, 160 insertions(+), 133 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 7e0c9a76207..11635adc14f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -26,6 +26,20 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("arr", "arr"); definedFunctions.put("wellFormed", "wellFormed"); + //LocSet functions + definedFunctions.put("elementOf", "elementOf"); + definedFunctions.put("subset", "subset"); + definedFunctions.put("disjoint", "disjoint"); + definedFunctions.put("empty", "empty"); + definedFunctions.put("allLocs", "allLocs"); + definedFunctions.put("singleton", "singleton"); + definedFunctions.put("union", "union"); + definedFunctions.put("intersect", "intersect"); + definedFunctions.put("setMinus", "setMinus"); + definedFunctions.put("allFields", "allFields"); + definedFunctions.put("allObjects", "allObjects"); + definedFunctions.put("arrayRange", "arrayRange"); + Map definedSortDependingFunctions = new HashMap<>(); definedSortDependingFunctions.put("select", "select"); definedSortDependingFunctions.put("cast", "cast"); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index efbb1a82326..b9bc1e63c08 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -4,195 +4,208 @@ General preamble - declare [[coercion_enabled]] - declare [[coercion_map image]] + declare [[coercion_enabled]] +declare [[coercion_map image]] - typedecl any +typedecl any - consts - int_subset_inany::"any set" - int2any::"int\<Rightarrow>any" - any2int::"any\<Rightarrow>int" +consts + int_subset_inany::"any set" + int2any::"int\<Rightarrow>any" + any2int::"any\<Rightarrow>int" - axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" - declare [[coercion int2any]] +axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" +declare [[coercion int2any]] - consts - bool_Image::"any set" - bool2any::"bool\<Rightarrow>any" - any2bool::"any\<Rightarrow>bool" +consts + bool_Image::"any set" + bool2any::"bool\<Rightarrow>any" + any2bool::"any\<Rightarrow>bool" - axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" - declare [[coercion bool2any]] +axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" +declare [[coercion bool2any]] - consts - bottom::"any" +consts + bottom::"any" - specification (bottom) "bottom = bottom" - by simp +specification (bottom) "bottom = bottom" + by simp - lemma bottom_in_any:"bottom \<in> (UNIV::any set)" - by simp +lemma bottom_in_any:"bottom \<in> (UNIV::any set)" + by simp - consts - java_lang_Object_UNIV::"any set" +consts + java_lang_Object_UNIV::"any set" - specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" - "bottom:java_lang_Object_UNIV" - by auto +specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" + "bottom:java_lang_Object_UNIV" + by auto - lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> - bottom:java_lang_Object_UNIV" - by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) +lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> + bottom:java_lang_Object_UNIV" + by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) - typedef java_lang_Object = "java_lang_Object_UNIV" - morphisms java_lang_Object2any any2java_lang_Object - using java_lang_Object_UNIV_specification by auto +typedef java_lang_Object = "java_lang_Object_UNIV" + morphisms java_lang_Object2any any2java_lang_Object + using java_lang_Object_UNIV_specification by auto - declare [[coercion java_lang_Object2any]] +declare [[coercion java_lang_Object2any]] - lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" - by simp +lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" + by simp - lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" - using java_lang_Object_UNIV_specification - using type_definition.Rep_range type_definition_java_lang_Object by blast +lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" + using java_lang_Object_UNIV_specification + using type_definition.Rep_range type_definition_java_lang_Object by blast - typedecl Field +typedecl Field - typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" - by simp +axiomatization arr::"int\<Rightarrow>Field" where arr_inject:"(arr x = arr y) = (x = y)" - declare [[coercion Rep_LocSet]] - consts - LocSet_Image::"any set" - LocSet2any::"LocSet\<Rightarrow>any" - any2LocSet::"any\<Rightarrow>LocSet" +typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" + by simp - axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" - declare [[coercion LocSet2any]] +setup_lifting type_definition_LocSet +lift_definition elementOf::"(java_lang_Object \<times> Field)\<Rightarrow>LocSet\<Rightarrow>bool" is Set.member. +lift_definition empty::"LocSet" is Set.empty. +lift_definition allLocs::"LocSet" is Set.UNIV. +lift_definition singleton::"(java_lang_Object \<times> Field)\<Rightarrow>LocSet" is "\<lambda>x. {x}". +lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. +lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. +lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. +lift_definition setMinus::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is minus. +lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\<lambda>x. {x} \<times> (UNIV::Field set)". +lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) \<times> {x}". +lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". +lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. - typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp +consts + LocSet_Image::"any set" + LocSet2any::"LocSet\<Rightarrow>any" + any2LocSet::"any\<Rightarrow>LocSet" - declare [[coercion Rep_Heap]] +axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" - consts - Heap_Image::"any set" - Heap2any::"Heap\<Rightarrow>any" - any2Heap::"any\<Rightarrow>Heap" +declare [[coercion LocSet2any]] - axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" +typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp - declare [[coercion Heap2any]] +declare [[coercion Rep_Heap]] - class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" - fixes exact_instance::"'a\<Rightarrow>bool" +consts + Heap_Image::"any set" + Heap2any::"Heap\<Rightarrow>any" + any2Heap::"any\<Rightarrow>Heap" +axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" - instantiation any::any - begin - fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" - fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" - instance by standard - end +declare [[coercion Heap2any]] +class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" + fixes exact_instance::"'a\<Rightarrow>bool" - instantiation int::any - begin - fun to_any_int where "to_any_int x = int2any x" - fun cast_int where "cast_int x = any2int x" - instance by standard - end +instantiation any::any +begin +fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" +fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" +instance by standard +end - instantiation bool::any - begin - fun to_any_bool where "to_any_bool x = bool2any x" - fun cast_bool where "cast_bool x = any2bool x" - instance by standard - end - instantiation LocSet::any - begin - fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" - fun cast_LocSet where "cast_LocSet x = any2LocSet x" - instance by standard - end +instantiation int::any +begin +fun to_any_int where "to_any_int x = int2any x" +fun cast_int where "cast_int x = any2int x" +instance by standard +end - class java_lang_Object = any +instantiation bool::any +begin +fun to_any_bool where "to_any_bool x = bool2any x" +fun cast_bool where "cast_bool x = any2bool x" +instance by standard +end - instantiation java_lang_Object::java_lang_Object - begin - fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" - fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" - instance by standard - end +instantiation LocSet::any +begin +fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" +fun cast_LocSet where "cast_LocSet x = any2LocSet x" +instance by standard +end - typedef (overloaded) Null = "{bottom}" - morphisms Null2any any2Null - by simp - declare [[coercion Null2any]] - lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast +class java_lang_Object = any - lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" - using bottom_Null_set bottom_in_java_lang_Object by auto +instantiation java_lang_Object::java_lang_Object +begin +fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" +fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" +instance by standard +end - definition "null \<equiv> any2Null bottom" +typedef (overloaded) Null = "{bottom}" + morphisms Null2any any2Null + by simp - instantiation Null::java_lang_Object - begin - fun to_any_Null where "to_any_Null (x::Null) = Null2any x" - fun cast_Null where "cast_Null x = any2Null x" - instance by standard - end +declare [[coercion Null2any]] - abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" +lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast - declare [[coercion Null2java_lang_Object]] +lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" + using bottom_Null_set bottom_in_java_lang_Object by auto - consts - store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" - create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" - anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" - created::"Field" - locEps::"(java_lang_Object \<times> Field \<times> LocSet) \<Rightarrow> bool" +definition "null \<equiv> any2Null bottom" - axiomatization arr::"int\<Rightarrow>Field" where arr_inject:"(arr x = arr y) = (x = y)" +instantiation Null::java_lang_Object +begin +fun to_any_Null where "to_any_Null (x::Null) = Null2any x" +fun cast_Null where "cast_Null x = any2Null x" +instance by standard +end - axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> - 0" +abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" - fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> - obj\<noteq>null}" +declare [[coercion Null2java_lang_Object]] - fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where - "select h obj f = cast (h obj f)" +consts + store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" + create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" + anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" + created::"Field" - section \<open>wellFormed Axioms\<close> - axiomatization wellFormed::"Heap\<Rightarrow>bool" where - onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> - ((select h (select h obj f) created)::bool)" - and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> ((o2::java_lang_Object), f2)\<in>((select - h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 - created)::bool)" - and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select - h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" +axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" - fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" - where "instanceof x y = (x : image to_any y)" +fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" + +fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where + "select h obj f = cast (h obj f)" + + +section \<open>wellFormed Axioms\<close> +axiomatization wellFormed::"Heap\<Rightarrow>bool" where + onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> + ((select h (select h obj f) created)::bool)" + and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf((o2::java_lang_Object), f2)((select + h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 + created)::bool)" + and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select + h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" + +fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" + where "instanceof x y = (x : image to_any y)" From 04b2b18859a73b64104e553de6ad76fa4635e178 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 18:47:03 +0100 Subject: [PATCH 059/248] made BSum use at least less than instead of subtracting one --- .../de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java index 52542186bca..197958a36db 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java @@ -41,7 +41,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } } result.append("="); - result.append(trans.translate(term.sub(0))).append("..").append(trans.translate(term.sub(1))).append("-1. "); + result.append(trans.translate(term.sub(0))).append("..<").append(trans.translate(term.sub(1))); result.append(trans.translate(term.sub(2))).append(")"); return result; } From b29c834997f78d21a47ce64cf35ad8ac357c053b Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 10 Mar 2024 23:49:00 +0100 Subject: [PATCH 060/248] 1st version of reasoning over Sequences --- .../UninterpretedSymbolsHandler.preamble.xml | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index b9bc1e63c08..f64ad184388 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -4,7 +4,7 @@ General preamble - declare [[coercion_enabled]] +declare [[coercion_enabled]] declare [[coercion_map image]] @@ -16,7 +16,7 @@ consts int2any::"int\<Rightarrow>any" any2int::"any\<Rightarrow>int" -axiomatization where int_sub_any:"type_definition int2any any2int (int_subset_inany)" +axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_subset_inany)" declare [[coercion int2any]] @@ -25,7 +25,7 @@ consts bool2any::"bool\<Rightarrow>any" any2bool::"any\<Rightarrow>bool" -axiomatization where bool_sub_any:"type_definition bool2any any2bool (bool_Image)" +axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_Image)" declare [[coercion bool2any]] consts @@ -66,7 +66,7 @@ lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Obj typedecl Field -axiomatization arr::"int\<Rightarrow>Field" where arr_inject:"(arr x = arr y) = (x = y)" +axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" @@ -92,7 +92,7 @@ consts LocSet2any::"LocSet\<Rightarrow>any" any2LocSet::"any\<Rightarrow>LocSet" -axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" +axiomatization where LocSet_sub_any[simp]:"type_definition LocSet2any any2LocSet LocSet_Image" declare [[coercion LocSet2any]] @@ -180,6 +180,32 @@ abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ& declare [[coercion Null2java_lang_Object]] +typedef Seq = "UNIV::any list set" + by auto + +consts +getSeqOutside::any + +setup_lifting type_definition_Seq +lift_definition seqLen::"Seq\<Rightarrow>int" is "\<lambda>x. int (List.length x)". +lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". +lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". +lift_definition seqEmpty::"Seq" is "[]". +lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". +lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. +lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. + + + +primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where +"listIndexOf [] a = undefined" | +"listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" + +lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>nat" is listIndexOf. + +fun seqSub::"int\<Rightarrow>int\<Rightarrow>Seq\<Rightarrow>Seq" where +"seqSub i j s = seqDef i j (\<lambda>x. seqGet s x)" + consts store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" From 081078bb8514f09b3ec132a1b7dc029e2045ee3c Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 11 Mar 2024 16:33:53 +0100 Subject: [PATCH 061/248] bug fixes --- .../ilkd/key/gui/isabelletranslation/BSumHandler.java | 2 +- .../gui/isabelletranslation/IsabelleTranslator.java | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java index 197958a36db..5dd60355f78 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java @@ -41,7 +41,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } } result.append("="); - result.append(trans.translate(term.sub(0))).append("..<").append(trans.translate(term.sub(1))); + result.append(trans.translate(term.sub(0))).append("..<").append(trans.translate(term.sub(1))).append(". "); result.append(trans.translate(term.sub(2))).append(")"); return result; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 8504bc298ec..7997715ebb6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -6,6 +6,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.sort.Sort; +import javax.sound.sampled.Line; import java.io.IOException; import java.util.*; @@ -45,6 +46,8 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } + Sort nullSort = services.getNamespaces().sorts().lookup("Null"); + Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); for (Sort sort : sortParentsMap.keySet()) { String sortName = masterHandler.translateSortName(sort); @@ -108,7 +111,12 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") .append(LINE_ENDING); result.append("instance by standard").append(LINE_ENDING); - result.append("end").append(LINE_ENDING); + result.append("end").append(LINE_ENDING).append(LINE_ENDING); + + if (nullSort.extendsTrans(sort)) { + result.append("abbreviation \"Null2").append(sortName).append("\\ any2Null \\ ").append(repName).append("\"").append(LINE_ENDING); + result.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + } result.append(LINE_ENDING).append(LINE_ENDING); } From 2c06f40cecc38714f23d3fde7a3b8ba313f75353 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 13 Mar 2024 12:37:55 +0100 Subject: [PATCH 062/248] added locale interpretation for int and bool to access additional lemmata --- .../UninterpretedSymbolsHandler.preamble.xml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index f64ad184388..492a3e49bba 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -12,13 +12,15 @@ typedecl any consts - int_subset_inany::"any set" + int_Image::"any set" int2any::"int\<Rightarrow>any" any2int::"any\<Rightarrow>int" -axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_subset_inany)" +axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_Image)" declare [[coercion int2any]] +interpretation int: type_definition int2any any2int int_Image + using int_sub_any by simp consts bool_Image::"any set" @@ -28,6 +30,10 @@ consts axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_Image)" declare [[coercion bool2any]] +interpretation bool: type_definition bool2any any2bool bool_Image + using bool_sub_any by simp + + consts bottom::"any" From 4992fbe6304ff47d51fa031f81dfccc04db21d95 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 13 Mar 2024 13:43:34 +0100 Subject: [PATCH 063/248] better translation of array sorts --- .../IsabelleMasterHandler.java | 4 +++ .../IsabelleTranslator.java | 30 +++++++++++++++---- .../UninterpretedSymbolsHandler.preamble.xml | 10 +++---- 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index d299638c80f..594e54cc6e7 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -3,6 +3,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.sort.ArraySort; import de.uka.ilkd.key.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; @@ -140,6 +141,9 @@ boolean isKnownSort(Sort s) { void addGenericSort(Sort sort) { if (!isKnownSort(sort)) { extraSorts.put(sort, new StringBuilder(sort.name().toString().replace("[]", "arr").replace(".", "_"))); + if (sort instanceof ArraySort) { + addGenericSort(((ArraySort) sort).elementSort()); + } } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 7997715ebb6..a8834bf5da8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -4,9 +4,9 @@ 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.sort.ArraySort; import de.uka.ilkd.key.logic.sort.Sort; -import javax.sound.sampled.Line; import java.io.IOException; import java.util.*; @@ -94,9 +94,8 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) } String parentSortName = masterHandler.translateSortName(parentSort); String parentSortInj = sortName + "2" + parentSortName; - result.append(LINE_ENDING).append("abbreviation \"").append(parentSortInj).append(" \\ "); - result.append("any2").append(parentSortName).append(" \\ ").append(repName).append("\"").append(LINE_ENDING); - + result.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) + .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); result.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); } @@ -108,16 +107,35 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) .append(LINE_ENDING); String cast_fun_Name = "cast_" + sortName; result.append("fun ").append(cast_fun_Name) - .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") + .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") .append(LINE_ENDING); result.append("instance by standard").append(LINE_ENDING); result.append("end").append(LINE_ENDING).append(LINE_ENDING); if (nullSort.extendsTrans(sort)) { - result.append("abbreviation \"Null2").append(sortName).append("\\ any2Null \\ ").append(repName).append("\"").append(LINE_ENDING); + String null_to_sort_name = "Null2" + sortName; + result.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) + .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); result.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); } + if (sort instanceof ArraySort) { + result.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); + result.append("begin").append(LINE_ENDING); + + String legal_Values_name = "legal_Values_" + sortName; + String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); + String elementSortUNIV = "((UNIV::" + elementSortName + " set)::any set)"; + result.append("fun ").append(legal_Values_name) + .append(" where \"").append(legal_Values_name) + .append(" (x::").append(sortName).append(")").append(" = ") + .append(elementSortUNIV).append("\"") + .append(LINE_ENDING); + + result.append("instance by standard").append(LINE_ENDING); + result.append("end").append(LINE_ENDING).append(LINE_ENDING); + } + result.append(LINE_ENDING).append(LINE_ENDING); } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 492a3e49bba..d8ead23b3ae 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -121,6 +121,9 @@ class any = fixes cast::"any\<Rightarrow>'a" fixes exact_instance::"'a\<Rightarrow>bool" +class array = + fixes legal_Values::"'a\<Rightarrow>any set" + instantiation any::any begin fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" @@ -151,10 +154,7 @@ instance by standard end - -class java_lang_Object = any - -instantiation java_lang_Object::java_lang_Object +instantiation java_lang_Object::any begin fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" @@ -175,7 +175,7 @@ lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV definition "null \<equiv> any2Null bottom" -instantiation Null::java_lang_Object +instantiation Null::any begin fun to_any_Null where "to_any_Null (x::Null) = Null2any x" fun cast_Null where "cast_Null x = any2Null x" From 060d99267cfcec28fa46c8341362eed138fdf421 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 14 Mar 2024 22:20:56 +0100 Subject: [PATCH 064/248] added lots of axioms and types to preamble --- .../IsabelleTranslator.java | 10 +- .../UninterpretedSymbolsHandler.preamble.xml | 111 ++++++++++++++---- 2 files changed, 92 insertions(+), 29 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a8834bf5da8..5e6fac96690 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -123,13 +123,13 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); result.append("begin").append(LINE_ENDING); - String legal_Values_name = "legal_Values_" + sortName; + String element_type_name = "element_type_" + sortName; String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); - String elementSortUNIV = "((UNIV::" + elementSortName + " set)::any set)"; - result.append("fun ").append(legal_Values_name) - .append(" where \"").append(legal_Values_name) + String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; + result.append("fun ").append(element_type_name) + .append(" where \"").append(element_type_name) .append(" (x::").append(sortName).append(")").append(" = ") - .append(elementSortUNIV).append("\"") + .append(elementSortType).append("\"") .append(LINE_ENDING); result.append("instance by standard").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index d8ead23b3ae..0ccf49551cf 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -10,6 +10,15 @@ declare [[coercion_map image]] typedecl any +typedef javaDL_type = "(UNIV::any set set)" + by auto + +setup_lifting type_definition_javaDL_type +lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.member. +lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. +lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. + + consts int_Image::"any set" @@ -22,6 +31,8 @@ declare [[coercion int2any]] interpretation int: type_definition int2any any2int int_Image using int_sub_any by simp +definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" + consts bool_Image::"any set" bool2any::"bool\<Rightarrow>any" @@ -33,6 +44,8 @@ declare [[coercion bool2any]] interpretation bool: type_definition bool2any any2bool bool_Image using bool_sub_any by simp +definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" + consts bottom::"any" @@ -63,6 +76,8 @@ typedef java_lang_Object = "java_lang_Object_UNIV" declare [[coercion java_lang_Object2any]] +definition java_lang_Object_type::"javaDL_type" where "java_lang_Object_type \<equiv> Abs_javaDL_type (UNIV::java_lang_Object set)" + lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" by simp @@ -70,8 +85,13 @@ lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Obj using java_lang_Object_UNIV_specification using type_definition.Rep_range type_definition_java_lang_Object by blast + typedecl Field +consts + created::"Field" + fieldType::"Field\<Rightarrow>javaDL_type" + axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" @@ -83,7 +103,7 @@ setup_lifting type_definition_LocSet lift_definition elementOf::"(java_lang_Object \<times> Field)\<Rightarrow>LocSet\<Rightarrow>bool" is Set.member. lift_definition empty::"LocSet" is Set.empty. lift_definition allLocs::"LocSet" is Set.UNIV. -lift_definition singleton::"(java_lang_Object \<times> Field)\<Rightarrow>LocSet" is "\<lambda>x. {x}". +lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj f. {(obj, f)}". lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. @@ -98,10 +118,17 @@ consts LocSet2any::"LocSet\<Rightarrow>any" any2LocSet::"any\<Rightarrow>LocSet" -axiomatization where LocSet_sub_any[simp]:"type_definition LocSet2any any2LocSet LocSet_Image" +axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" + +interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image + using LocSet_sub_any by simp declare [[coercion LocSet2any]] +definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" + + + typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" by simp @@ -114,15 +141,17 @@ consts axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" +interpretation Heap:type_definition Heap2any any2Heap Heap_Image + using Heap_sub_any by simp + declare [[coercion Heap2any]] +definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" + + class any = fixes to_any::"'a\<Rightarrow>any" fixes cast::"any\<Rightarrow>'a" - fixes exact_instance::"'a\<Rightarrow>bool" - -class array = - fixes legal_Values::"'a\<Rightarrow>any set" instantiation any::any begin @@ -131,7 +160,6 @@ fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" instance by standard end - instantiation int::any begin fun to_any_int where "to_any_int x = int2any x" @@ -153,6 +181,12 @@ fun cast_LocSet where "cast_LocSet x = any2LocSet x" instance by standard end +instantiation Heap::any +begin +fun to_any_Heap where "to_any_Heap x = Heap2any x" +fun cast_Heap where "cast_Heap x = any2Heap x" +instance by standard +end instantiation java_lang_Object::any begin @@ -190,10 +224,10 @@ typedef Seq = "UNIV::any list set" by auto consts -getSeqOutside::any + getSeqOutside::any setup_lifting type_definition_Seq -lift_definition seqLen::"Seq\<Rightarrow>int" is "\<lambda>x. int (List.length x)". +lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". lift_definition seqEmpty::"Seq" is "[]". @@ -201,31 +235,54 @@ lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. - +fun seqSub::"int\<Rightarrow>int\<Rightarrow>Seq\<Rightarrow>Seq" where + "seqSub i j s = seqDef i j (\<lambda>x. seqGet s x)" primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where -"listIndexOf [] a = undefined" | -"listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" + "listIndexOf [] a = undefined" | + "listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>nat" is listIndexOf. -fun seqSub::"int\<Rightarrow>int\<Rightarrow>Seq\<Rightarrow>Seq" where -"seqSub i j s = seqDef i j (\<lambda>x. seqGet s x)" +axiomatization Seq2any any2Seq Seq_UNIV + where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" -consts - store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" - create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" - anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" - created::"Field" +interpretation Seq: type_definition Seq2any any2Seq Seq_UNIV + using Seq_sub_any by simp +declare [[coercion Seq2any]] + +instantiation Seq::any +begin +fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" +fun cast_Seq where "cast_Seq (x::any) = any2Seq x" +instance by standard +end + + +fun instanceof::"javaDL_type\<Rightarrow>any\<Rightarrow>bool" + where "instanceof x type = typeof type x" axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" -fun unusedLocs where "unusedLocs (h::Heap) = {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" +fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where "select h obj f = cast (h obj f)" +fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where + "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf (obj, f) s \<and> f\<noteq>created \<or> elementOf (obj, f) (unusedLocs h1) + then select h2 obj f else select h1 obj f))" + +fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" where + "store h obj f x = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=f \<and> f\<noteq>created then x else h obj' f'))" + +fun create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" where + "create h obj = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=created \<and> obj\<noteq>null then cast True else h obj' f'))" + + +class array = any + + fixes element_type::"'a\<Rightarrow>javaDL_type" section \<open>wellFormed Axioms\<close> axiomatization wellFormed::"Heap\<Rightarrow>bool" where @@ -235,9 +292,15 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select - h x created) \<and> instanceof x)) \<Longrightarrow> wellFormed (store h obj f x)" - -fun instanceof::"any\<Rightarrow>'a::any set\<Rightarrow>bool" - where "instanceof x y = (x : image to_any y)" + h x created) \<and> instanceof (fieldType f) x)) \<Longrightarrow> wellFormed (store h obj f x)" + and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf (ov,fv) y \<longrightarrow> ov = null \<or> select h ov created)) + \<Longrightarrow> wellFormed (store h obj f y)" + and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> wellFormed h + \<Longrightarrow> wellFormed (store h obj f x))" + and wellFormedCreate:"wellFormed h \<Longrightarrow> wellFormed (create h obj)" + and wellFormedAnon:"wellFormed h \<and> wellFormed h2 \<Longrightarrow> wellFormed (anon h y h2)" + +axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) + \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" From dc1262bef83c001f28ccd4d15e8f2a72c7704eed Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 14 Mar 2024 22:30:17 +0100 Subject: [PATCH 065/248] added some more defined symbols in DefinedSymbolsHandler --- .../DefinedSymbolsHandler.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 11635adc14f..8f91ce19a92 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -25,6 +25,21 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("length", "obj_length"); definedFunctions.put("arr", "arr"); definedFunctions.put("wellFormed", "wellFormed"); + definedFunctions.put("anon", "anon"); + definedFunctions.put("store", "store"); + + //Seq functions + definedFunctions.put("seqLen", "seqLen"); + definedFunctions.put("seqIndexOf", "seqIndexOf"); + definedFunctions.put("seqGetOutside", "seqGetOutside"); + definedFunctions.put("seqEmpty", "seqEmpty"); + definedFunctions.put("seqSingleton", "seqSingleton"); + definedFunctions.put("seqConcat", "seqConcat"); + definedFunctions.put("seqSub", "seqSub"); + //TODO seqPerm + definedFunctions.put("seqSwap", "seqSwap"); + definedFunctions.put("seqRemove", "seqRemove"); + definedFunctions.put("seqReverse", "seqReverse"); //LocSet functions definedFunctions.put("elementOf", "elementOf"); @@ -43,8 +58,10 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Map definedSortDependingFunctions = new HashMap<>(); definedSortDependingFunctions.put("select", "select"); definedSortDependingFunctions.put("cast", "cast"); - definedSortDependingFunctions.put("instance", "instance"); - definedSortDependingFunctions.put("exactInstance", "exactInstance"); + //TODO separate handler for instance syntax + //definedSortDependingFunctions.put("instance", "instanceof"); + //definedSortDependingFunctions.put("exactInstance", "exactInstance"); + definedSortDependingFunctions.put("seqGet", "seqGet"); for (String name : definedFunctions.keySet()) { Function function = functionNamespace.lookup(name); From b3e03e42c89f69f34425f00411c737476c21e556 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 15 Mar 2024 19:38:08 +0100 Subject: [PATCH 066/248] inverted knownSymbol and knownSort functions --- .../key/gui/isabelletranslation/BSumHandler.java | 2 +- .../key/gui/isabelletranslation/FieldHandler.java | 2 +- .../isabelletranslation/IsabelleMasterHandler.java | 14 +++++++------- .../LogicalVariableHandler.java | 2 +- .../ObserverFunctionHandler.java | 2 +- .../gui/isabelletranslation/QuantifierHandler.java | 2 +- .../SortDependingFunctionHandler.java | 4 ++-- .../UninterpretedSymbolsHandler.java | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java index 5dd60355f78..5ee38b2f10e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java @@ -36,7 +36,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr for (QuantifiableVariable bv : term.boundVars()) { Sort sort = bv.sort(); result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); - if (!trans.isKnownSort(sort)) { + if (trans.isNewSort(sort)) { trans.addGenericSort(sort); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index efd86ecd99a..45d8a092ac2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -37,7 +37,7 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { - if (!trans.isKnownSymbol(term)) { + if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); String fieldName = op.name().toString().replace("::$", "_"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 594e54cc6e7..1d340233b7c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -120,7 +120,7 @@ private void addConstDeclaration(Term term) { decl.append("::\""); for (Term sub : term.subs()) { - if (!isKnownSort(sub.sort())) { + if (isNewSort(sub.sort())) { addGenericSort(sub.sort()); } decl.append(translateSortName(sub.sort())).append("=>"); @@ -130,16 +130,16 @@ private void addConstDeclaration(Term term) { constDeclarations.add(decl); } - boolean isKnownSymbol(Term term) { - return unknownValues.containsKey(term.op()); + boolean isNewSymbol(Term term) { + return !unknownValues.containsKey(term.op()); } - boolean isKnownSort(Sort s) { - return (predefinedSorts.containsKey(s) || extraSorts.containsKey(s)); + boolean isNewSort(Sort s) { + return (!predefinedSorts.containsKey(s) && !extraSorts.containsKey(s)); } void addGenericSort(Sort sort) { - if (!isKnownSort(sort)) { + if (isNewSort(sort)) { extraSorts.put(sort, new StringBuilder(sort.name().toString().replace("[]", "arr").replace(".", "_"))); if (sort instanceof ArraySort) { addGenericSort(((ArraySort) sort).elementSort()); @@ -156,7 +156,7 @@ List getPreambles() { } String translateSortName(Sort sort) { - if (!isKnownSort(sort)) { + if (isNewSort(sort)) { addGenericSort(sort); } if (predefinedSorts.containsKey(sort)) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java index 0a1340cc76e..58adb04b832 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java @@ -25,7 +25,7 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Sort sort = term.sort(); - if (!trans.isKnownSort(sort)) { + if (trans.isNewSort(sort)) { trans.addGenericSort(sort); } return makeVarRef(trans, term.toString(), sort); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index af20515e5cd..24222850603 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -25,7 +25,7 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { - if (!trans.isKnownSymbol(term)) { + if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); if (!m.find()) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java index a807f0a2bbb..72c8bad08a5 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java @@ -37,7 +37,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr for (QuantifiableVariable bv : term.boundVars()) { Sort sort = bv.sort(); result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); - if (!trans.isKnownSort(sort)) { + if (trans.isNewSort(sort)) { trans.addGenericSort(sort); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java index 9d6a9b5c01d..5fd5929b8ae 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java @@ -29,11 +29,11 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr SortDependingFunction op = (SortDependingFunction) term.op(); Sort dependentSort = op.getSortDependingOn(); - if (!trans.isKnownSort(dependentSort)) { + if (trans.isNewSort(dependentSort)) { trans.addGenericSort(dependentSort); } StringBuilder name; - if (!trans.isKnownSymbol(term)) { + if (trans.isNewSymbol(term)) { name = LogicalVariableHandler.makeVarRef(trans, op.name().toString().split("::")[1], dependentSort); trans.addKnownSymbol(term, name); } else { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index dbbcfd99cc4..2ff10644501 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -65,7 +65,7 @@ private static boolean bindsVars(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { SortedOperator op = (SortedOperator) term.op(); - if (!trans.isKnownSymbol(term)) { + if (trans.isNewSymbol(term)) { String name = PREFIX + op.name().toString(); trans.addKnownSymbol(term, new StringBuilder(name.replace("::", "_").replace(".", "_"))); } @@ -83,7 +83,7 @@ static StringBuilder getFunctionRef(IsabelleMasterHandler trans, Term term, Sort result.append(" ").append(child); } Sort sort = op.sort(); - if (!trans.isKnownSort(sort)) { + if (trans.isNewSort(sort)) { trans.addGenericSort(sort); } result.append(")"); From 6639c6e98f784b22354a68eee3585a4370a1ad39 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 15 Mar 2024 19:44:08 +0100 Subject: [PATCH 067/248] added jdiv and jmod to IntegerOpHandler --- .../uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index 14236a485d8..14e98b8b950 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -37,6 +37,9 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert supportedOperators.put(integerLDT.getMod(), "euclMod"); supportedOperators.put(integerLDT.getNeg(), "-"); + supportedOperators.put(integerLDT.getJDivision(), "jdiv"); + supportedOperators.put(integerLDT.getJModulo(), "jmod"); + supportedOperators.put(integerLDT.getLessOrEquals(), "<="); supportedOperators.put(integerLDT.getLessThan(), "<"); supportedOperators.put(integerLDT.getGreaterOrEquals(), ">="); From 4dc07dec2c559b5cb83cb6fa3e262400de8533fe Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 16 Mar 2024 00:23:20 +0100 Subject: [PATCH 068/248] added InstanceOperatorHandler --- .../DefinedSymbolsHandler.java | 3 - .../InstanceOperatorHandler.java | 57 +++++++++++++++++++ .../isabelletranslation/defaultHandlers.txt | 1 + 3 files changed, 58 insertions(+), 3 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 8f91ce19a92..f79f4de36ab 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -58,9 +58,6 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Map definedSortDependingFunctions = new HashMap<>(); definedSortDependingFunctions.put("select", "select"); definedSortDependingFunctions.put("cast", "cast"); - //TODO separate handler for instance syntax - //definedSortDependingFunctions.put("instance", "instanceof"); - //definedSortDependingFunctions.put("exactInstance", "exactInstance"); definedSortDependingFunctions.put("seqGet", "seqGet"); for (String name : definedFunctions.keySet()) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java new file mode 100644 index 00000000000..6e23cdb73d6 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java @@ -0,0 +1,57 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Namespace; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Function; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.SortDependingFunction; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class InstanceOperatorHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + Namespace functionNamespace = services.getNamespaces().functions(); + Map definedSortDependingFunctions = new HashMap<>(); + + definedSortDependingFunctions.put("instance", "instanceof"); + definedSortDependingFunctions.put("exactInstance", "exactInstance"); + + for (Function function : functionNamespace.elements()) { + if (!(function instanceof SortDependingFunction)) + continue; + String funName = function.name().toString().split("::")[1]; + for (String name : definedSortDependingFunctions.keySet()) { + if (funName.equals(name)) { + supportedOperators.put(function, definedSortDependingFunctions.get(name)); + } + } + } + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + SortDependingFunction op = (SortDependingFunction) term.op(); + String functionName = supportedOperators.get(op); + String dependingSortTypeName = trans.translateSortName(op.getSortDependingOn()) + "type"; + + StringBuilder result = new StringBuilder("("); + result.append("(").append(functionName).append(") "); + result.append(trans.translate(term.sub(0))).append(" "); + result.append(dependingSortTypeName).append(")"); + + return result; + } +} diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index 6fee436890a..2546d6eb05d 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -1,4 +1,5 @@ de.uka.ilkd.key.gui.isabelletranslation.DefinedSymbolsHandler +de.uka.ilkd.key.gui.isabelletranslation.InstanceOperatorHandler de.uka.ilkd.key.gui.isabelletranslation.BooleanOpHandler de.uka.ilkd.key.gui.isabelletranslation.PolymorphicHandler de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler From 75e262bcee034b5d794f0bd9051e226db1469bf3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 16 Mar 2024 16:07:50 +0100 Subject: [PATCH 069/248] added function to switch from int bSum to nat bSum in preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 0ccf49551cf..1444c10acd2 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -302,5 +302,56 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" + +lemma int_SUM_0[simp]: + fixes f::"int\<Rightarrow>int" + fixes lower::int + fixes upper::int + assumes "lower\<ge>0" + shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::nat) = (nat lower)..<(nat upper). f (int j))" +proof - + consider (baseCase) "lower \<ge> upper" | (complex) "lower < upper" by linarith + then show ?thesis + proof cases + case baseCase + then show ?thesis + by simp + next + case complex + then have "image int {(nat lower)..<(nat upper)} = {lower..<upper}" + using assms + by (simp add: image_int_atLeastLessThan) + then show ?thesis + proof - + have "\<forall>n f na. (\<Sum>n = n..<na. (f (int n)::int)) = sum f {int n..<int na}" + by (simp add: sum.atLeast_int_lessThan_int_shift) + then show ?thesis + by (metis (no_types) \<open>int ` {nat lower..<nat upper} = {lower..<upper}\<close> image_int_atLeastLessThan) + qed + qed +qed + +lemma int_SUM_neg[simp]: + fixes f::"int\<Rightarrow>int" + fixes lower::int + fixes upper::int + assumes "lower<0" + shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::nat) = (nat (lower-lower))..<(nat (upper - lower)). f (int j + lower))" +proof - + have "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper. (f \<circ> (\<lambda>x. x + lower) \<circ> (\<lambda>x. x - lower)) i)" + by simp + also have "... = sum (f\<circ>(\<lambda>x. x + lower)) (image (\<lambda>x. x - lower) {lower..<upper})" + by (simp add: sum.reindex) + finally have "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::int) = (0)..< (upper - lower). f (j + lower))" + proof - + have "sum (f \<circ> (\<lambda>i. i + lower)) {0..<upper - lower} = sum f {lower..<upper}" + by (metis (no_types) image_add_int_atLeastLessThan inj_on_add' sum.reindex) + then have "(\<Sum>i = 0..<upper - lower. f (i + lower)) = sum f {lower..<upper}" + by simp + then show ?thesis + by simp + qed + then show ?thesis by simp +qed From 2e4619e19812412658d7454cd06cdda4b1abc23a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 16 Mar 2024 19:00:21 +0100 Subject: [PATCH 070/248] field names should not include . --- .../de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 45d8a092ac2..7496a113d4c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -40,7 +40,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - String fieldName = op.name().toString().replace("::$", "_"); + String fieldName = op.name().toString().replace("::$", "_").replace(".", "_"); if (m.find()) { fieldName = m.group(1); } From e5fe37c73b545f3e054ae9c96022760e7229cfb3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 17 Mar 2024 19:39:25 +0100 Subject: [PATCH 071/248] neg, jdiv, jmod translation fixes --- .../gui/isabelletranslation/IntegerOpHandler.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java index 14e98b8b950..fb16e83948f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java @@ -24,11 +24,13 @@ public class IntegerOpHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); + private IntegerLDT integerLDT; + @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { supportedOperators.clear(); - IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); + integerLDT = services.getTypeConverter().getIntegerLDT(); supportedOperators.put(integerLDT.getAdd(), "+"); supportedOperators.put(integerLDT.getMul(), "*"); @@ -37,8 +39,8 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert supportedOperators.put(integerLDT.getMod(), "euclMod"); supportedOperators.put(integerLDT.getNeg(), "-"); - supportedOperators.put(integerLDT.getJDivision(), "jdiv"); - supportedOperators.put(integerLDT.getJModulo(), "jmod"); + supportedOperators.put(integerLDT.getJDivision(), "jDiv"); + supportedOperators.put(integerLDT.getJModulo(), "jMod"); supportedOperators.put(integerLDT.getLessOrEquals(), "<="); supportedOperators.put(integerLDT.getLessThan(), "<"); @@ -59,6 +61,11 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr List children = trans.translate(term.subs()); Operator op = term.op(); + //negation has a special pattern in Isabelle and thus can't be translated like the other functions + if (op == integerLDT.getNeg()) { + return new StringBuilder("(-").append(children.get(0)).append(")"); + } + StringBuilder result = new StringBuilder(); result.append("(("); result.append(supportedOperators.get(op)); From e2da013779e658ed480416beb3d9e504f3378ec2 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 17 Mar 2024 21:53:27 +0100 Subject: [PATCH 072/248] removed fulfilled TODO --- .../uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java | 1 - .../ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java | 1 - .../uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 1 - 3 files changed, 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java index d98aa7af8aa..342f9020e5e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java @@ -33,7 +33,6 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Operator logicTrue = ldt.getTrueConst(); supportedOperators.put(logicTrue, new StringBuilder("True")); - //TODO add boolean declarations masterHandler.addPredefinedSort(ldt.targetSort(), "bool"); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 1d340233b7c..27fcb49019c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -43,7 +43,6 @@ public class IsabelleMasterHandler { */ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { - //TODO efficient loading of handlers. See MasterHandler in SMT List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); predefinedSorts.put(Sort.ANY, new StringBuilder("any")); predefinedSorts.put(Sort.FORMULA, new StringBuilder("bool")); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 5e6fac96690..8d89ae32493 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -20,7 +20,6 @@ public IsabelleTranslator(Services services) { public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { List antecedents = sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); List succedents = sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); - // TODO find correct values IsabelleMasterHandler masterHandler; try { masterHandler = new IsabelleMasterHandler(services, new String[0], new String[0]); From 10417ae18c8360a94c04dcd6875d656c91a0264d Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 17 Mar 2024 23:04:59 +0100 Subject: [PATCH 073/248] fix javaDL_type declaration --- .../gui/isabelletranslation/InstanceOperatorHandler.java | 2 +- .../key/gui/isabelletranslation/IsabelleTranslator.java | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java index 6e23cdb73d6..bae95bd26e0 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java @@ -45,7 +45,7 @@ public boolean canHandle(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { SortDependingFunction op = (SortDependingFunction) term.op(); String functionName = supportedOperators.get(op); - String dependingSortTypeName = trans.translateSortName(op.getSortDependingOn()) + "type"; + String dependingSortTypeName = trans.translateSortName(op.getSortDependingOn()) + "_type"; StringBuilder result = new StringBuilder("("); result.append("(").append(functionName).append(") "); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 8d89ae32493..b6028dd07b4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -81,8 +81,10 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + + String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; result.append("lemma ").append(sortName).append("_type_specification[simp]:") - .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "(UNIV::" + sortName + " set)")) + .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) .append(LINE_ENDING); result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); result.append(LINE_ENDING).append(LINE_ENDING); @@ -135,6 +137,9 @@ public final StringBuilder translateProblem(Sequent sequent, Services services) result.append("end").append(LINE_ENDING).append(LINE_ENDING); } + String typeConstName = sortName + "_type"; + result.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); + result.append(LINE_ENDING).append(LINE_ENDING); } From 30f67200e0f89365e581eed5be08f20a4d53c8a3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 17 Mar 2024 23:15:26 +0100 Subject: [PATCH 074/248] currying applied to elementOf function --- .../UninterpretedSymbolsHandler.preamble.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 1444c10acd2..9fcb96377c6 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -100,7 +100,7 @@ typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" setup_lifting type_definition_LocSet -lift_definition elementOf::"(java_lang_Object \<times> Field)\<Rightarrow>LocSet\<Rightarrow>bool" is Set.member. +lift_definition elementOf::"java_lang_Object \<Rightarrow> Field \<Rightarrow>LocSet\<Rightarrow>bool" is "\<lambda>obj f s. (obj, f) \<in> s". lift_definition empty::"LocSet" is Set.empty. lift_definition allLocs::"LocSet" is Set.UNIV. lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj f. {(obj, f)}". @@ -271,7 +271,7 @@ fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\< "select h obj f = cast (h obj f)" fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where - "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf (obj, f) s \<and> f\<noteq>created \<or> elementOf (obj, f) (unusedLocs h1) + "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf obj f s \<and> f\<noteq>created \<or> elementOf obj f (unusedLocs h1) then select h2 obj f else select h1 obj f))" fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" where @@ -288,12 +288,12 @@ section \<open>wellFormed Axioms\<close> axiomatization wellFormed::"Heap\<Rightarrow>bool" where onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> ((select h (select h obj f) created)::bool)" - and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf((o2::java_lang_Object), f2)((select + and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf (o2::java_lang_Object) f2 ((select h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select h x created) \<and> instanceof (fieldType f) x)) \<Longrightarrow> wellFormed (store h obj f x)" - and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf (ov,fv) y \<longrightarrow> ov = null \<or> select h ov created)) + and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> ov = null \<or> select h ov created)) \<Longrightarrow> wellFormed (store h obj f y)" and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> wellFormed h \<Longrightarrow> wellFormed (store h obj f x))" From 48101e51b2d3a39100f91aa3fd31d6824b981a32 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 18 Mar 2024 16:06:08 +0100 Subject: [PATCH 075/248] now saves translation file to subdirectory of .key folder --- .../key/gui/isabelletranslation/TranslationAction.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 1580767e853..b8ab4d004a8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -7,9 +7,9 @@ import org.slf4j.LoggerFactory; import java.awt.event.ActionEvent; +import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Paths; public class TranslationAction extends MainWindowAction { @@ -32,11 +32,12 @@ private void generateTranslation() { IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); try { //TODO let user choose where to save file? - String path = System.getProperty("user.home") + "\\Translation.thy"; + File translationFile = new File(System.getProperty("user.home") + "/.key/IsabelleTranslations/Translation.thy"); StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent(), mediator.getServices()); try { - Files.write(Paths.get(path), translation.toString().getBytes()); - LOGGER.info("Saved to: " + path); + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationFile.toPath(), translation.toString().getBytes()); + LOGGER.info("Saved to: " + translationFile.toPath()); } catch (IOException e) { //TODO handle exception throw new RuntimeException(e); From da0aa66cc41d25c595618e272c63c2f5129fa38e Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 18 Mar 2024 16:14:30 +0100 Subject: [PATCH 076/248] moved services parameter of methods to field in Translator --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 5 ++++- .../ilkd/key/gui/isabelletranslation/TranslationAction.java | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index b6028dd07b4..03688da9ae3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -14,10 +14,13 @@ public class IsabelleTranslator { private static final String LINE_ENDING = "\n"; + private final Services services; + public IsabelleTranslator(Services services) { + this.services = services; } - public final StringBuilder translateProblem(Sequent sequent, Services services) throws IllegalFormulaException { + public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormulaException { List antecedents = sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); List succedents = sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); IsabelleMasterHandler masterHandler; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index b8ab4d004a8..05eb60218d1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -33,7 +33,7 @@ private void generateTranslation() { try { //TODO let user choose where to save file? File translationFile = new File(System.getProperty("user.home") + "/.key/IsabelleTranslations/Translation.thy"); - StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent(), mediator.getServices()); + StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); try { Files.createDirectories(translationFile.toPath().getParent()); Files.write(translationFile.toPath(), translation.toString().getBytes()); From 0d2a1e56410037ab18e26edbf13c82cee866871e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 20 Mar 2024 13:41:04 +0100 Subject: [PATCH 077/248] added scala-isabelle project to dependencies --- build.gradle | 6 ++++-- keyext.isabelletranslation/build.gradle | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index b0d1a7bb174..999ce4ad81c 100644 --- a/build.gradle +++ b/build.gradle @@ -22,6 +22,8 @@ plugins { // Code formatting id "com.diffplug.spotless" version "6.24.0" + + id "scala" } // Configure this project for use inside IntelliJ: @@ -338,9 +340,9 @@ subprojects { // specific delimiter: normally just 'package', but spotless crashes for files in default package // (see https://github.com/diffplug/spotless/issues/30), therefore 'import' is needed. '//' is for files // with completely commented out code (which would probably better just be removed in future). - if(project.name == 'recoder') { + if (project.name == 'recoder') { licenseHeaderFile("$rootDir/gradle/header-recoder", '(package|import|//)') - }else { + } else { licenseHeaderFile("$rootDir/gradle/header", '(package|import|//)') } } diff --git a/keyext.isabelletranslation/build.gradle b/keyext.isabelletranslation/build.gradle index 7d79bffb33f..3c6ea840523 100644 --- a/keyext.isabelletranslation/build.gradle +++ b/keyext.isabelletranslation/build.gradle @@ -3,4 +3,5 @@ description "Translate" dependencies { implementation project(':key.core') implementation project(':key.ui') + implementation("de.unruh:scala-isabelle_2.13:0.4.2") } From 44f50f2fcc52cc945c84ad083e182b8bfdf7ba11 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 20 Mar 2024 14:42:19 +0100 Subject: [PATCH 078/248] opens the translation file in Isabelle --- build.gradle | 2 -- .../TranslationAction.java | 35 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 999ce4ad81c..6e8c0fbb224 100644 --- a/build.gradle +++ b/build.gradle @@ -22,8 +22,6 @@ plugins { // Code formatting id "com.diffplug.spotless" version "6.24.0" - - id "scala" } // Configure this project for use inside IntelliJ: diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 05eb60218d1..6e04ac684c2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -3,13 +3,23 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.misc.Symbols; +import de.unruh.isabelle.pure.Context; +import de.unruh.isabelle.pure.Term; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import scala.collection.immutable.Seq; +import scala.collection.mutable.Builder; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; public class TranslationAction extends MainWindowAction { @@ -34,6 +44,21 @@ private void generateTranslation() { //TODO let user choose where to save file? File translationFile = new File(System.getProperty("user.home") + "/.key/IsabelleTranslations/Translation.thy"); StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); + + //TODO find Isabelle path + Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); + + //TODO automatically run try/sledgehammer instead of opening Isabelle + Isabelle isabelle = new Isabelle(setup); + Context context = Context.apply("Main", isabelle); + Term translationTerm = Term.apply(context, translation.toString(), Symbols.globalInstance(), isabelle); + + isabelle.destroy(); + + List filePaths = new ArrayList<>(); + filePaths.add(translationFile.toPath()); + + try { Files.createDirectories(translationFile.toPath().getParent()); Files.write(translationFile.toPath(), translation.toString().getBytes()); @@ -42,6 +67,16 @@ private void generateTranslation() { //TODO handle exception throw new RuntimeException(e); } + + Builder> builder = Seq.newBuilder(); + for (Path path : filePaths) { + builder.addOne(path); + } + + + Seq pathSeq = builder.result(); + + Isabelle.jedit(setup, pathSeq); } catch (IllegalFormulaException e) { //TODO output alert to user throw new RuntimeException(e); From a037d507b940ddf3a23c113767872bf40b1e21b1 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 20 Mar 2024 15:24:43 +0100 Subject: [PATCH 079/248] added naive concurrency implementation for opening Isabelle --- .../TranslationAction.java | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 6e04ac684c2..d2711190e6b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -5,9 +5,6 @@ import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; -import de.unruh.isabelle.misc.Symbols; -import de.unruh.isabelle.pure.Context; -import de.unruh.isabelle.pure.Term; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.collection.immutable.Seq; @@ -49,11 +46,11 @@ private void generateTranslation() { Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); //TODO automatically run try/sledgehammer instead of opening Isabelle - Isabelle isabelle = new Isabelle(setup); - Context context = Context.apply("Main", isabelle); - Term translationTerm = Term.apply(context, translation.toString(), Symbols.globalInstance(), isabelle); - - isabelle.destroy(); + //Isabelle isabelle = new Isabelle(setup); + //Context context = Context.apply("Main", isabelle); + //Term translationTerm = Term.apply(context, translation.toString(), Symbols.globalInstance(), isabelle); + + //isabelle.destroy(); List filePaths = new ArrayList<>(); filePaths.add(translationFile.toPath()); @@ -75,8 +72,15 @@ private void generateTranslation() { Seq pathSeq = builder.result(); + //TODO improve concurrency? + Thread isabelleJEdit = new Thread() { + public void run() { + + Isabelle.jedit(setup, pathSeq); + } + }; - Isabelle.jedit(setup, pathSeq); + isabelleJEdit.start(); } catch (IllegalFormulaException e) { //TODO output alert to user throw new RuntimeException(e); From 1da460a454a023683a70ed12faa3ac144c5737c7 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 21 Mar 2024 12:37:24 +0100 Subject: [PATCH 080/248] cleanup --- .../gui/isabelletranslation/TranslationAction.java | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index d2711190e6b..2cc51ad5e3e 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -46,12 +46,6 @@ private void generateTranslation() { Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); //TODO automatically run try/sledgehammer instead of opening Isabelle - //Isabelle isabelle = new Isabelle(setup); - //Context context = Context.apply("Main", isabelle); - //Term translationTerm = Term.apply(context, translation.toString(), Symbols.globalInstance(), isabelle); - - //isabelle.destroy(); - List filePaths = new ArrayList<>(); filePaths.add(translationFile.toPath()); @@ -73,12 +67,7 @@ private void generateTranslation() { Seq pathSeq = builder.result(); //TODO improve concurrency? - Thread isabelleJEdit = new Thread() { - public void run() { - - Isabelle.jedit(setup, pathSeq); - } - }; + Thread isabelleJEdit = new Thread(() -> Isabelle.jedit(setup, pathSeq)); isabelleJEdit.start(); } catch (IllegalFormulaException e) { From 4b7aad3e43d3154200c14ccca8537dde797c6adc Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 21 Mar 2024 16:32:53 +0100 Subject: [PATCH 081/248] handling other observer functions --- .../gui/isabelletranslation/ObserverFunctionHandler.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index 24222850603..c07c3eda71b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -28,10 +28,12 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); - if (!m.find()) { - throw new SMTTranslationException("Couldn't translate ObserverFunction: " + op.name().toString()); + String functionName; + if (m.find()) { + functionName = m.group(1); + } else { + functionName = op.name().toString().replace("::", "_"); } - String functionName = m.group(1); trans.addKnownSymbol(term, new StringBuilder(functionName)); } return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), trans.getKnownSymbol(term).toString()); From 4bddd78e5298d43af7a7a7f116132a5b76d9c330 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 22 Mar 2024 16:28:45 +0100 Subject: [PATCH 082/248] Seq handling improved --- .../DefinedSymbolsHandler.java | 1 + .../IsabelleTranslator.java | 7 +++- .../isabelletranslation/SeqDefHandler.java | 37 +++++++++++++++++++ .../UninterpretedSymbolsHandler.java | 3 ++ .../isabelletranslation/defaultHandlers.txt | 3 +- 5 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index f79f4de36ab..241b8f764f0 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -41,6 +41,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("seqRemove", "seqRemove"); definedFunctions.put("seqReverse", "seqReverse"); + //LocSet functions definedFunctions.put("elementOf", "elementOf"); definedFunctions.put("subset", "subset"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 03688da9ae3..143a819f98f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -182,7 +182,12 @@ public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormu result.append(LINE_ENDING).append("assumes antecedent_").append(i).append(":\"").append(antecedentFormula).append("\""); } result.append(LINE_ENDING); - result.append("shows \"").append(succedentTranslations.get(0)); + result.append("shows \""); + if (succedentTranslations.isEmpty()) { + result.append("False"); + } else { + result.append(succedentTranslations.get(0)); + } for (int i = 1; i < succedentTranslations.size(); i++) { StringBuilder succedentFormula = succedentTranslations.get(i); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java new file mode 100644 index 00000000000..c9a36253744 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java @@ -0,0 +1,37 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class SeqDefHandler implements IsabelleHandler { + + private final Map supportedOperators = new HashMap<>(); + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + supportedOperators.put(services.getTypeConverter().getSeqLDT().getSeqDef(), "SeqDef"); + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + Operator op = term.op(); + StringBuilder arg1 = trans.translate(term.sub(0)); + StringBuilder arg2 = trans.translate(term.sub(1)); + String arg3 = "(\\" + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". " + + " to_any (" + trans.translate(term.sub(2)) + "))"; + + return new StringBuilder("(seqDef ").append(arg1).append(arg2).append(arg3).append(")"); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index 2ff10644501..d024644477b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -6,6 +6,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.HeapLDT; import de.uka.ilkd.key.ldt.LocSetLDT; +import de.uka.ilkd.key.ldt.SeqLDT; import de.uka.ilkd.key.logic.Name; import de.uka.ilkd.key.logic.Namespace; import de.uka.ilkd.key.logic.Term; @@ -37,12 +38,14 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); + SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); Namespace sorts = services.getNamespaces().sorts(); masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object")), "java_lang_Object"); masterHandler.addPredefinedSort(sorts.lookup(new Name("Null")), "Null"); masterHandler.addPredefinedSort(heapLDT.targetSort(), "Heap"); masterHandler.addPredefinedSort(locSetLDT.targetSort(), "LocSet"); + masterHandler.addPredefinedSort(seqLDT.targetSort(), "Seq"); } @Override diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index 2546d6eb05d..8e9cd1be5bb 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -7,7 +7,8 @@ de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler de.uka.ilkd.key.gui.isabelletranslation.BSumHandler +de.uka.ilkd.key.gui.isabelletranslation.SeqDefHandler +de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.FieldHandler de.uka.ilkd.key.gui.isabelletranslation.ObserverFunctionHandler -de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From 233c48392a70474ec4e1a710bd4026ff945bfea6 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 25 Mar 2024 18:40:49 +0100 Subject: [PATCH 083/248] changed function signatures in preamble to match KeY --- .../UninterpretedSymbolsHandler.preamble.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 9fcb96377c6..77120ce63e6 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -228,15 +228,15 @@ consts setup_lifting type_definition_Seq lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". -lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". +lift_definition seqGet::"int\<Rightarrow>Seq\<Rightarrow>'a::any" is "\<lambda>i s. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". lift_definition seqEmpty::"Seq" is "[]". lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. -fun seqSub::"int\<Rightarrow>int\<Rightarrow>Seq\<Rightarrow>Seq" where - "seqSub i j s = seqDef i j (\<lambda>x. seqGet s x)" +fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where + "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where "listIndexOf [] a = undefined" | @@ -260,7 +260,7 @@ instance by standard end -fun instanceof::"javaDL_type\<Rightarrow>any\<Rightarrow>bool" +fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" where "instanceof x type = typeof type x" axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" From 47b0abd349811eb59f3980890c9a629c1ac6375c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 2 Apr 2024 15:17:15 +0200 Subject: [PATCH 084/248] parameter order fixes in functions --- .../UninterpretedSymbolsHandler.preamble.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 77120ce63e6..3dfd9c03557 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -236,7 +236,7 @@ lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where - "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" + "seqSub s i j = seqDef i j (\<lambda>x. seqGet x s)" primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where "listIndexOf [] a = undefined" | @@ -261,7 +261,7 @@ end fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" - where "instanceof x type = typeof type x" + where "instanceof x type = typeof x type" axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" @@ -292,7 +292,7 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 created)::bool)" and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select - h x created) \<and> instanceof (fieldType f) x)) \<Longrightarrow> wellFormed (store h obj f x)" + h x created) \<and> instanceof x (fieldType f))) \<Longrightarrow> wellFormed (store h obj f x)" and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> ov = null \<or> select h ov created)) \<Longrightarrow> wellFormed (store h obj f y)" and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> wellFormed h From 5b0d9a18e5f0699e9e93eacaea7b79678f3d9914 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 2 Apr 2024 16:01:42 +0200 Subject: [PATCH 085/248] further fixes --- .../UninterpretedSymbolsHandler.preamble.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 3dfd9c03557..2e6da7a37ac 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -228,7 +228,7 @@ consts setup_lifting type_definition_Seq lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". -lift_definition seqGet::"int\<Rightarrow>Seq\<Rightarrow>'a::any" is "\<lambda>i s. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". +lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". lift_definition seqEmpty::"Seq" is "[]". lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". @@ -236,7 +236,7 @@ lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where - "seqSub s i j = seqDef i j (\<lambda>x. seqGet x s)" + "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where "listIndexOf [] a = undefined" | From d10d8dae270370d34dabb550b86f55992428bee7 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 2 Apr 2024 22:24:45 +0200 Subject: [PATCH 086/248] removed div_nonzero --- .../key/gui/isabelletranslation/IntegerOpHandler.preamble.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml index ddad9487440..82b715b0682 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml @@ -13,9 +13,6 @@ else ((a div b) + 1))" fixes euclMod::"int\<Rightarrow>int\<Rightarrow>int" assumes eucl_Mod_def [simp]: "l\<noteq>0 \<Longrightarrow> euclMod k l = (if (k mod l < 0) then ((k mod l) + abs(l)) else (k mod l))" - -fixes div_nonzero::"int\<Rightarrow>int\<Rightarrow>int" -assumes div_nonzero_def [simp]: "b\<noteq>0 \<Longrightarrow> div_nonzero a b = a div b" begin definition int_HALFRANGE::int where [simp, intro]:"int_HALFRANGE=2^31" From 8c515d14e8996c55bd6bacfa983d7e99a4e9de53 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 8 Apr 2024 14:31:14 +0200 Subject: [PATCH 087/248] temp --- .../isabelletranslation/StringConverter.java | 37 +++++++++++ .../TranslationAction.java | 65 ++++++++++++++++++- 2 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java new file mode 100644 index 00000000000..6c81a5bd5d6 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java @@ -0,0 +1,37 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.mlvalue.MLValue; +import de.unruh.isabelle.mlvalue.StringConverter$; +import scala.concurrent.Future; +import scala.reflect.ScalaSignature; + +@ScalaSignature( + bytes = "\u0006\u0005};Q\u0001C\u0005\t\u0002I1Q\u0001F\u0005\t\u0002UAQAM\u0001\u0005\u0002MBQ\u0001N\u0001\u0005BUBQ\u0001S\u0001\u0005B%CQ\u0001V\u0001\u0005BUCQ\u0001W\u0001\u0005BeCQ\u0001X\u0001\u0005Bu\u000bqb\u0015;sS:<7i\u001c8wKJ$XM\u001d\u0006\u0003\u0015-\tq!\u001c7wC2,XM\u0003\u0002\r\u001b\u0005A\u0011n]1cK2dWM\u0003\u0002\u000f\u001f\u0005)QO\u001c:vQ*\t\u0001#\u0001\u0002eK\u000e\u0001\u0001CA\n\u0002\u001b\u0005I!aD*ue&twmQ8om\u0016\u0014H/\u001a:\u0014\u0005\u00051\u0002cA\f&Q9\u0011\u0001d\t\b\u00033\tr!AG\u0011\u000f\u0005m\u0001cB\u0001\u000f \u001b\u0005i\"B\u0001\u0010\u0012\u0003\u0019a$o\\8u}%\t\u0001#\u0003\u0002\u000f\u001f%\u0011A\"D\u0005\u0003\u0015-I!\u0001J\u0005\u0002\u000f5ce+\u00197vK&\u0011ae\n\u0002\n\u0007>tg/\u001a:uKJT!\u0001J\u0005\u0011\u0005%zcB\u0001\u0016.!\ta2FC\u0001-\u0003\u0015\u00198-\u00197b\u0013\tq3&\u0001\u0004Qe\u0016$WMZ\u0005\u0003aE\u0012aa\u0015;sS:<'B\u0001\u0018,\u0003\u0019a\u0014N\\5u}Q\t!#A\u0003ti>\u0014X\r\u0006\u00027\u0003R\u0011qG\u000f\t\u0004'aB\u0013BA\u001d\n\u0005\u001diEJV1mk\u0016DQ\u0001D\u0002A\u0004m\u0002\"\u0001P \u000e\u0003uR!AP\u0006\u0002\u000f\r|g\u000e\u001e:pY&\u0011\u0001)\u0010\u0002\t\u0013N\f'-\u001a7mK\")!i\u0001a\u0001Q\u0005)a/\u00197vK\"\u00121\u0001\u0012\t\u0003\u000b\u001ak\u0011aK\u0005\u0003\u000f.\u0012a!\u001b8mS:,\u0017\u0001\u0003:fiJLWM^3\u0015\u0005)\u0013FCA&R!\rau\nK\u0007\u0002\u001b*\u0011ajK\u0001\u000bG>t7-\u001e:sK:$\u0018B\u0001)N\u0005\u00191U\u000f^;sK\")A\u0002\u0002a\u0002w!)!\t\u0002a\u0001o!\u0012A\u0001R\u0001\u000bKbtGk\u001c,bYV,GC\u0001\u0015W\u0011\u0015aQ\u0001q\u0001 { + public String mlType(final Isabelle isabelle) { + return StringConverter$.MODULE$.mlType(isabelle); + } + + public String valueToExn(final Isabelle isabelle) { + return StringConverter$.MODULE$.valueToExn(isabelle); + } + + public String exnToValue(final Isabelle isabelle) { + return StringConverter$.MODULE$.exnToValue(isabelle); + } + + public Future retrieve(final MLValue value, final Isabelle isabelle) { + return StringConverter$.MODULE$.retrieve(value, isabelle); + } + + public MLValue store(final String value, final Isabelle isabelle) { + return StringConverter$.MODULE$.store(value, isabelle); + } +} \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 2cc51ad5e3e..7dae401ff83 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -5,8 +5,12 @@ import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.mlvalue.*; +import de.unruh.isabelle.pure.*; +import de.unruh.isabelle.pure.Implicits; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import scala.Tuple2; import scala.collection.immutable.Seq; import scala.collection.mutable.Builder; @@ -43,10 +47,67 @@ private void generateTranslation() { StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); //TODO find Isabelle path - Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); - + Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\nilsb\\Desktop\\Isabelle2023")); + Isabelle isabelle = new Isabelle(setup); //TODO automatically run try/sledgehammer instead of opening Isabelle List filePaths = new ArrayList<>(); + + + MLFunction2 getHeader = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, new StringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + TheoryHeader theoryHeader = getHeader.apply(translation.toString(), Position.none(isabelle), isabelle, new StringConverter(), Implicits.positionConverter()).retrieveNow(Implicits.theoryHeaderConverter(), isabelle); + MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + Theory thy0 = Theory.apply(translationFile.toPath(), isabelle); + MLFunction0 init_toplevel = MLValue.compileFunction0("Toplevel.init_toplevel", isabelle, Implicits.toplevelStateConverter()); + ToplevelState toplevel = init_toplevel.apply(isabelle).retrieveNow(Implicits.toplevelStateConverter(), isabelle); + + MLFunction2>> parse_text = MLValue.compileFunction( + """ + fn (thy, text) => let + | val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + | fun addtext symbols [tr] = + | [(tr, implode symbols)] + | | addtext _ [] = [] + | | addtext symbols (tr::nextTr::trs) = let + | val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + | in (tr, implode this) :: addtext rest (nextTr::trs) end + | in addtext (Symbol.explode text) transitions end + """, isabelle, Implicits.theoryConverter(), new StringConverter()); + + val command_exception = compileFunction[Boolean, Transition.T, ToplevelState, ToplevelState]( + "fn (int, tr, st) => Toplevel.command_exception int tr st") + + for ((transition, text) <- parse_text(thy0, theorySource.text).force.retrieveNow) { + println(s"""Transition: "${text.strip}"""") + toplevel = command_exception(true, transition, toplevel).retrieveNow.force + } + + // val finalThy = toplevel_end_theory(toplevel).retrieveNow.force + + val thy_for_sledgehammer = thy0 + val Sledgehammer: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer") + val Sledgehammer_Commands: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer_Commands") + val Sledgehammer_Prover: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer_Prover") + + val normal_with_Sledgehammer: MLFunction4[ToplevelState, Theory, List[String], List[String], (Boolean, (String, List[String]))] = + compileFunction[ToplevelState, Theory, List[String], List[String], (Boolean, (String, List[String]))]( + s""" fn (state, thy, adds, dels) => + | let + | val override = {add=[],del=[],only=false}; + | fun go_run (state, thy) = + | let + | val p_state = Toplevel.proof_of state; + | val ctxt = Proof.context_of p_state; + | val params = ${Sledgehammer_Commands}.default_params thy + | [("provers", "e"),("timeout","30"),("verbose","true")]; + | val results = ${Sledgehammer}.run_sledgehammer params ${Sledgehammer_Prover}.Normal NONE 1 override p_state; + | val (result, (outcome, step)) = results; + | in + | (result, (${Sledgehammer}.short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + | end; + | in + | Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end + |""".stripMargin + ) filePaths.add(translationFile.toPath()); From 388c6c428234b8112e5b43005c8908dba509aecb Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 11 Apr 2024 14:15:18 +0200 Subject: [PATCH 088/248] further temp --- .../isabelletranslation/BooleanConverter.java | 37 +++++++ .../TranslationAction.java | 104 ++++++++++-------- 2 files changed, 95 insertions(+), 46 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java new file mode 100644 index 00000000000..903780a2d03 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java @@ -0,0 +1,37 @@ +// +// Source code recreated from a .class file by IntelliJ IDEA +// (powered by FernFlower decompiler) +// + +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.mlvalue.BooleanConverter$; +import de.unruh.isabelle.mlvalue.MLValue; +import scala.concurrent.Future; +import scala.reflect.ScalaSignature; + +@ScalaSignature( + bytes = "\u0006\u0005\u0001dW-\u00198D_:4XM\u001d;feN\u0011\u0011A\u0006\t\u0004/\u0015BcB\u0001\r$\u001d\tI\"E\u0004\u0002\u001bC9\u00111\u0004\t\b\u00039}i\u0011!\b\u0006\u0003=E\ta\u0001\u0010:p_Rt\u0014\"\u0001\t\n\u00059y\u0011B\u0001\u0007\u000e\u0013\tQ1\"\u0003\u0002%\u0013\u00059Q\n\u0014,bYV,\u0017B\u0001\u0014(\u0005%\u0019uN\u001c4\u0016\r\\;f)\taE\u000b\u0005\u0002N#:\u0011aj\u0014\t\u00039)J!\u0001\u0015\u0016\u0002\rA\u0013X\rZ3g\u0013\t\u00116K\u0001\u0004TiJLgn\u001a\u0006\u0003!*BQ\u0001D\u0003A\u0004iB#!\u0002,\u0011\u0005%:\u0016B\u0001-+\u0005\u0019Ig\u000e\\5oK\u0006Qa/\u00197vKR{W\t\u001f8\u0015\u00051[\u0006\"\u0002\u0007\u0007\u0001\bQ\u0004F\u0001\u0004W\u0003\u0019iG\u000eV=qKR\u0011Aj\u0018\u0005\u0006\u0019\u001d\u0001\u001dA\u000f" +) +public final class BooleanConverter extends MLValue.Converter { + public String mlType(final Isabelle isabelle) { + return BooleanConverter$.MODULE$.mlType(isabelle); + } + + public String valueToExn(final Isabelle isabelle) { + return BooleanConverter$.MODULE$.valueToExn(isabelle); + } + + public String exnToValue(final Isabelle isabelle) { + return BooleanConverter$.MODULE$.exnToValue(isabelle); + } + + public MLValue store(final Object value, final Isabelle isabelle) { + return BooleanConverter$.MODULE$.store(value, isabelle); + } + + public Future retrieve(final MLValue value, final Isabelle isabelle) { + return BooleanConverter$.MODULE$.retrieve(value, isabelle); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 7dae401ff83..82db14ec76c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -6,8 +6,8 @@ import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.*; -import de.unruh.isabelle.pure.*; import de.unruh.isabelle.pure.Implicits; +import de.unruh.isabelle.pure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; @@ -47,13 +47,13 @@ private void generateTranslation() { StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); //TODO find Isabelle path - Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\nilsb\\Desktop\\Isabelle2023")); + Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); Isabelle isabelle = new Isabelle(setup); //TODO automatically run try/sledgehammer instead of opening Isabelle List filePaths = new ArrayList<>(); - MLFunction2 getHeader = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, new StringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + MLFunction2 getHeader = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, new StringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); TheoryHeader theoryHeader = getHeader.apply(translation.toString(), Position.none(isabelle), isabelle, new StringConverter(), Implicits.positionConverter()).retrieveNow(Implicits.theoryHeaderConverter(), isabelle); MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); Theory thy0 = Theory.apply(translationFile.toPath(), isabelle); @@ -62,52 +62,64 @@ private void generateTranslation() { MLFunction2>> parse_text = MLValue.compileFunction( """ - fn (thy, text) => let - | val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - | fun addtext symbols [tr] = - | [(tr, implode symbols)] - | | addtext _ [] = [] - | | addtext symbols (tr::nextTr::trs) = let - | val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - | in (tr, implode this) :: addtext rest (nextTr::trs) end - | in addtext (Symbol.explode text) transitions end - """, isabelle, Implicits.theoryConverter(), new StringConverter()); - - val command_exception = compileFunction[Boolean, Transition.T, ToplevelState, ToplevelState]( - "fn (int, tr, st) => Toplevel.command_exception int tr st") - - for ((transition, text) <- parse_text(thy0, theorySource.text).force.retrieveNow) { + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end + """, isabelle, Implicits.theoryConverter(), new StringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), new StringConverter()))); + + //MLFunction3 command_exception = MLValue.compileFunction( + // "fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, new BooleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + /*for ((transition, text) <- parse_text(thy0, theorySource.text).force.retrieveNow) { println(s"""Transition: "${text.strip}"""") toplevel = command_exception(true, transition, toplevel).retrieveNow.force - } + }*/ + + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); + String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); + String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); + + MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = + MLValue.compileFunction( + """ + fn (state, thy, adds, dels) => + let + val override = {add=[],del=[],only=false}; + fun go_run (state, thy) = + let + val p_state = Toplevel.proof_of state; + val ctxt = Proof.context_of p_state; + val params = """ + Sledgehammer_Commands + """ + .default_params thy + [("provers", "e"),("timeout","30"),("verbose","true")]; + val results = """ + + sledgehammer + """ + .run_sledgehammer params """ + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end + """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(new StringConverter()), + new ListConverter<>(new StringConverter()), + (new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter()))))); + + Builder> listBuilder = scala.collection.immutable.List.newBuilder(); + scala.collection.immutable.List list = listBuilder.result(); + var test = normal_with_Sledgehammer.apply(toplevel, thy0, list, list, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(new StringConverter()), + new ListConverter<>(new StringConverter())).retrieveNow((new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter())))), isabelle); - // val finalThy = toplevel_end_theory(toplevel).retrieveNow.force - - val thy_for_sledgehammer = thy0 - val Sledgehammer: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer") - val Sledgehammer_Commands: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer_Commands") - val Sledgehammer_Prover: String = thy_for_sledgehammer.importMLStructureNow("Sledgehammer_Prover") - - val normal_with_Sledgehammer: MLFunction4[ToplevelState, Theory, List[String], List[String], (Boolean, (String, List[String]))] = - compileFunction[ToplevelState, Theory, List[String], List[String], (Boolean, (String, List[String]))]( - s""" fn (state, thy, adds, dels) => - | let - | val override = {add=[],del=[],only=false}; - | fun go_run (state, thy) = - | let - | val p_state = Toplevel.proof_of state; - | val ctxt = Proof.context_of p_state; - | val params = ${Sledgehammer_Commands}.default_params thy - | [("provers", "e"),("timeout","30"),("verbose","true")]; - | val results = ${Sledgehammer}.run_sledgehammer params ${Sledgehammer_Prover}.Normal NONE 1 override p_state; - | val (result, (outcome, step)) = results; - | in - | (result, (${Sledgehammer}.short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - | end; - | in - | Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end - |""".stripMargin - ) filePaths.add(translationFile.toPath()); From 900db5e1fc04cdbcd5e75188e7df7c048064ec44 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 12 Apr 2024 19:54:40 +0200 Subject: [PATCH 089/248] Now calls sledgehammer and outputs result to command line --- .../IsabelleTranslator.java | 2 +- .../TranslationAction.java | 85 ++++++++++++------- 2 files changed, 55 insertions(+), 32 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 03688da9ae3..5f359880dd6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -192,7 +192,7 @@ public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormu result.append(LINE_ENDING).append(LINE_ENDING); result.append("(* Solve here *)").append(LINE_ENDING); - return result.append("end").append(LINE_ENDING).append("end"); + return result; } private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 82db14ec76c..2cb6e9d7ee1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -38,6 +38,20 @@ public void actionPerformed(ActionEvent e) { generateTranslation(); } + private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { + MLFunction3, Theory> begin_theory = + MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); + Path topDir = source.getParent(); + return begin_theory.apply(topDir, header, header.imports(isabelle).map((name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) + .retrieveNow(Implicits.theoryConverter(), isabelle); + } + private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); @@ -53,33 +67,36 @@ private void generateTranslation() { List filePaths = new ArrayList<>(); - MLFunction2 getHeader = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, new StringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - TheoryHeader theoryHeader = getHeader.apply(translation.toString(), Position.none(isabelle), isabelle, new StringConverter(), Implicits.positionConverter()).retrieveNow(Implicits.theoryHeaderConverter(), isabelle); - MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); - Theory thy0 = Theory.apply(translationFile.toPath(), isabelle); - MLFunction0 init_toplevel = MLValue.compileFunction0("Toplevel.init_toplevel", isabelle, Implicits.toplevelStateConverter()); - ToplevelState toplevel = init_toplevel.apply(isabelle).retrieveNow(Implicits.toplevelStateConverter(), isabelle); + Theory thy0 = beginTheory(translation.toString(), translationFile.toPath(), isabelle); + ToplevelState toplevel = ToplevelState.apply(isabelle); - MLFunction2>> parse_text = MLValue.compileFunction( - """ + MLFunction2>> parse_text = MLValue.compileFunction(""" fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end - """, isabelle, Implicits.theoryConverter(), new StringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), new StringConverter()))); - - //MLFunction3 command_exception = MLValue.compileFunction( - // "fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, new BooleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - - /*for ((transition, text) <- parse_text(thy0, theorySource.text).force.retrieveNow) { - println(s"""Transition: "${text.strip}"""") - toplevel = command_exception(true, transition, toplevel).retrieveNow.force - }*/ + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + + MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + List> transitionsAndTexts = new ArrayList<>(); + parse_text.apply(thy0, translation.toString(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) + .foreach(transitionsAndTexts::add); + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); @@ -95,12 +112,12 @@ fun go_run (state, thy) = let val p_state = Toplevel.proof_of state; val ctxt = Proof.context_of p_state; - val params = """ + Sledgehammer_Commands + """ + val params =\s""" + Sledgehammer_Commands + """ .default_params thy [("provers", "e"),("timeout","30"),("verbose","true")]; - val results = """ + val results =\s""" + sledgehammer + """ - .run_sledgehammer params """ + Sledgehammer_Prover + """ + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ .Normal NONE 1 override p_state; val (result, (outcome, step)) = results; in @@ -116,10 +133,16 @@ fun go_run (state, thy) = Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List list = listBuilder.result(); - var test = normal_with_Sledgehammer.apply(toplevel, thy0, list, list, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(new StringConverter()), - new ListConverter<>(new StringConverter())).retrieveNow((new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter())))), isabelle); + Boolean result; + try { + result = (Boolean) normal_with_Sledgehammer.apply(toplevel, thy0, list, list, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(new StringConverter()), + new ListConverter<>(new StringConverter())).retrieveNow((new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter())))), isabelle)._1(); + } catch (Exception exception) { + result = Boolean.FALSE; + } + LOGGER.info("Sledgehammer result: " + result); filePaths.add(translationFile.toPath()); From ce55e0b6f32d754998b904b8364e0ee451ebb005 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 13 Apr 2024 12:26:39 +0200 Subject: [PATCH 090/248] added type to lambda parameter --- .../uka/ilkd/key/gui/isabelletranslation/TranslationAction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 2cb6e9d7ee1..771ae8e9fb5 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -47,7 +47,7 @@ private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = source.getParent(); - return begin_theory.apply(topDir, header, header.imports(isabelle).map((name) -> Theory.apply(name, isabelle)), isabelle, + return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } From db3e478beae719ccb6ca48d9a75feb8be90f36c6 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 13 Apr 2024 12:32:40 +0200 Subject: [PATCH 091/248] removed unused converter stumps --- .../isabelletranslation/BooleanConverter.java | 37 ------------------- .../isabelletranslation/StringConverter.java | 37 ------------------- .../TranslationAction.java | 11 +++--- 3 files changed, 6 insertions(+), 79 deletions(-) delete mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java delete mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java deleted file mode 100644 index 903780a2d03..00000000000 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanConverter.java +++ /dev/null @@ -1,37 +0,0 @@ -// -// Source code recreated from a .class file by IntelliJ IDEA -// (powered by FernFlower decompiler) -// - -package de.uka.ilkd.key.gui.isabelletranslation; - -import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.mlvalue.BooleanConverter$; -import de.unruh.isabelle.mlvalue.MLValue; -import scala.concurrent.Future; -import scala.reflect.ScalaSignature; - -@ScalaSignature( - bytes = "\u0006\u0005\u0001dW-\u00198D_:4XM\u001d;feN\u0011\u0011A\u0006\t\u0004/\u0015BcB\u0001\r$\u001d\tI\"E\u0004\u0002\u001bC9\u00111\u0004\t\b\u00039}i\u0011!\b\u0006\u0003=E\ta\u0001\u0010:p_Rt\u0014\"\u0001\t\n\u00059y\u0011B\u0001\u0007\u000e\u0013\tQ1\"\u0003\u0002%\u0013\u00059Q\n\u0014,bYV,\u0017B\u0001\u0014(\u0005%\u0019uN\u001c4\u0016\r\\;f)\taE\u000b\u0005\u0002N#:\u0011aj\u0014\t\u00039)J!\u0001\u0015\u0016\u0002\rA\u0013X\rZ3g\u0013\t\u00116K\u0001\u0004TiJLgn\u001a\u0006\u0003!*BQ\u0001D\u0003A\u0004iB#!\u0002,\u0011\u0005%:\u0016B\u0001-+\u0005\u0019Ig\u000e\\5oK\u0006Qa/\u00197vKR{W\t\u001f8\u0015\u00051[\u0006\"\u0002\u0007\u0007\u0001\bQ\u0004F\u0001\u0004W\u0003\u0019iG\u000eV=qKR\u0011Aj\u0018\u0005\u0006\u0019\u001d\u0001\u001dA\u000f" -) -public final class BooleanConverter extends MLValue.Converter { - public String mlType(final Isabelle isabelle) { - return BooleanConverter$.MODULE$.mlType(isabelle); - } - - public String valueToExn(final Isabelle isabelle) { - return BooleanConverter$.MODULE$.valueToExn(isabelle); - } - - public String exnToValue(final Isabelle isabelle) { - return BooleanConverter$.MODULE$.exnToValue(isabelle); - } - - public MLValue store(final Object value, final Isabelle isabelle) { - return BooleanConverter$.MODULE$.store(value, isabelle); - } - - public Future retrieve(final MLValue value, final Isabelle isabelle) { - return BooleanConverter$.MODULE$.retrieve(value, isabelle); - } -} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java deleted file mode 100644 index 6c81a5bd5d6..00000000000 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/StringConverter.java +++ /dev/null @@ -1,37 +0,0 @@ -// -// Source code recreated from a .class file by IntelliJ IDEA -// (powered by FernFlower decompiler) -// - -package de.uka.ilkd.key.gui.isabelletranslation; - -import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.mlvalue.MLValue; -import de.unruh.isabelle.mlvalue.StringConverter$; -import scala.concurrent.Future; -import scala.reflect.ScalaSignature; - -@ScalaSignature( - bytes = "\u0006\u0005};Q\u0001C\u0005\t\u0002I1Q\u0001F\u0005\t\u0002UAQAM\u0001\u0005\u0002MBQ\u0001N\u0001\u0005BUBQ\u0001S\u0001\u0005B%CQ\u0001V\u0001\u0005BUCQ\u0001W\u0001\u0005BeCQ\u0001X\u0001\u0005Bu\u000bqb\u0015;sS:<7i\u001c8wKJ$XM\u001d\u0006\u0003\u0015-\tq!\u001c7wC2,XM\u0003\u0002\r\u001b\u0005A\u0011n]1cK2dWM\u0003\u0002\u000f\u001f\u0005)QO\u001c:vQ*\t\u0001#\u0001\u0002eK\u000e\u0001\u0001CA\n\u0002\u001b\u0005I!aD*ue&twmQ8om\u0016\u0014H/\u001a:\u0014\u0005\u00051\u0002cA\f&Q9\u0011\u0001d\t\b\u00033\tr!AG\u0011\u000f\u0005m\u0001cB\u0001\u000f \u001b\u0005i\"B\u0001\u0010\u0012\u0003\u0019a$o\\8u}%\t\u0001#\u0003\u0002\u000f\u001f%\u0011A\"D\u0005\u0003\u0015-I!\u0001J\u0005\u0002\u000f5ce+\u00197vK&\u0011ae\n\u0002\n\u0007>tg/\u001a:uKJT!\u0001J\u0005\u0011\u0005%zcB\u0001\u0016.!\ta2FC\u0001-\u0003\u0015\u00198-\u00197b\u0013\tq3&\u0001\u0004Qe\u0016$WMZ\u0005\u0003aE\u0012aa\u0015;sS:<'B\u0001\u0018,\u0003\u0019a\u0014N\\5u}Q\t!#A\u0003ti>\u0014X\r\u0006\u00027\u0003R\u0011qG\u000f\t\u0004'aB\u0013BA\u001d\n\u0005\u001diEJV1mk\u0016DQ\u0001D\u0002A\u0004m\u0002\"\u0001P \u000e\u0003uR!AP\u0006\u0002\u000f\r|g\u000e\u001e:pY&\u0011\u0001)\u0010\u0002\t\u0013N\f'-\u001a7mK\")!i\u0001a\u0001Q\u0005)a/\u00197vK\"\u00121\u0001\u0012\t\u0003\u000b\u001ak\u0011aK\u0005\u0003\u000f.\u0012a!\u001b8mS:,\u0017\u0001\u0003:fiJLWM^3\u0015\u0005)\u0013FCA&R!\rau\nK\u0007\u0002\u001b*\u0011ajK\u0001\u000bG>t7-\u001e:sK:$\u0018B\u0001)N\u0005\u00191U\u000f^;sK\")A\u0002\u0002a\u0002w!)!\t\u0002a\u0001o!\u0012A\u0001R\u0001\u000bKbtGk\u001c,bYV,GC\u0001\u0015W\u0011\u0015aQ\u0001q\u0001 { - public String mlType(final Isabelle isabelle) { - return StringConverter$.MODULE$.mlType(isabelle); - } - - public String valueToExn(final Isabelle isabelle) { - return StringConverter$.MODULE$.valueToExn(isabelle); - } - - public String exnToValue(final Isabelle isabelle) { - return StringConverter$.MODULE$.exnToValue(isabelle); - } - - public Future retrieve(final MLValue value, final Isabelle isabelle) { - return StringConverter$.MODULE$.retrieve(value, isabelle); - } - - public MLValue store(final String value, final Isabelle isabelle) { - return StringConverter$.MODULE$.store(value, isabelle); - } -} \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 771ae8e9fb5..9235375d9e2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -127,9 +127,9 @@ fun go_run (state, thy) = in Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(new StringConverter()), - new ListConverter<>(new StringConverter()), - (new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter()))))); + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List list = listBuilder.result(); @@ -137,8 +137,9 @@ fun go_run (state, thy) = Boolean result; try { result = (Boolean) normal_with_Sledgehammer.apply(toplevel, thy0, list, list, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(new StringConverter()), - new ListConverter<>(new StringConverter())).retrieveNow((new Tuple2Converter<>(new BooleanConverter(), new Tuple2Converter<>(new StringConverter(), new ListConverter<>(new StringConverter())))), isabelle)._1(); + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) + .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)._1(); } catch (Exception exception) { result = Boolean.FALSE; } From 4a4266727e7d090a7a494411bbf046d939b82833 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 13 Apr 2024 20:08:33 +0200 Subject: [PATCH 092/248] auto closes selected goal if proven by sledgehammer --- .../TranslationAction.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 9235375d9e2..04a6c39630b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -3,6 +3,8 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.uka.ilkd.key.rule.IBuiltInRuleApp; +import de.uka.ilkd.key.smt.SMTRuleApp; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.*; @@ -11,7 +13,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; -import scala.collection.immutable.Seq; import scala.collection.mutable.Builder; import java.awt.event.ActionEvent; @@ -132,18 +133,27 @@ fun go_run (state, thy) = (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); Builder> listBuilder = scala.collection.immutable.List.newBuilder(); - scala.collection.immutable.List list = listBuilder.result(); + scala.collection.immutable.List emptyList = listBuilder.result(); - Boolean result; + Tuple2>> result; + LOGGER.info("Sledgehammering..."); try { - result = (Boolean) normal_with_Sledgehammer.apply(toplevel, thy0, list, list, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + result = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) - .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)._1(); + .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); } catch (Exception exception) { - result = Boolean.FALSE; + result = new Tuple2<>(Boolean.FALSE, new Tuple2<>("", emptyList)); } LOGGER.info("Sledgehammer result: " + result); + + //TODO needs its own action to enable undo, etc. and naming reworks + if ((Boolean) result._1()) { + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result._2()._2().head()); + app.tryToInstantiate(mediator.getSelectedGoal()); + mediator.getSelectedGoal().apply(app); + } + filePaths.add(translationFile.toPath()); @@ -155,7 +165,7 @@ fun go_run (state, thy) = //TODO handle exception throw new RuntimeException(e); } - + /* Builder> builder = Seq.newBuilder(); for (Path path : filePaths) { builder.addOne(path); @@ -166,7 +176,7 @@ fun go_run (state, thy) = //TODO improve concurrency? Thread isabelleJEdit = new Thread(() -> Isabelle.jedit(setup, pathSeq)); - isabelleJEdit.start(); + isabelleJEdit.start();*/ } catch (IllegalFormulaException e) { //TODO output alert to user throw new RuntimeException(e); From 4a5d8899f7681251e45213c7c756f2ef50934504 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 13 Apr 2024 20:33:36 +0200 Subject: [PATCH 093/248] added all default provers to sledgehammer --- .../uka/ilkd/key/gui/isabelletranslation/TranslationAction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 04a6c39630b..942156f572f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -115,7 +115,7 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("provers", "e"),("timeout","30"),("verbose","true")]; + [("timeout","30"),("verbose","true")]; val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ From 493603dfd8f0e8f48e360b6138ce950742db0691 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 00:24:07 +0200 Subject: [PATCH 094/248] added settings to change save file path and isabelle path --- .../IsabelleTranslationExtension.java | 8 +- .../IsabelleTranslationSettings.java | 106 ++++++++++++++++++ .../TranslationAction.java | 24 ++-- .../TranslationOptionsPanel.java | 32 ------ 4 files changed, 128 insertions(+), 42 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java delete mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index d9985e38462..557989ed166 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -5,13 +5,19 @@ import de.uka.ilkd.key.gui.extension.api.ContextMenuAdapter; import de.uka.ilkd.key.gui.extension.api.ContextMenuKind; import de.uka.ilkd.key.gui.extension.api.KeYGuiExtension; +import de.uka.ilkd.key.gui.settings.SettingsDialog; import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.pp.PosInSequent; +import de.uka.ilkd.key.settings.Configuration; +import de.uka.ilkd.key.util.properties.Properties; import org.jspecify.annotations.NonNull; import javax.swing.*; +import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Objects; @KeYGuiExtension.Info(name = "Translation", optional = true, experimental = true) @@ -19,7 +25,7 @@ public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExte @Override public SettingsProvider getSettings() { - return new TranslationOptionsPanel(); + return new IsabelleSettingsProvider(); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java new file mode 100644 index 00000000000..ba75443a646 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -0,0 +1,106 @@ +/* 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.gui.isabelletranslation; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Path; +import java.util.Properties; + +import de.uka.ilkd.key.settings.AbstractSettings; +import de.uka.ilkd.key.settings.Configuration; +import de.uka.ilkd.key.settings.PathConfig; + +import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IsabelleTranslationSettings extends AbstractSettings { + protected static final File SETTINGS_FILE_NEW = + new File(PathConfig.getKeyConfigDir(), "isabelleSettings.json"); + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationSettings.class); + private static IsabelleTranslationSettings INSTANCE; + + private static final String isabellePathKey = "Path"; + private static final String translationPathKey = "TranslationPath"; + private Path isabellePath; + private Path translationPath; + private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); + private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "isabelleTranslations"); + + private static Configuration getDefaultConfig() { + Configuration config = new Configuration(); + config.set(isabellePathKey, DEFAULT_ISABELLE_PATH); + config.set(translationPathKey, DEFAULT_TRANSLATION_PATH); + return config; + } + + private IsabelleTranslationSettings(Configuration load) { + readSettings(load); + Runtime.getRuntime().addShutdownHook(new Thread(this::save)); + } + + public Path getIsabellePath() { + return isabellePath; + } + + public Path getTranslationPath() { + return translationPath; + } + + + public static IsabelleTranslationSettings getInstance() { + if (INSTANCE == null) { + if (SETTINGS_FILE_NEW.exists()) { + try { + LOGGER.info("Use new configuration format at {}", SETTINGS_FILE_NEW); + return INSTANCE = new IsabelleTranslationSettings(Configuration.load(SETTINGS_FILE_NEW)); + } catch (IOException e) { + LOGGER.error("Could not read {}", SETTINGS_FILE_NEW, e); + } + } + LOGGER.info("Resorting to default Isabelle settings"); + return INSTANCE = new IsabelleTranslationSettings(getDefaultConfig()); + } + return INSTANCE; + } + + public void save() { + LOGGER.info("Save Isabelle settings to: " + SETTINGS_FILE_NEW.getAbsolutePath()); + try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { + var config = new Configuration(); + writeSettings(config); + config.save(writer, "Isabelle settings"); + writer.flush(); + } catch (IOException ex) { + LOGGER.error("Failed to save Isabelle settings", ex); + } + } + + @Override + public void readSettings(Properties props) { + isabellePath = Path.of(props.getProperty(isabellePathKey)); + translationPath = Path.of(props.getProperty(translationPathKey)); + } + + @Override + public void writeSettings(Properties props) { + props.setProperty(isabellePathKey, isabellePath.toString()); + props.setProperty(translationPathKey, translationPath.toString()); + } + + @Override + public void readSettings(@NonNull Configuration props) { + isabellePath = Path.of(props.get(isabellePathKey, DEFAULT_ISABELLE_PATH.toString())); + translationPath = Path.of(props.get(translationPathKey, DEFAULT_TRANSLATION_PATH.toString())); + } + + @Override + public void writeSettings(@NonNull Configuration props) { + props.set(isabellePathKey, isabellePath.toString()); + props.set(translationPathKey, translationPath.toString()); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 942156f572f..9c6f1edad75 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -26,15 +26,17 @@ public class TranslationAction extends MainWindowAction { private static final Logger LOGGER = LoggerFactory.getLogger(TranslationAction.class); + private final Path isabelle_path; public TranslationAction(MainWindow mainWindow) { super(mainWindow); setName("Translate to Isabelle"); + this.isabelle_path = IsabelleTranslationSettings.getInstance().getIsabellePath(); } @Override public void actionPerformed(ActionEvent e) { - LOGGER.info("Translation Action"); + LOGGER.info("Translating..."); generateTranslation(); } @@ -57,16 +59,17 @@ private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); try { - //TODO let user choose where to save file? - File translationFile = new File(System.getProperty("user.home") + "/.key/IsabelleTranslations/Translation.thy"); + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "Translation.thy"); StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); - //TODO find Isabelle path - Isabelle.Setup setup = JIsabelle.setup(Path.of("C:\\Users\\Nils\\Documents\\Isabelle2023")); - Isabelle isabelle = new Isabelle(setup); - //TODO automatically run try/sledgehammer instead of opening Isabelle - List filePaths = new ArrayList<>(); - + Isabelle isabelle; + try { + Isabelle.Setup setup = JIsabelle.setup(isabelle_path); + isabelle = new Isabelle(setup); + } catch (Exception e) { + LOGGER.error("Can't find Isabelle at {}", isabelle_path); + return; + } Theory thy0 = beginTheory(translation.toString(), translationFile.toPath(), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); @@ -86,6 +89,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + LOGGER.info("Parsing theory..."); List> transitionsAndTexts = new ArrayList<>(); parse_text.apply(thy0, translation.toString(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) @@ -98,6 +102,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) .retrieveNow(Implicits.toplevelStateConverter(), isabelle); } + LOGGER.info("Finished Parsing"); String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); @@ -154,6 +159,7 @@ fun go_run (state, thy) = mediator.getSelectedGoal().apply(app); } + List filePaths = new ArrayList<>(); filePaths.add(translationFile.toPath()); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java deleted file mode 100644 index 83f397df94e..00000000000 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationOptionsPanel.java +++ /dev/null @@ -1,32 +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.gui.isabelletranslation; - -import de.uka.ilkd.key.gui.MainWindow; -import de.uka.ilkd.key.gui.settings.SettingsPanel; -import de.uka.ilkd.key.gui.settings.SettingsProvider; - -import javax.swing.*; - -public class TranslationOptionsPanel extends SettingsPanel implements SettingsProvider { - private static final long serialVersionUID = -2170118134719823425L; - - public TranslationOptionsPanel() { - setHeaderText(getDescription()); - } - - @Override - public String getDescription() { - return "Translate"; - } - - @Override - public JPanel getPanel(MainWindow window) { - return this; - } - - @Override - public void applySettings(MainWindow window) { - } -} From 9a679e13409cf32da600dd3d0e561acff445039b Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 00:30:31 +0200 Subject: [PATCH 095/248] better default path handling --- .../isabelletranslation/IsabelleTranslationSettings.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index ba75443a646..89cde1b30d9 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -94,8 +94,12 @@ public void writeSettings(Properties props) { @Override public void readSettings(@NonNull Configuration props) { - isabellePath = Path.of(props.get(isabellePathKey, DEFAULT_ISABELLE_PATH.toString())); - translationPath = Path.of(props.get(translationPathKey, DEFAULT_TRANSLATION_PATH.toString())); + if (INSTANCE == null) { + isabellePath = DEFAULT_ISABELLE_PATH; + translationPath = DEFAULT_TRANSLATION_PATH; + } + isabellePath = Path.of(props.get(isabellePathKey, isabellePath.toString())); + translationPath = Path.of(props.get(translationPathKey, translationPath.toString())); } @Override From 2d10f4b5d64877f10cfcc0b8674f806f7a78febf Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 00:45:58 +0200 Subject: [PATCH 096/248] added GUI settings --- .../IsabelleSettingsProvider.java | 64 +++++++++++++++++++ .../IsabelleTranslationSettings.java | 4 +- 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java new file mode 100644 index 00000000000..859368cf969 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java @@ -0,0 +1,64 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.settings.InvalidSettingsInputException; +import de.uka.ilkd.key.gui.settings.SettingsProvider; +import de.uka.ilkd.key.gui.settings.SettingsPanel; +import de.uka.ilkd.key.settings.Configuration; + +import javax.swing.*; + +public class IsabelleSettingsProvider extends SettingsPanel implements SettingsProvider { + private static final String infoTranslationPathPanel = + """ + Choose where the isabelle translation files are stored. + """; + private static final String infoIsabellePathPanel = + """ + Specify the absolute path of the Isabelle folder. + """; + + private final JTextField translationPathPanel; + private final JTextField isabellePathPanel; + + public IsabelleSettingsProvider() { + super(); + setHeaderText(getDescription()); + setSubHeaderText( + "Isabelle settings are stored in: " + IsabelleTranslationSettings.SETTINGS_FILE_NEW.getAbsolutePath()); + translationPathPanel = createTranslationPathPanel(); + isabellePathPanel = createIsabellePathPanel(); + } + + @Override + public String getDescription() { + return "Settings for Isabelle translation"; + } + + @Override + public JPanel getPanel(MainWindow window) { + isabellePathPanel.setText(IsabelleTranslationSettings.getInstance().getIsabellePath().toString()); + translationPathPanel.setText(IsabelleTranslationSettings.getInstance().getTranslationPath().toString()); + return this; + } + + protected JTextField createTranslationPathPanel() { + return addFileChooserPanel("Store translation to file:", "", infoTranslationPathPanel, + true, e -> { + }); + } + + protected JTextField createIsabellePathPanel() { + return addFileChooserPanel("Isabelle folder:", "", infoIsabellePathPanel, + true, e -> { + }); + } + + @Override + public void applySettings(MainWindow window) throws InvalidSettingsInputException { + Configuration newConfig = new Configuration(); + newConfig.set(IsabelleTranslationSettings.translationPathKey, translationPathPanel.getText()); + newConfig.set(IsabelleTranslationSettings.isabellePathKey, isabellePathPanel.getText()); + IsabelleTranslationSettings.getInstance().readSettings(newConfig); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index 89cde1b30d9..0cd94d9167f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -24,8 +24,8 @@ public class IsabelleTranslationSettings extends AbstractSettings { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationSettings.class); private static IsabelleTranslationSettings INSTANCE; - private static final String isabellePathKey = "Path"; - private static final String translationPathKey = "TranslationPath"; + protected static final String isabellePathKey = "Path"; + protected static final String translationPathKey = "TranslationPath"; private Path isabellePath; private Path translationPath; private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); From 5911edad0ed92d83eedd4ec2a796f0b80f2ae2f7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 00:49:11 +0200 Subject: [PATCH 097/248] fixed file store location --- .../gui/isabelletranslation/TranslationAction.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 9c6f1edad75..49803a929f0 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -59,7 +59,7 @@ private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); try { - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "Translation.thy"); + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); Isabelle isabelle; @@ -71,6 +71,7 @@ private void generateTranslation() { return; } + LOGGER.info("Parsing theory..."); Theory thy0 = beginTheory(translation.toString(), translationFile.toPath(), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); @@ -89,7 +90,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - LOGGER.info("Parsing theory..."); + List> transitionsAndTexts = new ArrayList<>(); parse_text.apply(thy0, translation.toString(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) @@ -159,8 +160,7 @@ fun go_run (state, thy) = mediator.getSelectedGoal().apply(app); } - List filePaths = new ArrayList<>(); - filePaths.add(translationFile.toPath()); + try { @@ -172,6 +172,9 @@ fun go_run (state, thy) = throw new RuntimeException(e); } /* + List filePaths = new ArrayList<>(); + filePaths.add(translationFile.toPath()); + Builder> builder = Seq.newBuilder(); for (Path path : filePaths) { builder.addOne(path); From 13391856f7f887b8be9089818b6ed220a6fb0297 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 00:56:36 +0200 Subject: [PATCH 098/248] now destroys isabelle resources --- .../ilkd/key/gui/isabelletranslation/TranslationAction.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 49803a929f0..730a0c0d4ad 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -62,6 +62,7 @@ private void generateTranslation() { File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); + LOGGER.info("Starting isabelle..."); Isabelle isabelle; try { Isabelle.Setup setup = JIsabelle.setup(isabelle_path); @@ -72,6 +73,7 @@ private void generateTranslation() { } LOGGER.info("Parsing theory..."); + Theory thy0 = beginTheory(translation.toString(), translationFile.toPath(), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); @@ -151,6 +153,8 @@ fun go_run (state, thy) = } catch (Exception exception) { result = new Tuple2<>(Boolean.FALSE, new Tuple2<>("", emptyList)); } + isabelle.destroy(); + LOGGER.info("Sledgehammer result: " + result); //TODO needs its own action to enable undo, etc. and naming reworks From a727966e83e9e660614aae34087c0ce8caa62205 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 15 Apr 2024 18:09:25 +0200 Subject: [PATCH 099/248] splitting into preamble and sequent --- .../isabelletranslation/IsabelleProblem.java | 161 ++++++++++++++++++ .../IsabelleTranslationSettings.java | 3 +- .../IsabelleTranslator.java | 126 +++++++------- .../SledgehammerResult.java | 14 ++ .../TranslationAction.java | 128 ++------------ 5 files changed, 252 insertions(+), 180 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java new file mode 100644 index 00000000000..45becb8f20e --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -0,0 +1,161 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.proof.Goal; +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.mlvalue.*; +import de.unruh.isabelle.pure.*; +import de.unruh.isabelle.pure.Implicits; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import scala.Tuple2; +import scala.collection.immutable.List; +import scala.collection.mutable.Builder; + +import java.nio.file.Path; +import java.util.ArrayList; + +public class IsabelleProblem { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); + private final Goal goal; + private SledgehammerResult result = null; + private final String preamble; + private final String sequentTranslation; + + public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { + this.goal = goal; + this.preamble = preamble; + this.sequentTranslation = sequentTranslation; + } + + public Goal getGoal() { + return goal; + } + + public String getSequentTranslation() { + return sequentTranslation; + } + + public String getPreamble() { + return preamble; + } + + public SledgehammerResult getResult() { + return result; + } + + public SledgehammerResult sledgehammer() { + LOGGER.info("Starting isabelle..."); + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); + + Isabelle isabelle; + try { + Isabelle.Setup setup = JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), JIsabelle.setup(settings.getIsabellePath())); + isabelle = new Isabelle(setup); + } catch (Exception e) { + LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); + return null; + } + + LOGGER.info("Parsing theory..."); + + Theory thy0 = beginTheory(getSequentTranslation(), Path.of((settings.getTranslationPath() + "\\Translation.thy")), isabelle); + ToplevelState toplevel = ToplevelState.apply(isabelle); + + MLFunction2>> parse_text = MLValue.compileFunction(""" + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + + MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + + java.util.List> transitionsAndTexts = new ArrayList<>(); + parse_text.apply(thy0, getSequentTranslation(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) + .foreach(transitionsAndTexts::add); + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } + LOGGER.info("Finished Parsing"); + + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); + String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); + String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); + + MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = + MLValue.compileFunction( + """ + fn (state, thy, adds, dels) => + let + val override = {add=[],del=[],only=false}; + fun go_run (state, thy) = + let + val p_state = Toplevel.proof_of state; + val ctxt = Proof.context_of p_state; + val params =\s""" + Sledgehammer_Commands + """ + .default_params thy + [("timeout","30"),("verbose","true")]; + val results =\s""" + + sledgehammer + """ + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end + """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); + + Builder> listBuilder = scala.collection.immutable.List.newBuilder(); + scala.collection.immutable.List emptyList = listBuilder.result(); + + SledgehammerResult result; + LOGGER.info("Sledgehammering..."); + try { + result = new SledgehammerResult(normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) + .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)); + } catch (Exception exception) { + result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>("", emptyList))); + } + isabelle.destroy(); + + LOGGER.info("Sledgehammer result: " + result); + return this.result = result; + } + + private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { + MLFunction3, Theory> begin_theory = + MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + + TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); + Path topDir = source.getParent(); + return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) + .retrieveNow(Implicits.theoryConverter(), isabelle); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index 0cd94d9167f..3d6dde81d69 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -59,7 +59,8 @@ public static IsabelleTranslationSettings getInstance() { LOGGER.info("Use new configuration format at {}", SETTINGS_FILE_NEW); return INSTANCE = new IsabelleTranslationSettings(Configuration.load(SETTINGS_FILE_NEW)); } catch (IOException e) { - LOGGER.error("Could not read {}", SETTINGS_FILE_NEW, e); + LOGGER.error("Could not read {}, resorting to default", SETTINGS_FILE_NEW, e); + return INSTANCE = new IsabelleTranslationSettings(getDefaultConfig()); } } LOGGER.info("Resorting to default Isabelle settings"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index d0121979594..3d17733bf8b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -6,6 +6,7 @@ import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.sort.ArraySort; import de.uka.ilkd.key.logic.sort.Sort; +import de.uka.ilkd.key.proof.Goal; import java.io.IOException; import java.util.*; @@ -20,7 +21,8 @@ public IsabelleTranslator(Services services) { this.services = services; } - public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormulaException { + public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaException { + Sequent sequent = goal.sequent(); List antecedents = sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); List succedents = sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); IsabelleMasterHandler masterHandler; @@ -41,11 +43,11 @@ public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormu throw new RuntimeException(message.toString()); } - StringBuilder result = new StringBuilder(); - result.append("theory Translation imports Main begin").append(LINE_ENDING); + StringBuilder translationPreamble = new StringBuilder(); + translationPreamble.append("theory TranslationPreamble imports Main begin").append(LINE_ENDING); for (StringBuilder preamble : masterHandler.getPreambles()) { - result.append(LINE_ENDING).append(preamble).append(LINE_ENDING); + translationPreamble.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } Sort nullSort = services.getNamespaces().sorts().lookup("Null"); @@ -55,42 +57,42 @@ public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormu String sortName = masterHandler.translateSortName(sort); String UNIV = sortName + "_UNIV"; - result.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); - result.append("lemma ex_").append(UNIV).append(":"); - result.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); - result.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); + translationPreamble.append("lemma ex_").append(UNIV).append(":"); + translationPreamble.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); + translationPreamble.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); - result.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); - result.append(LINE_ENDING); + translationPreamble.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); + translationPreamble.append(LINE_ENDING); - result.append("specification (").append(UNIV).append(") "); - result.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - result.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); - result.append(LINE_ENDING); + translationPreamble.append("specification (").append(UNIV).append(") "); + translationPreamble.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + translationPreamble.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); + translationPreamble.append(LINE_ENDING); String UNIV_spec_lemma_name = UNIV + "_specification"; - result.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - result.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); - result.append(LINE_ENDING); + translationPreamble.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + translationPreamble.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); + translationPreamble.append(LINE_ENDING); - result.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); + translationPreamble.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); String repName = sortName + "2any"; String absName = "any2" + sortName; - result.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); - result.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); + translationPreamble.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); - result.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; - result.append("lemma ").append(sortName).append("_type_specification[simp]:") + translationPreamble.append("lemma ").append(sortName).append("_type_specification[simp]:") .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) .append(LINE_ENDING); - result.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); - result.append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); + translationPreamble.append(LINE_ENDING).append(LINE_ENDING); for (Sort parentSort : sortParentsMap.get(sort)) { if (parentSort == Sort.ANY) { @@ -98,106 +100,106 @@ public final StringBuilder translateProblem(Sequent sequent) throws IllegalFormu } String parentSortName = masterHandler.translateSortName(parentSort); String parentSortInj = sortName + "2" + parentSortName; - result.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) + translationPreamble.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); - result.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); } - result.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); - result.append("begin").append(LINE_ENDING); + translationPreamble.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); + translationPreamble.append("begin").append(LINE_ENDING); String to_any_fun_Name = "to_any_" + sortName; - result.append("fun ").append(to_any_fun_Name) + translationPreamble.append("fun ").append(to_any_fun_Name) .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") .append(LINE_ENDING); String cast_fun_Name = "cast_" + sortName; - result.append("fun ").append(cast_fun_Name) + translationPreamble.append("fun ").append(cast_fun_Name) .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") .append(LINE_ENDING); - result.append("instance by standard").append(LINE_ENDING); - result.append("end").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("instance by standard").append(LINE_ENDING); + translationPreamble.append("end").append(LINE_ENDING).append(LINE_ENDING); if (nullSort.extendsTrans(sort)) { String null_to_sort_name = "Null2" + sortName; - result.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) + translationPreamble.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); - result.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); } if (sort instanceof ArraySort) { - result.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); - result.append("begin").append(LINE_ENDING); + translationPreamble.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); + translationPreamble.append("begin").append(LINE_ENDING); String element_type_name = "element_type_" + sortName; String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; - result.append("fun ").append(element_type_name) + translationPreamble.append("fun ").append(element_type_name) .append(" where \"").append(element_type_name) .append(" (x::").append(sortName).append(")").append(" = ") .append(elementSortType).append("\"") .append(LINE_ENDING); - result.append("instance by standard").append(LINE_ENDING); - result.append("end").append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append("instance by standard").append(LINE_ENDING); + translationPreamble.append("end").append(LINE_ENDING).append(LINE_ENDING); } String typeConstName = sortName + "_type"; - result.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); + translationPreamble.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); - result.append(LINE_ENDING).append(LINE_ENDING); + translationPreamble.append(LINE_ENDING).append(LINE_ENDING); } + translationPreamble.append("end"); - result.append("locale varsAndFunctions"); + StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main TranslationPreamble begin").append(LINE_ENDING); + sequentTranslation.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); boolean locale_empty = true; if (!locales.isEmpty()) { - result.append(" = "); - result.append(locales.remove(0)); + sequentTranslation.append(" = "); + sequentTranslation.append(locales.remove(0)); locale_empty = false; } for (StringBuilder locale : locales) { - result.append(" + ").append(locale); + sequentTranslation.append(" + ").append(locale); } List constDecls = masterHandler.getConstDeclarations(); if (!constDecls.isEmpty() && locale_empty) { - result.append(" = "); - result.append(locales.remove(0)); + sequentTranslation.append(" = "); + sequentTranslation.append(locales.remove(0)); locale_empty = false; } else if (!locale_empty) { - result.append(" + ").append(LINE_ENDING); + sequentTranslation.append(" + ").append(LINE_ENDING); } for (StringBuilder constDecl : constDecls) { - result.append(LINE_ENDING).append(constDecl); + sequentTranslation.append(LINE_ENDING).append(constDecl); } - result.append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); - result.append("begin").append(LINE_ENDING); + sequentTranslation.append("begin").append(LINE_ENDING); - result.append("theorem solve: "); + sequentTranslation.append("theorem solve: "); for (int i = 0; i < antecedentTranslations.size(); i++) { StringBuilder antecedentFormula = antecedentTranslations.get(i); - result.append(LINE_ENDING).append("assumes antecedent_").append(i).append(":\"").append(antecedentFormula).append("\""); + sequentTranslation.append(LINE_ENDING).append("assumes antecedent_").append(i).append(":\"").append(antecedentFormula).append("\""); } - result.append(LINE_ENDING); - result.append("shows \""); + sequentTranslation.append(LINE_ENDING); + sequentTranslation.append("shows \""); if (succedentTranslations.isEmpty()) { - result.append("False"); + sequentTranslation.append("False"); } else { - result.append(succedentTranslations.get(0)); + sequentTranslation.append(succedentTranslations.get(0)); } for (int i = 1; i < succedentTranslations.size(); i++) { StringBuilder succedentFormula = succedentTranslations.get(i); - result.append(LINE_ENDING).append("\\").append(succedentFormula); + sequentTranslation.append(LINE_ENDING).append("\\").append(succedentFormula); } - result.append("\""); - result.append(LINE_ENDING).append(LINE_ENDING); - result.append("(* Solve here *)").append(LINE_ENDING); + sequentTranslation.append("\""); - return result; + return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java new file mode 100644 index 00000000000..6ba5c4c7def --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java @@ -0,0 +1,14 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import scala.Tuple2; +import scala.collection.immutable.List; + +public record SledgehammerResult(Tuple2>> result) { + public Boolean isSuccessful() { + return (Boolean) result._1(); + } + + public Tuple2> getTactic() { + return result._2(); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 730a0c0d4ad..f067b6d6a5f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -26,12 +26,10 @@ public class TranslationAction extends MainWindowAction { private static final Logger LOGGER = LoggerFactory.getLogger(TranslationAction.class); - private final Path isabelle_path; public TranslationAction(MainWindow mainWindow) { super(mainWindow); setName("Translate to Isabelle"); - this.isabelle_path = IsabelleTranslationSettings.getInstance().getIsabellePath(); } @Override @@ -41,140 +39,36 @@ public void actionPerformed(ActionEvent e) { generateTranslation(); } - private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { - MLFunction3, Theory> begin_theory = - MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); - MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) - .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); - Path topDir = source.getParent(); - return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) - .retrieveNow(Implicits.theoryConverter(), isabelle); - } private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); try { File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); - StringBuilder translation = translator.translateProblem(mediator.getSelectedGoal().sequent()); + File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\TranslationPreamble.thy"); + IsabelleProblem translation = translator.translateProblem(mediator.getSelectedGoal()); - LOGGER.info("Starting isabelle..."); - Isabelle isabelle; try { - Isabelle.Setup setup = JIsabelle.setup(isabelle_path); - isabelle = new Isabelle(setup); - } catch (Exception e) { - LOGGER.error("Can't find Isabelle at {}", isabelle_path); + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); + Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); + LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); + } catch (IOException e) { + LOGGER.error("Failed to save translation", e); return; } - LOGGER.info("Parsing theory..."); - - Theory thy0 = beginTheory(translation.toString(), translationFile.toPath(), isabelle); - ToplevelState toplevel = ToplevelState.apply(isabelle); - - MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); - - MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - - - List> transitionsAndTexts = new ArrayList<>(); - parse_text.apply(thy0, translation.toString(), isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) - .foreach(transitionsAndTexts::add); - - for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") - toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) - .retrieveNow(Implicits.toplevelStateConverter(), isabelle); - } - LOGGER.info("Finished Parsing"); - - String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); - String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); - String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); - - MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = - MLValue.compileFunction( - """ - fn (state, thy, adds, dels) => - let - val override = {add=[],del=[],only=false}; - fun go_run (state, thy) = - let - val p_state = Toplevel.proof_of state; - val ctxt = Proof.context_of p_state; - val params =\s""" + Sledgehammer_Commands + """ - .default_params thy - [("timeout","30"),("verbose","true")]; - val results =\s""" - + sledgehammer + """ - .run_sledgehammer params\s""" + Sledgehammer_Prover + """ - .Normal NONE 1 override p_state; - val (result, (outcome, step)) = results; - in - (result, (""" + sledgehammer + """ - .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - end; - in - Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end - """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); - - Builder> listBuilder = scala.collection.immutable.List.newBuilder(); - scala.collection.immutable.List emptyList = listBuilder.result(); - - Tuple2>> result; - LOGGER.info("Sledgehammering..."); - try { - result = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) - .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - } catch (Exception exception) { - result = new Tuple2<>(Boolean.FALSE, new Tuple2<>("", emptyList)); - } - isabelle.destroy(); - - LOGGER.info("Sledgehammer result: " + result); + SledgehammerResult result = translation.sledgehammer(); //TODO needs its own action to enable undo, etc. and naming reworks - if ((Boolean) result._1()) { - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result._2()._2().head()); + if (result.isSuccessful()) { + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getTactic()); app.tryToInstantiate(mediator.getSelectedGoal()); mediator.getSelectedGoal().apply(app); } - - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationFile.toPath(), translation.toString().getBytes()); - LOGGER.info("Saved to: " + translationFile.toPath()); - } catch (IOException e) { - //TODO handle exception - throw new RuntimeException(e); - } /* List filePaths = new ArrayList<>(); filePaths.add(translationFile.toPath()); From 3d16ccd7a72f03f46dffcef2dded49484149642e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 18:34:37 +0200 Subject: [PATCH 100/248] handle missing isabelle correctly --- .../TranslationAction.java | 60 ++++++++----------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index f067b6d6a5f..29cd4f67537 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -5,23 +5,13 @@ import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.uka.ilkd.key.rule.IBuiltInRuleApp; import de.uka.ilkd.key.smt.SMTRuleApp; -import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.java.JIsabelle; -import de.unruh.isabelle.mlvalue.*; -import de.unruh.isabelle.pure.Implicits; -import de.unruh.isabelle.pure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import scala.Tuple2; -import scala.collection.mutable.Builder; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; public class TranslationAction extends MainWindowAction { @@ -43,29 +33,35 @@ public void actionPerformed(ActionEvent e) { private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); + + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); + File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\TranslationPreamble.thy"); + IsabelleProblem translation; try { - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); - File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\TranslationPreamble.thy"); - IsabelleProblem translation = translator.translateProblem(mediator.getSelectedGoal()); - - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); - Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); - LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); - } catch (IOException e) { - LOGGER.error("Failed to save translation", e); - return; - } + translation = translator.translateProblem(mediator.getSelectedGoal()); + } catch (IllegalFormulaException e) { + LOGGER.error("Failed to generate translation", e); + return; + } - SledgehammerResult result = translation.sledgehammer(); + try { + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); + Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); + LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); + } catch (IOException e) { + LOGGER.error("Failed to save translation", e); + return; + } - //TODO needs its own action to enable undo, etc. and naming reworks - if (result.isSuccessful()) { - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getTactic()); - app.tryToInstantiate(mediator.getSelectedGoal()); - mediator.getSelectedGoal().apply(app); - } + SledgehammerResult result = translation.sledgehammer(); + + //TODO needs its own action to enable undo, etc. and naming reworks + if (result != null && result.isSuccessful()) { + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getTactic()); + app.tryToInstantiate(mediator.getSelectedGoal()); + mediator.getSelectedGoal().apply(app); + } @@ -84,9 +80,5 @@ private void generateTranslation() { Thread isabelleJEdit = new Thread(() -> Isabelle.jedit(setup, pathSeq)); isabelleJEdit.start();*/ - } catch (IllegalFormulaException e) { - //TODO output alert to user - throw new RuntimeException(e); - } } } From 5a4f8c1a65c0afd4969ef06158f95693258ecf76 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 18:35:22 +0200 Subject: [PATCH 101/248] rename settings window --- .../gui/isabelletranslation/IsabelleSettingsProvider.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java index 859368cf969..23d3adf41a4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java @@ -2,8 +2,8 @@ import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.settings.InvalidSettingsInputException; -import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.gui.settings.SettingsPanel; +import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.settings.Configuration; import javax.swing.*; @@ -32,7 +32,7 @@ public IsabelleSettingsProvider() { @Override public String getDescription() { - return "Settings for Isabelle translation"; + return "Isabelle translation"; } @Override @@ -50,8 +50,8 @@ protected JTextField createTranslationPathPanel() { protected JTextField createIsabellePathPanel() { return addFileChooserPanel("Isabelle folder:", "", infoIsabellePathPanel, - true, e -> { - }); + true, e -> { + }); } @Override From e308a88d3871cac89703859835eabd029e4ef00f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 18:39:09 +0200 Subject: [PATCH 102/248] default translation path rename --- .../IsabelleTranslationSettings.java | 35 +++++++++---------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index 3d6dde81d69..e57e7a23cef 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -3,21 +3,20 @@ * SPDX-License-Identifier: GPL-2.0-only */ package de.uka.ilkd.key.gui.isabelletranslation; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.nio.file.Path; -import java.util.Properties; - import de.uka.ilkd.key.settings.AbstractSettings; import de.uka.ilkd.key.settings.Configuration; import de.uka.ilkd.key.settings.PathConfig; - import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.nio.file.Path; +import java.util.Properties; + public class IsabelleTranslationSettings extends AbstractSettings { protected static final File SETTINGS_FILE_NEW = new File(PathConfig.getKeyConfigDir(), "isabelleSettings.json"); @@ -29,7 +28,7 @@ public class IsabelleTranslationSettings extends AbstractSettings { private Path isabellePath; private Path translationPath; private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); - private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "isabelleTranslations"); + private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); private static Configuration getDefaultConfig() { Configuration config = new Configuration(); @@ -70,15 +69,15 @@ public static IsabelleTranslationSettings getInstance() { } public void save() { - LOGGER.info("Save Isabelle settings to: " + SETTINGS_FILE_NEW.getAbsolutePath()); - try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { - var config = new Configuration(); - writeSettings(config); - config.save(writer, "Isabelle settings"); - writer.flush(); - } catch (IOException ex) { - LOGGER.error("Failed to save Isabelle settings", ex); - } + LOGGER.info("Save Isabelle settings to: " + SETTINGS_FILE_NEW.getAbsolutePath()); + try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { + var config = new Configuration(); + writeSettings(config); + config.save(writer, "Isabelle settings"); + writer.flush(); + } catch (IOException ex) { + LOGGER.error("Failed to save Isabelle settings", ex); + } } @Override From c47c91937411ae244703d418ead0940e9158d45e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 18:47:36 +0200 Subject: [PATCH 103/248] fix translation preamble --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- .../uka/ilkd/key/gui/isabelletranslation/TranslationAction.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 3d17733bf8b..169f1987ec6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -149,7 +149,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } translationPreamble.append("end"); - StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main TranslationPreamble begin").append(LINE_ENDING); + StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main Draft.TranslationPreamble begin").append(LINE_ENDING); sequentTranslation.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 29cd4f67537..e139ab50f3f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -46,8 +46,8 @@ private void generateTranslation() { try { Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); + Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); } catch (IOException e) { LOGGER.error("Failed to save translation", e); From eba83d126a872bfdbed549d4c88306730948c111 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 18:55:21 +0200 Subject: [PATCH 104/248] improve close message --- .../key/gui/isabelletranslation/SledgehammerResult.java | 7 +++++-- .../key/gui/isabelletranslation/TranslationAction.java | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java index 6ba5c4c7def..b00618c39b6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java @@ -8,7 +8,10 @@ public Boolean isSuccessful() { return (Boolean) result._1(); } - public Tuple2> getTactic() { - return result._2(); + public String getSuccessfulTactic() { + if (!isSuccessful()) { + return null; + } + return result._2()._2().head(); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index e139ab50f3f..04d7d24d081 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -58,7 +58,7 @@ private void generateTranslation() { //TODO needs its own action to enable undo, etc. and naming reworks if (result != null && result.isSuccessful()) { - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getTactic()); + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getSuccessfulTactic()); app.tryToInstantiate(mediator.getSelectedGoal()); mediator.getSelectedGoal().apply(app); } From e950c8b2b5aa7a2b5520e897c5d68b2a75825591 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 15 Apr 2024 19:09:01 +0200 Subject: [PATCH 105/248] better Log messages --- .../isabelletranslation/IsabelleProblem.java | 49 ++++++++++--------- .../SledgehammerResult.java | 5 ++ 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 45becb8f20e..d01382dfbb3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -4,8 +4,8 @@ import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.*; -import de.unruh.isabelle.pure.*; import de.unruh.isabelle.pure.Implicits; +import de.unruh.isabelle.pure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; @@ -57,27 +57,28 @@ public SledgehammerResult sledgehammer() { return null; } - LOGGER.info("Parsing theory..."); + LOGGER.info("Opening theory..."); Theory thy0 = beginTheory(getSequentTranslation(), Path.of((settings.getTranslationPath() + "\\Translation.thy")), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + LOGGER.info("Parsing theory..."); java.util.List> transitionsAndTexts = new ArrayList<>(); parse_text.apply(thy0, getSequentTranslation(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) @@ -107,20 +108,20 @@ fun go_run (state, thy) = val p_state = Toplevel.proof_of state; val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ - .default_params thy - [("timeout","30"),("verbose","true")]; - val results =\s""" + .default_params thy + [("timeout","30"),("verbose","true")]; + val results =\s""" + sledgehammer + """ - .run_sledgehammer params\s""" + Sledgehammer_Prover + """ - .Normal NONE 1 override p_state; - val (result, (outcome, step)) = results; - in - (result, (""" + sledgehammer + """ - .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - end; - in - Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end - """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end + """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java index b00618c39b6..5f3611bbe53 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java @@ -14,4 +14,9 @@ public String getSuccessfulTactic() { } return result._2()._2().head(); } + + @Override + public String toString() { + return result.toString(); + } } From c9c4ad498fec50d9452f660afe6c8b6cd1e4d190 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 13:04:15 +0200 Subject: [PATCH 106/248] add SeqPerm --- .../ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java | 2 +- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- .../UninterpretedSymbolsHandler.preamble.xml | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 241b8f764f0..5fa19a63c72 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -36,7 +36,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("seqSingleton", "seqSingleton"); definedFunctions.put("seqConcat", "seqConcat"); definedFunctions.put("seqSub", "seqSub"); - //TODO seqPerm + definedFunctions.put("seqPerm", "seqPerm"); definedFunctions.put("seqSwap", "seqSwap"); definedFunctions.put("seqRemove", "seqRemove"); definedFunctions.put("seqReverse", "seqReverse"); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 169f1987ec6..a9b83652239 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -44,7 +44,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } StringBuilder translationPreamble = new StringBuilder(); - translationPreamble.append("theory TranslationPreamble imports Main begin").append(LINE_ENDING); + translationPreamble.append("theory TranslationPreamble imports Main \"HOL-Combinatorics.List_Permutation\" begin").append(LINE_ENDING); for (StringBuilder preamble : masterHandler.getPreambles()) { translationPreamble.append(LINE_ENDING).append(preamble).append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 2e6da7a37ac..91d9f5fba62 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -234,6 +234,7 @@ lift_definition seqEmpty::"Seq" is "[]". lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. +lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" From 752897095b9ae34adcd10684113e02e18a4a22bd Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 15:50:35 +0200 Subject: [PATCH 107/248] now built around having a ROOT session and unchanging preamble --- .../isabelletranslation/IsabelleProblem.java | 9 ++- .../IsabelleTranslator.java | 80 ++++++++++--------- 2 files changed, 48 insertions(+), 41 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index d01382dfbb3..db2ee0d6845 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -45,12 +45,17 @@ public SledgehammerResult getResult() { } public SledgehammerResult sledgehammer() { - LOGGER.info("Starting isabelle..."); + LOGGER.info("Starting Isabelle..."); IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); Isabelle isabelle; + ArrayList sessionRoots = new ArrayList<>(); + sessionRoots.add(settings.getTranslationPath()); try { - Isabelle.Setup setup = JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), JIsabelle.setup(settings.getIsabellePath())); + Isabelle.Setup setup = JIsabelle.setupSetLogic("IsabelleTranslations", + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); isabelle = new Isabelle(setup); } catch (Exception e) { LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a9b83652239..8286141ff6c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -49,6 +49,9 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx for (StringBuilder preamble : masterHandler.getPreambles()) { translationPreamble.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } + translationPreamble.append("end"); + + StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main KeYTranslations.TranslationPreamble begin").append(LINE_ENDING); Sort nullSort = services.getNamespaces().sorts().lookup("Null"); @@ -57,42 +60,42 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx String sortName = masterHandler.translateSortName(sort); String UNIV = sortName + "_UNIV"; - translationPreamble.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); - translationPreamble.append("lemma ex_").append(UNIV).append(":"); - translationPreamble.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); - translationPreamble.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); + sequentTranslation.append("lemma ex_").append(UNIV).append(":"); + sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); + sequentTranslation.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); - translationPreamble.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); - translationPreamble.append(LINE_ENDING); + sequentTranslation.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); - translationPreamble.append("specification (").append(UNIV).append(") "); - translationPreamble.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - translationPreamble.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); - translationPreamble.append(LINE_ENDING); + sequentTranslation.append("specification (").append(UNIV).append(") "); + sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + sequentTranslation.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); String UNIV_spec_lemma_name = UNIV + "_specification"; - translationPreamble.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - translationPreamble.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); - translationPreamble.append(LINE_ENDING); + sequentTranslation.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + sequentTranslation.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); - translationPreamble.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); + sequentTranslation.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); String repName = sortName + "2any"; String absName = "any2" + sortName; - translationPreamble.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); - translationPreamble.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); + sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); - translationPreamble.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; - translationPreamble.append("lemma ").append(sortName).append("_type_specification[simp]:") + sequentTranslation.append("lemma ").append(sortName).append("_type_specification[simp]:") .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) .append(LINE_ENDING); - translationPreamble.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); - translationPreamble.append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); for (Sort parentSort : sortParentsMap.get(sort)) { if (parentSort == Sort.ANY) { @@ -100,56 +103,55 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } String parentSortName = masterHandler.translateSortName(parentSort); String parentSortInj = sortName + "2" + parentSortName; - translationPreamble.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) + sequentTranslation.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); - translationPreamble.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); } - translationPreamble.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); - translationPreamble.append("begin").append(LINE_ENDING); + sequentTranslation.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); + sequentTranslation.append("begin").append(LINE_ENDING); String to_any_fun_Name = "to_any_" + sortName; - translationPreamble.append("fun ").append(to_any_fun_Name) + sequentTranslation.append("fun ").append(to_any_fun_Name) .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") .append(LINE_ENDING); String cast_fun_Name = "cast_" + sortName; - translationPreamble.append("fun ").append(cast_fun_Name) + sequentTranslation.append("fun ").append(cast_fun_Name) .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") .append(LINE_ENDING); - translationPreamble.append("instance by standard").append(LINE_ENDING); - translationPreamble.append("end").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("instance by standard").append(LINE_ENDING); + sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); if (nullSort.extendsTrans(sort)) { String null_to_sort_name = "Null2" + sortName; - translationPreamble.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) + sequentTranslation.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); - translationPreamble.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); } if (sort instanceof ArraySort) { - translationPreamble.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); - translationPreamble.append("begin").append(LINE_ENDING); + sequentTranslation.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); + sequentTranslation.append("begin").append(LINE_ENDING); String element_type_name = "element_type_" + sortName; String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; - translationPreamble.append("fun ").append(element_type_name) + sequentTranslation.append("fun ").append(element_type_name) .append(" where \"").append(element_type_name) .append(" (x::").append(sortName).append(")").append(" = ") .append(elementSortType).append("\"") .append(LINE_ENDING); - translationPreamble.append("instance by standard").append(LINE_ENDING); - translationPreamble.append("end").append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append("instance by standard").append(LINE_ENDING); + sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); } String typeConstName = sortName + "_type"; - translationPreamble.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); + sequentTranslation.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); - translationPreamble.append(LINE_ENDING).append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); } - translationPreamble.append("end"); + sequentTranslation.append("end"); - StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main Draft.TranslationPreamble begin").append(LINE_ENDING); sequentTranslation.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); From eba422e5fee16f8ff52bf3eae4209446d488a7fa Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 20:00:28 +0200 Subject: [PATCH 108/248] load settings at startup --- .../IsabelleTranslationExtension.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index 557989ed166..b717afcd267 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -5,23 +5,17 @@ import de.uka.ilkd.key.gui.extension.api.ContextMenuAdapter; import de.uka.ilkd.key.gui.extension.api.ContextMenuKind; import de.uka.ilkd.key.gui.extension.api.KeYGuiExtension; -import de.uka.ilkd.key.gui.settings.SettingsDialog; import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.pp.PosInSequent; -import de.uka.ilkd.key.settings.Configuration; -import de.uka.ilkd.key.util.properties.Properties; import org.jspecify.annotations.NonNull; import javax.swing.*; -import java.io.IOException; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import java.util.Objects; @KeYGuiExtension.Info(name = "Translation", optional = true, experimental = true) -public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu { +public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { @Override public SettingsProvider getSettings() { @@ -49,4 +43,9 @@ public List getContextActions( public @NonNull List getContextActions(@NonNull KeYMediator mediator, @NonNull ContextMenuKind kind, @NonNull Object underlyingObject) { return adapter.getContextActions(mediator, kind, underlyingObject); } + + @Override + public void init(MainWindow window, KeYMediator mediator) { + IsabelleTranslationSettings.getInstance(); + } } From 2c4ce322cbf64039fe3443650e6096769b2fd1eb Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 20:11:52 +0200 Subject: [PATCH 109/248] file path changes --- .../ilkd/key/gui/isabelletranslation/TranslationAction.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 04d7d24d081..42acc4debd5 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -34,8 +34,8 @@ private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\Translation.thy"); - File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "\\TranslationPreamble.thy"); + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); + File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); IsabelleProblem translation; try { translation = translator.translateProblem(mediator.getSelectedGoal()); From 82ed6e568c5331849abc34684cf932b33eecc9ed Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 20:36:54 +0200 Subject: [PATCH 110/248] create session files at startup and when changing translation path --- .../IsabelleTranslationExtension.java | 6 +- .../IsabelleTranslationSettings.java | 51 +++++++++++++--- .../uka/ilkd/key/gui/isabelletranslation/ROOT | 6 ++ .../ilkd/key/gui/isabelletranslation/root.tex | 60 +++++++++++++++++++ 4 files changed, 115 insertions(+), 8 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT create mode 100644 keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index b717afcd267..be450746f79 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -8,6 +8,8 @@ import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.pp.PosInSequent; import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.swing.*; import java.util.ArrayList; @@ -17,6 +19,8 @@ experimental = true) public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationExtension.class); + @Override public SettingsProvider getSettings() { return new IsabelleSettingsProvider(); @@ -46,6 +50,6 @@ public List getContextActions( @Override public void init(MainWindow window, KeYMediator mediator) { - IsabelleTranslationSettings.getInstance(); + IsabelleTranslationSettings.getInstance().createSessionFiles(); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index e57e7a23cef..2732de538ff 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -10,12 +10,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; +import java.io.*; +import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; +import java.util.stream.Collectors; public class IsabelleTranslationSettings extends AbstractSettings { protected static final File SETTINGS_FILE_NEW = @@ -30,6 +29,8 @@ public class IsabelleTranslationSettings extends AbstractSettings { private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); + private boolean sessionFilesPresent; + private static Configuration getDefaultConfig() { Configuration config = new Configuration(); config.set(isabellePathKey, DEFAULT_ISABELLE_PATH); @@ -39,6 +40,12 @@ private static Configuration getDefaultConfig() { private IsabelleTranslationSettings(Configuration load) { readSettings(load); + Path rootPath = Path.of(translationPath + "/ROOT"); + Path documentPath = Path.of(translationPath + "/documents/root.tex"); + + if (!rootPath.toFile().exists() || !documentPath.toFile().exists()) { + sessionFilesPresent = false; + } Runtime.getRuntime().addShutdownHook(new Thread(this::save)); } @@ -68,6 +75,27 @@ public static IsabelleTranslationSettings getInstance() { return INSTANCE; } + protected void createSessionFiles() { + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); + Path sessionRootPath = Path.of(settings.getTranslationPath() + "/ROOT"); + BufferedReader sessionReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("ROOT"))); + String sessionRoot = sessionReader.lines().collect(Collectors.joining()); + + Path sessionDocumentPath = Path.of(settings.getTranslationPath() + "/document/root.tex"); + BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("document/root.tex"))); + String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining()); + + try { + Files.write(sessionRootPath, sessionRoot.getBytes()); + Files.write(sessionDocumentPath, sessionDocument.getBytes()); + LOGGER.info("Created Isabelle session files at: {}", settings.getTranslationPath()); + sessionFilesPresent = true; + } catch (IOException e) { + LOGGER.error("Failed to create ROOT file for Isabelle Translation"); + sessionFilesPresent = false; + } + } + public void save() { LOGGER.info("Save Isabelle settings to: " + SETTINGS_FILE_NEW.getAbsolutePath()); try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { @@ -83,7 +111,11 @@ public void save() { @Override public void readSettings(Properties props) { isabellePath = Path.of(props.getProperty(isabellePathKey)); - translationPath = Path.of(props.getProperty(translationPathKey)); + Path newTranslationPath = Path.of(props.getProperty(translationPathKey)); + if (newTranslationPath != translationPath) { + sessionFilesPresent = false; + } + translationPath = newTranslationPath; } @Override @@ -94,12 +126,17 @@ public void writeSettings(Properties props) { @Override public void readSettings(@NonNull Configuration props) { - if (INSTANCE == null) { + if (isabellePath == null || translationPath == null) { isabellePath = DEFAULT_ISABELLE_PATH; translationPath = DEFAULT_TRANSLATION_PATH; } isabellePath = Path.of(props.get(isabellePathKey, isabellePath.toString())); - translationPath = Path.of(props.get(translationPathKey, translationPath.toString())); + + Path newTranslationPath = Path.of(props.get(translationPathKey, translationPath.toString())); + if (newTranslationPath != translationPath) { + sessionFilesPresent = false; + } + translationPath = newTranslationPath; } @Override diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT new file mode 100644 index 00000000000..84c0d6c4b4b --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT @@ -0,0 +1,6 @@ +session KeYTranslations = HOL + + sessions "HOL-Combinatorics" + theories + TranslationPreamble + document_files + "root.tex" \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex new file mode 100644 index 00000000000..aa5dbaa6a3e --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex @@ -0,0 +1,60 @@ +\documentclass[11pt,a4paper]{article} +\usepackage[T1]{fontenc} +\usepackage{isabelle,isabellesym} + +% further packages required for unusual symbols (see also +% isabellesym.sty), use only when needed + +%\usepackage{amssymb} + %for \, \, \, \, \, \, + %\, \, \, \, \, + %\, \, \ + +%\usepackage{eurosym} + %for \ + +%\usepackage[only,bigsqcap,bigparallel,fatsemi,interleave,sslash]{stmaryrd} + %for \, \, \, \, \ + +%\usepackage{eufrak} + %for \ ... \, \ ... \ (also included in amssymb) + +%\usepackage{textcomp} + %for \, \, \, \, \, + %\ + +% this should be the last package used +\usepackage{pdfsetup} + +% urls in roman style, theory text in math-similar italics +\urlstyle{rm} +\isabellestyle{it} + +% for uniform font size +%\renewcommand{\isastyle}{\isastyleminor} + + +\begin{document} + +\title{KeYTranslations} +\author{Nils Buchholz} +\maketitle + +\tableofcontents + +% sane default for proof documents +\parindent 0pt\parskip 0.5ex + +% generated text of all theories +\input{session} + +% optional bibliography +%\bibliographystyle{abbrv} +%\bibliography{root} + +\end{document} + +%%% Local Variables: +%%% mode: latex +%%% TeX-master: t +%%% End: \ No newline at end of file From dd1e262ae53ec8addc43e0ecbc7b261e218315b4 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 21:10:56 +0200 Subject: [PATCH 111/248] fix file loading errors and translation imports --- .../isabelletranslation/IsabelleProblem.java | 2 +- .../IsabelleTranslationExtension.java | 2 +- .../IsabelleTranslationSettings.java | 40 +++++++++---------- .../IsabelleTranslator.java | 1 - .../uka/ilkd/key/gui/isabelletranslation/ROOT | 1 + 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index db2ee0d6845..7d7ec378e5a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -52,7 +52,7 @@ public SledgehammerResult sledgehammer() { ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); try { - Isabelle.Setup setup = JIsabelle.setupSetLogic("IsabelleTranslations", + Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", JIsabelle.setupSetSessionRoots(sessionRoots, JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), JIsabelle.setup(settings.getIsabellePath())))); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java index be450746f79..d532b024a19 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java @@ -50,6 +50,6 @@ public List getContextActions( @Override public void init(MainWindow window, KeYMediator mediator) { - IsabelleTranslationSettings.getInstance().createSessionFiles(); + IsabelleTranslationSettings.getInstance(); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index 2732de538ff..361d655f936 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -29,7 +29,7 @@ public class IsabelleTranslationSettings extends AbstractSettings { private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); - private boolean sessionFilesPresent; + private boolean sessionFilesPresent = false; private static Configuration getDefaultConfig() { Configuration config = new Configuration(); @@ -62,37 +62,37 @@ public static IsabelleTranslationSettings getInstance() { if (INSTANCE == null) { if (SETTINGS_FILE_NEW.exists()) { try { - LOGGER.info("Use new configuration format at {}", SETTINGS_FILE_NEW); + LOGGER.info("Load Isabelle settings at {}", SETTINGS_FILE_NEW); return INSTANCE = new IsabelleTranslationSettings(Configuration.load(SETTINGS_FILE_NEW)); } catch (IOException e) { - LOGGER.error("Could not read {}, resorting to default", SETTINGS_FILE_NEW, e); + LOGGER.error("Could not read {}, resorting to default settings", SETTINGS_FILE_NEW, e); return INSTANCE = new IsabelleTranslationSettings(getDefaultConfig()); } } - LOGGER.info("Resorting to default Isabelle settings"); + LOGGER.info("No settings present, resorting to default Isabelle settings"); return INSTANCE = new IsabelleTranslationSettings(getDefaultConfig()); } return INSTANCE; } - protected void createSessionFiles() { - IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); - Path sessionRootPath = Path.of(settings.getTranslationPath() + "/ROOT"); - BufferedReader sessionReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("ROOT"))); - String sessionRoot = sessionReader.lines().collect(Collectors.joining()); + protected boolean createSessionFiles() { + Path sessionRootPath = Path.of(translationPath + "/ROOT"); + BufferedReader sessionReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("ROOT"))); + String sessionRoot = sessionReader.lines().collect(Collectors.joining(System.lineSeparator())); - Path sessionDocumentPath = Path.of(settings.getTranslationPath() + "/document/root.tex"); - BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("document/root.tex"))); - String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining()); + Path sessionDocumentPath = Path.of(translationPath + "/document/root.tex"); + BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("root.tex"))); + String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining(System.lineSeparator())); try { Files.write(sessionRootPath, sessionRoot.getBytes()); + Files.createDirectories(sessionDocumentPath.getParent()); Files.write(sessionDocumentPath, sessionDocument.getBytes()); - LOGGER.info("Created Isabelle session files at: {}", settings.getTranslationPath()); - sessionFilesPresent = true; + LOGGER.info("Created Isabelle session files at: {}", translationPath); + return sessionFilesPresent = true; } catch (IOException e) { - LOGGER.error("Failed to create ROOT file for Isabelle Translation"); - sessionFilesPresent = false; + LOGGER.error("Failed to create ROOT file for Isabelle Translation, because: {}", e.toString()); + return sessionFilesPresent = false; } } @@ -113,9 +113,9 @@ public void readSettings(Properties props) { isabellePath = Path.of(props.getProperty(isabellePathKey)); Path newTranslationPath = Path.of(props.getProperty(translationPathKey)); if (newTranslationPath != translationPath) { - sessionFilesPresent = false; + translationPath = newTranslationPath; + sessionFilesPresent = createSessionFiles(); } - translationPath = newTranslationPath; } @Override @@ -134,9 +134,9 @@ public void readSettings(@NonNull Configuration props) { Path newTranslationPath = Path.of(props.get(translationPathKey, translationPath.toString())); if (newTranslationPath != translationPath) { - sessionFilesPresent = false; + translationPath = newTranslationPath; + sessionFilesPresent = createSessionFiles(); } - translationPath = newTranslationPath; } @Override diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 8286141ff6c..67707d8ff30 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -150,7 +150,6 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); } - sequentTranslation.append("end"); sequentTranslation.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT index 84c0d6c4b4b..0dec1b31ef4 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT @@ -1,4 +1,5 @@ session KeYTranslations = HOL + + options [document=false] sessions "HOL-Combinatorics" theories TranslationPreamble From cefc94a74e51426a511e4ee1f753fc4017cd7ef5 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 16 Apr 2024 22:57:36 +0200 Subject: [PATCH 112/248] remove interpretations as subtypes of any (might interfere with induction, etc. over respective isabelle types) --- .../UninterpretedSymbolsHandler.preamble.xml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 91d9f5fba62..86913ae30de 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -28,9 +28,6 @@ consts axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_Image)" declare [[coercion int2any]] -interpretation int: type_definition int2any any2int int_Image - using int_sub_any by simp - definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" consts @@ -41,9 +38,6 @@ consts axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_Image)" declare [[coercion bool2any]] -interpretation bool: type_definition bool2any any2bool bool_Image - using bool_sub_any by simp - definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" @@ -120,9 +114,6 @@ consts axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" -interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image - using LocSet_sub_any by simp - declare [[coercion LocSet2any]] definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" @@ -141,9 +132,6 @@ consts axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -interpretation Heap:type_definition Heap2any any2Heap Heap_Image - using Heap_sub_any by simp - declare [[coercion Heap2any]] definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" @@ -248,9 +236,6 @@ lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>nat" is axiomatization Seq2any any2Seq Seq_UNIV where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" -interpretation Seq: type_definition Seq2any any2Seq Seq_UNIV - using Seq_sub_any by simp - declare [[coercion Seq2any]] instantiation Seq::any From ab3d918612bbaddd3ab1e86c7be0b15c849a2f66 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 10:54:04 +0200 Subject: [PATCH 113/248] fix observer functions --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 +- .../key/gui/isabelletranslation/ObserverFunctionHandler.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 7d7ec378e5a..12eee3f6cfc 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -142,7 +142,7 @@ fun go_run (state, thy) = new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)); } catch (Exception exception) { - result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>("", emptyList))); + result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); } isabelle.destroy(); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index c07c3eda71b..2d1a1354d45 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -33,6 +33,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr functionName = m.group(1); } else { functionName = op.name().toString().replace("::", "_"); + functionName = functionName.replace("$", ""); } trans.addKnownSymbol(term, new StringBuilder(functionName)); } From 2c63a1e217be75319eb9f0bda1537d047006dc93 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 11:03:41 +0200 Subject: [PATCH 114/248] add infiniteUnion --- .../InfiniteUnionHandler.java | 34 +++++++++++++++++++ .../isabelletranslation/defaultHandlers.txt | 1 + 2 files changed, 35 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java new file mode 100644 index 00000000000..657531ebd99 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java @@ -0,0 +1,34 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.smt.SMTTranslationException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class InfiniteUnionHandler implements IsabelleHandler { + private final Map supportedOperators = new HashMap<>(); + + @Override + public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + supportedOperators.put(services.getTypeConverter().getLocSetLDT().getInfiniteUnion(), "SeqDef"); + } + + @Override + public boolean canHandle(Operator op) { + return supportedOperators.containsKey(op); + } + + @Override + public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + Operator op = term.op(); + String arg1 = "(\\" + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". " + + " to_any (" + trans.translate(term.sub(0)) + "))"; + + return new StringBuilder("(\\").append(arg1).append(")"); + } +} diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt index 8e9cd1be5bb..25432437380 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt @@ -6,6 +6,7 @@ de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler +de.uka.ilkd.key.gui.isabelletranslation.InfiniteUnionHandler de.uka.ilkd.key.gui.isabelletranslation.BSumHandler de.uka.ilkd.key.gui.isabelletranslation.SeqDefHandler de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler From 9e399000e2bdbbe9eae0ec9d561c20d5734e8314 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 11:21:47 +0200 Subject: [PATCH 115/248] fix translation when multiple invariants occur --- .../key/gui/isabelletranslation/ObserverFunctionHandler.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index 2d1a1354d45..ee3a29f335a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -30,7 +30,8 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); String functionName; if (m.find()) { - functionName = m.group(1); + functionName = op.name().toString().replace("<" + m.group(1) + ">", "_" + m.group(1)) + .replace("::", "_").replace("$", "").replace(".", "_"); } else { functionName = op.name().toString().replace("::", "_"); functionName = functionName.replace("$", ""); From 6c7a20467939f6b39450f3db5a6882e2f4929abb Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 11:57:50 +0200 Subject: [PATCH 116/248] fix infiniteUnion and add preamble definition for it --- .../key/gui/isabelletranslation/InfiniteUnionHandler.java | 7 +++---- .../gui/isabelletranslation/ObserverFunctionHandler.java | 3 +-- .../UninterpretedSymbolsHandler.preamble.xml | 1 + 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java index 657531ebd99..0c715db70d8 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java @@ -15,7 +15,7 @@ public class InfiniteUnionHandler implements IsabelleHandler { @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { - supportedOperators.put(services.getTypeConverter().getLocSetLDT().getInfiniteUnion(), "SeqDef"); + supportedOperators.put(services.getTypeConverter().getLocSetLDT().getInfiniteUnion(), "infiniteUnion"); } @Override @@ -26,9 +26,8 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { Operator op = term.op(); - String arg1 = "(\\" + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". " + - " to_any (" + trans.translate(term.sub(0)) + "))"; + String arg1 = "{" + trans.translate(term.sub(0)) + "| " + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". True }"; - return new StringBuilder("(\\").append(arg1).append(")"); + return new StringBuilder("(").append(supportedOperators.get(op)).append(arg1).append(")"); } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index ee3a29f335a..88467f57175 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -33,8 +33,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr functionName = op.name().toString().replace("<" + m.group(1) + ">", "_" + m.group(1)) .replace("::", "_").replace("$", "").replace(".", "_"); } else { - functionName = op.name().toString().replace("::", "_"); - functionName = functionName.replace("$", ""); + functionName = op.name().toString().replace("::", "_").replace("$", ""); } trans.addKnownSymbol(term, new StringBuilder(functionName)); } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 86913ae30de..c68434f26de 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -106,6 +106,7 @@ lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\< lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) \<times> {x}". lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. +lift_definition infiniteUnion::"LocSet set\<Rightarrow>LocSet" is Complete_Lattices.Union. consts LocSet_Image::"any set" From cf717b669248caa2d1aa5e1f2e6defac4521ea2e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 21:12:33 +0200 Subject: [PATCH 117/248] add broken main file --- .../src/test/java/evaluation/Main.java | 516 ++++++++++++++++++ 1 file changed, 516 insertions(+) create mode 100644 keyext.isabelletranslation/src/test/java/evaluation/Main.java diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java new file mode 100644 index 00000000000..db7e1abc002 --- /dev/null +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -0,0 +1,516 @@ +package evaluation; + +import de.uka.ilkd.key.api.KeYApi; +import de.uka.ilkd.key.api.ProofApi; +import de.uka.ilkd.key.api.ProofManagementApi; +import de.uka.ilkd.key.control.DefaultUserInterfaceControl; +import de.uka.ilkd.key.control.UserInterfaceControl; +import de.uka.ilkd.key.proof.Node; +import de.uka.ilkd.key.proof.Proof; +import de.uka.ilkd.key.proof.io.ProblemLoaderException; +import de.uka.ilkd.key.proof.io.ProofSaver; +import de.uka.ilkd.key.settings.ProofIndependentSettings; +import de.uka.ilkd.key.strategy.JavaCardDLStrategyFactory; +import de.uka.ilkd.key.strategy.Strategy; +import de.uka.ilkd.key.strategy.StrategyProperties; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; + +import static java.nio.file.StandardOpenOption.APPEND; + +public class Main { + private static final Path VALID_LIST_PATH = Paths.get("/tmp/valid_list.txt"); + + private static final Set VALID_SET = new HashSet<>(); + + private static final Map STATS = new HashMap<>(); + + private static final PrintStream STDOUT = System.out; + private static final PrintStream STDERR = System.err; + + private static Path outDir; + + private static class StatEntry { + final Path p; + ProofState keyState = ProofState.UNKOWN; + long keyTime; + int keyNodes; + long z3TranslationLines; + long translationAndZ3Time; + long z3ProofLines; + long replayTime; + long replayAutoModeTime; + int replayAutoModeNodes; + int replayNodes; + ProofState replayState = ProofState.UNKOWN; + + StatEntry(Path p) { + this.p = p; + } + } + + private enum ProofState { + UNKOWN, + ERROR, + OPEN, + CLOSED + } + + public static void main(String[] args) { + outDir = Paths.get("/tmp/benchmark" + + System.currentTimeMillis()); + try { + Files.createDirectories(outDir); + } catch (IOException e) { + e.printStackTrace(); + } + + if (args.length > 0 && args[0].equals("--create-provable-list")) { + updateZ3ProvableList(); + } else { + run(); + } + } + + private static void run() { + List pathStrings = null; + try { + pathStrings = Files.readAllLines(VALID_LIST_PATH); + } catch (IOException e) { + e.printStackTrace(); + return; + } + for (String s : pathStrings) { + Path p = Paths.get(s); + VALID_SET.add(p); + processFile(p, true, true, true); + } + printStatisticsCSV(); + } + + private static void printStatisticsCSV() { + // print to console + System.setOut(STDOUT); + System.setErr(STDERR); + + System.out.print("input_file"); + System.out.print(","); + System.out.print("KeY_state"); + System.out.print(","); + System.out.print("KeY_time"); + System.out.print(","); + System.out.print("KeY_proof_nodes"); + System.out.print(","); + System.out.print("SMT_translation_lines"); + System.out.print(","); + System.out.print("transl_+_Z3_time"); + System.out.print(","); + System.out.print("Z3_proof_lines"); + System.out.print(","); + System.out.print("replay_time"); + System.out.print(","); + System.out.print("replay_automode_time"); + System.out.print(","); + System.out.print("replayed_proof_nodes"); + System.out.print(","); + System.out.print("replayed_proof_automode_nodes"); + System.out.print(","); + System.out.print("replay_result"); + System.out.println(); + + for (StatEntry statEntry : STATS.values()) { + System.out.print(statEntry.p); + System.out.print(","); + System.out.print(statEntry.keyState); + System.out.print(","); + System.out.print(statEntry.keyTime); + System.out.print(","); + System.out.print(statEntry.keyNodes); + System.out.print(","); + System.out.print(statEntry.z3TranslationLines); + System.out.print(","); + System.out.print(statEntry.translationAndZ3Time); + System.out.print(","); + System.out.print(statEntry.z3ProofLines); + System.out.print(","); + System.out.print(statEntry.replayTime); + System.out.print(","); + System.out.print(statEntry.replayAutoModeTime); + System.out.print(","); + System.out.print(statEntry.replayNodes); + System.out.print(","); + System.out.print(statEntry.replayAutoModeNodes); + System.out.print(","); + System.out.print(statEntry.replayState); + System.out.println(); + } + } + + private static void loadValidSet() throws IOException { + if (Files.exists(VALID_LIST_PATH)) { + Files.lines(VALID_LIST_PATH).forEach(s -> VALID_SET.add(Paths.get(s))); + } + } + + private static void updateZ3ProvableList() { + //Path exampleDir = FindResources.getExampleDirectory().toPath().toAbsolutePath().normalize(); + try { + loadValidSet(); + List dirs = new ArrayList<>(); + //dirs.add(exampleDir); + dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/newBook/Using_KeY")); + dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/smt")); + dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/standard_key")); + //dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/firstTouch")); + dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/firstTouch/01-Agatha")); + + Files.createDirectories(VALID_LIST_PATH.getParent()); + if (!Files.exists(VALID_LIST_PATH)) { + Files.createFile(VALID_LIST_PATH); + } + + for (Path dir : dirs) { + Files.walkFileTree(dir, new FileVisitor() { + + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) + throws IOException { + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + System.out.println("Visiting " + file.toString()); + processFile(file, false, true, false); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) + throws IOException { + return FileVisitResult.CONTINUE; + } + }); + } + } catch (OutOfMemoryError e) { + e.printStackTrace(); + // can not continue in a useful manner + System.exit(-1); + } catch (Throwable e) { + // continue even if an exception is thrown + e.printStackTrace(); + } + } + + private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean tryReplay) { + if (input.toString().endsWith(".key")) { + try { + System.out.println("Processing " + input.toString()); + if (runKeY) { + runeWithKeYAuto(input); + } + if (tryReplay) { + runZ3ToFile(input, true); + } else if (runZ3) { + runZ3ToFile(input, false); + } + } catch (ProblemLoaderException | IOException e) { + e.printStackTrace(); + } + } + } + + private static void runeWithKeYAuto(Path input) throws ProblemLoaderException, IOException { + ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); + ProofApi papi = pm.getLoadedProof(); + Proof proof = papi.getProof(); + UserInterfaceControl uic = new DefaultUserInterfaceControl(); + + // this should initialize with the default properties, + // necessary to enable quantifier instantiation + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + proof.getSettings().getStrategySettings().setMaxSteps(1000000); + proof.getSettings().getStrategySettings().setTimeout(300000); + + long manualTime = System.currentTimeMillis(); + uic.getProofControl().startAndWaitForAutoMode(proof); + manualTime = System.currentTimeMillis() - manualTime; + + int nodes = proof.getStatistics().nodes; + updateKeYNodes(input, nodes); + + long keyTime = proof.getStatistics().autoModeTimeInMillis; + System.out.println(" KeY statistics: " + keyTime); + System.out.println(" Manual logging: " + manualTime); + + updateKeYState(input, proof.closed() ? ProofState.CLOSED : ProofState.OPEN); + updateKeYTime(input, manualTime); + Path proofPath = getOutPath(input, "_key.proof"); + ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); + saver.save(); + + papi.getEnv().dispose(); + } + + private static void runZ3ToFile(Path input, boolean tryReplay) + throws ProblemLoaderException, IOException { + + ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); + ProofApi papi = pm.getLoadedProof(); + + if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { + return; + } + + // currently we do not support files with Java programs + if (pm.getProofContracts() == null || !pm.getProofContracts().isEmpty()) { + return; + } + + Node n = papi.getFirstOpenGoal().getProofNode(); + Proof proof = n.proof(); + + //SMTProblem problem = new SMTProblem(n.sequent(), proof.getServices()); + SMTProblem problem = new SMTProblem(proof.openGoals().head()); + + SMTSettings settings = new SMTSettings(proof.getSettings().getSMTSettings(), + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof); + SolverLauncher launcher = new SolverLauncher(settings); + + launcher.addListener(new SolverLauncherListener() { + long translationAndZ3Time = 0; + + @Override + public void launcherStopped(SolverLauncher launcher, + Collection finishedSolvers) { + System.out.println("Z3 finished (" + finishedSolvers.size() + " solvers)."); + + translationAndZ3Time = System.currentTimeMillis() - translationAndZ3Time; + updateZ3Time(input, translationAndZ3Time); + + // we exactly have that single solver + if (finishedSolvers.size() != 1) { + return; + } + SMTSolver z3 = finishedSolvers.iterator().next(); + + String smtTranslation = z3.getTranslation(); + updateZ3TranslationLines(input, countLines(smtTranslation)); + try { + Files.write(getOutPath(input, "_translation.smt2"), smtTranslation.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + + String z3Proof = z3.getSolverOutput(); + + if (z3.getFinalResult().isValid() == SMTSolverResult.ThreeValuedTruth.VALID) { + try { + appendValid(input); + + Path outPath = getOutPath(input, "_proof.smt2"); + updateZ3ProofLines(input, countLines(z3Proof)); + Files.write(outPath, z3Proof.getBytes()); + + if (tryReplay) { + tryReplay(problem, input); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + // try to avoid memory leaks + papi.getEnv().dispose(); + } + System.setOut(STDOUT); + System.setErr(STDERR); + } + } + + @Override + public void launcherStarted(Collection problems, + Collection solverTypes, + SolverLauncher launcher) { + System.out.println("Running Z3 ..."); + translationAndZ3Time = System.currentTimeMillis(); + } + }); + launcher.launch(problem, proof.getServices(), SolverType.Z3_NEW_TL_SOLVER); + } + + private static void appendValid(Path keyPath) { + try { + if (!VALID_SET.contains(keyPath)) { + VALID_SET.add(keyPath); + Files.write(VALID_LIST_PATH, Collections.singleton(keyPath.toString()), APPEND); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static long countLines(String input) { + return input.chars().filter(ch -> ch == '\n').count(); + } + + private static Path getOutPath(Path input, String newExt) { + String origFileName = input.getFileName().toString(); + String name = origFileName.substring(0, origFileName.lastIndexOf('.')); + String prefixedName = input.getName(input.getNameCount() - 3) + + "_" + input.getName(input.getNameCount() - 2) + + "_" + name; + String newName = prefixedName + newExt; + return outDir.resolve(newName); + } + + private static void tryReplay(SMTProblem problem, Path inPath) { + try { + SMTReplayer replayer = new SMTReplayer(problem); + + // prepare logging stdout to file + Path log = getOutPath(inPath, ".log"); + Path proofPath = getOutPath(inPath, ".proof"); + + PrintStream printStream = new PrintStream(log.toFile()); + System.setOut(printStream); + System.setErr(printStream); + + long time = System.currentTimeMillis(); + replayer.replay(); + Proof proof = replayer.getProof(); + long replayTime = System.currentTimeMillis() - time; + updateReplayTime(inPath, replayTime); + updateReplayNodes(inPath, proof.getStatistics().nodes); + long replayAutoModeTime = proof.getAutoModeTime(); + updateReplayAutoModeTime(inPath, replayAutoModeTime); + updateReplayAutoModeNodes(inPath, proof.getStatistics().interactiveSteps); + + if (proof.closed()) { + System.out.println("Proof is closed!"); + + ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); + saver.save(); + + updateReplayState(inPath, ProofState.CLOSED); + } else { + System.out.println("Proof is still open (" + proof.openGoals().size() + " goals)!"); + updateReplayState(inPath, ProofState.OPEN); + } + } catch (Throwable e) { + // error in replay -> log to file + e.printStackTrace(); + updateReplayState(inPath, ProofState.ERROR); + } + } + + private static void updateReplayTime(Path p, long replayTime) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.replayTime = replayTime; + STATS.put(p, stats); + } + + private static void updateReplayAutoModeTime(Path p, long replayAutoModeTime) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.replayAutoModeTime = replayAutoModeTime; + STATS.put(p, stats); + } + + private static void updateReplayNodes(Path p, int replayNodes) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.replayNodes = replayNodes; + STATS.put(p, stats); + } + + private static void updateReplayAutoModeNodes(Path p, int replayAutoModeNodes) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.replayAutoModeNodes = replayAutoModeNodes; + STATS.put(p, stats); + } + + private static void updateReplayState(Path p, ProofState replayState) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.replayState = replayState; + STATS.put(p, stats); + } + + private static void updateZ3Time(Path p, long z3Time) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.translationAndZ3Time = z3Time; + STATS.put(p, stats); + } + + private static void updateZ3TranslationLines(Path p, long z3TranslationLines) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.z3TranslationLines = z3TranslationLines; + STATS.put(p, stats); + } + + private static void updateZ3ProofLines(Path p, long z3ProofLines) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.z3ProofLines = z3ProofLines; + STATS.put(p, stats); + } + + private static void updateKeYNodes(Path p, int keyNodes) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.keyNodes = keyNodes; + STATS.put(p, stats); + } + + + private static void updateKeYTime(Path p, long keyTime) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.keyTime = keyTime; + STATS.put(p, stats); + } + + private static void updateKeYState(Path p, ProofState keyState) { + StatEntry stats = STATS.get(p); + if (stats == null) { + stats = new StatEntry(p); + } + stats.keyState = keyState; + STATS.put(p, stats); + } +} From 8d7e497f8aa56e2dcd63865d320ba17c39924047 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 21:26:13 +0200 Subject: [PATCH 118/248] fixed main file --- .../src/test/java/evaluation/Main.java | 122 +++--------------- 1 file changed, 21 insertions(+), 101 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index db7e1abc002..fe2939743e8 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -9,7 +9,12 @@ import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.io.ProblemLoaderException; import de.uka.ilkd.key.proof.io.ProofSaver; +import de.uka.ilkd.key.settings.DefaultSMTSettings; import de.uka.ilkd.key.settings.ProofIndependentSettings; +import de.uka.ilkd.key.smt.*; +import de.uka.ilkd.key.smt.solvertypes.SolverType; +import de.uka.ilkd.key.smt.solvertypes.SolverTypeImplementation; +import de.uka.ilkd.key.smt.solvertypes.SolverTypes; import de.uka.ilkd.key.strategy.JavaCardDLStrategyFactory; import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; @@ -23,6 +28,11 @@ import static java.nio.file.StandardOpenOption.APPEND; public class Main { + private static final SolverType Z3_SOLVER = SolverTypes.getSolverTypes().stream() + .filter(it -> it.getClass().equals(SolverTypeImplementation.class) + && it.getName().equals("Z3 (Legacy Translation)")) + .findFirst().orElse(null); + private static final Path VALID_LIST_PATH = Paths.get("/tmp/valid_list.txt"); private static final Set VALID_SET = new HashSet<>(); @@ -36,7 +46,7 @@ public class Main { private static class StatEntry { final Path p; - ProofState keyState = ProofState.UNKOWN; + ProofState keyState = ProofState.UNKNOWN; long keyTime; int keyNodes; long z3TranslationLines; @@ -46,7 +56,7 @@ private static class StatEntry { long replayAutoModeTime; int replayAutoModeNodes; int replayNodes; - ProofState replayState = ProofState.UNKOWN; + ProofState replayState = ProofState.UNKNOWN; StatEntry(Path p) { this.p = p; @@ -54,7 +64,7 @@ private static class StatEntry { } private enum ProofState { - UNKOWN, + UNKNOWN, ERROR, OPEN, CLOSED @@ -162,11 +172,10 @@ private static void updateZ3ProvableList() { loadValidSet(); List dirs = new ArrayList<>(); //dirs.add(exampleDir); - dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/newBook/Using_KeY")); - dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/smt")); - dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/standard_key")); - //dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/firstTouch")); - dirs.add(Paths.get("/home/wolfram/Desktop/key/key/key.ui/examples/firstTouch/01-Agatha")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/newBook/Using_KeY")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/smt")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/standard_key")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/firstTouch/")); Files.createDirectories(VALID_LIST_PATH.getParent()); if (!Files.exists(VALID_LIST_PATH)) { @@ -285,8 +294,8 @@ private static void runZ3ToFile(Path input, boolean tryReplay) //SMTProblem problem = new SMTProblem(n.sequent(), proof.getServices()); SMTProblem problem = new SMTProblem(proof.openGoals().head()); - SMTSettings settings = new SMTSettings(proof.getSettings().getSMTSettings(), - ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof); + SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof.getSettings().getNewSMTSettings(), proof); SolverLauncher launcher = new SolverLauncher(settings); launcher.addListener(new SolverLauncherListener() { @@ -314,7 +323,7 @@ public void launcherStopped(SolverLauncher launcher, e.printStackTrace(); } - String z3Proof = z3.getSolverOutput(); + String z3Proof = z3.getRawSolverOutput(); if (z3.getFinalResult().isValid() == SMTSolverResult.ThreeValuedTruth.VALID) { try { @@ -323,10 +332,6 @@ public void launcherStopped(SolverLauncher launcher, Path outPath = getOutPath(input, "_proof.smt2"); updateZ3ProofLines(input, countLines(z3Proof)); Files.write(outPath, z3Proof.getBytes()); - - if (tryReplay) { - tryReplay(problem, input); - } } catch (IOException e) { e.printStackTrace(); } finally { @@ -346,7 +351,7 @@ public void launcherStarted(Collection problems, translationAndZ3Time = System.currentTimeMillis(); } }); - launcher.launch(problem, proof.getServices(), SolverType.Z3_NEW_TL_SOLVER); + launcher.launch(problem, proof.getServices(), Z3_SOLVER); } private static void appendValid(Path keyPath) { @@ -374,91 +379,6 @@ private static Path getOutPath(Path input, String newExt) { return outDir.resolve(newName); } - private static void tryReplay(SMTProblem problem, Path inPath) { - try { - SMTReplayer replayer = new SMTReplayer(problem); - - // prepare logging stdout to file - Path log = getOutPath(inPath, ".log"); - Path proofPath = getOutPath(inPath, ".proof"); - - PrintStream printStream = new PrintStream(log.toFile()); - System.setOut(printStream); - System.setErr(printStream); - - long time = System.currentTimeMillis(); - replayer.replay(); - Proof proof = replayer.getProof(); - long replayTime = System.currentTimeMillis() - time; - updateReplayTime(inPath, replayTime); - updateReplayNodes(inPath, proof.getStatistics().nodes); - long replayAutoModeTime = proof.getAutoModeTime(); - updateReplayAutoModeTime(inPath, replayAutoModeTime); - updateReplayAutoModeNodes(inPath, proof.getStatistics().interactiveSteps); - - if (proof.closed()) { - System.out.println("Proof is closed!"); - - ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); - saver.save(); - - updateReplayState(inPath, ProofState.CLOSED); - } else { - System.out.println("Proof is still open (" + proof.openGoals().size() + " goals)!"); - updateReplayState(inPath, ProofState.OPEN); - } - } catch (Throwable e) { - // error in replay -> log to file - e.printStackTrace(); - updateReplayState(inPath, ProofState.ERROR); - } - } - - private static void updateReplayTime(Path p, long replayTime) { - StatEntry stats = STATS.get(p); - if (stats == null) { - stats = new StatEntry(p); - } - stats.replayTime = replayTime; - STATS.put(p, stats); - } - - private static void updateReplayAutoModeTime(Path p, long replayAutoModeTime) { - StatEntry stats = STATS.get(p); - if (stats == null) { - stats = new StatEntry(p); - } - stats.replayAutoModeTime = replayAutoModeTime; - STATS.put(p, stats); - } - - private static void updateReplayNodes(Path p, int replayNodes) { - StatEntry stats = STATS.get(p); - if (stats == null) { - stats = new StatEntry(p); - } - stats.replayNodes = replayNodes; - STATS.put(p, stats); - } - - private static void updateReplayAutoModeNodes(Path p, int replayAutoModeNodes) { - StatEntry stats = STATS.get(p); - if (stats == null) { - stats = new StatEntry(p); - } - stats.replayAutoModeNodes = replayAutoModeNodes; - STATS.put(p, stats); - } - - private static void updateReplayState(Path p, ProofState replayState) { - StatEntry stats = STATS.get(p); - if (stats == null) { - stats = new StatEntry(p); - } - stats.replayState = replayState; - STATS.put(p, stats); - } - private static void updateZ3Time(Path p, long z3Time) { StatEntry stats = STATS.get(p); if (stats == null) { From 295635fc56c3fddfae351a8a22e1ed09603c3e92 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 21:44:56 +0200 Subject: [PATCH 119/248] bugs in main file --- .../src/test/java/evaluation/Main.java | 118 +++++++++--------- 1 file changed, 61 insertions(+), 57 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index fe2939743e8..db43a70e296 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -99,64 +99,68 @@ private static void run() { VALID_SET.add(p); processFile(p, true, true, true); } - printStatisticsCSV(); + saveStatisticsCSV(); } - private static void printStatisticsCSV() { - // print to console - System.setOut(STDOUT); - System.setErr(STDERR); - - System.out.print("input_file"); - System.out.print(","); - System.out.print("KeY_state"); - System.out.print(","); - System.out.print("KeY_time"); - System.out.print(","); - System.out.print("KeY_proof_nodes"); - System.out.print(","); - System.out.print("SMT_translation_lines"); - System.out.print(","); - System.out.print("transl_+_Z3_time"); - System.out.print(","); - System.out.print("Z3_proof_lines"); - System.out.print(","); - System.out.print("replay_time"); - System.out.print(","); - System.out.print("replay_automode_time"); - System.out.print(","); - System.out.print("replayed_proof_nodes"); - System.out.print(","); - System.out.print("replayed_proof_automode_nodes"); - System.out.print(","); - System.out.print("replay_result"); - System.out.println(); + private static void saveStatisticsCSV() { + StringBuilder sb = new StringBuilder(); + + sb.append("input_file"); + sb.append(","); + sb.append("KeY_state"); + sb.append(","); + sb.append("KeY_time"); + sb.append(","); + sb.append("KeY_proof_nodes"); + sb.append(","); + sb.append("SMT_translation_lines"); + sb.append(","); + sb.append("transl_+_Z3_time"); + sb.append(","); + sb.append("Z3_proof_lines"); + sb.append(","); + sb.append("replay_time"); + sb.append(","); + sb.append("replay_automode_time"); + sb.append(","); + sb.append("replayed_proof_nodes"); + sb.append(","); + sb.append("replayed_proof_automode_nodes"); + sb.append(","); + sb.append("replay_result"); + sb.append(System.lineSeparator()); for (StatEntry statEntry : STATS.values()) { - System.out.print(statEntry.p); - System.out.print(","); - System.out.print(statEntry.keyState); - System.out.print(","); - System.out.print(statEntry.keyTime); - System.out.print(","); - System.out.print(statEntry.keyNodes); - System.out.print(","); - System.out.print(statEntry.z3TranslationLines); - System.out.print(","); - System.out.print(statEntry.translationAndZ3Time); - System.out.print(","); - System.out.print(statEntry.z3ProofLines); - System.out.print(","); - System.out.print(statEntry.replayTime); - System.out.print(","); - System.out.print(statEntry.replayAutoModeTime); - System.out.print(","); - System.out.print(statEntry.replayNodes); - System.out.print(","); - System.out.print(statEntry.replayAutoModeNodes); - System.out.print(","); - System.out.print(statEntry.replayState); - System.out.println(); + sb.append(statEntry.p); + sb.append(","); + sb.append(statEntry.keyState); + sb.append(","); + sb.append(statEntry.keyTime); + sb.append(","); + sb.append(statEntry.keyNodes); + sb.append(","); + sb.append(statEntry.z3TranslationLines); + sb.append(","); + sb.append(statEntry.translationAndZ3Time); + sb.append(","); + sb.append(statEntry.z3ProofLines); + sb.append(","); + sb.append(statEntry.replayTime); + sb.append(","); + sb.append(statEntry.replayAutoModeTime); + sb.append(","); + sb.append(statEntry.replayNodes); + sb.append(","); + sb.append(statEntry.replayAutoModeNodes); + sb.append(","); + sb.append(statEntry.replayState); + sb.append(System.lineSeparator()); + } + + try { + Files.write(Path.of(outDir + "/statistics.csv"), sb.toString().getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); } } @@ -173,9 +177,9 @@ private static void updateZ3ProvableList() { List dirs = new ArrayList<>(); //dirs.add(exampleDir); dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/newBook/Using_KeY")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/smt")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/standard_key")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeitkey/key/key.ui/examples/firstTouch/")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/smt")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/standard_key")); + dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/firstTouch/")); Files.createDirectories(VALID_LIST_PATH.getParent()); if (!Files.exists(VALID_LIST_PATH)) { From 9fb3910436d1d388a8cd63c97be3077d6c00240e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 16 Apr 2024 21:47:14 +0200 Subject: [PATCH 120/248] remove replay from stats --- .../src/test/java/evaluation/Main.java | 25 ------------------- 1 file changed, 25 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index db43a70e296..a6f275b759d 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -52,11 +52,6 @@ private static class StatEntry { long z3TranslationLines; long translationAndZ3Time; long z3ProofLines; - long replayTime; - long replayAutoModeTime; - int replayAutoModeNodes; - int replayNodes; - ProofState replayState = ProofState.UNKNOWN; StatEntry(Path p) { this.p = p; @@ -118,16 +113,6 @@ private static void saveStatisticsCSV() { sb.append("transl_+_Z3_time"); sb.append(","); sb.append("Z3_proof_lines"); - sb.append(","); - sb.append("replay_time"); - sb.append(","); - sb.append("replay_automode_time"); - sb.append(","); - sb.append("replayed_proof_nodes"); - sb.append(","); - sb.append("replayed_proof_automode_nodes"); - sb.append(","); - sb.append("replay_result"); sb.append(System.lineSeparator()); for (StatEntry statEntry : STATS.values()) { @@ -144,16 +129,6 @@ private static void saveStatisticsCSV() { sb.append(statEntry.translationAndZ3Time); sb.append(","); sb.append(statEntry.z3ProofLines); - sb.append(","); - sb.append(statEntry.replayTime); - sb.append(","); - sb.append(statEntry.replayAutoModeTime); - sb.append(","); - sb.append(statEntry.replayNodes); - sb.append(","); - sb.append(statEntry.replayAutoModeNodes); - sb.append(","); - sb.append(statEntry.replayState); sb.append(System.lineSeparator()); } From 958a812c2b3d3ef36939311c1544d5b2e980945e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 17 Apr 2024 11:07:32 +0200 Subject: [PATCH 121/248] write files down in file crawler --- .../src/test/java/evaluation/Main.java | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index a6f275b759d..b583098e263 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -44,6 +44,8 @@ public class Main { private static Path outDir; + private static boolean skipProvable = false; + private static class StatEntry { final Path p; ProofState keyState = ProofState.UNKNOWN; @@ -75,6 +77,9 @@ public static void main(String[] args) { } if (args.length > 0 && args[0].equals("--create-provable-list")) { + if (args.length > 1) { + skipProvable = Boolean.parseBoolean(args[1]); + } updateZ3ProvableList(); } else { run(); @@ -92,7 +97,7 @@ private static void run() { for (String s : pathStrings) { Path p = Paths.get(s); VALID_SET.add(p); - processFile(p, true, true, true); + processFile(p, true, true, false); } saveStatisticsCSV(); } @@ -161,6 +166,8 @@ private static void updateZ3ProvableList() { Files.createFile(VALID_LIST_PATH); } + StringBuilder sb = new StringBuilder(); + for (Path dir : dirs) { Files.walkFileTree(dir, new FileVisitor() { @@ -173,7 +180,12 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { System.out.println("Visiting " + file.toString()); - processFile(file, false, true, false); + if (file.toString().endsWith(".key")) { + sb.append(System.lineSeparator()).append(file.toAbsolutePath()); + } + if (!skipProvable) { + processFile(file, false, true, false); + } return FileVisitResult.CONTINUE; } @@ -189,6 +201,7 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) return FileVisitResult.CONTINUE; } }); + Files.write(VALID_LIST_PATH, sb.toString().getBytes()); } } catch (OutOfMemoryError e) { e.printStackTrace(); @@ -262,11 +275,6 @@ private static void runZ3ToFile(Path input, boolean tryReplay) return; } - // currently we do not support files with Java programs - if (pm.getProofContracts() == null || !pm.getProofContracts().isEmpty()) { - return; - } - Node n = papi.getFirstOpenGoal().getProofNode(); Proof proof = n.proof(); From c1fb9e9c9312b477b4ceb23b2d3154f2121f73b9 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 17 Apr 2024 11:48:12 +0200 Subject: [PATCH 122/248] run SMT Prep and launch solvers on all goals --- .../src/test/java/evaluation/Main.java | 57 ++++++++++++++++++- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index b583098e263..55c37ebe445 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -5,6 +5,7 @@ import de.uka.ilkd.key.api.ProofManagementApi; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.UserInterfaceControl; +import de.uka.ilkd.key.macros.SMTPreparationMacro; import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.proof.io.ProblemLoaderException; @@ -18,6 +19,7 @@ import de.uka.ilkd.key.strategy.JavaCardDLStrategyFactory; import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; +import org.key_project.util.collection.ImmutableList; import java.io.IOException; import java.io.PrintStream; @@ -157,7 +159,6 @@ private static void updateZ3ProvableList() { List dirs = new ArrayList<>(); //dirs.add(exampleDir); dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/newBook/Using_KeY")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/smt")); dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/standard_key")); dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/firstTouch/")); @@ -180,7 +181,7 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { System.out.println("Visiting " + file.toString()); - if (file.toString().endsWith(".key")) { + if (file.toString().endsWith(".key") && checkNonTrivialNoError(file)) { sb.append(System.lineSeparator()).append(file.toAbsolutePath()); } if (!skipProvable) { @@ -213,6 +214,39 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) } } + private static boolean checkNonTrivialNoError(Path file) { + ProofManagementApi pm = null; + try { + pm = KeYApi.loadFromKeyFile(file.toFile()); + } catch (ProblemLoaderException e) { + return false; + } + ProofApi papi = pm.getLoadedProof(); + + if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { + return false; + } + + Node n = papi.getFirstOpenGoal().getProofNode(); + Proof proof = n.proof(); + + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + if (proof.openGoals().isEmpty()) { + System.out.println("No open goals found after Preparation"); + return false; + } + return true; + } + + private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean tryReplay) { if (input.toString().endsWith(".key")) { try { @@ -278,6 +312,20 @@ private static void runZ3ToFile(Path input, boolean tryReplay) Node n = papi.getFirstOpenGoal().getProofNode(); Proof proof = n.proof(); + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + if (proof.openGoals().isEmpty()) { + System.out.println("No open goals found after Preparation"); + return; + } + //SMTProblem problem = new SMTProblem(n.sequent(), proof.getServices()); SMTProblem problem = new SMTProblem(proof.openGoals().head()); @@ -338,7 +386,10 @@ public void launcherStarted(Collection problems, translationAndZ3Time = System.currentTimeMillis(); } }); - launcher.launch(problem, proof.getServices(), Z3_SOLVER); + List problems = proof.openGoals().stream().map(SMTProblem::new).toList(); + List solverTypes = problems.stream().map((SMTProblem smtProblem) -> Z3_SOLVER).toList(); + + launcher.launch(solverTypes, problems, proof.getServices()); } private static void appendValid(Path keyPath) { From ee43f0bb13ad433499f194e43c7bd4fcea1a3477 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 17 Apr 2024 13:06:35 +0200 Subject: [PATCH 123/248] first attempt at recording stats for each goal --- .../src/test/java/evaluation/Main.java | 155 +++++++++++------- 1 file changed, 95 insertions(+), 60 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 55c37ebe445..21016ab2d65 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -5,7 +5,9 @@ import de.uka.ilkd.key.api.ProofManagementApi; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.UserInterfaceControl; +import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.macros.SMTPreparationMacro; +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.io.ProblemLoaderException; @@ -26,6 +28,7 @@ import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; +import java.util.stream.Stream; import static java.nio.file.StandardOpenOption.APPEND; @@ -39,7 +42,7 @@ public class Main { private static final Set VALID_SET = new HashSet<>(); - private static final Map STATS = new HashMap<>(); + private static final Map> STATS = new HashMap<>(); private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; @@ -122,21 +125,23 @@ private static void saveStatisticsCSV() { sb.append("Z3_proof_lines"); sb.append(System.lineSeparator()); - for (StatEntry statEntry : STATS.values()) { - sb.append(statEntry.p); - sb.append(","); - sb.append(statEntry.keyState); - sb.append(","); - sb.append(statEntry.keyTime); - sb.append(","); - sb.append(statEntry.keyNodes); - sb.append(","); - sb.append(statEntry.z3TranslationLines); - sb.append(","); - sb.append(statEntry.translationAndZ3Time); - sb.append(","); - sb.append(statEntry.z3ProofLines); - sb.append(System.lineSeparator()); + for (Map entryMap : STATS.values()) { + entryMap.forEach((Goal goal, StatEntry entry) -> { + sb.append(entry.p).append(goal.node().name()); + sb.append(","); + sb.append(entry.keyState); + sb.append(","); + sb.append(entry.keyTime); + sb.append(","); + sb.append(entry.keyNodes); + sb.append(","); + sb.append(entry.z3TranslationLines); + sb.append(","); + sb.append(entry.translationAndZ3Time); + sb.append(","); + sb.append(entry.z3ProofLines); + sb.append(System.lineSeparator()); + }); } try { @@ -279,24 +284,41 @@ private static void runeWithKeYAuto(Path input) throws ProblemLoaderException, I proof.getSettings().getStrategySettings().setMaxSteps(1000000); proof.getSettings().getStrategySettings().setTimeout(300000); - long manualTime = System.currentTimeMillis(); - uic.getProofControl().startAndWaitForAutoMode(proof); - manualTime = System.currentTimeMillis() - manualTime; + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + if (proof.openGoals().isEmpty()) { + System.out.println("No open goals found after Preparation"); + return; + } + ImmutableList goals = proof.openGoals(); + + for (Goal g : goals) { + long manualTime = System.currentTimeMillis(); + uic.getProofControl().startAndWaitForAutoMode(proof, ImmutableList.of(g)); + manualTime = System.currentTimeMillis() - manualTime; - int nodes = proof.getStatistics().nodes; - updateKeYNodes(input, nodes); + int nodes = proof.getStatistics().nodes; + updateKeYNodes(input, g, nodes); - long keyTime = proof.getStatistics().autoModeTimeInMillis; - System.out.println(" KeY statistics: " + keyTime); - System.out.println(" Manual logging: " + manualTime); + long keyTime = proof.getStatistics().autoModeTimeInMillis; + System.out.println(" KeY statistics: " + keyTime); + System.out.println(" Manual logging: " + manualTime); - updateKeYState(input, proof.closed() ? ProofState.CLOSED : ProofState.OPEN); - updateKeYTime(input, manualTime); - Path proofPath = getOutPath(input, "_key.proof"); - ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); - saver.save(); + updateKeYState(input, g, (proof.isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); + updateKeYTime(input, g, manualTime); + Path proofPath = getOutPath(input, "_key.proof"); + ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); + saver.save(); - papi.getEnv().dispose(); + papi.getEnv().dispose(); + } } private static void runZ3ToFile(Path input, boolean tryReplay) @@ -312,10 +334,12 @@ private static void runZ3ToFile(Path input, boolean tryReplay) Node n = papi.getFirstOpenGoal().getProofNode(); Proof proof = n.proof(); + UserInterfaceControl uic = new DefaultUserInterfaceControl(); + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { - smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); } catch (Exception e) { e.printStackTrace(); return; @@ -326,15 +350,18 @@ private static void runZ3ToFile(Path input, boolean tryReplay) return; } - //SMTProblem problem = new SMTProblem(n.sequent(), proof.getServices()); - SMTProblem problem = new SMTProblem(proof.openGoals().head()); - SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof.getSettings().getNewSMTSettings(), proof); SolverLauncher launcher = new SolverLauncher(settings); - launcher.addListener(new SolverLauncherListener() { + + class TimedListener implements SolverLauncherListener { long translationAndZ3Time = 0; + Goal goal; + + public TimedListener(Goal g) { + goal = g; + } @Override public void launcherStopped(SolverLauncher launcher, @@ -342,7 +369,10 @@ public void launcherStopped(SolverLauncher launcher, System.out.println("Z3 finished (" + finishedSolvers.size() + " solvers)."); translationAndZ3Time = System.currentTimeMillis() - translationAndZ3Time; - updateZ3Time(input, translationAndZ3Time); + for (SMTSolver solver : finishedSolvers) { + SMTProblem solverProblem = solver.getProblem(); + updateZ3Time(input, goal, translationAndZ3Time); + } // we exactly have that single solver if (finishedSolvers.size() != 1) { @@ -351,7 +381,7 @@ public void launcherStopped(SolverLauncher launcher, SMTSolver z3 = finishedSolvers.iterator().next(); String smtTranslation = z3.getTranslation(); - updateZ3TranslationLines(input, countLines(smtTranslation)); + updateZ3TranslationLines(input, goal, countLines(smtTranslation)); try { Files.write(getOutPath(input, "_translation.smt2"), smtTranslation.getBytes()); } catch (IOException e) { @@ -365,7 +395,7 @@ public void launcherStopped(SolverLauncher launcher, appendValid(input); Path outPath = getOutPath(input, "_proof.smt2"); - updateZ3ProofLines(input, countLines(z3Proof)); + updateZ3ProofLines(input, goal, countLines(z3Proof)); Files.write(outPath, z3Proof.getBytes()); } catch (IOException e) { e.printStackTrace(); @@ -376,6 +406,7 @@ public void launcherStopped(SolverLauncher launcher, System.setOut(STDOUT); System.setErr(STDERR); } + launcher.removeListener(this); } @Override @@ -385,11 +416,15 @@ public void launcherStarted(Collection problems, System.out.println("Running Z3 ..."); translationAndZ3Time = System.currentTimeMillis(); } - }); - List problems = proof.openGoals().stream().map(SMTProblem::new).toList(); - List solverTypes = problems.stream().map((SMTProblem smtProblem) -> Z3_SOLVER).toList(); + } + + Stream problems = proof.openGoals().stream().map(SMTProblem::new); + Services services = proof.getServices(); - launcher.launch(solverTypes, problems, proof.getServices()); + problems.forEach((SMTProblem problem) -> { + launcher.addListener(new TimedListener(problem.getGoal())); + launcher.launch(problem, services, Z3_SOLVER); + }); } private static void appendValid(Path keyPath) { @@ -417,58 +452,58 @@ private static Path getOutPath(Path input, String newExt) { return outDir.resolve(newName); } - private static void updateZ3Time(Path p, long z3Time) { - StatEntry stats = STATS.get(p); + private static void updateZ3Time(Path p, Goal g, long z3Time) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.translationAndZ3Time = z3Time; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } - private static void updateZ3TranslationLines(Path p, long z3TranslationLines) { - StatEntry stats = STATS.get(p); + private static void updateZ3TranslationLines(Path p, Goal g, long z3TranslationLines) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.z3TranslationLines = z3TranslationLines; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } - private static void updateZ3ProofLines(Path p, long z3ProofLines) { - StatEntry stats = STATS.get(p); + private static void updateZ3ProofLines(Path p, Goal g, long z3ProofLines) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.z3ProofLines = z3ProofLines; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } - private static void updateKeYNodes(Path p, int keyNodes) { - StatEntry stats = STATS.get(p); + private static void updateKeYNodes(Path p, Goal g, int keyNodes) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyNodes = keyNodes; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } - private static void updateKeYTime(Path p, long keyTime) { - StatEntry stats = STATS.get(p); + private static void updateKeYTime(Path p, Goal g, long keyTime) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyTime = keyTime; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } - private static void updateKeYState(Path p, ProofState keyState) { - StatEntry stats = STATS.get(p); + private static void updateKeYState(Path p, Goal g, ProofState keyState) { + StatEntry stats = STATS.get(p).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyState = keyState; - STATS.put(p, stats); + STATS.get(p).put(g, stats); } } From 48b960e7cbd8f8dae7055b5954afc6b48c7214f2 Mon Sep 17 00:00:00 2001 From: BookWood Date: Wed, 17 Apr 2024 15:51:18 +0200 Subject: [PATCH 124/248] message improvement add timeout for valid file search --- .../src/test/java/evaluation/Main.java | 93 ++++++++++++++----- 1 file changed, 71 insertions(+), 22 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 21016ab2d65..dffcd18d8aa 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -1,5 +1,7 @@ package evaluation; +import com.google.common.util.concurrent.SimpleTimeLimiter; +import com.google.common.util.concurrent.TimeLimiter; import de.uka.ilkd.key.api.KeYApi; import de.uka.ilkd.key.api.ProofApi; import de.uka.ilkd.key.api.ProofManagementApi; @@ -22,12 +24,18 @@ import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; import org.key_project.util.collection.ImmutableList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import scala.Int; import java.io.IOException; import java.io.PrintStream; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import static java.nio.file.StandardOpenOption.APPEND; @@ -51,6 +59,8 @@ public class Main { private static boolean skipProvable = false; + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + private static class StatEntry { final Path p; ProofState keyState = ProofState.UNKNOWN; @@ -112,6 +122,8 @@ private static void saveStatisticsCSV() { sb.append("input_file"); sb.append(","); + sb.append("goalNodeName"); + sb.append(","); sb.append("KeY_state"); sb.append(","); sb.append("KeY_time"); @@ -127,7 +139,9 @@ private static void saveStatisticsCSV() { for (Map entryMap : STATS.values()) { entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p).append(goal.node().name()); + sb.append(entry.p); + sb.append(","); + sb.append(goal.node().name()); sb.append(","); sb.append(entry.keyState); sb.append(","); @@ -163,17 +177,13 @@ private static void updateZ3ProvableList() { loadValidSet(); List dirs = new ArrayList<>(); //dirs.add(exampleDir); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/newBook/Using_KeY")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/standard_key")); - dirs.add(Paths.get("D:/Uni/Bachelor-Arbeit/key/key.ui/examples/firstTouch/")); + dirs.add(Paths.get("C:/Users/nilsb/Documents/Uni/Bachelor-Arbeit/key/key.ui/examples")); Files.createDirectories(VALID_LIST_PATH.getParent()); if (!Files.exists(VALID_LIST_PATH)) { Files.createFile(VALID_LIST_PATH); } - StringBuilder sb = new StringBuilder(); - for (Path dir : dirs) { Files.walkFileTree(dir, new FileVisitor() { @@ -186,8 +196,8 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { System.out.println("Visiting " + file.toString()); - if (file.toString().endsWith(".key") && checkNonTrivialNoError(file)) { - sb.append(System.lineSeparator()).append(file.toAbsolutePath()); + if (file.toString().endsWith(".key") && checkNonTrivialNoErrorQuickLoad(file)) { + appendValid(file.toAbsolutePath()); } if (!skipProvable) { processFile(file, false, true, false); @@ -207,7 +217,6 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) return FileVisitResult.CONTINUE; } }); - Files.write(VALID_LIST_PATH, sb.toString().getBytes()); } } catch (OutOfMemoryError e) { e.printStackTrace(); @@ -219,14 +228,34 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) } } - private static boolean checkNonTrivialNoError(Path file) { - ProofManagementApi pm = null; + private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { + AtomicReference pm = new AtomicReference<>(); + AtomicBoolean success = new AtomicBoolean(false); + Runnable task = () -> { + try { + pm.set(KeYApi.loadFromKeyFile(file.toFile())); + success.set(true); + } catch (ProblemLoaderException e) { + success.set(false); + } + }; + ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); + + TimeLimiter tl = SimpleTimeLimiter.create(executorService); try { - pm = KeYApi.loadFromKeyFile(file.toFile()); - } catch (ProblemLoaderException e) { + tl.runWithTimeout(task, 60000, TimeUnit.MILLISECONDS); + } catch (TimeoutException | InterruptedException e) { + LOGGER.error("Load timeout {}", file); return false; } - ProofApi papi = pm.getLoadedProof(); + if (!success.get()) { + LOGGER.error("Load failed {}", file); + return false; + } + + + LOGGER.info("Loaded {}", file); + ProofApi papi = pm.get().getLoadedProof(); if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { return false; @@ -235,17 +264,37 @@ private static boolean checkNonTrivialNoError(Path file) { Node n = papi.getFirstOpenGoal().getProofNode(); Proof proof = n.proof(); - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - } catch (Exception e) { - e.printStackTrace(); - return false; + + Runnable prep = () -> { + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + LOGGER.info("Prep done {}", file); + success.set(true); + } catch (Exception e) { + e.printStackTrace(); + success.set(false); + } + } else { + LOGGER.error("Prep failed {}", file); + success.set(false); } + }; + + try { + tl.runWithTimeout(prep, 60, TimeUnit.SECONDS); + } catch (TimeoutException | InterruptedException e) { + LOGGER.error("Prep timeout {}", file); + return false; } + if (!success.get()) { + LOGGER.error("Prep failed {}", file); + return false; + } + if (proof.openGoals().isEmpty()) { - System.out.println("No open goals found after Preparation"); + LOGGER.error("No open goals found after Preparation {}", file); return false; } return true; From bed3a441a90215408b83fe70d5ba9b047ef990be Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 17 Apr 2024 22:57:45 +0200 Subject: [PATCH 125/248] evaluation now works for KeY and Z3 --- .../src/test/java/evaluation/Main.java | 347 ++++++++++++------ 1 file changed, 241 insertions(+), 106 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index dffcd18d8aa..3f36dc6a4ba 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -12,6 +12,7 @@ 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.io.ProblemLoaderException; import de.uka.ilkd.key.proof.io.ProofSaver; import de.uka.ilkd.key.settings.DefaultSMTSettings; @@ -20,13 +21,13 @@ import de.uka.ilkd.key.smt.solvertypes.SolverType; import de.uka.ilkd.key.smt.solvertypes.SolverTypeImplementation; import de.uka.ilkd.key.smt.solvertypes.SolverTypes; +import de.uka.ilkd.key.speclang.Contract; import de.uka.ilkd.key.strategy.JavaCardDLStrategyFactory; import de.uka.ilkd.key.strategy.Strategy; import de.uka.ilkd.key.strategy.StrategyProperties; import org.key_project.util.collection.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import scala.Int; import java.io.IOException; import java.io.PrintStream; @@ -50,7 +51,7 @@ public class Main { private static final Set VALID_SET = new HashSet<>(); - private static final Map> STATS = new HashMap<>(); + private static final Map>> STATS = new HashMap<>(); private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; @@ -69,6 +70,7 @@ private static class StatEntry { long z3TranslationLines; long translationAndZ3Time; long z3ProofLines; + SMTSolverResult.ThreeValuedTruth z3State; StatEntry(Path p) { this.p = p; @@ -122,6 +124,8 @@ private static void saveStatisticsCSV() { sb.append("input_file"); sb.append(","); + sb.append("contractName"); + sb.append(","); sb.append("goalNodeName"); sb.append(","); sb.append("KeY_state"); @@ -135,26 +139,34 @@ private static void saveStatisticsCSV() { sb.append("transl_+_Z3_time"); sb.append(","); sb.append("Z3_proof_lines"); + sb.append(","); + sb.append("Z3_State"); sb.append(System.lineSeparator()); - for (Map entryMap : STATS.values()) { - entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p); - sb.append(","); - sb.append(goal.node().name()); - sb.append(","); - sb.append(entry.keyState); - sb.append(","); - sb.append(entry.keyTime); - sb.append(","); - sb.append(entry.keyNodes); - sb.append(","); - sb.append(entry.z3TranslationLines); - sb.append(","); - sb.append(entry.translationAndZ3Time); - sb.append(","); - sb.append(entry.z3ProofLines); - sb.append(System.lineSeparator()); + for (Map> contractMap : STATS.values()) { + contractMap.forEach((Contract c, Map entryMap) -> { + entryMap.forEach((Goal goal, StatEntry entry) -> { + sb.append(entry.p); + sb.append(","); + sb.append(c.getDisplayName()); + sb.append(","); + sb.append(goal.getTime()); + sb.append(","); + sb.append(entry.keyState); + sb.append(","); + sb.append(entry.keyTime); + sb.append(","); + sb.append(entry.keyNodes); + sb.append(","); + sb.append(entry.z3TranslationLines); + sb.append(","); + sb.append(entry.translationAndZ3Time); + sb.append(","); + sb.append(entry.z3ProofLines); + sb.append(","); + sb.append(entry.z3State); + sb.append(System.lineSeparator()); + }); }); } @@ -177,7 +189,7 @@ private static void updateZ3ProvableList() { loadValidSet(); List dirs = new ArrayList<>(); //dirs.add(exampleDir); - dirs.add(Paths.get("C:/Users/nilsb/Documents/Uni/Bachelor-Arbeit/key/key.ui/examples")); + dirs.add(Paths.get(System.getProperty("user.home") + "/Desktop/examples")); Files.createDirectories(VALID_LIST_PATH.getParent()); if (!Files.exists(VALID_LIST_PATH)) { @@ -230,13 +242,13 @@ public FileVisitResult postVisitDirectory(Path dir, IOException exc) private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { AtomicReference pm = new AtomicReference<>(); - AtomicBoolean success = new AtomicBoolean(false); + AtomicBoolean success = new AtomicBoolean(true); Runnable task = () -> { try { pm.set(KeYApi.loadFromKeyFile(file.toFile())); success.set(true); } catch (ProblemLoaderException e) { - success.set(false); + LOGGER.error("Load error {}", e.getMessage()); } }; ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); @@ -248,19 +260,25 @@ private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { LOGGER.error("Load timeout {}", file); return false; } - if (!success.get()) { + if (!success.get() || pm.get() == null) { LOGGER.error("Load failed {}", file); return false; } - LOGGER.info("Loaded {}", file); ProofApi papi = pm.get().getLoadedProof(); if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { - return false; + for (Contract contract : pm.get().getProofContracts()) { + if (!checkTrivialNoErrorQuickLoadContract(file, contract, pm.get(), tl)) { + return false; + } + } + return true; } + LOGGER.info("Loaded {}", file); + Node n = papi.getFirstOpenGoal().getProofNode(); Proof proof = n.proof(); @@ -300,29 +318,129 @@ private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { return true; } + private static boolean checkTrivialNoErrorQuickLoadContract(Path file, Contract contract, ProofManagementApi pm, TimeLimiter tl) { + ProofApi papi; + try { + papi = pm.startProof(contract); + } catch (ProofInputException e) { + e.printStackTrace(); + LOGGER.error("Failed to load contract: " + contract.getDisplayName()); + return false; + } + + Node n = papi.getFirstOpenGoal().getProofNode(); + Proof proof = n.proof(); + + + AtomicBoolean success = new AtomicBoolean(true); + + Runnable prep = () -> { + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + LOGGER.info("Prep done {}", file); + success.set(true); + } catch (Exception e) { + e.printStackTrace(); + success.set(false); + } + } else { + LOGGER.error("Prep failed {}", file); + success.set(false); + } + }; + + try { + tl.runWithTimeout(prep, 60, TimeUnit.SECONDS); + } catch (TimeoutException | InterruptedException e) { + LOGGER.error("Prep timeout {}", file); + return false; + } + if (!success.get()) { + LOGGER.error("Prep failed {}", file); + return false; + } + return true; + } + private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean tryReplay) { if (input.toString().endsWith(".key")) { + ProofApi papi = null; try { System.out.println("Processing " + input.toString()); + ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); + papi = pm.getLoadedProof(); + + if (papi.getProof() == null) { + for (Contract contract : pm.getProofContracts()) { + processContract(pm, contract, input, runKeY, runZ3); + } + return; + } + + Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); + UserInterfaceControl uic = new DefaultUserInterfaceControl(); + + // this should initialize with the default properties, + // necessary to enable quantifier instantiation + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + proof.getSettings().getStrategySettings().setMaxSteps(1000000); + proof.getSettings().getStrategySettings().setTimeout(100000); + + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { + try { + smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + } catch (Exception e) { + e.printStackTrace(); + return; + } + } + if (proof.openGoals().isEmpty()) { + System.out.println("No open goals found after Preparation"); + return; + } + ImmutableList goals = proof.openGoals(); + + + STATS.put(input, new HashMap<>()); + STATS.get(input).put(null, new HashMap<>()); + + if (runKeY) { - runeWithKeYAuto(input); + runWithKeYAuto(input, null, goals); } - if (tryReplay) { - runZ3ToFile(input, true); - } else if (runZ3) { - runZ3ToFile(input, false); + if (runZ3) { + runZ3ToFile(input, null, goals, false); } + papi.getEnv().dispose(); } catch (ProblemLoaderException | IOException e) { e.printStackTrace(); + } finally { + if (papi != null) { + papi.getEnv().dispose(); + } } } } - private static void runeWithKeYAuto(Path input) throws ProblemLoaderException, IOException { - ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); - ProofApi papi = pm.getLoadedProof(); - Proof proof = papi.getProof(); + private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3) throws IOException, ProblemLoaderException { + System.out.println("Processing contract " + contract.getDisplayName() + " of " + input); + + ProofApi papi = null; + try { + papi = pm.startProof(contract); + } catch (ProofInputException e) { + e.printStackTrace(); + LOGGER.error("Problem starting proof {}", e.getMessage()); + return; + } + + Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); // this should initialize with the default properties, @@ -331,7 +449,7 @@ private static void runeWithKeYAuto(Path input) throws ProblemLoaderException, I Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); proof.setActiveStrategy(strategy); proof.getSettings().getStrategySettings().setMaxSteps(1000000); - proof.getSettings().getStrategySettings().setTimeout(300000); + proof.getSettings().getStrategySettings().setTimeout(100000); SMTPreparationMacro smtMacro = new SMTPreparationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { @@ -348,68 +466,72 @@ private static void runeWithKeYAuto(Path input) throws ProblemLoaderException, I } ImmutableList goals = proof.openGoals(); + + STATS.put(input, new HashMap<>()); + STATS.get(input).put(contract, new HashMap<>()); + + + if (runZ3) { + runZ3ToFile(input, contract, goals, false); + } + if (runKeY) { + runWithKeYAuto(input, contract, goals); + } + papi.getEnv().dispose(); + } + + private static void runWithKeYAuto(Path input, Contract contract, ImmutableList goals) throws ProblemLoaderException, IOException { + Proof proof = goals.stream().findFirst().get().proof(); + UserInterfaceControl uic = new DefaultUserInterfaceControl(); + + // this should initialize with the default properties, + // necessary to enable quantifier instantiation + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + proof.getSettings().getStrategySettings().setMaxSteps(1000000); + proof.getSettings().getStrategySettings().setTimeout(1000); + for (Goal g : goals) { + long goalTime = g.getTime(); + long manualTime = System.currentTimeMillis(); - uic.getProofControl().startAndWaitForAutoMode(proof, ImmutableList.of(g)); + uic.getProofControl().startFocussedAutoMode(null, g); + uic.getProofControl().waitWhileAutoMode(); manualTime = System.currentTimeMillis() - manualTime; - int nodes = proof.getStatistics().nodes; - updateKeYNodes(input, g, nodes); + int nodes = g.proof().getStatistics().nodes; + updateKeYNodes(input, contract, g, nodes); - long keyTime = proof.getStatistics().autoModeTimeInMillis; + long keyTime = g.proof().getStatistics().autoModeTimeInMillis; System.out.println(" KeY statistics: " + keyTime); System.out.println(" Manual logging: " + manualTime); - updateKeYState(input, g, (proof.isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); - updateKeYTime(input, g, manualTime); - Path proofPath = getOutPath(input, "_key.proof"); - ProofSaver saver = new ProofSaver(proof, proofPath.toFile()); + updateKeYState(input, contract, g, !(g.proof().isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); + updateKeYTime(input, contract, g, manualTime); + Path proofPath = getOutPath(input, goalTime + "_key.proof"); + ProofSaver saver = new ProofSaver(g.proof(), proofPath.toFile()); saver.save(); - - papi.getEnv().dispose(); } } - private static void runZ3ToFile(Path input, boolean tryReplay) + private static void runZ3ToFile(Path input, Contract contract, ImmutableList goals, boolean tryReplay) throws ProblemLoaderException, IOException { - ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); - ProofApi papi = pm.getLoadedProof(); - - if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { - return; - } - - Node n = papi.getFirstOpenGoal().getProofNode(); - Proof proof = n.proof(); - - UserInterfaceControl uic = new DefaultUserInterfaceControl(); - - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - } catch (Exception e) { - e.printStackTrace(); - return; - } - } - if (proof.openGoals().isEmpty()) { - System.out.println("No open goals found after Preparation"); - return; - } + Proof proof = goals.stream().findFirst().get().proof(); SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof.getSettings().getNewSMTSettings(), proof); - SolverLauncher launcher = new SolverLauncher(settings); class TimedListener implements SolverLauncherListener { long translationAndZ3Time = 0; Goal goal; + long goalNumber; - public TimedListener(Goal g) { + public TimedListener(Goal g, long goalNumber) { goal = g; + this.goalNumber = goalNumber; } @Override @@ -420,7 +542,7 @@ public void launcherStopped(SolverLauncher launcher, translationAndZ3Time = System.currentTimeMillis() - translationAndZ3Time; for (SMTSolver solver : finishedSolvers) { SMTProblem solverProblem = solver.getProblem(); - updateZ3Time(input, goal, translationAndZ3Time); + updateZ3Time(input, contract, goal, translationAndZ3Time); } // we exactly have that single solver @@ -430,27 +552,24 @@ public void launcherStopped(SolverLauncher launcher, SMTSolver z3 = finishedSolvers.iterator().next(); String smtTranslation = z3.getTranslation(); - updateZ3TranslationLines(input, goal, countLines(smtTranslation)); + updateZ3TranslationLines(input, contract, goal, countLines(smtTranslation)); try { - Files.write(getOutPath(input, "_translation.smt2"), smtTranslation.getBytes()); + Files.write(getOutPath(input, goalNumber + "_translation.smt"), smtTranslation.getBytes()); } catch (IOException e) { e.printStackTrace(); } String z3Proof = z3.getRawSolverOutput(); + + updateZ3State(input, contract, goal, z3.getFinalResult().isValid()); if (z3.getFinalResult().isValid() == SMTSolverResult.ThreeValuedTruth.VALID) { try { - appendValid(input); - - Path outPath = getOutPath(input, "_proof.smt2"); - updateZ3ProofLines(input, goal, countLines(z3Proof)); + Path outPath = getOutPath(input, goalNumber + "_proof.smt2"); + updateZ3ProofLines(input, contract, goal, countLines(z3Proof)); Files.write(outPath, z3Proof.getBytes()); } catch (IOException e) { e.printStackTrace(); - } finally { - // try to avoid memory leaks - papi.getEnv().dispose(); } System.setOut(STDOUT); System.setErr(STDERR); @@ -462,16 +581,17 @@ public void launcherStopped(SolverLauncher launcher, public void launcherStarted(Collection problems, Collection solverTypes, SolverLauncher launcher) { - System.out.println("Running Z3 ..."); translationAndZ3Time = System.currentTimeMillis(); + System.out.println("Running Z3 ..." + translationAndZ3Time); } } - Stream problems = proof.openGoals().stream().map(SMTProblem::new); + Stream problems = goals.stream().map(SMTProblem::new); Services services = proof.getServices(); problems.forEach((SMTProblem problem) -> { - launcher.addListener(new TimedListener(problem.getGoal())); + SolverLauncher launcher = new SolverLauncher(settings); + launcher.addListener(new TimedListener(problem.getGoal(), problem.getGoal().getTime())); launcher.launch(problem, services, Z3_SOLVER); }); } @@ -493,7 +613,12 @@ private static long countLines(String input) { private static Path getOutPath(Path input, String newExt) { String origFileName = input.getFileName().toString(); - String name = origFileName.substring(0, origFileName.lastIndexOf('.')); + String name; + if (origFileName.contains(".")) { + name = origFileName.substring(0, origFileName.lastIndexOf('.')); + } else { + name = origFileName; + } String prefixedName = input.getName(input.getNameCount() - 3) + "_" + input.getName(input.getNameCount() - 2) + "_" + name; @@ -501,58 +626,68 @@ private static Path getOutPath(Path input, String newExt) { return outDir.resolve(newName); } - private static void updateZ3Time(Path p, Goal g, long z3Time) { - StatEntry stats = STATS.get(p).get(g); + private static void updateZ3Time(Path p, Contract c, Goal g, long z3Time) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.translationAndZ3Time = z3Time; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); + } + + + private static void updateZ3State(Path p, Contract c, Goal g, SMTSolverResult.ThreeValuedTruth valid) { + StatEntry stats = STATS.get(p).get(c).get(g); + if (stats == null) { + stats = new StatEntry(p); + } + stats.z3State = valid; + STATS.get(p).get(c).put(g, stats); } - private static void updateZ3TranslationLines(Path p, Goal g, long z3TranslationLines) { - StatEntry stats = STATS.get(p).get(g); + private static void updateZ3TranslationLines(Path p, Contract c, Goal g, long z3TranslationLines) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.z3TranslationLines = z3TranslationLines; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); } - private static void updateZ3ProofLines(Path p, Goal g, long z3ProofLines) { - StatEntry stats = STATS.get(p).get(g); + private static void updateZ3ProofLines(Path p, Contract c, Goal g, long z3ProofLines) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.z3ProofLines = z3ProofLines; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); } - private static void updateKeYNodes(Path p, Goal g, int keyNodes) { - StatEntry stats = STATS.get(p).get(g); + private static void updateKeYNodes(Path p, Contract c, Goal g, int keyNodes) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyNodes = keyNodes; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); } - private static void updateKeYTime(Path p, Goal g, long keyTime) { - StatEntry stats = STATS.get(p).get(g); + private static void updateKeYTime(Path p, Contract c, Goal g, long keyTime) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyTime = keyTime; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); } - private static void updateKeYState(Path p, Goal g, ProofState keyState) { - StatEntry stats = STATS.get(p).get(g); + private static void updateKeYState(Path p, Contract c, Goal g, ProofState keyState) { + StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } stats.keyState = keyState; - STATS.get(p).put(g, stats); + STATS.get(p).get(c).put(g, stats); } } From 368cd48cd7d8df2828e9958b56a9d7dd64433b0c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 02:07:51 +0200 Subject: [PATCH 126/248] fixes statistics save --- .../src/test/java/evaluation/Main.java | 100 +++++++++--------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 3f36dc6a4ba..098852c4201 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -51,7 +51,7 @@ public class Main { private static final Set VALID_SET = new HashSet<>(); - private static final Map>> STATS = new HashMap<>(); + private static final Map>> STATS = new HashMap<>(); private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; @@ -104,7 +104,7 @@ public static void main(String[] args) { } private static void run() { - List pathStrings = null; + List pathStrings; try { pathStrings = Files.readAllLines(VALID_LIST_PATH); } catch (IOException e) { @@ -115,6 +115,7 @@ private static void run() { Path p = Paths.get(s); VALID_SET.add(p); processFile(p, true, true, false); + saveStatisticsCSV(); } saveStatisticsCSV(); } @@ -143,31 +144,29 @@ private static void saveStatisticsCSV() { sb.append("Z3_State"); sb.append(System.lineSeparator()); - for (Map> contractMap : STATS.values()) { - contractMap.forEach((Contract c, Map entryMap) -> { - entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p); - sb.append(","); - sb.append(c.getDisplayName()); - sb.append(","); - sb.append(goal.getTime()); - sb.append(","); - sb.append(entry.keyState); - sb.append(","); - sb.append(entry.keyTime); - sb.append(","); - sb.append(entry.keyNodes); - sb.append(","); - sb.append(entry.z3TranslationLines); - sb.append(","); - sb.append(entry.translationAndZ3Time); - sb.append(","); - sb.append(entry.z3ProofLines); - sb.append(","); - sb.append(entry.z3State); - sb.append(System.lineSeparator()); - }); - }); + for (Map> contractMap : STATS.values()) { + contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { + sb.append(entry.p); + sb.append(","); + sb.append(c); + sb.append(","); + sb.append(goal.getTime()); + sb.append(","); + sb.append(entry.keyState); + sb.append(","); + sb.append(entry.keyTime); + sb.append(","); + sb.append(entry.keyNodes); + sb.append(","); + sb.append(entry.z3TranslationLines); + sb.append(","); + sb.append(entry.translationAndZ3Time); + sb.append(","); + sb.append(entry.z3ProofLines); + sb.append(","); + sb.append(entry.z3State); + sb.append(System.lineSeparator()); + })); } try { @@ -197,7 +196,7 @@ private static void updateZ3ProvableList() { } for (Path dir : dirs) { - Files.walkFileTree(dir, new FileVisitor() { + Files.walkFileTree(dir, new FileVisitor<>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) @@ -369,7 +368,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole if (input.toString().endsWith(".key")) { ProofApi papi = null; try { - System.out.println("Processing " + input.toString()); + System.out.println("Processing " + input); ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); papi = pm.getLoadedProof(); @@ -410,13 +409,12 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole STATS.put(input, new HashMap<>()); STATS.get(input).put(null, new HashMap<>()); - - if (runKeY) { - runWithKeYAuto(input, null, goals); - } if (runZ3) { runZ3ToFile(input, null, goals, false); } + if (runKeY) { + runWithKeYAuto(input, null, goals); + } papi.getEnv().dispose(); } catch (ProblemLoaderException | IOException e) { e.printStackTrace(); @@ -429,7 +427,8 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole } private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3) throws IOException, ProblemLoaderException { - System.out.println("Processing contract " + contract.getDisplayName() + " of " + input); + String contractName = (contract != null) ? contract.getDisplayName() : ""; + System.out.println("Processing contract " + contractName + " of " + input); ProofApi papi = null; try { @@ -468,7 +467,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa STATS.put(input, new HashMap<>()); - STATS.get(input).put(contract, new HashMap<>()); + STATS.get(input).put(contract.getDisplayName(), new HashMap<>()); if (runZ3) { @@ -483,6 +482,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa private static void runWithKeYAuto(Path input, Contract contract, ImmutableList goals) throws ProblemLoaderException, IOException { Proof proof = goals.stream().findFirst().get().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); + String contractName = (contract != null) ? contract.getDisplayName() : ""; // this should initialize with the default properties, // necessary to enable quantifier instantiation @@ -501,14 +501,14 @@ private static void runWithKeYAuto(Path input, Contract contract, ImmutableList< manualTime = System.currentTimeMillis() - manualTime; int nodes = g.proof().getStatistics().nodes; - updateKeYNodes(input, contract, g, nodes); + updateKeYNodes(input, contractName, g, nodes); long keyTime = g.proof().getStatistics().autoModeTimeInMillis; System.out.println(" KeY statistics: " + keyTime); System.out.println(" Manual logging: " + manualTime); - updateKeYState(input, contract, g, !(g.proof().isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); - updateKeYTime(input, contract, g, manualTime); + updateKeYState(input, contractName, g, !(g.proof().isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); + updateKeYTime(input, contractName, g, manualTime); Path proofPath = getOutPath(input, goalTime + "_key.proof"); ProofSaver saver = new ProofSaver(g.proof(), proofPath.toFile()); saver.save(); @@ -523,6 +523,8 @@ private static void runZ3ToFile(Path input, Contract contract, ImmutableList Date: Thu, 18 Apr 2024 10:52:20 +0200 Subject: [PATCH 127/248] fix csv --- .../src/test/java/evaluation/Main.java | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 098852c4201..9f2c7a2429f 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -12,6 +12,7 @@ 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.Statistics; import de.uka.ilkd.key.proof.init.ProofInputException; import de.uka.ilkd.key.proof.io.ProblemLoaderException; import de.uka.ilkd.key.proof.io.ProofSaver; @@ -148,7 +149,7 @@ private static void saveStatisticsCSV() { contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { sb.append(entry.p); sb.append(","); - sb.append(c); + sb.append(c.replace(",", "_")); sb.append(","); sb.append(goal.getTime()); sb.append(","); @@ -171,6 +172,7 @@ private static void saveStatisticsCSV() { try { Files.write(Path.of(outDir + "/statistics.csv"), sb.toString().getBytes()); + LOGGER.info("Statistics CSV written to {}", outDir); } catch (IOException e) { throw new RuntimeException(e); } @@ -407,13 +409,13 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole STATS.put(input, new HashMap<>()); - STATS.get(input).put(null, new HashMap<>()); + STATS.get(input).put("", new HashMap<>()); if (runZ3) { - runZ3ToFile(input, null, goals, false); + runZ3ToFile(input, "", goals, false); } if (runKeY) { - runWithKeYAuto(input, null, goals); + runWithKeYAuto(input, "", goals); } papi.getEnv().dispose(); } catch (ProblemLoaderException | IOException e) { @@ -427,9 +429,6 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole } private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3) throws IOException, ProblemLoaderException { - String contractName = (contract != null) ? contract.getDisplayName() : ""; - System.out.println("Processing contract " + contractName + " of " + input); - ProofApi papi = null; try { papi = pm.startProof(contract); @@ -442,6 +441,9 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); + String contractName = proof.name().toString(); + System.out.println("Processing contract " + contractName + " of " + input); + // this should initialize with the default properties, // necessary to enable quantifier instantiation StrategyProperties properties = new StrategyProperties(); @@ -467,22 +469,21 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa STATS.put(input, new HashMap<>()); - STATS.get(input).put(contract.getDisplayName(), new HashMap<>()); + STATS.get(input).put(proof.name().toString(), new HashMap<>()); if (runZ3) { - runZ3ToFile(input, contract, goals, false); + runZ3ToFile(input, proof.name().toString(), goals, false); } if (runKeY) { - runWithKeYAuto(input, contract, goals); + runWithKeYAuto(input, proof.name().toString(), goals); } papi.getEnv().dispose(); } - private static void runWithKeYAuto(Path input, Contract contract, ImmutableList goals) throws ProblemLoaderException, IOException { + private static void runWithKeYAuto(Path input, String contractName, ImmutableList goals) throws ProblemLoaderException, IOException { Proof proof = goals.stream().findFirst().get().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); - String contractName = (contract != null) ? contract.getDisplayName() : ""; // this should initialize with the default properties, // necessary to enable quantifier instantiation @@ -493,6 +494,7 @@ private static void runWithKeYAuto(Path input, Contract contract, ImmutableList< proof.getSettings().getStrategySettings().setTimeout(1000); for (Goal g : goals) { + int nodes = -g.proof().getStatistics().nodes; long goalTime = g.getTime(); long manualTime = System.currentTimeMillis(); @@ -500,10 +502,12 @@ private static void runWithKeYAuto(Path input, Contract contract, ImmutableList< uic.getProofControl().waitWhileAutoMode(); manualTime = System.currentTimeMillis() - manualTime; - int nodes = g.proof().getStatistics().nodes; + Statistics statistics = g.proof().getStatistics(); + + nodes += statistics.nodes; updateKeYNodes(input, contractName, g, nodes); - long keyTime = g.proof().getStatistics().autoModeTimeInMillis; + long keyTime = statistics.autoModeTimeInMillis; System.out.println(" KeY statistics: " + keyTime); System.out.println(" Manual logging: " + manualTime); @@ -515,7 +519,7 @@ private static void runWithKeYAuto(Path input, Contract contract, ImmutableList< } } - private static void runZ3ToFile(Path input, Contract contract, ImmutableList goals, boolean tryReplay) + private static void runZ3ToFile(Path input, String contractName, ImmutableList goals, boolean tryReplay) throws ProblemLoaderException, IOException { Proof proof = goals.stream().findFirst().get().proof(); @@ -523,8 +527,6 @@ private static void runZ3ToFile(Path input, Contract contract, ImmutableList Date: Thu, 18 Apr 2024 12:27:36 +0200 Subject: [PATCH 128/248] add timeout and listeners to IsabelleProblem --- .../isabelletranslation/IsabelleProblem.java | 138 ++++++++++++++++-- .../IsabelleSolverListener.java | 29 ++++ .../TranslationAction.java | 2 +- 3 files changed, 153 insertions(+), 16 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 12eee3f6cfc..6a005a6f8b2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -14,6 +14,8 @@ import java.nio.file.Path; import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; public class IsabelleProblem { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); @@ -21,6 +23,7 @@ public class IsabelleProblem { private SledgehammerResult result = null; private final String preamble; private final String sequentTranslation; + private Collection listeners = new HashSet<>(); public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { this.goal = goal; @@ -28,6 +31,10 @@ public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { this.sequentTranslation = sequentTranslation; } + public void addListener(IsabelleSolverListener listener) { + listeners.add(listener); + } + public Goal getGoal() { return goal; } @@ -44,13 +51,15 @@ public SledgehammerResult getResult() { return result; } - public SledgehammerResult sledgehammer() { + public SledgehammerResult sledgehammer(int timeout_seconds) { LOGGER.info("Starting Isabelle..."); + notifyProcessStarted(); IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); Isabelle isabelle; ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); + notifyBuildingStarted(); try { Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", JIsabelle.setupSetSessionRoots(sessionRoots, @@ -59,6 +68,8 @@ public SledgehammerResult sledgehammer() { isabelle = new Isabelle(setup); } catch (Exception e) { LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); + notifyBuildingError(e); + notifyProcessError(e); return null; } @@ -66,6 +77,7 @@ public SledgehammerResult sledgehammer() { Theory thy0 = beginTheory(getSequentTranslation(), Path.of((settings.getTranslationPath() + "\\Translation.thy")), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); + notifyBuildingFinished(); MLFunction2>> parse_text = MLValue.compileFunction(""" fn (thy, text) => let @@ -84,18 +96,25 @@ in addtext (Symbol.explode text) transitions end""", isabelle, LOGGER.info("Parsing theory..."); - java.util.List> transitionsAndTexts = new ArrayList<>(); - parse_text.apply(thy0, getSequentTranslation(), isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) - .foreach(transitionsAndTexts::add); - - for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") - toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) - .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + notifyParsingStarted(); + try { + java.util.List> transitionsAndTexts = new ArrayList<>(); + parse_text.apply(thy0, getSequentTranslation(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) + .foreach(transitionsAndTexts::add); + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } + } catch (Exception e) { + notifyParsingError(e); + return null; } + notifyParsingFinished(); LOGGER.info("Finished Parsing"); String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); @@ -125,8 +144,8 @@ fun go_run (state, thy) = .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) end; in - Timeout.apply (Time.fromSeconds 35) go_run (state, thy) end - """, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + Timeout.apply (Time.fromSeconds\s + """ + timeout_seconds + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); @@ -136,6 +155,7 @@ fun go_run (state, thy) = SledgehammerResult result; LOGGER.info("Sledgehammering..."); + notifySledgehammerStarted(); try { result = new SledgehammerResult(normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), @@ -143,8 +163,17 @@ fun go_run (state, thy) = .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)); } catch (Exception exception) { result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); + if (exception.getMessage().equals("timeout")) { + notifyProcessTimeout(); + } else { + notifySledgehammerError(exception); + notifyProcessError(exception); + } + } finally { + notifySledgehammerFinished(); + notifyProcessFinished(); + isabelle.destroy(); } - isabelle.destroy(); LOGGER.info("Sledgehammer result: " + result); return this.result = result; @@ -164,4 +193,83 @@ private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } + + + private void notifyParsingStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.parsingStarted(this); + } + } + + private void notifyParsingFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.parsingFinished(this); + } + } + + private void notifyParsingError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.parsingFailed(this, e); + } + } + + private void notifyBuildingStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.buildingStarted(this); + } + } + + private void notifyBuildingFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.buildingFinished(this); + } + } + + private void notifyBuildingError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.buildingFailed(this, e); + } + } + + private void notifyProcessStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.processStarted(this); + } + } + + private void notifyProcessFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.processStopped(this); + } + } + + private void notifyProcessError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.processInterrupted(this, e); + } + } + + private void notifyProcessTimeout() { + for (IsabelleSolverListener listener : listeners) { + listener.processTimeout(this); + } + } + + private void notifySledgehammerStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.sledgehammerStarted(this); + } + } + + private void notifySledgehammerFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.sledgehammerFinished(this); + } + } + + private void notifySledgehammerError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.sledgeHammerFailed(this, e); + } + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java new file mode 100644 index 00000000000..5c7a45691f6 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java @@ -0,0 +1,29 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +public interface IsabelleSolverListener { + void parsingStarted(IsabelleProblem problem); + + void parsingFinished(IsabelleProblem problem); + + void parsingFailed(IsabelleProblem problem, Exception e); + + void buildingStarted(IsabelleProblem problem); + + void buildingFinished(IsabelleProblem problem); + + void buildingFailed(IsabelleProblem problem, Exception e); + + void processStarted(IsabelleProblem problem); + + void processInterrupted(IsabelleProblem problem, Exception e); + + void processStopped(IsabelleProblem problem); + + void processTimeout(IsabelleProblem problem); + + void sledgehammerStarted(IsabelleProblem problem); + + void sledgehammerFinished(IsabelleProblem problem); + + void sledgeHammerFailed(IsabelleProblem problem, Exception e); +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index 42acc4debd5..cdbb009385b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -54,7 +54,7 @@ private void generateTranslation() { return; } - SledgehammerResult result = translation.sledgehammer(); + SledgehammerResult result = translation.sledgehammer(30); //TODO needs its own action to enable undo, etc. and naming reworks if (result != null && result.isSuccessful()) { From 8cde773f3800cb4acf76b80ba62d6ae59351fcb7 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 15:20:10 +0200 Subject: [PATCH 129/248] add Isabelle to evaluation class --- .../isabelletranslation/IsabelleProblem.java | 6 +- .../IsabelleSolverListener.java | 2 +- .../src/test/java/evaluation/Main.java | 198 +++++++++++++++++- 3 files changed, 200 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 6a005a6f8b2..48116b4f1e2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -269,7 +269,11 @@ private void notifySledgehammerFinished() { private void notifySledgehammerError(Exception e) { for (IsabelleSolverListener listener : listeners) { - listener.sledgeHammerFailed(this, e); + listener.sledgehammerFailed(this, e); } } + + public void removeListener(IsabelleSolverListener listener) { + listeners.remove(listener); + } } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java index 5c7a45691f6..2b8c83834c4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java @@ -25,5 +25,5 @@ public interface IsabelleSolverListener { void sledgehammerFinished(IsabelleProblem problem); - void sledgeHammerFailed(IsabelleProblem problem, Exception e); + void sledgehammerFailed(IsabelleProblem problem, Exception e); } diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 9f2c7a2429f..1de0cfc00a9 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -7,6 +7,10 @@ import de.uka.ilkd.key.api.ProofManagementApi; import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.UserInterfaceControl; +import de.uka.ilkd.key.gui.isabelletranslation.IllegalFormulaException; +import de.uka.ilkd.key.gui.isabelletranslation.IsabelleProblem; +import de.uka.ilkd.key.gui.isabelletranslation.IsabelleSolverListener; +import de.uka.ilkd.key.gui.isabelletranslation.IsabelleTranslator; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.macros.SMTPreparationMacro; import de.uka.ilkd.key.proof.Goal; @@ -72,6 +76,13 @@ private static class StatEntry { long translationAndZ3Time; long z3ProofLines; SMTSolverResult.ThreeValuedTruth z3State; + long isabelleBuildTime; + long isabelleParseTime; + long isabelleSledgehammerTime; + long isabelleTotalTime; + long isabelleTranslationLines; + String isabelleProofTactic; + ProofState isabelleState = ProofState.UNKNOWN; StatEntry(Path p) { this.p = p; @@ -366,7 +377,7 @@ private static boolean checkTrivialNoErrorQuickLoadContract(Path file, Contract } - private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean tryReplay) { + private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean runIsabelle) { if (input.toString().endsWith(".key")) { ProofApi papi = null; try { @@ -376,7 +387,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole if (papi.getProof() == null) { for (Contract contract : pm.getProofContracts()) { - processContract(pm, contract, input, runKeY, runZ3); + processContract(pm, contract, input, runKeY, runZ3, runIsabelle); } return; } @@ -411,6 +422,9 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole STATS.put(input, new HashMap<>()); STATS.get(input).put("", new HashMap<>()); + if (runIsabelle) { + runIsabelleToFile(input, "", goals); + } if (runZ3) { runZ3ToFile(input, "", goals, false); } @@ -428,7 +442,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole } } - private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3) throws IOException, ProblemLoaderException { + private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3, boolean runIsabelle) throws IOException, ProblemLoaderException { ProofApi papi = null; try { papi = pm.startProof(contract); @@ -471,7 +485,9 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa STATS.put(input, new HashMap<>()); STATS.get(input).put(proof.name().toString(), new HashMap<>()); - + if (runIsabelle) { + runIsabelleToFile(input, "", goals); + } if (runZ3) { runZ3ToFile(input, proof.name().toString(), goals, false); } @@ -600,6 +616,180 @@ public void launcherStarted(Collection problems, }); } + private static void runIsabelleToFile(Path input, String contractName, ImmutableList goals) + throws ProblemLoaderException, IOException { + + Proof proof = goals.stream().findFirst().get().proof(); + + SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), + ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof.getSettings().getNewSMTSettings(), proof); + + + class TimedListener implements IsabelleSolverListener { + long sledgehammerTime = 0L; + long parsingTime = 0L; + long buildingTime = 0L; + Goal goal; + long goalNumber; + + public TimedListener(Goal g, long goalNumber) { + goal = g; + this.goalNumber = goalNumber; + } + + @Override + public void parsingStarted(IsabelleProblem problem) { + parsingTime = System.currentTimeMillis(); + } + + @Override + public void parsingFinished(IsabelleProblem problem) { + parsingTime = System.currentTimeMillis() - parsingTime; + updateIsabelleParseTime(input, contractName, goal, parsingTime); + } + + @Override + public void parsingFailed(IsabelleProblem problem, Exception e) { + updateIsabelleState(input, contractName, goal, ProofState.ERROR); + } + + @Override + public void buildingStarted(IsabelleProblem problem) { + buildingTime = System.currentTimeMillis(); + } + + @Override + public void buildingFinished(IsabelleProblem problem) { + buildingTime = System.currentTimeMillis() - buildingTime; + updateIsabelleBuildTime(input, contractName, goal, buildingTime); + } + + @Override + public void buildingFailed(IsabelleProblem problem, Exception e) { + updateIsabelleState(input, contractName, goal, ProofState.ERROR); + } + + @Override + public void processStarted(IsabelleProblem problem) { + System.out.println("Starting Isabelle..."); + } + + @Override + public void processStopped(IsabelleProblem problem) { + String isabelleTranslation = problem.getSequentTranslation(); + updateIsabelleTranslationLines(input, contractName, goal, countLines(isabelleTranslation + problem.getPreamble())); + try { + Files.write(getOutPath(input, goalNumber + "_translation.thy"), isabelleTranslation.getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + + + if (problem.getResult().isSuccessful()) { + updateIsabelleState(input, contractName, goal, ProofState.CLOSED); + String isabelleProof = problem.getResult().getSuccessfulTactic(); + } + } + + @Override + public void processTimeout(IsabelleProblem problem) { + updateIsabelleState(input, contractName, goal, ProofState.OPEN); + } + + @Override + public void sledgehammerStarted(IsabelleProblem problem) { + sledgehammerTime = System.currentTimeMillis(); + } + + @Override + public void sledgehammerFinished(IsabelleProblem problem) { + sledgehammerTime = System.currentTimeMillis() - sledgehammerTime; + updateIsabelleSledgehammerTime(input, contractName, goal, sledgehammerTime); + } + + @Override + public void sledgehammerFailed(IsabelleProblem problem, Exception e) { + updateIsabelleState(input, contractName, goal, ProofState.ERROR); + } + + @Override + public void processInterrupted(IsabelleProblem problem, Exception e) { + + } + } + Services services = proof.getServices(); + IsabelleTranslator translator = new IsabelleTranslator(services); + + goals.forEach((Goal goal) -> { + long totalTime = System.currentTimeMillis(); + IsabelleProblem problem; + try { + problem = translator.translateProblem(goal); + } catch (IllegalFormulaException e) { + LOGGER.error("Translation failed: {}", e.getMessage()); + return; + } + problem.addListener(new TimedListener(goal, goal.getTime())); + problem.sledgehammer(60); + totalTime = System.currentTimeMillis() - totalTime; + updateIsabelleTime(input, contractName, goal, totalTime); + }); + } + + private static void updateIsabelleTime(Path input, String contractName, Goal goal, long totalTime) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleTotalTime = totalTime; + STATS.get(input).get(contractName).put(goal, stats); + } + + private static void updateIsabelleState(Path input, String contractName, Goal goal, ProofState state) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleState = state; + STATS.get(input).get(contractName).put(goal, stats); + } + + private static void updateIsabelleSledgehammerTime(Path input, String contractName, Goal goal, long sledgehammerTime) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleSledgehammerTime = sledgehammerTime; + STATS.get(input).get(contractName).put(goal, stats); + } + + private static void updateIsabelleBuildTime(Path input, String contractName, Goal goal, long buildTime) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleBuildTime = buildTime; + STATS.get(input).get(contractName).put(goal, stats); + } + + private static void updateIsabelleParseTime(Path input, String contractName, Goal goal, long parseTime) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleParseTime = parseTime; + STATS.get(input).get(contractName).put(goal, stats); + } + + private static void updateIsabelleTranslationLines(Path input, String contractName, Goal goal, long lineCount) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleTranslationLines = lineCount; + STATS.get(input).get(contractName).put(goal, stats); + } + private static void appendValid(Path keyPath) { try { if (!VALID_SET.contains(keyPath)) { From cab98ce8b8f0a445e79a16472bdadac1c71543a5 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 15:42:08 +0200 Subject: [PATCH 130/248] fix result not being set when notifying listeners --- .../key/gui/isabelletranslation/IsabelleProblem.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 48116b4f1e2..fafef6c88b7 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -164,19 +164,24 @@ fun go_run (state, thy) = } catch (Exception exception) { result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); if (exception.getMessage().equals("timeout")) { + this.result = result; notifyProcessTimeout(); + return this.result; } else { + this.result = result; notifySledgehammerError(exception); notifyProcessError(exception); + return this.result; } } finally { - notifySledgehammerFinished(); - notifyProcessFinished(); isabelle.destroy(); } + this.result = result; + notifySledgehammerFinished(); + notifyProcessFinished(); LOGGER.info("Sledgehammer result: " + result); - return this.result = result; + return this.result; } private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { From ac7cb919f73b584f5baca0cac54d2efe20328869 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 15:42:29 +0200 Subject: [PATCH 131/248] change runtimeexception to illegal formula exception --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 67707d8ff30..21c0c0efb90 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -40,7 +40,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx for (Throwable t : exceptions) { message.append(t.getMessage()).append(System.lineSeparator()); } - throw new RuntimeException(message.toString()); + throw new IllegalFormulaException(message.toString()); } StringBuilder translationPreamble = new StringBuilder(); From 0745812b0d27dd4bc2d60d6167ae983dcd54aff0 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 15:42:47 +0200 Subject: [PATCH 132/248] fix Isabelle actually starting --- .../src/test/java/evaluation/Main.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 1de0cfc00a9..f2d4f219c63 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -126,7 +126,7 @@ private static void run() { for (String s : pathStrings) { Path p = Paths.get(s); VALID_SET.add(p); - processFile(p, true, true, false); + processFile(p, true, true, true); saveStatisticsCSV(); } saveStatisticsCSV(); @@ -486,7 +486,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa STATS.get(input).put(proof.name().toString(), new HashMap<>()); if (runIsabelle) { - runIsabelleToFile(input, "", goals); + runIsabelleToFile(input, proof.name().toString(), goals); } if (runZ3) { runZ3ToFile(input, proof.name().toString(), goals, false); @@ -730,7 +730,7 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { return; } problem.addListener(new TimedListener(goal, goal.getTime())); - problem.sledgehammer(60); + problem.sledgehammer(10); totalTime = System.currentTimeMillis() - totalTime; updateIsabelleTime(input, contractName, goal, totalTime); }); From 5268259d28104c68f11e9372dc9f680c4c4e24e2 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 15:48:17 +0200 Subject: [PATCH 133/248] add isabelle stats to csv --- .../src/test/java/evaluation/Main.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index f2d4f219c63..5afec63c546 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -154,6 +154,20 @@ private static void saveStatisticsCSV() { sb.append("Z3_proof_lines"); sb.append(","); sb.append("Z3_State"); + sb.append(","); + sb.append("Isabelle_build_time"); + sb.append(","); + sb.append("Isabelle_parse_time"); + sb.append(","); + sb.append("Isabelle_sledgehammer_time"); + sb.append(","); + sb.append("Isabelle_total_time"); + sb.append(","); + sb.append("Isabelle_translation_lines"); + sb.append(","); + sb.append("Isabelle_proof"); + sb.append(","); + sb.append("Isabelle_state"); sb.append(System.lineSeparator()); for (Map> contractMap : STATS.values()) { @@ -177,6 +191,20 @@ private static void saveStatisticsCSV() { sb.append(entry.z3ProofLines); sb.append(","); sb.append(entry.z3State); + sb.append(","); + sb.append(entry.isabelleBuildTime); + sb.append(","); + sb.append(entry.isabelleParseTime); + sb.append(","); + sb.append(entry.isabelleSledgehammerTime); + sb.append(","); + sb.append(entry.isabelleTotalTime); + sb.append(","); + sb.append(entry.isabelleTranslationLines); + sb.append(","); + sb.append(entry.isabelleProofTactic); + sb.append(","); + sb.append(entry.isabelleState); sb.append(System.lineSeparator()); })); } From f941eb478a15d9b295ca47a16badf448b0d8a4f3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 16:05:39 +0200 Subject: [PATCH 134/248] change return timing to get notifications --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index fafef6c88b7..c2f4638e755 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -166,12 +166,10 @@ fun go_run (state, thy) = if (exception.getMessage().equals("timeout")) { this.result = result; notifyProcessTimeout(); - return this.result; } else { this.result = result; notifySledgehammerError(exception); notifyProcessError(exception); - return this.result; } } finally { isabelle.destroy(); From d3e5e3831a98a0a135531f1553973b692366bcd0 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 16:08:44 +0200 Subject: [PATCH 135/248] fix exactInstance overlapping for multiple instances --- .../UninterpretedSymbolsHandler.preamble.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index c68434f26de..15feac72c3c 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -250,6 +250,9 @@ end fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" where "instanceof x type = typeof x type" +consts + exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" From 2c73ff014df10f31f64feb28fa7113ab75849814 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 16:08:44 +0200 Subject: [PATCH 136/248] fix exactInstance overlapping for multiple instances --- .../UninterpretedSymbolsHandler.preamble.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index c68434f26de..15feac72c3c 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -250,6 +250,9 @@ end fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" where "instanceof x type = typeof x type" +consts + exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" From e9929c2f7023ce0a323adf1e03f46660be4220f8 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 16:38:09 +0200 Subject: [PATCH 137/248] fix array types being defined before their base type --- .../IsabelleTranslator.java | 219 ++++++++++-------- 1 file changed, 125 insertions(+), 94 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 67707d8ff30..5dafd7f33a4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -17,8 +17,11 @@ public class IsabelleTranslator { private final Services services; + private final Sort nullSort; + public IsabelleTranslator(Services services) { this.services = services; + nullSort = services.getNamespaces().sorts().lookup("Null"); } public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaException { @@ -53,103 +56,15 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main KeYTranslations.TranslationPreamble begin").append(LINE_ENDING); - Sort nullSort = services.getNamespaces().sorts().lookup("Null"); - + //TODO make this into a tree structure to avoid excessive looping (over sorts) | sort the implementation queue Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); - for (Sort sort : sortParentsMap.keySet()) { - String sortName = masterHandler.translateSortName(sort); - String UNIV = sortName + "_UNIV"; - - sequentTranslation.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); - sequentTranslation.append("lemma ex_").append(UNIV).append(":"); - sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); - sequentTranslation.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); - - - sequentTranslation.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); - - sequentTranslation.append("specification (").append(UNIV).append(") "); - sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - sequentTranslation.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); - - - String UNIV_spec_lemma_name = UNIV + "_specification"; - sequentTranslation.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - sequentTranslation.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); - - sequentTranslation.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); - String repName = sortName + "2any"; - String absName = "any2" + sortName; + Map sortImplemented = new HashMap<>(); + sortParentsMap.keySet().forEach((Sort sort) -> sortImplemented.put(sort, false)); + masterHandler.getPredefinedSorts().forEach((Sort sort) -> sortImplemented.put(sort, true)); - sequentTranslation.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); - sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); + Queue sortImplementationQueue = new LinkedList<>(sortParentsMap.keySet()); + implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); - sequentTranslation.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); - - - String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; - sequentTranslation.append("lemma ").append(sortName).append("_type_specification[simp]:") - .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) - .append(LINE_ENDING); - sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); - - for (Sort parentSort : sortParentsMap.get(sort)) { - if (parentSort == Sort.ANY) { - continue; - } - String parentSortName = masterHandler.translateSortName(parentSort); - String parentSortInj = sortName + "2" + parentSortName; - sequentTranslation.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) - .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); - sequentTranslation.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); - } - - sequentTranslation.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); - sequentTranslation.append("begin").append(LINE_ENDING); - String to_any_fun_Name = "to_any_" + sortName; - sequentTranslation.append("fun ").append(to_any_fun_Name) - .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") - .append(LINE_ENDING); - String cast_fun_Name = "cast_" + sortName; - sequentTranslation.append("fun ").append(cast_fun_Name) - .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") - .append(LINE_ENDING); - sequentTranslation.append("instance by standard").append(LINE_ENDING); - sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); - - if (nullSort.extendsTrans(sort)) { - String null_to_sort_name = "Null2" + sortName; - sequentTranslation.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) - .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); - sequentTranslation.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); - } - - if (sort instanceof ArraySort) { - sequentTranslation.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); - sequentTranslation.append("begin").append(LINE_ENDING); - - String element_type_name = "element_type_" + sortName; - String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); - String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; - sequentTranslation.append("fun ").append(element_type_name) - .append(" where \"").append(element_type_name) - .append(" (x::").append(sortName).append(")").append(" = ") - .append(elementSortType).append("\"") - .append(LINE_ENDING); - - sequentTranslation.append("instance by standard").append(LINE_ENDING); - sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); - } - - String typeConstName = sortName + "_type"; - sequentTranslation.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); - - sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); - } sequentTranslation.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); @@ -203,6 +118,122 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } + private void implementSorts(StringBuilder sequentTranslation, Queue sortImplementationQueue, Map sortImplemented, + Map> sortParentsMap, IsabelleMasterHandler masterHandler) { + if (sortImplementationQueue.isEmpty()) { + return; + } + + Sort sort = sortImplementationQueue.poll(); + for (Sort parent : sortParentsMap.get(sort)) { + if (!sortImplemented.get(parent)) { + sortImplementationQueue.add(sort); + implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + return; + } + } + if ((sort instanceof ArraySort) && !sortImplemented.get(((ArraySort) sort).elementSort())) { + sortImplementationQueue.add(sort); + implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + return; + } + String sortName = masterHandler.translateSortName(sort); + String UNIV = sortName + "_UNIV"; + + sequentTranslation.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); + sequentTranslation.append("lemma ex_").append(UNIV).append(":"); + sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); + sequentTranslation.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); + + + sequentTranslation.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); + + sequentTranslation.append("specification (").append(UNIV).append(") "); + sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + sequentTranslation.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); + + + String UNIV_spec_lemma_name = UNIV + "_specification"; + sequentTranslation.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); + sequentTranslation.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING); + + sequentTranslation.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); + String repName = sortName + "2any"; + String absName = "any2" + sortName; + + sequentTranslation.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); + sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); + + sequentTranslation.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + + + String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; + sequentTranslation.append("lemma ").append(sortName).append("_type_specification[simp]:") + .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) + .append(LINE_ENDING); + sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); + sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); + + for (Sort parentSort : sortParentsMap.get(sort)) { + if (parentSort == Sort.ANY) { + continue; + } + String parentSortName = masterHandler.translateSortName(parentSort); + String parentSortInj = sortName + "2" + parentSortName; + sequentTranslation.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) + .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); + sequentTranslation.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); + } + + sequentTranslation.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); + sequentTranslation.append("begin").append(LINE_ENDING); + String to_any_fun_Name = "to_any_" + sortName; + sequentTranslation.append("fun ").append(to_any_fun_Name) + .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") + .append(LINE_ENDING); + String cast_fun_Name = "cast_" + sortName; + sequentTranslation.append("fun ").append(cast_fun_Name) + .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") + .append(LINE_ENDING); + sequentTranslation.append("instance by standard").append(LINE_ENDING); + sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); + + if (nullSort.extendsTrans(sort)) { + String null_to_sort_name = "Null2" + sortName; + sequentTranslation.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) + .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); + sequentTranslation.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + } + + if (sort instanceof ArraySort) { + sequentTranslation.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); + sequentTranslation.append("begin").append(LINE_ENDING); + + String element_type_name = "element_type_" + sortName; + String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); + String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; + sequentTranslation.append("fun ").append(element_type_name) + .append(" where \"").append(element_type_name) + .append(" (x::").append(sortName).append(")").append(" = ") + .append(elementSortType).append("\"") + .append(LINE_ENDING); + + sequentTranslation.append("instance by standard").append(LINE_ENDING); + sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); + } + + String typeConstName = sortName + "_type"; + sequentTranslation.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); + + sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); + + sortImplemented.put(sort, true); + implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + } + private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { List parentSortNames = new ArrayList<>(parents.stream().map(masterHandler::translateSortName).toList()); StringBuilder univSpec = new StringBuilder(); From 25f330226443e8f54f8bf623983f1c82e7337ff5 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 19:11:45 +0200 Subject: [PATCH 138/248] add timeout in other places it should occur --- .../isabelletranslation/IsabelleProblem.java | 35 ++++++++++++------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index c2f4638e755..ee715bac96d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -11,11 +11,16 @@ import scala.Tuple2; import scala.collection.immutable.List; import scala.collection.mutable.Builder; +import scala.concurrent.Await; +import scala.concurrent.Future; +import scala.concurrent.duration.Duration; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; public class IsabelleProblem { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); @@ -133,8 +138,10 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout","30"),("verbose","true")]; - val results =\s""" + [("timeout", + """ + timeout_seconds + """ + ),(verbose","true"),("falsify","false")]; + val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ .Normal NONE 1 override p_state; @@ -157,25 +164,27 @@ fun go_run (state, thy) = LOGGER.info("Sledgehammering..."); notifySledgehammerStarted(); try { - result = new SledgehammerResult(normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) - .retrieveNow(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle)); - } catch (Exception exception) { + .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); + result = new SledgehammerResult(Await.result(resultFuture, Duration.create(timeout_seconds + 10, TimeUnit.SECONDS))); + } catch (TimeoutException exception) { result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); - if (exception.getMessage().equals("timeout")) { - this.result = result; - notifyProcessTimeout(); - } else { - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } + this.result = result; + notifyProcessTimeout(); + } catch (InterruptedException exception) { + result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); } finally { isabelle.destroy(); } this.result = result; + notifySledgehammerFinished(); + notifyProcessFinished(); LOGGER.info("Sledgehammer result: " + result); From d5d266154569d924ad163d02b6d0e685e59c7658 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 18 Apr 2024 19:12:05 +0200 Subject: [PATCH 139/248] add isabelle proof to csv --- .../src/test/java/evaluation/Main.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 5afec63c546..c22ac038da4 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -679,6 +679,7 @@ public void parsingFinished(IsabelleProblem problem) { @Override public void parsingFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); + updateIsabelleProof(input, contractName, goal, e.getMessage()); } @Override @@ -695,6 +696,7 @@ public void buildingFinished(IsabelleProblem problem) { @Override public void buildingFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); + updateIsabelleProof(input, contractName, goal, e.getMessage()); } @Override @@ -716,6 +718,7 @@ public void processStopped(IsabelleProblem problem) { if (problem.getResult().isSuccessful()) { updateIsabelleState(input, contractName, goal, ProofState.CLOSED); String isabelleProof = problem.getResult().getSuccessfulTactic(); + updateIsabelleProof(input, contractName, goal, isabelleProof); } } @@ -738,6 +741,7 @@ public void sledgehammerFinished(IsabelleProblem problem) { @Override public void sledgehammerFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); + updateIsabelleProof(input, contractName, goal, e.getMessage()); } @Override @@ -764,6 +768,15 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { }); } + private static void updateIsabelleProof(Path input, String contractName, Goal goal, String isabelleProof) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.isabelleProofTactic = isabelleProof; + STATS.get(input).get(contractName).put(goal, stats); + } + private static void updateIsabelleTime(Path input, String contractName, Goal goal, long totalTime) { StatEntry stats = STATS.get(input).get(contractName).get(goal); if (stats == null) { From 0203874a27288843a795a39ce1566080cbb0dd89 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 11:44:29 +0200 Subject: [PATCH 140/248] try try0 before sledgehammering --- .../isabelletranslation/IsabelleProblem.java | 60 +++++++++++++++---- .../SledgehammerResult.java | 14 +++-- 2 files changed, 58 insertions(+), 16 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index ee715bac96d..9d562bf9b6a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -8,6 +8,7 @@ import de.unruh.isabelle.pure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import scala.Option; import scala.Tuple2; import scala.collection.immutable.List; import scala.collection.mutable.Builder; @@ -28,7 +29,7 @@ public class IsabelleProblem { private SledgehammerResult result = null; private final String preamble; private final String sequentTranslation; - private Collection listeners = new HashSet<>(); + private final Collection listeners = new HashSet<>(); public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { this.goal = goal; @@ -56,7 +57,7 @@ public SledgehammerResult getResult() { return result; } - public SledgehammerResult sledgehammer(int timeout_seconds) { + public SledgehammerResult sledgehammer(long timeout_seconds) { LOGGER.info("Starting Isabelle..."); notifyProcessStarted(); IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); @@ -122,6 +123,19 @@ in addtext (Symbol.explode text) transitions end""", isabelle, notifyParsingFinished(); LOGGER.info("Finished Parsing"); + String Try = thy0.importMLStructureNow("Try0", isabelle); + MLFunction try_function = + MLValue.compileFunction( + """ + fn (state) => + let + val p_state = Toplevel.proof_of state; + in + \s""" + Try + ".try0 (SOME (seconds 5.0)) ([], [], [], []) p_state" + """ + end + """, isabelle, Implicits.toplevelStateConverter(), + de.unruh.isabelle.mlvalue.Implicits.booleanConverter()); + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); @@ -138,9 +152,8 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout", - """ + timeout_seconds + """ - ),(verbose","true"),("falsify","false")]; + [("timeout",\"""" + timeout_seconds + """ + "),("verbose","true"),("falsify","false"),("provers", "e spass vampire cvc4 z3 zipperposition")]; val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ @@ -161,33 +174,58 @@ fun go_run (state, thy) = scala.collection.immutable.List emptyList = listBuilder.result(); SledgehammerResult result; - LOGGER.info("Sledgehammering..."); + SledgehammerResult tryResult = null; + LOGGER.info("Trying..."); notifySledgehammerStarted(); try { Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - result = new SledgehammerResult(Await.result(resultFuture, Duration.create(timeout_seconds + 10, TimeUnit.SECONDS))); + Future tryResultFuture = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) + .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + if ((boolean) Await.result(tryResultFuture, Duration.create(10, TimeUnit.SECONDS))) { + tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); + this.result = tryResult; + notifySledgehammerFinished(); + notifyProcessFinished(); + LOGGER.info("Sledgehammer result: " + this.result); + return this.result; + } + Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); + result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); + this.result = result; } catch (TimeoutException exception) { - result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); this.result = result; notifyProcessTimeout(); } catch (InterruptedException exception) { - result = new SledgehammerResult(new Tuple2<>(Boolean.FALSE, new Tuple2<>(exception.getMessage(), emptyList))); + result = new SledgehammerResult(Option.apply(null)); this.result = result; notifySledgehammerError(exception); notifyProcessError(exception); + } catch (Exception exception) { + if (exception.getMessage().contains("Timeout after")) { + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = result; + notifyProcessTimeout(); + } else { + LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); + exception.printStackTrace(); + result = new SledgehammerResult(Option.apply(null)); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); + } } finally { isabelle.destroy(); } - this.result = result; notifySledgehammerFinished(); notifyProcessFinished(); - LOGGER.info("Sledgehammer result: " + result); + LOGGER.info("Sledgehammer result: " + this.result); return this.result; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java index 5f3611bbe53..b35c845a840 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java @@ -1,22 +1,26 @@ package de.uka.ilkd.key.gui.isabelletranslation; +import scala.Option; import scala.Tuple2; -import scala.collection.immutable.List; -public record SledgehammerResult(Tuple2>> result) { +public record SledgehammerResult(Option> result) { public Boolean isSuccessful() { - return (Boolean) result._1(); + return result.exists((Tuple2 tactic) -> !tactic._1().equals("timeout")); } public String getSuccessfulTactic() { if (!isSuccessful()) { return null; } - return result._2()._2().head(); + return result.get()._2(); } @Override public String toString() { - return result.toString(); + return result.get().toString(); + } + + public boolean isTimeout() { + return result.exists((Tuple2 tactic) -> tactic._1().equals("timeout")); } } From b6aaba2a4c0efd54330823da36d3616f19a6c8b3 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 11:44:47 +0200 Subject: [PATCH 141/248] add right sum induct lemma to preamble --- .../UninterpretedSymbolsHandler.preamble.xml | 58 +++++-------------- 1 file changed, 14 insertions(+), 44 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 15feac72c3c..38d8c4f9544 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -293,55 +293,25 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" -lemma int_SUM_0[simp]: +lemma induct_sum_upper_limit[simp]: fixes f::"int\<Rightarrow>int" fixes lower::int fixes upper::int - assumes "lower\<ge>0" - shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::nat) = (nat lower)..<(nat upper). f (int j))" + assumes "lower<upper" + shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f (upper - 1)" proof - - consider (baseCase) "lower \<ge> upper" | (complex) "lower < upper" by linarith - then show ?thesis - proof cases - case baseCase - then show ?thesis + have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" + using assms by auto + have "{upper-1..<upper} = {upper - 1}" + by auto + then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) + then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> by presburger + also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i)" by simp - next - case complex - then have "image int {(nat lower)..<(nat upper)} = {lower..<upper}" - using assms - by (simp add: image_int_atLeastLessThan) - then show ?thesis - proof - - have "\<forall>n f na. (\<Sum>n = n..<na. (f (int n)::int)) = sum f {int n..<int na}" - by (simp add: sum.atLeast_int_lessThan_int_shift) - then show ?thesis - by (metis (no_types) \<open>int ` {nat lower..<nat upper} = {lower..<upper}\<close> image_int_atLeastLessThan) - qed - qed -qed - -lemma int_SUM_neg[simp]: - fixes f::"int\<Rightarrow>int" - fixes lower::int - fixes upper::int - assumes "lower<0" - shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::nat) = (nat (lower-lower))..<(nat (upper - lower)). f (int j + lower))" -proof - - have "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper. (f \<circ> (\<lambda>x. x + lower) \<circ> (\<lambda>x. x - lower)) i)" - by simp - also have "... = sum (f\<circ>(\<lambda>x. x + lower)) (image (\<lambda>x. x - lower) {lower..<upper})" - by (simp add: sum.reindex) - finally have "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(j::int) = (0)..< (upper - lower). f (j + lower))" - proof - - have "sum (f \<circ> (\<lambda>i. i + lower)) {0..<upper - lower} = sum f {lower..<upper}" - by (metis (no_types) image_add_int_atLeastLessThan inj_on_add' sum.reindex) - then have "(\<Sum>i = 0..<upper - lower. f (i + lower)) = sum f {lower..<upper}" - by simp - then show ?thesis - by simp - qed - then show ?thesis by simp + finally show ?thesis + using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto qed From 35a49854fd884351d2bcffd8747321050b3a3083 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 11:45:18 +0200 Subject: [PATCH 142/248] various fixes, adding a timeout --- .../src/test/java/evaluation/Main.java | 165 ++++++++++++++++-- 1 file changed, 146 insertions(+), 19 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index c22ac038da4..7038e4e05e4 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -21,6 +21,7 @@ import de.uka.ilkd.key.proof.io.ProblemLoaderException; import de.uka.ilkd.key.proof.io.ProofSaver; import de.uka.ilkd.key.settings.DefaultSMTSettings; +import de.uka.ilkd.key.settings.ProofIndependentSMTSettings; import de.uka.ilkd.key.settings.ProofIndependentSettings; import de.uka.ilkd.key.smt.*; import de.uka.ilkd.key.smt.solvertypes.SolverType; @@ -49,7 +50,7 @@ public class Main { private static final SolverType Z3_SOLVER = SolverTypes.getSolverTypes().stream() .filter(it -> it.getClass().equals(SolverTypeImplementation.class) - && it.getName().equals("Z3 (Legacy Translation)")) + && it.getName().equals("Z3")) .findFirst().orElse(null); private static final Path VALID_LIST_PATH = Paths.get("/tmp/valid_list.txt"); @@ -61,12 +62,16 @@ public class Main { private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; + private static final long timeoutSeconds = 60; + private static Path outDir; private static boolean skipProvable = false; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + private static final Collection flaggedTranslations = new HashSet<>(); + private static class StatEntry { final Path p; ProofState keyState = ProofState.UNKNOWN; @@ -75,7 +80,8 @@ private static class StatEntry { long z3TranslationLines; long translationAndZ3Time; long z3ProofLines; - SMTSolverResult.ThreeValuedTruth z3State; + ProofState z3State; + String z3ErrorMessage; long isabelleBuildTime; long isabelleParseTime; long isabelleSledgehammerTime; @@ -127,11 +133,101 @@ private static void run() { Path p = Paths.get(s); VALID_SET.add(p); processFile(p, true, true, true); - saveStatisticsCSV(); + saveStatisticsCSVFile(p); + saveFlaggedTranslations(); } saveStatisticsCSV(); } + private static void saveStatisticsCSVFile(Path input) { + StringBuilder sb = new StringBuilder(); + + sb.append("input_file"); + sb.append(","); + sb.append("contractName"); + sb.append(","); + sb.append("goalNodeName"); + sb.append(","); + sb.append("KeY_state"); + sb.append(","); + sb.append("Isabelle_state"); + sb.append(","); + sb.append("Z3_State"); + sb.append(","); + sb.append("KeY_time"); + sb.append(","); + sb.append("KeY_proof_nodes"); + sb.append(","); + sb.append("SMT_translation_lines"); + sb.append(","); + sb.append("transl_+_Z3_time"); + sb.append(","); + sb.append("Z3_proof_lines"); + sb.append(","); + sb.append("Z3_error_msg"); + sb.append(","); + sb.append("Isabelle_build_time"); + sb.append(","); + sb.append("Isabelle_parse_time"); + sb.append(","); + sb.append("Isabelle_sledgehammer_time"); + sb.append(","); + sb.append("Isabelle_total_time"); + sb.append(","); + sb.append("Isabelle_translation_lines"); + sb.append(","); + sb.append("Isabelle_proof"); + sb.append(System.lineSeparator()); + + Map> contractMap = STATS.get(input); + + contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { + sb.append(entry.p); + sb.append(","); + sb.append(c.replace(",", "_")); + sb.append(","); + sb.append(goal.getTime()); + sb.append(","); + sb.append(entry.keyState); + sb.append(","); + sb.append(entry.isabelleState); + sb.append(","); + sb.append(entry.z3State); + sb.append(","); + sb.append(entry.keyTime); + sb.append(","); + sb.append(entry.keyNodes); + sb.append(","); + sb.append(entry.z3TranslationLines); + sb.append(","); + sb.append(entry.translationAndZ3Time); + sb.append(","); + sb.append(entry.z3ProofLines); + sb.append(","); + sb.append(entry.z3ErrorMessage); + sb.append(","); + sb.append(entry.isabelleBuildTime); + sb.append(","); + sb.append(entry.isabelleParseTime); + sb.append(","); + sb.append(entry.isabelleSledgehammerTime); + sb.append(","); + sb.append(entry.isabelleTotalTime); + sb.append(","); + sb.append(entry.isabelleTranslationLines); + sb.append(","); + sb.append(entry.isabelleProofTactic); + sb.append(System.lineSeparator()); + })); + + try { + Files.write(Path.of(outDir + "/" + input.getParent().getFileName() + "_statistics.csv"), sb.toString().getBytes()); + LOGGER.info("Statistics CSV written to {}", outDir); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + private static void saveStatisticsCSV() { StringBuilder sb = new StringBuilder(); @@ -180,6 +276,10 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append(entry.keyState); sb.append(","); + sb.append(entry.isabelleState); + sb.append(","); + sb.append(entry.z3State); + sb.append(","); sb.append(entry.keyTime); sb.append(","); sb.append(entry.keyNodes); @@ -190,8 +290,6 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append(entry.z3ProofLines); sb.append(","); - sb.append(entry.z3State); - sb.append(","); sb.append(entry.isabelleBuildTime); sb.append(","); sb.append(entry.isabelleParseTime); @@ -203,8 +301,6 @@ private static void saveStatisticsCSV() { sb.append(entry.isabelleTranslationLines); sb.append(","); sb.append(entry.isabelleProofTactic); - sb.append(","); - sb.append(entry.isabelleState); sb.append(System.lineSeparator()); })); } @@ -295,7 +391,7 @@ private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { TimeLimiter tl = SimpleTimeLimiter.create(executorService); try { - tl.runWithTimeout(task, 60000, TimeUnit.MILLISECONDS); + tl.runWithTimeout(task, 30000, TimeUnit.MILLISECONDS); } catch (TimeoutException | InterruptedException e) { LOGGER.error("Load timeout {}", file); return false; @@ -392,7 +488,7 @@ private static boolean checkTrivialNoErrorQuickLoadContract(Path file, Contract }; try { - tl.runWithTimeout(prep, 60, TimeUnit.SECONDS); + tl.runWithTimeout(prep, timeoutSeconds, TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException e) { LOGGER.error("Prep timeout {}", file); return false; @@ -509,8 +605,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa } ImmutableList goals = proof.openGoals(); - - STATS.put(input, new HashMap<>()); + STATS.computeIfAbsent(input, k -> new HashMap<>()); STATS.get(input).put(proof.name().toString(), new HashMap<>()); if (runIsabelle) { @@ -535,7 +630,7 @@ private static void runWithKeYAuto(Path input, String contractName, ImmutableLis Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); proof.setActiveStrategy(strategy); proof.getSettings().getStrategySettings().setMaxSteps(1000000); - proof.getSettings().getStrategySettings().setTimeout(1000); + proof.getSettings().getStrategySettings().setTimeout(timeoutSeconds * 1000); for (Goal g : goals) { int nodes = -g.proof().getStatistics().nodes; @@ -568,8 +663,10 @@ private static void runZ3ToFile(Path input, String contractName, ImmutableList problems, problems.forEach((SMTProblem problem) -> { SolverLauncher launcher = new SolverLauncher(settings); launcher.addListener(new TimedListener(problem.getGoal(), problem.getGoal().getTime())); - launcher.launch(problem, services, Z3_SOLVER); + try { + launcher.launch(problem, services, Z3_SOLVER); + } catch (Exception e) { + LOGGER.error("Exception during Z3... {}", e.getMessage()); + e.printStackTrace(); + updateZ3State(input, contractName, problem.getGoal(), ProofState.ERROR); + updateZ3State(input, contractName, problem.getGoal(), e.getMessage()); + } }); } @@ -758,16 +864,28 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { try { problem = translator.translateProblem(goal); } catch (IllegalFormulaException e) { + flaggedTranslations.add(input); LOGGER.error("Translation failed: {}", e.getMessage()); return; } problem.addListener(new TimedListener(goal, goal.getTime())); - problem.sledgehammer(10); + problem.sledgehammer(timeoutSeconds); totalTime = System.currentTimeMillis() - totalTime; updateIsabelleTime(input, contractName, goal, totalTime); }); } + private static void saveFlaggedTranslations() { + StringBuilder sb = new StringBuilder(); + flaggedTranslations.forEach(sb::append); + + try { + Files.write(Path.of(outDir + "flagged.txt"), sb.toString().getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + private static void updateIsabelleProof(Path input, String contractName, Goal goal, String isabelleProof) { StatEntry stats = STATS.get(input).get(contractName).get(goal); if (stats == null) { @@ -871,12 +989,21 @@ private static void updateZ3Time(Path p, String c, Goal g, long z3Time) { } - private static void updateZ3State(Path p, String c, Goal g, SMTSolverResult.ThreeValuedTruth valid) { + private static void updateZ3State(Path p, String c, Goal g, ProofState state) { + StatEntry stats = STATS.get(p).get(c).get(g); + if (stats == null) { + stats = new StatEntry(p); + } + stats.z3State = state; + STATS.get(p).get(c).put(g, stats); + } + + private static void updateZ3State(Path p, String c, Goal g, String msg) { StatEntry stats = STATS.get(p).get(c).get(g); if (stats == null) { stats = new StatEntry(p); } - stats.z3State = valid; + stats.z3ErrorMessage = msg; STATS.get(p).get(c).put(g, stats); } From ee335915372366e90da74bee8374de4a00b33745 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 11:52:24 +0200 Subject: [PATCH 143/248] verit missing from sledgehammer --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 9d562bf9b6a..f7d83bdfcdc 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -153,7 +153,7 @@ fun go_run (state, thy) = val params =\s""" + Sledgehammer_Commands + """ .default_params thy [("timeout",\"""" + timeout_seconds + """ - "),("verbose","true"),("falsify","false"),("provers", "e spass vampire cvc4 z3 zipperposition")]; + "),("verbose","true"),("falsify","false"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ From bae7037b8d2dae0602201203f47ffccbb8585134 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 12:00:27 +0200 Subject: [PATCH 144/248] wrong timeout being thrown --- .../ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index f7d83bdfcdc..4a9cecad754 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -182,9 +182,9 @@ fun go_run (state, thy) = new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Future tryResultFuture = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) - .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); - if ((boolean) Await.result(tryResultFuture, Duration.create(10, TimeUnit.SECONDS))) { + Boolean tryResultSuccess = (Boolean) try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) + .retrieveNow(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + if (tryResultSuccess) { tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); this.result = tryResult; notifySledgehammerFinished(); From 99ee8ffc4e2cf9c7da5134aed3fd4efb2636a5b1 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 13:24:15 +0200 Subject: [PATCH 145/248] string for empty results --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 4a9cecad754..151ba281a57 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -173,7 +173,7 @@ fun go_run (state, thy) = Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List emptyList = listBuilder.result(); - SledgehammerResult result; + SledgehammerResult result = null; SledgehammerResult tryResult = null; LOGGER.info("Trying..."); notifySledgehammerStarted(); From 9a16c074c438d3c247e099de7d1dc459367f03bd Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 13:24:43 +0200 Subject: [PATCH 146/248] add create to defined symbols --- .../ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 5fa19a63c72..0c6dbc2f042 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -27,6 +27,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("wellFormed", "wellFormed"); definedFunctions.put("anon", "anon"); definedFunctions.put("store", "store"); + definedFunctions.put("create", "create"); //Seq functions definedFunctions.put("seqLen", "seqLen"); From 5a86b7ba2eafbd6772cf08e49c617830119a4457 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 13:24:49 +0200 Subject: [PATCH 147/248] add create to defined symbols --- .../ilkd/key/gui/isabelletranslation/SledgehammerResult.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java index b35c845a840..2bb4b144415 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java @@ -17,7 +17,7 @@ public String getSuccessfulTactic() { @Override public String toString() { - return result.get().toString(); + return (result.exists((r) -> true)) ? result.get().toString() : null; } public boolean isTimeout() { From 38dd2991c8b8a8416e0217c1833812457fcdef9a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 15:10:51 +0200 Subject: [PATCH 148/248] fix invariants for different types colliding --- .../IsabelleMasterHandler.java | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 27fcb49019c..4a16b019313 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -3,6 +3,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.SortedOperator; import de.uka.ilkd.key.logic.sort.ArraySort; import de.uka.ilkd.key.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; @@ -118,14 +119,26 @@ private void addConstDeclaration(Term term) { decl.append(unknownValues.get(term.op())); decl.append("::\""); - for (Term sub : term.subs()) { - if (isNewSort(sub.sort())) { - addGenericSort(sub.sort()); + if (term.op() instanceof SortedOperator) { + SortedOperator op = (SortedOperator) term.op(); + for (Sort argSort : op.argSorts()) { + if (isNewSort(argSort)) { + addGenericSort(argSort); + } + decl.append(translateSortName(argSort)).append("=>"); + } + decl.append((translateSortName(op.sort()))); + decl.append("\""); + } else { + for (Term sub : term.subs()) { + if (isNewSort(sub.sort())) { + addGenericSort(sub.sort()); + } + decl.append(translateSortName(sub.sort())).append("=>"); } - decl.append(translateSortName(sub.sort())).append("=>"); + decl.append((translateSortName(term.sort()))); + decl.append("\""); } - decl.append((translateSortName(term.sort()))); - decl.append("\""); constDeclarations.add(decl); } From 422cdd219f0ebafae595502b6f538718a8219c35 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 19 Apr 2024 19:14:14 +0200 Subject: [PATCH 149/248] add back falsify to sledgehammer --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 151ba281a57..812b61d7a55 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -153,7 +153,7 @@ fun go_run (state, thy) = val params =\s""" + Sledgehammer_Commands + """ .default_params thy [("timeout",\"""" + timeout_seconds + """ - "),("verbose","true"),("falsify","false"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; + "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ From 355a457cca5c2c742ac5cfc835d914a110864734 Mon Sep 17 00:00:00 2001 From: BookWood Date: Fri, 19 Apr 2024 21:29:36 +0200 Subject: [PATCH 150/248] strategy settings messed up the SMT Prep macro --- .../src/test/java/evaluation/Main.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 7038e4e05e4..13d7f2fa815 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -519,14 +519,6 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); - // this should initialize with the default properties, - // necessary to enable quantifier instantiation - StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(1000000); - proof.getSettings().getStrategySettings().setTimeout(100000); - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { @@ -582,13 +574,6 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa String contractName = proof.name().toString(); System.out.println("Processing contract " + contractName + " of " + input); - // this should initialize with the default properties, - // necessary to enable quantifier instantiation - StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(1000000); - proof.getSettings().getStrategySettings().setTimeout(100000); SMTPreparationMacro smtMacro = new SMTPreparationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { From 93ddcb3a3e6c2a8c82a6955f1f574b5d85b0b411 Mon Sep 17 00:00:00 2001 From: BookWood Date: Sat, 20 Apr 2024 14:22:26 +0200 Subject: [PATCH 151/248] fix locale for no variables in sequent and destroy isabelle process env upon parsing error --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 1 + .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 812b61d7a55..00e6addb188 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -117,6 +117,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, .retrieveNow(Implicits.toplevelStateConverter(), isabelle); } } catch (Exception e) { + isabelle.destroy(); notifyParsingError(e); return null; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 2abf7f50c2c..31e4ff5beea 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -85,7 +85,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(" = "); sequentTranslation.append(locales.remove(0)); locale_empty = false; - } else if (!locale_empty) { + } else if (!constDecls.isEmpty()) { sequentTranslation.append(" + ").append(LINE_ENDING); } for (StringBuilder constDecl : constDecls) { From 26c04b4f1d74754d51ca086bb7883fbd89f645b8 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 20 Apr 2024 20:47:12 +0200 Subject: [PATCH 152/248] added launcher for Isabelle to avoid loading theory for each problem --- .../isabelletranslation/IsabelleLauncher.java | 71 ++++++++++ .../isabelletranslation/IsabelleProblem.java | 126 ++++++++++++++++++ .../src/test/java/evaluation/Main.java | 30 +++-- 3 files changed, 218 insertions(+), 9 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java new file mode 100644 index 00000000000..98251ea07c7 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -0,0 +1,71 @@ +package de.uka.ilkd.key.gui.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.mlvalue.ListConverter; +import de.unruh.isabelle.mlvalue.MLFunction2; +import de.unruh.isabelle.mlvalue.MLFunction3; +import de.unruh.isabelle.mlvalue.MLValue; +import de.unruh.isabelle.pure.Implicits; +import de.unruh.isabelle.pure.Position; +import de.unruh.isabelle.pure.Theory; +import de.unruh.isabelle.pure.TheoryHeader; +import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + +public class IsabelleLauncher { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); + + private final IsabelleTranslationSettings settings; + private Isabelle isabelle; + private Theory thy0; + + public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { + this.settings = settings; + } + + public List try0ThenSledgehammerAll(List problems, long timeout_seconds) throws IOException { + if (problems.isEmpty()) { + return new ArrayList<>(); + } + ArrayList sessionRoots = new ArrayList<>(); + sessionRoots.add(settings.getTranslationPath()); + try { + Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); + isabelle = new Isabelle(setup); + } catch (Exception e) { + LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); + throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); + } + //thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); + List results = problems.stream().map((problem) -> problem.try0ThenSledgehammer(isabelle, thy0, settings, timeout_seconds)).toList(); + LOGGER.info("Completed all problems"); + isabelle.destroy(); + return results; + } + + private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { + MLFunction3, Theory> begin_theory = + MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + + TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); + Path topDir = source.getParent(); + return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) + .retrieveNow(Implicits.theoryConverter(), isabelle); + } +} diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 00e6addb188..46343277e1d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -230,6 +230,132 @@ fun go_run (state, thy) = return this.result; } + protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0, IsabelleTranslationSettings settings, long timeout_seconds) { + notifyProcessStarted(); + ToplevelState toplevel = ToplevelState.apply(isabelle); + + MLFunction2>> parse_text = MLValue.compileFunction(""" + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + + MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + + LOGGER.info("Parsing theory..."); + notifyParsingStarted(); + try { + java.util.List> transitionsAndTexts = new ArrayList<>(); + parse_text.apply(thy0, getSequentTranslation(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()).retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle).foreach(transitionsAndTexts::add); + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()).retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } + } catch (Exception e) { + notifyParsingError(e); + return null; + } + notifyParsingFinished(); + LOGGER.info("Finished Parsing"); + + String Try = thy0.importMLStructureNow("Try0", isabelle); + MLFunction try_function = MLValue.compileFunction(""" + fn (state) => + let + val p_state = Toplevel.proof_of state; + in + \s""" + Try + ".try0 (SOME (seconds 5.0)) ([], [], [], []) p_state" + """ + end + """, isabelle, Implicits.toplevelStateConverter(), de.unruh.isabelle.mlvalue.Implicits.booleanConverter()); + + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); + String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); + String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); + + MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = MLValue.compileFunction(""" + fn (state, thy, adds, dels) => + let + val override = {add=[],del=[],only=false}; + fun go_run (state, thy) = + let + val p_state = Toplevel.proof_of state; + val ctxt = Proof.context_of p_state; + val params =\s""" + Sledgehammer_Commands + """ + .default_params thy + [("timeout",\"""" + (timeout_seconds - 5) + """ + "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; + val results =\s""" + sledgehammer + """ + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds\s + """ + (timeout_seconds + 100) + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); + + Builder> listBuilder = scala.collection.immutable.List.newBuilder(); + scala.collection.immutable.List emptyList = listBuilder.result(); + + SledgehammerResult result = null; + SledgehammerResult tryResult = null; + LOGGER.info("Trying..."); + notifySledgehammerStarted(); + try { + Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())).retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); + Boolean tryResultSuccess = (Boolean) try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()).retrieveNow(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + if (tryResultSuccess) { + tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); + this.result = tryResult; + notifySledgehammerFinished(); + notifyProcessFinished(); + LOGGER.info("Sledgehammer result: " + this.result); + return this.result; + } + Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); + result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); + this.result = result; + } catch (TimeoutException exception) { + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = result; + notifyProcessTimeout(); + } catch (InterruptedException exception) { + result = new SledgehammerResult(Option.apply(null)); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); + } catch (Exception exception) { + if (exception.getMessage().contains("Timeout after")) { + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = result; + notifyProcessTimeout(); + } else { + LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); + exception.printStackTrace(); + result = new SledgehammerResult(Option.apply(null)); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); + } + } + + notifySledgehammerFinished(); + + notifyProcessFinished(); + + LOGGER.info("Sledgehammer result: " + this.result); + return this.result; + } + private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 13d7f2fa815..e31a3a44d0b 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -8,10 +8,9 @@ import de.uka.ilkd.key.control.DefaultUserInterfaceControl; import de.uka.ilkd.key.control.UserInterfaceControl; import de.uka.ilkd.key.gui.isabelletranslation.IllegalFormulaException; -import de.uka.ilkd.key.gui.isabelletranslation.IsabelleProblem; -import de.uka.ilkd.key.gui.isabelletranslation.IsabelleSolverListener; -import de.uka.ilkd.key.gui.isabelletranslation.IsabelleTranslator; +import de.uka.ilkd.key.gui.isabelletranslation.*; import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.macros.FullPropositionalExpansionMacro; import de.uka.ilkd.key.macros.SMTPreparationMacro; import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.proof.Node; @@ -62,7 +61,7 @@ public class Main { private static final PrintStream STDOUT = System.out; private static final PrintStream STDERR = System.err; - private static final long timeoutSeconds = 60; + private static final long timeoutSeconds = 30; private static Path outDir; @@ -520,9 +519,13 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole UserInterfaceControl uic = new DefaultUserInterfaceControl(); SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + FullPropositionalExpansionMacro expansionMacro = new FullPropositionalExpansionMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + LOGGER.info("Prep done, {} goals remaining", papi.getProof().openGoals().size()); + expansionMacro.applyTo(uic, papi.getProof(), papi.getProof().openGoals(), null, null); + LOGGER.info("Expansion done, {} goals remaining", papi.getProof().openGoals().size()); } catch (Exception e) { e.printStackTrace(); return; @@ -576,9 +579,13 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa SMTPreparationMacro smtMacro = new SMTPreparationMacro(); + FullPropositionalExpansionMacro expansionMacro = new FullPropositionalExpansionMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); + LOGGER.info("Prep done, {} goals remaining", papi.getProof().openGoals().size()); + expansionMacro.applyTo(uic, papi.getProof(), papi.getProof().openGoals(), null, null); + LOGGER.info("Expansion done, {} goals remaining", papi.getProof().openGoals().size()); } catch (Exception e) { e.printStackTrace(); return; @@ -750,6 +757,7 @@ class TimedListener implements IsabelleSolverListener { long buildingTime = 0L; Goal goal; long goalNumber; + long totalTime; public TimedListener(Goal g, long goalNumber) { goal = g; @@ -792,11 +800,14 @@ public void buildingFailed(IsabelleProblem problem, Exception e) { @Override public void processStarted(IsabelleProblem problem) { - System.out.println("Starting Isabelle..."); + totalTime = System.currentTimeMillis(); } @Override public void processStopped(IsabelleProblem problem) { + totalTime = System.currentTimeMillis() - totalTime; + updateIsabelleTime(input, contractName, goal, totalTime); + String isabelleTranslation = problem.getSequentTranslation(); updateIsabelleTranslationLines(input, contractName, goal, countLines(isabelleTranslation + problem.getPreamble())); try { @@ -842,9 +853,10 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { } Services services = proof.getServices(); IsabelleTranslator translator = new IsabelleTranslator(services); + IsabelleLauncher launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); + List problems = new ArrayList<>(); goals.forEach((Goal goal) -> { - long totalTime = System.currentTimeMillis(); IsabelleProblem problem; try { problem = translator.translateProblem(goal); @@ -854,10 +866,10 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { return; } problem.addListener(new TimedListener(goal, goal.getTime())); - problem.sledgehammer(timeoutSeconds); - totalTime = System.currentTimeMillis() - totalTime; - updateIsabelleTime(input, contractName, goal, totalTime); + + problems.add(problem); }); + launcher.try0ThenSledgehammerAll(problems, timeoutSeconds); } private static void saveFlaggedTranslations() { From 17499135241245dd8b7475794121666b20ea4ed4 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 20 Apr 2024 20:47:26 +0200 Subject: [PATCH 153/248] observer function naming fix --- .../key/gui/isabelletranslation/ObserverFunctionHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java index 88467f57175..7dd90f7d526 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java @@ -33,7 +33,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr functionName = op.name().toString().replace("<" + m.group(1) + ">", "_" + m.group(1)) .replace("::", "_").replace("$", "").replace(".", "_"); } else { - functionName = op.name().toString().replace("::", "_").replace("$", ""); + functionName = op.name().toString().replace("::", "_").replace("$", "").replace(".", "_"); } trans.addKnownSymbol(term, new StringBuilder(functionName)); } From 4fa03e77b37413aff499a63884cafe356c24dc0a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 20 Apr 2024 20:48:28 +0200 Subject: [PATCH 154/248] move logger outputs in IsabelleProblem to debug --- .../isabelletranslation/IsabelleProblem.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 46343277e1d..5d49f920097 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -58,7 +58,7 @@ public SledgehammerResult getResult() { } public SledgehammerResult sledgehammer(long timeout_seconds) { - LOGGER.info("Starting Isabelle..."); + LOGGER.debug("Starting Isabelle..."); notifyProcessStarted(); IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); @@ -79,7 +79,7 @@ public SledgehammerResult sledgehammer(long timeout_seconds) { return null; } - LOGGER.info("Opening theory..."); + LOGGER.debug("Opening theory..."); Theory thy0 = beginTheory(getSequentTranslation(), Path.of((settings.getTranslationPath() + "\\Translation.thy")), isabelle); ToplevelState toplevel = ToplevelState.apply(isabelle); @@ -101,7 +101,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - LOGGER.info("Parsing theory..."); + LOGGER.debug("Parsing theory..."); notifyParsingStarted(); try { java.util.List> transitionsAndTexts = new ArrayList<>(); @@ -122,7 +122,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, return null; } notifyParsingFinished(); - LOGGER.info("Finished Parsing"); + LOGGER.debug("Finished Parsing"); String Try = thy0.importMLStructureNow("Try0", isabelle); MLFunction try_function = @@ -176,7 +176,7 @@ fun go_run (state, thy) = SledgehammerResult result = null; SledgehammerResult tryResult = null; - LOGGER.info("Trying..."); + LOGGER.debug("Trying..."); notifySledgehammerStarted(); try { Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), @@ -190,7 +190,7 @@ fun go_run (state, thy) = this.result = tryResult; notifySledgehammerFinished(); notifyProcessFinished(); - LOGGER.info("Sledgehammer result: " + this.result); + LOGGER.debug("Sledgehammer result: " + this.result); return this.result; } Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); @@ -226,7 +226,7 @@ fun go_run (state, thy) = notifyProcessFinished(); - LOGGER.info("Sledgehammer result: " + this.result); + LOGGER.debug("Sledgehammer result: " + this.result); return this.result; } @@ -248,7 +248,7 @@ protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0 MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - LOGGER.info("Parsing theory..."); + LOGGER.debug("Parsing theory..."); notifyParsingStarted(); try { java.util.List> transitionsAndTexts = new ArrayList<>(); @@ -263,7 +263,7 @@ protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0 return null; } notifyParsingFinished(); - LOGGER.info("Finished Parsing"); + LOGGER.debug("Finished Parsing"); String Try = thy0.importMLStructureNow("Try0", isabelle); MLFunction try_function = MLValue.compileFunction(""" @@ -308,7 +308,7 @@ fun go_run (state, thy) = SledgehammerResult result = null; SledgehammerResult tryResult = null; - LOGGER.info("Trying..."); + LOGGER.debug("Trying..."); notifySledgehammerStarted(); try { Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())).retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); @@ -318,7 +318,7 @@ fun go_run (state, thy) = this.result = tryResult; notifySledgehammerFinished(); notifyProcessFinished(); - LOGGER.info("Sledgehammer result: " + this.result); + LOGGER.debug("Sledgehammer result: " + this.result); return this.result; } Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); @@ -352,7 +352,7 @@ fun go_run (state, thy) = notifyProcessFinished(); - LOGGER.info("Sledgehammer result: " + this.result); + LOGGER.debug("Sledgehammer result: " + this.result); return this.result; } From 2d0f65d5f1f408b3b821c45f1232b8e138104010 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 21 Apr 2024 11:39:21 +0200 Subject: [PATCH 155/248] remove settings parameter from individual sledgehammer calls, fix bug in try0Sledghammerall --- .../ilkd/key/gui/isabelletranslation/IsabelleLauncher.java | 7 +++++-- .../ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 98251ea07c7..1860cbad871 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -46,9 +46,12 @@ public List try0ThenSledgehammerAll(List pr LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); } - //thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); - List results = problems.stream().map((problem) -> problem.try0ThenSledgehammer(isabelle, thy0, settings, timeout_seconds)).toList(); + List results = new ArrayList<>(); + for (IsabelleProblem problem : problems) { + results.add(problem.try0ThenSledgehammer(isabelle, thy0, timeout_seconds)); + } LOGGER.info("Completed all problems"); isabelle.destroy(); return results; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 5d49f920097..1b5ff1fa1c0 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -230,7 +230,7 @@ fun go_run (state, thy) = return this.result; } - protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0, IsabelleTranslationSettings settings, long timeout_seconds) { + protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0, long timeout_seconds) { notifyProcessStarted(); ToplevelState toplevel = ToplevelState.apply(isabelle); From 2817fc74f8fd9f351ecae674c47531f815ac8309 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 21 Apr 2024 11:41:09 +0200 Subject: [PATCH 156/248] logger outputs and setting max steps to max value --- .../src/test/java/evaluation/Main.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index e31a3a44d0b..ac370bc169f 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -621,7 +621,7 @@ private static void runWithKeYAuto(Path input, String contractName, ImmutableLis StrategyProperties properties = new StrategyProperties(); Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(1000000); + proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); proof.getSettings().getStrategySettings().setTimeout(timeoutSeconds * 1000); for (Goal g : goals) { @@ -752,6 +752,7 @@ private static void runIsabelleToFile(Path input, String contractName, Immutable class TimedListener implements IsabelleSolverListener { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolverListener.class); long sledgehammerTime = 0L; long parsingTime = 0L; long buildingTime = 0L; @@ -801,6 +802,7 @@ public void buildingFailed(IsabelleProblem problem, Exception e) { @Override public void processStarted(IsabelleProblem problem) { totalTime = System.currentTimeMillis(); + LOGGER.info("Started on goal {} of contract {} in file {}", goalNumber, contractName, input); } @Override @@ -822,6 +824,8 @@ public void processStopped(IsabelleProblem problem) { String isabelleProof = problem.getResult().getSuccessfulTactic(); updateIsabelleProof(input, contractName, goal, isabelleProof); } + + LOGGER.info("Result: {}", problem.getResult()); } @Override From 838bbcd2b31bec3bd01297eca14fbfac654ec2f2 Mon Sep 17 00:00:00 2001 From: BookWood Date: Sun, 21 Apr 2024 18:58:10 +0200 Subject: [PATCH 157/248] fix unknowns with # --- .../gui/isabelletranslation/UninterpretedSymbolsHandler.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java index d024644477b..ab20cacb122 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java @@ -70,7 +70,8 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr SortedOperator op = (SortedOperator) term.op(); if (trans.isNewSymbol(term)) { String name = PREFIX + op.name().toString(); - trans.addKnownSymbol(term, new StringBuilder(name.replace("::", "_").replace(".", "_"))); + trans.addKnownSymbol(term, new StringBuilder(name.replace("::", "_").replace(".", "_") + .replace("$", "_").replace("#", "_"))); } String name = trans.getKnownSymbol(term).toString(); From 59529ff6181c2db2e65f771b94bd62a7c6b86c45 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 21 Apr 2024 23:53:43 +0200 Subject: [PATCH 158/248] add assumption to locale to make sure all fields are distinct. --- .../gui/isabelletranslation/FieldHandler.java | 1 + .../IsabelleMasterHandler.java | 21 +++++++++++++++--- .../IsabelleTranslator.java | 22 +++++++++++++++++-- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java index 7496a113d4c..b1a0972ee15 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java @@ -48,6 +48,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr return new StringBuilder(fieldName); } trans.addKnownSymbol(term, new StringBuilder(fieldName)); + trans.addField((Function) op); } return trans.getKnownSymbol(term); } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java index 4a16b019313..b18c233c124 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java @@ -2,6 +2,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; +import de.uka.ilkd.key.logic.op.Function; import de.uka.ilkd.key.logic.op.Operator; import de.uka.ilkd.key.logic.op.SortedOperator; import de.uka.ilkd.key.logic.sort.ArraySort; @@ -13,6 +14,8 @@ public class IsabelleMasterHandler { + private final Services services; + private final List exceptions = new ArrayList<>(); private final List handlers; @@ -31,7 +34,9 @@ public class IsabelleMasterHandler { private final Map handlerMap = new IdentityHashMap<>(); private final List locales = new ArrayList<>(); - private final List constDeclarations = new ArrayList<>(); + private final Collection constDeclarations = new HashSet<>(); + + private final Collection newFields = new HashSet<>(); /** * Create a new handler with the default set of smt handlers. @@ -44,6 +49,7 @@ public class IsabelleMasterHandler { */ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { + this.services = services; List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); predefinedSorts.put(Sort.ANY, new StringBuilder("any")); predefinedSorts.put(Sort.FORMULA, new StringBuilder("bool")); @@ -112,6 +118,15 @@ private StringBuilder handleAsUnknownValue(Term problem) { return abbr; } + protected boolean addField(Function field) { + assert (field.sort() == services.getNamespaces().sorts().lookup("Field") && field.arity() == 0); + return newFields.add(unknownValues.get(field)); + } + + protected Collection getNewFields() { + return newFields; + } + private void addConstDeclaration(Term term) { StringBuilder decl = new StringBuilder(); assert unknownValues.get(term.op()) != null; @@ -139,7 +154,7 @@ private void addConstDeclaration(Term term) { decl.append((translateSortName(term.sort()))); decl.append("\""); } - constDeclarations.add(decl); + constDeclarations.add(decl.toString()); } boolean isNewSymbol(Term term) { @@ -215,7 +230,7 @@ StringBuilder getKnownSymbol(Term term) { return unknownValues.get(term.op()); } - List getConstDeclarations() { + Collection getConstDeclarations() { return constDeclarations; } diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 31e4ff5beea..9aa0e1ea620 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -80,7 +80,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(" + ").append(locale); } - List constDecls = masterHandler.getConstDeclarations(); + Collection constDecls = masterHandler.getConstDeclarations(); if (!constDecls.isEmpty() && locale_empty) { sequentTranslation.append(" = "); sequentTranslation.append(locales.remove(0)); @@ -88,11 +88,16 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } else if (!constDecls.isEmpty()) { sequentTranslation.append(" + ").append(LINE_ENDING); } - for (StringBuilder constDecl : constDecls) { + for (String constDecl : constDecls) { sequentTranslation.append(LINE_ENDING).append(constDecl); } sequentTranslation.append(LINE_ENDING); + if (!masterHandler.getNewFields().isEmpty()) { + sequentTranslation.append("assumes distinct_fields:"); + sequentTranslation.append(getDistinctFieldLemma(masterHandler.getNewFields())); + sequentTranslation.append(LINE_ENDING); + } sequentTranslation.append("begin").append(LINE_ENDING); @@ -118,6 +123,19 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } + private StringBuilder getDistinctFieldLemma(Collection newFields) { + if (newFields.isEmpty()) + return new StringBuilder(); + String commaSeparatedFields = String.join(",", newFields); + StringBuilder distinctFieldLemma = new StringBuilder(); + distinctFieldLemma.append("\"(distinct ["); + distinctFieldLemma.append(commaSeparatedFields); + distinctFieldLemma.append("]) \\ (({"); + distinctFieldLemma.append(commaSeparatedFields); + distinctFieldLemma.append("} \\ image arr (UNIV::int set)) = {})\""); + return distinctFieldLemma; + } + private void implementSorts(StringBuilder sequentTranslation, Queue sortImplementationQueue, Map sortImplemented, Map> sortParentsMap, IsabelleMasterHandler masterHandler) { if (sortImplementationQueue.isEmpty()) { From 77ab9a61cb1946e49143deca28f6046033ae56a2 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 21 Apr 2024 23:54:26 +0200 Subject: [PATCH 159/248] Change to LOGGER from System.out.println, parallelize Z3, hopefully correct goal index --- .../src/test/java/evaluation/Main.java | 56 ++++++++++++------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index ac370bc169f..1a53fb196aa 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -185,7 +185,7 @@ private static void saveStatisticsCSVFile(Path input) { sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); - sb.append(goal.getTime()); + sb.append(goal.node().getStepIndex()); sb.append(","); sb.append(entry.keyState); sb.append(","); @@ -271,7 +271,7 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); - sb.append(goal.getTime()); + sb.append(goal.node().getStepIndex()); sb.append(","); sb.append(entry.keyState); sb.append(","); @@ -342,7 +342,7 @@ public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - System.out.println("Visiting " + file.toString()); + LOGGER.info("Visiting " + file.toString()); if (file.toString().endsWith(".key") && checkNonTrivialNoErrorQuickLoad(file)) { appendValid(file.toAbsolutePath()); } @@ -439,17 +439,21 @@ private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { tl.runWithTimeout(prep, 60, TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException e) { LOGGER.error("Prep timeout {}", file); + executorService.shutdown(); return false; } if (!success.get()) { LOGGER.error("Prep failed {}", file); + executorService.shutdown(); return false; } if (proof.openGoals().isEmpty()) { LOGGER.error("No open goals found after Preparation {}", file); + executorService.shutdown(); return false; } + executorService.shutdown(); return true; } @@ -504,7 +508,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole if (input.toString().endsWith(".key")) { ProofApi papi = null; try { - System.out.println("Processing " + input); + LOGGER.info("Processing " + input); ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); papi = pm.getLoadedProof(); @@ -532,7 +536,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole } } if (proof.openGoals().isEmpty()) { - System.out.println("No open goals found after Preparation"); + LOGGER.info("No open goals found after Preparation"); return; } ImmutableList goals = proof.openGoals(); @@ -575,7 +579,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa UserInterfaceControl uic = new DefaultUserInterfaceControl(); String contractName = proof.name().toString(); - System.out.println("Processing contract " + contractName + " of " + input); + LOGGER.info("Processing contract " + contractName + " of " + input); SMTPreparationMacro smtMacro = new SMTPreparationMacro(); @@ -592,7 +596,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa } } if (proof.openGoals().isEmpty()) { - System.out.println("No open goals found after Preparation"); + LOGGER.info("No open goals found after Preparation"); return; } ImmutableList goals = proof.openGoals(); @@ -626,7 +630,7 @@ private static void runWithKeYAuto(Path input, String contractName, ImmutableLis for (Goal g : goals) { int nodes = -g.proof().getStatistics().nodes; - long goalTime = g.getTime(); + long goalTime = g.node().getStepIndex(); long manualTime = System.currentTimeMillis(); uic.getProofControl().startFocussedAutoMode(null, g); @@ -639,8 +643,8 @@ private static void runWithKeYAuto(Path input, String contractName, ImmutableLis updateKeYNodes(input, contractName, g, nodes); long keyTime = statistics.autoModeTimeInMillis; - System.out.println(" KeY statistics: " + keyTime); - System.out.println(" Manual logging: " + manualTime); + LOGGER.info(" KeY statistics: " + keyTime); + LOGGER.info(" Manual logging: " + manualTime); updateKeYState(input, contractName, g, !(g.proof().isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); updateKeYTime(input, contractName, g, manualTime); @@ -674,7 +678,7 @@ public TimedListener(Goal g, long goalNumber) { @Override public void launcherStopped(SolverLauncher launcher, Collection finishedSolvers) { - System.out.println("Z3 finished (" + finishedSolvers.size() + " solvers)."); + LOGGER.info("Z3 finished ({} solvers).", finishedSolvers.size()); translationAndZ3Time = System.currentTimeMillis() - translationAndZ3Time; for (SMTSolver solver : finishedSolvers) { @@ -721,25 +725,37 @@ public void launcherStarted(Collection problems, Collection solverTypes, SolverLauncher launcher) { translationAndZ3Time = System.currentTimeMillis(); - System.out.println("Running Z3 ..." + translationAndZ3Time); + LOGGER.info("Running Z3 ..."); } } + Collection> launcherRunnables = new LinkedBlockingQueue<>(); + Stream problems = goals.stream().map(SMTProblem::new); Services services = proof.getServices(); - problems.forEach((SMTProblem problem) -> { + + problems.forEach((SMTProblem problem) -> launcherRunnables.add(() -> { SolverLauncher launcher = new SolverLauncher(settings); - launcher.addListener(new TimedListener(problem.getGoal(), problem.getGoal().getTime())); + launcher.addListener(new TimedListener(problem.getGoal(), problem.getGoal().node().getStepIndex())); try { launcher.launch(problem, services, Z3_SOLVER); } catch (Exception e) { LOGGER.error("Exception during Z3... {}", e.getMessage()); e.printStackTrace(); updateZ3State(input, contractName, problem.getGoal(), ProofState.ERROR); - updateZ3State(input, contractName, problem.getGoal(), e.getMessage()); + updateZ3State(input, contractName, problem.getGoal(), e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); } - }); + return null; + })); + + ExecutorService executorService = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); + try { + executorService.invokeAll(launcherRunnables); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + executorService.shutdown(); } private static void runIsabelleToFile(Path input, String contractName, ImmutableList goals) @@ -779,7 +795,7 @@ public void parsingFinished(IsabelleProblem problem) { @Override public void parsingFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage()); + updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); } @Override @@ -796,7 +812,7 @@ public void buildingFinished(IsabelleProblem problem) { @Override public void buildingFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage()); + updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); } @Override @@ -847,7 +863,7 @@ public void sledgehammerFinished(IsabelleProblem problem) { @Override public void sledgehammerFailed(IsabelleProblem problem, Exception e) { updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage()); + updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); } @Override @@ -869,7 +885,7 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { LOGGER.error("Translation failed: {}", e.getMessage()); return; } - problem.addListener(new TimedListener(goal, goal.getTime())); + problem.addListener(new TimedListener(goal, goal.node().getStepIndex())); problems.add(problem); }); From fb11bffbc92c1fe410544646e7195a92d3bf1b30 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 21 Apr 2024 23:58:38 +0200 Subject: [PATCH 160/248] stop Z3 launcher to hopefully prevent zombie Z3 instances --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 1a53fb196aa..4c5a1d3e04f 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -745,6 +745,8 @@ public void launcherStarted(Collection problems, e.printStackTrace(); updateZ3State(input, contractName, problem.getGoal(), ProofState.ERROR); updateZ3State(input, contractName, problem.getGoal(), e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); + } finally { + launcher.stop(); } return null; })); From bca4777f0da239ba2ab941c32799636891cac905 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 22 Apr 2024 11:00:20 +0200 Subject: [PATCH 161/248] add created field to distinct field lemma --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 9aa0e1ea620..a0e7de0d9a6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -130,9 +130,9 @@ private StringBuilder getDistinctFieldLemma(Collection newFields) StringBuilder distinctFieldLemma = new StringBuilder(); distinctFieldLemma.append("\"(distinct ["); distinctFieldLemma.append(commaSeparatedFields); - distinctFieldLemma.append("]) \\ (({"); + distinctFieldLemma.append(", created]) \\ (({"); distinctFieldLemma.append(commaSeparatedFields); - distinctFieldLemma.append("} \\ image arr (UNIV::int set)) = {})\""); + distinctFieldLemma.append(", created} \\ image arr (UNIV::int set)) = {})\""); return distinctFieldLemma; } From 198ca2fc3fecb11e103d988d251e2ed06cf87d5e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 22 Apr 2024 20:42:51 +0200 Subject: [PATCH 162/248] move outdir to home/tmp --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 4c5a1d3e04f..38ed2df6f77 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -52,7 +52,7 @@ public class Main { && it.getName().equals("Z3")) .findFirst().orElse(null); - private static final Path VALID_LIST_PATH = Paths.get("/tmp/valid_list.txt"); + private static final Path VALID_LIST_PATH = Paths.get(System.getenv("user.home"), "/tmp/valid_list.txt"); private static final Set VALID_SET = new HashSet<>(); @@ -102,7 +102,7 @@ private enum ProofState { } public static void main(String[] args) { - outDir = Paths.get("/tmp/benchmark" + outDir = Paths.get(System.getenv("user.home"), "/tmp/benchmark" + System.currentTimeMillis()); try { Files.createDirectories(outDir); From 622fe1796d4ad95ca982580afa95ce243afd93ad Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 00:55:58 +0200 Subject: [PATCH 163/248] fix last commit --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 38ed2df6f77..229251aad51 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -52,7 +52,7 @@ public class Main { && it.getName().equals("Z3")) .findFirst().orElse(null); - private static final Path VALID_LIST_PATH = Paths.get(System.getenv("user.home"), "/tmp/valid_list.txt"); + private static final Path VALID_LIST_PATH = Path.of(System.getProperty("user.home"), "/tmp/valid_list.txt"); private static final Set VALID_SET = new HashSet<>(); @@ -102,7 +102,7 @@ private enum ProofState { } public static void main(String[] args) { - outDir = Paths.get(System.getenv("user.home"), "/tmp/benchmark" + outDir = Path.of(System.getProperty("user.home"), "/tmp/benchmark" + System.currentTimeMillis()); try { Files.createDirectories(outDir); From acad9df75392d06537ad26634dac76ccec2a7abb Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 01:10:06 +0200 Subject: [PATCH 164/248] example now dependent on user home --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 229251aad51..8d1e7c64408 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -129,7 +129,7 @@ private static void run() { return; } for (String s : pathStrings) { - Path p = Paths.get(s); + Path p = Path.of(System.getProperty("user.home"), s); VALID_SET.add(p); processFile(p, true, true, true); saveStatisticsCSVFile(p); From a3ed40f9175efe9456426eafb5935954d0e78bb7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 01:13:26 +0200 Subject: [PATCH 165/248] need to create directories before session files --- .../gui/isabelletranslation/IsabelleTranslationSettings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java index 361d655f936..783762bbf19 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java @@ -85,8 +85,8 @@ protected boolean createSessionFiles() { String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining(System.lineSeparator())); try { - Files.write(sessionRootPath, sessionRoot.getBytes()); Files.createDirectories(sessionDocumentPath.getParent()); + Files.write(sessionRootPath, sessionRoot.getBytes()); Files.write(sessionDocumentPath, sessionDocument.getBytes()); LOGGER.info("Created Isabelle session files at: {}", translationPath); return sessionFilesPresent = true; From ce9d4058f607059f2d3c6fadcbd843d15b7a248e Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 01:36:21 +0200 Subject: [PATCH 166/248] write translation files on launcher start --- .../isabelletranslation/IsabelleLauncher.java | 2 ++ .../TranslationAction.java | 26 +++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 1860cbad871..42f09412984 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -34,6 +35,7 @@ public List try0ThenSledgehammerAll(List pr if (problems.isEmpty()) { return new ArrayList<>(); } + TranslationAction.writeTranslationFiles(problems.get(0)); ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); try { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java index cdbb009385b..f9097282e07 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java @@ -34,8 +34,6 @@ private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); - File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); IsabelleProblem translation; try { translation = translator.translateProblem(mediator.getSelectedGoal()); @@ -44,15 +42,7 @@ private void generateTranslation() { return; } - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); - Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); - LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); - } catch (IOException e) { - LOGGER.error("Failed to save translation", e); - return; - } + writeTranslationFiles(translation); SledgehammerResult result = translation.sledgehammer(30); @@ -81,4 +71,18 @@ private void generateTranslation() { isabelleJEdit.start();*/ } + + protected static void writeTranslationFiles(IsabelleProblem translation) { + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); + File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); + try { + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); + Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); + LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); + } catch (IOException e) { + LOGGER.error("Failed to save translation", e); + return; + } + } } From a41e62fc97d64afa18b8214ae8986b82cced78f5 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 01:58:15 +0200 Subject: [PATCH 167/248] add shutdown hook for saving csv and increase concurrency --- .../isabelletranslation/IsabelleLauncher.java | 35 +++++++++++++++++++ .../src/test/java/evaluation/Main.java | 5 +-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 42f09412984..780df5c3ec3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -18,7 +18,9 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.concurrent.*; public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); @@ -73,4 +75,37 @@ private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } + + public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int coreCount) throws IOException { + ExecutorService executorService = new ThreadPoolExecutor(coreCount, coreCount, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>()); + Collection> tasks = new LinkedBlockingDeque<>(); + + if (problems.isEmpty()) { + return; + } + TranslationAction.writeTranslationFiles(problems.get(0)); + ArrayList sessionRoots = new ArrayList<>(); + sessionRoots.add(settings.getTranslationPath()); + try { + Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); + isabelle = new Isabelle(setup); + } catch (Exception e) { + LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); + throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); + } + thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); + + List results = new ArrayList<>(); + problems.forEach((IsabelleProblem problem) -> tasks.add(() -> problem.try0ThenSledgehammer(isabelle, thy0, timeoutSeconds))); + + try { + executorService.invokeAll(tasks); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } } diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 8d1e7c64408..5a0636fb715 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -116,6 +116,7 @@ public static void main(String[] args) { } updateZ3ProvableList(); } else { + Runtime.getRuntime().addShutdownHook(new Thread(Main::saveStatisticsCSV)); run(); } } @@ -751,7 +752,7 @@ public void launcherStarted(Collection problems, return null; })); - ExecutorService executorService = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); + ExecutorService executorService = new ThreadPoolExecutor(6, 6, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); try { executorService.invokeAll(launcherRunnables); } catch (InterruptedException e) { @@ -891,7 +892,7 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { problems.add(problem); }); - launcher.try0ThenSledgehammerAll(problems, timeoutSeconds); + launcher.try0ThenSledgehammerAllPooled(problems, timeoutSeconds, 2); } private static void saveFlaggedTranslations() { From d7ec385e15a4fb33d8b5834503bf4a85aee15bc2 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 02:01:38 +0200 Subject: [PATCH 168/248] switch to expansion without splits and set indices for goals --- .../src/test/java/evaluation/Main.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 5a0636fb715..50c168f47d3 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -11,6 +11,7 @@ import de.uka.ilkd.key.gui.isabelletranslation.*; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.macros.FullPropositionalExpansionMacro; +import de.uka.ilkd.key.macros.PropositionalExpansionWithSimplificationMacro; import de.uka.ilkd.key.macros.SMTPreparationMacro; import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.proof.Node; @@ -524,7 +525,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole UserInterfaceControl uic = new DefaultUserInterfaceControl(); SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - FullPropositionalExpansionMacro expansionMacro = new FullPropositionalExpansionMacro(); + PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); @@ -540,6 +541,7 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole LOGGER.info("No open goals found after Preparation"); return; } + proof.setStepIndices(); ImmutableList goals = proof.openGoals(); @@ -584,7 +586,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - FullPropositionalExpansionMacro expansionMacro = new FullPropositionalExpansionMacro(); + PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { try { smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); @@ -600,6 +602,7 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa LOGGER.info("No open goals found after Preparation"); return; } + proof.setStepIndices(); ImmutableList goals = proof.openGoals(); STATS.computeIfAbsent(input, k -> new HashMap<>()); From 33ac48825fa5b0964deae5cdacbce9a3c6f1e405 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 11:37:43 +0200 Subject: [PATCH 169/248] improve concurrency and resource management --- .../isabelletranslation/IsabelleLauncher.java | 78 ++++++++++++------- 1 file changed, 50 insertions(+), 28 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 780df5c3ec3..42f19982690 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -1,5 +1,6 @@ package de.uka.ilkd.key.gui.isabelletranslation; +import de.uka.ilkd.key.util.Pair; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.ListConverter; @@ -26,8 +27,6 @@ public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); private final IsabelleTranslationSettings settings; - private Isabelle isabelle; - private Theory thy0; public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { this.settings = settings; @@ -38,19 +37,10 @@ public List try0ThenSledgehammerAll(List pr return new ArrayList<>(); } TranslationAction.writeTranslationFiles(problems.get(0)); - ArrayList sessionRoots = new ArrayList<>(); - sessionRoots.add(settings.getTranslationPath()); - try { - Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); - isabelle = new Isabelle(setup); - } catch (Exception e) { - LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); - throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); - } - thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + Isabelle isabelle = startIsabelleInstance(); + Thread destroyIsabelle = new Thread(isabelle::destroy); + Runtime.getRuntime().addShutdownHook(destroyIsabelle); + Theory thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); List results = new ArrayList<>(); for (IsabelleProblem problem : problems) { @@ -58,6 +48,7 @@ public List try0ThenSledgehammerAll(List pr } LOGGER.info("Completed all problems"); isabelle.destroy(); + Runtime.getRuntime().removeShutdownHook(destroyIsabelle); return results; } @@ -77,15 +68,56 @@ private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { } public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int coreCount) throws IOException { - ExecutorService executorService = new ThreadPoolExecutor(coreCount, coreCount, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>()); - Collection> tasks = new LinkedBlockingDeque<>(); + ExecutorService executorService = Executors.newFixedThreadPool(coreCount); + Collection>> tasks = new LinkedBlockingDeque<>(); + LinkedBlockingDeque> resourceInstances = new LinkedBlockingDeque<>(); + LinkedBlockingDeque problemsQueue = new LinkedBlockingDeque<>(problems); + + Thread shutdownResources = new Thread(() -> { + for (Pair resources : resourceInstances) { + resources.first.destroy(); + } + executorService.shutdown(); + }); + Runtime.getRuntime().addShutdownHook(shutdownResources); if (problems.isEmpty()) { return; } TranslationAction.writeTranslationFiles(problems.get(0)); + + for (int i = 0; i < coreCount; i++) { + Isabelle isabelle = startIsabelleInstance(); + Theory thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + resourceInstances.add(new Pair<>(isabelle, thy0)); + + tasks.add(()-> { + IsabelleProblem problem; + Pair resources; + while ((problem = problemsQueue.poll()) != null && (resources = resourceInstances.poll()) != null) { + problem.try0ThenSledgehammer(resources.first, resources.second, timeoutSeconds); + resourceInstances.add(resources); + } + return null; + }); + } + + LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); + + try { + executorService.invokeAll(tasks); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } finally { + shutdownResources.start(); + Runtime.getRuntime().removeShutdownHook(shutdownResources); + } + } + + private Isabelle startIsabelleInstance() throws IOException { ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); + Isabelle isabelle; try { Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", JIsabelle.setupSetSessionRoots(sessionRoots, @@ -96,16 +128,6 @@ public void try0ThenSledgehammerAllPooled(List problems, long t LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); } - thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); - LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); - - List results = new ArrayList<>(); - problems.forEach((IsabelleProblem problem) -> tasks.add(() -> problem.try0ThenSledgehammer(isabelle, thy0, timeoutSeconds))); - - try { - executorService.invokeAll(tasks); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } + return isabelle; } } From ffff41701fdc0b00720497ee22471afbd0ec35df Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 11:38:14 +0200 Subject: [PATCH 170/248] take advantage of more Z3 launches, and Isabelle concurrency --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 50c168f47d3..5c8c7cfec60 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -755,7 +755,7 @@ public void launcherStarted(Collection problems, return null; })); - ExecutorService executorService = new ThreadPoolExecutor(6, 6, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); + ExecutorService executorService = Executors.newFixedThreadPool(8); try { executorService.invokeAll(launcherRunnables); } catch (InterruptedException e) { From 5c6dd540762091b67f00718c63a9885a681309da Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 11:38:44 +0200 Subject: [PATCH 171/248] add shadow plugin to create executable jars for evaluation deployment --- keyext.isabelletranslation/build.gradle | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/keyext.isabelletranslation/build.gradle b/keyext.isabelletranslation/build.gradle index 3c6ea840523..7d3eec26544 100644 --- a/keyext.isabelletranslation/build.gradle +++ b/keyext.isabelletranslation/build.gradle @@ -1,3 +1,16 @@ +plugins { + id("com.github.johnrengelman.shadow") version "8.1.1" +} + + +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +shadowJar() { + manifest { + attributes 'Main-Class': 'evaluation.Main' + } + from sourceSets.test.output +} + description "Translate" dependencies { From c6b9e3574ded6f7bca816e30f0842ea2aba491ee Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 11:40:42 +0200 Subject: [PATCH 172/248] remove non pooled sledgehammerAll, was redundant --- .../isabelletranslation/IsabelleLauncher.java | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 42f19982690..0ca903afbe1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -32,26 +32,6 @@ public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IO this.settings = settings; } - public List try0ThenSledgehammerAll(List problems, long timeout_seconds) throws IOException { - if (problems.isEmpty()) { - return new ArrayList<>(); - } - TranslationAction.writeTranslationFiles(problems.get(0)); - Isabelle isabelle = startIsabelleInstance(); - Thread destroyIsabelle = new Thread(isabelle::destroy); - Runtime.getRuntime().addShutdownHook(destroyIsabelle); - Theory thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); - LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); - List results = new ArrayList<>(); - for (IsabelleProblem problem : problems) { - results.add(problem.try0ThenSledgehammer(isabelle, thy0, timeout_seconds)); - } - LOGGER.info("Completed all problems"); - isabelle.destroy(); - Runtime.getRuntime().removeShutdownHook(destroyIsabelle); - return results; - } - private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, From 5a8de7518cca4acd1552422152b535c5ea00d2fa Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 11:41:15 +0200 Subject: [PATCH 173/248] inline begin theory parameter --- .../ilkd/key/gui/isabelletranslation/IsabelleLauncher.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 0ca903afbe1..80ba134f94a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -16,7 +16,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; @@ -32,14 +31,14 @@ public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IO this.settings = settings; } - private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { + private Theory beginTheory(Path source, Isabelle isabelle) { MLFunction3, Theory> begin_theory = MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + TheoryHeader header = header_read.apply("theory Translation imports Main KeYTranslations.TranslationPreamble begin", Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = source.getParent(); return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, @@ -68,7 +67,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t for (int i = 0; i < coreCount; i++) { Isabelle isabelle = startIsabelleInstance(); - Theory thy0 = beginTheory("theory Translation imports Main KeYTranslations.TranslationPreamble begin", settings.getTranslationPath(), isabelle); + Theory thy0 = beginTheory(settings.getTranslationPath(), isabelle); resourceInstances.add(new Pair<>(isabelle, thy0)); tasks.add(()-> { From 62de571b62f77e29b1f1ce5da4d0736a3cb4aa76 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 23 Apr 2024 18:21:46 +0200 Subject: [PATCH 174/248] fix csv header, illegal characters --- .../src/test/java/evaluation/Main.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 5c8c7cfec60..46850839006 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -240,6 +240,10 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append("KeY_state"); sb.append(","); + sb.append("Isabelle_state"); + sb.append(","); + sb.append("Z3_State"); + sb.append(","); sb.append("KeY_time"); sb.append(","); sb.append("KeY_proof_nodes"); @@ -250,8 +254,6 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append("Z3_proof_lines"); sb.append(","); - sb.append("Z3_State"); - sb.append(","); sb.append("Isabelle_build_time"); sb.append(","); sb.append("Isabelle_parse_time"); @@ -263,8 +265,6 @@ private static void saveStatisticsCSV() { sb.append("Isabelle_translation_lines"); sb.append(","); sb.append("Isabelle_proof"); - sb.append(","); - sb.append("Isabelle_state"); sb.append(System.lineSeparator()); for (Map> contractMap : STATS.values()) { @@ -914,7 +914,7 @@ private static void updateIsabelleProof(Path input, String contractName, Goal go if (stats == null) { stats = new StatEntry(input); } - stats.isabelleProofTactic = isabelleProof; + stats.isabelleProofTactic = isabelleProof.replace(",", " ").replace(System.lineSeparator(), " "); STATS.get(input).get(contractName).put(goal, stats); } From d55e4fa9d948dcbaa32802cd23ed2d251d0850f7 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Apr 2024 11:36:23 +0200 Subject: [PATCH 175/248] fix typo of seqGetOutside --- .../UninterpretedSymbolsHandler.preamble.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 38d8c4f9544..5f573b06016 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -213,11 +213,11 @@ typedef Seq = "UNIV::any list set" by auto consts - getSeqOutside::any + seqGetOutside::any setup_lifting type_definition_Seq lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". -lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast getSeqOutside)". +lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast seqGetOutside)". lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". lift_definition seqEmpty::"Seq" is "[]". lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". From 9e87fca9df08dddc5a4caf8a7c69318c201e4c6b Mon Sep 17 00:00:00 2001 From: BookWood Date: Wed, 24 Apr 2024 14:10:19 +0200 Subject: [PATCH 176/248] load smt settings instead of using default instance --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 46850839006..35a9b138707 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -9,6 +9,7 @@ import de.uka.ilkd.key.control.UserInterfaceControl; import de.uka.ilkd.key.gui.isabelletranslation.IllegalFormulaException; import de.uka.ilkd.key.gui.isabelletranslation.*; +import de.uka.ilkd.key.gui.settings.SettingsManager; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.macros.FullPropositionalExpansionMacro; import de.uka.ilkd.key.macros.PropositionalExpansionWithSimplificationMacro; @@ -663,7 +664,7 @@ private static void runZ3ToFile(Path input, String contractName, ImmutableList Date: Wed, 24 Apr 2024 21:10:06 +0200 Subject: [PATCH 177/248] add seqNPerm --- .../UninterpretedSymbolsHandler.preamble.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 5f573b06016..e0617eb7350 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -225,6 +225,9 @@ lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. +fun seqNPerm::"Seq\<Rightarrow>bool" + where "seqNPerm s = seqPerm s (seqDef 0 (seqLen s - 1) (to_any))" + fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" From 50956dea9b5357faafe9fd8e3a2aed9737b25a30 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Apr 2024 21:12:09 +0200 Subject: [PATCH 178/248] add seqNPerm to DefinedSymbolsHandler --- .../ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java | 1 + 1 file changed, 1 insertion(+) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java index 0c6dbc2f042..b8bb96f4316 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java @@ -38,6 +38,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("seqConcat", "seqConcat"); definedFunctions.put("seqSub", "seqSub"); definedFunctions.put("seqPerm", "seqPerm"); + definedFunctions.put("seqNPerm", "seqNPerm"); definedFunctions.put("seqSwap", "seqSwap"); definedFunctions.put("seqRemove", "seqRemove"); definedFunctions.put("seqReverse", "seqReverse"); From 2078118076be68b8ab3bebb84566e7e07ab61b42 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 24 Apr 2024 21:46:05 +0200 Subject: [PATCH 179/248] add seqSwap and seqRemove --- .../UninterpretedSymbolsHandler.preamble.xml | 66 ++++++++++++------- 1 file changed, 42 insertions(+), 24 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index e0617eb7350..9316398d410 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -209,9 +209,26 @@ abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ& declare [[coercion Null2java_lang_Object]] +fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + where "instanceof x type = typeof x type" + typedef Seq = "UNIV::any list set" by auto +axiomatization Seq2any any2Seq Seq_UNIV + where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" + +declare [[coercion Seq2any]] + +instantiation Seq::any +begin +fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" +fun cast_Seq where "cast_Seq (x::any) = any2Seq x" +instance by standard +end + +definition Seq_type::"javaDL_type" where "Seq_type \<equiv> Abs_javaDL_type (UNIV::Seq set)" + consts seqGetOutside::any @@ -231,27 +248,28 @@ fun seqNPerm::"Seq\<Rightarrow>bool" fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" -primrec listIndexOf::"any list\<Rightarrow>any\<Rightarrow>nat" where +primrec listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>nat" where "listIndexOf [] a = undefined" | "listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>nat" is listIndexOf. -axiomatization Seq2any any2Seq Seq_UNIV - where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" +fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" + where "listSwap l i j = +(if \<not>(0\<le>i \<and> i<int (length l) \<and> 0\<le>j \<and> i<int (length l)) +then l +else list_update (list_update l (nat i) (l ! (nat j))) (nat j) (l ! (nat i)))" -declare [[coercion Seq2any]] +lift_definition seqSwap::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" is listSwap. -instantiation Seq::any -begin -fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" -fun cast_Seq where "cast_Seq (x::any) = any2Seq x" -instance by standard -end +fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" + where "listRemove [] _ = []" + | "listRemove (x#xs) 0 = xs" + | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" + +lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s i. (if \<not>(0\<le>i \<and> i<int (length l)) then l else listRemove s (nat i))" -fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" - where "instanceof x type = typeof x type" consts exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" @@ -303,18 +321,18 @@ lemma induct_sum_upper_limit[simp]: assumes "lower<upper" shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f (upper - 1)" proof - - have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" - using assms by auto - have "{upper-1..<upper} = {upper - 1}" - by auto - then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) - then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> by presburger - also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i)" - by simp - finally show ?thesis - using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto + have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" + using assms by auto + have "{upper-1..<upper} = {upper - 1}" + by auto + then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) + then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> by presburger + also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i)" + by simp + finally show ?thesis + using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto qed From 2303777bd37f4f431bbe0bec6edcdb9a7009b479 Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 25 Apr 2024 02:36:45 +0200 Subject: [PATCH 180/248] ensure try0 is not waited on indefinitely --- .../isabelletranslation/IsabelleProblem.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index 1b5ff1fa1c0..b57457ee02d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -183,8 +183,14 @@ fun go_run (state, thy) = new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Boolean tryResultSuccess = (Boolean) try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) - .retrieveNow(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + Future tryResultSuccessF = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) + .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + Boolean tryResultSuccess = false; + try { + tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); + } catch (TimeoutException e){ + tryResultSuccess = false; + } if (tryResultSuccess) { tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); this.result = tryResult; @@ -312,7 +318,14 @@ fun go_run (state, thy) = notifySledgehammerStarted(); try { Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())).retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Boolean tryResultSuccess = (Boolean) try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()).retrieveNow(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + Future tryResultSuccessF = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) + .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); + Boolean tryResultSuccess; + try { + tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); + } catch (TimeoutException e){ + tryResultSuccess = false; + } if (tryResultSuccess) { tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); this.result = tryResult; From 64e64c832280aff23a92fdc58c5e9d879bcc059e Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 25 Apr 2024 02:50:39 +0200 Subject: [PATCH 181/248] fix seqRemove --- .../UninterpretedSymbolsHandler.preamble.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 9316398d410..bbc73da63a4 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -267,8 +267,7 @@ fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" | "listRemove (x#xs) 0 = xs" | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" -lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s i. (if \<not>(0\<le>i \<and> i<int (length l)) then l else listRemove s (nat i))" - +lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s (i::int). (if \<not>(0\<le>i \<and> i<int (length s)) then s else listRemove s (nat i))". consts From 50ad2e8ae113185a00825fbdac34768760959652 Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 25 Apr 2024 15:18:57 +0200 Subject: [PATCH 182/248] seqIndexOf undefined case --- .../UninterpretedSymbolsHandler.preamble.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index bbc73da63a4..d621e59dc69 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -252,7 +252,7 @@ primrec listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>nat" where "listIndexOf [] a = undefined" | "listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" -lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>nat" is listIndexOf. +definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" where "listIndexOf (Rep_Seq (s::Seq)) x \<noteq> undefined \<Longrightarrow> seqIndexOf s x \<equiv> int (listIndexOf (Rep_Seq (s::Seq)) x)" fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" where "listSwap l i j = From 7e7b4008747e9a3e2b9292e8ab73f9d55714de53 Mon Sep 17 00:00:00 2001 From: BookWood Date: Fri, 26 Apr 2024 11:10:58 +0200 Subject: [PATCH 183/248] replace seqIndexOf with nonexhaustive function --- .../UninterpretedSymbolsHandler.preamble.xml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index d621e59dc69..e9de6de3cf3 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -248,11 +248,10 @@ fun seqNPerm::"Seq\<Rightarrow>bool" fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" -primrec listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>nat" where - "listIndexOf [] a = undefined" | - "listIndexOf (x#xs) a = (if (x=a) then 0 else Suc (listIndexOf xs a))" +primrec (nonexhaustive) listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>int" where + "listIndexOf (x#xs) a = (if (x=a) then 0 else 1+(listIndexOf xs a))" -definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" where "listIndexOf (Rep_Seq (s::Seq)) x \<noteq> undefined \<Longrightarrow> seqIndexOf s x \<equiv> int (listIndexOf (Rep_Seq (s::Seq)) x)" +lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" is "listIndexOf". fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" where "listSwap l i j = From e5e73b4bf84156b8134872417b4b95fc777ae1cc Mon Sep 17 00:00:00 2001 From: BookWood Date: Fri, 26 Apr 2024 12:29:13 +0200 Subject: [PATCH 184/248] add back interpretations --- .../UninterpretedSymbolsHandler.preamble.xml | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index e9de6de3cf3..9a607576d90 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -18,8 +18,6 @@ lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>boo lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. - - consts int_Image::"any set" int2any::"int\<Rightarrow>any" @@ -28,6 +26,10 @@ consts axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_Image)" declare [[coercion int2any]] +interpretation int:type_definition int2any any2int int_Image + by simp + + definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" consts @@ -38,6 +40,10 @@ consts axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_Image)" declare [[coercion bool2any]] +interpretation bool:type_definition bool2any any2bool bool_Image + by simp + + definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" @@ -117,6 +123,10 @@ axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSe declare [[coercion LocSet2any]] +interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image + by (rule LocSet_sub_any) + + definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" @@ -135,6 +145,10 @@ axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" declare [[coercion Heap2any]] +interpretation Heap:type_definition Heap2any any2Heap Heap_Image + by (rule Heap_sub_any) + + definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" @@ -220,6 +234,10 @@ axiomatization Seq2any any2Seq Seq_UNIV declare [[coercion Seq2any]] +interpretation Seq:type_definition Seq2any any2Seq Seq_UNIV + by (rule Seq_sub_any) + + instantiation Seq::any begin fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" From a9614a74aa8224e16723ac80e6c26cb5d1d4081e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 3 May 2024 22:44:27 +0200 Subject: [PATCH 185/248] add disjoint types axioms and assumptions --- .../IsabelleTranslator.java | 39 +- .../UninterpretedSymbolsHandler.preamble.xml | 593 ++++++++++-------- 2 files changed, 359 insertions(+), 273 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a0e7de0d9a6..f77703b6c70 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -63,7 +63,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx masterHandler.getPredefinedSorts().forEach((Sort sort) -> sortImplemented.put(sort, true)); Queue sortImplementationQueue = new LinkedList<>(sortParentsMap.keySet()); - implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); sequentTranslation.append("locale varsAndFunctions"); @@ -99,6 +99,8 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(LINE_ENDING); } + sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); + sequentTranslation.append("begin").append(LINE_ENDING); sequentTranslation.append("theorem solve: "); @@ -123,6 +125,31 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } + private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler masterHandler) { + Set sorts = masterHandler.getExtraSorts(); + Queue sortsCheckQueue = new LinkedList<>(sorts); + StringBuilder sortsAssumptions = new StringBuilder(); + + while (!sortsCheckQueue.isEmpty()) { + Sort s = sortsCheckQueue.remove(); + if (s == Sort.ANY) { + continue; + } + String sType = masterHandler.translateSortName(s) + "_type"; + for (Sort s2 : sortsCheckQueue) { + if (s2 == Sort.ANY) { + continue; + } + if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { + String s2Type = masterHandler.translateSortName(s2) + "_type"; + //Sorts are unrelated need to add distinctness assumption + sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + } + } + } + return sortsAssumptions; + } + private StringBuilder getDistinctFieldLemma(Collection newFields) { if (newFields.isEmpty()) return new StringBuilder(); @@ -136,8 +163,8 @@ private StringBuilder getDistinctFieldLemma(Collection newFields) return distinctFieldLemma; } - private void implementSorts(StringBuilder sequentTranslation, Queue sortImplementationQueue, Map sortImplemented, - Map> sortParentsMap, IsabelleMasterHandler masterHandler) { + private void addSortsDefinitions(StringBuilder sequentTranslation, Queue sortImplementationQueue, Map sortImplemented, + Map> sortParentsMap, IsabelleMasterHandler masterHandler) { if (sortImplementationQueue.isEmpty()) { return; } @@ -146,13 +173,13 @@ private void implementSorts(StringBuilder sequentTranslation, Queue sortIm for (Sort parent : sortParentsMap.get(sort)) { if (!sortImplemented.get(parent)) { sortImplementationQueue.add(sort); - implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); return; } } if ((sort instanceof ArraySort) && !sortImplemented.get(((ArraySort) sort).elementSort())) { sortImplementationQueue.add(sort); - implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); return; } String sortName = masterHandler.translateSortName(sort); @@ -249,7 +276,7 @@ private void implementSorts(StringBuilder sequentTranslation, Queue sortIm sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); sortImplemented.put(sort, true); - implementSorts(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); } private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 9a607576d90..2fe26010760 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -4,351 +4,410 @@ General preamble -declare [[coercion_enabled]] -declare [[coercion_map image]] + declare [[coercion_enabled]] + declare [[coercion_map image]] -typedecl any + typedecl any -typedef javaDL_type = "(UNIV::any set set)" - by auto + typedef javaDL_type = "(UNIV::any set set)" + by auto -setup_lifting type_definition_javaDL_type -lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.member. -lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. -lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. + setup_lifting type_definition_javaDL_type + lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.member. + lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. + lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is + Set.subset. + lift_definition disjointTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.disjnt. -consts - int_Image::"any set" - int2any::"int\<Rightarrow>any" - any2int::"any\<Rightarrow>int" + consts + int_UNIV::"any set" + int2any::"int\<Rightarrow>any" + any2int::"any\<Rightarrow>int" -axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_Image)" -declare [[coercion int2any]] + axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_UNIV)" + declare [[coercion int2any]] -interpretation int:type_definition int2any any2int int_Image - by simp + interpretation int:type_definition int2any any2int int_UNIV + by simp -definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" + definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" -consts - bool_Image::"any set" - bool2any::"bool\<Rightarrow>any" - any2bool::"any\<Rightarrow>bool" + consts + bool_UNIV::"any set" + bool2any::"bool\<Rightarrow>any" + any2bool::"any\<Rightarrow>bool" -axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_Image)" -declare [[coercion bool2any]] + axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_UNIV)" + declare [[coercion bool2any]] -interpretation bool:type_definition bool2any any2bool bool_Image - by simp + interpretation bool:type_definition bool2any any2bool bool_UNIV + by simp -definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" + definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" -consts - bottom::"any" + consts + bottom::"any" -specification (bottom) "bottom = bottom" - by simp + specification (bottom) "bottom = bottom" + by simp -lemma bottom_in_any:"bottom \<in> (UNIV::any set)" - by simp + lemma bottom_in_any:"bottom \<in> (UNIV::any set)" + by simp -consts - java_lang_Object_UNIV::"any set" + consts + java_lang_Object_UNIV::"any set" -specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" - "bottom:java_lang_Object_UNIV" - by auto + specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" + "bottom:java_lang_Object_UNIV" + by auto -lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> - bottom:java_lang_Object_UNIV" - by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) + lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> + bottom:java_lang_Object_UNIV" + by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) -typedef java_lang_Object = "java_lang_Object_UNIV" - morphisms java_lang_Object2any any2java_lang_Object - using java_lang_Object_UNIV_specification by auto + typedef java_lang_Object = "java_lang_Object_UNIV" + morphisms java_lang_Object2any any2java_lang_Object + using java_lang_Object_UNIV_specification by auto -declare [[coercion java_lang_Object2any]] + declare [[coercion java_lang_Object2any]] -definition java_lang_Object_type::"javaDL_type" where "java_lang_Object_type \<equiv> Abs_javaDL_type (UNIV::java_lang_Object set)" + definition java_lang_Object_type::"javaDL_type" where "java_lang_Object_type \<equiv> Abs_javaDL_type + (UNIV::java_lang_Object set)" -lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" - by simp + lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" + by simp -lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" - using java_lang_Object_UNIV_specification - using type_definition.Rep_range type_definition_java_lang_Object by blast + lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" + using java_lang_Object_UNIV_specification + using type_definition.Rep_range type_definition_java_lang_Object by blast -typedecl Field + consts + Field_UNIV::"any set" -consts - created::"Field" - fieldType::"Field\<Rightarrow>javaDL_type" + specification (Field_UNIV) "Field_UNIV \<subseteq> (UNIV::any set)" + "Field_UNIV \<noteq> {}" + by auto -axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" + lemma Field_UNIV_specification:"Field_UNIV \<subseteq> (UNIV::any set) \<and> + Field_UNIV \<noteq> {}" + by (metis (mono_tags, lifting) Field_UNIV_def empty_not_UNIV someI_ex top_greatest) + typedef Field = Field_UNIV + morphisms Field2any any2Field + using Field_UNIV_specification by auto -typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" - by simp + declare [[coercion Field2any]] + consts + created::"Field" + fieldType::"Field\<Rightarrow>javaDL_type" -setup_lifting type_definition_LocSet -lift_definition elementOf::"java_lang_Object \<Rightarrow> Field \<Rightarrow>LocSet\<Rightarrow>bool" is "\<lambda>obj f s. (obj, f) \<in> s". -lift_definition empty::"LocSet" is Set.empty. -lift_definition allLocs::"LocSet" is Set.UNIV. -lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj f. {(obj, f)}". -lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. -lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. -lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. -lift_definition setMinus::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is minus. -lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\<lambda>x. {x} \<times> (UNIV::Field set)". -lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) \<times> {x}". -lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". -lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. -lift_definition infiniteUnion::"LocSet set\<Rightarrow>LocSet" is Complete_Lattices.Union. + axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" -consts - LocSet_Image::"any set" - LocSet2any::"LocSet\<Rightarrow>any" - any2LocSet::"any\<Rightarrow>LocSet" + definition Field_type::"javaDL_type" where "Field_type \<equiv> Abs_javaDL_type (UNIV::Field set)" -axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" -declare [[coercion LocSet2any]] + typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" + by simp -interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image - by (rule LocSet_sub_any) + setup_lifting type_definition_LocSet + lift_definition elementOf::"java_lang_Object \<Rightarrow> Field \<Rightarrow>LocSet\<Rightarrow>bool" + is "\<lambda>obj f s. (obj, f) \<in> s". + lift_definition empty::"LocSet" is Set.empty. + lift_definition allLocs::"LocSet" is Set.UNIV. + lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj + f. {(obj, f)}". + lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. + lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. + lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. + lift_definition setMinus::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is minus. + lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\<lambda>x. {x} \<times> + (UNIV::Field set)". + lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) + \<times> {x}". + lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" + is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". + lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. + lift_definition infiniteUnion::"LocSet set\<Rightarrow>LocSet" is Complete_Lattices.Union. -definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" + consts + LocSet_Image::"any set" + LocSet2any::"LocSet\<Rightarrow>any" + any2LocSet::"any\<Rightarrow>LocSet" + axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" + declare [[coercion LocSet2any]] -typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp + interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image + by (rule LocSet_sub_any) -declare [[coercion Rep_Heap]] -consts - Heap_Image::"any set" - Heap2any::"Heap\<Rightarrow>any" - any2Heap::"any\<Rightarrow>Heap" + definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" -axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" -declare [[coercion Heap2any]] + typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp -interpretation Heap:type_definition Heap2any any2Heap Heap_Image - by (rule Heap_sub_any) + declare [[coercion Rep_Heap]] + consts + Heap_Image::"any set" + Heap2any::"Heap\<Rightarrow>any" + any2Heap::"any\<Rightarrow>Heap" -definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" + axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" + declare [[coercion Heap2any]] -class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" + interpretation Heap:type_definition Heap2any any2Heap Heap_Image + by (rule Heap_sub_any) -instantiation any::any -begin -fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" -fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" -instance by standard -end -instantiation int::any -begin -fun to_any_int where "to_any_int x = int2any x" -fun cast_int where "cast_int x = any2int x" -instance by standard -end + definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" -instantiation bool::any -begin -fun to_any_bool where "to_any_bool x = bool2any x" -fun cast_bool where "cast_bool x = any2bool x" -instance by standard -end -instantiation LocSet::any -begin -fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" -fun cast_LocSet where "cast_LocSet x = any2LocSet x" -instance by standard -end + class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" -instantiation Heap::any -begin -fun to_any_Heap where "to_any_Heap x = Heap2any x" -fun cast_Heap where "cast_Heap x = any2Heap x" -instance by standard -end + instantiation any::any + begin + fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" + fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" + instance by standard + end -instantiation java_lang_Object::any -begin -fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" -fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" -instance by standard -end + instantiation int::any + begin + fun to_any_int where "to_any_int x = int2any x" + fun cast_int where "cast_int x = any2int x" + instance by standard + end -typedef (overloaded) Null = "{bottom}" - morphisms Null2any any2Null - by simp + instantiation bool::any + begin + fun to_any_bool where "to_any_bool x = bool2any x" + fun cast_bool where "cast_bool x = any2bool x" + instance by standard + end -declare [[coercion Null2any]] + instantiation Field::any + begin + fun to_any_Field where "to_any_Field x = Field2any x" + fun cast_Field where "cast_Field x = any2Field x" + instance by standard + end -lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast + instantiation LocSet::any + begin + fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" + fun cast_LocSet where "cast_LocSet x = any2LocSet x" + instance by standard + end -lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" - using bottom_Null_set bottom_in_java_lang_Object by auto + instantiation Heap::any + begin + fun to_any_Heap where "to_any_Heap x = Heap2any x" + fun cast_Heap where "cast_Heap x = any2Heap x" + instance by standard + end -definition "null \<equiv> any2Null bottom" + instantiation java_lang_Object::any + begin + fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" + fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" + instance by standard + end -instantiation Null::any -begin -fun to_any_Null where "to_any_Null (x::Null) = Null2any x" -fun cast_Null where "cast_Null x = any2Null x" -instance by standard -end + typedef (overloaded) Null = "{bottom}" + morphisms Null2any any2Null + by simp -abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" + declare [[coercion Null2any]] -declare [[coercion Null2java_lang_Object]] + lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast -fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" - where "instanceof x type = typeof x type" + lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" + using bottom_Null_set bottom_in_java_lang_Object by auto -typedef Seq = "UNIV::any list set" - by auto + definition "null \<equiv> any2Null bottom" -axiomatization Seq2any any2Seq Seq_UNIV - where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" + instantiation Null::any + begin + fun to_any_Null where "to_any_Null (x::Null) = Null2any x" + fun cast_Null where "cast_Null x = any2Null x" + instance by standard + end -declare [[coercion Seq2any]] + abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" -interpretation Seq:type_definition Seq2any any2Seq Seq_UNIV - by (rule Seq_sub_any) + declare [[coercion Null2java_lang_Object]] + fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + where "instanceof x type = typeof x type" -instantiation Seq::any -begin -fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" -fun cast_Seq where "cast_Seq (x::any) = any2Seq x" -instance by standard -end + typedef Seq = "UNIV::any list set" + by auto -definition Seq_type::"javaDL_type" where "Seq_type \<equiv> Abs_javaDL_type (UNIV::Seq set)" - -consts - seqGetOutside::any - -setup_lifting type_definition_Seq -lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". -lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast seqGetOutside)". -lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". -lift_definition seqEmpty::"Seq" is "[]". -lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". -lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. -lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. -lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. - -fun seqNPerm::"Seq\<Rightarrow>bool" - where "seqNPerm s = seqPerm s (seqDef 0 (seqLen s - 1) (to_any))" - -fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where - "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" - -primrec (nonexhaustive) listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>int" where - "listIndexOf (x#xs) a = (if (x=a) then 0 else 1+(listIndexOf xs a))" - -lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" is "listIndexOf". - -fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" - where "listSwap l i j = -(if \<not>(0\<le>i \<and> i<int (length l) \<and> 0\<le>j \<and> i<int (length l)) -then l -else list_update (list_update l (nat i) (l ! (nat j))) (nat j) (l ! (nat i)))" - -lift_definition seqSwap::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" is listSwap. - -fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" - where "listRemove [] _ = []" - | "listRemove (x#xs) 0 = xs" - | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" + axiomatization Seq2any any2Seq Seq_UNIV + where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) + (Seq_UNIV::any set)" -lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s (i::int). (if \<not>(0\<le>i \<and> i<int (length s)) then s else listRemove s (nat i))". - - -consts - exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + declare [[coercion Seq2any]] -axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" - -fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" - -fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where - "select h obj f = cast (h obj f)" - -fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where - "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf obj f s \<and> f\<noteq>created \<or> elementOf obj f (unusedLocs h1) - then select h2 obj f else select h1 obj f))" - -fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" where - "store h obj f x = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=f \<and> f\<noteq>created then x else h obj' f'))" - -fun create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" where - "create h obj = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=created \<and> obj\<noteq>null then cast True else h obj' f'))" - - -class array = any + - fixes element_type::"'a\<Rightarrow>javaDL_type" - -section \<open>wellFormed Axioms\<close> -axiomatization wellFormed::"Heap\<Rightarrow>bool" where - onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> - ((select h (select h obj f) created)::bool)" - and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf (o2::java_lang_Object) f2 ((select - h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 - created)::bool)" - and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select - h x created) \<and> instanceof x (fieldType f))) \<Longrightarrow> wellFormed (store h obj f x)" - and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> ov = null \<or> select h ov created)) - \<Longrightarrow> wellFormed (store h obj f y)" - and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> wellFormed h - \<Longrightarrow> wellFormed (store h obj f x))" - and wellFormedCreate:"wellFormed h \<Longrightarrow> wellFormed (create h obj)" - and wellFormedAnon:"wellFormed h \<and> wellFormed h2 \<Longrightarrow> wellFormed (anon h y h2)" - -axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) - \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" - -lemma induct_sum_upper_limit[simp]: - fixes f::"int\<Rightarrow>int" - fixes lower::int - fixes upper::int - assumes "lower<upper" - shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f (upper - 1)" -proof - - have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" - using assms by auto - have "{upper-1..<upper} = {upper - 1}" - by auto - then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) - then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> by presburger - also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i)" - by simp - finally show ?thesis - using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto -qed + interpretation Seq:type_definition Seq2any any2Seq Seq_UNIV + by (rule Seq_sub_any) + + + instantiation Seq::any + begin + fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" + fun cast_Seq where "cast_Seq (x::any) = any2Seq x" + instance by standard + end + + definition Seq_type::"javaDL_type" where "Seq_type \<equiv> Abs_javaDL_type (UNIV::Seq set)" + + consts + seqGetOutside::any + + setup_lifting type_definition_Seq + lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". + lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if + (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast seqGetOutside)". + lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" + is "\<lambda>le ri e. map e [le..ri - 1]". + lift_definition seqEmpty::"Seq" is "[]". + lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". + lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. + lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. + lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. + + fun seqNPerm::"Seq\<Rightarrow>bool" + where "seqNPerm s = seqPerm s (seqDef 0 (seqLen s - 1) (to_any))" + + fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where + "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" + + primrec (nonexhaustive) listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>int" where + "listIndexOf (x#xs) a = (if (x=a) then 0 else 1+(listIndexOf xs a))" + + lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" is "listIndexOf". + + fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" + where "listSwap l i j = + (if \<not>(0\<le>i \<and> i<int (length l) \<and> 0\<le>j \<and> i<int + (length l)) + then l + else list_update (list_update l (nat i) (l ! (nat j))) (nat j) (l ! (nat i)))" + + lift_definition seqSwap::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" is listSwap. + + fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" + where "listRemove [] _ = []" + | "listRemove (x#xs) 0 = xs" + | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" + + lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s (i::int). (if + \<not>(0\<le>i \<and> i<int (length s)) then s else listRemove s (nat i))". + + + consts + exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + + axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> + 0" + + fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj + created=False)\<and> obj\<noteq>null}" + + fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where + "select h obj f = cast (h obj f)" + + fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where + "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf obj f s \<and> + f\<noteq>created \<or> elementOf obj f (unusedLocs h1) + then select h2 obj f else select h1 obj f))" + + fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" + where + "store h obj f x = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=f + \<and> f\<noteq>created then x else h obj' f'))" + + fun create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" where + "create h obj = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> + f'=created \<and> obj\<noteq>null then cast True else h obj' f'))" + + + class array = any + + fixes element_type::"'a\<Rightarrow>javaDL_type" + + section \<open>wellFormed Axioms\<close> + axiomatization wellFormed::"Heap\<Rightarrow>bool" where + onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> + ((select h (select h obj f) created)::bool)" + and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf (o2::java_lang_Object) f2 + ((select + h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 + created)::bool)" + and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select + h x created) \<and> instanceof x (fieldType f))) \<Longrightarrow> wellFormed (store h obj f x)" + and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> + ov = null \<or> select h ov created)) + \<Longrightarrow> wellFormed (store h obj f y)" + and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x + java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> + wellFormed h + \<Longrightarrow> wellFormed (store h obj f x))" + and wellFormedCreate:"wellFormed h \<Longrightarrow> wellFormed (create h obj)" + and wellFormedAnon:"wellFormed h \<and> wellFormed h2 \<Longrightarrow> wellFormed (anon h y h2)" + + axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> + (select h x created \<and> (typeof x (element_type obj)))) + \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" + + definition "setOfStandardAnySubtypes\<equiv>{int_type, bool_type, java_lang_Object_type, Field_type, + Heap_type, LocSet_type, Seq_type}" + + (*ensure types are distinct where necessary*) + axiomatization where distinctStandardTypes[simp]:"\<forall>x\<in>setOfStandardAnySubtypes. (\<forall>y\<in>setOfStandardAnySubtypes. + disjointTypes x y)" + + lemma induct_sum_upper_limit[simp]: + fixes f::"int\<Rightarrow>int" + fixes lower::int + fixes upper::int + assumes "lower<upper" + shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f + (upper - 1)" + proof - + have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" + using assms by auto + have "{upper-1..<upper} = {upper - 1}" + by auto + then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. + f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) + then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = + upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> + by presburger + also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. + f i)" + by simp + finally show ?thesis + using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto + qed From 59dbc6e87617a050d3e139e2631c0aba2dde059f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 3 May 2024 22:47:37 +0200 Subject: [PATCH 186/248] fix indent --- .../UninterpretedSymbolsHandler.preamble.xml | 621 +++++++++--------- 1 file changed, 295 insertions(+), 326 deletions(-) diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 2fe26010760..c10585aa9a4 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -4,410 +4,379 @@ General preamble - declare [[coercion_enabled]] - declare [[coercion_map image]] +declare [[coercion_enabled]] +declare [[coercion_map image]] +typedecl any +typedef javaDL_type = "(UNIV::any set set)" + by auto - typedecl any +setup_lifting type_definition_javaDL_type +lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.member. +lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. +lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. +lift_definition disjointTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.disjnt. - typedef javaDL_type = "(UNIV::any set set)" - by auto +consts + int_UNIV::"any set" + int2any::"int\<Rightarrow>any" + any2int::"any\<Rightarrow>int" - setup_lifting type_definition_javaDL_type - lift_definition typeof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.member. - lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset_eq. - lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is - Set.subset. - lift_definition disjointTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.disjnt. +axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_UNIV)" +declare [[coercion int2any]] - consts - int_UNIV::"any set" - int2any::"int\<Rightarrow>any" - any2int::"any\<Rightarrow>int" +interpretation int:type_definition int2any any2int int_UNIV + by simp - axiomatization where int_sub_any[simp]:"type_definition int2any any2int (int_UNIV)" - declare [[coercion int2any]] - interpretation int:type_definition int2any any2int int_UNIV - by simp +definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" +consts + bool_UNIV::"any set" + bool2any::"bool\<Rightarrow>any" + any2bool::"any\<Rightarrow>bool" - definition int_type::"javaDL_type" where "int_type \<equiv> Abs_javaDL_type (UNIV::int set)" +axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_UNIV)" +declare [[coercion bool2any]] - consts - bool_UNIV::"any set" - bool2any::"bool\<Rightarrow>any" - any2bool::"any\<Rightarrow>bool" +interpretation bool:type_definition bool2any any2bool bool_UNIV + by simp - axiomatization where bool_sub_any[simp]:"type_definition bool2any any2bool (bool_UNIV)" - declare [[coercion bool2any]] - interpretation bool:type_definition bool2any any2bool bool_UNIV - by simp +definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" - definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" +consts + bottom::"any" +specification (bottom) "bottom = bottom" + by simp - consts - bottom::"any" +lemma bottom_in_any:"bottom \<in> (UNIV::any set)" + by simp - specification (bottom) "bottom = bottom" - by simp - lemma bottom_in_any:"bottom \<in> (UNIV::any set)" - by simp +consts + java_lang_Object_UNIV::"any set" - consts - java_lang_Object_UNIV::"any set" +specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" + "bottom:java_lang_Object_UNIV" + by auto +lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> + bottom:java_lang_Object_UNIV" + by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) - specification (java_lang_Object_UNIV) "java_lang_Object_UNIV \<subseteq> (UNIV::any set)" - "bottom:java_lang_Object_UNIV" - by auto - lemma java_lang_Object_UNIV_specification:"java_lang_Object_UNIV \<subseteq> (UNIV::any set) \<and> - bottom:java_lang_Object_UNIV" - by (metis (mono_tags, lifting) java_lang_Object_UNIV_def UNIV_I subset_UNIV verit_sko_ex_indirect) +typedef java_lang_Object = "java_lang_Object_UNIV" + morphisms java_lang_Object2any any2java_lang_Object + using java_lang_Object_UNIV_specification by auto +declare [[coercion java_lang_Object2any]] - typedef java_lang_Object = "java_lang_Object_UNIV" - morphisms java_lang_Object2any any2java_lang_Object - using java_lang_Object_UNIV_specification by auto +definition java_lang_Object_type::"javaDL_type" where "java_lang_Object_type \<equiv> Abs_javaDL_type (UNIV::java_lang_Object set)" - declare [[coercion java_lang_Object2any]] +lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" + by simp - definition java_lang_Object_type::"javaDL_type" where "java_lang_Object_type \<equiv> Abs_javaDL_type - (UNIV::java_lang_Object set)" +lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" + using java_lang_Object_UNIV_specification + using type_definition.Rep_range type_definition_java_lang_Object by blast - lemma java_lang_Object_subset_any[simp]:"(UNIV::java_lang_Object set) \<subseteq> (UNIV::any set)" - by simp - lemma bottom_in_java_lang_Object[simp] :"bottom \<in> (UNIV::java_lang_Object set)" - using java_lang_Object_UNIV_specification - using type_definition.Rep_range type_definition_java_lang_Object by blast +consts + Field_UNIV::"any set" +specification (Field_UNIV) "Field_UNIV \<subseteq> (UNIV::any set)" + "Field_UNIV \<noteq> {}" + by auto - consts - Field_UNIV::"any set" +lemma Field_UNIV_specification:"Field_UNIV \<subseteq> (UNIV::any set) \<and> + Field_UNIV \<noteq> {}" + by (metis (mono_tags, lifting) Field_UNIV_def empty_not_UNIV someI_ex top_greatest) - specification (Field_UNIV) "Field_UNIV \<subseteq> (UNIV::any set)" - "Field_UNIV \<noteq> {}" - by auto +typedef Field = Field_UNIV + morphisms Field2any any2Field + using Field_UNIV_specification by auto - lemma Field_UNIV_specification:"Field_UNIV \<subseteq> (UNIV::any set) \<and> - Field_UNIV \<noteq> {}" - by (metis (mono_tags, lifting) Field_UNIV_def empty_not_UNIV someI_ex top_greatest) +declare [[coercion Field2any]] - typedef Field = Field_UNIV - morphisms Field2any any2Field - using Field_UNIV_specification by auto +consts + created::"Field" + fieldType::"Field\<Rightarrow>javaDL_type" - declare [[coercion Field2any]] +axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" - consts - created::"Field" - fieldType::"Field\<Rightarrow>javaDL_type" +definition Field_type::"javaDL_type" where "Field_type \<equiv> Abs_javaDL_type (UNIV::Field set)" - axiomatization arr::"int\<Rightarrow>Field" where arr_inject[simp]:"(arr x = arr y) = (x = y)" - definition Field_type::"javaDL_type" where "Field_type \<equiv> Abs_javaDL_type (UNIV::Field set)" +typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" + by simp - typedef LocSet = "UNIV::(java_lang_Object \<times> Field) set set" - by simp +setup_lifting type_definition_LocSet +lift_definition elementOf::"java_lang_Object \<Rightarrow> Field \<Rightarrow>LocSet\<Rightarrow>bool" is "\<lambda>obj f s. (obj, f) \<in> s". +lift_definition empty::"LocSet" is Set.empty. +lift_definition allLocs::"LocSet" is Set.UNIV. +lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj f. {(obj, f)}". +lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. +lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. +lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. +lift_definition setMinus::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is minus. +lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\<lambda>x. {x} \<times> (UNIV::Field set)". +lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) \<times> {x}". +lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". +lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. +lift_definition infiniteUnion::"LocSet set\<Rightarrow>LocSet" is Complete_Lattices.Union. +consts + LocSet_Image::"any set" + LocSet2any::"LocSet\<Rightarrow>any" + any2LocSet::"any\<Rightarrow>LocSet" - setup_lifting type_definition_LocSet - lift_definition elementOf::"java_lang_Object \<Rightarrow> Field \<Rightarrow>LocSet\<Rightarrow>bool" - is "\<lambda>obj f s. (obj, f) \<in> s". - lift_definition empty::"LocSet" is Set.empty. - lift_definition allLocs::"LocSet" is Set.UNIV. - lift_definition singleton::"java_lang_Object\<Rightarrow>Field\<Rightarrow>LocSet" is "\<lambda>obj - f. {(obj, f)}". - lift_definition disjoint::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.disjnt. - lift_definition union::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.union. - lift_definition intersect::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is Set.inter. - lift_definition setMinus::"LocSet\<Rightarrow>LocSet\<Rightarrow>LocSet" is minus. - lift_definition allFields::"java_lang_Object\<Rightarrow>LocSet" is "\<lambda>x. {x} \<times> - (UNIV::Field set)". - lift_definition allObjects::"Field\<Rightarrow>LocSet" is "\<lambda>x. (UNIV::java_lang_Object set) - \<times> {x}". - lift_definition arrayRange::"java_lang_Object\<Rightarrow>int\<Rightarrow>int\<Rightarrow>LocSet" - is "\<lambda>obj x y. {obj} \<times> (image arr {x..y})". - lift_definition subset::"LocSet\<Rightarrow>LocSet\<Rightarrow>bool" is Set.subset. - lift_definition infiniteUnion::"LocSet set\<Rightarrow>LocSet" is Complete_Lattices.Union. +axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" - consts - LocSet_Image::"any set" - LocSet2any::"LocSet\<Rightarrow>any" - any2LocSet::"any\<Rightarrow>LocSet" +declare [[coercion LocSet2any]] - axiomatization where LocSet_sub_any:"type_definition LocSet2any any2LocSet LocSet_Image" +interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image + by (rule LocSet_sub_any) - declare [[coercion LocSet2any]] - interpretation LocSet:type_definition LocSet2any any2LocSet LocSet_Image - by (rule LocSet_sub_any) +definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" - definition LocSet_type::"javaDL_type" where "LocSet_type \<equiv> Abs_javaDL_type (UNIV::LocSet set)" +typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" + by simp - typedef Heap = "UNIV::(java_lang_Object \<Rightarrow> Field \<Rightarrow> any) set" - by simp +declare [[coercion Rep_Heap]] - declare [[coercion Rep_Heap]] +consts + Heap_Image::"any set" + Heap2any::"Heap\<Rightarrow>any" + any2Heap::"any\<Rightarrow>Heap" - consts - Heap_Image::"any set" - Heap2any::"Heap\<Rightarrow>any" - any2Heap::"any\<Rightarrow>Heap" +axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" - axiomatization where Heap_sub_any:"type_definition Heap2any any2Heap Heap_Image" +declare [[coercion Heap2any]] - declare [[coercion Heap2any]] +interpretation Heap:type_definition Heap2any any2Heap Heap_Image + by (rule Heap_sub_any) - interpretation Heap:type_definition Heap2any any2Heap Heap_Image - by (rule Heap_sub_any) +definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" - definition Heap_type::"javaDL_type" where "Heap_type \<equiv> Abs_javaDL_type (UNIV::Heap set)" +class any = + fixes to_any::"'a\<Rightarrow>any" + fixes cast::"any\<Rightarrow>'a" - class any = - fixes to_any::"'a\<Rightarrow>any" - fixes cast::"any\<Rightarrow>'a" +instantiation any::any +begin +fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" +fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" +instance by standard +end - instantiation any::any - begin - fun to_any_any where "to_any_any x = (id::any\<Rightarrow>any) x" - fun cast_any where "cast_any x = (id::any\<Rightarrow>any) x" - instance by standard - end +instantiation int::any +begin +fun to_any_int where "to_any_int x = int2any x" +fun cast_int where "cast_int x = any2int x" +instance by standard +end - instantiation int::any - begin - fun to_any_int where "to_any_int x = int2any x" - fun cast_int where "cast_int x = any2int x" - instance by standard - end +instantiation bool::any +begin +fun to_any_bool where "to_any_bool x = bool2any x" +fun cast_bool where "cast_bool x = any2bool x" +instance by standard +end - instantiation bool::any - begin - fun to_any_bool where "to_any_bool x = bool2any x" - fun cast_bool where "cast_bool x = any2bool x" - instance by standard - end +instantiation Field::any +begin +fun to_any_Field where "to_any_Field x = Field2any x" +fun cast_Field where "cast_Field x = any2Field x" +instance by standard +end - instantiation Field::any - begin - fun to_any_Field where "to_any_Field x = Field2any x" - fun cast_Field where "cast_Field x = any2Field x" - instance by standard - end +instantiation LocSet::any +begin +fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" +fun cast_LocSet where "cast_LocSet x = any2LocSet x" +instance by standard +end - instantiation LocSet::any - begin - fun to_any_LocSet where "to_any_LocSet x = LocSet2any x" - fun cast_LocSet where "cast_LocSet x = any2LocSet x" - instance by standard - end +instantiation Heap::any +begin +fun to_any_Heap where "to_any_Heap x = Heap2any x" +fun cast_Heap where "cast_Heap x = any2Heap x" +instance by standard +end - instantiation Heap::any - begin - fun to_any_Heap where "to_any_Heap x = Heap2any x" - fun cast_Heap where "cast_Heap x = any2Heap x" - instance by standard - end +instantiation java_lang_Object::any +begin +fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" +fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" +instance by standard +end - instantiation java_lang_Object::any - begin - fun cast_java_lang_Object where "cast_java_lang_Object x = any2java_lang_Object x" - fun to_any_java_lang_Object where "to_any_java_lang_Object x = java_lang_Object2any x" - instance by standard - end +typedef (overloaded) Null = "{bottom}" + morphisms Null2any any2Null + by simp - typedef (overloaded) Null = "{bottom}" - morphisms Null2any any2Null - by simp +declare [[coercion Null2any]] - declare [[coercion Null2any]] +lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" + using type_definition.Rep_range type_definition_Null by blast - lemma bottom_Null_set:"(UNIV::Null set) = {bottom}" - using type_definition.Rep_range type_definition_Null by blast +lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" + using bottom_Null_set bottom_in_java_lang_Object by auto - lemma Null_sub_java_lang_Object_Types: "(UNIV::Null set) \<subseteq> (UNIV::java_lang_Object set)" - using bottom_Null_set bottom_in_java_lang_Object by auto +definition "null \<equiv> any2Null bottom" - definition "null \<equiv> any2Null bottom" +instantiation Null::any +begin +fun to_any_Null where "to_any_Null (x::Null) = Null2any x" +fun cast_Null where "cast_Null x = any2Null x" +instance by standard +end - instantiation Null::any - begin - fun to_any_Null where "to_any_Null (x::Null) = Null2any x" - fun cast_Null where "cast_Null x = any2Null x" - instance by standard - end +abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" - abbreviation "Null2java_lang_Object\<equiv>any2java_lang_Object \<circ> Null2any" +declare [[coercion Null2java_lang_Object]] - declare [[coercion Null2java_lang_Object]] +fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + where "instanceof x type = typeof x type" - fun instanceof::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" - where "instanceof x type = typeof x type" +typedef Seq = "UNIV::any list set" + by auto - typedef Seq = "UNIV::any list set" - by auto +axiomatization Seq2any any2Seq Seq_UNIV + where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) (Seq_UNIV::any set)" - axiomatization Seq2any any2Seq Seq_UNIV - where Seq_sub_any:"type_definition (Seq2any::Seq\<Rightarrow>any) (any2Seq::any\<Rightarrow>Seq) - (Seq_UNIV::any set)" +declare [[coercion Seq2any]] - declare [[coercion Seq2any]] +interpretation Seq:type_definition Seq2any any2Seq Seq_UNIV + by (rule Seq_sub_any) - interpretation Seq:type_definition Seq2any any2Seq Seq_UNIV - by (rule Seq_sub_any) - - - instantiation Seq::any - begin - fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" - fun cast_Seq where "cast_Seq (x::any) = any2Seq x" - instance by standard - end - - definition Seq_type::"javaDL_type" where "Seq_type \<equiv> Abs_javaDL_type (UNIV::Seq set)" - - consts - seqGetOutside::any - - setup_lifting type_definition_Seq - lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". - lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if - (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast seqGetOutside)". - lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" - is "\<lambda>le ri e. map e [le..ri - 1]". - lift_definition seqEmpty::"Seq" is "[]". - lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". - lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. - lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. - lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. - - fun seqNPerm::"Seq\<Rightarrow>bool" - where "seqNPerm s = seqPerm s (seqDef 0 (seqLen s - 1) (to_any))" - - fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where - "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" - - primrec (nonexhaustive) listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>int" where - "listIndexOf (x#xs) a = (if (x=a) then 0 else 1+(listIndexOf xs a))" - - lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" is "listIndexOf". - - fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" - where "listSwap l i j = - (if \<not>(0\<le>i \<and> i<int (length l) \<and> 0\<le>j \<and> i<int - (length l)) - then l - else list_update (list_update l (nat i) (l ! (nat j))) (nat j) (l ! (nat i)))" - - lift_definition seqSwap::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" is listSwap. - - fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" - where "listRemove [] _ = []" - | "listRemove (x#xs) 0 = xs" - | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" - - lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s (i::int). (if - \<not>(0\<le>i \<and> i<int (length s)) then s else listRemove s (nat i))". - - - consts - exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" - - axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> - 0" - - fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj - created=False)\<and> obj\<noteq>null}" - - fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where - "select h obj f = cast (h obj f)" - - fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where - "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf obj f s \<and> - f\<noteq>created \<or> elementOf obj f (unusedLocs h1) - then select h2 obj f else select h1 obj f))" - - fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" - where - "store h obj f x = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=f - \<and> f\<noteq>created then x else h obj' f'))" - - fun create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" where - "create h obj = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> - f'=created \<and> obj\<noteq>null then cast True else h obj' f'))" - - - class array = any + - fixes element_type::"'a\<Rightarrow>javaDL_type" - - section \<open>wellFormed Axioms\<close> - axiomatization wellFormed::"Heap\<Rightarrow>bool" where - onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> - ((select h (select h obj f) created)::bool)" - and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf (o2::java_lang_Object) f2 - ((select - h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 - created)::bool)" - and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select - h x created) \<and> instanceof x (fieldType f))) \<Longrightarrow> wellFormed (store h obj f x)" - and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> - ov = null \<or> select h ov created)) - \<Longrightarrow> wellFormed (store h obj f y)" - and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x - java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> - wellFormed h - \<Longrightarrow> wellFormed (store h obj f x))" - and wellFormedCreate:"wellFormed h \<Longrightarrow> wellFormed (create h obj)" - and wellFormedAnon:"wellFormed h \<and> wellFormed h2 \<Longrightarrow> wellFormed (anon h y h2)" - - axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> - (select h x created \<and> (typeof x (element_type obj)))) - \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" - - definition "setOfStandardAnySubtypes\<equiv>{int_type, bool_type, java_lang_Object_type, Field_type, - Heap_type, LocSet_type, Seq_type}" - - (*ensure types are distinct where necessary*) - axiomatization where distinctStandardTypes[simp]:"\<forall>x\<in>setOfStandardAnySubtypes. (\<forall>y\<in>setOfStandardAnySubtypes. - disjointTypes x y)" - - lemma induct_sum_upper_limit[simp]: - fixes f::"int\<Rightarrow>int" - fixes lower::int - fixes upper::int - assumes "lower<upper" - shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f - (upper - 1)" - proof - - have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" - using assms by auto - have "{upper-1..<upper} = {upper - 1}" - by auto - then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. - f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) - then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = - upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" - using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> - by presburger - also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. - f i)" - by simp - finally show ?thesis - using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto - qed + +instantiation Seq::any +begin +fun to_any_Seq where "to_any_Seq (x::Seq) = Seq2any x" +fun cast_Seq where "cast_Seq (x::any) = any2Seq x" +instance by standard +end + +definition Seq_type::"javaDL_type" where "Seq_type \<equiv> Abs_javaDL_type (UNIV::Seq set)" + +consts + seqGetOutside::any + +setup_lifting type_definition_Seq +lift_definition seqLen::"Seq\<Rightarrow>int" is "int \<circ> List.length". +lift_definition seqGet::"Seq\<Rightarrow>int\<Rightarrow>'a::any" is "\<lambda>s i. (if (0::int)\<le>i\<and>i<(int (length s)) then cast (s ! (nat i)) else cast seqGetOutside)". +lift_definition seqDef::"int\<Rightarrow>int\<Rightarrow>(int\<Rightarrow>any)\<Rightarrow>Seq" is "\<lambda>le ri e. map e [le..ri - 1]". +lift_definition seqEmpty::"Seq" is "[]". +lift_definition seqSingleton::"any\<Rightarrow>Seq" is "\<lambda>x. [x]". +lift_definition seqConcat::"Seq\<Rightarrow>Seq\<Rightarrow>Seq" is List.append. +lift_definition seqReverse::"Seq\<Rightarrow>Seq" is List.rev. +lift_definition seqPerm::"Seq\<Rightarrow>Seq\<Rightarrow>bool" is List_Permutation.perm. + +fun seqNPerm::"Seq\<Rightarrow>bool" + where "seqNPerm s = seqPerm s (seqDef 0 (seqLen s - 1) (to_any))" + +fun seqSub::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" where + "seqSub s i j = seqDef i j (\<lambda>x. seqGet s x)" + +primrec (nonexhaustive) listIndexOf::"'a list\<Rightarrow>'a\<Rightarrow>int" where + "listIndexOf (x#xs) a = (if (x=a) then 0 else 1+(listIndexOf xs a))" + +lift_definition seqIndexOf::"Seq\<Rightarrow>any\<Rightarrow>int" is "listIndexOf". + +fun listSwap::"'a list\<Rightarrow>int\<Rightarrow>int\<Rightarrow>'a list" + where "listSwap l i j = +(if \<not>(0\<le>i \<and> i<int (length l) \<and> 0\<le>j \<and> i<int (length l)) +then l +else list_update (list_update l (nat i) (l ! (nat j))) (nat j) (l ! (nat i)))" + +lift_definition seqSwap::"Seq\<Rightarrow>int\<Rightarrow>int\<Rightarrow>Seq" is listSwap. + +fun listRemove::"'a list\<Rightarrow>nat\<Rightarrow>'a list" + where "listRemove [] _ = []" + | "listRemove (x#xs) 0 = xs" + | "listRemove (x#xs) (Suc k) = x # (listRemove xs k)" + +lift_definition seqRemove::"Seq\<Rightarrow>int\<Rightarrow>Seq" is "\<lambda>s (i::int). (if \<not>(0\<le>i \<and> i<int (length s)) then s else listRemove s (nat i))". + + +consts + exactInstance::"any\<Rightarrow>javaDL_type\<Rightarrow>bool" + +axiomatization obj_length::"java_lang_Object\<Rightarrow>int" where length_nonneg[simp]:"obj_length obj \<ge> 0" + +fun unusedLocs where "unusedLocs (h::Heap) = Abs_LocSet {((obj::java_lang_Object), (f::Field)). (h obj created=False)\<and> obj\<noteq>null}" + +fun select::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>'a::any" where + "select h obj f = cast (h obj f)" + +fun anon::"Heap\<Rightarrow>LocSet\<Rightarrow>Heap\<Rightarrow>Heap" where + "anon h1 s h2 = Abs_Heap (\<lambda>(obj::java_lang_Object) (f::Field). (if elementOf obj f s \<and> f\<noteq>created \<or> elementOf obj f (unusedLocs h1) + then select h2 obj f else select h1 obj f))" + +fun store::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Field\<Rightarrow>any\<Rightarrow>Heap" where + "store h obj f x = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=f \<and> f\<noteq>created then x else h obj' f'))" + +fun create::"Heap\<Rightarrow>java_lang_Object\<Rightarrow>Heap" where + "create h obj = Abs_Heap (\<lambda>(obj'::java_lang_Object) (f'::Field). (if obj'=obj \<and> f'=created \<and> obj\<noteq>null then cast True else h obj' f'))" + + +class array = any + + fixes element_type::"'a\<Rightarrow>javaDL_type" + +section \<open>wellFormed Axioms\<close> +axiomatization wellFormed::"Heap\<Rightarrow>bool" where + onlyCreatedjava_lang_ObjecteAreReferenced:"wellFormed h \<Longrightarrow> select h obj f = null \<or> + ((select h (select h obj f) created)::bool)" + and onlyCreatedjava_lang_ObjectsAreInLocSets:"wellFormed h \<and> elementOf (o2::java_lang_Object) f2 ((select + h obj f)::LocSet) \<Longrightarrow> Null2java_lang_Object null=o2 \<or> ((select h o2 + created)::bool)" + and wellFormedStorejava_lang_Object:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> ((select + h x created) \<and> instanceof x (fieldType f))) \<Longrightarrow> wellFormed (store h obj f x)" + and wellFormedStoreLocSet:"wellFormed h \<and> (\<forall>ov fv. (elementOf ov fv y \<longrightarrow> ov = null \<or> select h ov created)) + \<Longrightarrow> wellFormed (store h obj f y)" + and wellFormedStorePrimitive:"(typeof x (fieldType f) \<Longrightarrow> \<not>typeof x java_lang_Object_type \<Longrightarrow> \<not>typeof x LocSet_type \<Longrightarrow> wellFormed h + \<Longrightarrow> wellFormed (store h obj f x))" + and wellFormedCreate:"wellFormed h \<Longrightarrow> wellFormed (create h obj)" + and wellFormedAnon:"wellFormed h \<and> wellFormed h2 \<Longrightarrow> wellFormed (anon h y h2)" + +axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) + \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" + +definition "setOfStandardAnySubtypes\<equiv>{int_type, bool_type, java_lang_Object_type, Field_type, Heap_type, LocSet_type, Seq_type}" + +(*ensure types are distinct where necessary*) +axiomatization where distinctStandardTypes[simp]:"\<forall>x\<in>setOfStandardAnySubtypes. (\<forall>y\<in>setOfStandardAnySubtypes. disjointTypes x y)" + +lemma induct_sum_upper_limit[simp]: + fixes f::"int\<Rightarrow>int" + fixes lower::int + fixes upper::int + assumes "lower<upper" + shows "(\<Sum>(i::int) = lower..<upper. f i) = (\<Sum>(i::int) = lower..<upper - 1. f i) + f (upper - 1)" +proof - + have "{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}" + using assms by auto + have "{upper-1..<upper} = {upper - 1}" + by auto + then have "sum f ({lower..<upper-1} \<union> {upper-1..<upper}) = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + by (subst sum.union_inter [symmetric]) (auto simp add: algebra_simps) + then have "sum f {lower..<upper} = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i) - sum f ({lower..<upper-1} \<inter> {upper-1..<upper})" + using \<open>{lower..<upper} = {lower..<upper-1} \<union> {upper-1..<upper}\<close> by presburger + also have "... = (\<Sum>(i::int) = lower..<upper-1. f i) + (\<Sum>(i::int) = upper-1..<upper. f i)" + by simp + finally show ?thesis + using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto +qed From af496ef297a917c78cb92853abc5d9d6cc89d079 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sat, 4 May 2024 12:31:56 +0200 Subject: [PATCH 187/248] add disjointModNull for java types --- .../IsabelleTranslator.java | 8 ++++++-- .../UninterpretedSymbolsHandler.preamble.xml | 19 ++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index f77703b6c70..c5cd1d6fa90 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -142,8 +142,12 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; - //Sorts are unrelated need to add distinctness assumption - sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + if (s.extendsTrans(nullSort) && s2.extendsTrans(nullSort)) { + sortsAssumptions.append("assumes \"disjointModNullTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + } else { + //Sorts are unrelated. need to add distinctness assumption + sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + } } } } diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index c10585aa9a4..3dbd5d4cfff 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -8,6 +8,15 @@ declare [[coercion_enabled]] declare [[coercion_map image]] typedecl any +consts + bottom::"any" + +specification (bottom) "bottom = bottom" + by simp + +lemma bottom_in_any:"bottom \<in> (UNIV::any set)" + by simp + typedef javaDL_type = "(UNIV::any set set)" by auto @@ -17,6 +26,9 @@ lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarr lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. lift_definition disjointTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.disjnt. +fun disjointModNullTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" where + "disjointModNullTypes a b = ((Rep_javaDL_type a) \<inter> (Rep_javaDL_type b) = {bottom})" + consts int_UNIV::"any set" int2any::"int\<Rightarrow>any" @@ -46,14 +58,7 @@ interpretation bool:type_definition bool2any any2bool bool_UNIV definition bool_type::"javaDL_type" where "bool_type \<equiv> Abs_javaDL_type (UNIV::bool set)" -consts - bottom::"any" - -specification (bottom) "bottom = bottom" - by simp -lemma bottom_in_any:"bottom \<in> (UNIV::any set)" - by simp consts From b348d4479cb71edee4db223a5ef0a194ed5149b7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Sat, 4 May 2024 13:15:39 +0200 Subject: [PATCH 188/248] fix java type disjoint --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index c5cd1d6fa90..1ba2698f532 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -142,7 +142,7 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; - if (s.extendsTrans(nullSort) && s2.extendsTrans(nullSort)) { + if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { sortsAssumptions.append("assumes \"disjointModNullTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption From 645ed2abf692f3ba1abd037de4086b7b8ae480ae Mon Sep 17 00:00:00 2001 From: BookWood Date: Sun, 5 May 2024 00:24:56 +0200 Subject: [PATCH 189/248] change the disjointModNull assumptions for java types to be easier to work with --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 4 +++- .../UninterpretedSymbolsHandler.preamble.xml | 5 +---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 1ba2698f532..db4d596d1ad 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -136,14 +136,16 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas continue; } String sType = masterHandler.translateSortName(s) + "_type"; + String sVal = "(s::" + masterHandler.translateSortName(s) + ")"; for (Sort s2 : sortsCheckQueue) { if (s2 == Sort.ANY) { continue; } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; + String s2Val = "(s2::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { - sortsAssumptions.append("assumes \"disjointModNullTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + sortsAssumptions.append("assumes \"").append(sVal).append(" = ").append(s2Val).append("\\ s = null\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 3dbd5d4cfff..14b24ed688e 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -26,9 +26,6 @@ lift_definition subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarr lift_definition strict_subtype::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.subset. lift_definition disjointTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" is Set.disjnt. -fun disjointModNullTypes::"javaDL_type\<Rightarrow>javaDL_type\<Rightarrow>bool" where - "disjointModNullTypes a b = ((Rep_javaDL_type a) \<inter> (Rep_javaDL_type b) = {bottom})" - consts int_UNIV::"any set" int2any::"int\<Rightarrow>any" @@ -383,5 +380,5 @@ proof - finally show ?thesis using \<open>{upper-1..<upper} = {upper - 1}\<close> by auto qed - + From ae284ef21c832beaa54dd8cdb9d12adf9c3ca7a0 Mon Sep 17 00:00:00 2001 From: BookWood Date: Sun, 5 May 2024 00:58:38 +0200 Subject: [PATCH 190/248] give names to assumptions disjoint types --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index db4d596d1ad..a496edf1e71 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -145,7 +145,8 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas String s2Type = masterHandler.translateSortName(s2) + "_type"; String s2Val = "(s2::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { - sortsAssumptions.append("assumes \"").append(sVal).append(" = ").append(s2Val).append("\\ s = null\"").append(LINE_ENDING); + sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) + .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ (s=null & s2=null)\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); From b08a6962d86476e6efc1e09cfca82d79c2d702a1 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 6 May 2024 12:26:26 +0200 Subject: [PATCH 191/248] change disjointModNull --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a496edf1e71..afecd65b4f2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -146,7 +146,7 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas String s2Val = "(s2::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ (s=null & s2=null)\"").append(LINE_ENDING); + .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); From 03de9d9c36ccdcf0aa365e41f3d8e10038b1ba3c Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 6 May 2024 17:26:07 +0200 Subject: [PATCH 192/248] set KeY strategy before preparation --- .../src/test/java/evaluation/Main.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 35a9b138707..1f65e6c0994 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -100,7 +100,8 @@ private enum ProofState { UNKNOWN, ERROR, OPEN, - CLOSED + CLOSED, + TRANSLATION_FAIL } public static void main(String[] args) { @@ -525,6 +526,10 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { @@ -582,6 +587,11 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); + + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + String contractName = proof.name().toString(); LOGGER.info("Processing contract " + contractName + " of " + input); @@ -889,6 +899,7 @@ public void processInterrupted(IsabelleProblem problem, Exception e) { problem = translator.translateProblem(goal); } catch (IllegalFormulaException e) { flaggedTranslations.add(input); + updateIsabelleState(input, contractName, goal, ProofState.TRANSLATION_FAIL); LOGGER.error("Translation failed: {}", e.getMessage()); return; } From e4dd0af33296ddf18a479ee56399caec744fb849 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 7 May 2024 11:03:16 +0200 Subject: [PATCH 193/248] ensure timeouts sent by sledgehammer are recognized as timeouts --- .../gui/isabelletranslation/IsabelleProblem.java | 15 ++++++++++----- .../src/test/java/evaluation/Main.java | 3 ++- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index b57457ee02d..f91b5b028ca 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -188,7 +188,7 @@ fun go_run (state, thy) = Boolean tryResultSuccess = false; try { tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - } catch (TimeoutException e){ + } catch (TimeoutException e) { tryResultSuccess = false; } if (tryResultSuccess) { @@ -295,7 +295,7 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout",\"""" + (timeout_seconds - 5) + """ + [("timeout",\"""" + (timeout_seconds) + """ "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ .run_sledgehammer params\s""" + Sledgehammer_Prover + """ @@ -323,7 +323,7 @@ fun go_run (state, thy) = Boolean tryResultSuccess; try { tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - } catch (TimeoutException e){ + } catch (TimeoutException e) { tryResultSuccess = false; } if (tryResultSuccess) { @@ -361,9 +361,14 @@ fun go_run (state, thy) = } } - notifySledgehammerFinished(); + if (result.isTimeout()) { + notifyProcessTimeout(); + + notifySledgehammerFinished(); + + notifyProcessFinished(); + } - notifyProcessFinished(); LOGGER.debug("Sledgehammer result: " + this.result); return this.result; diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 1f65e6c0994..8dff88f2f12 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -11,7 +11,6 @@ import de.uka.ilkd.key.gui.isabelletranslation.*; import de.uka.ilkd.key.gui.settings.SettingsManager; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.macros.FullPropositionalExpansionMacro; import de.uka.ilkd.key.macros.PropositionalExpansionWithSimplificationMacro; import de.uka.ilkd.key.macros.SMTPreparationMacro; import de.uka.ilkd.key.proof.Goal; @@ -856,6 +855,8 @@ public void processStopped(IsabelleProblem problem) { updateIsabelleState(input, contractName, goal, ProofState.CLOSED); String isabelleProof = problem.getResult().getSuccessfulTactic(); updateIsabelleProof(input, contractName, goal, isabelleProof); + } else { + updateIsabelleState(input, contractName, goal, ProofState.OPEN); } LOGGER.info("Result: {}", problem.getResult()); From 005be5d58ad4367fd10a4d749f748ef0116dad66 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:10:48 +0200 Subject: [PATCH 194/248] listener change to avoid mislabelling state --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 8dff88f2f12..70dd03ab470 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -855,8 +855,6 @@ public void processStopped(IsabelleProblem problem) { updateIsabelleState(input, contractName, goal, ProofState.CLOSED); String isabelleProof = problem.getResult().getSuccessfulTactic(); updateIsabelleProof(input, contractName, goal, isabelleProof); - } else { - updateIsabelleState(input, contractName, goal, ProofState.OPEN); } LOGGER.info("Result: {}", problem.getResult()); From 26a62d20d6e912ff79a7bd851851d48d4d8c9bd7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:11:59 +0200 Subject: [PATCH 195/248] remove strategy settings before prep, caused prep to stop prematurely --- .../src/test/java/evaluation/Main.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 70dd03ab470..77d03ffdb45 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -525,10 +525,6 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); - StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { @@ -586,11 +582,6 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); - - StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - String contractName = proof.name().toString(); LOGGER.info("Processing contract " + contractName + " of " + input); From 0878b3560aa055a7798f2aa23075eba7d6ed8c7f Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:20:09 +0200 Subject: [PATCH 196/248] fix goalNr in csv --- .../src/test/java/evaluation/Main.java | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 77d03ffdb45..7b1a68df3a5 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -76,7 +76,8 @@ private static class StatEntry { final Path p; ProofState keyState = ProofState.UNKNOWN; long keyTime; - int keyNodes; + long keyNodes; + int goalNr; long z3TranslationLines; long translationAndZ3Time; long z3ProofLines; @@ -148,7 +149,7 @@ private static void saveStatisticsCSVFile(Path input) { sb.append(","); sb.append("contractName"); sb.append(","); - sb.append("goalNodeName"); + sb.append("goalNr"); sb.append(","); sb.append("KeY_state"); sb.append(","); @@ -188,7 +189,7 @@ private static void saveStatisticsCSVFile(Path input) { sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); - sb.append(goal.node().getStepIndex()); + sb.append(entry.goalNr); sb.append(","); sb.append(entry.keyState); sb.append(","); @@ -237,7 +238,7 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append("contractName"); sb.append(","); - sb.append("goalNodeName"); + sb.append("goalNr"); sb.append(","); sb.append("KeY_state"); sb.append(","); @@ -274,7 +275,7 @@ private static void saveStatisticsCSV() { sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); - sb.append(goal.node().getStepIndex()); + sb.append(entry.goalNr); sb.append(","); sb.append(entry.keyState); sb.append(","); @@ -545,6 +546,8 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole proof.setStepIndices(); ImmutableList goals = proof.openGoals(); + goals.forEach((Goal goal) -> updateGoalNr(input, "", goal, goal.node().getStepIndex())); + STATS.put(input, new HashMap<>()); STATS.get(input).put("", new HashMap<>()); @@ -606,6 +609,8 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa proof.setStepIndices(); ImmutableList goals = proof.openGoals(); + goals.forEach((Goal goal) -> updateGoalNr(input, proof.name().toString(), goal, goal.node().getStepIndex())); + STATS.computeIfAbsent(input, k -> new HashMap<>()); STATS.get(input).put(proof.name().toString(), new HashMap<>()); @@ -911,6 +916,15 @@ private static void saveFlaggedTranslations() { } } + private static void updateGoalNr(Path input, String contractName, Goal goal, int goalNr) { + StatEntry stats = STATS.get(input).get(contractName).get(goal); + if (stats == null) { + stats = new StatEntry(input); + } + stats.goalNr = goalNr; + STATS.get(input).get(contractName).put(goal, stats); + } + private static void updateIsabelleProof(Path input, String contractName, Goal goal, String isabelleProof) { StatEntry stats = STATS.get(input).get(contractName).get(goal); if (stats == null) { From dfe148dfe13dff6ca417293124b48508278a73cc Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:26:48 +0200 Subject: [PATCH 197/248] change input file format to save parent directory name --- keyext.isabelletranslation/src/test/java/evaluation/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 7b1a68df3a5..800058a4b32 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -185,7 +185,7 @@ private static void saveStatisticsCSVFile(Path input) { Map> contractMap = STATS.get(input); contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p); + sb.append(entry.p.getParent().getFileName()); sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); @@ -271,7 +271,7 @@ private static void saveStatisticsCSV() { for (Map> contractMap : STATS.values()) { contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p); + sb.append(entry.p.getParent().getFileName()); sb.append(","); sb.append(c.replace(",", "_")); sb.append(","); From aaa067d8082a61470218f2b08caaeff83034cfed Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:36:30 +0200 Subject: [PATCH 198/248] wrong order of setting goalNr --- .../src/test/java/evaluation/Main.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index 800058a4b32..c5cf6206b82 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -546,12 +546,11 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole proof.setStepIndices(); ImmutableList goals = proof.openGoals(); - goals.forEach((Goal goal) -> updateGoalNr(input, "", goal, goal.node().getStepIndex())); - - STATS.put(input, new HashMap<>()); STATS.get(input).put("", new HashMap<>()); + goals.forEach((Goal goal) -> updateGoalNr(input, "", goal, goal.node().getStepIndex())); + if (runIsabelle) { runIsabelleToFile(input, "", goals); } @@ -609,11 +608,11 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa proof.setStepIndices(); ImmutableList goals = proof.openGoals(); - goals.forEach((Goal goal) -> updateGoalNr(input, proof.name().toString(), goal, goal.node().getStepIndex())); - STATS.computeIfAbsent(input, k -> new HashMap<>()); STATS.get(input).put(proof.name().toString(), new HashMap<>()); + goals.forEach((Goal goal) -> updateGoalNr(input, proof.name().toString(), goal, goal.node().getStepIndex())); + if (runIsabelle) { runIsabelleToFile(input, proof.name().toString(), goals); } From e161552a895c6e40b5be44b960f3477d158c4eaf Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:43:59 +0200 Subject: [PATCH 199/248] add back strategy with right timeouts before prep --- .../src/test/java/evaluation/Main.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index c5cf6206b82..de95f4eb43a 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -526,6 +526,15 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); UserInterfaceControl uic = new DefaultUserInterfaceControl(); + + // this should initialize with the default properties, + // necessary to enable quantifier instantiation + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); + proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE); + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { @@ -587,6 +596,14 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa String contractName = proof.name().toString(); LOGGER.info("Processing contract " + contractName + " of " + input); + // this should initialize with the default properties, + // necessary to enable quantifier instantiation + StrategyProperties properties = new StrategyProperties(); + Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); + proof.setActiveStrategy(strategy); + proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); + proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE); + SMTPreparationMacro smtMacro = new SMTPreparationMacro(); PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); From 514afd4e1d24a630f3400d83f02174f98579796b Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 11:50:07 +0200 Subject: [PATCH 200/248] timeout recognition problem --- .../ilkd/key/gui/isabelletranslation/IsabelleProblem.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java index f91b5b028ca..ed88455acdc 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java @@ -363,11 +363,11 @@ fun go_run (state, thy) = if (result.isTimeout()) { notifyProcessTimeout(); + } - notifySledgehammerFinished(); + notifySledgehammerFinished(); - notifyProcessFinished(); - } + notifyProcessFinished(); LOGGER.debug("Sledgehammer result: " + this.result); From caa8c12b94ff23329f4ab41bebb10d2048e37ec3 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 13:59:39 +0200 Subject: [PATCH 201/248] change distinct types to include standard types --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 1 + .../UninterpretedSymbolsHandler.preamble.xml | 5 ----- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index afecd65b4f2..b33fa85c070 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -127,6 +127,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler masterHandler) { Set sorts = masterHandler.getExtraSorts(); + sorts.addAll(masterHandler.getPredefinedSorts()); Queue sortsCheckQueue = new LinkedList<>(sorts); StringBuilder sortsAssumptions = new StringBuilder(); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 14b24ed688e..5e6f59c7e20 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -355,11 +355,6 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" -definition "setOfStandardAnySubtypes\<equiv>{int_type, bool_type, java_lang_Object_type, Field_type, Heap_type, LocSet_type, Seq_type}" - -(*ensure types are distinct where necessary*) -axiomatization where distinctStandardTypes[simp]:"\<forall>x\<in>setOfStandardAnySubtypes. (\<forall>y\<in>setOfStandardAnySubtypes. disjointTypes x y)" - lemma induct_sum_upper_limit[simp]: fixes f::"int\<Rightarrow>int" fixes lower::int From 2cdc2ed6216cc025d27ebb5b556db978f8d5476f Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 14:11:02 +0200 Subject: [PATCH 202/248] unfolded disjoint Types assumptions --- .../key/gui/isabelletranslation/IsabelleTranslator.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index b33fa85c070..71112977896 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -99,7 +99,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(LINE_ENDING); } - sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); + sequentTranslation.append(getDistinctSortsAssumptions(masterHandler)); sequentTranslation.append("begin").append(LINE_ENDING); @@ -125,7 +125,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } - private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler masterHandler) { + private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHandler) { Set sorts = masterHandler.getExtraSorts(); sorts.addAll(masterHandler.getPredefinedSorts()); Queue sortsCheckQueue = new LinkedList<>(sorts); @@ -150,7 +150,8 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption - sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + sortsAssumptions.append("assumes disjointTypes_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) + .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ False\"").append(LINE_ENDING); } } } From cef85d3831f409ed6161e9cb81809b9b2e00c79f Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 14:31:00 +0200 Subject: [PATCH 203/248] fix distinctSortsAssumptions --- .../ilkd/key/gui/isabelletranslation/IsabelleTranslator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 71112977896..a034976496c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -126,7 +126,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHandler) { - Set sorts = masterHandler.getExtraSorts(); + Set sorts = new HashSet<>(masterHandler.getExtraSorts()); sorts.addAll(masterHandler.getPredefinedSorts()); Queue sortsCheckQueue = new LinkedList<>(sorts); StringBuilder sortsAssumptions = new StringBuilder(); From 2d35493590db5fa056eb44c188230aa6ba650d58 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 14:36:05 +0200 Subject: [PATCH 204/248] flipflop strategy for prep --- .../src/test/java/evaluation/Main.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java index de95f4eb43a..c21efa043a8 100644 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ b/keyext.isabelletranslation/src/test/java/evaluation/Main.java @@ -529,11 +529,11 @@ private static void processFile(Path input, boolean runKeY, boolean runZ3, boole // this should initialize with the default properties, // necessary to enable quantifier instantiation - StrategyProperties properties = new StrategyProperties(); + /*StrategyProperties properties = new StrategyProperties(); Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); proof.setActiveStrategy(strategy); proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); - proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE); + proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE);*/ SMTPreparationMacro smtMacro = new SMTPreparationMacro(); PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); @@ -598,11 +598,11 @@ private static void processContract(ProofManagementApi pm, Contract contract, Pa // this should initialize with the default properties, // necessary to enable quantifier instantiation - StrategyProperties properties = new StrategyProperties(); + /*StrategyProperties properties = new StrategyProperties(); Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); proof.setActiveStrategy(strategy); proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); - proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE); + proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE);*/ SMTPreparationMacro smtMacro = new SMTPreparationMacro(); From aa4caf24d01c88fc575d6441a55debd42a08b08f Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 15:09:26 +0200 Subject: [PATCH 205/248] fix disjoint types assumptions --- .../key/gui/isabelletranslation/IsabelleTranslator.java | 8 ++++---- .../UninterpretedSymbolsHandler.preamble.xml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index a034976496c..d0a3ca34ea2 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -133,18 +133,18 @@ private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHa while (!sortsCheckQueue.isEmpty()) { Sort s = sortsCheckQueue.remove(); - if (s == Sort.ANY) { + if (s == Sort.ANY || s == Sort.FORMULA) { continue; } String sType = masterHandler.translateSortName(s) + "_type"; - String sVal = "(s::" + masterHandler.translateSortName(s) + ")"; + String sVal = "(" + masterHandler.translateSortName(s) + "_val::" + masterHandler.translateSortName(s) + ")"; for (Sort s2 : sortsCheckQueue) { - if (s2 == Sort.ANY) { + if (s2 == Sort.ANY || s2 == Sort.FORMULA) { continue; } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; - String s2Val = "(s2::" + masterHandler.translateSortName(s2) + ")"; + String s2Val = "("+ masterHandler.translateSortName(s2) + "_val::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml index 5e6f59c7e20..0dd3102e77e 100644 --- a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml +++ b/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml @@ -355,7 +355,7 @@ axiomatization wellFormed::"Heap\<Rightarrow>bool" where axiomatization where wellFormedStoreArray:"wellFormed h \<and> ((x::java_lang_Object)=null \<or> (select h x created \<and> (typeof x (element_type obj)))) \<Longrightarrow> wellFormed (store h (cast (to_any (obj::'a::{array, any}))) (arr idx) x)" -lemma induct_sum_upper_limit[simp]: +lemma induct_sum_upper_limit: fixes f::"int\<Rightarrow>int" fixes lower::int fixes upper::int From 2dbba8f2acd7b892a5934b1dca0e050f7ddc29c6 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 23:58:07 +0200 Subject: [PATCH 206/248] fix disjoint types assumptions name collision by binding to quantifier --- .../key/gui/isabelletranslation/IsabelleTranslator.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index d0a3ca34ea2..287a73c976a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -147,11 +147,13 @@ private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHa String s2Val = "("+ masterHandler.translateSortName(s2) + "_val::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); + .append(":\"\\(").append(sVal).append(") (").append(s2Val).append("). ") + .append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption sortsAssumptions.append("assumes disjointTypes_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ False\"").append(LINE_ENDING); + .append(":\"\\(").append(sVal).append(") (").append(s2Val).append("). ") + .append(sVal).append(" = ").append(s2Val).append("\\ False\"").append(LINE_ENDING); } } } From bb7b93c259f3fae7bc323be4899e4f9f9b1aebfc Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 7 May 2024 23:58:19 +0200 Subject: [PATCH 207/248] run instead of start shutdownResources --- .../uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 80ba134f94a..9521560dc2d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -88,7 +88,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t } catch (InterruptedException e) { throw new RuntimeException(e); } finally { - shutdownResources.start(); + shutdownResources.run(); Runtime.getRuntime().removeShutdownHook(shutdownResources); } } From 68c592e923002791708199069b6d574484fed0cb Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 8 May 2024 09:31:51 +0200 Subject: [PATCH 208/248] revert new disjoint type changes. Assumptions overwhelmed sledgehammer --- .../isabelletranslation/IsabelleLauncher.java | 7 +++++-- .../IsabelleTranslator.java | 18 +++++++----------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java index 9521560dc2d..a7739eaf753 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java @@ -20,7 +20,10 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.concurrent.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); @@ -70,7 +73,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t Theory thy0 = beginTheory(settings.getTranslationPath(), isabelle); resourceInstances.add(new Pair<>(isabelle, thy0)); - tasks.add(()-> { + tasks.add(() -> { IsabelleProblem problem; Pair resources; while ((problem = problemsQueue.poll()) != null && (resources = resourceInstances.poll()) != null) { diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 287a73c976a..189afe06464 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -99,7 +99,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(LINE_ENDING); } - sequentTranslation.append(getDistinctSortsAssumptions(masterHandler)); + sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); sequentTranslation.append("begin").append(LINE_ENDING); @@ -125,9 +125,8 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); } - private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHandler) { - Set sorts = new HashSet<>(masterHandler.getExtraSorts()); - sorts.addAll(masterHandler.getPredefinedSorts()); + private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler masterHandler) { + Set sorts = masterHandler.getExtraSorts(); Queue sortsCheckQueue = new LinkedList<>(sorts); StringBuilder sortsAssumptions = new StringBuilder(); @@ -137,23 +136,20 @@ private StringBuilder getDistinctSortsAssumptions(IsabelleMasterHandler masterHa continue; } String sType = masterHandler.translateSortName(s) + "_type"; - String sVal = "(" + masterHandler.translateSortName(s) + "_val::" + masterHandler.translateSortName(s) + ")"; + String sVal = "(" + masterHandler.translateSortName(s) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + masterHandler.translateSortName(s) + ")"; for (Sort s2 : sortsCheckQueue) { if (s2 == Sort.ANY || s2 == Sort.FORMULA) { continue; } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; - String s2Val = "("+ masterHandler.translateSortName(s2) + "_val::" + masterHandler.translateSortName(s2) + ")"; + String s2Val = "(" + masterHandler.translateSortName(s2) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"\\(").append(sVal).append(") (").append(s2Val).append("). ") - .append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); + .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); } else { //Sorts are unrelated. need to add distinctness assumption - sortsAssumptions.append("assumes disjointTypes_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"\\(").append(sVal).append(") (").append(s2Val).append("). ") - .append(sVal).append(" = ").append(s2Val).append("\\ False\"").append(LINE_ENDING); + sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); } } } From 973df0feba18031e4d3391a0b046124d0af4a387 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 8 May 2024 16:08:03 +0200 Subject: [PATCH 209/248] remove the disjoint types as they did not help --- .../IsabelleTranslator.java | 3 +- .../src/test/java/evaluation/Main.java | 1110 ----------------- 2 files changed, 2 insertions(+), 1111 deletions(-) delete mode 100644 keyext.isabelletranslation/src/test/java/evaluation/Main.java diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java index 189afe06464..3b7595ca979 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java @@ -99,7 +99,8 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx sequentTranslation.append(LINE_ENDING); } - sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); + //This did not seem helpful from my testing + //sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); sequentTranslation.append("begin").append(LINE_ENDING); diff --git a/keyext.isabelletranslation/src/test/java/evaluation/Main.java b/keyext.isabelletranslation/src/test/java/evaluation/Main.java deleted file mode 100644 index c21efa043a8..00000000000 --- a/keyext.isabelletranslation/src/test/java/evaluation/Main.java +++ /dev/null @@ -1,1110 +0,0 @@ -package evaluation; - -import com.google.common.util.concurrent.SimpleTimeLimiter; -import com.google.common.util.concurrent.TimeLimiter; -import de.uka.ilkd.key.api.KeYApi; -import de.uka.ilkd.key.api.ProofApi; -import de.uka.ilkd.key.api.ProofManagementApi; -import de.uka.ilkd.key.control.DefaultUserInterfaceControl; -import de.uka.ilkd.key.control.UserInterfaceControl; -import de.uka.ilkd.key.gui.isabelletranslation.IllegalFormulaException; -import de.uka.ilkd.key.gui.isabelletranslation.*; -import de.uka.ilkd.key.gui.settings.SettingsManager; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.macros.PropositionalExpansionWithSimplificationMacro; -import de.uka.ilkd.key.macros.SMTPreparationMacro; -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.Statistics; -import de.uka.ilkd.key.proof.init.ProofInputException; -import de.uka.ilkd.key.proof.io.ProblemLoaderException; -import de.uka.ilkd.key.proof.io.ProofSaver; -import de.uka.ilkd.key.settings.DefaultSMTSettings; -import de.uka.ilkd.key.settings.ProofIndependentSMTSettings; -import de.uka.ilkd.key.settings.ProofIndependentSettings; -import de.uka.ilkd.key.smt.*; -import de.uka.ilkd.key.smt.solvertypes.SolverType; -import de.uka.ilkd.key.smt.solvertypes.SolverTypeImplementation; -import de.uka.ilkd.key.smt.solvertypes.SolverTypes; -import de.uka.ilkd.key.speclang.Contract; -import de.uka.ilkd.key.strategy.JavaCardDLStrategyFactory; -import de.uka.ilkd.key.strategy.Strategy; -import de.uka.ilkd.key.strategy.StrategyProperties; -import org.key_project.util.collection.ImmutableList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.PrintStream; -import java.nio.file.*; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.stream.Stream; - -import static java.nio.file.StandardOpenOption.APPEND; - -public class Main { - private static final SolverType Z3_SOLVER = SolverTypes.getSolverTypes().stream() - .filter(it -> it.getClass().equals(SolverTypeImplementation.class) - && it.getName().equals("Z3")) - .findFirst().orElse(null); - - private static final Path VALID_LIST_PATH = Path.of(System.getProperty("user.home"), "/tmp/valid_list.txt"); - - private static final Set VALID_SET = new HashSet<>(); - - private static final Map>> STATS = new HashMap<>(); - - private static final PrintStream STDOUT = System.out; - private static final PrintStream STDERR = System.err; - - private static final long timeoutSeconds = 30; - - private static Path outDir; - - private static boolean skipProvable = false; - - private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); - - private static final Collection flaggedTranslations = new HashSet<>(); - - private static class StatEntry { - final Path p; - ProofState keyState = ProofState.UNKNOWN; - long keyTime; - long keyNodes; - int goalNr; - long z3TranslationLines; - long translationAndZ3Time; - long z3ProofLines; - ProofState z3State; - String z3ErrorMessage; - long isabelleBuildTime; - long isabelleParseTime; - long isabelleSledgehammerTime; - long isabelleTotalTime; - long isabelleTranslationLines; - String isabelleProofTactic; - ProofState isabelleState = ProofState.UNKNOWN; - - StatEntry(Path p) { - this.p = p; - } - } - - private enum ProofState { - UNKNOWN, - ERROR, - OPEN, - CLOSED, - TRANSLATION_FAIL - } - - public static void main(String[] args) { - outDir = Path.of(System.getProperty("user.home"), "/tmp/benchmark" - + System.currentTimeMillis()); - try { - Files.createDirectories(outDir); - } catch (IOException e) { - e.printStackTrace(); - } - - if (args.length > 0 && args[0].equals("--create-provable-list")) { - if (args.length > 1) { - skipProvable = Boolean.parseBoolean(args[1]); - } - updateZ3ProvableList(); - } else { - Runtime.getRuntime().addShutdownHook(new Thread(Main::saveStatisticsCSV)); - run(); - } - } - - private static void run() { - List pathStrings; - try { - pathStrings = Files.readAllLines(VALID_LIST_PATH); - } catch (IOException e) { - e.printStackTrace(); - return; - } - for (String s : pathStrings) { - Path p = Path.of(System.getProperty("user.home"), s); - VALID_SET.add(p); - processFile(p, true, true, true); - saveStatisticsCSVFile(p); - saveFlaggedTranslations(); - } - saveStatisticsCSV(); - } - - private static void saveStatisticsCSVFile(Path input) { - StringBuilder sb = new StringBuilder(); - - sb.append("input_file"); - sb.append(","); - sb.append("contractName"); - sb.append(","); - sb.append("goalNr"); - sb.append(","); - sb.append("KeY_state"); - sb.append(","); - sb.append("Isabelle_state"); - sb.append(","); - sb.append("Z3_State"); - sb.append(","); - sb.append("KeY_time"); - sb.append(","); - sb.append("KeY_proof_nodes"); - sb.append(","); - sb.append("SMT_translation_lines"); - sb.append(","); - sb.append("transl_+_Z3_time"); - sb.append(","); - sb.append("Z3_proof_lines"); - sb.append(","); - sb.append("Z3_error_msg"); - sb.append(","); - sb.append("Isabelle_build_time"); - sb.append(","); - sb.append("Isabelle_parse_time"); - sb.append(","); - sb.append("Isabelle_sledgehammer_time"); - sb.append(","); - sb.append("Isabelle_total_time"); - sb.append(","); - sb.append("Isabelle_translation_lines"); - sb.append(","); - sb.append("Isabelle_proof"); - sb.append(System.lineSeparator()); - - Map> contractMap = STATS.get(input); - - contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p.getParent().getFileName()); - sb.append(","); - sb.append(c.replace(",", "_")); - sb.append(","); - sb.append(entry.goalNr); - sb.append(","); - sb.append(entry.keyState); - sb.append(","); - sb.append(entry.isabelleState); - sb.append(","); - sb.append(entry.z3State); - sb.append(","); - sb.append(entry.keyTime); - sb.append(","); - sb.append(entry.keyNodes); - sb.append(","); - sb.append(entry.z3TranslationLines); - sb.append(","); - sb.append(entry.translationAndZ3Time); - sb.append(","); - sb.append(entry.z3ProofLines); - sb.append(","); - sb.append(entry.z3ErrorMessage); - sb.append(","); - sb.append(entry.isabelleBuildTime); - sb.append(","); - sb.append(entry.isabelleParseTime); - sb.append(","); - sb.append(entry.isabelleSledgehammerTime); - sb.append(","); - sb.append(entry.isabelleTotalTime); - sb.append(","); - sb.append(entry.isabelleTranslationLines); - sb.append(","); - sb.append(entry.isabelleProofTactic); - sb.append(System.lineSeparator()); - })); - - try { - Files.write(Path.of(outDir + "/" + input.getParent().getFileName() + "_statistics.csv"), sb.toString().getBytes()); - LOGGER.info("Statistics CSV written to {}", outDir); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static void saveStatisticsCSV() { - StringBuilder sb = new StringBuilder(); - - sb.append("input_file"); - sb.append(","); - sb.append("contractName"); - sb.append(","); - sb.append("goalNr"); - sb.append(","); - sb.append("KeY_state"); - sb.append(","); - sb.append("Isabelle_state"); - sb.append(","); - sb.append("Z3_State"); - sb.append(","); - sb.append("KeY_time"); - sb.append(","); - sb.append("KeY_proof_nodes"); - sb.append(","); - sb.append("SMT_translation_lines"); - sb.append(","); - sb.append("transl_+_Z3_time"); - sb.append(","); - sb.append("Z3_proof_lines"); - sb.append(","); - sb.append("Isabelle_build_time"); - sb.append(","); - sb.append("Isabelle_parse_time"); - sb.append(","); - sb.append("Isabelle_sledgehammer_time"); - sb.append(","); - sb.append("Isabelle_total_time"); - sb.append(","); - sb.append("Isabelle_translation_lines"); - sb.append(","); - sb.append("Isabelle_proof"); - sb.append(System.lineSeparator()); - - for (Map> contractMap : STATS.values()) { - contractMap.forEach((String c, Map entryMap) -> entryMap.forEach((Goal goal, StatEntry entry) -> { - sb.append(entry.p.getParent().getFileName()); - sb.append(","); - sb.append(c.replace(",", "_")); - sb.append(","); - sb.append(entry.goalNr); - sb.append(","); - sb.append(entry.keyState); - sb.append(","); - sb.append(entry.isabelleState); - sb.append(","); - sb.append(entry.z3State); - sb.append(","); - sb.append(entry.keyTime); - sb.append(","); - sb.append(entry.keyNodes); - sb.append(","); - sb.append(entry.z3TranslationLines); - sb.append(","); - sb.append(entry.translationAndZ3Time); - sb.append(","); - sb.append(entry.z3ProofLines); - sb.append(","); - sb.append(entry.isabelleBuildTime); - sb.append(","); - sb.append(entry.isabelleParseTime); - sb.append(","); - sb.append(entry.isabelleSledgehammerTime); - sb.append(","); - sb.append(entry.isabelleTotalTime); - sb.append(","); - sb.append(entry.isabelleTranslationLines); - sb.append(","); - sb.append(entry.isabelleProofTactic); - sb.append(System.lineSeparator()); - })); - } - - try { - Files.write(Path.of(outDir + "/statistics.csv"), sb.toString().getBytes()); - LOGGER.info("Statistics CSV written to {}", outDir); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static void loadValidSet() throws IOException { - if (Files.exists(VALID_LIST_PATH)) { - Files.lines(VALID_LIST_PATH).forEach(s -> VALID_SET.add(Paths.get(s))); - } - } - - private static void updateZ3ProvableList() { - //Path exampleDir = FindResources.getExampleDirectory().toPath().toAbsolutePath().normalize(); - try { - loadValidSet(); - List dirs = new ArrayList<>(); - //dirs.add(exampleDir); - dirs.add(Paths.get(System.getProperty("user.home") + "/Desktop/examples")); - - Files.createDirectories(VALID_LIST_PATH.getParent()); - if (!Files.exists(VALID_LIST_PATH)) { - Files.createFile(VALID_LIST_PATH); - } - - for (Path dir : dirs) { - Files.walkFileTree(dir, new FileVisitor<>() { - - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) - throws IOException { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - LOGGER.info("Visiting " + file.toString()); - if (file.toString().endsWith(".key") && checkNonTrivialNoErrorQuickLoad(file)) { - appendValid(file.toAbsolutePath()); - } - if (!skipProvable) { - processFile(file, false, true, false); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) - throws IOException { - return FileVisitResult.CONTINUE; - } - }); - } - } catch (OutOfMemoryError e) { - e.printStackTrace(); - // can not continue in a useful manner - System.exit(-1); - } catch (Throwable e) { - // continue even if an exception is thrown - e.printStackTrace(); - } - } - - private static boolean checkNonTrivialNoErrorQuickLoad(Path file) { - AtomicReference pm = new AtomicReference<>(); - AtomicBoolean success = new AtomicBoolean(true); - Runnable task = () -> { - try { - pm.set(KeYApi.loadFromKeyFile(file.toFile())); - success.set(true); - } catch (ProblemLoaderException e) { - LOGGER.error("Load error {}", e.getMessage()); - } - }; - ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>()); - - TimeLimiter tl = SimpleTimeLimiter.create(executorService); - try { - tl.runWithTimeout(task, 30000, TimeUnit.MILLISECONDS); - } catch (TimeoutException | InterruptedException e) { - LOGGER.error("Load timeout {}", file); - return false; - } - if (!success.get() || pm.get() == null) { - LOGGER.error("Load failed {}", file); - return false; - } - - - ProofApi papi = pm.get().getLoadedProof(); - - if (papi == null || papi.getProof() == null || papi.getProof().closed() || papi.getFirstOpenGoal() == null) { - for (Contract contract : pm.get().getProofContracts()) { - if (!checkTrivialNoErrorQuickLoadContract(file, contract, pm.get(), tl)) { - return false; - } - } - return true; - } - - LOGGER.info("Loaded {}", file); - - Node n = papi.getFirstOpenGoal().getProofNode(); - Proof proof = n.proof(); - - - Runnable prep = () -> { - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - LOGGER.info("Prep done {}", file); - success.set(true); - } catch (Exception e) { - e.printStackTrace(); - success.set(false); - } - } else { - LOGGER.error("Prep failed {}", file); - success.set(false); - } - }; - - try { - tl.runWithTimeout(prep, 60, TimeUnit.SECONDS); - } catch (TimeoutException | InterruptedException e) { - LOGGER.error("Prep timeout {}", file); - executorService.shutdown(); - return false; - } - if (!success.get()) { - LOGGER.error("Prep failed {}", file); - executorService.shutdown(); - return false; - } - - if (proof.openGoals().isEmpty()) { - LOGGER.error("No open goals found after Preparation {}", file); - executorService.shutdown(); - return false; - } - executorService.shutdown(); - return true; - } - - private static boolean checkTrivialNoErrorQuickLoadContract(Path file, Contract contract, ProofManagementApi pm, TimeLimiter tl) { - ProofApi papi; - try { - papi = pm.startProof(contract); - } catch (ProofInputException e) { - e.printStackTrace(); - LOGGER.error("Failed to load contract: " + contract.getDisplayName()); - return false; - } - - Node n = papi.getFirstOpenGoal().getProofNode(); - Proof proof = n.proof(); - - - AtomicBoolean success = new AtomicBoolean(true); - - Runnable prep = () -> { - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(null, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - LOGGER.info("Prep done {}", file); - success.set(true); - } catch (Exception e) { - e.printStackTrace(); - success.set(false); - } - } else { - LOGGER.error("Prep failed {}", file); - success.set(false); - } - }; - - try { - tl.runWithTimeout(prep, timeoutSeconds, TimeUnit.SECONDS); - } catch (TimeoutException | InterruptedException e) { - LOGGER.error("Prep timeout {}", file); - return false; - } - if (!success.get()) { - LOGGER.error("Prep failed {}", file); - return false; - } - return true; - } - - - private static void processFile(Path input, boolean runKeY, boolean runZ3, boolean runIsabelle) { - if (input.toString().endsWith(".key")) { - ProofApi papi = null; - try { - LOGGER.info("Processing " + input); - ProofManagementApi pm = KeYApi.loadFromKeyFile(input.toFile()); - papi = pm.getLoadedProof(); - - if (papi.getProof() == null) { - for (Contract contract : pm.getProofContracts()) { - processContract(pm, contract, input, runKeY, runZ3, runIsabelle); - } - return; - } - - Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); - UserInterfaceControl uic = new DefaultUserInterfaceControl(); - - - // this should initialize with the default properties, - // necessary to enable quantifier instantiation - /*StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); - proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE);*/ - - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - LOGGER.info("Prep done, {} goals remaining", papi.getProof().openGoals().size()); - expansionMacro.applyTo(uic, papi.getProof(), papi.getProof().openGoals(), null, null); - LOGGER.info("Expansion done, {} goals remaining", papi.getProof().openGoals().size()); - } catch (Exception e) { - e.printStackTrace(); - return; - } - } - if (proof.openGoals().isEmpty()) { - LOGGER.info("No open goals found after Preparation"); - return; - } - proof.setStepIndices(); - ImmutableList goals = proof.openGoals(); - - STATS.put(input, new HashMap<>()); - STATS.get(input).put("", new HashMap<>()); - - goals.forEach((Goal goal) -> updateGoalNr(input, "", goal, goal.node().getStepIndex())); - - if (runIsabelle) { - runIsabelleToFile(input, "", goals); - } - if (runZ3) { - runZ3ToFile(input, "", goals, false); - } - if (runKeY) { - runWithKeYAuto(input, "", goals); - } - papi.getEnv().dispose(); - } catch (ProblemLoaderException | IOException e) { - e.printStackTrace(); - } finally { - if (papi != null) { - papi.getEnv().dispose(); - } - } - } - } - - private static void processContract(ProofManagementApi pm, Contract contract, Path input, boolean runKeY, boolean runZ3, boolean runIsabelle) throws IOException, ProblemLoaderException { - ProofApi papi = null; - try { - papi = pm.startProof(contract); - } catch (ProofInputException e) { - e.printStackTrace(); - LOGGER.error("Problem starting proof {}", e.getMessage()); - return; - } - - Proof proof = papi.getFirstOpenGoal().getProofNode().proof(); - UserInterfaceControl uic = new DefaultUserInterfaceControl(); - - String contractName = proof.name().toString(); - LOGGER.info("Processing contract " + contractName + " of " + input); - - // this should initialize with the default properties, - // necessary to enable quantifier instantiation - /*StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); - proof.getSettings().getStrategySettings().setTimeout(Long.MAX_VALUE);*/ - - - SMTPreparationMacro smtMacro = new SMTPreparationMacro(); - PropositionalExpansionWithSimplificationMacro expansionMacro = new PropositionalExpansionWithSimplificationMacro(); - if (smtMacro.canApplyTo(proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null)) { - try { - smtMacro.applyTo(uic, proof, ImmutableList.of(proof.getOpenGoal(papi.getFirstOpenGoal().getProofNode())), null, null); - LOGGER.info("Prep done, {} goals remaining", papi.getProof().openGoals().size()); - expansionMacro.applyTo(uic, papi.getProof(), papi.getProof().openGoals(), null, null); - LOGGER.info("Expansion done, {} goals remaining", papi.getProof().openGoals().size()); - } catch (Exception e) { - e.printStackTrace(); - return; - } - } - if (proof.openGoals().isEmpty()) { - LOGGER.info("No open goals found after Preparation"); - return; - } - proof.setStepIndices(); - ImmutableList goals = proof.openGoals(); - - STATS.computeIfAbsent(input, k -> new HashMap<>()); - STATS.get(input).put(proof.name().toString(), new HashMap<>()); - - goals.forEach((Goal goal) -> updateGoalNr(input, proof.name().toString(), goal, goal.node().getStepIndex())); - - if (runIsabelle) { - runIsabelleToFile(input, proof.name().toString(), goals); - } - if (runZ3) { - runZ3ToFile(input, proof.name().toString(), goals, false); - } - if (runKeY) { - runWithKeYAuto(input, proof.name().toString(), goals); - } - papi.getEnv().dispose(); - } - - private static void runWithKeYAuto(Path input, String contractName, ImmutableList goals) throws ProblemLoaderException, IOException { - Proof proof = goals.stream().findFirst().get().proof(); - UserInterfaceControl uic = new DefaultUserInterfaceControl(); - - // this should initialize with the default properties, - // necessary to enable quantifier instantiation - StrategyProperties properties = new StrategyProperties(); - Strategy strategy = new JavaCardDLStrategyFactory().create(proof, properties); - proof.setActiveStrategy(strategy); - proof.getSettings().getStrategySettings().setMaxSteps(Integer.MAX_VALUE); - proof.getSettings().getStrategySettings().setTimeout(timeoutSeconds * 1000); - - for (Goal g : goals) { - int nodes = -g.proof().getStatistics().nodes; - long goalTime = g.node().getStepIndex(); - - long manualTime = System.currentTimeMillis(); - uic.getProofControl().startFocussedAutoMode(null, g); - uic.getProofControl().waitWhileAutoMode(); - manualTime = System.currentTimeMillis() - manualTime; - - Statistics statistics = g.proof().getStatistics(); - - nodes += statistics.nodes; - updateKeYNodes(input, contractName, g, nodes); - - long keyTime = statistics.autoModeTimeInMillis; - LOGGER.info(" KeY statistics: " + keyTime); - LOGGER.info(" Manual logging: " + manualTime); - - updateKeYState(input, contractName, g, !(g.proof().isOpenGoal(g.node())) ? ProofState.CLOSED : ProofState.OPEN); - updateKeYTime(input, contractName, g, manualTime); - Path proofPath = getOutPath(input, goalTime + "_key.proof"); - ProofSaver saver = new ProofSaver(g.proof(), proofPath.toFile()); - saver.save(); - } - } - - private static void runZ3ToFile(Path input, String contractName, ImmutableList goals, boolean tryReplay) - throws ProblemLoaderException, IOException { - - Proof proof = goals.stream().findFirst().get().proof(); - - ProofIndependentSMTSettings piSettings = SettingsManager.getSmtPiSettings(); - piSettings.setTimeout(timeoutSeconds * 1000); - SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), piSettings, - proof.getSettings().getNewSMTSettings(), proof); - - - class TimedListener implements SolverLauncherListener { - long translationAndZ3Time = 0; - Goal goal; - long goalNumber; - - public TimedListener(Goal g, long goalNumber) { - goal = g; - this.goalNumber = goalNumber; - } - - @Override - public void launcherStopped(SolverLauncher launcher, - Collection finishedSolvers) { - LOGGER.info("Z3 finished ({} solvers).", finishedSolvers.size()); - - translationAndZ3Time = System.currentTimeMillis() - translationAndZ3Time; - for (SMTSolver solver : finishedSolvers) { - SMTProblem solverProblem = solver.getProblem(); - updateZ3Time(input, contractName, goal, translationAndZ3Time); - } - - // we exactly have that single solver - if (finishedSolvers.size() != 1) { - return; - } - SMTSolver z3 = finishedSolvers.iterator().next(); - - String smtTranslation = z3.getTranslation(); - updateZ3TranslationLines(input, contractName, goal, countLines(smtTranslation)); - try { - Files.write(getOutPath(input, goalNumber + "_translation.smt"), smtTranslation.getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - - String z3Proof = z3.getRawSolverOutput(); - - - if (z3.getFinalResult().isValid() == SMTSolverResult.ThreeValuedTruth.VALID) { - updateZ3State(input, contractName, goal, ProofState.CLOSED); - try { - Path outPath = getOutPath(input, goalNumber + "_proof.smt2"); - updateZ3ProofLines(input, contractName, goal, countLines(z3Proof)); - Files.write(outPath, z3Proof.getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - System.setOut(STDOUT); - System.setErr(STDERR); - } else { - updateZ3State(input, contractName, goal, ProofState.OPEN); - } - launcher.removeListener(this); - } - - @Override - public void launcherStarted(Collection problems, - Collection solverTypes, - SolverLauncher launcher) { - translationAndZ3Time = System.currentTimeMillis(); - LOGGER.info("Running Z3 ..."); - } - } - - Collection> launcherRunnables = new LinkedBlockingQueue<>(); - - Stream problems = goals.stream().map(SMTProblem::new); - Services services = proof.getServices(); - - - problems.forEach((SMTProblem problem) -> launcherRunnables.add(() -> { - SolverLauncher launcher = new SolverLauncher(settings); - launcher.addListener(new TimedListener(problem.getGoal(), problem.getGoal().node().getStepIndex())); - try { - launcher.launch(problem, services, Z3_SOLVER); - } catch (Exception e) { - LOGGER.error("Exception during Z3... {}", e.getMessage()); - e.printStackTrace(); - updateZ3State(input, contractName, problem.getGoal(), ProofState.ERROR); - updateZ3State(input, contractName, problem.getGoal(), e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); - } finally { - launcher.stop(); - } - return null; - })); - - ExecutorService executorService = Executors.newFixedThreadPool(8); - try { - executorService.invokeAll(launcherRunnables); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - executorService.shutdown(); - } - - private static void runIsabelleToFile(Path input, String contractName, ImmutableList goals) - throws ProblemLoaderException, IOException { - - Proof proof = goals.stream().findFirst().get().proof(); - - SMTSettings settings = new DefaultSMTSettings(proof.getSettings().getSMTSettings(), - ProofIndependentSettings.DEFAULT_INSTANCE.getSMTSettings(), proof.getSettings().getNewSMTSettings(), proof); - - - class TimedListener implements IsabelleSolverListener { - private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolverListener.class); - long sledgehammerTime = 0L; - long parsingTime = 0L; - long buildingTime = 0L; - Goal goal; - long goalNumber; - long totalTime; - - public TimedListener(Goal g, long goalNumber) { - goal = g; - this.goalNumber = goalNumber; - } - - @Override - public void parsingStarted(IsabelleProblem problem) { - parsingTime = System.currentTimeMillis(); - } - - @Override - public void parsingFinished(IsabelleProblem problem) { - parsingTime = System.currentTimeMillis() - parsingTime; - updateIsabelleParseTime(input, contractName, goal, parsingTime); - } - - @Override - public void parsingFailed(IsabelleProblem problem, Exception e) { - updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); - } - - @Override - public void buildingStarted(IsabelleProblem problem) { - buildingTime = System.currentTimeMillis(); - } - - @Override - public void buildingFinished(IsabelleProblem problem) { - buildingTime = System.currentTimeMillis() - buildingTime; - updateIsabelleBuildTime(input, contractName, goal, buildingTime); - } - - @Override - public void buildingFailed(IsabelleProblem problem, Exception e) { - updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); - } - - @Override - public void processStarted(IsabelleProblem problem) { - totalTime = System.currentTimeMillis(); - LOGGER.info("Started on goal {} of contract {} in file {}", goalNumber, contractName, input); - } - - @Override - public void processStopped(IsabelleProblem problem) { - totalTime = System.currentTimeMillis() - totalTime; - updateIsabelleTime(input, contractName, goal, totalTime); - - String isabelleTranslation = problem.getSequentTranslation(); - updateIsabelleTranslationLines(input, contractName, goal, countLines(isabelleTranslation + problem.getPreamble())); - try { - Files.write(getOutPath(input, goalNumber + "_translation.thy"), isabelleTranslation.getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - - - if (problem.getResult().isSuccessful()) { - updateIsabelleState(input, contractName, goal, ProofState.CLOSED); - String isabelleProof = problem.getResult().getSuccessfulTactic(); - updateIsabelleProof(input, contractName, goal, isabelleProof); - } - - LOGGER.info("Result: {}", problem.getResult()); - } - - @Override - public void processTimeout(IsabelleProblem problem) { - updateIsabelleState(input, contractName, goal, ProofState.OPEN); - } - - @Override - public void sledgehammerStarted(IsabelleProblem problem) { - sledgehammerTime = System.currentTimeMillis(); - } - - @Override - public void sledgehammerFinished(IsabelleProblem problem) { - sledgehammerTime = System.currentTimeMillis() - sledgehammerTime; - updateIsabelleSledgehammerTime(input, contractName, goal, sledgehammerTime); - } - - @Override - public void sledgehammerFailed(IsabelleProblem problem, Exception e) { - updateIsabelleState(input, contractName, goal, ProofState.ERROR); - updateIsabelleProof(input, contractName, goal, e.getMessage().replace(System.lineSeparator(), " ").replace(",", " ")); - } - - @Override - public void processInterrupted(IsabelleProblem problem, Exception e) { - - } - } - Services services = proof.getServices(); - IsabelleTranslator translator = new IsabelleTranslator(services); - IsabelleLauncher launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); - List problems = new ArrayList<>(); - - goals.forEach((Goal goal) -> { - IsabelleProblem problem; - try { - problem = translator.translateProblem(goal); - } catch (IllegalFormulaException e) { - flaggedTranslations.add(input); - updateIsabelleState(input, contractName, goal, ProofState.TRANSLATION_FAIL); - LOGGER.error("Translation failed: {}", e.getMessage()); - return; - } - problem.addListener(new TimedListener(goal, goal.node().getStepIndex())); - - problems.add(problem); - }); - launcher.try0ThenSledgehammerAllPooled(problems, timeoutSeconds, 2); - } - - private static void saveFlaggedTranslations() { - StringBuilder sb = new StringBuilder(); - flaggedTranslations.forEach(sb::append); - - try { - Files.write(Path.of(outDir + "flagged.txt"), sb.toString().getBytes()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static void updateGoalNr(Path input, String contractName, Goal goal, int goalNr) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.goalNr = goalNr; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleProof(Path input, String contractName, Goal goal, String isabelleProof) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleProofTactic = isabelleProof.replace(",", " ").replace(System.lineSeparator(), " "); - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleTime(Path input, String contractName, Goal goal, long totalTime) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleTotalTime = totalTime; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleState(Path input, String contractName, Goal goal, ProofState state) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleState = state; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleSledgehammerTime(Path input, String contractName, Goal goal, long sledgehammerTime) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleSledgehammerTime = sledgehammerTime; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleBuildTime(Path input, String contractName, Goal goal, long buildTime) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleBuildTime = buildTime; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleParseTime(Path input, String contractName, Goal goal, long parseTime) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleParseTime = parseTime; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void updateIsabelleTranslationLines(Path input, String contractName, Goal goal, long lineCount) { - StatEntry stats = STATS.get(input).get(contractName).get(goal); - if (stats == null) { - stats = new StatEntry(input); - } - stats.isabelleTranslationLines = lineCount; - STATS.get(input).get(contractName).put(goal, stats); - } - - private static void appendValid(Path keyPath) { - try { - if (!VALID_SET.contains(keyPath)) { - VALID_SET.add(keyPath); - Files.write(VALID_LIST_PATH, Collections.singleton(keyPath.toString()), APPEND); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static long countLines(String input) { - return input.chars().filter(ch -> ch == '\n').count(); - } - - private static Path getOutPath(Path input, String newExt) { - String origFileName = input.getFileName().toString(); - String name; - if (origFileName.contains(".")) { - name = origFileName.substring(0, origFileName.lastIndexOf('.')); - } else { - name = origFileName; - } - String prefixedName = input.getName(input.getNameCount() - 3) - + "_" + input.getName(input.getNameCount() - 2) - + "_" + name; - String newName = prefixedName + newExt; - return outDir.resolve(newName); - } - - private static void updateZ3Time(Path p, String c, Goal g, long z3Time) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.translationAndZ3Time = z3Time; - STATS.get(p).get(c).put(g, stats); - } - - - private static void updateZ3State(Path p, String c, Goal g, ProofState state) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.z3State = state; - STATS.get(p).get(c).put(g, stats); - } - - private static void updateZ3State(Path p, String c, Goal g, String msg) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.z3ErrorMessage = msg; - STATS.get(p).get(c).put(g, stats); - } - - private static void updateZ3TranslationLines(Path p, String c, Goal g, long z3TranslationLines) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.z3TranslationLines = z3TranslationLines; - STATS.get(p).get(c).put(g, stats); - } - - private static void updateZ3ProofLines(Path p, String c, Goal g, long z3ProofLines) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.z3ProofLines = z3ProofLines; - STATS.get(p).get(c).put(g, stats); - } - - private static void updateKeYNodes(Path p, String c, Goal g, int keyNodes) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.keyNodes = keyNodes; - STATS.get(p).get(c).put(g, stats); - } - - - private static void updateKeYTime(Path p, String c, Goal g, long keyTime) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.keyTime = keyTime; - STATS.get(p).get(c).put(g, stats); - } - - private static void updateKeYState(Path p, String c, Goal g, ProofState keyState) { - StatEntry stats = STATS.get(p).get(c).get(g); - if (stats == null) { - stats = new StatEntry(p); - } - stats.keyState = keyState; - STATS.get(p).get(c).put(g, stats); - } -} From ece94ded288e5a8b2d64ee2a6ab98cd40a493fe7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 4 Jul 2024 12:30:16 +0200 Subject: [PATCH 210/248] remove evaluation artifacts --- keyext.isabelletranslation/build.gradle | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/keyext.isabelletranslation/build.gradle b/keyext.isabelletranslation/build.gradle index 7d3eec26544..aec44b4c809 100644 --- a/keyext.isabelletranslation/build.gradle +++ b/keyext.isabelletranslation/build.gradle @@ -1,17 +1,4 @@ -plugins { - id("com.github.johnrengelman.shadow") version "8.1.1" -} - - -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar -shadowJar() { - manifest { - attributes 'Main-Class': 'evaluation.Main' - } - from sourceSets.test.output -} - -description "Translate" +description "Translation of Sequents to Isabelle" dependencies { implementation project(':key.core') From 443a7ab3220a52499ca7069ded7ae3f21de35c8c Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 4 Jul 2024 12:32:44 +0200 Subject: [PATCH 211/248] renamed translation package --- .../ilkd/key/gui => key}/isabelletranslation/BSumHandler.java | 2 +- .../key/gui => key}/isabelletranslation/BooleanOpHandler.java | 2 +- .../gui => key}/isabelletranslation/DefinedSymbolsHandler.java | 2 +- .../ilkd/key/gui => key}/isabelletranslation/FieldHandler.java | 2 +- .../isabelletranslation/IllegalFormulaException.java | 2 +- .../gui => key}/isabelletranslation/InfiniteUnionHandler.java | 2 +- .../isabelletranslation/InstanceOperatorHandler.java | 2 +- .../key/gui => key}/isabelletranslation/IntegerOpHandler.java | 2 +- .../key/gui => key}/isabelletranslation/IsabelleHandler.java | 2 +- .../isabelletranslation/IsabelleHandlerServices.java | 2 +- .../key/gui => key}/isabelletranslation/IsabelleLauncher.java | 2 +- .../gui => key}/isabelletranslation/IsabelleMasterHandler.java | 2 +- .../key/gui => key}/isabelletranslation/IsabelleProblem.java | 2 +- .../isabelletranslation/IsabelleSettingsProvider.java | 2 +- .../gui => key}/isabelletranslation/IsabelleSolverListener.java | 2 +- .../isabelletranslation/IsabelleTranslationExtension.java | 2 +- .../isabelletranslation/IsabelleTranslationSettings.java | 2 +- .../key/gui => key}/isabelletranslation/IsabelleTranslator.java | 2 +- .../gui => key}/isabelletranslation/LogicalVariableHandler.java | 2 +- .../gui => key}/isabelletranslation/NumberConstantsHandler.java | 2 +- .../isabelletranslation/ObserverFunctionHandler.java | 2 +- .../key/gui => key}/isabelletranslation/PolymorphicHandler.java | 2 +- .../key/gui => key}/isabelletranslation/QuantifierHandler.java | 2 +- .../ilkd/key/gui => key}/isabelletranslation/SeqDefHandler.java | 2 +- .../key/gui => key}/isabelletranslation/SledgehammerResult.java | 2 +- .../isabelletranslation/SortDependingFunctionHandler.java | 2 +- .../key/gui => key}/isabelletranslation/TranslationAction.java | 2 +- .../isabelletranslation/UninterpretedSymbolsHandler.java | 2 +- .../services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension | 2 +- .../isabelletranslation/IntegerOpHandler.preamble.xml | 0 .../{de/uka/ilkd/key/gui => key}/isabelletranslation/ROOT | 0 .../UninterpretedSymbolsHandler.preamble.xml | 0 .../key/gui => key}/isabelletranslation/defaultHandlers.txt | 0 .../{de/uka/ilkd/key/gui => key}/isabelletranslation/root.tex | 0 34 files changed, 29 insertions(+), 29 deletions(-) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/BSumHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/BooleanOpHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/DefinedSymbolsHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/FieldHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IllegalFormulaException.java (88%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/InfiniteUnionHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/InstanceOperatorHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IntegerOpHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleHandler.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleHandlerServices.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleLauncher.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleMasterHandler.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleProblem.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleSettingsProvider.java (98%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleSolverListener.java (94%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleTranslationExtension.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleTranslationSettings.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/IsabelleTranslator.java (99%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/LogicalVariableHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/NumberConstantsHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/ObserverFunctionHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/PolymorphicHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/QuantifierHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/SeqDefHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/SledgehammerResult.java (93%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/SortDependingFunctionHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/TranslationAction.java (98%) rename keyext.isabelletranslation/src/main/java/{de/uka/ilkd/key/gui => key}/isabelletranslation/UninterpretedSymbolsHandler.java (98%) rename keyext.isabelletranslation/src/main/resources/{de/uka/ilkd/key/gui => key}/isabelletranslation/IntegerOpHandler.preamble.xml (100%) rename keyext.isabelletranslation/src/main/resources/{de/uka/ilkd/key/gui => key}/isabelletranslation/ROOT (100%) rename keyext.isabelletranslation/src/main/resources/{de/uka/ilkd/key/gui => key}/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml (100%) rename keyext.isabelletranslation/src/main/resources/{de/uka/ilkd/key/gui => key}/isabelletranslation/defaultHandlers.txt (100%) rename keyext.isabelletranslation/src/main/resources/{de/uka/ilkd/key/gui => key}/isabelletranslation/root.tex (100%) diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java index 5ee38b2f10e..7e30bf09561 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java index 342f9020e5e..547ca8937ff 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.BooleanLDT; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java index b8bb96f4316..a8a0efaf28a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java index b1a0972ee15..1832ee6cd0f 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Name; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java similarity index 88% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java index d6281bd391f..66d4634128c 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IllegalFormulaException.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; public class IllegalFormulaException extends Exception { /** diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java index 0c715db70d8..c566191c512 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java index bae95bd26e0..3821b774a11 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java index fb16e83948f..38b37e4b474 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java index c3cc5237ef2..e2d0497320d 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java index d400a49a204..96e82d723c3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleHandlerServices.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.jspecify.annotations.NonNull; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index a7739eaf753..2de7c9de9b6 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.util.Pair; import de.unruh.isabelle.control.Isabelle; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java index b18c233c124..917fe4fa28b 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java index ed88455acdc..37e64758ac1 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.proof.Goal; import de.unruh.isabelle.control.Isabelle; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java index 23d3adf41a4..8695fd7cba4 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSettingsProvider.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.settings.InvalidSettingsInputException; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java similarity index 94% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java index 2b8c83834c4..4bf0597d87a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; public interface IsabelleSolverListener { void parsingStarted(IsabelleProblem problem); diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java index d532b024a19..0af832dcb00 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java index 783762bbf19..20fd5c6f931 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.settings.AbstractSettings; import de.uka.ilkd.key.settings.Configuration; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java index 3b7595ca979..bf2523eee17 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Sequent; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java index 58adb04b832..74a52d5c002 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java index 083881883a6..ec545f56b3a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java index 7dd90f7d526..0b10025aea3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java index 31d166c7427..bad11435f94 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/PolymorphicHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java index 72c8bad08a5..8d9ef9b1242 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java index c9a36253744..bc8ddabad77 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SeqDefHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java similarity index 93% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java index 2bb4b144415..e360feec85a 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import scala.Option; import scala.Tuple2; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java index 5fd5929b8ae..840a37fb1d3 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index f9097282e07..79578b18178 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -1,4 +1,4 @@ -package de.uka.ilkd.key.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java index ab20cacb122..f619d34ec20 100644 --- a/keyext.isabelletranslation/src/main/java/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java @@ -1,7 +1,7 @@ /* 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.gui.isabelletranslation; +package key.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.HeapLDT; diff --git a/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension index 289dacddb4d..c86d523a867 100644 --- a/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension +++ b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension @@ -1 +1 @@ -de.uka.ilkd.key.gui.isabelletranslation.IsabelleTranslationExtension \ No newline at end of file +key.isabelletranslation.IsabelleTranslationExtension \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/IntegerOpHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/IntegerOpHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/key/isabelletranslation/IntegerOpHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/ROOT similarity index 100% rename from keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/ROOT rename to keyext.isabelletranslation/src/main/resources/key/isabelletranslation/ROOT diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/key/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt similarity index 100% rename from keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/defaultHandlers.txt rename to keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt diff --git a/keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/root.tex similarity index 100% rename from keyext.isabelletranslation/src/main/resources/de/uka/ilkd/key/gui/isabelletranslation/root.tex rename to keyext.isabelletranslation/src/main/resources/key/isabelletranslation/root.tex From 0c6861fb4cd75540f376dd90574d05fbccd66e1f Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 17 Jul 2024 21:05:46 +0200 Subject: [PATCH 212/248] Refactored Handler classes to use the new ncore package --- .../key/isabelletranslation/BSumHandler.java | 8 ++--- .../isabelletranslation/BooleanOpHandler.java | 20 ++++++------- .../DefinedSymbolsHandler.java | 11 +++---- .../key/isabelletranslation/FieldHandler.java | 10 +++---- .../InfiniteUnionHandler.java | 4 +-- .../InstanceOperatorHandler.java | 9 +++--- .../isabelletranslation/IntegerOpHandler.java | 4 +-- .../isabelletranslation/IsabelleHandler.java | 4 +-- .../isabelletranslation/IsabelleLauncher.java | 2 +- .../IsabelleMasterHandler.java | 18 ++++++----- .../IsabelleTranslationExtension.java | 2 +- .../IsabelleTranslationSettings.java | 4 +-- .../IsabelleTranslator.java | 9 +++--- .../LogicalVariableHandler.java | 6 ++-- .../NumberConstantsHandler.java | 11 ++++--- .../ObserverFunctionHandler.java | 6 ++-- .../PolymorphicHandler.java | 4 +-- .../QuantifierHandler.java | 11 +++---- .../isabelletranslation/SeqDefHandler.java | 4 +-- .../SortDependingFunctionHandler.java | 6 ++-- .../UninterpretedSymbolsHandler.java | 15 +++++----- .../isabelletranslation/defaultHandlers.txt | 30 +++++++++---------- 22 files changed, 101 insertions(+), 97 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java index 7e30bf09561..578fe38cfb2 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java @@ -2,10 +2,10 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.op.QuantifiableVariable; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; +import org.key_project.logic.op.QuantifiableVariable; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java index 547ca8937ff..a4ea3331f7a 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java @@ -2,10 +2,10 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.BooleanLDT; -import de.uka.ilkd.key.logic.Term; +import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.Equality; import de.uka.ilkd.key.logic.op.Junctor; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.op.Operator; import java.util.HashMap; import java.util.List; @@ -15,15 +15,6 @@ public class BooleanOpHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); - { - supportedOperators.put(Junctor.AND, new StringBuilder("\\")); - supportedOperators.put(Junctor.OR, new StringBuilder("\\")); - supportedOperators.put(Junctor.IMP, new StringBuilder("-->")); - supportedOperators.put(Junctor.NOT, new StringBuilder("Not")); - supportedOperators.put(Junctor.FALSE, new StringBuilder("False")); - supportedOperators.put(Junctor.TRUE, new StringBuilder("True")); - supportedOperators.put(Equality.EQV, new StringBuilder("\\")); - } @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { @@ -34,6 +25,13 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert Operator logicTrue = ldt.getTrueConst(); supportedOperators.put(logicTrue, new StringBuilder("True")); masterHandler.addPredefinedSort(ldt.targetSort(), "bool"); + supportedOperators.put(Junctor.AND, new StringBuilder("\\")); + supportedOperators.put(Junctor.OR, new StringBuilder("\\")); + supportedOperators.put(Junctor.IMP, new StringBuilder("-->")); + supportedOperators.put(Junctor.NOT, new StringBuilder("Not")); + supportedOperators.put(Junctor.FALSE, new StringBuilder("False")); + supportedOperators.put(Junctor.TRUE, new StringBuilder("True")); + supportedOperators.put(Equality.EQV, new StringBuilder("\\")); } @Override diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java index a8a0efaf28a..22567e239a1 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java @@ -2,12 +2,13 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.JFunction; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.logic.op.SortDependingFunction; -import de.uka.ilkd.key.logic.op.SortedOperator; import de.uka.ilkd.key.smt.SMTTranslationException; +import org.key_project.logic.op.SortedOperator; import java.io.IOException; import java.util.HashMap; @@ -19,7 +20,7 @@ public class DefinedSymbolsHandler implements IsabelleHandler { @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { - Namespace functionNamespace = services.getNamespaces().functions(); + Namespace functionNamespace = services.getNamespaces().functions(); Map definedFunctions = new HashMap<>(); definedFunctions.put("null", "null"); definedFunctions.put("length", "obj_length"); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java index 1832ee6cd0f..ab34548ed11 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java @@ -1,12 +1,12 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Name; +import org.key_project.logic.Name; import de.uka.ilkd.key.logic.Namespace; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java index c566191c512..75014889cd6 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java @@ -1,8 +1,8 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java index 3821b774a11..8807e3d6873 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java @@ -2,9 +2,10 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; +import de.uka.ilkd.key.logic.op.JFunction; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.logic.op.SortDependingFunction; import de.uka.ilkd.key.smt.SMTTranslationException; @@ -18,7 +19,7 @@ public class InstanceOperatorHandler implements IsabelleHandler { @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { - Namespace functionNamespace = services.getNamespaces().functions(); + Namespace functionNamespace = services.getNamespaces().functions(); Map definedSortDependingFunctions = new HashMap<>(); definedSortDependingFunctions.put("instance", "instanceof"); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java index 38b37e4b474..232178fb443 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java @@ -5,8 +5,8 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.util.HashMap; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java index e2d0497320d..15b61f2cdc2 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java @@ -4,8 +4,8 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index 2de7c9de9b6..7a1f60e3109 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -1,6 +1,6 @@ package key.isabelletranslation; -import de.uka.ilkd.key.util.Pair; +import org.key_project.util.collection.Pair; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.ListConverter; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java index 917fe4fa28b..2e413edf415 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java @@ -1,13 +1,15 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.op.SortedOperator; +import de.uka.ilkd.key.ldt.JavaDLTheory; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; +import org.key_project.logic.op.SortedOperator; import de.uka.ilkd.key.logic.sort.ArraySort; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; +import org.key_project.util.collection.ImmutableArray; import java.io.IOException; import java.util.*; @@ -51,8 +53,8 @@ public IsabelleMasterHandler(Services services, String[] handlerNames, String[] handlerOptions) throws IOException { this.services = services; List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); - predefinedSorts.put(Sort.ANY, new StringBuilder("any")); - predefinedSorts.put(Sort.FORMULA, new StringBuilder("bool")); + predefinedSorts.put(JavaDLTheory.ANY, new StringBuilder("any")); + predefinedSorts.put(JavaDLTheory.FORMULA, new StringBuilder("bool")); this.handlers = handlers; } @@ -86,7 +88,7 @@ public StringBuilder translate(Term problem) { } } - public List translate(Iterable terms) { + public List translate(ImmutableArray terms) { List result = new LinkedList<>(); for (Term term : terms) { result.add(translate(term)); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java index 0af832dcb00..d1b5214a32c 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java @@ -15,7 +15,7 @@ import java.util.ArrayList; import java.util.List; -@KeYGuiExtension.Info(name = "Translation", optional = true, +@KeYGuiExtension.Info(name = "Isabelle Translation", optional = true, experimental = true) public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java index 20fd5c6f931..9652a5916fd 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java @@ -130,9 +130,9 @@ public void readSettings(@NonNull Configuration props) { isabellePath = DEFAULT_ISABELLE_PATH; translationPath = DEFAULT_TRANSLATION_PATH; } - isabellePath = Path.of(props.get(isabellePathKey, isabellePath.toString())); + isabellePath = Path.of(props.getString(isabellePathKey, isabellePath.toString())); - Path newTranslationPath = Path.of(props.get(translationPathKey, translationPath.toString())); + Path newTranslationPath = Path.of(props.getString(translationPathKey, translationPath.toString())); if (newTranslationPath != translationPath) { translationPath = newTranslationPath; sessionFilesPresent = createSessionFiles(); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java index bf2523eee17..833ac4ea4b6 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java @@ -1,11 +1,12 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.JavaDLTheory; 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.sort.ArraySort; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.proof.Goal; import java.io.IOException; @@ -133,13 +134,13 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas while (!sortsCheckQueue.isEmpty()) { Sort s = sortsCheckQueue.remove(); - if (s == Sort.ANY || s == Sort.FORMULA) { + if (s == JavaDLTheory.ANY || s == JavaDLTheory.FORMULA) { continue; } String sType = masterHandler.translateSortName(s) + "_type"; String sVal = "(" + masterHandler.translateSortName(s) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + masterHandler.translateSortName(s) + ")"; for (Sort s2 : sortsCheckQueue) { - if (s2 == Sort.ANY || s2 == Sort.FORMULA) { + if (s2 == JavaDLTheory.ANY || s2 == JavaDLTheory.FORMULA) { continue; } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { @@ -231,7 +232,7 @@ private void addSortsDefinitions(StringBuilder sequentTranslation, Queue s sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); for (Sort parentSort : sortParentsMap.get(sort)) { - if (parentSort == Sort.ANY) { + if (parentSort == JavaDLTheory.ANY) { continue; } String parentSortName = masterHandler.translateSortName(parentSort); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java index 74a52d5c002..d2d08d4de09 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java @@ -1,10 +1,10 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; +import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.LogicVariable; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.op.Operator; +import org.key_project.logic.sort.Sort; import java.util.Properties; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java index ec545f56b3a..5e89829c92a 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java @@ -4,10 +4,10 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; +import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.AbstractTermTransformer; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; import java.util.Properties; @@ -35,7 +35,10 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) { - String string = AbstractTermTransformer.convertToDecimalString(term, services); + //TODO This needs an updated AbstractTermTransformer to comply with the new ncore package of KeY + assert (term instanceof de.uka.ilkd.key.logic.Term); + + String string = AbstractTermTransformer.convertToDecimalString((de.uka.ilkd.key.logic.Term) term, services); return new StringBuilder("(").append(string).append("::int)"); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java index 0b10025aea3..1c8c0b6d364 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java @@ -1,10 +1,10 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; +import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.ObserverFunction; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.op.SortedOperator; +import org.key_project.logic.op.Operator; +import org.key_project.logic.op.SortedOperator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java index bad11435f94..5bfbe6aef96 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java @@ -4,10 +4,10 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; +import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.Equality; import de.uka.ilkd.key.logic.op.IfThenElse; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.util.List; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java index 8d9ef9b1242..b453cbb7755 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java @@ -1,11 +1,11 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; -import de.uka.ilkd.key.logic.op.QuantifiableVariable; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; +import org.key_project.logic.op.QuantifiableVariable; import de.uka.ilkd.key.logic.op.Quantifier; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; @@ -15,14 +15,11 @@ public class QuantifierHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); - private Services services; @Override public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { supportedOperators.put(Quantifier.ALL, "\\"); supportedOperators.put(Quantifier.EX, "\\"); - - this.services = services; } @Override diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java index bc8ddabad77..45ea78b999b 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java @@ -1,8 +1,8 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java index 840a37fb1d3..0a65a0ea84e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java @@ -1,10 +1,10 @@ package key.isabelletranslation; import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.logic.op.SortDependingFunction; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.io.IOException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java index f619d34ec20..d285750d058 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java @@ -5,16 +5,17 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.HeapLDT; +import de.uka.ilkd.key.ldt.JavaDLTheory; import de.uka.ilkd.key.ldt.LocSetLDT; import de.uka.ilkd.key.ldt.SeqLDT; -import de.uka.ilkd.key.logic.Name; +import org.key_project.logic.Name; import de.uka.ilkd.key.logic.Namespace; -import de.uka.ilkd.key.logic.Term; -import de.uka.ilkd.key.logic.op.Function; -import de.uka.ilkd.key.logic.op.Operator; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; import de.uka.ilkd.key.logic.op.ProgramVariable; -import de.uka.ilkd.key.logic.op.SortedOperator; -import de.uka.ilkd.key.logic.sort.Sort; +import org.key_project.logic.op.SortedOperator; +import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.smt.SMTTranslationException; import java.util.List; @@ -34,7 +35,7 @@ public class UninterpretedSymbolsHandler implements IsabelleHandler { public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { masterHandler.addPreamblesLocales(handlerSnippets); - masterHandler.addPredefinedSort(Sort.ANY, "any"); + masterHandler.addPredefinedSort(JavaDLTheory.ANY, "any"); HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt index 25432437380..5a67b6bcc06 100644 --- a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt +++ b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt @@ -1,15 +1,15 @@ -de.uka.ilkd.key.gui.isabelletranslation.DefinedSymbolsHandler -de.uka.ilkd.key.gui.isabelletranslation.InstanceOperatorHandler -de.uka.ilkd.key.gui.isabelletranslation.BooleanOpHandler -de.uka.ilkd.key.gui.isabelletranslation.PolymorphicHandler -de.uka.ilkd.key.gui.isabelletranslation.QuantifierHandler -de.uka.ilkd.key.gui.isabelletranslation.LogicalVariableHandler -de.uka.ilkd.key.gui.isabelletranslation.NumberConstantsHandler -de.uka.ilkd.key.gui.isabelletranslation.IntegerOpHandler -de.uka.ilkd.key.gui.isabelletranslation.InfiniteUnionHandler -de.uka.ilkd.key.gui.isabelletranslation.BSumHandler -de.uka.ilkd.key.gui.isabelletranslation.SeqDefHandler -de.uka.ilkd.key.gui.isabelletranslation.SortDependingFunctionHandler -de.uka.ilkd.key.gui.isabelletranslation.FieldHandler -de.uka.ilkd.key.gui.isabelletranslation.ObserverFunctionHandler -de.uka.ilkd.key.gui.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file +key.isabelletranslation.DefinedSymbolsHandler +key.isabelletranslation.InstanceOperatorHandler +key.isabelletranslation.BooleanOpHandler +key.isabelletranslation.PolymorphicHandler +key.isabelletranslation.QuantifierHandler +key.isabelletranslation.LogicalVariableHandler +key.isabelletranslation.NumberConstantsHandler +key.isabelletranslation.IntegerOpHandler +key.isabelletranslation.InfiniteUnionHandler +key.isabelletranslation.BSumHandler +key.isabelletranslation.SeqDefHandler +key.isabelletranslation.SortDependingFunctionHandler +key.isabelletranslation.FieldHandler +key.isabelletranslation.ObserverFunctionHandler +key.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file From 51d85cde22be438b825e14faa2b103faf5f9aad2 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 21 Aug 2024 15:18:13 +0200 Subject: [PATCH 213/248] Major Launcher reworks and first version of UI (nonfunctional) --- .../isabelletranslation/IsabelleLauncher.java | 13 + .../IsabelleLauncherListener.java | 13 + .../IsabelleResourceController.java | 131 ++++++ .../IsabelleSimpleSolverListener.java | 111 +++++ .../isabelletranslation/IsabelleSolver.java | 63 +++ .../IsabelleSolverInstance.java | 182 ++++++++ .../IsabelleSolverListener.java | 2 +- .../IsabelleTranslationExtension.java | 2 +- .../IsabelleTranslationSettings.java | 4 + .../IsabelleTranslator.java | 2 +- .../TranslationAction.java | 53 ++- .../gui/IsabelleProgressDialog.java | 427 ++++++++++++++++++ .../gui/IsabelleProgressModel.java | 241 ++++++++++ 13 files changed, 1222 insertions(+), 22 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index 7a1f60e3109..42debbfbb26 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -1,5 +1,9 @@ package key.isabelletranslation; +import de.uka.ilkd.key.gui.smt.ProgressDialog; +import de.uka.ilkd.key.gui.smt.SolverListener; +import de.uka.ilkd.key.smt.SolverLauncher; +import key.isabelletranslation.gui.IsabelleProgressDialog; import org.key_project.util.collection.Pair; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; @@ -15,6 +19,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; @@ -24,11 +29,14 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; +import key.isabelletranslation.gui.IsabelleProgressModel; public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); private final IsabelleTranslationSettings settings; + private IsabelleLauncherListener listener; + public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { this.settings = settings; @@ -50,6 +58,7 @@ private Theory beginTheory(Path source, Isabelle isabelle) { } public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int coreCount) throws IOException { + listener.launcherStarted(this, problems); ExecutorService executorService = Executors.newFixedThreadPool(coreCount); Collection>> tasks = new LinkedBlockingDeque<>(); LinkedBlockingDeque> resourceInstances = new LinkedBlockingDeque<>(); @@ -112,4 +121,8 @@ private Isabelle startIsabelleInstance() throws IOException { } return isabelle; } + + public void addListener(IsabelleLauncherListener listener) { + this.listener = listener; + } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java new file mode 100644 index 00000000000..fcc686c541d --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java @@ -0,0 +1,13 @@ +package key.isabelletranslation; + +import key.isabelletranslation.gui.IsabelleProgressDialog; +import key.isabelletranslation.gui.IsabelleProgressModel; + +import javax.swing.*; +import java.util.Collection; + +public interface IsabelleLauncherListener { + void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances); + + void launcherStarted(IsabelleLauncher launcher, Collection problems); +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java new file mode 100644 index 00000000000..e5309597dca --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -0,0 +1,131 @@ +package key.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.mlvalue.ListConverter; +import de.unruh.isabelle.mlvalue.MLFunction2; +import de.unruh.isabelle.mlvalue.MLFunction3; +import de.unruh.isabelle.mlvalue.MLValue; +import de.unruh.isabelle.pure.Implicits; +import de.unruh.isabelle.pure.Position; +import de.unruh.isabelle.pure.Theory; +import de.unruh.isabelle.pure.TheoryHeader; +import org.slf4j.LoggerFactory; +import org.slf4j.Logger; +import scala.collection.immutable.List; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.concurrent.LinkedBlockingQueue; + +public class IsabelleResourceController { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleResourceController.class); + private LinkedBlockingQueue idleInstances; + + private IsabelleTranslationSettings settings; + + private boolean isShutdown = false; + + private Collection waitingSolvers; + + + + public IsabelleResourceController(int numberOfInstances) throws IOException { + settings = IsabelleTranslationSettings.getInstance(); + idleInstances = new LinkedBlockingQueue<>(numberOfInstances); + waitingSolvers = new HashSet<>(); + for (int i = 0; i < numberOfInstances; i++) { + idleInstances.add(createIsabelleResource()); + } + } + + public IsabelleResource getIsabelleResource(IsabelleSolver requestingSolver) throws InterruptedException { + waitingSolvers.add(requestingSolver); + return idleInstances.take(); + } + + public void shutdownGracefully() { + isShutdown = true; + + waitingSolvers.forEach((x) -> x.interrupt(IsabelleSolver.ReasonOfInterruption.Exception)); + waitingSolvers.clear(); + + idleInstances.forEach(IsabelleResource::destroy); + idleInstances.clear(); + } + + public static IsabelleResource createIsabelleResourceFromInstance(Isabelle isabelle, IsabelleTranslationSettings settings) { + Theory theory = beginTheory(isabelle, settings); + return new IsabelleResource(isabelle, theory); + } + + + public void returnResource(IsabelleResource resource) { + if (resource.isDestroyed()) { + try { + resource = createIsabelleResource(); + } catch (IOException e) { + //Should not occur. If it was possible to create instances during creation, it should be possible now. + shutdownGracefully(); + LOGGER.error(e.getMessage()); + } + } + resource.interrupt(); + idleInstances.offer(resource); + } + + private IsabelleResource createIsabelleResource() throws IOException { + Isabelle isabelleInstance = startIsabelleInstance(); + Theory theory = beginTheory(isabelleInstance, settings); + return new IsabelleResource(isabelleInstance, theory); + } + + private Isabelle startIsabelleInstance() throws IOException { + ArrayList sessionRoots = new ArrayList<>(); + sessionRoots.add(settings.getTranslationPath()); + Isabelle isabelle; + try { + Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); + isabelle = new Isabelle(setup); + } catch (Exception e) { + LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); + throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); + } + return isabelle; + } + + private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings settings) { + MLFunction3, Theory> begin_theory = + MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + + TheoryHeader header = header_read.apply(settings.getHeader(), Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); + Path topDir = settings.getTranslationPath(); + return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) + .retrieveNow(Implicits.theoryConverter(), isabelle); + } + + public record IsabelleResource(Isabelle instance, Theory theory) { + public boolean isDestroyed() { + return instance.isDestroyed(); + } + + public void destroy() { + instance.destroy(); + } + + public void interrupt() { + instance.executeMLCodeNow("error \"Interrupt\""); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java new file mode 100644 index 00000000000..eca34281902 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java @@ -0,0 +1,111 @@ +package key.isabelletranslation; + +import de.uka.ilkd.key.gui.smt.ProgressDialog; +import de.uka.ilkd.key.gui.smt.SolverListener; +import de.uka.ilkd.key.smt.SolverLauncher; +import key.isabelletranslation.gui.IsabelleProgressDialog; +import key.isabelletranslation.gui.IsabelleProgressModel; + +import javax.swing.*; +import java.util.Collection; + +public class IsabelleSimpleSolverListener implements IsabelleLauncherListener { + @Override + public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { + + } + + @Override + public void launcherStarted(IsabelleLauncher launcher, Collection problems) { + prepareDialog(problems, launcher); + } + + protected void stopEvent(IsabelleLauncher launcher) { + + } + + protected void applyEvent(IsabelleLauncher launcher) { + + } + + protected void discardEvent(IsabelleLauncher launcher) { + + } + + public IsabelleSimpleSolverListener(IsabelleTranslationSettings settings) { + + } + + + private static final int RESOLUTION = 1000; + + private Collection problems; + private IsabelleProgressModel progressModel; + private boolean[] problemProcessed; + private IsabelleProgressDialog progressDialog; + + private void prepareDialog(Collection problems, final IsabelleLauncher launcher) { + this.problems = problems; + progressModel = new IsabelleProgressModel(); + + String[] captions = new String[problems.size()]; + + int i = 0; + for (IsabelleProblem problem : problems) { + captions[i] = "Problem " + i; + i++; + } + + progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); + problemProcessed = new boolean[problems.size()]; + progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(problems.size())); + + for (IsabelleProblem problem : problems) { + + } + + + progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, + RESOLUTION, problems.size(), new String[] {}, (new String[]{"Isabelle"})); + + + SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); + + } + + private class IsabelleProgressDialogListenerImpl implements IsabelleProgressDialog.IsabelleProgressDialogListener { + + + private final IsabelleLauncher launcher; + + + public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { + super(); + this.launcher = launcher; + } + + @Override + public void infoButtonClicked(int column, int row) { + //SolverListener.InternSMTProblem problem = getProblem(column, row); + //showInformation(problem); + + } + + @Override + public void stopButtonClicked() { + + stopEvent(launcher); + } + + @Override + public void applyButtonClicked() { + applyEvent(launcher); + + } + + @Override + public void discardButtonClicked() { + discardEvent(launcher); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java new file mode 100644 index 00000000000..3d6f4f553fc --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java @@ -0,0 +1,63 @@ +package key.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; + +import java.util.TimerTask; + +public interface IsabelleSolver { + enum ReasonOfInterruption { + User, Timeout, Exception, NoInterruption + } + + enum SolverState{ + Waiting, StartingIsabelle, Building, Parsing, Running, Stopped + } + + String name(); + + String getTranslation(); + + IsabelleProblem getProblem(); + + Throwable getException(); + + void interrupt(ReasonOfInterruption reason); + + long getStartTime(); + + long getTimeout(); + + void setTimeout(long timeout); + + SolverState getState(); + + boolean wasInterrupted(); + + boolean isRunning(); + + void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings); + + + void start(IsabelleSolverTimeout timeout, Isabelle isabelleInstance); + + String getRawSolverOutput(); + + String getRawSolverInput(); + + SledgehammerResult getFinalResult(); + + + class IsabelleSolverTimeout extends TimerTask { + private final IsabelleSolver solver; + + public IsabelleSolverTimeout(IsabelleSolver solver) { + this.solver = solver; + } + + @Override + public void run() { + solver.interrupt(ReasonOfInterruption.Timeout); + } + } + +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java new file mode 100644 index 00000000000..92291513755 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -0,0 +1,182 @@ +package key.isabelletranslation; + +import de.unruh.isabelle.control.Isabelle; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IsabelleSolverInstance implements IsabelleSolver, Runnable { + private SledgehammerResult result; + + private IsabelleResourceController.IsabelleResource isabelleResource; + + /** + * The SMT problem that is related to this solver + */ + private final IsabelleProblem problem; + + /** + * It is possible that a solver has a listener. + */ + private final IsabelleSolverListener listener; + + /** + * The thread that is associated with this solver. + */ + private Thread thread; + + /** + * The timeout that is associated with this solver. Represents the timertask that is started + * when the solver is started. + */ + private IsabelleSolverTimeout solverTimeout; + + /** + * stores the reason for interruption if present (e.g. User, Timeout, Exception) + */ + private ReasonOfInterruption reasonOfInterruption = ReasonOfInterruption.NoInterruption; + + /** + * the state the solver is currently in + */ + private SolverState solverState = SolverState.Waiting; + + /** + * Stores the settings that are used for the execution. + */ + private IsabelleTranslationSettings isabelleSettings; + + /** + * Stores the translation of the problem that is associated with this solver + */ + private String problemString = "NOT YET COMPUTED"; + + /** + * If there was an exception while executing the solver it is stored in this attribute. + */ + private Throwable exception; + + /** + * The timeout in seconds for this SMT solver run. + */ + private long timeout = -1; + + private IsabelleResourceController resourceController; + + + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); + + public IsabelleSolverInstance(IsabelleProblem problem, IsabelleSolverListener listener, IsabelleResourceController resourceController) { + this.problem = problem; + this.listener = listener; + this.resourceController = resourceController; + } + + @Override + public String name() { + return "Isabelle"; + } + + @Override + public String getTranslation() { + return problem.getSequentTranslation(); + } + + @Override + public IsabelleProblem getProblem() { + return problem; + } + + @Override + public Throwable getException() { + return exception; + } + + @Override + public void interrupt(ReasonOfInterruption reason) { + setReasonOfInterruption(reason); + setSolverState(SolverState.Stopped); + if (solverTimeout != null) { + solverTimeout.cancel(); + } + if (thread != null) { + thread.interrupt(); + } + } + + private void setSolverState(SolverState solverState) { + this.solverState = solverState; + } + + public void setReasonOfInterruption(ReasonOfInterruption reasonOfInterruption) { + this.reasonOfInterruption = reasonOfInterruption; + } + + @Override + public long getStartTime() { + return 0; + } + + @Override + public long getTimeout() { + return 0; + } + + @Override + public void setTimeout(long timeout) { + + } + + @Override + public SolverState getState() { + return null; + } + + @Override + public boolean wasInterrupted() { + return false; + } + + @Override + public boolean isRunning() { + return false; + } + + @Override + public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings) { + thread = new Thread(this, "IsabelleSolverInstance"); + this.solverTimeout = timeout; + isabelleSettings = settings; + thread.start(); + } + + @Override + public void start(IsabelleSolverTimeout timeout, Isabelle isabelleInstance) { + thread = new Thread(this, "IsabelleSolverInstance"); + isabelleResource = IsabelleResourceController.createIsabelleResourceFromInstance(isabelleInstance, isabelleSettings); + this.solverTimeout = timeout; + thread.start(); + } + + @Override + public String getRawSolverOutput() { + return problem.getResult().result().toString(); + } + + @Override + public String getRawSolverInput() { + return problem.getSequentTranslation(); + } + + @Override + public SledgehammerResult getFinalResult() { + return problem.getResult(); + } + + @Override + public void run() { + //Ensure there is an active IsabelleInstance + setSolverState(SolverState.StartingIsabelle); + listener.processStarted(problem); + + } +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java index 4bf0597d87a..ebeeb068596 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java @@ -1,6 +1,6 @@ package key.isabelletranslation; -public interface IsabelleSolverListener { +public interface IsabelleSolverListener extends IsabelleLauncherListener { void parsingStarted(IsabelleProblem problem); void parsingFinished(IsabelleProblem problem); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java index d1b5214a32c..2f7734b3dcc 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java @@ -16,7 +16,7 @@ import java.util.List; @KeYGuiExtension.Info(name = "Isabelle Translation", optional = true, - experimental = true) + experimental = false) public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationExtension.class); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java index 9652a5916fd..ee3195c7723 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java @@ -144,4 +144,8 @@ public void writeSettings(@NonNull Configuration props) { props.set(isabellePathKey, isabellePath.toString()); props.set(translationPathKey, translationPath.toString()); } + + public String getHeader() { + return "theory Translation imports Main KeYTranslations.TranslationPreamble begin"; + } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java index 833ac4ea4b6..86c91d65ac8 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java @@ -55,7 +55,7 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx } translationPreamble.append("end"); - StringBuilder sequentTranslation = new StringBuilder("theory Translation imports Main KeYTranslations.TranslationPreamble begin").append(LINE_ENDING); + StringBuilder sequentTranslation = new StringBuilder(IsabelleTranslationSettings.getInstance().getHeader()).append(LINE_ENDING); //TODO make this into a tree structure to avoid excessive looping (over sorts) | sort the implementation queue Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index 79578b18178..6d77716d23c 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -3,8 +3,14 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.uka.ilkd.key.gui.smt.SolverListener; import de.uka.ilkd.key.rule.IBuiltInRuleApp; +import de.uka.ilkd.key.settings.DefaultSMTSettings; +import de.uka.ilkd.key.settings.ProofIndependentSettings; +import de.uka.ilkd.key.smt.SMTProblem; import de.uka.ilkd.key.smt.SMTRuleApp; +import de.uka.ilkd.key.smt.SolverLauncher; +import de.unruh.isabelle.control.Isabelle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,6 +18,8 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; public class TranslationAction extends MainWindowAction { @@ -44,7 +52,32 @@ private void generateTranslation() { writeTranslationFiles(translation); - SledgehammerResult result = translation.sledgehammer(30); + List list = new ArrayList<>(); + + list.add(translation); + + SledgehammerResult result = null; + Thread thread = new Thread(() -> { + + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); + IsabelleLauncher launcher; + try { + launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); + } catch (IOException e) { + throw new RuntimeException(e); + } + + launcher.addListener(new IsabelleSimpleSolverListener(settings)); + try { + launcher.try0ThenSledgehammerAllPooled(list, 30, 1); + } catch (IOException e) { + throw new RuntimeException(e); + } + + }, "IsabelleControlThread"); + thread.start(); + result = translation.getResult(); + //SledgehammerResult result = translation.sledgehammer(30); //TODO needs its own action to enable undo, etc. and naming reworks if (result != null && result.isSuccessful()) { @@ -52,24 +85,6 @@ private void generateTranslation() { app.tryToInstantiate(mediator.getSelectedGoal()); mediator.getSelectedGoal().apply(app); } - - - - /* - List filePaths = new ArrayList<>(); - filePaths.add(translationFile.toPath()); - - Builder> builder = Seq.newBuilder(); - for (Path path : filePaths) { - builder.addOne(path); - } - - - Seq pathSeq = builder.result(); - //TODO improve concurrency? - Thread isabelleJEdit = new Thread(() -> Isabelle.jedit(setup, pathSeq)); - - isabelleJEdit.start();*/ } protected static void writeTranslationFiles(IsabelleProblem translation) { diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java new file mode 100644 index 00000000000..2439eae1d31 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java @@ -0,0 +1,427 @@ +/* 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 key.isabelletranslation.gui; + +import de.uka.ilkd.key.gui.IssueDialog; +import de.uka.ilkd.key.gui.MainWindow; +import org.key_project.util.java.SwingUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import key.isabelletranslation.gui.IsabelleProgressModel.ProcessColumn.ProcessData; + +import javax.swing.*; +import javax.swing.event.TableModelEvent; +import javax.swing.plaf.basic.BasicProgressBarUI; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; +import java.awt.*; + +/** + * Dialog showing launched Isabelle processes and results. + */ +public class IsabelleProgressDialog extends JDialog { + + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProgressDialog.class); + + private final ProgressTable table; + /** + * Button to apply the results of running the SMT solver. + * May close some open goals if the solver returned unsat. + */ + private JButton applyButton; + /** + * Button to stop the launched SMT solvers. + */ + private JButton stopButton; + /** + * Scroll pane listing the open goals and the results of running each SMT solver on them. + */ + private JScrollPane scrollPane; + /** + * Overall progress of the SMT solvers (# goals started / total goals). + */ + private JProgressBar progressBar; + private final IsabelleProgressDialogListener listener; + + /** + * Current state of the dialog. + */ + public enum Modus { + /** + * SMT solvers are running and may be stopped by the user. + */ + SOLVERS_RUNNING, + /** + * SMT solvers are done (or terminated). Results may be applied by the user. + */ + SOLVERS_DONE + } + + /** + * Current state of the dialog. + */ + private Modus modus = Modus.SOLVERS_RUNNING; + + public interface IsabelleProgressDialogListener extends ProgressTable.ProgressTableListener { + void applyButtonClicked(); + + void stopButtonClicked(); + + void discardButtonClicked(); + } + + public IsabelleProgressDialog(IsabelleProgressModel model, IsabelleProgressDialogListener listener, + boolean counterexample, int resolution, int progressBarMax, String[] labelTitles, + String... titles) { + super(MainWindow.getInstance()); + table = new ProgressTable(resolution, listener, labelTitles); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + table.getTableHeader().setReorderingAllowed(false); + table.setModel(model, titles); + this.listener = listener; + this.setTitle("Isabelle Interface"); + + getProgressBar().setMaximum(progressBarMax); + + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setModal(true); + Container contentPane = this.getContentPane(); + contentPane.setLayout(new GridBagLayout()); + Box buttonBox = Box.createHorizontalBox(); + buttonBox.add(Box.createHorizontalGlue()); + buttonBox.add(getStopButton()); + buttonBox.add(Box.createHorizontalStrut(5)); + if (!counterexample) { + buttonBox.add(Box.createHorizontalStrut(5)); + buttonBox.add(getApplyButton()); + buttonBox.add(Box.createHorizontalStrut(5)); + } + + + GridBagConstraints constraints = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, + GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 0, 5), 0, 0); + + contentPane.add(getProgressBar(), constraints); + constraints.gridy++; + constraints.weighty = 2.0; + contentPane.add(getScrollPane(), constraints); + constraints.gridy += 2; + constraints.weighty = 0.0; + constraints.insets.bottom = 5; + contentPane.add(buttonBox, constraints); + this.pack(); + // always set the location last, otherwise it is not centered! + setLocationRelativeTo(MainWindow.getInstance()); + } + + public void setProgress(int value) { + getProgressBar().setValue(value); + } + + public JProgressBar getProgressBar() { + if (progressBar == null) { + progressBar = new JProgressBar(); + + } + + return progressBar; + } + + private JButton getApplyButton() { + if (applyButton == null) { + applyButton = new JButton("Apply"); + applyButton.setToolTipText( + "Apply the results (i.e. close goals if the SMT solver was successful)"); + applyButton.setEnabled(false); + applyButton.addActionListener(e -> { + try { + listener.applyButtonClicked(); + } catch (Exception exception) { + // There may be exceptions during rule application that should not be lost. + LOGGER.error("", exception); + IssueDialog.showExceptionDialog(this, exception); + } + }); + } + return applyButton; + } + + private JScrollPane getScrollPane() { + if (scrollPane == null) { + scrollPane = SwingUtil.createScrollPane(table); + } + return scrollPane; + } + + private JButton getStopButton() { + if (stopButton == null) { + stopButton = new JButton("Stop"); + stopButton.addActionListener(e -> { + if (modus.equals(Modus.SOLVERS_DONE)) { + listener.discardButtonClicked(); + } + if (modus.equals(Modus.SOLVERS_RUNNING)) { + listener.stopButtonClicked(); + } + }); + } + return stopButton; + } + + public void setModus(Modus m) { + modus = m; + switch (modus) { + case SOLVERS_DONE -> { + stopButton.setText("Discard"); + if (applyButton != null) { + applyButton.setEnabled(true); + } + } + case SOLVERS_RUNNING -> { + stopButton.setText("Stop"); + if (applyButton != null) { + applyButton.setEnabled(false); + } + } + } + } +} + + +class ProgressTable extends JTable { + + private static final long serialVersionUID = 1L; + private static final int NUMBER_OF_VISIBLE_ROWS = 8; + + public interface ProgressTableListener { + void infoButtonClicked(int column, int row); + } + + + public static class ProgressPanel extends JPanel { + private static final long serialVersionUID = 1L; + private JProgressBar progressBar; + private JButton infoButton; + + private JProgressBar getProgressBar() { + if (progressBar == null) { + progressBar = new JProgressBar(); + int height = getInfoButton().getMaximumSize().height; + progressBar.setMaximumSize(new Dimension(Integer.MAX_VALUE, height)); + progressBar.setString("Test"); + progressBar.setStringPainted(true); + progressBar.setFont(this.getFont()); + } + return progressBar; + } + + private JButton getInfoButton() { + if (infoButton == null) { + infoButton = new JButton("Info"); + infoButton.setFont(this.getFont()); + + Dimension dim = new Dimension(); + infoButton.setMargin(new Insets(0, 0, 0, 0)); + + dim.height = this.getFontMetrics(this.getFont()).getHeight() + 2; + dim.width = dim.height * 3; + + infoButton.setMinimumSize(dim); + infoButton.setPreferredSize(dim); + infoButton.setMaximumSize(dim); + + } + return infoButton; + } + + ProgressPanel() { + + this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + this.add(Box.createVerticalStrut(2)); + Box content = Box.createHorizontalBox(); + content.add(Box.createHorizontalStrut(2)); + content.add(getProgressBar()); + content.add(Box.createHorizontalStrut(2)); + content.add(getInfoButton()); + content.add(Box.createHorizontalStrut(2)); + this.add(content); + this.add(Box.createVerticalStrut(2)); + } + + public void setValue(int value) { + getProgressBar().setValue(value); + } + + public void setText(String text) { + getProgressBar().setString(text); + getProgressBar().setStringPainted(text != null && !text.isEmpty()); + } + } + + + + private final ProgressPanel progressPanelRenderer = new ProgressPanel(); + private ProgressPanel progressPanelEditor; + + + + private class ProgressCellEditor extends AbstractCellEditor implements TableCellEditor { + + private static final long serialVersionUID = 1L; + + + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, + int row, int column) { + + currentEditorCell.x = column; + currentEditorCell.y = row; + ProcessData data = (ProcessData) value; + prepareProgressPanel(getProgressPanelEditor(), data); + return getProgressPanelEditor(); + } + + + + @Override + public Object getCellEditorValue() { + return null; + } + + } + + + + private void prepareProgressPanel(ProgressPanel panel, final ProcessData data) { + panel.setValue(data.getProgress()); + panel.setText(data.getText()); + panel.infoButton.setEnabled(data.isEditable()); + panel.progressBar.setBackground(data.getBackgroundColor()); + panel.progressBar.setForeground(data.getForegroundColor()); + panel.progressBar.setUI(new BasicProgressBarUI() { + + + @Override + protected Color getSelectionForeground() { + return data.getSelectedTextColor(); + } + + protected Color getSelectionBackground() { return data.getTextColor(); } + }); + + } + + private final TableCellRenderer renderer = + (table, value, isSelected, hasFocus, row, column) -> { + ProcessData data = (ProcessData) value; + prepareProgressPanel(progressPanelRenderer, data); + return progressPanelRenderer; + }; + + + private final TableCellEditor editor = new ProgressCellEditor(); + private final Point currentEditorCell = new Point(); + + + + public ProgressTable(int resolution, ProgressTableListener listener, String... titles) { + this.setDefaultRenderer(IsabelleProgressModel.ProcessColumn.class, renderer); + this.setDefaultEditor(IsabelleProgressModel.ProcessColumn.class, editor); + init(getProgressPanelEditor(), this.getFont(), resolution, listener); + init(progressPanelRenderer, this.getFont(), resolution, listener); + + } + + private void init(ProgressPanel panel, Font font, int resolution, + final ProgressTableListener listener) { + panel.setFont(font); + panel.progressBar.setMaximum(resolution); + panel.infoButton.addActionListener( + e -> listener.infoButtonClicked(currentEditorCell.x - 1, currentEditorCell.y)); + + + } + + + public void setModel(IsabelleProgressModel model, String... titles) { + + assert titles.length == model.getColumnCount(); + super.setModel(model); + for (int i = 0; i < titles.length; i++) { + TableColumn col = getTableHeader().getColumnModel().getColumn(i); + + col.setHeaderValue(titles[i]); + packColumn(this, i, 5); + + } + for (int i = 0; i < model.getRowCount(); i++) { + this.setRowHeight(progressPanelRenderer.getPreferredSize().height + 5); + } + + + + } + + @Override + public Dimension getPreferredScrollableViewportSize() { + Dimension dim = new Dimension(super.getPreferredScrollableViewportSize()); + + dim.height = + Math.min(NUMBER_OF_VISIBLE_ROWS * (progressPanelRenderer.getPreferredSize().height + 5), + dim.height); + return dim; + } + + public static void packColumn(JTable table, int vColIndex, int margin) { + + TableColumnModel colModel = table.getColumnModel(); + TableColumn col = colModel.getColumn(vColIndex); + int width = 0; + + + TableCellRenderer renderer = col.getHeaderRenderer(); + if (renderer == null) { + renderer = table.getTableHeader().getDefaultRenderer(); + } + Component comp = + renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); + width = comp.getPreferredSize().width; + + + for (int r = 0; r < table.getRowCount(); r++) { + renderer = table.getCellRenderer(r, vColIndex); + comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), + false, false, r, vColIndex); + width = Math.max(width, comp.getPreferredSize().width); + } + + width += 10 * margin; + + col.setPreferredWidth(width); + } + + + + private ProgressPanel getProgressPanelEditor() { + if (progressPanelEditor == null) { + progressPanelEditor = new ProgressPanel(); + } + return progressPanelEditor; + } + + + @Override + public void tableChanged(TableModelEvent e) { + if (e.getType() == TableModelEvent.UPDATE) { + this.repaint(); + + } + super.tableChanged(e); + } + +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java new file mode 100644 index 00000000000..586e7c32808 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java @@ -0,0 +1,241 @@ +/* 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 key.isabelletranslation.gui; + +import java.awt.Color; +import java.util.ArrayList; +import javax.swing.table.AbstractTableModel; + +/** + * Encapsulates the table of progress bars that is shown within the progress dialog: For each solver + * and each goal there is a cell. + */ +public class IsabelleProgressModel extends AbstractTableModel { + private static final long serialVersionUID = 1L; + + private interface Column { + Object getObject(int row); + + int getRowCount(); + + boolean isEditable(); + + } + + public static class TitleColumn implements Column { + private final String[] titles; + + public TitleColumn(String... titles) { + super(); + this.titles = titles; + + } + + @Override + public Object getObject(int row) { + return titles[row]; + } + + @Override + public int getRowCount() { + + return titles.length; + } + + @Override + public boolean isEditable() { + + return false; + } + + } + + public static class ProcessColumn implements Column { + + static class ProcessData { + private int progress = 0; + private String text = ""; + private boolean isEditable = false; + private Color textColor = Color.BLACK; + private Color backgroundColor = Color.WHITE; + private Color foregroundColor = Color.BLUE; + private final Color selectedTextColor = Color.WHITE; + + public int getProgress() { + return progress; + } + + public String getText() { + return text; + } + + public boolean isEditable() { + return isEditable; + } + + public Color getBackgroundColor() { + return backgroundColor; + } + + public Color getSelectedTextColor() { + return selectedTextColor; + } + + public Color getTextColor() { + return textColor; + } + + public Color getForegroundColor() { + return foregroundColor; + } + + } + + // private final Object [] processes; + public final ProcessData[] data; + private boolean isEditable = false; + + public ProcessColumn(int size) { + super(); + + this.data = new ProcessData[size]; + + for (int i = 0; i < data.length; i++) { + data[i] = new ProcessData(); + + } + + } + + @Override + public Object getObject(int row) { + + return data[row]; + } + + public void setProgress(int value, int row) { + data[row].progress = value; + } + + public void setText(String value, int row) { + data[row].text = value; + } + + @Override + public int getRowCount() { + + return data.length; + } + + public void setEditable(boolean b) { + isEditable = b; + for (ProcessData datum : data) { + datum.isEditable = b; + } + } + + @Override + public boolean isEditable() { + + return isEditable; + } + + } + + private final ArrayList columns = new ArrayList<>(); + + private int rowCount = -1; + + public IsabelleProgressModel() { + super(); + } + + public void addColumn(Column column) { + if (rowCount != -1 && rowCount != column.getRowCount()) { + throw new IllegalArgumentException("Columns must have the same number of rows."); + } + rowCount = column.getRowCount(); + columns.add(column); + } + + public void setProgress(int value, int column, int row) { + column++; + ProcessColumn col = (ProcessColumn) columns.get(column); + col.setProgress(value, row); + this.fireTableCellUpdated(row, column); + } + + public void setText(String text, int column, int row) { + column++; + ProcessColumn col = (ProcessColumn) columns.get(column); + col.setText(text, row); + this.fireTableCellUpdated(row, column); + } + + public void setTextColor(Color color, int x, int y) { + x++; + ProcessColumn col = (ProcessColumn) columns.get(x); + col.data[y].textColor = color; + + this.fireTableCellUpdated(x, y); + } + + public void setForegroundColor(Color color, int x, int y) { + x++; + ProcessColumn col = (ProcessColumn) columns.get(x); + col.data[y].foregroundColor = color; + + this.fireTableCellUpdated(x, y); + } + + public void setBackgroundColor(Color color, int x, int y) { + x++; + ProcessColumn col = (ProcessColumn) columns.get(x); + col.data[y].backgroundColor = color; + this.fireTableCellUpdated(x, y); + } + + public void setEditable(boolean b) { + for (Column column : columns) { + if (column instanceof ProcessColumn) { + ((ProcessColumn) column).setEditable(b); + } + } + } + + @Override + public int getColumnCount() { + + return columns.size(); + } + + @Override + public int getRowCount() { + + return rowCount; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + return columns.get(columnIndex).isEditable(); + } + + @Override + public Class getColumnClass(int columnIndex) { + return columns.get(columnIndex).getClass(); + + } + + @Override + public Object getValueAt(int row, int col) { + + return columns.get(col).getObject(row); + } + + public Column getColumn(int col) { + return columns.get(col); + } + +} From fee0bafeb057e9ffcdfd75266ba516ff25b844e5 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 22 Aug 2024 01:38:33 +0200 Subject: [PATCH 214/248] Further Launcher Structure reworks and adding TranslateAllAction --- .../isabelletranslation/IsabelleLauncher.java | 64 +-- ...java => IsabelleLauncherListenerImpl.java} | 9 +- .../isabelletranslation/IsabelleProblem.java | 415 +----------------- .../IsabelleResourceController.java | 14 +- .../IsabelleSolverInstance.java | 278 +++++++++++- .../IsabelleSolverListener.java | 26 +- .../IsabelleTranslationExtension.java | 1 + .../TranslateAllAction.java | 95 ++++ .../TranslationAction.java | 8 +- 9 files changed, 414 insertions(+), 496 deletions(-) rename keyext.isabelletranslation/src/main/java/key/isabelletranslation/{IsabelleSimpleSolverListener.java => IsabelleLauncherListenerImpl.java} (88%) create mode 100644 keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index 42debbfbb26..d32fd1a62b0 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -1,9 +1,5 @@ package key.isabelletranslation; -import de.uka.ilkd.key.gui.smt.ProgressDialog; -import de.uka.ilkd.key.gui.smt.SolverListener; -import de.uka.ilkd.key.smt.SolverLauncher; -import key.isabelletranslation.gui.IsabelleProgressDialog; import org.key_project.util.collection.Pair; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.java.JIsabelle; @@ -19,17 +15,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.swing.*; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Timer; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; -import key.isabelletranslation.gui.IsabelleProgressModel; public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); @@ -57,71 +52,60 @@ private Theory beginTheory(Path source, Isabelle isabelle) { .retrieveNow(Implicits.theoryConverter(), isabelle); } - public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int coreCount) throws IOException { + public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int instanceCount) throws IOException { listener.launcherStarted(this, problems); - ExecutorService executorService = Executors.newFixedThreadPool(coreCount); + ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); Collection>> tasks = new LinkedBlockingDeque<>(); - LinkedBlockingDeque> resourceInstances = new LinkedBlockingDeque<>(); - LinkedBlockingDeque problemsQueue = new LinkedBlockingDeque<>(problems); + LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); + + + IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); Thread shutdownResources = new Thread(() -> { - for (Pair resources : resourceInstances) { - resources.first.destroy(); - } executorService.shutdown(); + resourceController.shutdownGracefully(); }); Runtime.getRuntime().addShutdownHook(shutdownResources); if (problems.isEmpty()) { return; } + //Ensure the preamble theory is present TranslationAction.writeTranslationFiles(problems.get(0)); - for (int i = 0; i < coreCount; i++) { - Isabelle isabelle = startIsabelleInstance(); - Theory thy0 = beginTheory(settings.getTranslationPath(), isabelle); - resourceInstances.add(new Pair<>(isabelle, thy0)); + problems.forEach((problem) -> { + IsabelleSolver solver = new IsabelleSolverInstance(problem, List.of(new IsabelleSolverListener[0]), resourceController); + solver.setTimeout(timeoutSeconds); + solverQueue.add(solver); + }); + + Timer timer = new Timer(true); + for (int i = 0; i < instanceCount; i++) { tasks.add(() -> { - IsabelleProblem problem; + IsabelleSolver solver; Pair resources; - while ((problem = problemsQueue.poll()) != null && (resources = resourceInstances.poll()) != null) { - problem.try0ThenSledgehammer(resources.first, resources.second, timeoutSeconds); - resourceInstances.add(resources); + while ((solver = solverQueue.poll()) != null) { + //IsabelleSolver.IsabelleSolverTimeout solverTimeout = new IsabelleSolver.IsabelleSolverTimeout(solver); + //timer.schedule(null, solver.getTimeout()); + solver.start(null, settings); } return null; }); } - LOGGER.info("Setup complete, solver starting {} problems...", problems.size()); + LOGGER.info("Setup complete, starting {} problems...", problems.size()); try { executorService.invokeAll(tasks); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { - shutdownResources.run(); + shutdownResources.start(); Runtime.getRuntime().removeShutdownHook(shutdownResources); } } - private Isabelle startIsabelleInstance() throws IOException { - ArrayList sessionRoots = new ArrayList<>(); - sessionRoots.add(settings.getTranslationPath()); - Isabelle isabelle; - try { - Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); - isabelle = new Isabelle(setup); - } catch (Exception e) { - LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); - throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); - } - return isabelle; - } - public void addListener(IsabelleLauncherListener listener) { this.listener = listener; } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java similarity index 88% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java index eca34281902..b62e131807f 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSimpleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java @@ -1,15 +1,12 @@ package key.isabelletranslation; -import de.uka.ilkd.key.gui.smt.ProgressDialog; -import de.uka.ilkd.key.gui.smt.SolverListener; -import de.uka.ilkd.key.smt.SolverLauncher; import key.isabelletranslation.gui.IsabelleProgressDialog; import key.isabelletranslation.gui.IsabelleProgressModel; import javax.swing.*; import java.util.Collection; -public class IsabelleSimpleSolverListener implements IsabelleLauncherListener { +public class IsabelleLauncherListenerImpl implements IsabelleLauncherListener { @Override public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { @@ -32,7 +29,7 @@ protected void discardEvent(IsabelleLauncher launcher) { } - public IsabelleSimpleSolverListener(IsabelleTranslationSettings settings) { + public IsabelleLauncherListenerImpl(IsabelleTranslationSettings settings) { } @@ -66,7 +63,7 @@ private void prepareDialog(Collection problems, final IsabelleL progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, - RESOLUTION, problems.size(), new String[] {}, (new String[]{"Isabelle"})); + RESOLUTION, problems.size(), new String[] {}, "", "Isabelle"); SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java index 37e64758ac1..6bf740f366b 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java @@ -57,418 +57,7 @@ public SledgehammerResult getResult() { return result; } - public SledgehammerResult sledgehammer(long timeout_seconds) { - LOGGER.debug("Starting Isabelle..."); - notifyProcessStarted(); - IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); - - Isabelle isabelle; - ArrayList sessionRoots = new ArrayList<>(); - sessionRoots.add(settings.getTranslationPath()); - notifyBuildingStarted(); - try { - Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); - isabelle = new Isabelle(setup); - } catch (Exception e) { - LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); - notifyBuildingError(e); - notifyProcessError(e); - return null; - } - - LOGGER.debug("Opening theory..."); - - Theory thy0 = beginTheory(getSequentTranslation(), Path.of((settings.getTranslationPath() + "\\Translation.thy")), isabelle); - ToplevelState toplevel = ToplevelState.apply(isabelle); - notifyBuildingFinished(); - - MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); - - MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - - - LOGGER.debug("Parsing theory..."); - notifyParsingStarted(); - try { - java.util.List> transitionsAndTexts = new ArrayList<>(); - parse_text.apply(thy0, getSequentTranslation(), isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) - .foreach(transitionsAndTexts::add); - - for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") - toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) - .retrieveNow(Implicits.toplevelStateConverter(), isabelle); - } - } catch (Exception e) { - isabelle.destroy(); - notifyParsingError(e); - return null; - } - notifyParsingFinished(); - LOGGER.debug("Finished Parsing"); - - String Try = thy0.importMLStructureNow("Try0", isabelle); - MLFunction try_function = - MLValue.compileFunction( - """ - fn (state) => - let - val p_state = Toplevel.proof_of state; - in - \s""" + Try + ".try0 (SOME (seconds 5.0)) ([], [], [], []) p_state" + """ - end - """, isabelle, Implicits.toplevelStateConverter(), - de.unruh.isabelle.mlvalue.Implicits.booleanConverter()); - - String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); - String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); - String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); - - MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = - MLValue.compileFunction( - """ - fn (state, thy, adds, dels) => - let - val override = {add=[],del=[],only=false}; - fun go_run (state, thy) = - let - val p_state = Toplevel.proof_of state; - val ctxt = Proof.context_of p_state; - val params =\s""" + Sledgehammer_Commands + """ - .default_params thy - [("timeout",\"""" + timeout_seconds + """ - "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; - val results =\s""" - + sledgehammer + """ - .run_sledgehammer params\s""" + Sledgehammer_Prover + """ - .Normal NONE 1 override p_state; - val (result, (outcome, step)) = results; - in - (result, (""" + sledgehammer + """ - .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - end; - in - Timeout.apply (Time.fromSeconds\s - """ + timeout_seconds + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); - - Builder> listBuilder = scala.collection.immutable.List.newBuilder(); - scala.collection.immutable.List emptyList = listBuilder.result(); - - SledgehammerResult result = null; - SledgehammerResult tryResult = null; - LOGGER.debug("Trying..."); - notifySledgehammerStarted(); - try { - Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) - .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Future tryResultSuccessF = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) - .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); - Boolean tryResultSuccess = false; - try { - tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - } catch (TimeoutException e) { - tryResultSuccess = false; - } - if (tryResultSuccess) { - tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); - this.result = tryResult; - notifySledgehammerFinished(); - notifyProcessFinished(); - LOGGER.debug("Sledgehammer result: " + this.result); - return this.result; - } - Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); - this.result = result; - } catch (TimeoutException exception) { - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } catch (InterruptedException exception) { - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } catch (Exception exception) { - if (exception.getMessage().contains("Timeout after")) { - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } else { - LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); - exception.printStackTrace(); - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } - } finally { - isabelle.destroy(); - } - - notifySledgehammerFinished(); - - notifyProcessFinished(); - - LOGGER.debug("Sledgehammer result: " + this.result); - return this.result; - } - - protected SledgehammerResult try0ThenSledgehammer(Isabelle isabelle, Theory thy0, long timeout_seconds) { - notifyProcessStarted(); - ToplevelState toplevel = ToplevelState.apply(isabelle); - - MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); - - MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - - - LOGGER.debug("Parsing theory..."); - notifyParsingStarted(); - try { - java.util.List> transitionsAndTexts = new ArrayList<>(); - parse_text.apply(thy0, getSequentTranslation(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()).retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle).foreach(transitionsAndTexts::add); - - for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") - toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()).retrieveNow(Implicits.toplevelStateConverter(), isabelle); - } - } catch (Exception e) { - notifyParsingError(e); - return null; - } - notifyParsingFinished(); - LOGGER.debug("Finished Parsing"); - - String Try = thy0.importMLStructureNow("Try0", isabelle); - MLFunction try_function = MLValue.compileFunction(""" - fn (state) => - let - val p_state = Toplevel.proof_of state; - in - \s""" + Try + ".try0 (SOME (seconds 5.0)) ([], [], [], []) p_state" + """ - end - """, isabelle, Implicits.toplevelStateConverter(), de.unruh.isabelle.mlvalue.Implicits.booleanConverter()); - - String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); - String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); - String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); - - MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = MLValue.compileFunction(""" - fn (state, thy, adds, dels) => - let - val override = {add=[],del=[],only=false}; - fun go_run (state, thy) = - let - val p_state = Toplevel.proof_of state; - val ctxt = Proof.context_of p_state; - val params =\s""" + Sledgehammer_Commands + """ - .default_params thy - [("timeout",\"""" + (timeout_seconds) + """ - "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; - val results =\s""" + sledgehammer + """ - .run_sledgehammer params\s""" + Sledgehammer_Prover + """ - .Normal NONE 1 override p_state; - val (result, (outcome, step)) = results; - in - (result, (""" + sledgehammer + """ - .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - end; - in - Timeout.apply (Time.fromSeconds\s - """ + (timeout_seconds + 100) + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); - - Builder> listBuilder = scala.collection.immutable.List.newBuilder(); - scala.collection.immutable.List emptyList = listBuilder.result(); - - SledgehammerResult result = null; - SledgehammerResult tryResult = null; - LOGGER.debug("Trying..."); - notifySledgehammerStarted(); - try { - Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())).retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Future tryResultSuccessF = try_function.apply(toplevel, isabelle, Implicits.toplevelStateConverter()) - .retrieve(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), isabelle); - Boolean tryResultSuccess; - try { - tryResultSuccess = (Boolean) Await.result(tryResultSuccessF, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - } catch (TimeoutException e) { - tryResultSuccess = false; - } - if (tryResultSuccess) { - tryResult = new SledgehammerResult(Option.apply(new Tuple2<>("some", "try0"))); - this.result = tryResult; - notifySledgehammerFinished(); - notifyProcessFinished(); - LOGGER.debug("Sledgehammer result: " + this.result); - return this.result; - } - Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(timeout_seconds, TimeUnit.SECONDS)); - result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); - this.result = result; - } catch (TimeoutException exception) { - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } catch (InterruptedException exception) { - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } catch (Exception exception) { - if (exception.getMessage().contains("Timeout after")) { - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } else { - LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); - exception.printStackTrace(); - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } - } - - if (result.isTimeout()) { - notifyProcessTimeout(); - } - - notifySledgehammerFinished(); - - notifyProcessFinished(); - - - LOGGER.debug("Sledgehammer result: " + this.result); - return this.result; - } - - private Theory beginTheory(String thyText, Path source, Isabelle isabelle) { - MLFunction3, Theory> begin_theory = - MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); - MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - - TheoryHeader header = header_read.apply(thyText, Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) - .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); - Path topDir = source.getParent(); - return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) - .retrieveNow(Implicits.theoryConverter(), isabelle); - } - - - private void notifyParsingStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.parsingStarted(this); - } - } - - private void notifyParsingFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.parsingFinished(this); - } - } - - private void notifyParsingError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.parsingFailed(this, e); - } - } - - private void notifyBuildingStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.buildingStarted(this); - } - } - - private void notifyBuildingFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.buildingFinished(this); - } - } - - private void notifyBuildingError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.buildingFailed(this, e); - } - } - - private void notifyProcessStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.processStarted(this); - } - } - - private void notifyProcessFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.processStopped(this); - } - } - - private void notifyProcessError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.processInterrupted(this, e); - } - } - - private void notifyProcessTimeout() { - for (IsabelleSolverListener listener : listeners) { - listener.processTimeout(this); - } - } - - private void notifySledgehammerStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerStarted(this); - } - } - - private void notifySledgehammerFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerFinished(this); - } - } - - private void notifySledgehammerError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerFailed(this, e); - } - } - - public void removeListener(IsabelleSolverListener listener) { - listeners.remove(listener); + protected void setResult(SledgehammerResult result) { + this.result = result; } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java index e5309597dca..3959cd8cde3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -1,6 +1,7 @@ package key.isabelletranslation; import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.control.IsabelleMLException; import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.ListConverter; import de.unruh.isabelle.mlvalue.MLFunction2; @@ -63,7 +64,7 @@ public static IsabelleResource createIsabelleResourceFromInstance(Isabelle isabe } - public void returnResource(IsabelleResource resource) { + public void returnResource(IsabelleSolver returningSolver, IsabelleResource resource) { if (resource.isDestroyed()) { try { resource = createIsabelleResource(); @@ -74,6 +75,7 @@ public void returnResource(IsabelleResource resource) { } } resource.interrupt(); + waitingSolvers.remove(returningSolver); idleInstances.offer(resource); } @@ -124,8 +126,16 @@ public void destroy() { instance.destroy(); } - public void interrupt() { + private void interruptIntern() throws IsabelleMLException { instance.executeMLCodeNow("error \"Interrupt\""); } + + public void interrupt() { + try { + interruptIntern(); + } catch (IsabelleMLException e) { + //Always throws this due to the way Isabelle is interrupted. + } + } } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index 92291513755..3fa109cfa2b 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -1,8 +1,31 @@ package key.isabelletranslation; +import com.sun.java.accessibility.util.TopLevelWindowListener; +import de.uka.ilkd.key.strategy.quantifierHeuristics.Constraint; import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.java.JIsabelle; +import de.unruh.isabelle.mlvalue.*; +import de.unruh.isabelle.pure.Implicits; +import de.unruh.isabelle.pure.Theory; +import de.unruh.isabelle.pure.ToplevelState; +import de.unruh.isabelle.pure.Transition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import scala.Option; +import scala.Tuple2; +import scala.collection.immutable.List; +import scala.collection.mutable.Builder; +import scala.concurrent.Await; +import scala.concurrent.Future; +import scala.concurrent.duration.Duration; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Timer; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; public class IsabelleSolverInstance implements IsabelleSolver, Runnable { private SledgehammerResult result; @@ -14,11 +37,6 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { */ private final IsabelleProblem problem; - /** - * It is possible that a solver has a listener. - */ - private final IsabelleSolverListener listener; - /** * The thread that is associated with this solver. */ @@ -64,10 +82,12 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); + private Collection listeners; - public IsabelleSolverInstance(IsabelleProblem problem, IsabelleSolverListener listener, IsabelleResourceController resourceController) { + public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, IsabelleResourceController resourceController) { this.problem = problem; - this.listener = listener; + this.listeners = new HashSet<>(); + this.listeners.addAll(listeners); this.resourceController = resourceController; } @@ -101,6 +121,14 @@ public void interrupt(ReasonOfInterruption reason) { if (thread != null) { thread.interrupt(); } + if (isabelleResource != null) { + shutdownAndReturnResource(); + } + } + + private void shutdownAndReturnResource() { + isabelleResource.interrupt(); + resourceController.returnResource(this, isabelleResource); } private void setSolverState(SolverState solverState) { @@ -113,32 +141,35 @@ public void setReasonOfInterruption(ReasonOfInterruption reasonOfInterruption) { @Override public long getStartTime() { - return 0; + if (solverTimeout == null) { + return -1; + } + return solverTimeout.scheduledExecutionTime(); } @Override public long getTimeout() { - return 0; + return this.timeout; } @Override public void setTimeout(long timeout) { - + this.timeout = timeout; } @Override public SolverState getState() { - return null; + return solverState; } @Override public boolean wasInterrupted() { - return false; + return reasonOfInterruption != ReasonOfInterruption.NoInterruption; } @Override public boolean isRunning() { - return false; + return solverState == SolverState.Running; } @Override @@ -146,7 +177,10 @@ public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings set thread = new Thread(this, "IsabelleSolverInstance"); this.solverTimeout = timeout; isabelleSettings = settings; - thread.start(); + + //TODO probably want asynchronous behavior + //Thread.start(); + run(); } @Override @@ -176,7 +210,221 @@ public SledgehammerResult getFinalResult() { public void run() { //Ensure there is an active IsabelleInstance setSolverState(SolverState.StartingIsabelle); - listener.processStarted(problem); + notifyProcessStarted(); + + try { + isabelleResource = resourceController.getIsabelleResource(this); + } catch (InterruptedException e) { + this.interrupt(ReasonOfInterruption.Exception); + notifyProcessError(e); + } + + Isabelle isabelle = isabelleResource.instance(); + Theory thy0 = isabelleResource.theory(); + + MLFunction2>> parse_text = MLValue.compileFunction(""" + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + + MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + + ToplevelState toplevel = ToplevelState.apply(isabelle); + LOGGER.debug("Parsing theory..."); + notifyParsingStarted(); + try { + java.util.List> transitionsAndTexts = new ArrayList<>(); + parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) + .foreach(transitionsAndTexts::add); + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } + } catch (Exception e) { + isabelleResource.destroy(); + notifyParsingError(e); + return; + } + notifyParsingFinished(); + LOGGER.debug("Finished Parsing"); + + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); + String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); + String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); + + MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = + MLValue.compileFunction( + """ + fn (state, thy, adds, dels) => + let + val override = {add=[],del=[],only=false}; + fun go_run (state, thy) = + let + val p_state = Toplevel.proof_of state; + val ctxt = Proof.context_of p_state; + val params =\s""" + Sledgehammer_Commands + """ + .default_params thy + [("timeout",\"""" + getTimeout() + """ + "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; + val results =\s""" + + sledgehammer + """ + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds\s + """ + getTimeout() + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); + + Builder> listBuilder = scala.collection.immutable.List.newBuilder(); + scala.collection.immutable.List emptyList = listBuilder.result(); + + SledgehammerResult result = null; + notifySledgehammerStarted(); + try { + Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) + .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); + Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); + result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); + this.result = result; + } catch (TimeoutException exception) { + interrupt(ReasonOfInterruption.Timeout); + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = result; + notifyProcessTimeout(); + } catch (InterruptedException exception) { + interrupt(ReasonOfInterruption.Exception); + result = new SledgehammerResult(Option.apply(null)); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); + } catch (Exception exception) { + interrupt(ReasonOfInterruption.Exception); + if (exception.getMessage().contains("Timeout after")) { + result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = result; + notifyProcessTimeout(); + } else { + LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); + exception.printStackTrace(); + result = new SledgehammerResult(Option.apply(null)); + this.result = result; + notifySledgehammerError(exception); + notifyProcessError(exception); + } + } + getProblem().setResult(this.result); + resourceController.returnResource(this, isabelleResource); + notifySledgehammerFinished(); + + notifyProcessFinished(); + + LOGGER.debug("Sledgehammer result: " + this.result); + } + + + + private void notifyParsingStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.parsingStarted(this, getProblem()); + } + } + + private void notifyParsingFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.parsingFinished(this, getProblem()); + } + } + + private void notifyParsingError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.parsingFailed(this, getProblem(), e); + } + } + + private void notifyBuildingStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.buildingStarted(this, getProblem()); + } + } + + private void notifyBuildingFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.buildingFinished(this, getProblem()); + } + } + + private void notifyBuildingError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.buildingFailed(this, getProblem(), e); + } + } + + private void notifyProcessStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.processStarted(this, getProblem()); + } + } + + private void notifyProcessFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.processStopped(this, getProblem()); + } + } + + private void notifyProcessError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.processInterrupted(this, getProblem(), e); + } + } + + private void notifyProcessTimeout() { + for (IsabelleSolverListener listener : listeners) { + listener.processTimeout(this, getProblem()); + } + } + + private void notifySledgehammerStarted() { + for (IsabelleSolverListener listener : listeners) { + listener.sledgehammerStarted(this, getProblem()); + } + } + + private void notifySledgehammerFinished() { + for (IsabelleSolverListener listener : listeners) { + listener.sledgehammerFinished(this, getProblem()); + } + } + + private void notifySledgehammerError(Exception e) { + for (IsabelleSolverListener listener : listeners) { + listener.sledgehammerFailed(this, getProblem(), e); + } + } + public void removeListener(IsabelleSolverListener listener) { + listeners.remove(listener); } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java index ebeeb068596..9c47f92d66f 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java @@ -1,29 +1,29 @@ package key.isabelletranslation; public interface IsabelleSolverListener extends IsabelleLauncherListener { - void parsingStarted(IsabelleProblem problem); + void parsingStarted(IsabelleSolver solver, IsabelleProblem problem); - void parsingFinished(IsabelleProblem problem); + void parsingFinished(IsabelleSolver solver, IsabelleProblem problem); - void parsingFailed(IsabelleProblem problem, Exception e); + void parsingFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); - void buildingStarted(IsabelleProblem problem); + void buildingStarted(IsabelleSolver solver, IsabelleProblem problem); - void buildingFinished(IsabelleProblem problem); + void buildingFinished(IsabelleSolver solver, IsabelleProblem problem); - void buildingFailed(IsabelleProblem problem, Exception e); + void buildingFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); - void processStarted(IsabelleProblem problem); + void processStarted(IsabelleSolver solver, IsabelleProblem problem); - void processInterrupted(IsabelleProblem problem, Exception e); + void processInterrupted(IsabelleSolver solver, IsabelleProblem problem, Exception e); - void processStopped(IsabelleProblem problem); + void processStopped(IsabelleSolver solver, IsabelleProblem problem); - void processTimeout(IsabelleProblem problem); + void processTimeout(IsabelleSolver solver, IsabelleProblem problem); - void sledgehammerStarted(IsabelleProblem problem); + void sledgehammerStarted(IsabelleSolver solver, IsabelleProblem problem); - void sledgehammerFinished(IsabelleProblem problem); + void sledgehammerFinished(IsabelleSolver solver, IsabelleProblem problem); - void sledgehammerFailed(IsabelleProblem problem, Exception e); + void sledgehammerFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java index 2f7734b3dcc..f04d158db32 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java @@ -39,6 +39,7 @@ public List getContextActions( } List list = new ArrayList<>(); list.add(new TranslationAction(MainWindow.getInstance())); + list.add(new TranslateAllAction(MainWindow.getInstance())); return list; } }; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java new file mode 100644 index 00000000000..8dee50ac958 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java @@ -0,0 +1,95 @@ +package key.isabelletranslation; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.uka.ilkd.key.proof.Goal; +import de.uka.ilkd.key.rule.IBuiltInRuleApp; +import de.uka.ilkd.key.smt.SMTRuleApp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +public class TranslateAllAction extends MainWindowAction { + private static final Logger LOGGER = LoggerFactory.getLogger(TranslateAllAction.class); + + public TranslateAllAction(MainWindow mainWindow) { + super(mainWindow); + setName("Translate all goals to Isabelle"); + } + + @Override + public void actionPerformed(ActionEvent e) { + LOGGER.info("Translating..."); + + generateTranslation(); + } + + + private void generateTranslation() { + KeYMediator mediator = getMediator(); + IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); + + List translations = new ArrayList<>(); + try { + for (Goal goal : mediator.getSelectedProof().openGoals()) { + translations.add(translator.translateProblem(goal)); + } + } catch (IllegalFormulaException e) { + LOGGER.error("Failed to generate translation", e); + return; + } + + writeTranslationFiles(translations.get(0)); + + SledgehammerResult result = null; + Thread thread = new Thread(() -> { + + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); + IsabelleLauncher launcher; + try { + launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); + } catch (IOException e) { + throw new RuntimeException(e); + } + + launcher.addListener(new IsabelleLauncherListenerImpl(settings)); + try { + launcher.try0ThenSledgehammerAllPooled(translations, 30, 1); + } catch (IOException e) { + throw new RuntimeException(e); + } + + }, "IsabelleControlThread"); + thread.start(); + //result = translation.getResult(); + //SledgehammerResult result = translation.sledgehammer(30); + + //TODO needs its own action to enable undo, etc. and naming reworks + if (result != null && result.isSuccessful()) { + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getSuccessfulTactic()); + app.tryToInstantiate(mediator.getSelectedGoal()); + mediator.getSelectedGoal().apply(app); + } + } + + protected static void writeTranslationFiles(IsabelleProblem translation) { + File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); + File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); + try { + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); + Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); + LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); + } catch (IOException e) { + LOGGER.error("Failed to save translation", e); + return; + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index 6d77716d23c..71fa29a29a3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -3,14 +3,8 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; -import de.uka.ilkd.key.gui.smt.SolverListener; import de.uka.ilkd.key.rule.IBuiltInRuleApp; -import de.uka.ilkd.key.settings.DefaultSMTSettings; -import de.uka.ilkd.key.settings.ProofIndependentSettings; -import de.uka.ilkd.key.smt.SMTProblem; import de.uka.ilkd.key.smt.SMTRuleApp; -import de.uka.ilkd.key.smt.SolverLauncher; -import de.unruh.isabelle.control.Isabelle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,7 +61,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleSimpleSolverListener(settings)); + launcher.addListener(new IsabelleLauncherListenerImpl(settings)); try { launcher.try0ThenSledgehammerAllPooled(list, 30, 1); } catch (IOException e) { From 46b2f28bd9ca725ca2c5fa0c19ceb3cdd9019875 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:13:37 +0200 Subject: [PATCH 215/248] Update scala-isabelle version --- keyext.isabelletranslation/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/build.gradle b/keyext.isabelletranslation/build.gradle index aec44b4c809..e5d113a3c1f 100644 --- a/keyext.isabelletranslation/build.gradle +++ b/keyext.isabelletranslation/build.gradle @@ -3,5 +3,5 @@ description "Translation of Sequents to Isabelle" dependencies { implementation project(':key.core') implementation project(':key.ui') - implementation("de.unruh:scala-isabelle_2.13:0.4.2") + implementation("de.unruh:scala-isabelle_2.13:0.4.3-RC1") } From 311aafe6414e95aad27f82f960323ba418d82f0a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:37:09 +0200 Subject: [PATCH 216/248] Better naming in Isabelle dialog --- .../IsabelleLauncherListenerImpl.java | 2 +- .../key/isabelletranslation/IsabelleProblem.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java index b62e131807f..19d200c5aed 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java @@ -49,7 +49,7 @@ private void prepareDialog(Collection problems, final IsabelleL int i = 0; for (IsabelleProblem problem : problems) { - captions[i] = "Problem " + i; + captions[i] = problem.getName(); i++; } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java index 6bf740f366b..766483d8da5 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java @@ -24,21 +24,17 @@ import java.util.concurrent.TimeoutException; public class IsabelleProblem { - private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); private final Goal goal; private SledgehammerResult result = null; private final String preamble; private final String sequentTranslation; - private final Collection listeners = new HashSet<>(); + private final String name; public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { this.goal = goal; this.preamble = preamble; this.sequentTranslation = sequentTranslation; - } - - public void addListener(IsabelleSolverListener listener) { - listeners.add(listener); + this.name = "Goal " + goal.node().serialNr(); } public Goal getGoal() { @@ -53,6 +49,10 @@ public String getPreamble() { return preamble; } + public String getName() { + return name; + } + public SledgehammerResult getResult() { return result; } From a3cba4a9f3b7106610158f647ce6b463f0279e28 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:37:52 +0200 Subject: [PATCH 217/248] Remove unsuitable start method --- .../isabelletranslation/IsabelleSolverInstance.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index 3fa109cfa2b..7b8fb014069 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -1,9 +1,6 @@ package key.isabelletranslation; -import com.sun.java.accessibility.util.TopLevelWindowListener; -import de.uka.ilkd.key.strategy.quantifierHeuristics.Constraint; import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.java.JIsabelle; import de.unruh.isabelle.mlvalue.*; import de.unruh.isabelle.pure.Implicits; import de.unruh.isabelle.pure.Theory; @@ -19,11 +16,9 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; -import java.util.Timer; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -183,14 +178,6 @@ public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings set run(); } - @Override - public void start(IsabelleSolverTimeout timeout, Isabelle isabelleInstance) { - thread = new Thread(this, "IsabelleSolverInstance"); - isabelleResource = IsabelleResourceController.createIsabelleResourceFromInstance(isabelleInstance, isabelleSettings); - this.solverTimeout = timeout; - thread.start(); - } - @Override public String getRawSolverOutput() { return problem.getResult().result().toString(); From 4014b571930fa6fc7af6b51ac8aa009dd6a161f9 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:38:13 +0200 Subject: [PATCH 218/248] Let Launcher write back files, no need for double writing, add interface changes for previous commit --- .../key/isabelletranslation/IsabelleSolver.java | 3 --- .../key/isabelletranslation/TranslationAction.java | 13 +------------ 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java index 3d6f4f553fc..00ac7090acf 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java @@ -37,9 +37,6 @@ enum SolverState{ void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings); - - void start(IsabelleSolverTimeout timeout, Isabelle isabelleInstance); - String getRawSolverOutput(); String getRawSolverInput(); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index 71fa29a29a3..31749717f74 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -44,8 +44,6 @@ private void generateTranslation() { return; } - writeTranslationFiles(translation); - List list = new ArrayList<>(); list.add(translation); @@ -56,7 +54,7 @@ private void generateTranslation() { IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleLauncher launcher; try { - launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); + launcher = new IsabelleLauncher(settings); } catch (IOException e) { throw new RuntimeException(e); } @@ -70,15 +68,6 @@ private void generateTranslation() { }, "IsabelleControlThread"); thread.start(); - result = translation.getResult(); - //SledgehammerResult result = translation.sledgehammer(30); - - //TODO needs its own action to enable undo, etc. and naming reworks - if (result != null && result.isSuccessful()) { - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getSuccessfulTactic()); - app.tryToInstantiate(mediator.getSelectedGoal()); - mediator.getSelectedGoal().apply(app); - } } protected static void writeTranslationFiles(IsabelleProblem translation) { From d211ae59d9c2a18c6129874b12c6c99ba6df9328 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:52:47 +0200 Subject: [PATCH 219/248] IsabelleResourceController now uses ThreadPool for instance creation and can be shutdown during instance creation. Also split into init() function --- .../isabelletranslation/IsabelleLauncher.java | 2 + .../IsabelleResourceController.java | 62 +++++++++++++++---- 2 files changed, 52 insertions(+), 12 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index d32fd1a62b0..8d567e15402 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -67,6 +67,8 @@ public void try0ThenSledgehammerAllPooled(List problems, long t }); Runtime.getRuntime().addShutdownHook(shutdownResources); + resourceController.init(); + if (problems.isEmpty()) { return; } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java index 3959cd8cde3..2489b552125 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -20,7 +20,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; -import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.*; public class IsabelleResourceController { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleResourceController.class); @@ -32,14 +32,36 @@ public class IsabelleResourceController { private Collection waitingSolvers; + private final int numberOfInstances; - public IsabelleResourceController(int numberOfInstances) throws IOException { + private final ExecutorService instanceCreatorService; + + + + public IsabelleResourceController(int numberOfInstances) { settings = IsabelleTranslationSettings.getInstance(); idleInstances = new LinkedBlockingQueue<>(numberOfInstances); waitingSolvers = new HashSet<>(); + this.numberOfInstances = numberOfInstances; + instanceCreatorService = Executors.newFixedThreadPool(numberOfInstances); + } + + public void init() throws IOException { + Collection>> tasks = new LinkedBlockingDeque<>(); for (int i = 0; i < numberOfInstances; i++) { - idleInstances.add(createIsabelleResource()); + tasks.add(() -> { + idleInstances.add(createIsabelleResource()); + return null; + }); + } + + try { + instanceCreatorService.invokeAll(tasks); + } catch (InterruptedException e) { + if (!isShutdown) { + throw new RuntimeException(e); + } } } @@ -51,6 +73,8 @@ public IsabelleResource getIsabelleResource(IsabelleSolver requestingSolver) thr public void shutdownGracefully() { isShutdown = true; + instanceCreatorService.shutdownNow(); + waitingSolvers.forEach((x) -> x.interrupt(IsabelleSolver.ReasonOfInterruption.Exception)); waitingSolvers.clear(); @@ -58,12 +82,6 @@ public void shutdownGracefully() { idleInstances.clear(); } - public static IsabelleResource createIsabelleResourceFromInstance(Isabelle isabelle, IsabelleTranslationSettings settings) { - Theory theory = beginTheory(isabelle, settings); - return new IsabelleResource(isabelle, theory); - } - - public void returnResource(IsabelleSolver returningSolver, IsabelleResource resource) { if (resource.isDestroyed()) { try { @@ -80,9 +98,25 @@ public void returnResource(IsabelleSolver returningSolver, IsabelleResource reso } private IsabelleResource createIsabelleResource() throws IOException { - Isabelle isabelleInstance = startIsabelleInstance(); - Theory theory = beginTheory(isabelleInstance, settings); - return new IsabelleResource(isabelleInstance, theory); + Callable creationTask = () -> { + Isabelle isabelleInstance = startIsabelleInstance(); + Theory theory = beginTheory(isabelleInstance, settings); + return new IsabelleResource(isabelleInstance, theory); + }; + try { + return instanceCreatorService.submit(creationTask).get(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } catch (ExecutionException e) { + if (e.getCause() instanceof IOException) { + throw (IOException) e.getCause(); + } + LOGGER.error("Error during Isabelle setup"); + throw new RuntimeException(e); + } catch (RejectedExecutionException e) { + //IsabelleResourceController is shutdown + return null; + } } private Isabelle startIsabelleInstance() throws IOException { @@ -109,9 +143,13 @@ private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + + TheoryHeader header = header_read.apply(settings.getHeader(), Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = settings.getTranslationPath(); + + return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); From 74f3f1867dcd988a670171cd0aafdeb3f6a3f396 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:53:26 +0200 Subject: [PATCH 220/248] Allow IsabelleLauncher to be shutdown --- .../isabelletranslation/IsabelleLauncher.java | 63 +++++++++---------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index 8d567e15402..fca97b884b7 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -2,29 +2,14 @@ import org.key_project.util.collection.Pair; import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.java.JIsabelle; -import de.unruh.isabelle.mlvalue.ListConverter; -import de.unruh.isabelle.mlvalue.MLFunction2; -import de.unruh.isabelle.mlvalue.MLFunction3; -import de.unruh.isabelle.mlvalue.MLValue; -import de.unruh.isabelle.pure.Implicits; -import de.unruh.isabelle.pure.Position; import de.unruh.isabelle.pure.Theory; -import de.unruh.isabelle.pure.TheoryHeader; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Timer; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingDeque; +import java.util.*; +import java.util.concurrent.*; public class IsabelleLauncher { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); @@ -32,36 +17,28 @@ public class IsabelleLauncher { private final IsabelleTranslationSettings settings; private IsabelleLauncherListener listener; + private Thread shutdownResources; + + + private final List runningSolvers = Collections.synchronizedList(new ArrayList<>()); + + + private final LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); + public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { this.settings = settings; } - private Theory beginTheory(Path source, Isabelle isabelle) { - MLFunction3, Theory> begin_theory = - MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); - MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - - TheoryHeader header = header_read.apply("theory Translation imports Main KeYTranslations.TranslationPreamble begin", Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) - .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); - Path topDir = source.getParent(); - return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) - .retrieveNow(Implicits.theoryConverter(), isabelle); - } - public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int instanceCount) throws IOException { listener.launcherStarted(this, problems); ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); Collection>> tasks = new LinkedBlockingDeque<>(); - LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); - Thread shutdownResources = new Thread(() -> { + shutdownResources = new Thread(() -> { executorService.shutdown(); resourceController.shutdownGracefully(); }); @@ -90,7 +67,9 @@ public void try0ThenSledgehammerAllPooled(List problems, long t while ((solver = solverQueue.poll()) != null) { //IsabelleSolver.IsabelleSolverTimeout solverTimeout = new IsabelleSolver.IsabelleSolverTimeout(solver); //timer.schedule(null, solver.getTimeout()); + runningSolvers.add(solver); solver.start(null, settings); + runningSolvers.remove(solver); } return null; }); @@ -102,13 +81,27 @@ public void try0ThenSledgehammerAllPooled(List problems, long t executorService.invokeAll(tasks); } catch (InterruptedException e) { throw new RuntimeException(e); + } catch (RejectedExecutionException e) { + //Launcher has been shutdown before running instances + //Nothing to do here, intended behavior } finally { + shutdown(); + } + } + + private void shutdown() { + Runtime.getRuntime().removeShutdownHook(shutdownResources); + if (shutdownResources.getState() == Thread.State.NEW) { shutdownResources.start(); - Runtime.getRuntime().removeShutdownHook(shutdownResources); } } public void addListener(IsabelleLauncherListener listener) { this.listener = listener; } + + public void stopAll(IsabelleSolver.ReasonOfInterruption reasonOfInterruption) { + shutdown(); + runningSolvers.forEach((solver) -> solver.interrupt(reasonOfInterruption)); + } } From 5f99dc01538858fd209e3659cf2e48485846e2e2 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 4 Sep 2024 13:53:37 +0200 Subject: [PATCH 221/248] Implement stop button in Isabelle dialog --- .../key/isabelletranslation/IsabelleLauncherListener.java | 4 ---- .../key/isabelletranslation/IsabelleLauncherListenerImpl.java | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java index fcc686c541d..d67cd42fd74 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java @@ -1,9 +1,5 @@ package key.isabelletranslation; -import key.isabelletranslation.gui.IsabelleProgressDialog; -import key.isabelletranslation.gui.IsabelleProgressModel; - -import javax.swing.*; import java.util.Collection; public interface IsabelleLauncherListener { diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java index 19d200c5aed..3feb052ace7 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java @@ -18,7 +18,7 @@ public void launcherStarted(IsabelleLauncher launcher, Collection Date: Wed, 4 Sep 2024 16:08:23 +0200 Subject: [PATCH 222/248] Make final fields final in IsabelleResourceController --- .../isabelletranslation/IsabelleResourceController.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java index 2489b552125..13d1ea8d8cb 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -24,13 +24,13 @@ public class IsabelleResourceController { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleResourceController.class); - private LinkedBlockingQueue idleInstances; + private final LinkedBlockingQueue idleInstances; - private IsabelleTranslationSettings settings; + private final IsabelleTranslationSettings settings; private boolean isShutdown = false; - private Collection waitingSolvers; + private final Collection waitingSolvers; private final int numberOfInstances; @@ -83,6 +83,8 @@ public void shutdownGracefully() { } public void returnResource(IsabelleSolver returningSolver, IsabelleResource resource) { + assert resource != null; + if (resource.isDestroyed()) { try { resource = createIsabelleResource(); From fda17aee0fd1cb26e9f11b749f12adbde9612541 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 5 Sep 2024 00:22:49 +0200 Subject: [PATCH 223/248] first version of reporting solver status in dialog --- .../isabelletranslation/IsabelleLauncher.java | 58 ++++---- .../IsabelleLauncherListener.java | 6 +- .../IsabelleLauncherListenerImpl.java | 129 +++++++++++++++--- .../IsabelleResourceController.java | 14 +- .../isabelletranslation/IsabelleSolver.java | 4 +- .../IsabelleSolverInstance.java | 23 +++- 6 files changed, 170 insertions(+), 64 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index fca97b884b7..7571523bbc2 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -1,5 +1,6 @@ package key.isabelletranslation; +import org.jetbrains.annotations.NotNull; import org.key_project.util.collection.Pair; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.pure.Theory; @@ -24,6 +25,7 @@ public class IsabelleLauncher { private final LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); + private final Collection solverSet = new HashSet<>(); public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { @@ -31,20 +33,27 @@ public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IO } public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int instanceCount) throws IOException { - listener.launcherStarted(this, problems); - ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); - Collection>> tasks = new LinkedBlockingDeque<>(); - - IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); + ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); + shutdownResources = new Thread(() -> { executorService.shutdown(); resourceController.shutdownGracefully(); }); Runtime.getRuntime().addShutdownHook(shutdownResources); + for (int i = 0; i < problems.size(); i++) { + IsabelleSolver solver = new IsabelleSolverInstance(problems.get(i), List.of(new IsabelleSolverListener[0]), i, resourceController); + solver.setTimeout(timeoutSeconds); + solverQueue.add(solver); + solverSet.add(solver); + } + + listener.launcherStarted(this, solverSet); + resourceController.init(); + listener.launcherPreparationFinished(this, solverSet); if (problems.isEmpty()) { return; @@ -52,28 +61,8 @@ public void try0ThenSledgehammerAllPooled(List problems, long t //Ensure the preamble theory is present TranslationAction.writeTranslationFiles(problems.get(0)); - problems.forEach((problem) -> { - IsabelleSolver solver = new IsabelleSolverInstance(problem, List.of(new IsabelleSolverListener[0]), resourceController); - solver.setTimeout(timeoutSeconds); - solverQueue.add(solver); - }); - Timer timer = new Timer(true); - - for (int i = 0; i < instanceCount; i++) { - tasks.add(() -> { - IsabelleSolver solver; - Pair resources; - while ((solver = solverQueue.poll()) != null) { - //IsabelleSolver.IsabelleSolverTimeout solverTimeout = new IsabelleSolver.IsabelleSolverTimeout(solver); - //timer.schedule(null, solver.getTimeout()); - runningSolvers.add(solver); - solver.start(null, settings); - runningSolvers.remove(solver); - } - return null; - }); - } + Collection>> tasks = launchSolverInstances(instanceCount); LOGGER.info("Setup complete, starting {} problems...", problems.size()); @@ -89,6 +78,23 @@ public void try0ThenSledgehammerAllPooled(List problems, long t } } + private @NotNull Collection>> launchSolverInstances(int instanceCount) { + Collection>> tasks = new LinkedBlockingDeque<>(); + + for (int i = 0; i < instanceCount; i++) { + tasks.add(() -> { + IsabelleSolver solver; + while ((solver = solverQueue.poll()) != null) { + runningSolvers.add(solver); + solver.start(null, settings); + runningSolvers.remove(solver); + } + return null; + }); + } + return tasks; + } + private void shutdown() { Runtime.getRuntime().removeShutdownHook(shutdownResources); if (shutdownResources.getState() == Thread.State.NEW) { diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java index d67cd42fd74..3e6b6dd181e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java @@ -3,7 +3,9 @@ import java.util.Collection; public interface IsabelleLauncherListener { - void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances); + void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances); - void launcherStarted(IsabelleLauncher launcher, Collection problems); + void launcherStarted(IsabelleLauncher launcher, Collection solvers); + + void launcherPreparationFinished(IsabelleLauncher launcher, Collection solvers); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java index 3feb052ace7..01aa3dcf1d0 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java @@ -1,20 +1,39 @@ package key.isabelletranslation; +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; import key.isabelletranslation.gui.IsabelleProgressDialog; import key.isabelletranslation.gui.IsabelleProgressModel; import javax.swing.*; +import java.util.Timer; import java.util.Collection; +import java.util.TimerTask; public class IsabelleLauncherListenerImpl implements IsabelleLauncherListener { + private final Timer timer = new Timer(); + @Override - public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { + public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { + + } + @Override + public void launcherStarted(IsabelleLauncher launcher, Collection solvers) { + prepareDialog(solvers, launcher); + + setProgressText(-1); + timer.schedule(new TimerTask() { + @Override + public void run() { + refreshDialog(); + } + }, 0, 10); } @Override - public void launcherStarted(IsabelleLauncher launcher, Collection problems) { - prepareDialog(problems, launcher); + public void launcherPreparationFinished(IsabelleLauncher launcher, Collection solvers) { + setProgressText(0); } protected void stopEvent(IsabelleLauncher launcher) { @@ -22,7 +41,38 @@ protected void stopEvent(IsabelleLauncher launcher) { } protected void applyEvent(IsabelleLauncher launcher) { + launcher.stopAll(IsabelleSolver.ReasonOfInterruption.NoInterruption); + applyResults(); + progressDialog.dispose(); + } + private void applyResults() { + KeYMediator mediator = MainWindow.getInstance().getMediator(); + // ensure that the goal closing does not lag the UI + mediator.stopInterface(true); + try { + //TODO create own close action + } finally { + mediator.startInterface(true); + // switch to new open goal + mediator.getSelectionModel().defaultSelection(); + } + } + + private void setProgressText(int value) { + JProgressBar bar = progressDialog.getProgressBar(); + if (bar.getMaximum() == 1) { + if (value == -1) { + bar.setString("Preparing..."); + bar.setStringPainted(true); + return; + } + bar.setString(value == 0 ? "Processing..." : "Finished."); + bar.setStringPainted(true); + } else { + bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); + bar.setStringPainted(true); + } } protected void discardEvent(IsabelleLauncher launcher) { @@ -36,38 +86,86 @@ public IsabelleLauncherListenerImpl(IsabelleTranslationSettings settings) { private static final int RESOLUTION = 1000; - private Collection problems; + private Collection solvers; private IsabelleProgressModel progressModel; private boolean[] problemProcessed; private IsabelleProgressDialog progressDialog; - private void prepareDialog(Collection problems, final IsabelleLauncher launcher) { - this.problems = problems; + private void prepareDialog(Collection solvers, final IsabelleLauncher launcher) { + this.solvers = solvers; progressModel = new IsabelleProgressModel(); - String[] captions = new String[problems.size()]; + String[] captions = new String[solvers.size()]; int i = 0; - for (IsabelleProblem problem : problems) { - captions[i] = problem.getName(); + for (IsabelleSolver solver : solvers) { + captions[i] = solver.getProblem().getName(); i++; } progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); - problemProcessed = new boolean[problems.size()]; - progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(problems.size())); + problemProcessed = new boolean[solvers.size()]; + progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); + + + progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, + RESOLUTION, solvers.size(), new String[] {}, "", "Isabelle"); + - for (IsabelleProblem problem : problems) { + SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); + } + private void refreshDialog() { + for (IsabelleSolver solver : solvers) { + refreshProgressOfSolver(solver); } + } + private boolean refreshProgressOfSolver(IsabelleSolver solver) { + IsabelleSolver.SolverState state = solver.getState(); + return switch (state) { + case Preparing -> { + preparing(solver); + yield true; + } + case Parsing -> { + parsing(solver); + yield true; + } + case Running -> { + running(solver); + yield true; + } + case Stopped -> { + stopped(solver); + yield false; + } + case Waiting -> { + waiting(solver); + yield true; + } + }; - progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, - RESOLUTION, problems.size(), new String[] {}, "", "Isabelle"); + } + private void stopped(IsabelleSolver solver) { + progressModel.setText("Stopped...", 0, solver.getSolverIndex()); + } - SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); + private void running(IsabelleSolver solver) { + progressModel.setText("Running...", 0, solver.getSolverIndex()); + } + + private void parsing(IsabelleSolver solver) { + progressModel.setText("Parsing...", 0, solver.getSolverIndex()); + } + private void waiting(IsabelleSolver solver) { + progressModel.setText("Waiting...", 0, solver.getSolverIndex()); + } + + private void preparing(IsabelleSolver solver) { + progressModel.setText("Preparing...", 0, solver.getSolverIndex()); } private class IsabelleProgressDialogListenerImpl implements IsabelleProgressDialog.IsabelleProgressDialogListener { @@ -90,7 +188,6 @@ public void infoButtonClicked(int column, int row) { @Override public void stopButtonClicked() { - stopEvent(launcher); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java index 13d1ea8d8cb..e0f58688eb3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -48,20 +48,8 @@ public IsabelleResourceController(int numberOfInstances) { } public void init() throws IOException { - Collection>> tasks = new LinkedBlockingDeque<>(); for (int i = 0; i < numberOfInstances; i++) { - tasks.add(() -> { - idleInstances.add(createIsabelleResource()); - return null; - }); - } - - try { - instanceCreatorService.invokeAll(tasks); - } catch (InterruptedException e) { - if (!isShutdown) { - throw new RuntimeException(e); - } + idleInstances.add(createIsabelleResource()); } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java index 00ac7090acf..8df5180877a 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java @@ -5,12 +5,14 @@ import java.util.TimerTask; public interface IsabelleSolver { + int getSolverIndex(); + enum ReasonOfInterruption { User, Timeout, Exception, NoInterruption } enum SolverState{ - Waiting, StartingIsabelle, Building, Parsing, Running, Stopped + Waiting, Preparing, Parsing, Running, Stopped } String name(); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index 7b8fb014069..2e60a4179e0 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -23,6 +23,7 @@ import java.util.concurrent.TimeoutException; public class IsabelleSolverInstance implements IsabelleSolver, Runnable { + private final int solverIndex; private SledgehammerResult result; private IsabelleResourceController.IsabelleResource isabelleResource; @@ -79,13 +80,19 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); private Collection listeners; - public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, IsabelleResourceController resourceController) { + public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController) { this.problem = problem; + this.solverIndex = solverIndex; this.listeners = new HashSet<>(); this.listeners.addAll(listeners); this.resourceController = resourceController; } + @Override + public int getSolverIndex() { + return solverIndex; + } + @Override public String name() { return "Isabelle"; @@ -196,9 +203,7 @@ public SledgehammerResult getFinalResult() { @Override public void run() { //Ensure there is an active IsabelleInstance - setSolverState(SolverState.StartingIsabelle); - notifyProcessStarted(); - + setSolverState(SolverState.Preparing); try { isabelleResource = resourceController.getIsabelleResource(this); } catch (InterruptedException e) { @@ -206,6 +211,8 @@ public void run() { notifyProcessError(e); } + + notifyProcessStarted(); Isabelle isabelle = isabelleResource.instance(); Theory thy0 = isabelleResource.theory(); @@ -226,7 +233,8 @@ in addtext (Symbol.explode text) transitions end""", isabelle, ToplevelState toplevel = ToplevelState.apply(isabelle); - LOGGER.debug("Parsing theory..."); + LOGGER.info("Parsing theory for: " + problem.getName()); + setSolverState(SolverState.Parsing); notifyParsingStarted(); try { java.util.List> transitionsAndTexts = new ArrayList<>(); @@ -287,6 +295,7 @@ fun go_run (state, thy) = scala.collection.immutable.List emptyList = listBuilder.result(); SledgehammerResult result = null; + setSolverState(SolverState.Running); notifySledgehammerStarted(); try { Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), @@ -324,11 +333,13 @@ fun go_run (state, thy) = } getProblem().setResult(this.result); resourceController.returnResource(this, isabelleResource); + + setSolverState(SolverState.Stopped); notifySledgehammerFinished(); notifyProcessFinished(); - LOGGER.debug("Sledgehammer result: " + this.result); + LOGGER.info("Sledgehammer result: " + this.result); } From 861a3cd0d84c3267fb9bef5cbe440d5ed09528af Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 5 Sep 2024 00:44:06 +0200 Subject: [PATCH 224/248] report result of solvers instead of simply state --- .../IsabelleLauncherListenerImpl.java | 74 +++++++++++++++++-- .../isabelletranslation/IsabelleSolver.java | 2 + .../IsabelleSolverInstance.java | 7 +- .../TranslationAction.java | 5 +- 4 files changed, 78 insertions(+), 10 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java index 01aa3dcf1d0..be1ec7f4b7b 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java @@ -2,16 +2,26 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.colors.ColorSettings; import key.isabelletranslation.gui.IsabelleProgressDialog; import key.isabelletranslation.gui.IsabelleProgressModel; import javax.swing.*; +import java.awt.*; import java.util.Timer; import java.util.Collection; import java.util.TimerTask; public class IsabelleLauncherListenerImpl implements IsabelleLauncherListener { private final Timer timer = new Timer(); + private int finishedCounter = 0; + + + private final static ColorSettings.ColorProperty RED = + ColorSettings.define("[solverListener]red", "", new Color(180, 43, 43)); + + private final static ColorSettings.ColorProperty GREEN = + ColorSettings.define("[solverListener]green", "", new Color(43, 180, 43)); @Override public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { @@ -59,6 +69,62 @@ private void applyResults() { } } + private void stopped(IsabelleSolver solver) { + + int x = 0; + int y = solver.getSolverIndex(); + + if (!problemProcessed[x][y]) { + finishedCounter++; + progressDialog.setProgress(finishedCounter); + JProgressBar bar = progressDialog.getProgressBar(); + bar.setValue(finishedCounter); + setProgressText(finishedCounter); + problemProcessed[x][y] = true; + } + + if (solver.wasInterrupted()) { + interrupted(solver); + } else if (solver.getFinalResult().isSuccessful()) { + successfullyStopped(solver, x, y); + } else { + unknownStopped(x, y); + } + } + + private void interrupted(IsabelleSolver solver) { + IsabelleSolver.ReasonOfInterruption reason = solver.getReasonOfInterruption(); + int x = 0; + int y = solver.getSolverIndex(); + switch (reason) { + case Exception -> { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(RED.get(), x, y); + progressModel.setText("Exception!", x, y); + } + case NoInterruption -> throw new RuntimeException("This position should not be reachable!"); + case Timeout -> { + progressModel.setProgress(0, x, y); + progressModel.setText("Timeout.", x, y); + } + case User -> progressModel.setText("Interrupted by user.", x, y); + } + } + + private void successfullyStopped(IsabelleSolver solver, int x, int y) { + //TODO add time information + + progressModel.setProgress(0, x, y); + progressModel.setTextColor(GREEN.get(), x, y); + progressModel.setText("Valid", x, y); + } + + private void unknownStopped(int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(Color.BLUE, x, y); + progressModel.setText("Unknown.", x, y); + } + private void setProgressText(int value) { JProgressBar bar = progressDialog.getProgressBar(); if (bar.getMaximum() == 1) { @@ -88,7 +154,7 @@ public IsabelleLauncherListenerImpl(IsabelleTranslationSettings settings) { private Collection solvers; private IsabelleProgressModel progressModel; - private boolean[] problemProcessed; + private boolean[][] problemProcessed; private IsabelleProgressDialog progressDialog; private void prepareDialog(Collection solvers, final IsabelleLauncher launcher) { @@ -104,7 +170,7 @@ private void prepareDialog(Collection solvers, final IsabelleLau } progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); - problemProcessed = new boolean[solvers.size()]; + problemProcessed = new boolean[1][solvers.size()]; progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); @@ -148,10 +214,6 @@ private boolean refreshProgressOfSolver(IsabelleSolver solver) { } - private void stopped(IsabelleSolver solver) { - progressModel.setText("Stopped...", 0, solver.getSolverIndex()); - } - private void running(IsabelleSolver solver) { progressModel.setText("Running...", 0, solver.getSolverIndex()); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java index 8df5180877a..dde8013643f 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java @@ -7,6 +7,8 @@ public interface IsabelleSolver { int getSolverIndex(); + ReasonOfInterruption getReasonOfInterruption(); + enum ReasonOfInterruption { User, Timeout, Exception, NoInterruption } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index 2e60a4179e0..f02dd37d834 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -74,7 +74,7 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { */ private long timeout = -1; - private IsabelleResourceController resourceController; + private final IsabelleResourceController resourceController; private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); @@ -93,6 +93,11 @@ public int getSolverIndex() { return solverIndex; } + @Override + public ReasonOfInterruption getReasonOfInterruption() { + return reasonOfInterruption; + } + @Override public String name() { return "Isabelle"; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index 31749717f74..bd52f356b1e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -48,8 +48,7 @@ private void generateTranslation() { list.add(translation); - SledgehammerResult result = null; - Thread thread = new Thread(() -> { + Thread thread = new Thread(() -> { IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleLauncher launcher; @@ -66,7 +65,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - }, "IsabelleControlThread"); + }, "IsabelleLauncherThread"); thread.start(); } From c30fbc5ac8416a2d8c9a999695a92eb560c9732e Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 5 Sep 2024 01:28:35 +0200 Subject: [PATCH 225/248] tracking down some uncaught exceptions when interrupting Isabelle solvers manually --- .../isabelletranslation/IsabelleLauncher.java | 5 +++ ...abelleLauncherProgressDialogMediator.java} | 18 +++++------ .../IsabelleResourceController.java | 31 ++++++++++++++++--- .../IsabelleSolverInstance.java | 10 +++--- .../TranslateAllAction.java | 2 +- .../TranslationAction.java | 4 +-- 6 files changed, 47 insertions(+), 23 deletions(-) rename keyext.isabelletranslation/src/main/java/key/isabelletranslation/{IsabelleLauncherListenerImpl.java => IsabelleLauncherProgressDialogMediator.java} (94%) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index 7571523bbc2..b79b2388e58 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -109,5 +109,10 @@ public void addListener(IsabelleLauncherListener listener) { public void stopAll(IsabelleSolver.ReasonOfInterruption reasonOfInterruption) { shutdown(); runningSolvers.forEach((solver) -> solver.interrupt(reasonOfInterruption)); + solverQueue.forEach((solver) -> solver.interrupt(reasonOfInterruption)); + + runningSolvers.clear(); + solverQueue.clear(); + listener.launcherStopped(this, solverSet); } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java similarity index 94% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java rename to keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index be1ec7f4b7b..a713cc62408 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListenerImpl.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -12,7 +12,7 @@ import java.util.Collection; import java.util.TimerTask; -public class IsabelleLauncherListenerImpl implements IsabelleLauncherListener { +public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { private final Timer timer = new Timer(); private int finishedCounter = 0; @@ -127,25 +127,23 @@ private void unknownStopped(int x, int y) { private void setProgressText(int value) { JProgressBar bar = progressDialog.getProgressBar(); - if (bar.getMaximum() == 1) { if (value == -1) { bar.setString("Preparing..."); bar.setStringPainted(true); - return; + } else if (value == bar.getMaximum()){ + bar.setString("Finished."); + bar.setStringPainted(true); + } else { + bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); + bar.setStringPainted(true); } - bar.setString(value == 0 ? "Processing..." : "Finished."); - bar.setStringPainted(true); - } else { - bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); - bar.setStringPainted(true); - } } protected void discardEvent(IsabelleLauncher launcher) { } - public IsabelleLauncherListenerImpl(IsabelleTranslationSettings settings) { + public IsabelleLauncherProgressDialogMediator(IsabelleTranslationSettings settings) { } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java index e0f58688eb3..0e02fe9d11b 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java @@ -49,13 +49,18 @@ public IsabelleResourceController(int numberOfInstances) { public void init() throws IOException { for (int i = 0; i < numberOfInstances; i++) { - idleInstances.add(createIsabelleResource()); + IsabelleResource newResource = createIsabelleResource(); + if (!isShutdown() && newResource != null) { + idleInstances.add(newResource); + } } } public IsabelleResource getIsabelleResource(IsabelleSolver requestingSolver) throws InterruptedException { waitingSolvers.add(requestingSolver); - return idleInstances.take(); + IsabelleResource freeResource = idleInstances.take(); + waitingSolvers.remove(requestingSolver); + return freeResource; } public void shutdownGracefully() { @@ -73,6 +78,14 @@ public void shutdownGracefully() { public void returnResource(IsabelleSolver returningSolver, IsabelleResource resource) { assert resource != null; + if (isShutdown()) { + if (!resource.isDestroyed()) { + //TODO some kind of race condition happens here + resource.destroy(); + } + return; + } + if (resource.isDestroyed()) { try { resource = createIsabelleResource(); @@ -81,12 +94,16 @@ public void returnResource(IsabelleSolver returningSolver, IsabelleResource reso shutdownGracefully(); LOGGER.error(e.getMessage()); } + } else { + resource.interrupt(); } - resource.interrupt(); - waitingSolvers.remove(returningSolver); idleInstances.offer(resource); } + public boolean isShutdown() { + return isShutdown; + } + private IsabelleResource createIsabelleResource() throws IOException { Callable creationTask = () -> { Isabelle isabelleInstance = startIsabelleInstance(); @@ -96,11 +113,15 @@ private IsabelleResource createIsabelleResource() throws IOException { try { return instanceCreatorService.submit(creationTask).get(); } catch (InterruptedException e) { + shutdownGracefully(); throw new RuntimeException(e); } catch (ExecutionException e) { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } + if (isShutdown()) { + return null; + } LOGGER.error("Error during Isabelle setup"); throw new RuntimeException(e); } catch (RejectedExecutionException e) { @@ -150,7 +171,7 @@ public boolean isDestroyed() { return instance.isDestroyed(); } - public void destroy() { + void destroy() { instance.destroy(); } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index f02dd37d834..45392dc50d3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -129,13 +129,13 @@ public void interrupt(ReasonOfInterruption reason) { thread.interrupt(); } if (isabelleResource != null) { - shutdownAndReturnResource(); + returnResource(); } } - private void shutdownAndReturnResource() { - isabelleResource.interrupt(); + private void returnResource() { resourceController.returnResource(this, isabelleResource); + isabelleResource = null; } private void setSolverState(SolverState solverState) { @@ -316,7 +316,9 @@ fun go_run (state, thy) = this.result = result; notifyProcessTimeout(); } catch (InterruptedException exception) { - interrupt(ReasonOfInterruption.Exception); + if (reasonOfInterruption == ReasonOfInterruption.NoInterruption) { + interrupt(ReasonOfInterruption.Exception); + } result = new SledgehammerResult(Option.apply(null)); this.result = result; notifySledgehammerError(exception); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java index 8dee50ac958..c8a300c0f8e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java @@ -59,7 +59,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherListenerImpl(settings)); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings)); try { launcher.try0ThenSledgehammerAllPooled(translations, 30, 1); } catch (IOException e) { diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java index bd52f356b1e..92330b2da3d 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java @@ -3,8 +3,6 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; -import de.uka.ilkd.key.rule.IBuiltInRuleApp; -import de.uka.ilkd.key.smt.SMTRuleApp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,7 +56,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherListenerImpl(settings)); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings)); try { launcher.try0ThenSledgehammerAllPooled(list, 30, 1); } catch (IOException e) { From 5b797f3cd22b2b2cde491ea3313447eeaafe0b9e Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 5 Sep 2024 13:48:13 +0200 Subject: [PATCH 226/248] Change interrupt behaviour for Isabelle solvers --- .../isabelletranslation/IsabelleLauncher.java | 2 +- .../IsabelleSolverInstance.java | 186 ++++++++++-------- 2 files changed, 106 insertions(+), 82 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java index b79b2388e58..258e1793ca7 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java @@ -38,7 +38,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); shutdownResources = new Thread(() -> { - executorService.shutdown(); + executorService.shutdownNow(); resourceController.shutdownGracefully(); }); Runtime.getRuntime().addShutdownHook(shutdownResources); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java index 45392dc50d3..a2bb99003c3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java @@ -1,6 +1,7 @@ package key.isabelletranslation; import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.control.IsabelleMLException; import de.unruh.isabelle.mlvalue.*; import de.unruh.isabelle.pure.Implicits; import de.unruh.isabelle.pure.Theory; @@ -171,7 +172,7 @@ public SolverState getState() { @Override public boolean wasInterrupted() { - return reasonOfInterruption != ReasonOfInterruption.NoInterruption; + return Thread.currentThread().isInterrupted(); } @Override @@ -181,13 +182,17 @@ public boolean isRunning() { @Override public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings) { - thread = new Thread(this, "IsabelleSolverInstance"); + thread = new Thread(this, "IsabelleSolverInstance: " + getProblem().getName()); this.solverTimeout = timeout; isabelleSettings = settings; //TODO probably want asynchronous behavior - //Thread.start(); - run(); + thread.start(); + try { + thread.join(); + } catch (InterruptedException e) { + thread.interrupt(); + } } @Override @@ -212,60 +217,117 @@ public void run() { try { isabelleResource = resourceController.getIsabelleResource(this); } catch (InterruptedException e) { - this.interrupt(ReasonOfInterruption.Exception); notifyProcessError(e); + return; } notifyProcessStarted(); Isabelle isabelle = isabelleResource.instance(); - Theory thy0 = isabelleResource.theory(); - - MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); - - MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); - ToplevelState toplevel = ToplevelState.apply(isabelle); LOGGER.info("Parsing theory for: " + problem.getName()); setSolverState(SolverState.Parsing); notifyParsingStarted(); try { - java.util.List> transitionsAndTexts = new ArrayList<>(); - parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle) - .foreach(transitionsAndTexts::add); - - for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") - toplevel = command_exception.apply(Boolean.TRUE, transitionAndText._1(), toplevel, isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) - .retrieveNow(Implicits.toplevelStateConverter(), isabelle); - } - } catch (Exception e) { - isabelleResource.destroy(); + toplevel = parseTheory(toplevel, isabelleResource); + } catch (InterruptedException e) { + setSolverState(SolverState.Stopped); + notifyParsingError(e); + returnResource(); + return; + } catch (IsabelleMLException e) { + setSolverState(SolverState.Stopped); + returnResource(); notifyParsingError(e); return; } notifyParsingFinished(); LOGGER.debug("Finished Parsing"); + setSolverState(SolverState.Running); + notifySledgehammerStarted(); + + try { + this.result = sledgehammer(isabelleResource, toplevel); + notifySledgehammerFinished(); + } catch (TimeoutException e) { + setReasonOfInterruption(ReasonOfInterruption.Timeout); + this.result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + notifySledgehammerFinished(); + } catch (InterruptedException e) { + notifySledgehammerError(e); + } catch (IsabelleMLException e) { + setReasonOfInterruption(ReasonOfInterruption.Exception); + notifySledgehammerError(e); + } finally { + returnResource(); + getProblem().setResult(this.result); + setSolverState(SolverState.Stopped); + notifyProcessFinished(); + LOGGER.info("Sledgehammer result: {}", this.result); + } + } + + private ToplevelState parseTheory(ToplevelState toplevel, IsabelleResourceController.IsabelleResource resource) throws InterruptedException, IsabelleMLException { + ToplevelState result = toplevel; + Isabelle isabelle = resource.instance(); + Theory thy0 = resource.theory(); + + if (wasInterrupted()) { + throw new InterruptedException(); + } + MLFunction2>> parse_text = MLValue.compileFunction(""" + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + + if (wasInterrupted()) { + throw new InterruptedException(); + } + MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + + java.util.List> transitionsAndTexts = new ArrayList<>(); + Future>> transitionList = parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieve(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle); + try { + Await.result(transitionList, Duration.create(1, TimeUnit.HOURS)) + .foreach(transitionsAndTexts::add); + } catch (TimeoutException e) { + //Should not be reached + throw new RuntimeException(e); + } + + for (Tuple2 transitionAndText : transitionsAndTexts) { + //println(s"""Transition: "${text.strip}"""") + if (reasonOfInterruption != ReasonOfInterruption.NoInterruption) { + throw new InterruptedException(); + } + result = command_exception.apply(Boolean.TRUE, transitionAndText._1(), result, isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + } + return result; + } + + + private SledgehammerResult sledgehammer(IsabelleResourceController.IsabelleResource resource, ToplevelState toplevel) + throws TimeoutException, InterruptedException, IsabelleMLException { + Isabelle isabelle = resource.instance(); + Theory thy0 = resource.theory(); + String sledgehammer = thy0.importMLStructureNow("Sledgehammer", isabelle); String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); - MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = MLValue.compileFunction( """ @@ -296,57 +358,19 @@ fun go_run (state, thy) = new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); + Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List emptyList = listBuilder.result(); SledgehammerResult result = null; - setSolverState(SolverState.Running); - notifySledgehammerStarted(); - try { - Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); - result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); - this.result = result; - } catch (TimeoutException exception) { - interrupt(ReasonOfInterruption.Timeout); - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } catch (InterruptedException exception) { - if (reasonOfInterruption == ReasonOfInterruption.NoInterruption) { - interrupt(ReasonOfInterruption.Exception); - } - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } catch (Exception exception) { - interrupt(ReasonOfInterruption.Exception); - if (exception.getMessage().contains("Timeout after")) { - result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); - this.result = result; - notifyProcessTimeout(); - } else { - LOGGER.error("Exception during Sledgehammer {}", exception.getMessage()); - exception.printStackTrace(); - result = new SledgehammerResult(Option.apply(null)); - this.result = result; - notifySledgehammerError(exception); - notifyProcessError(exception); - } - } - getProblem().setResult(this.result); - resourceController.returnResource(this, isabelleResource); - - setSolverState(SolverState.Stopped); - notifySledgehammerFinished(); - - notifyProcessFinished(); - - LOGGER.info("Sledgehammer result: " + this.result); + Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); + result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); + this.result = result; + return this.result; } From 061c43b586f32b910db1a955c9319a283ca56762 Mon Sep 17 00:00:00 2001 From: BookWood Date: Thu, 19 Sep 2024 13:26:53 +0200 Subject: [PATCH 227/248] rename package --- .../isabelletranslation/BSumHandler.java | 2 +- .../isabelletranslation/BooleanOpHandler.java | 2 +- .../DefinedSymbolsHandler.java | 2 +- .../isabelletranslation/FieldHandler.java | 2 +- .../IllegalFormulaException.java | 2 +- .../InfiniteUnionHandler.java | 2 +- .../InstanceOperatorHandler.java | 2 +- .../isabelletranslation/IntegerOpHandler.java | 2 +- .../isabelletranslation/IsabelleHandler.java | 2 +- .../IsabelleHandlerServices.java | 2 +- .../isabelletranslation/IsabelleLauncher.java | 5 +--- .../IsabelleLauncherListener.java | 2 +- ...sabelleLauncherProgressDialogMediator.java | 8 +++---- .../IsabelleMasterHandler.java | 2 +- .../isabelletranslation/IsabelleProblem.java | 23 +------------------ .../IsabelleResourceController.java | 2 +- .../IsabelleSettingsProvider.java | 2 +- .../isabelletranslation/IsabelleSolver.java | 4 +--- .../IsabelleSolverInstance.java | 4 ++-- .../IsabelleSolverListener.java | 2 +- .../IsabelleTranslationExtension.java | 2 +- .../IsabelleTranslationSettings.java | 2 +- .../IsabelleTranslator.java | 2 +- .../LogicalVariableHandler.java | 2 +- .../NumberConstantsHandler.java | 2 +- .../ObserverFunctionHandler.java | 2 +- .../PolymorphicHandler.java | 2 +- .../QuantifierHandler.java | 2 +- .../isabelletranslation/SeqDefHandler.java | 2 +- .../SledgehammerResult.java | 2 +- .../SortDependingFunctionHandler.java | 2 +- .../TranslateAllAction.java | 2 +- .../TranslationAction.java | 2 +- .../UninterpretedSymbolsHandler.java | 2 +- .../gui/IsabelleProgressDialog.java | 4 ++-- .../gui/IsabelleProgressModel.java | 2 +- ...ilkd.key.gui.extension.api.KeYGuiExtension | 2 +- .../isabelletranslation/defaultHandlers.txt | 15 ------------ .../IntegerOpHandler.preamble.xml | 0 .../key_project}/isabelletranslation/ROOT | 0 .../UninterpretedSymbolsHandler.preamble.xml | 0 .../isabelletranslation/defaultHandlers.txt | 15 ++++++++++++ .../key_project}/isabelletranslation/root.tex | 0 43 files changed, 57 insertions(+), 83 deletions(-) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/BSumHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/BooleanOpHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/DefinedSymbolsHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/FieldHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IllegalFormulaException.java (89%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/InfiniteUnionHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/InstanceOperatorHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IntegerOpHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleHandler.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleHandlerServices.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleLauncher.java (96%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleLauncherListener.java (89%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleLauncherProgressDialogMediator.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleMasterHandler.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleProblem.java (57%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleResourceController.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleSettingsProvider.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleSolver.java (94%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleSolverInstance.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleSolverListener.java (96%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleTranslationExtension.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleTranslationSettings.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/IsabelleTranslator.java (99%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/LogicalVariableHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/NumberConstantsHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/ObserverFunctionHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/PolymorphicHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/QuantifierHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/SeqDefHandler.java (96%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/SledgehammerResult.java (93%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/SortDependingFunctionHandler.java (97%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/TranslateAllAction.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/TranslationAction.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/UninterpretedSymbolsHandler.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/gui/IsabelleProgressDialog.java (98%) rename keyext.isabelletranslation/src/main/java/{key => org/key_project}/isabelletranslation/gui/IsabelleProgressModel.java (99%) delete mode 100644 keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt rename keyext.isabelletranslation/src/main/resources/{key => org/key_project}/isabelletranslation/IntegerOpHandler.preamble.xml (100%) rename keyext.isabelletranslation/src/main/resources/{key => org/key_project}/isabelletranslation/ROOT (100%) rename keyext.isabelletranslation/src/main/resources/{key => org/key_project}/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml (100%) create mode 100644 keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt rename keyext.isabelletranslation/src/main/resources/{key => org/key_project}/isabelletranslation/root.tex (100%) diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java index 578fe38cfb2..0508d1a249a 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java index a4ea3331f7a..69453d4a5ee 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.BooleanLDT; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java index 22567e239a1..4ba998d25fe 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java index ab34548ed11..1a32309efd5 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Name; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java similarity index 89% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java index 66d4634128c..3d79f10eb6d 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IllegalFormulaException.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; public class IllegalFormulaException extends Exception { /** diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java index 75014889cd6..8952470e078 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java index 8807e3d6873..626b138f936 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java index 232178fb443..c7b511b489f 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java index 15b61f2cdc2..b3e041abea5 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java index 96e82d723c3..14d6ee2b405 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleHandlerServices.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.jspecify.annotations.NonNull; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java index 258e1793ca7..227fb5a6365 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java @@ -1,9 +1,6 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import org.jetbrains.annotations.NotNull; -import org.key_project.util.collection.Pair; -import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.pure.Theory; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java similarity index 89% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java index 3e6b6dd181e..a546cfb3e6c 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import java.util.Collection; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index a713cc62408..1ab26b6202e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -1,10 +1,10 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.colors.ColorSettings; -import key.isabelletranslation.gui.IsabelleProgressDialog; -import key.isabelletranslation.gui.IsabelleProgressModel; +import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; +import org.key_project.isabelletranslation.gui.IsabelleProgressModel; import javax.swing.*; import java.awt.*; @@ -64,7 +64,7 @@ private void applyResults() { //TODO create own close action } finally { mediator.startInterface(true); - // switch to new open goal + //switch to new open goal mediator.getSelectionModel().defaultSelection(); } } diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java index 2e413edf415..d2000551d5e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java similarity index 57% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java index 766483d8da5..212d032a6e6 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java @@ -1,27 +1,6 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.proof.Goal; -import de.unruh.isabelle.control.Isabelle; -import de.unruh.isabelle.java.JIsabelle; -import de.unruh.isabelle.mlvalue.*; -import de.unruh.isabelle.pure.Implicits; -import de.unruh.isabelle.pure.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import scala.Option; -import scala.Tuple2; -import scala.collection.immutable.List; -import scala.collection.mutable.Builder; -import scala.concurrent.Await; -import scala.concurrent.Future; -import scala.concurrent.duration.Duration; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; public class IsabelleProblem { private final Goal goal; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java index 0e02fe9d11b..7a34f4cfc73 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java index 8695fd7cba4..9a833beb291 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSettingsProvider.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.settings.InvalidSettingsInputException; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java similarity index 94% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java index dde8013643f..b85c96f073d 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java @@ -1,6 +1,4 @@ -package key.isabelletranslation; - -import de.unruh.isabelle.control.Isabelle; +package org.key_project.isabelletranslation; import java.util.TimerTask; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java index a2bb99003c3..24f54366705 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; @@ -172,7 +172,7 @@ public SolverState getState() { @Override public boolean wasInterrupted() { - return Thread.currentThread().isInterrupted(); + return reasonOfInterruption != ReasonOfInterruption.NoInterruption; } @Override diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java index 9c47f92d66f..2c4de318195 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; public interface IsabelleSolverListener extends IsabelleLauncherListener { void parsingStarted(IsabelleSolver solver, IsabelleProblem problem); diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java index f04d158db32..cdf37c0ee67 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java index ee3195c7723..95eaa483ee9 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.settings.AbstractSettings; import de.uka.ilkd.key.settings.Configuration; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java index 86c91d65ac8..f4838457454 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java index d2d08d4de09..e1f6b3f6336 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java index 5e89829c92a..a9cda9c6a79 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java index 1c8c0b6d364..9bc3d50ee35 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java index 5bfbe6aef96..0b272cadf9e 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/PolymorphicHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java index b453cbb7755..849a53d34d2 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java index 45ea78b999b..14e161e7959 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SeqDefHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java similarity index 93% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java index e360feec85a..5bf5a7bdccc 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SledgehammerResult.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import scala.Option; import scala.Tuple2; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java index 0a65a0ea84e..74f725cc29d 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java index c8a300c0f8e..4ba3430958d 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java index 92330b2da3d..0c667ebe43c 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java @@ -1,4 +1,4 @@ -package key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java index d285750d058..6319b52a524 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation; +package org.key_project.isabelletranslation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.HeapLDT; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java index 2439eae1d31..253b2352df3 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressDialog.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java @@ -1,14 +1,14 @@ /* 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 key.isabelletranslation.gui; +package org.key_project.isabelletranslation.gui; import de.uka.ilkd.key.gui.IssueDialog; import de.uka.ilkd.key.gui.MainWindow; import org.key_project.util.java.SwingUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import key.isabelletranslation.gui.IsabelleProgressModel.ProcessColumn.ProcessData; +import org.key_project.isabelletranslation.gui.IsabelleProgressModel.ProcessColumn.ProcessData; import javax.swing.*; import javax.swing.event.TableModelEvent; diff --git a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressModel.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressModel.java index 586e7c32808..fc08390b071 100644 --- a/keyext.isabelletranslation/src/main/java/key/isabelletranslation/gui/IsabelleProgressModel.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressModel.java @@ -1,7 +1,7 @@ /* 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 key.isabelletranslation.gui; +package org.key_project.isabelletranslation.gui; import java.awt.Color; import java.util.ArrayList; diff --git a/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension index c86d523a867..91385657445 100644 --- a/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension +++ b/keyext.isabelletranslation/src/main/resources/META-INF/services/de.uka.ilkd.key.gui.extension.api.KeYGuiExtension @@ -1 +1 @@ -key.isabelletranslation.IsabelleTranslationExtension \ No newline at end of file +org.key_project.isabelletranslation.IsabelleTranslationExtension \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt deleted file mode 100644 index 5a67b6bcc06..00000000000 --- a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/defaultHandlers.txt +++ /dev/null @@ -1,15 +0,0 @@ -key.isabelletranslation.DefinedSymbolsHandler -key.isabelletranslation.InstanceOperatorHandler -key.isabelletranslation.BooleanOpHandler -key.isabelletranslation.PolymorphicHandler -key.isabelletranslation.QuantifierHandler -key.isabelletranslation.LogicalVariableHandler -key.isabelletranslation.NumberConstantsHandler -key.isabelletranslation.IntegerOpHandler -key.isabelletranslation.InfiniteUnionHandler -key.isabelletranslation.BSumHandler -key.isabelletranslation.SeqDefHandler -key.isabelletranslation.SortDependingFunctionHandler -key.isabelletranslation.FieldHandler -key.isabelletranslation.ObserverFunctionHandler -key.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/IntegerOpHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/key/isabelletranslation/IntegerOpHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/IntegerOpHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/ROOT b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/ROOT similarity index 100% rename from keyext.isabelletranslation/src/main/resources/key/isabelletranslation/ROOT rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/ROOT diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/key/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt new file mode 100644 index 00000000000..190d34d901b --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt @@ -0,0 +1,15 @@ +org.key_project.isabelletranslation.DefinedSymbolsHandler +org.key_project.isabelletranslation.InstanceOperatorHandler +org.key_project.isabelletranslation.BooleanOpHandler +org.key_project.isabelletranslation.PolymorphicHandler +org.key_project.isabelletranslation.QuantifierHandler +org.key_project.isabelletranslation.LogicalVariableHandler +org.key_project.isabelletranslation.NumberConstantsHandler +org.key_project.isabelletranslation.IntegerOpHandler +org.key_project.isabelletranslation.InfiniteUnionHandler +org.key_project.isabelletranslation.BSumHandler +org.key_project.isabelletranslation.SeqDefHandler +org.key_project.isabelletranslation.SortDependingFunctionHandler +org.key_project.isabelletranslation.FieldHandler +org.key_project.isabelletranslation.ObserverFunctionHandler +org.key_project.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/key/isabelletranslation/root.tex b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/root.tex similarity index 100% rename from keyext.isabelletranslation/src/main/resources/key/isabelletranslation/root.tex rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/root.tex From 34fef8fccfb840c96faa97eee8ccb085b4b95c56 Mon Sep 17 00:00:00 2001 From: BookWood Date: Sun, 22 Sep 2024 13:40:07 +0200 Subject: [PATCH 228/248] add new IsabelleResult to replace SledgehammerResult prototype --- .../isabelletranslation/IsabelleResult.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java new file mode 100644 index 00000000000..8dca456425d --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java @@ -0,0 +1,62 @@ +package org.key_project.isabelletranslation; + +public class IsabelleResult { + enum Type { + SUCCESS, + ERROR, + TIMEOUT + } + + + + private final Type type; + + private final long computationTime; + + private final String successfulTactic; + + private final Exception exception; + + private IsabelleResult(Type type, long computationTime, String successfulTactic, Exception exception) { + this.type = type; + this.computationTime = computationTime; + this.successfulTactic = successfulTactic; + this.exception = exception; + } + + public boolean isSuccessful() { + return type == Type.SUCCESS; + } + + public static IsabelleResult getTimeoutResult(long computationTime) { + return new IsabelleResult(Type.TIMEOUT, computationTime, null, null); + } + + public static IsabelleResult getErrorResult(Exception exception) { + return new IsabelleResult(Type.ERROR, -1, null, exception); + } + + public static IsabelleResult getSuccessResult(String successfulTactic, long computationTime) { + return new IsabelleResult(Type.SUCCESS, computationTime, successfulTactic, null); + } + + public boolean isError() { + return type == Type.ERROR; + } + + public boolean isTimeout() { + return type == Type.TIMEOUT; + } + + public long getComputationTime() { + return this.computationTime; + } + + public Exception getException() { + return this.exception; + } + + public String getSuccessfulTactic() { + return this.successfulTactic; + } +} From 74b631fac761bf2644af7611ca9cb293b706aed0 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 22 Sep 2024 13:45:44 +0200 Subject: [PATCH 229/248] replacing SledgehammerResult --- .../isabelletranslation/IsabelleLauncher.java | 8 +++--- .../isabelletranslation/IsabelleProblem.java | 6 ++--- .../isabelletranslation/IsabelleSolver.java | 2 +- .../IsabelleSolverInstance.java | 26 ++++++++++++------- .../SledgehammerResult.java | 26 ------------------- .../TranslateAllAction.java | 2 +- 6 files changed, 26 insertions(+), 44 deletions(-) delete mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java index 227fb5a6365..9599bcc8d8e 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java @@ -41,7 +41,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t Runtime.getRuntime().addShutdownHook(shutdownResources); for (int i = 0; i < problems.size(); i++) { - IsabelleSolver solver = new IsabelleSolverInstance(problems.get(i), List.of(new IsabelleSolverListener[0]), i, resourceController); + IsabelleSolver solver = new IsabelleSolverInstance(problems.get(i), List.of(new IsabelleSolverListener[0]), i, resourceController, settings); solver.setTimeout(timeoutSeconds); solverQueue.add(solver); solverSet.add(solver); @@ -59,7 +59,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t TranslationAction.writeTranslationFiles(problems.get(0)); - Collection>> tasks = launchSolverInstances(instanceCount); + Collection>> tasks = launchSolverInstances(instanceCount); LOGGER.info("Setup complete, starting {} problems...", problems.size()); @@ -75,8 +75,8 @@ public void try0ThenSledgehammerAllPooled(List problems, long t } } - private @NotNull Collection>> launchSolverInstances(int instanceCount) { - Collection>> tasks = new LinkedBlockingDeque<>(); + private @NotNull Collection>> launchSolverInstances(int instanceCount) { + Collection>> tasks = new LinkedBlockingDeque<>(); for (int i = 0; i < instanceCount; i++) { tasks.add(() -> { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java index 212d032a6e6..33c09aec039 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java @@ -4,7 +4,7 @@ public class IsabelleProblem { private final Goal goal; - private SledgehammerResult result = null; + private IsabelleResult result = null; private final String preamble; private final String sequentTranslation; private final String name; @@ -32,11 +32,11 @@ public String getName() { return name; } - public SledgehammerResult getResult() { + public IsabelleResult getResult() { return result; } - protected void setResult(SledgehammerResult result) { + protected void setResult(IsabelleResult result) { this.result = result; } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java index b85c96f073d..455d3ea25a4 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java @@ -43,7 +43,7 @@ enum SolverState{ String getRawSolverInput(); - SledgehammerResult getFinalResult(); + IsabelleResult getFinalResult(); class IsabelleSolverTimeout extends TimerTask { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java index 24f54366705..eb2c2bd004c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java @@ -25,7 +25,7 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { private final int solverIndex; - private SledgehammerResult result; + private IsabelleResult result; private IsabelleResourceController.IsabelleResource isabelleResource; @@ -81,12 +81,13 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); private Collection listeners; - public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController) { + public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { this.problem = problem; this.solverIndex = solverIndex; this.listeners = new HashSet<>(); this.listeners.addAll(listeners); this.resourceController = resourceController; + this.isabelleSettings = settings; } @Override @@ -197,7 +198,7 @@ public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings set @Override public String getRawSolverOutput() { - return problem.getResult().result().toString(); + return problem.getResult().getSuccessfulTactic(); } @Override @@ -206,7 +207,7 @@ public String getRawSolverInput() { } @Override - public SledgehammerResult getFinalResult() { + public IsabelleResult getFinalResult() { return problem.getResult(); } @@ -253,7 +254,7 @@ public void run() { notifySledgehammerFinished(); } catch (TimeoutException e) { setReasonOfInterruption(ReasonOfInterruption.Timeout); - this.result = new SledgehammerResult(Option.apply(new Tuple2<>("timeout", "timeout"))); + this.result = IsabelleResult.getTimeoutResult(042); notifySledgehammerFinished(); } catch (InterruptedException e) { notifySledgehammerError(e); @@ -320,7 +321,7 @@ in addtext (Symbol.explode text) transitions end""", isabelle, } - private SledgehammerResult sledgehammer(IsabelleResourceController.IsabelleResource resource, ToplevelState toplevel) + private IsabelleResult sledgehammer(IsabelleResourceController.IsabelleResource resource, ToplevelState toplevel) throws TimeoutException, InterruptedException, IsabelleMLException { Isabelle isabelle = resource.instance(); Theory thy0 = resource.theory(); @@ -340,7 +341,7 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout",\"""" + getTimeout() + """ + [("timeout",\"""" + 2 + """ "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ @@ -362,13 +363,20 @@ fun go_run (state, thy) = Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List emptyList = listBuilder.result(); - SledgehammerResult result = null; + IsabelleResult result = null; Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); - result = new SledgehammerResult(Option.apply(new Tuple2<>(resultFutureCollect._2()._1(), resultFutureCollect._2()._2().head()))); + + boolean successful = (boolean) resultFutureCollect._1(); + + if (successful) { + result = IsabelleResult.getSuccessResult(resultFutureCollect._2()._1(), 042); + } else { + result = IsabelleResult.getTimeoutResult(042); + } this.result = result; return this.result; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java deleted file mode 100644 index 5bf5a7bdccc..00000000000 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SledgehammerResult.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.key_project.isabelletranslation; - -import scala.Option; -import scala.Tuple2; - -public record SledgehammerResult(Option> result) { - public Boolean isSuccessful() { - return result.exists((Tuple2 tactic) -> !tactic._1().equals("timeout")); - } - - public String getSuccessfulTactic() { - if (!isSuccessful()) { - return null; - } - return result.get()._2(); - } - - @Override - public String toString() { - return (result.exists((r) -> true)) ? result.get().toString() : null; - } - - public boolean isTimeout() { - return result.exists((Tuple2 tactic) -> tactic._1().equals("timeout")); - } -} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java index 4ba3430958d..6b18a5f7f00 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java @@ -48,7 +48,7 @@ private void generateTranslation() { writeTranslationFiles(translations.get(0)); - SledgehammerResult result = null; + IsabelleResult result = null; Thread thread = new Thread(() -> { IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); From a2f6a87fcb27491bde120a8a89452800f1039b2c Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Mon, 23 Sep 2024 16:15:46 +0200 Subject: [PATCH 230/248] fix running additional solvers after user interruptions --- .../isabelletranslation/IsabelleLauncher.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java index 9599bcc8d8e..14762f45207 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java @@ -30,12 +30,16 @@ public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IO } public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int instanceCount) throws IOException { + if (problems.isEmpty()) { + return; + } + IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); shutdownResources = new Thread(() -> { - executorService.shutdownNow(); + executorService.shutdown(); resourceController.shutdownGracefully(); }); Runtime.getRuntime().addShutdownHook(shutdownResources); @@ -52,9 +56,7 @@ public void try0ThenSledgehammerAllPooled(List problems, long t resourceController.init(); listener.launcherPreparationFinished(this, solverSet); - if (problems.isEmpty()) { - return; - } + //Ensure the preamble theory is present TranslationAction.writeTranslationFiles(problems.get(0)); @@ -105,11 +107,14 @@ public void addListener(IsabelleLauncherListener listener) { public void stopAll(IsabelleSolver.ReasonOfInterruption reasonOfInterruption) { shutdown(); - runningSolvers.forEach((solver) -> solver.interrupt(reasonOfInterruption)); solverQueue.forEach((solver) -> solver.interrupt(reasonOfInterruption)); + solverQueue.clear(); + + runningSolvers.forEach((solver) -> solver.interrupt(reasonOfInterruption)); runningSolvers.clear(); - solverQueue.clear(); + + listener.launcherStopped(this, solverSet); } } From 83008bcc7b332cc6d5d2d647a5dafb012e7fe22b Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 24 Sep 2024 18:09:25 +0200 Subject: [PATCH 231/248] notify listener when launcher finishes work --- .../org/key_project/isabelletranslation/IsabelleLauncher.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java index 14762f45207..79bf5dc6011 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java @@ -75,6 +75,8 @@ public void try0ThenSledgehammerAllPooled(List problems, long t } finally { shutdown(); } + + listener.launcherStopped(this, solverSet); } private @NotNull Collection>> launchSolverInstances(int instanceCount) { From 2de68956a29a304a8308b39e70fd759f0c32120b Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 24 Sep 2024 18:11:04 +0200 Subject: [PATCH 232/248] discard button functionality --- ...sabelleLauncherProgressDialogMediator.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index 1ab26b6202e..82c226b6f23 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -3,8 +3,10 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.colors.ColorSettings; +import de.uka.ilkd.key.proof.Proof; import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; import org.key_project.isabelletranslation.gui.IsabelleProgressModel; +import org.key_project.isabelletranslation.gui.ProofApplyUserAction; import javax.swing.*; import java.awt.*; @@ -16,16 +18,25 @@ public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherL private final Timer timer = new Timer(); private int finishedCounter = 0; + private final Proof proof; + private final IsabelleTranslationSettings settings; + private final static ColorSettings.ColorProperty RED = - ColorSettings.define("[solverListener]red", "", new Color(180, 43, 43)); + ColorSettings.define("[isabelleDialog]red", "", new Color(180, 43, 43)); private final static ColorSettings.ColorProperty GREEN = - ColorSettings.define("[solverListener]green", "", new Color(43, 180, 43)); + ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); @Override public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { + timer.cancel(); + + progressModel.setEditable(true); + refreshDialog(); + progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); + //TODO automatic closing of goals without apply button? } @Override @@ -140,11 +151,13 @@ private void setProgressText(int value) { } protected void discardEvent(IsabelleLauncher launcher) { - + launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); + progressDialog.dispose(); } - public IsabelleLauncherProgressDialogMediator(IsabelleTranslationSettings settings) { - + public IsabelleLauncherProgressDialogMediator(IsabelleTranslationSettings settings, Proof proof) { + this.settings = settings; + this.proof = proof; } @@ -221,7 +234,6 @@ private void parsing(IsabelleSolver solver) { } private void waiting(IsabelleSolver solver) { - progressModel.setText("Waiting...", 0, solver.getSolverIndex()); } private void preparing(IsabelleSolver solver) { @@ -243,7 +255,6 @@ public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { public void infoButtonClicked(int column, int row) { //SolverListener.InternSMTProblem problem = getProblem(column, row); //showInformation(problem); - } @Override @@ -254,7 +265,6 @@ public void stopButtonClicked() { @Override public void applyButtonClicked() { applyEvent(launcher); - } @Override From 5d800ecbde8b74047b4a5c30d910986b597e7a15 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 24 Sep 2024 18:14:46 +0200 Subject: [PATCH 233/248] show solver progress in dialog, remove bugs in dialog, remove info button --- ...sabelleLauncherProgressDialogMediator.java | 39 +++++++++++++-- .../IsabelleResourceController.java | 1 - .../isabelletranslation/IsabelleResult.java | 20 ++++++-- .../isabelletranslation/IsabelleSolver.java | 2 + .../IsabelleSolverInstance.java | 48 +++++++++++-------- .../TranslateAllAction.java | 2 +- .../TranslationAction.java | 2 +- .../gui/IsabelleProgressDialog.java | 2 +- 8 files changed, 85 insertions(+), 31 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index 82c226b6f23..35dc8157a49 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -118,7 +118,10 @@ private void interrupted(IsabelleSolver solver) { progressModel.setProgress(0, x, y); progressModel.setText("Timeout.", x, y); } - case User -> progressModel.setText("Interrupted by user.", x, y); + case User -> { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by user.", x, y); + } } } @@ -127,7 +130,18 @@ private void successfullyStopped(IsabelleSolver solver, int x, int y) { progressModel.setProgress(0, x, y); progressModel.setTextColor(GREEN.get(), x, y); - progressModel.setText("Valid", x, y); + + String timeInfo = getTimeInSecAsString(solver.getComputationTime()); + + progressModel.setText("Valid (" + timeInfo + ")", x, y); + } + + String getTimeInSecAsString(long timeToSolve) { + long intPart = timeToSolve / 1000; + long decPart = timeToSolve % 1000; + String decString = decPart >= 100 ? Long.toString(decPart) + : decPart >= 10 ? "0" + decPart : "00" + decPart; + return intPart + "." + decString + "s"; } private void unknownStopped(int x, int y) { @@ -226,7 +240,26 @@ private boolean refreshProgressOfSolver(IsabelleSolver solver) { } private void running(IsabelleSolver solver) { - progressModel.setText("Running...", 0, solver.getSolverIndex()); + long progress = calculateProgress(solver); + progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); + + float remainingTime = calculateRemainingTime(solver); + progressModel.setText(remainingTime + " sec.", 0, solver.getSolverIndex()); + } + + private long calculateProgress(IsabelleSolver solver) { + long maxTime = solver.getTimeout() * 1000; + long startTime = solver.getStartTime(); + long currentTime = System.currentTimeMillis(); + + return RESOLUTION - ((currentTime - startTime) * RESOLUTION) / maxTime; + } + + private float calculateRemainingTime(IsabelleSolver solver) { + long timeoutTime = solver.getStartTime() + solver.getTimeout() * 1000; + long currentTime = System.currentTimeMillis(); + long temp = (timeoutTime - currentTime) / 100; + return Math.max((float) temp / 10.0f, 0); } private void parsing(IsabelleSolver solver) { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java index 7a34f4cfc73..85feebfce5a 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java @@ -80,7 +80,6 @@ public void returnResource(IsabelleSolver returningSolver, IsabelleResource reso if (isShutdown()) { if (!resource.isDestroyed()) { - //TODO some kind of race condition happens here resource.destroy(); } return; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java index 8dca456425d..0177e18674c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java @@ -1,10 +1,24 @@ package org.key_project.isabelletranslation; public class IsabelleResult { + public String getDescription() { + return this.type.getDescription(); + } + enum Type { - SUCCESS, - ERROR, - TIMEOUT + SUCCESS ("Success"), + ERROR ("Error"), + TIMEOUT ("Timeout"); + + Type(String description) { + this.description = description; + } + + private final String description; + + public String getDescription() { + return description; + } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java index 455d3ea25a4..0835c0cd1fb 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java @@ -27,6 +27,8 @@ enum SolverState{ long getStartTime(); + long getComputationTime(); + long getTimeout(); void setTimeout(long timeout); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java index eb2c2bd004c..6529b2549e6 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java @@ -60,11 +60,6 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { */ private IsabelleTranslationSettings isabelleSettings; - /** - * Stores the translation of the problem that is associated with this solver - */ - private String problemString = "NOT YET COMPUTED"; - /** * If there was an exception while executing the solver it is stored in this attribute. */ @@ -75,11 +70,15 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { */ private long timeout = -1; + private long startTime; + + private long computationTime; + private final IsabelleResourceController resourceController; - private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolver.class); - private Collection listeners; + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolverInstance.class); + private final Collection listeners; public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { this.problem = problem; @@ -102,7 +101,7 @@ public ReasonOfInterruption getReasonOfInterruption() { @Override public String name() { - return "Isabelle"; + return "Isabelle Solver: " + problem.getName(); } @Override @@ -123,6 +122,7 @@ public Throwable getException() { @Override public void interrupt(ReasonOfInterruption reason) { setReasonOfInterruption(reason); + this.result = IsabelleResult.getErrorResult(new TimeoutException()); setSolverState(SolverState.Stopped); if (solverTimeout != null) { solverTimeout.cancel(); @@ -150,10 +150,7 @@ public void setReasonOfInterruption(ReasonOfInterruption reasonOfInterruption) { @Override public long getStartTime() { - if (solverTimeout == null) { - return -1; - } - return solverTimeout.scheduledExecutionTime(); + return startTime; } @Override @@ -198,7 +195,7 @@ public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings set @Override public String getRawSolverOutput() { - return problem.getResult().getSuccessfulTactic(); + return result.getSuccessfulTactic(); } @Override @@ -208,7 +205,7 @@ public String getRawSolverInput() { @Override public IsabelleResult getFinalResult() { - return problem.getResult(); + return this.result; } @Override @@ -224,6 +221,7 @@ public void run() { notifyProcessStarted(); + startTime = System.currentTimeMillis(); Isabelle isabelle = isabelleResource.instance(); ToplevelState toplevel = ToplevelState.apply(isabelle); @@ -251,22 +249,26 @@ public void run() { try { this.result = sledgehammer(isabelleResource, toplevel); + computationTime = System.currentTimeMillis() - startTime; notifySledgehammerFinished(); } catch (TimeoutException e) { setReasonOfInterruption(ReasonOfInterruption.Timeout); - this.result = IsabelleResult.getTimeoutResult(042); + computationTime = System.currentTimeMillis() - startTime; + this.result = IsabelleResult.getTimeoutResult(computationTime); notifySledgehammerFinished(); } catch (InterruptedException e) { + this.result = IsabelleResult.getErrorResult(e); notifySledgehammerError(e); } catch (IsabelleMLException e) { + this.result = IsabelleResult.getErrorResult(e); setReasonOfInterruption(ReasonOfInterruption.Exception); notifySledgehammerError(e); } finally { returnResource(); - getProblem().setResult(this.result); + //getProblem().setResult(this.result); setSolverState(SolverState.Stopped); notifyProcessFinished(); - LOGGER.info("Sledgehammer result: {}", this.result); + LOGGER.info("Sledgehammer result: {}", this.result.getDescription()); } } @@ -341,7 +343,7 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout",\"""" + 2 + """ + [("timeout",\"""" + timeout + """ "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ @@ -363,7 +365,7 @@ fun go_run (state, thy) = Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List emptyList = listBuilder.result(); - IsabelleResult result = null; + IsabelleResult result; Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) @@ -373,14 +375,18 @@ fun go_run (state, thy) = boolean successful = (boolean) resultFutureCollect._1(); if (successful) { - result = IsabelleResult.getSuccessResult(resultFutureCollect._2()._1(), 042); + result = IsabelleResult.getSuccessResult(resultFutureCollect._2()._2().head(), computationTime); } else { - result = IsabelleResult.getTimeoutResult(042); + result = IsabelleResult.getTimeoutResult(computationTime); } this.result = result; return this.result; } + @Override + public long getComputationTime() { + return computationTime; + } private void notifyParsingStarted() { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java index 6b18a5f7f00..dfc7e1fef53 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java @@ -59,7 +59,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings)); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings, mediator.getSelectedProof())); try { launcher.try0ThenSledgehammerAllPooled(translations, 30, 1); } catch (IOException e) { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java index 0c667ebe43c..f994d730e8a 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java @@ -56,7 +56,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings)); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings, mediator.getSelectedProof())); try { launcher.try0ThenSledgehammerAllPooled(list, 30, 1); } catch (IOException e) { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java index 253b2352df3..9788060b2f6 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java @@ -246,7 +246,7 @@ private JButton getInfoButton() { content.add(Box.createHorizontalStrut(2)); content.add(getProgressBar()); content.add(Box.createHorizontalStrut(2)); - content.add(getInfoButton()); + //content.add(getInfoButton()); content.add(Box.createHorizontalStrut(2)); this.add(content); this.add(Box.createVerticalStrut(2)); From 3038ce143b7d79d4d92a46e34581b051adba9e70 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 24 Sep 2024 18:15:03 +0200 Subject: [PATCH 234/248] separate IsabelleProblem from solvers, remove result --- .../key_project/isabelletranslation/IsabelleProblem.java | 9 --------- .../isabelletranslation/IsabelleSolverInstance.java | 1 - 2 files changed, 10 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java index 33c09aec039..4461f2d50b5 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java @@ -4,7 +4,6 @@ public class IsabelleProblem { private final Goal goal; - private IsabelleResult result = null; private final String preamble; private final String sequentTranslation; private final String name; @@ -31,12 +30,4 @@ public String getPreamble() { public String getName() { return name; } - - public IsabelleResult getResult() { - return result; - } - - protected void setResult(IsabelleResult result) { - this.result = result; - } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java index 6529b2549e6..c86e65e67ee 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java @@ -9,7 +9,6 @@ import de.unruh.isabelle.pure.Transition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import scala.Option; import scala.Tuple2; import scala.collection.immutable.List; import scala.collection.mutable.Builder; From 3a784bba4aa6c350b5ea9f3dfb0041d2312913aa Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 24 Sep 2024 18:16:02 +0200 Subject: [PATCH 235/248] add prototypical apply action for dialog that does not require changes to KeY core --- ...sabelleLauncherProgressDialogMediator.java | 2 +- .../gui/ProofApplyUserAction.java | 73 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index 35dc8157a49..89378a8265c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -72,7 +72,7 @@ private void applyResults() { // ensure that the goal closing does not lag the UI mediator.stopInterface(true); try { - //TODO create own close action + new ProofApplyUserAction(mediator, proof, solvers).actionPerformed(null); } finally { mediator.startInterface(true); //switch to new open goal diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java new file mode 100644 index 00000000000..2f39de0e3c2 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java @@ -0,0 +1,73 @@ +package org.key_project.isabelletranslation.gui; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.actions.useractions.UserAction; +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.rule.IBuiltInRuleApp; +import de.uka.ilkd.key.smt.SMTRuleApp; +import org.key_project.isabelletranslation.IsabelleProblem; +import org.key_project.isabelletranslation.IsabelleSolver; + +import java.util.Collection; +import java.util.HashSet; + +public class ProofApplyUserAction extends UserAction { + private final Collection solvers; + + private final Collection goalsClosed = new HashSet<>(); + + private final int numberOfGoalsClosed; + + public ProofApplyUserAction(KeYMediator mediator, Proof proof, + Collection solvers) { + super(mediator, proof); + this.solvers = solvers; + this.numberOfGoalsClosed = (int) solvers.stream().filter(solver -> + solver.getFinalResult().isSuccessful()).count(); + } + + @Override + public String name() { + return String.format("Close: %d goals by Isabelle", numberOfGoalsClosed); + } + + @Override + protected void apply() { + for (IsabelleSolver solver : solvers) { + IsabelleProblem problem = solver.getProblem(); + Goal goal = problem.getGoal(); + + if (goalsClosed.contains(goal) || !solver.getFinalResult().isSuccessful()) { + continue; + } + + goalsClosed.add(goal); + + //TODO SMTRuleApp does not serve any purpose as a SMT exclusive rule. + // The documentation does not suggest it should only be used for SMT, yet the name would suggest this. + // Changing this requires changing parts of the KeY core. This needs a different class, which does not prepend "SMT" to all titles + IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("") + .setTitle("Isabelle: " + solver.getFinalResult().getSuccessfulTactic()); + app.tryToInstantiate(goal); + goal.apply(app); + } + } + + @Override + public void undo() { + for (Goal g : goalsClosed) { + Node n = g.node(); + n.setAppliedRuleApp(null); + // re-open the goal + Goal firstGoal = proof.getClosedGoal(n); + proof.reOpenGoal(firstGoal); + } + } + + @Override + public boolean canUndo() { + return goalsClosed.stream().allMatch(g -> proof.find(g.node())); + } +} From a7f8af24180d403178ef5b05695e1ecfd1658d87 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 8 Oct 2024 16:34:03 +0200 Subject: [PATCH 236/248] make solvers callable. Add timeout settings --- .../isabelletranslation/IsabelleLauncher.java | 69 +++--- ...sabelleLauncherProgressDialogMediator.java | 111 ++++----- .../IsabelleResourceController.java | 14 +- .../isabelletranslation/IsabelleResult.java | 32 ++- .../IsabelleSettingsProvider.java | 29 ++- ...e.java => IsabelleSledgehammerSolver.java} | 226 +++++------------- .../isabelletranslation/IsabelleSolver.java | 34 +-- .../IsabelleSolverListener.java | 24 +- .../IsabelleTranslationSettings.java | 38 +-- .../TranslateAllAction.java | 4 +- .../TranslationAction.java | 7 +- 11 files changed, 248 insertions(+), 340 deletions(-) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{IsabelleSolverInstance.java => IsabelleSledgehammerSolver.java} (67%) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java index 79bf5dc6011..a9d005f3f30 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java @@ -1,6 +1,5 @@ package org.key_project.isabelletranslation; -import org.jetbrains.annotations.NotNull; import org.jspecify.annotations.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,7 +8,7 @@ import java.util.*; import java.util.concurrent.*; -public class IsabelleLauncher { +public class IsabelleLauncher implements IsabelleSolverListener { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); private final IsabelleTranslationSettings settings; @@ -17,26 +16,29 @@ public class IsabelleLauncher { private Thread shutdownResources; + private ExecutorService executorService; + private final List runningSolvers = Collections.synchronizedList(new ArrayList<>()); private final LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); private final Collection solverSet = new HashSet<>(); + private IsabelleSolver.ReasonOfInterruption reasonOfInterruption; public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { this.settings = settings; } - public void try0ThenSledgehammerAllPooled(List problems, long timeoutSeconds, int instanceCount) throws IOException { + public void try0ThenSledgehammerAllPooled(List problems, int timeoutSeconds, int instanceCount) throws IOException { if (problems.isEmpty()) { return; } IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); - ExecutorService executorService = Executors.newFixedThreadPool(instanceCount); + executorService = Executors.newFixedThreadPool(instanceCount); shutdownResources = new Thread(() -> { executorService.shutdown(); @@ -45,8 +47,9 @@ public void try0ThenSledgehammerAllPooled(List problems, long t Runtime.getRuntime().addShutdownHook(shutdownResources); for (int i = 0; i < problems.size(); i++) { - IsabelleSolver solver = new IsabelleSolverInstance(problems.get(i), List.of(new IsabelleSolverListener[0]), i, resourceController, settings); + IsabelleSolver solver = new IsabelleSledgehammerSolver(problems.get(i), List.of(this), i, resourceController, settings); solver.setTimeout(timeoutSeconds); + solverQueue.add(solver); solverSet.add(solver); } @@ -60,13 +63,10 @@ public void try0ThenSledgehammerAllPooled(List problems, long t //Ensure the preamble theory is present TranslationAction.writeTranslationFiles(problems.get(0)); - - Collection>> tasks = launchSolverInstances(instanceCount); - LOGGER.info("Setup complete, starting {} problems...", problems.size()); try { - executorService.invokeAll(tasks); + executorService.invokeAll(solverQueue); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (RejectedExecutionException e) { @@ -79,23 +79,6 @@ public void try0ThenSledgehammerAllPooled(List problems, long t listener.launcherStopped(this, solverSet); } - private @NotNull Collection>> launchSolverInstances(int instanceCount) { - Collection>> tasks = new LinkedBlockingDeque<>(); - - for (int i = 0; i < instanceCount; i++) { - tasks.add(() -> { - IsabelleSolver solver; - while ((solver = solverQueue.poll()) != null) { - runningSolvers.add(solver); - solver.start(null, settings); - runningSolvers.remove(solver); - } - return null; - }); - } - return tasks; - } - private void shutdown() { Runtime.getRuntime().removeShutdownHook(shutdownResources); if (shutdownResources.getState() == Thread.State.NEW) { @@ -108,15 +91,41 @@ public void addListener(IsabelleLauncherListener listener) { } public void stopAll(IsabelleSolver.ReasonOfInterruption reasonOfInterruption) { + this.reasonOfInterruption = reasonOfInterruption; + shutdown(); - solverQueue.forEach((solver) -> solver.interrupt(reasonOfInterruption)); - solverQueue.clear(); + executorService.shutdownNow(); - runningSolvers.forEach((solver) -> solver.interrupt(reasonOfInterruption)); - runningSolvers.clear(); + solverQueue.forEach(solver -> solver.interrupt(reasonOfInterruption)); + solverQueue.clear(); + runningSolvers.forEach(solver -> { + if (reasonOfInterruption != null) { + solver.interrupt(reasonOfInterruption); + } + }); + runningSolvers.clear(); listener.launcherStopped(this, solverSet); } + + @Override + public void processStarted(IsabelleSolver solver, IsabelleProblem problem) { + runningSolvers.add(solver); + solverQueue.remove(solver); + } + + @Override + public void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e) { + runningSolvers.remove(solver); + if (reasonOfInterruption != null) { + solver.interrupt(reasonOfInterruption); + } + } + + @Override + public void processStopped(IsabelleSolver solver, IsabelleProblem problem) { + runningSolvers.remove(solver); + } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java index 89378a8265c..11518bc0835 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java @@ -10,16 +10,19 @@ import javax.swing.*; import java.awt.*; +import java.text.DecimalFormat; +import java.time.Duration; +import java.time.Instant; import java.util.Timer; import java.util.Collection; import java.util.TimerTask; public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { + private static final DecimalFormat remainingTimeFormat = new DecimalFormat("#.#"); private final Timer timer = new Timer(); private int finishedCounter = 0; private final Proof proof; - private final IsabelleTranslationSettings settings; private final static ColorSettings.ColorProperty RED = @@ -27,6 +30,7 @@ public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherL private final static ColorSettings.ColorProperty GREEN = ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); + private boolean userStopFlag = false; @Override public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { @@ -35,8 +39,6 @@ public void launcherStopped(IsabelleLauncher launcher, Collection { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(RED.get(), x, y); - progressModel.setText("Exception!", x, y); - } - case NoInterruption -> throw new RuntimeException("This position should not be reachable!"); - case Timeout -> { - progressModel.setProgress(0, x, y); - progressModel.setText("Timeout.", x, y); - } - case User -> { - progressModel.setProgress(0, x, y); - progressModel.setText("Interrupted by user.", x, y); - } + private void interrupted(IsabelleSolver solver, int x, int y) { + if (userStopFlag) { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by user.", x, y); + } else { + throw new RuntimeException("This position should not be reachable!"); } } private void successfullyStopped(IsabelleSolver solver, int x, int y) { - //TODO add time information - progressModel.setProgress(0, x, y); progressModel.setTextColor(GREEN.get(), x, y); - String timeInfo = getTimeInSecAsString(solver.getComputationTime()); + String timeInfo = solver.getComputationTime().toMillis() / 1000d + "s"; progressModel.setText("Valid (" + timeInfo + ")", x, y); } - String getTimeInSecAsString(long timeToSolve) { - long intPart = timeToSolve / 1000; - long decPart = timeToSolve % 1000; - String decString = decPart >= 100 ? Long.toString(decPart) - : decPart >= 10 ? "0" + decPart : "00" + decPart; - return intPart + "." + decString + "s"; + private void encounteredError(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(RED.get(), x, y); + progressModel.setText("Exception!", x, y); + } + + private void timedOut(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by User.", x, y); } private void unknownStopped(int x, int y) { @@ -153,7 +155,7 @@ private void unknownStopped(int x, int y) { private void setProgressText(int value) { JProgressBar bar = progressDialog.getProgressBar(); if (value == -1) { - bar.setString("Preparing..."); + bar.setString("Preparing... (this might take a few seconds)"); bar.setStringPainted(true); } else if (value == bar.getMaximum()){ bar.setString("Finished."); @@ -169,8 +171,7 @@ protected void discardEvent(IsabelleLauncher launcher) { progressDialog.dispose(); } - public IsabelleLauncherProgressDialogMediator(IsabelleTranslationSettings settings, Proof proof) { - this.settings = settings; + public IsabelleLauncherProgressDialogMediator(Proof proof) { this.proof = proof; } @@ -212,30 +213,25 @@ private void refreshDialog() { } } - private boolean refreshProgressOfSolver(IsabelleSolver solver) { + private void refreshProgressOfSolver(IsabelleSolver solver) { IsabelleSolver.SolverState state = solver.getState(); - return switch (state) { + switch (state) { case Preparing -> { preparing(solver); - yield true; } case Parsing -> { parsing(solver); - yield true; } case Running -> { running(solver); - yield true; } case Stopped -> { stopped(solver); - yield false; } case Waiting -> { waiting(solver); - yield true; } - }; + } } @@ -244,22 +240,19 @@ private void running(IsabelleSolver solver) { progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); float remainingTime = calculateRemainingTime(solver); - progressModel.setText(remainingTime + " sec.", 0, solver.getSolverIndex()); + progressModel.setText(remainingTimeFormat.format(remainingTime) + " sec.", 0, solver.getSolverIndex()); } private long calculateProgress(IsabelleSolver solver) { - long maxTime = solver.getTimeout() * 1000; - long startTime = solver.getStartTime(); - long currentTime = System.currentTimeMillis(); + Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); + Instant startTime = solver.getStartTime(); - return RESOLUTION - ((currentTime - startTime) * RESOLUTION) / maxTime; + return RESOLUTION * (Duration.between(startTime, Instant.now()).toMillis() / maxDuration.toMillis()); } private float calculateRemainingTime(IsabelleSolver solver) { - long timeoutTime = solver.getStartTime() + solver.getTimeout() * 1000; - long currentTime = System.currentTimeMillis(); - long temp = (timeoutTime - currentTime) / 100; - return Math.max((float) temp / 10.0f, 0); + Instant timeoutTime = solver.getStartTime().plusSeconds(solver.getTimeout()); + return Duration.between(Instant.now(), timeoutTime).toMillis() / 1000f; } private void parsing(IsabelleSolver solver) { @@ -286,8 +279,6 @@ public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { @Override public void infoButtonClicked(int column, int row) { - //SolverListener.InternSMTProblem problem = getProblem(column, row); - //showInformation(problem); } @Override diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java index 85feebfce5a..061ffde651f 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java @@ -49,8 +49,8 @@ public IsabelleResourceController(int numberOfInstances) { public void init() throws IOException { for (int i = 0; i < numberOfInstances; i++) { - IsabelleResource newResource = createIsabelleResource(); - if (!isShutdown() && newResource != null) { + if (!isShutdown()) { + IsabelleResource newResource = createIsabelleResource(); idleInstances.add(newResource); } } @@ -68,7 +68,7 @@ public void shutdownGracefully() { instanceCreatorService.shutdownNow(); - waitingSolvers.forEach((x) -> x.interrupt(IsabelleSolver.ReasonOfInterruption.Exception)); + waitingSolvers.forEach((x) -> x.interrupt(IsabelleSolver.ReasonOfInterruption.User)); waitingSolvers.clear(); idleInstances.forEach(IsabelleResource::destroy); @@ -118,14 +118,10 @@ private IsabelleResource createIsabelleResource() throws IOException { if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } - if (isShutdown()) { - return null; - } LOGGER.error("Error during Isabelle setup"); throw new RuntimeException(e); } catch (RejectedExecutionException e) { - //IsabelleResourceController is shutdown - return null; + throw new RuntimeException("Unreachable code during Isabelle instance creation"); } } @@ -178,7 +174,7 @@ private void interruptIntern() throws IsabelleMLException { instance.executeMLCodeNow("error \"Interrupt\""); } - public void interrupt() { + private void interrupt() { try { interruptIntern(); } catch (IsabelleMLException e) { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java index 0177e18674c..b3148314d06 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java @@ -1,14 +1,22 @@ package org.key_project.isabelletranslation; +import java.time.Duration; + public class IsabelleResult { public String getDescription() { return this.type.getDescription(); } - enum Type { + public Type getType() { + return this.type; + } + + public enum Type { SUCCESS ("Success"), ERROR ("Error"), - TIMEOUT ("Timeout"); + TIMEOUT ("Timeout"), + INTERRUPTED("Interrupted"), + UNKNOWN ("Unknown"); Type(String description) { this.description = description; @@ -25,13 +33,13 @@ public String getDescription() { private final Type type; - private final long computationTime; + private final Duration computationTime; private final String successfulTactic; private final Exception exception; - private IsabelleResult(Type type, long computationTime, String successfulTactic, Exception exception) { + private IsabelleResult(Type type, Duration computationTime, String successfulTactic, Exception exception) { this.type = type; this.computationTime = computationTime; this.successfulTactic = successfulTactic; @@ -42,18 +50,26 @@ public boolean isSuccessful() { return type == Type.SUCCESS; } - public static IsabelleResult getTimeoutResult(long computationTime) { + public static IsabelleResult getTimeoutResult(Duration computationTime) { return new IsabelleResult(Type.TIMEOUT, computationTime, null, null); } public static IsabelleResult getErrorResult(Exception exception) { - return new IsabelleResult(Type.ERROR, -1, null, exception); + return new IsabelleResult(Type.ERROR, null, null, exception); } - public static IsabelleResult getSuccessResult(String successfulTactic, long computationTime) { + public static IsabelleResult getSuccessResult(String successfulTactic, Duration computationTime) { return new IsabelleResult(Type.SUCCESS, computationTime, successfulTactic, null); } + public static IsabelleResult getInterruptedResult() { + return new IsabelleResult(Type.INTERRUPTED, null, null, null); + } + + public static IsabelleResult getUnknownResult() { + return new IsabelleResult(Type.UNKNOWN, null, null, null); + } + public boolean isError() { return type == Type.ERROR; } @@ -62,7 +78,7 @@ public boolean isTimeout() { return type == Type.TIMEOUT; } - public long getComputationTime() { + public Duration getComputationTime() { return this.computationTime; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java index 9a833beb291..5f19e0deaa4 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java @@ -7,8 +7,13 @@ import de.uka.ilkd.key.settings.Configuration; import javax.swing.*; +import java.math.RoundingMode; public class IsabelleSettingsProvider extends SettingsPanel implements SettingsProvider { + public static final String INFO_TIMEOUT_FIELD = + """ + Timeout for the external solvers in seconds. Fractions of a second are allowed. Example: 6.5 + """; private static final String infoTranslationPathPanel = """ Choose where the isabelle translation files are stored. @@ -20,6 +25,8 @@ public class IsabelleSettingsProvider extends SettingsPanel implements SettingsP private final JTextField translationPathPanel; private final JTextField isabellePathPanel; + private final JSpinner timeoutField; + private final IsabelleTranslationSettings settings; public IsabelleSettingsProvider() { super(); @@ -28,6 +35,8 @@ public IsabelleSettingsProvider() { "Isabelle settings are stored in: " + IsabelleTranslationSettings.SETTINGS_FILE_NEW.getAbsolutePath()); translationPathPanel = createTranslationPathPanel(); isabellePathPanel = createIsabellePathPanel(); + timeoutField = createTimeoutField(); + this.settings = IsabelleTranslationSettings.getInstance(); } @Override @@ -42,23 +51,37 @@ public JPanel getPanel(MainWindow window) { return this; } - protected JTextField createTranslationPathPanel() { + private JTextField createTranslationPathPanel() { return addFileChooserPanel("Store translation to file:", "", infoTranslationPathPanel, true, e -> { }); } - protected JTextField createIsabellePathPanel() { + private JTextField createIsabellePathPanel() { return addFileChooserPanel("Isabelle folder:", "", infoIsabellePathPanel, true, e -> { }); } + private JSpinner createTimeoutField() { + // Use doubles so that the formatter doesn't make every entered String into integers. + // [see NumberFormatter#stringToValue()]. + JSpinner timeoutSpinner = addNumberField("Timeout:", 1, Integer.MAX_VALUE, 1, + INFO_TIMEOUT_FIELD, + e -> settings.setTimeout(e.intValue())); + // Set the editor so that entered Strings only have three decimal places. + JSpinner.NumberEditor editor = new JSpinner.NumberEditor(timeoutSpinner, "#"); + // Use floor rounding to be consistent with the value that will be set for the timeout. + editor.getFormat().setRoundingMode(RoundingMode.FLOOR); + timeoutSpinner.setEditor(editor); + return timeoutSpinner; + } + @Override public void applySettings(MainWindow window) throws InvalidSettingsInputException { Configuration newConfig = new Configuration(); newConfig.set(IsabelleTranslationSettings.translationPathKey, translationPathPanel.getText()); newConfig.set(IsabelleTranslationSettings.isabellePathKey, isabellePathPanel.getText()); - IsabelleTranslationSettings.getInstance().readSettings(newConfig); + settings.readSettings(newConfig); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java similarity index 67% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java index c86e65e67ee..067d4bde2b4 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverInstance.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java @@ -16,13 +16,14 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; +import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -public class IsabelleSolverInstance implements IsabelleSolver, Runnable { +public class IsabelleSledgehammerSolver implements IsabelleSolver { private final int solverIndex; private IsabelleResult result; @@ -33,17 +34,6 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { */ private final IsabelleProblem problem; - /** - * The thread that is associated with this solver. - */ - private Thread thread; - - /** - * The timeout that is associated with this solver. Represents the timertask that is started - * when the solver is started. - */ - private IsabelleSolverTimeout solverTimeout; - /** * stores the reason for interruption if present (e.g. User, Timeout, Exception) */ @@ -57,7 +47,7 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { /** * Stores the settings that are used for the execution. */ - private IsabelleTranslationSettings isabelleSettings; + private final IsabelleTranslationSettings isabelleSettings; /** * If there was an exception while executing the solver it is stored in this attribute. @@ -67,25 +57,26 @@ public class IsabelleSolverInstance implements IsabelleSolver, Runnable { /** * The timeout in seconds for this SMT solver run. */ - private long timeout = -1; + private int timeout; - private long startTime; + private Instant startTime; - private long computationTime; + private java.time.Duration computationTime; private final IsabelleResourceController resourceController; - private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSolverInstance.class); + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSledgehammerSolver.class); private final Collection listeners; - public IsabelleSolverInstance(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { + public IsabelleSledgehammerSolver(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { this.problem = problem; this.solverIndex = solverIndex; this.listeners = new HashSet<>(); this.listeners.addAll(listeners); this.resourceController = resourceController; this.isabelleSettings = settings; + this.timeout = isabelleSettings.getTimeout(); } @Override @@ -121,20 +112,17 @@ public Throwable getException() { @Override public void interrupt(ReasonOfInterruption reason) { setReasonOfInterruption(reason); - this.result = IsabelleResult.getErrorResult(new TimeoutException()); - setSolverState(SolverState.Stopped); - if (solverTimeout != null) { - solverTimeout.cancel(); - } - if (thread != null) { - thread.interrupt(); - } + this.result = IsabelleResult.getInterruptedResult(); if (isabelleResource != null) { returnResource(); } + setSolverState(SolverState.Stopped); } private void returnResource() { + if (isabelleResource == null) { + return; + } resourceController.returnResource(this, isabelleResource); isabelleResource = null; } @@ -148,17 +136,17 @@ public void setReasonOfInterruption(ReasonOfInterruption reasonOfInterruption) { } @Override - public long getStartTime() { + public Instant getStartTime() { return startTime; } @Override - public long getTimeout() { + public int getTimeout() { return this.timeout; } @Override - public void setTimeout(long timeout) { + public void setTimeout(int timeout) { this.timeout = timeout; } @@ -167,31 +155,11 @@ public SolverState getState() { return solverState; } - @Override - public boolean wasInterrupted() { - return reasonOfInterruption != ReasonOfInterruption.NoInterruption; - } - @Override public boolean isRunning() { return solverState == SolverState.Running; } - @Override - public void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings) { - thread = new Thread(this, "IsabelleSolverInstance: " + getProblem().getName()); - this.solverTimeout = timeout; - isabelleSettings = settings; - - //TODO probably want asynchronous behavior - thread.start(); - try { - thread.join(); - } catch (InterruptedException e) { - thread.interrupt(); - } - } - @Override public String getRawSolverOutput() { return result.getSuccessfulTactic(); @@ -207,68 +175,53 @@ public IsabelleResult getFinalResult() { return this.result; } + @Override - public void run() { + public IsabelleResult call() throws InterruptedException { //Ensure there is an active IsabelleInstance setSolverState(SolverState.Preparing); try { isabelleResource = resourceController.getIsabelleResource(this); } catch (InterruptedException e) { - notifyProcessError(e); - return; + return handleInterrupt(); } notifyProcessStarted(); - startTime = System.currentTimeMillis(); + startTime = Instant.now(); Isabelle isabelle = isabelleResource.instance(); - ToplevelState toplevel = ToplevelState.apply(isabelle); - LOGGER.info("Parsing theory for: " + problem.getName()); + + LOGGER.info("Parsing theory for: {}", problem.getName()); setSolverState(SolverState.Parsing); - notifyParsingStarted(); + ToplevelState toplevel = ToplevelState.apply(isabelle); try { toplevel = parseTheory(toplevel, isabelleResource); } catch (InterruptedException e) { - setSolverState(SolverState.Stopped); - notifyParsingError(e); - returnResource(); - return; + return handleInterrupt(); } catch (IsabelleMLException e) { - setSolverState(SolverState.Stopped); - returnResource(); - notifyParsingError(e); - return; + return handleIsabelleError(e); } - notifyParsingFinished(); - LOGGER.debug("Finished Parsing"); + LOGGER.info("Finished Parsing"); - setSolverState(SolverState.Running); - notifySledgehammerStarted(); + setSolverState(SolverState.Running); try { this.result = sledgehammer(isabelleResource, toplevel); - computationTime = System.currentTimeMillis() - startTime; - notifySledgehammerFinished(); + computationTime = java.time.Duration.between(startTime, Instant.now()); } catch (TimeoutException e) { - setReasonOfInterruption(ReasonOfInterruption.Timeout); - computationTime = System.currentTimeMillis() - startTime; this.result = IsabelleResult.getTimeoutResult(computationTime); - notifySledgehammerFinished(); + computationTime = java.time.Duration.between(startTime, Instant.now()); } catch (InterruptedException e) { - this.result = IsabelleResult.getErrorResult(e); - notifySledgehammerError(e); + return handleInterrupt(); } catch (IsabelleMLException e) { - this.result = IsabelleResult.getErrorResult(e); - setReasonOfInterruption(ReasonOfInterruption.Exception); - notifySledgehammerError(e); - } finally { - returnResource(); - //getProblem().setResult(this.result); - setSolverState(SolverState.Stopped); - notifyProcessFinished(); - LOGGER.info("Sledgehammer result: {}", this.result.getDescription()); + return handleIsabelleError(e); } + LOGGER.info("Sledgehammer result: {}", this.result.getDescription()); + returnResource(); + setSolverState(SolverState.Stopped); + notifyProcessFinished(); + return this.result; } private ToplevelState parseTheory(ToplevelState toplevel, IsabelleResourceController.IsabelleResource resource) throws InterruptedException, IsabelleMLException { @@ -276,7 +229,7 @@ private ToplevelState parseTheory(ToplevelState toplevel, IsabelleResourceContro Isabelle isabelle = resource.instance(); Theory thy0 = resource.theory(); - if (wasInterrupted()) { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } MLFunction2>> parse_text = MLValue.compileFunction(""" @@ -291,27 +244,21 @@ private ToplevelState parseTheory(ToplevelState toplevel, IsabelleResourceContro in addtext (Symbol.explode text) transitions end""", isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); - if (wasInterrupted()) { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); java.util.List> transitionsAndTexts = new ArrayList<>(); - Future>> transitionList = parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, + List> transitionList = parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieve(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle); - try { - Await.result(transitionList, Duration.create(1, TimeUnit.HOURS)) - .foreach(transitionsAndTexts::add); - } catch (TimeoutException e) { - //Should not be reached - throw new RuntimeException(e); - } + .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle); + transitionList.foreach(transitionsAndTexts::add); for (Tuple2 transitionAndText : transitionsAndTexts) { //println(s"""Transition: "${text.strip}"""") - if (reasonOfInterruption != ReasonOfInterruption.NoInterruption) { + if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } result = command_exception.apply(Boolean.TRUE, transitionAndText._1(), result, isabelle, @@ -342,7 +289,7 @@ fun go_run (state, thy) = val ctxt = Proof.context_of p_state; val params =\s""" + Sledgehammer_Commands + """ .default_params thy - [("timeout",\"""" + timeout + """ + [("timeout",\"""" + (double) timeout + """ "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; val results =\s""" + sledgehammer + """ @@ -376,52 +323,33 @@ fun go_run (state, thy) = if (successful) { result = IsabelleResult.getSuccessResult(resultFutureCollect._2()._2().head(), computationTime); } else { - result = IsabelleResult.getTimeoutResult(computationTime); + result = IsabelleResult.getUnknownResult(); } this.result = result; return this.result; } - @Override - public long getComputationTime() { - return computationTime; - } - - - private void notifyParsingStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.parsingStarted(this, getProblem()); - } - } - - private void notifyParsingFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.parsingFinished(this, getProblem()); - } - } - - private void notifyParsingError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.parsingFailed(this, getProblem(), e); - } - } - - private void notifyBuildingStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.buildingStarted(this, getProblem()); - } + private IsabelleResult handleInterrupt() { + this.result = IsabelleResult.getInterruptedResult(); + returnResource(); + Thread.currentThread().interrupt(); + setSolverState(SolverState.Stopped); + notifyProcessError(new InterruptedException()); + return this.result; } - private void notifyBuildingFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.buildingFinished(this, getProblem()); - } + private IsabelleResult handleIsabelleError(Exception e) { + this.result = IsabelleResult.getErrorResult(e); + this.exception = e; + returnResource(); + setSolverState(SolverState.Stopped); + notifyProcessError(e); + return this.result; } - private void notifyBuildingError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.buildingFailed(this, getProblem(), e); - } + @Override + public java.time.Duration getComputationTime() { + return computationTime; } private void notifyProcessStarted() { @@ -438,35 +366,7 @@ private void notifyProcessFinished() { private void notifyProcessError(Exception e) { for (IsabelleSolverListener listener : listeners) { - listener.processInterrupted(this, getProblem(), e); - } - } - - private void notifyProcessTimeout() { - for (IsabelleSolverListener listener : listeners) { - listener.processTimeout(this, getProblem()); - } - } - - private void notifySledgehammerStarted() { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerStarted(this, getProblem()); + listener.processError(this, getProblem(), e); } } - - private void notifySledgehammerFinished() { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerFinished(this, getProblem()); - } - } - - private void notifySledgehammerError(Exception e) { - for (IsabelleSolverListener listener : listeners) { - listener.sledgehammerFailed(this, getProblem(), e); - } - } - - public void removeListener(IsabelleSolverListener listener) { - listeners.remove(listener); - } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java index 0835c0cd1fb..babfb5f3143 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java @@ -1,14 +1,16 @@ package org.key_project.isabelletranslation; -import java.util.TimerTask; +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.Callable; -public interface IsabelleSolver { +public interface IsabelleSolver extends Callable { int getSolverIndex(); ReasonOfInterruption getReasonOfInterruption(); enum ReasonOfInterruption { - User, Timeout, Exception, NoInterruption + User, NoInterruption } enum SolverState{ @@ -25,40 +27,22 @@ enum SolverState{ void interrupt(ReasonOfInterruption reason); - long getStartTime(); + Instant getStartTime(); - long getComputationTime(); + Duration getComputationTime(); - long getTimeout(); + int getTimeout(); - void setTimeout(long timeout); + void setTimeout(int timeout); SolverState getState(); - boolean wasInterrupted(); - boolean isRunning(); - void start(IsabelleSolverTimeout timeout, IsabelleTranslationSettings settings); - String getRawSolverOutput(); String getRawSolverInput(); IsabelleResult getFinalResult(); - - class IsabelleSolverTimeout extends TimerTask { - private final IsabelleSolver solver; - - public IsabelleSolverTimeout(IsabelleSolver solver) { - this.solver = solver; - } - - @Override - public void run() { - solver.interrupt(ReasonOfInterruption.Timeout); - } - } - } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java index 2c4de318195..282faf18048 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java @@ -1,29 +1,9 @@ package org.key_project.isabelletranslation; -public interface IsabelleSolverListener extends IsabelleLauncherListener { - void parsingStarted(IsabelleSolver solver, IsabelleProblem problem); - - void parsingFinished(IsabelleSolver solver, IsabelleProblem problem); - - void parsingFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); - - void buildingStarted(IsabelleSolver solver, IsabelleProblem problem); - - void buildingFinished(IsabelleSolver solver, IsabelleProblem problem); - - void buildingFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); - +public interface IsabelleSolverListener { void processStarted(IsabelleSolver solver, IsabelleProblem problem); - void processInterrupted(IsabelleSolver solver, IsabelleProblem problem, Exception e); + void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e); void processStopped(IsabelleSolver solver, IsabelleProblem problem); - - void processTimeout(IsabelleSolver solver, IsabelleProblem problem); - - void sledgehammerStarted(IsabelleSolver solver, IsabelleProblem problem); - - void sledgehammerFinished(IsabelleSolver solver, IsabelleProblem problem); - - void sledgehammerFailed(IsabelleSolver solver, IsabelleProblem problem, Exception e); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java index 95eaa483ee9..afcaf23730b 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java @@ -13,6 +13,7 @@ import java.io.*; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Objects; import java.util.Properties; import java.util.stream.Collectors; @@ -24,28 +25,24 @@ public class IsabelleTranslationSettings extends AbstractSettings { protected static final String isabellePathKey = "Path"; protected static final String translationPathKey = "TranslationPath"; + protected static final String timeoutKey = "Timeout"; private Path isabellePath; private Path translationPath; private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); - private boolean sessionFilesPresent = false; + private int timeoutSeconds; private static Configuration getDefaultConfig() { Configuration config = new Configuration(); config.set(isabellePathKey, DEFAULT_ISABELLE_PATH); config.set(translationPathKey, DEFAULT_TRANSLATION_PATH); + config.set(timeoutKey, 30); return config; } private IsabelleTranslationSettings(Configuration load) { readSettings(load); - Path rootPath = Path.of(translationPath + "/ROOT"); - Path documentPath = Path.of(translationPath + "/documents/root.tex"); - - if (!rootPath.toFile().exists() || !documentPath.toFile().exists()) { - sessionFilesPresent = false; - } Runtime.getRuntime().addShutdownHook(new Thread(this::save)); } @@ -77,11 +74,11 @@ public static IsabelleTranslationSettings getInstance() { protected boolean createSessionFiles() { Path sessionRootPath = Path.of(translationPath + "/ROOT"); - BufferedReader sessionReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("ROOT"))); + BufferedReader sessionReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(getClass().getResourceAsStream("ROOT")))); String sessionRoot = sessionReader.lines().collect(Collectors.joining(System.lineSeparator())); Path sessionDocumentPath = Path.of(translationPath + "/document/root.tex"); - BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("root.tex"))); + BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(getClass().getResourceAsStream("root.tex")))); String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining(System.lineSeparator())); try { @@ -89,15 +86,15 @@ protected boolean createSessionFiles() { Files.write(sessionRootPath, sessionRoot.getBytes()); Files.write(sessionDocumentPath, sessionDocument.getBytes()); LOGGER.info("Created Isabelle session files at: {}", translationPath); - return sessionFilesPresent = true; + return true; } catch (IOException e) { LOGGER.error("Failed to create ROOT file for Isabelle Translation, because: {}", e.toString()); - return sessionFilesPresent = false; + return false; } } public void save() { - LOGGER.info("Save Isabelle settings to: " + SETTINGS_FILE_NEW.getAbsolutePath()); + LOGGER.info("Save Isabelle settings to: {}", SETTINGS_FILE_NEW.getAbsolutePath()); try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { var config = new Configuration(); writeSettings(config); @@ -114,14 +111,16 @@ public void readSettings(Properties props) { Path newTranslationPath = Path.of(props.getProperty(translationPathKey)); if (newTranslationPath != translationPath) { translationPath = newTranslationPath; - sessionFilesPresent = createSessionFiles(); + createSessionFiles(); } + timeoutSeconds = Integer.parseInt(props.getProperty(timeoutKey, "30")); } @Override public void writeSettings(Properties props) { props.setProperty(isabellePathKey, isabellePath.toString()); props.setProperty(translationPathKey, translationPath.toString()); + props.setProperty(timeoutKey, String.valueOf(timeoutSeconds)); } @Override @@ -135,17 +134,28 @@ public void readSettings(@NonNull Configuration props) { Path newTranslationPath = Path.of(props.getString(translationPathKey, translationPath.toString())); if (newTranslationPath != translationPath) { translationPath = newTranslationPath; - sessionFilesPresent = createSessionFiles(); + createSessionFiles(); } + + timeoutSeconds = props.getInt(timeoutKey, 30); } @Override public void writeSettings(@NonNull Configuration props) { props.set(isabellePathKey, isabellePath.toString()); props.set(translationPathKey, translationPath.toString()); + props.set(timeoutKey, String.valueOf(timeoutSeconds)); } public String getHeader() { return "theory Translation imports Main KeYTranslations.TranslationPreamble begin"; } + + public int getTimeout() { + return this.timeoutSeconds; + } + + public void setTimeout(int i) { + timeoutSeconds = i; + } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java index dfc7e1fef53..b3e8a78c6ef 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java @@ -59,9 +59,9 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings, mediator.getSelectedProof())); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); try { - launcher.try0ThenSledgehammerAllPooled(translations, 30, 1); + launcher.try0ThenSledgehammerAllPooled(translations, settings.getTimeout(), 1); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java index f994d730e8a..cdaeae1c124 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java @@ -56,9 +56,9 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(settings, mediator.getSelectedProof())); + launcher.addListener(new IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); try { - launcher.try0ThenSledgehammerAllPooled(list, 30, 1); + launcher.try0ThenSledgehammerAllPooled(list, settings.getTimeout(), 1); } catch (IOException e) { throw new RuntimeException(e); } @@ -74,10 +74,9 @@ protected static void writeTranslationFiles(IsabelleProblem translation) { Files.createDirectories(translationFile.toPath().getParent()); Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); - LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); + LOGGER.info("Saved to: {} and {}", translationFile.toPath(), translationPreambleFile.toPath()); } catch (IOException e) { LOGGER.error("Failed to save translation", e); - return; } } } From 27f50837ecefe949a30912e6f93463d212d76210 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Tue, 8 Oct 2024 16:40:03 +0200 Subject: [PATCH 237/248] package refactoring --- .../isabelletranslation/IsabelleProblem.java | 33 -- .../IsabelleSolverListener.java | 9 - .../TranslateAllAction.java | 37 +-- .../TranslationAction.java | 20 +- .../{ => automation}/IsabelleLauncher.java | 13 +- .../IsabelleLauncherListener.java | 2 +- ...sabelleLauncherProgressDialogMediator.java | 2 +- .../automation/IsabelleProblem.java | 55 ++++ .../IsabelleResourceController.java | 3 +- .../{ => automation}/IsabelleResult.java | 2 +- .../IsabelleSledgehammerSolver.java | 3 +- .../{ => automation}/IsabelleSolver.java | 2 +- .../automation/IsabelleSolverListener.java | 307 ++++++++++++++++++ .../gui/ProofApplyUserAction.java | 4 +- .../{ => translation}/BSumHandler.java | 2 +- .../{ => translation}/BooleanOpHandler.java | 2 +- .../DefinedSymbolsHandler.java | 2 +- .../{ => translation}/FieldHandler.java | 2 +- .../IllegalFormulaException.java | 2 +- .../InfiniteUnionHandler.java | 2 +- .../InstanceOperatorHandler.java | 2 +- .../{ => translation}/IntegerOpHandler.java | 2 +- .../{ => translation}/IsabelleHandler.java | 2 +- .../IsabelleHandlerServices.java | 2 +- .../IsabelleMasterHandler.java | 2 +- .../{ => translation}/IsabelleTranslator.java | 4 +- .../LogicalVariableHandler.java | 2 +- .../NumberConstantsHandler.java | 2 +- .../ObserverFunctionHandler.java | 2 +- .../{ => translation}/PolymorphicHandler.java | 2 +- .../{ => translation}/QuantifierHandler.java | 2 +- .../{ => translation}/SeqDefHandler.java | 2 +- .../SortDependingFunctionHandler.java | 2 +- .../UninterpretedSymbolsHandler.java | 2 +- .../isabelletranslation/defaultHandlers.txt | 15 - .../IntegerOpHandler.preamble.xml | 0 .../UninterpretedSymbolsHandler.preamble.xml | 0 .../translation/defaultHandlers.txt | 15 + 38 files changed, 432 insertions(+), 132 deletions(-) delete mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java delete mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleLauncher.java (93%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleLauncherListener.java (86%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleLauncherProgressDialogMediator.java (99%) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleResourceController.java (98%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleResult.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleSledgehammerSolver.java (99%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => automation}/IsabelleSolver.java (93%) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/BSumHandler.java (96%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/BooleanOpHandler.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/DefinedSymbolsHandler.java (98%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/FieldHandler.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IllegalFormulaException.java (86%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/InfiniteUnionHandler.java (95%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/InstanceOperatorHandler.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IntegerOpHandler.java (98%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IsabelleHandler.java (98%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IsabelleHandlerServices.java (99%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IsabelleMasterHandler.java (99%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/IsabelleTranslator.java (98%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/LogicalVariableHandler.java (95%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/NumberConstantsHandler.java (96%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/ObserverFunctionHandler.java (96%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/PolymorphicHandler.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/QuantifierHandler.java (96%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/SeqDefHandler.java (96%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/SortDependingFunctionHandler.java (97%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => translation}/UninterpretedSymbolsHandler.java (98%) delete mode 100644 keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt rename keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/{ => translation}/IntegerOpHandler.preamble.xml (100%) rename keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/{ => translation}/UninterpretedSymbolsHandler.preamble.xml (100%) create mode 100644 keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/defaultHandlers.txt diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java deleted file mode 100644 index 4461f2d50b5..00000000000 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleProblem.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.key_project.isabelletranslation; - -import de.uka.ilkd.key.proof.Goal; - -public class IsabelleProblem { - private final Goal goal; - private final String preamble; - private final String sequentTranslation; - private final String name; - - public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { - this.goal = goal; - this.preamble = preamble; - this.sequentTranslation = sequentTranslation; - this.name = "Goal " + goal.node().serialNr(); - } - - public Goal getGoal() { - return goal; - } - - public String getSequentTranslation() { - return sequentTranslation; - } - - public String getPreamble() { - return preamble; - } - - public String getName() { - return name; - } -} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java deleted file mode 100644 index 282faf18048..00000000000 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolverListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.key_project.isabelletranslation; - -public interface IsabelleSolverListener { - void processStarted(IsabelleSolver solver, IsabelleProblem problem); - - void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e); - - void processStopped(IsabelleSolver solver, IsabelleProblem problem); -} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java index b3e8a78c6ef..175de313248 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java @@ -6,6 +6,12 @@ import de.uka.ilkd.key.proof.Goal; import de.uka.ilkd.key.rule.IBuiltInRuleApp; import de.uka.ilkd.key.smt.SMTRuleApp; +import org.key_project.isabelletranslation.automation.IsabelleLauncher; +import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.isabelletranslation.automation.IsabelleResult; +import org.key_project.isabelletranslation.automation.IsabelleSolverListener; +import org.key_project.isabelletranslation.translation.IllegalFormulaException; +import org.key_project.isabelletranslation.translation.IsabelleTranslator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,6 +40,7 @@ public void actionPerformed(ActionEvent e) { private void generateTranslation() { KeYMediator mediator = getMediator(); + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); List translations = new ArrayList<>(); @@ -46,12 +53,9 @@ private void generateTranslation() { return; } - writeTranslationFiles(translations.get(0)); + translations.get(0).writeTranslationFiles(settings); - IsabelleResult result = null; Thread thread = new Thread(() -> { - - IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleLauncher launcher; try { launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); @@ -59,7 +63,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); + launcher.addListener(new IsabelleSolverListener.IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); try { launcher.try0ThenSledgehammerAllPooled(translations, settings.getTimeout(), 1); } catch (IOException e) { @@ -68,28 +72,5 @@ private void generateTranslation() { }, "IsabelleControlThread"); thread.start(); - //result = translation.getResult(); - //SledgehammerResult result = translation.sledgehammer(30); - - //TODO needs its own action to enable undo, etc. and naming reworks - if (result != null && result.isSuccessful()) { - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("Isabelle " + result.getSuccessfulTactic()); - app.tryToInstantiate(mediator.getSelectedGoal()); - mediator.getSelectedGoal().apply(app); - } - } - - protected static void writeTranslationFiles(IsabelleProblem translation) { - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); - File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); - Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); - LOGGER.info("Saved to: " + translationFile.toPath() + " and " + translationPreambleFile.toPath()); - } catch (IOException e) { - LOGGER.error("Failed to save translation", e); - return; - } } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java index cdaeae1c124..23e952c0bf7 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java @@ -3,6 +3,11 @@ import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; +import org.key_project.isabelletranslation.automation.IsabelleLauncher; +import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.isabelletranslation.automation.IsabelleSolverListener; +import org.key_project.isabelletranslation.translation.IllegalFormulaException; +import org.key_project.isabelletranslation.translation.IsabelleTranslator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,7 +61,7 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); + launcher.addListener(new IsabelleSolverListener.IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); try { launcher.try0ThenSledgehammerAllPooled(list, settings.getTimeout(), 1); } catch (IOException e) { @@ -66,17 +71,4 @@ private void generateTranslation() { }, "IsabelleLauncherThread"); thread.start(); } - - protected static void writeTranslationFiles(IsabelleProblem translation) { - File translationFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/Translation.thy"); - File translationPreambleFile = new File(IsabelleTranslationSettings.getInstance().getTranslationPath() + "/TranslationPreamble.thy"); - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationPreambleFile.toPath(), translation.getPreamble().getBytes()); - Files.write(translationFile.toPath(), translation.getSequentTranslation().getBytes()); - LOGGER.info("Saved to: {} and {}", translationFile.toPath(), translationPreambleFile.toPath()); - } catch (IOException e) { - LOGGER.error("Failed to save translation", e); - } - } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java similarity index 93% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index a9d005f3f30..44a656af6a8 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -1,10 +1,14 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import org.jspecify.annotations.NonNull; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; +import org.key_project.isabelletranslation.TranslationAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.util.*; import java.util.concurrent.*; @@ -36,6 +40,9 @@ public void try0ThenSledgehammerAllPooled(List problems, int ti return; } + //Ensure the preamble theory is present + problems.get(0).writeTranslationFiles(settings); + IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); executorService = Executors.newFixedThreadPool(instanceCount); @@ -59,10 +66,6 @@ public void try0ThenSledgehammerAllPooled(List problems, int ti resourceController.init(); listener.launcherPreparationFinished(this, solverSet); - - //Ensure the preamble theory is present - TranslationAction.writeTranslationFiles(problems.get(0)); - LOGGER.info("Setup complete, starting {} problems...", problems.size()); try { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java similarity index 86% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java index a546cfb3e6c..bf71536ccc2 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import java.util.Collection; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java index 11518bc0835..c2551f1a046 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java new file mode 100644 index 00000000000..b8247647a16 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java @@ -0,0 +1,55 @@ +package org.key_project.isabelletranslation.automation; + +import de.uka.ilkd.key.proof.Goal; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +public class IsabelleProblem { + private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); + + private final Goal goal; + private final String preamble; + private final String sequentTranslation; + private final String name; + + public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { + this.goal = goal; + this.preamble = preamble; + this.sequentTranslation = sequentTranslation; + this.name = "Goal " + goal.node().serialNr(); + } + + public Goal getGoal() { + return goal; + } + + public String getSequentTranslation() { + return sequentTranslation; + } + + public String getPreamble() { + return preamble; + } + + public String getName() { + return name; + } + + public void writeTranslationFiles(IsabelleTranslationSettings settings) { + File translationFile = new File(settings.getTranslationPath() + "/Translation.thy"); + File translationPreambleFile = new File(settings.getTranslationPath() + "/TranslationPreamble.thy"); + try { + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationPreambleFile.toPath(), this.getPreamble().getBytes()); + Files.write(translationFile.toPath(), this.getSequentTranslation().getBytes()); + LOGGER.info("Saved to: {} and {}", translationFile.toPath(), translationPreambleFile.toPath()); + } catch (IOException e) { + LOGGER.error("Failed to save translation", e); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java index 061ffde651f..f64c7efd014 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; @@ -11,6 +11,7 @@ import de.unruh.isabelle.pure.Position; import de.unruh.isabelle.pure.Theory; import de.unruh.isabelle.pure.TheoryHeader; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import scala.collection.immutable.List; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java index b3148314d06..5835118abcf 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleResult.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import java.time.Duration; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java index 067d4bde2b4..4dfbefdfc60 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSledgehammerSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; @@ -7,6 +7,7 @@ import de.unruh.isabelle.pure.Theory; import de.unruh.isabelle.pure.ToplevelState; import de.unruh.isabelle.pure.Transition; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java similarity index 93% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java index babfb5f3143..65985753ac7 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.automation; import java.time.Duration; import java.time.Instant; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java new file mode 100644 index 00000000000..d5a4d301b31 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java @@ -0,0 +1,307 @@ +package org.key_project.isabelletranslation.automation; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.colors.ColorSettings; +import de.uka.ilkd.key.proof.Proof; +import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; +import org.key_project.isabelletranslation.gui.IsabelleProgressModel; +import org.key_project.isabelletranslation.gui.ProofApplyUserAction; + +import javax.swing.*; +import java.awt.*; +import java.text.DecimalFormat; +import java.time.Duration; +import java.time.Instant; +import java.util.Collection; +import java.util.Timer; +import java.util.TimerTask; + +public interface IsabelleSolverListener { + void processStarted(IsabelleSolver solver, IsabelleProblem problem); + + void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e); + + void processStopped(IsabelleSolver solver, IsabelleProblem problem); + + class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { + private static final DecimalFormat remainingTimeFormat = new DecimalFormat("#.#"); + private final Timer timer = new Timer(); + private int finishedCounter = 0; + + private final Proof proof; + + + private final static ColorSettings.ColorProperty RED = + ColorSettings.define("[isabelleDialog]red", "", new Color(180, 43, 43)); + + private final static ColorSettings.ColorProperty GREEN = + ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); + private boolean userStopFlag = false; + + @Override + public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { + timer.cancel(); + + progressModel.setEditable(true); + refreshDialog(); + progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); + } + + @Override + public void launcherStarted(IsabelleLauncher launcher, Collection solvers) { + prepareDialog(solvers, launcher); + + setProgressText(-1); + timer.schedule(new TimerTask() { + @Override + public void run() { + refreshDialog(); + } + }, 0, 10); + } + + @Override + public void launcherPreparationFinished(IsabelleLauncher launcher, Collection solvers) { + setProgressText(0); + } + + protected void stopEvent(IsabelleLauncher launcher) { + userStopFlag = true; + launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); + } + + protected void applyEvent(IsabelleLauncher launcher) { + launcher.stopAll(IsabelleSolver.ReasonOfInterruption.NoInterruption); + applyResults(); + progressDialog.dispose(); + } + + private void applyResults() { + KeYMediator mediator = MainWindow.getInstance().getMediator(); + // ensure that the goal closing does not lag the UI + mediator.stopInterface(true); + try { + new ProofApplyUserAction(mediator, proof, solvers).actionPerformed(null); + } finally { + mediator.startInterface(true); + //switch to new open goal + mediator.getSelectionModel().defaultSelection(); + } + } + + private void stopped(IsabelleSolver solver) { + int x = 0; + int y = solver.getSolverIndex(); + + if (!problemProcessed[x][y]) { + finishedCounter++; + progressDialog.setProgress(finishedCounter); + JProgressBar bar = progressDialog.getProgressBar(); + bar.setValue(finishedCounter); + setProgressText(finishedCounter); + problemProcessed[x][y] = true; + } + + IsabelleResult result = solver.getFinalResult(); + + switch (result.getType()) { + case INTERRUPTED: + interrupted(solver, x, y); + break; + case SUCCESS: + successfullyStopped(solver, x, y); + break; + case ERROR: + encounteredError(solver, x, y); + break; + case TIMEOUT: + timedOut(solver, x, y); + break; + default: + unknownStopped(x, y); + break; + } + } + + private void interrupted(IsabelleSolver solver, int x, int y) { + if (userStopFlag) { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by user.", x, y); + } else { + throw new RuntimeException("This position should not be reachable!"); + } + } + + private void successfullyStopped(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(GREEN.get(), x, y); + + String timeInfo = solver.getComputationTime().toMillis() / 1000d + "s"; + + progressModel.setText("Valid (" + timeInfo + ")", x, y); + } + + private void encounteredError(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(RED.get(), x, y); + progressModel.setText("Exception!", x, y); + } + + private void timedOut(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by User.", x, y); + } + + private void unknownStopped(int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(Color.BLUE, x, y); + progressModel.setText("Unknown.", x, y); + } + + private void setProgressText(int value) { + JProgressBar bar = progressDialog.getProgressBar(); + if (value == -1) { + bar.setString("Preparing... (this might take a few seconds)"); + bar.setStringPainted(true); + } else if (value == bar.getMaximum()){ + bar.setString("Finished."); + bar.setStringPainted(true); + } else { + bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); + bar.setStringPainted(true); + } + } + + protected void discardEvent(IsabelleLauncher launcher) { + launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); + progressDialog.dispose(); + } + + public IsabelleLauncherProgressDialogMediator(Proof proof) { + this.proof = proof; + } + + + private static final int RESOLUTION = 1000; + + private Collection solvers; + private IsabelleProgressModel progressModel; + private boolean[][] problemProcessed; + private IsabelleProgressDialog progressDialog; + + private void prepareDialog(Collection solvers, final IsabelleLauncher launcher) { + this.solvers = solvers; + progressModel = new IsabelleProgressModel(); + + String[] captions = new String[solvers.size()]; + + int i = 0; + for (IsabelleSolver solver : solvers) { + captions[i] = solver.getProblem().getName(); + i++; + } + + progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); + problemProcessed = new boolean[1][solvers.size()]; + progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); + + + progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, + RESOLUTION, solvers.size(), new String[] {}, "", "Isabelle"); + + + SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); + } + + private void refreshDialog() { + for (IsabelleSolver solver : solvers) { + refreshProgressOfSolver(solver); + } + } + + private void refreshProgressOfSolver(IsabelleSolver solver) { + IsabelleSolver.SolverState state = solver.getState(); + switch (state) { + case Preparing -> { + preparing(solver); + } + case Parsing -> { + parsing(solver); + } + case Running -> { + running(solver); + } + case Stopped -> { + stopped(solver); + } + case Waiting -> { + waiting(solver); + } + } + + } + + private void running(IsabelleSolver solver) { + long progress = calculateProgress(solver); + progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); + + float remainingTime = calculateRemainingTime(solver); + progressModel.setText(remainingTimeFormat.format(remainingTime) + " sec.", 0, solver.getSolverIndex()); + } + + private long calculateProgress(IsabelleSolver solver) { + Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); + Instant startTime = solver.getStartTime(); + + return RESOLUTION * (Duration.between(startTime, Instant.now()).toMillis() / maxDuration.toMillis()); + } + + private float calculateRemainingTime(IsabelleSolver solver) { + Instant timeoutTime = solver.getStartTime().plusSeconds(solver.getTimeout()); + return Duration.between(Instant.now(), timeoutTime).toMillis() / 1000f; + } + + private void parsing(IsabelleSolver solver) { + progressModel.setText("Parsing...", 0, solver.getSolverIndex()); + } + + private void waiting(IsabelleSolver solver) { + } + + private void preparing(IsabelleSolver solver) { + progressModel.setText("Preparing...", 0, solver.getSolverIndex()); + } + + private class IsabelleProgressDialogListenerImpl implements IsabelleProgressDialog.IsabelleProgressDialogListener { + + + private final IsabelleLauncher launcher; + + + public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { + super(); + this.launcher = launcher; + } + + @Override + public void infoButtonClicked(int column, int row) { + } + + @Override + public void stopButtonClicked() { + stopEvent(launcher); + } + + @Override + public void applyButtonClicked() { + applyEvent(launcher); + } + + @Override + public void discardButtonClicked() { + discardEvent(launcher); + } + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java index 2f39de0e3c2..6837f5fbfac 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java @@ -7,8 +7,8 @@ import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.rule.IBuiltInRuleApp; import de.uka.ilkd.key.smt.SMTRuleApp; -import org.key_project.isabelletranslation.IsabelleProblem; -import org.key_project.isabelletranslation.IsabelleSolver; +import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.isabelletranslation.automation.IsabelleSolver; import java.util.Collection; import java.util.HashSet; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java index 0508d1a249a..8e37d1d5249 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java index 69453d4a5ee..70059428c03 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.BooleanLDT; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java index 4ba998d25fe..00b93560d94 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java index 1a32309efd5..afcc30fb20d 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Name; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IllegalFormulaException.java similarity index 86% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IllegalFormulaException.java index 3d79f10eb6d..cf7a7d142eb 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IllegalFormulaException.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IllegalFormulaException.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; public class IllegalFormulaException extends Exception { /** diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java similarity index 95% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java index 8952470e078..62276b8a90a 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java index 626b138f936..c7c0bcae513 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java index c7b511b489f..7314293c3fd 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.IntegerLDT; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java index b3e041abea5..88df7fc5296 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java index 14d6ee2b405..02c7d47ab4c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleHandlerServices.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.jspecify.annotations.NonNull; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java similarity index 99% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java index d2000551d5e..970891afb87 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java index f4838457454..24b572833d8 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; @@ -6,6 +6,8 @@ import de.uka.ilkd.key.logic.SequentFormula; import de.uka.ilkd.key.logic.Term; import de.uka.ilkd.key.logic.sort.ArraySort; +import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.proof.Goal; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java similarity index 95% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java index e1f6b3f6336..a6699889106 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java index a9cda9c6a79..aae07917435 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java index 9bc3d50ee35..7efc9fe5470 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java index 0b272cadf9e..bd07032e379 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/PolymorphicHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java index 849a53d34d2..896ef5f7443 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java similarity index 96% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java index 14e161e7959..c3cd098983d 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SeqDefHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java similarity index 97% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java index 74f725cc29d..c051a71cdcc 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java @@ -1,4 +1,4 @@ -package org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import org.key_project.logic.Term; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java similarity index 98% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java index 6319b52a524..a7c532d1466 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java @@ -1,7 +1,7 @@ /* 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 org.key_project.isabelletranslation; +package org.key_project.isabelletranslation.translation; import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.HeapLDT; diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt deleted file mode 100644 index 190d34d901b..00000000000 --- a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/defaultHandlers.txt +++ /dev/null @@ -1,15 +0,0 @@ -org.key_project.isabelletranslation.DefinedSymbolsHandler -org.key_project.isabelletranslation.InstanceOperatorHandler -org.key_project.isabelletranslation.BooleanOpHandler -org.key_project.isabelletranslation.PolymorphicHandler -org.key_project.isabelletranslation.QuantifierHandler -org.key_project.isabelletranslation.LogicalVariableHandler -org.key_project.isabelletranslation.NumberConstantsHandler -org.key_project.isabelletranslation.IntegerOpHandler -org.key_project.isabelletranslation.InfiniteUnionHandler -org.key_project.isabelletranslation.BSumHandler -org.key_project.isabelletranslation.SeqDefHandler -org.key_project.isabelletranslation.SortDependingFunctionHandler -org.key_project.isabelletranslation.FieldHandler -org.key_project.isabelletranslation.ObserverFunctionHandler -org.key_project.isabelletranslation.UninterpretedSymbolsHandler \ No newline at end of file diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/IntegerOpHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/IntegerOpHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/IntegerOpHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/IntegerOpHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/UninterpretedSymbolsHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.preamble.xml diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/defaultHandlers.txt b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/defaultHandlers.txt new file mode 100644 index 00000000000..fbe87b62455 --- /dev/null +++ b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/defaultHandlers.txt @@ -0,0 +1,15 @@ +org.key_project.isabelletranslation.translation.DefinedSymbolsHandler +org.key_project.isabelletranslation.translation.InstanceOperatorHandler +org.key_project.isabelletranslation.translation.BooleanOpHandler +org.key_project.isabelletranslation.translation.PolymorphicHandler +org.key_project.isabelletranslation.translation.QuantifierHandler +org.key_project.isabelletranslation.translation.LogicalVariableHandler +org.key_project.isabelletranslation.translation.NumberConstantsHandler +org.key_project.isabelletranslation.translation.IntegerOpHandler +org.key_project.isabelletranslation.translation.InfiniteUnionHandler +org.key_project.isabelletranslation.translation.BSumHandler +org.key_project.isabelletranslation.translation.SeqDefHandler +org.key_project.isabelletranslation.translation.SortDependingFunctionHandler +org.key_project.isabelletranslation.translation.FieldHandler +org.key_project.isabelletranslation.translation.ObserverFunctionHandler +org.key_project.isabelletranslation.translation.UninterpretedSymbolsHandler \ No newline at end of file From d16bdd612f3bd347e1c59a85d4497f47b81c262b Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 10 Oct 2024 12:17:17 +0200 Subject: [PATCH 238/248] fix progress bars --- .../automation/IsabelleLauncherProgressDialogMediator.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java index c2551f1a046..3516fbcd794 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java @@ -247,7 +247,8 @@ private long calculateProgress(IsabelleSolver solver) { Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); Instant startTime = solver.getStartTime(); - return RESOLUTION * (Duration.between(startTime, Instant.now()).toMillis() / maxDuration.toMillis()); + return (long) Math.floor(RESOLUTION + * (Duration.between(startTime, Instant.now()).toMillis() / (double) maxDuration.toMillis())); } private float calculateRemainingTime(IsabelleSolver solver) { From c1b990e79d476faf1675146fee17230b29a7d180 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Fri, 11 Oct 2024 12:28:00 +0200 Subject: [PATCH 239/248] major documentation and spotless compliance push --- .../IsabelleSettingsProvider.java | 72 ++- .../IsabelleTranslationExtension.java | 31 +- .../IsabelleTranslationSettings.java | 127 +++-- .../automation/IsabelleLauncher.java | 163 ++++-- .../automation/IsabelleLauncherListener.java | 12 + ...sabelleLauncherProgressDialogMediator.java | 300 ----------- .../automation/IsabelleProblem.java | 121 ++++- .../automation/IsabelleResource.java | 48 ++ .../IsabelleResourceController.java | 221 +++++++-- .../automation/IsabelleResult.java | 137 ++++- .../IsabelleSledgehammerSolver.java | 314 +++++++----- .../automation/IsabelleSolver.java | 88 +++- .../automation/IsabelleSolverListener.java | 323 +----------- .../gui/IsabelleProgressDialog.java | 138 ++++-- .../gui/ProofApplyUserAction.java | 24 +- ...sabelleLauncherProgressDialogMediator.java | 469 ++++++++++++++++++ .../controller}/TranslateAllAction.java | 51 +- .../controller}/TranslationAction.java | 62 ++- .../translation/BSumHandler.java | 44 +- .../translation/BooleanOpHandler.java | 27 +- .../translation/DefinedSymbolsHandler.java | 126 +++-- .../translation/FieldHandler.java | 43 +- .../translation/InfiniteUnionHandler.java | 34 +- .../translation/InstanceOperatorHandler.java | 30 +- .../translation/IntegerOpHandler.java | 28 +- .../translation/IsabelleHandler.java | 62 +-- .../translation/IsabelleHandlerServices.java | 110 ++-- .../translation/IsabelleMasterHandler.java | 284 ++++++++--- .../translation/IsabelleTranslator.java | 355 +++++++++---- .../translation/LogicalVariableHandler.java | 29 +- .../translation/NumberConstantsHandler.java | 20 +- .../translation/ObserverFunctionHandler.java | 38 +- .../translation/PolymorphicHandler.java | 23 +- .../translation/QuantifierHandler.java | 50 +- .../translation/SeqDefHandler.java | 29 +- .../SortDependingFunctionHandler.java | 46 +- .../UninterpretedSymbolsHandler.java | 59 +-- ...xml => DefinedSymbolsHandler.preamble.xml} | 0 38 files changed, 2621 insertions(+), 1517 deletions(-) delete mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResource.java create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => gui/controller}/TranslateAllAction.java (61%) rename keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/{ => gui/controller}/TranslationAction.java (58%) rename keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/{UninterpretedSymbolsHandler.preamble.xml => DefinedSymbolsHandler.preamble.xml} (100%) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java index 5f19e0deaa4..9268586782c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleSettingsProvider.java @@ -1,38 +1,60 @@ +/* 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 org.key_project.isabelletranslation; +import java.math.RoundingMode; +import javax.swing.*; + import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.settings.InvalidSettingsInputException; import de.uka.ilkd.key.gui.settings.SettingsPanel; import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.settings.Configuration; -import javax.swing.*; -import java.math.RoundingMode; - +/** + * {@link SettingsProvider} for Isabelle translation extension + */ public class IsabelleSettingsProvider extends SettingsPanel implements SettingsProvider { - public static final String INFO_TIMEOUT_FIELD = - """ - Timeout for the external solvers in seconds. Fractions of a second are allowed. Example: 6.5 - """; + private static final String INFO_TIMEOUT_FIELD = + """ + Timeout for the external solvers in seconds. Fractions of a second are allowed. Example: 6.5 + """; private static final String infoTranslationPathPanel = - """ - Choose where the isabelle translation files are stored. - """; + """ + Choose where the isabelle translation files are stored. + """; private static final String infoIsabellePathPanel = - """ - Specify the absolute path of the Isabelle folder. - """; + """ + Specify the absolute path of the Isabelle folder. + """; + /** + * Panel for inputting the path to where translations are stored + */ private final JTextField translationPathPanel; + + /** + * Panel for inputting the path to Isabelle installation + */ private final JTextField isabellePathPanel; + + /** + * Input field for timeout in seconds + */ private final JSpinner timeoutField; + + /** + * The current settings object + */ private final IsabelleTranslationSettings settings; public IsabelleSettingsProvider() { super(); setHeaderText(getDescription()); setSubHeaderText( - "Isabelle settings are stored in: " + IsabelleTranslationSettings.SETTINGS_FILE_NEW.getAbsolutePath()); + "Isabelle settings are stored in: " + + IsabelleTranslationSettings.SETTINGS_FILE_NEW.getAbsolutePath()); translationPathPanel = createTranslationPathPanel(); isabellePathPanel = createIsabellePathPanel(); timeoutField = createTimeoutField(); @@ -46,29 +68,32 @@ public String getDescription() { @Override public JPanel getPanel(MainWindow window) { - isabellePathPanel.setText(IsabelleTranslationSettings.getInstance().getIsabellePath().toString()); - translationPathPanel.setText(IsabelleTranslationSettings.getInstance().getTranslationPath().toString()); + isabellePathPanel + .setText(settings.getIsabellePath().toString()); + translationPathPanel + .setText(settings.getTranslationPath().toString()); + timeoutField.setValue(settings.getTimeout()); return this; } private JTextField createTranslationPathPanel() { return addFileChooserPanel("Store translation to file:", "", infoTranslationPathPanel, - true, e -> { - }); + true, e -> { + }); } private JTextField createIsabellePathPanel() { return addFileChooserPanel("Isabelle folder:", "", infoIsabellePathPanel, - true, e -> { - }); + true, e -> { + }); } private JSpinner createTimeoutField() { // Use doubles so that the formatter doesn't make every entered String into integers. // [see NumberFormatter#stringToValue()]. JSpinner timeoutSpinner = addNumberField("Timeout:", 1, Integer.MAX_VALUE, 1, - INFO_TIMEOUT_FIELD, - e -> settings.setTimeout(e.intValue())); + INFO_TIMEOUT_FIELD, + e -> settings.setTimeout(e.intValue())); // Set the editor so that entered Strings only have three decimal places. JSpinner.NumberEditor editor = new JSpinner.NumberEditor(timeoutSpinner, "#"); // Use floor rounding to be consistent with the value that will be set for the timeout. @@ -80,7 +105,8 @@ private JSpinner createTimeoutField() { @Override public void applySettings(MainWindow window) throws InvalidSettingsInputException { Configuration newConfig = new Configuration(); - newConfig.set(IsabelleTranslationSettings.translationPathKey, translationPathPanel.getText()); + newConfig.set(IsabelleTranslationSettings.translationPathKey, + translationPathPanel.getText()); newConfig.set(IsabelleTranslationSettings.isabellePathKey, isabellePathPanel.getText()); settings.readSettings(newConfig); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java index cdf37c0ee67..8c8593aebaf 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationExtension.java @@ -1,5 +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 org.key_project.isabelletranslation; +import java.util.ArrayList; +import java.util.List; +import javax.swing.*; + import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.extension.api.ContextMenuAdapter; @@ -7,20 +14,19 @@ import de.uka.ilkd.key.gui.extension.api.KeYGuiExtension; import de.uka.ilkd.key.gui.settings.SettingsProvider; import de.uka.ilkd.key.pp.PosInSequent; -import org.jspecify.annotations.NonNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.swing.*; -import java.util.ArrayList; -import java.util.List; -@KeYGuiExtension.Info(name = "Isabelle Translation", optional = true, - experimental = false) -public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { +import org.key_project.isabelletranslation.gui.controller.TranslateAllAction; +import org.key_project.isabelletranslation.gui.controller.TranslationAction; - private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationExtension.class); +import org.jspecify.annotations.NonNull; +/** + * Extension class for Isabelle translation + */ +@KeYGuiExtension.Info(name = "Isabelle Translation", optional = true, + experimental = false) +public class IsabelleTranslationExtension implements KeYGuiExtension, KeYGuiExtension.Settings, + KeYGuiExtension.ContextMenu, KeYGuiExtension.Startup { @Override public SettingsProvider getSettings() { return new IsabelleSettingsProvider(); @@ -45,7 +51,8 @@ public List getContextActions( }; @Override - public @NonNull List getContextActions(@NonNull KeYMediator mediator, @NonNull ContextMenuKind kind, @NonNull Object underlyingObject) { + public @NonNull List getContextActions(@NonNull KeYMediator mediator, + @NonNull ContextMenuKind kind, @NonNull Object underlyingObject) { return adapter.getContextActions(mediator, kind, underlyingObject); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java index afcaf23730b..21a0d47eb73 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/IsabelleTranslationSettings.java @@ -3,13 +3,6 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation; -import de.uka.ilkd.key.settings.AbstractSettings; -import de.uka.ilkd.key.settings.Configuration; -import de.uka.ilkd.key.settings.PathConfig; -import org.jspecify.annotations.NonNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.*; import java.nio.file.Files; import java.nio.file.Path; @@ -17,27 +10,77 @@ import java.util.Properties; import java.util.stream.Collectors; +import de.uka.ilkd.key.settings.AbstractSettings; +import de.uka.ilkd.key.settings.Configuration; +import de.uka.ilkd.key.settings.PathConfig; + +import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Settings object used for Isabelle translation. + */ public class IsabelleTranslationSettings extends AbstractSettings { - protected static final File SETTINGS_FILE_NEW = - new File(PathConfig.getKeyConfigDir(), "isabelleSettings.json"); private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleTranslationSettings.class); + + /** + * the file where settings are stored + */ + protected static final File SETTINGS_FILE_NEW = + new File(PathConfig.getKeyConfigDir(), "isabelleSettings.json"); + /** + * The settings instance + */ private static IsabelleTranslationSettings INSTANCE; + /** + * Key to get Isabelle path in JSON + */ protected static final String isabellePathKey = "Path"; + /** + * Key to get translation path in JSON + */ protected static final String translationPathKey = "TranslationPath"; + /** + * Key to get timeout in JSON + */ protected static final String timeoutKey = "Timeout"; + + /** + * The Isabelle path + */ private Path isabellePath; + /** + * The translation path + */ private Path translationPath; - private static final Path DEFAULT_ISABELLE_PATH = Path.of(System.getProperty("user.home"), "Isabelle2023"); - private static final Path DEFAULT_TRANSLATION_PATH = Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); - + /** + * The timeout in seconds + */ private int timeoutSeconds; + /** + * The default path for Isabelle + */ + private static final Path DEFAULT_ISABELLE_PATH = + Path.of(System.getProperty("user.home"), "Isabelle2024-RC1"); + /** + * The default path for translations + */ + private static final Path DEFAULT_TRANSLATION_PATH = + Path.of(PathConfig.getKeyConfigDir(), "IsabelleTranslations"); + /** + * default timeout setting + */ + private static final int DEFAULT_TIMEOUT_SECONDS = 30; + + private static Configuration getDefaultConfig() { Configuration config = new Configuration(); config.set(isabellePathKey, DEFAULT_ISABELLE_PATH); config.set(translationPathKey, DEFAULT_TRANSLATION_PATH); - config.set(timeoutKey, 30); + config.set(timeoutKey, DEFAULT_TIMEOUT_SECONDS); return config; } @@ -46,23 +89,21 @@ private IsabelleTranslationSettings(Configuration load) { Runtime.getRuntime().addShutdownHook(new Thread(this::save)); } - public Path getIsabellePath() { - return isabellePath; - } - - public Path getTranslationPath() { - return translationPath; - } - - + /** + * Returns the instance of this class + * + * @return instance of this class + */ public static IsabelleTranslationSettings getInstance() { if (INSTANCE == null) { if (SETTINGS_FILE_NEW.exists()) { try { LOGGER.info("Load Isabelle settings at {}", SETTINGS_FILE_NEW); - return INSTANCE = new IsabelleTranslationSettings(Configuration.load(SETTINGS_FILE_NEW)); + return INSTANCE = + new IsabelleTranslationSettings(Configuration.load(SETTINGS_FILE_NEW)); } catch (IOException e) { - LOGGER.error("Could not read {}, resorting to default settings", SETTINGS_FILE_NEW, e); + LOGGER.error("Could not read {}, resorting to default settings", + SETTINGS_FILE_NEW, e); return INSTANCE = new IsabelleTranslationSettings(getDefaultConfig()); } } @@ -72,27 +113,33 @@ public static IsabelleTranslationSettings getInstance() { return INSTANCE; } - protected boolean createSessionFiles() { + protected void createSessionFiles() { Path sessionRootPath = Path.of(translationPath + "/ROOT"); - BufferedReader sessionReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(getClass().getResourceAsStream("ROOT")))); - String sessionRoot = sessionReader.lines().collect(Collectors.joining(System.lineSeparator())); + BufferedReader sessionReader = new BufferedReader( + new InputStreamReader(Objects.requireNonNull(getClass().getResourceAsStream("ROOT")))); + String sessionRoot = + sessionReader.lines().collect(Collectors.joining(System.lineSeparator())); Path sessionDocumentPath = Path.of(translationPath + "/document/root.tex"); - BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader(Objects.requireNonNull(getClass().getResourceAsStream("root.tex")))); - String sessionDocument = sessionDocumentReader.lines().collect(Collectors.joining(System.lineSeparator())); + BufferedReader sessionDocumentReader = new BufferedReader(new InputStreamReader( + Objects.requireNonNull(getClass().getResourceAsStream("root.tex")))); + String sessionDocument = + sessionDocumentReader.lines().collect(Collectors.joining(System.lineSeparator())); try { Files.createDirectories(sessionDocumentPath.getParent()); Files.write(sessionRootPath, sessionRoot.getBytes()); Files.write(sessionDocumentPath, sessionDocument.getBytes()); LOGGER.info("Created Isabelle session files at: {}", translationPath); - return true; } catch (IOException e) { - LOGGER.error("Failed to create ROOT file for Isabelle Translation, because: {}", e.toString()); - return false; + LOGGER.error("Failed to create ROOT file for Isabelle Translation, because: {}", + e.toString()); } } + /** + * Writes the settings to the JSON file + */ public void save() { LOGGER.info("Save Isabelle settings to: {}", SETTINGS_FILE_NEW.getAbsolutePath()); try (Writer writer = new FileWriter(SETTINGS_FILE_NEW)) { @@ -131,7 +178,8 @@ public void readSettings(@NonNull Configuration props) { } isabellePath = Path.of(props.getString(isabellePathKey, isabellePath.toString())); - Path newTranslationPath = Path.of(props.getString(translationPathKey, translationPath.toString())); + Path newTranslationPath = + Path.of(props.getString(translationPathKey, translationPath.toString())); if (newTranslationPath != translationPath) { translationPath = newTranslationPath; createSessionFiles(); @@ -147,10 +195,23 @@ public void writeSettings(@NonNull Configuration props) { props.set(timeoutKey, String.valueOf(timeoutSeconds)); } + /** + * @return + * The header used for translation theories. Includes the preamble and Main theory + * imports + */ public String getHeader() { return "theory Translation imports Main KeYTranslations.TranslationPreamble begin"; } + public Path getIsabellePath() { + return isabellePath; + } + + public Path getTranslationPath() { + return translationPath; + } + public int getTimeout() { return this.timeoutSeconds; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index 44a656af6a8..1712473c81e 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -1,70 +1,113 @@ +/* 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 org.key_project.isabelletranslation.automation; -import org.jspecify.annotations.NonNull; -import org.key_project.isabelletranslation.IsabelleTranslationSettings; -import org.key_project.isabelletranslation.TranslationAction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; import java.io.IOException; -import java.nio.file.Files; import java.util.*; import java.util.concurrent.*; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; +import org.key_project.isabelletranslation.gui.controller.IsabelleLauncherProgressDialogMediator; + +import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class allows for the launch of automated proof searches in Isabelle for a list of isabelle + * problems. + */ public class IsabelleLauncher implements IsabelleSolverListener { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleLauncher.class); + /** + * The settings used during proof search in Isabelle. + */ private final IsabelleTranslationSettings settings; - private IsabelleLauncherListener listener; + /** + * The listener objects for this launcher. + * Is used to control the Isabelle dialog with {@link IsabelleLauncherProgressDialogMediator}. + */ + private final List listeners = new ArrayList<>(); + + /** + * The thread, that will be called on shutdown of KeY to ensure there are no runaway Isabelle + * instances or open ThreadPools + */ private Thread shutdownResources; + /** + * The ExecutorService used to call the solver instances. + */ private ExecutorService executorService; - - private final List runningSolvers = Collections.synchronizedList(new ArrayList<>()); - - + /** + * The list of currently running solver instances. + */ + private final List runningSolvers = + Collections.synchronizedList(new ArrayList<>()); + + /** + * + */ + private final List finishedSolvers = + Collections.synchronizedList(new ArrayList<>()); + + /** + * The queue of solver instances that have not started yet. + */ private final LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); - private final Collection solverSet = new HashSet<>(); - private IsabelleSolver.ReasonOfInterruption reasonOfInterruption; public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { this.settings = settings; } - public void try0ThenSledgehammerAllPooled(List problems, int timeoutSeconds, int instanceCount) throws IOException { + /** + * Launches the given problems with the specified timeout using a specified number of concurrent + * Isabelle instances + * + * @param problems The problems for which proof search will be started + * @param timeoutSeconds The timeout setting to use for the Isabelle instances + * @param instanceCount The number of concurrent Isabelle instances + * @throws IOException If {@link IsabelleResourceController} fails to initiate || translation + * files could not be written + */ + public void launch(List problems, int timeoutSeconds, + int instanceCount) throws IOException { if (problems.isEmpty()) { return; } - //Ensure the preamble theory is present + // Ensure the preamble theory file is present, so theory objects can be created. problems.get(0).writeTranslationFiles(settings); - IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount); + IsabelleResourceController resourceController = + new IsabelleResourceController(instanceCount, settings); executorService = Executors.newFixedThreadPool(instanceCount); shutdownResources = new Thread(() -> { executorService.shutdown(); resourceController.shutdownGracefully(); + finishedSolvers.clear(); }); Runtime.getRuntime().addShutdownHook(shutdownResources); for (int i = 0; i < problems.size(); i++) { - IsabelleSolver solver = new IsabelleSledgehammerSolver(problems.get(i), List.of(this), i, resourceController, settings); + IsabelleSolver solver = new IsabelleSledgehammerSolver(problems.get(i), List.of(this), + i, resourceController, settings); solver.setTimeout(timeoutSeconds); solverQueue.add(solver); - solverSet.add(solver); } - listener.launcherStarted(this, solverSet); + notifyLauncherStarted(); resourceController.init(); - listener.launcherPreparationFinished(this, solverSet); + notifyPreparationFinished(); LOGGER.info("Setup complete, starting {} problems...", problems.size()); @@ -73,15 +116,42 @@ public void try0ThenSledgehammerAllPooled(List problems, int ti } catch (InterruptedException e) { throw new RuntimeException(e); } catch (RejectedExecutionException e) { - //Launcher has been shutdown before running instances - //Nothing to do here, intended behavior + // Launcher has been shutdown before running instances + // Nothing to do here, intended behavior } finally { shutdown(); } - listener.launcherStopped(this, solverSet); + notifyLauncherStopped(); + } + + /** + * Notifies all listeners of the launcher stop. + */ + private void notifyLauncherStopped() { + listeners.forEach(listener -> listener.launcherStopped(this, finishedSolvers)); } + /** + * Notifies all listeners that the launcher has finished preparations. + * This usually means the Isabelle instances have been created by the + * {@link IsabelleResourceController}. + */ + private void notifyPreparationFinished() { + listeners.forEach(listener -> listener.launcherPreparationFinished(this, finishedSolvers)); + } + + /** + * Notifies all listeners that the launcher has started. + */ + private void notifyLauncherStarted() { + listeners.forEach(listener -> listener.launcherStarted(this, solverQueue)); + } + + /** + * Starts the shutdownResources thread, if it was not started already. + * Also removes the shutdown hook. + */ private void shutdown() { Runtime.getRuntime().removeShutdownHook(shutdownResources); if (shutdownResources.getState() == Thread.State.NEW) { @@ -89,46 +159,59 @@ private void shutdown() { } } + /** + * Adds a listener. Primarily used for {@link IsabelleLauncherProgressDialogMediator} to update + * the Isabelle dialog. + * + * @param listener The listener to be used + */ public void addListener(IsabelleLauncherListener listener) { - this.listener = listener; + listeners.add(listener); } - public void stopAll(IsabelleSolver.ReasonOfInterruption reasonOfInterruption) { - this.reasonOfInterruption = reasonOfInterruption; - + /** + * Calls the {@link #shutdown()} function. Then stops the execution of all + * {@link IsabelleSolver} instances that were not started. + * Also interrupts all running solvers. Can be used to perform a user initiated interrupt when + * using IsabelleSolver.ReasonOfInterruption.User. + */ + public void stopAll() { shutdown(); executorService.shutdownNow(); - solverQueue.forEach(solver -> solver.interrupt(reasonOfInterruption)); + solverQueue.forEach(IsabelleSolver::abort); solverQueue.clear(); - runningSolvers.forEach(solver -> { - if (reasonOfInterruption != null) { - solver.interrupt(reasonOfInterruption); - } - }); + runningSolvers.forEach(IsabelleSolver::abort); runningSolvers.clear(); - listener.launcherStopped(this, solverSet); + notifyLauncherStopped(); + + finishedSolvers.clear(); } @Override public void processStarted(IsabelleSolver solver, IsabelleProblem problem) { runningSolvers.add(solver); - solverQueue.remove(solver); + if (!solverQueue.remove(solver)) { + LOGGER.error( + "Something went wrong during Isabelle instance management! Solver \"{}\" was not in queue, but started anyway.", + solver.name()); + stopAll(); + throw new RuntimeException("Something went wrong during Isabelle instance management!"); + } } @Override public void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e) { runningSolvers.remove(solver); - if (reasonOfInterruption != null) { - solver.interrupt(reasonOfInterruption); - } + finishedSolvers.add(solver); } @Override public void processStopped(IsabelleSolver solver, IsabelleProblem problem) { runningSolvers.remove(solver); + finishedSolvers.add(solver); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java index bf71536ccc2..bd7438743dd 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherListener.java @@ -1,8 +1,20 @@ +/* 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 org.key_project.isabelletranslation.automation; import java.util.Collection; +/** + * Interface for listener classes for the {@link IsabelleLauncher} + */ public interface IsabelleLauncherListener { + /** + * Called when the launcher has stopped (both successfully and due to interruptions etc.). + * + * @param launcher The stopped launcher + * @param finishedInstances The instances which have finished processing in the launcher. + */ void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances); void launcherStarted(IsabelleLauncher launcher, Collection solvers); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java deleted file mode 100644 index 3516fbcd794..00000000000 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncherProgressDialogMediator.java +++ /dev/null @@ -1,300 +0,0 @@ -package org.key_project.isabelletranslation.automation; - -import de.uka.ilkd.key.core.KeYMediator; -import de.uka.ilkd.key.gui.MainWindow; -import de.uka.ilkd.key.gui.colors.ColorSettings; -import de.uka.ilkd.key.proof.Proof; -import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; -import org.key_project.isabelletranslation.gui.IsabelleProgressModel; -import org.key_project.isabelletranslation.gui.ProofApplyUserAction; - -import javax.swing.*; -import java.awt.*; -import java.text.DecimalFormat; -import java.time.Duration; -import java.time.Instant; -import java.util.Timer; -import java.util.Collection; -import java.util.TimerTask; - -public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { - private static final DecimalFormat remainingTimeFormat = new DecimalFormat("#.#"); - private final Timer timer = new Timer(); - private int finishedCounter = 0; - - private final Proof proof; - - - private final static ColorSettings.ColorProperty RED = - ColorSettings.define("[isabelleDialog]red", "", new Color(180, 43, 43)); - - private final static ColorSettings.ColorProperty GREEN = - ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); - private boolean userStopFlag = false; - - @Override - public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { - timer.cancel(); - - progressModel.setEditable(true); - refreshDialog(); - progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); - } - - @Override - public void launcherStarted(IsabelleLauncher launcher, Collection solvers) { - prepareDialog(solvers, launcher); - - setProgressText(-1); - timer.schedule(new TimerTask() { - @Override - public void run() { - refreshDialog(); - } - }, 0, 10); - } - - @Override - public void launcherPreparationFinished(IsabelleLauncher launcher, Collection solvers) { - setProgressText(0); - } - - protected void stopEvent(IsabelleLauncher launcher) { - userStopFlag = true; - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); - } - - protected void applyEvent(IsabelleLauncher launcher) { - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.NoInterruption); - applyResults(); - progressDialog.dispose(); - } - - private void applyResults() { - KeYMediator mediator = MainWindow.getInstance().getMediator(); - // ensure that the goal closing does not lag the UI - mediator.stopInterface(true); - try { - new ProofApplyUserAction(mediator, proof, solvers).actionPerformed(null); - } finally { - mediator.startInterface(true); - //switch to new open goal - mediator.getSelectionModel().defaultSelection(); - } - } - - private void stopped(IsabelleSolver solver) { - int x = 0; - int y = solver.getSolverIndex(); - - if (!problemProcessed[x][y]) { - finishedCounter++; - progressDialog.setProgress(finishedCounter); - JProgressBar bar = progressDialog.getProgressBar(); - bar.setValue(finishedCounter); - setProgressText(finishedCounter); - problemProcessed[x][y] = true; - } - - IsabelleResult result = solver.getFinalResult(); - - switch (result.getType()) { - case INTERRUPTED: - interrupted(solver, x, y); - break; - case SUCCESS: - successfullyStopped(solver, x, y); - break; - case ERROR: - encounteredError(solver, x, y); - break; - case TIMEOUT: - timedOut(solver, x, y); - break; - default: - unknownStopped(x, y); - break; - } - } - - private void interrupted(IsabelleSolver solver, int x, int y) { - if (userStopFlag) { - progressModel.setProgress(0, x, y); - progressModel.setText("Interrupted by user.", x, y); - } else { - throw new RuntimeException("This position should not be reachable!"); - } - } - - private void successfullyStopped(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(GREEN.get(), x, y); - - String timeInfo = solver.getComputationTime().toMillis() / 1000d + "s"; - - progressModel.setText("Valid (" + timeInfo + ")", x, y); - } - - private void encounteredError(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(RED.get(), x, y); - progressModel.setText("Exception!", x, y); - } - - private void timedOut(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setText("Interrupted by User.", x, y); - } - - private void unknownStopped(int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(Color.BLUE, x, y); - progressModel.setText("Unknown.", x, y); - } - - private void setProgressText(int value) { - JProgressBar bar = progressDialog.getProgressBar(); - if (value == -1) { - bar.setString("Preparing... (this might take a few seconds)"); - bar.setStringPainted(true); - } else if (value == bar.getMaximum()){ - bar.setString("Finished."); - bar.setStringPainted(true); - } else { - bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); - bar.setStringPainted(true); - } - } - - protected void discardEvent(IsabelleLauncher launcher) { - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); - progressDialog.dispose(); - } - - public IsabelleLauncherProgressDialogMediator(Proof proof) { - this.proof = proof; - } - - - private static final int RESOLUTION = 1000; - - private Collection solvers; - private IsabelleProgressModel progressModel; - private boolean[][] problemProcessed; - private IsabelleProgressDialog progressDialog; - - private void prepareDialog(Collection solvers, final IsabelleLauncher launcher) { - this.solvers = solvers; - progressModel = new IsabelleProgressModel(); - - String[] captions = new String[solvers.size()]; - - int i = 0; - for (IsabelleSolver solver : solvers) { - captions[i] = solver.getProblem().getName(); - i++; - } - - progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); - problemProcessed = new boolean[1][solvers.size()]; - progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); - - - progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, - RESOLUTION, solvers.size(), new String[] {}, "", "Isabelle"); - - - SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); - } - - private void refreshDialog() { - for (IsabelleSolver solver : solvers) { - refreshProgressOfSolver(solver); - } - } - - private void refreshProgressOfSolver(IsabelleSolver solver) { - IsabelleSolver.SolverState state = solver.getState(); - switch (state) { - case Preparing -> { - preparing(solver); - } - case Parsing -> { - parsing(solver); - } - case Running -> { - running(solver); - } - case Stopped -> { - stopped(solver); - } - case Waiting -> { - waiting(solver); - } - } - - } - - private void running(IsabelleSolver solver) { - long progress = calculateProgress(solver); - progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); - - float remainingTime = calculateRemainingTime(solver); - progressModel.setText(remainingTimeFormat.format(remainingTime) + " sec.", 0, solver.getSolverIndex()); - } - - private long calculateProgress(IsabelleSolver solver) { - Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); - Instant startTime = solver.getStartTime(); - - return (long) Math.floor(RESOLUTION - * (Duration.between(startTime, Instant.now()).toMillis() / (double) maxDuration.toMillis())); - } - - private float calculateRemainingTime(IsabelleSolver solver) { - Instant timeoutTime = solver.getStartTime().plusSeconds(solver.getTimeout()); - return Duration.between(Instant.now(), timeoutTime).toMillis() / 1000f; - } - - private void parsing(IsabelleSolver solver) { - progressModel.setText("Parsing...", 0, solver.getSolverIndex()); - } - - private void waiting(IsabelleSolver solver) { - } - - private void preparing(IsabelleSolver solver) { - progressModel.setText("Preparing...", 0, solver.getSolverIndex()); - } - - private class IsabelleProgressDialogListenerImpl implements IsabelleProgressDialog.IsabelleProgressDialogListener { - - - private final IsabelleLauncher launcher; - - - public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { - super(); - this.launcher = launcher; - } - - @Override - public void infoButtonClicked(int column, int row) { - } - - @Override - public void stopButtonClicked() { - stopEvent(launcher); - } - - @Override - public void applyButtonClicked() { - applyEvent(launcher); - } - - @Override - public void discardButtonClicked() { - discardEvent(launcher); - } - } -} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java index b8247647a16..5afe9c20bad 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java @@ -1,55 +1,138 @@ +/* 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 org.key_project.isabelletranslation.automation; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + import de.uka.ilkd.key.proof.Goal; + import org.key_project.isabelletranslation.IsabelleTranslationSettings; +import org.key_project.isabelletranslation.translation.IllegalFormulaException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - +/** + * This class represents an Isabelle problem. It contains the goal corresponding to the problem, as + * well as the content of the preamble and translation theory. + * + * @author Nils Buchholz + */ public class IsabelleProblem { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProblem.class); + /** + * The goal associated with this problem + */ private final Goal goal; + + /** + * Content of the preamble theory + */ private final String preamble; - private final String sequentTranslation; + + /** + * Content of the translation theory + */ + private final String translation; + + /** + * Name of the problem. Contains the serialNr of the associated goal + * Used to display the goal in the rows of Isabelle dialogs + */ private final String name; - public IsabelleProblem(Goal goal, String preamble, String sequentTranslation) { + /** + * Exception encountered during translation + */ + private final IllegalFormulaException exception; + + /** + * Creates a new problem for the given goal. + * + * @param goal the goal associated with this problem + * @param preamble content of the preamble theory + * @param translation content of the translation theory + */ + public IsabelleProblem(Goal goal, String preamble, String translation) { this.goal = goal; this.preamble = preamble; - this.sequentTranslation = sequentTranslation; + this.translation = translation; + this.name = "Goal " + goal.node().serialNr(); + this.exception = null; + } + + public IsabelleProblem(Goal goal, IllegalFormulaException exception) { + this.goal = goal; + this.preamble = null; + this.translation = null; this.name = "Goal " + goal.node().serialNr(); + this.exception = exception; } + /** + * Returns goal associated with this problem. + * + * @return goal associated with this problem + */ public Goal getGoal() { return goal; } - public String getSequentTranslation() { - return sequentTranslation; + /** + * Returns content of translation theory + * + * @return content of translation theory + */ + public String getTranslation() { + return translation; } + /** + * Returns content of preamble theory + * + * @return content of preamble theory + */ public String getPreamble() { return preamble; } + /** + * Returns the name of this problem + * + * @return the name of this problem + */ public String getName() { return name; } - public void writeTranslationFiles(IsabelleTranslationSettings settings) { + /** + * Writes the contents of the preamble and translation theory to the files specified in the + * {@link IsabelleTranslationSettings}. + * If the files and directories are not already present, they are created. + * + * @param settings settings to be used + */ + public void writeTranslationFiles(IsabelleTranslationSettings settings) throws IOException { File translationFile = new File(settings.getTranslationPath() + "/Translation.thy"); - File translationPreambleFile = new File(settings.getTranslationPath() + "/TranslationPreamble.thy"); - try { - Files.createDirectories(translationFile.toPath().getParent()); - Files.write(translationPreambleFile.toPath(), this.getPreamble().getBytes()); - Files.write(translationFile.toPath(), this.getSequentTranslation().getBytes()); - LOGGER.info("Saved to: {} and {}", translationFile.toPath(), translationPreambleFile.toPath()); - } catch (IOException e) { - LOGGER.error("Failed to save translation", e); - } + File translationPreambleFile = + new File(settings.getTranslationPath() + "/TranslationPreamble.thy"); + Files.createDirectories(translationFile.toPath().getParent()); + Files.write(translationPreambleFile.toPath(), this.getPreamble().getBytes()); + Files.write(translationFile.toPath(), this.getTranslation().getBytes()); + LOGGER.info("Saved to: {} and {}", translationFile.toPath(), + translationPreambleFile.toPath()); + } + + /** + * Checks if a translation, preamble are present + * + * @return true - both translation and preamble are present, false - otherwise + */ + public boolean hasTranslation() { + return translation != null || preamble != null; } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResource.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResource.java new file mode 100644 index 00000000000..80424e4dbc1 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResource.java @@ -0,0 +1,48 @@ +/* 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 org.key_project.isabelletranslation.automation; + +import de.unruh.isabelle.control.Isabelle; +import de.unruh.isabelle.pure.Theory; + +/** + * An IsabelleResource is a bundling of an Isabelle instance and a {@link Theory} derived from that + * instance. + * It can be used to provide solvers with these values for computation. + */ +public interface IsabelleResource { + /** + * Checks if the resource has been destroyed. If this is true the resource should not be used + * anymore. + * + * @return true - resource destroyed, false otherwise + */ + boolean isDestroyed(); + + /** + * Destroys the resource. Usually by destroying the Isabelle instance. + */ + void destroy(); + + /** + * Interrupts the Isabelle instance. + */ + void interrupt(); + + /** + * Returns the instance matching the {@link Theory} returned by + * {@link IsabelleResource#theory()} + * + * @return {@link Isabelle} usable with {@link IsabelleResource#theory()} + */ + Isabelle instance(); + + /** + * Returns the {@link Theory} matching the {@link Isabelle} returned by + * {@link IsabelleResource#instance()} + * + * @return {@link Theory} usable with {@link IsabelleResource#instance()} + */ + Theory theory(); +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java index f64c7efd014..8839ad5fd46 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java @@ -1,5 +1,15 @@ +/* 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 org.key_project.isabelletranslation.automation; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.concurrent.*; + +import org.key_project.isabelletranslation.IsabelleTranslationSettings; + import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; import de.unruh.isabelle.java.JIsabelle; @@ -11,43 +21,75 @@ import de.unruh.isabelle.pure.Position; import de.unruh.isabelle.pure.Theory; import de.unruh.isabelle.pure.TheoryHeader; -import org.key_project.isabelletranslation.IsabelleTranslationSettings; -import org.slf4j.LoggerFactory; import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import scala.collection.immutable.List; -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.concurrent.*; - +/** + * This class handles creation of Isabelle instances, as well as providing methods for their + * destruction. + * This class also acts as a semaphore for Isabelle instances. + * The Isabelle instances are bundled with a {@link Theory} into a {@link IsabelleResource} for this + * purpose. + */ public class IsabelleResourceController { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleResourceController.class); + /** + * The idle Isabelle instances. + */ private final LinkedBlockingQueue idleInstances; + /** + * The settings to be used. Needed for path to Isabelle + */ private final IsabelleTranslationSettings settings; + /** + * Flag to check for shutdowns. + */ private boolean isShutdown = false; - private final Collection waitingSolvers; + /** + * Queue of threads waiting for Isabelle resources. + */ + private final LinkedBlockingQueue waitingThreads; + /** + * The number of Isabelle instances to create and store in this semaphore. + */ private final int numberOfInstances; - + /** + * Thread pool for instance creation + */ private final ExecutorService instanceCreatorService; + /** + * Semaphore to ensure fairness when taking Isabelle instance. + */ + private final Semaphore takeSemaphore; - public IsabelleResourceController(int numberOfInstances) { - settings = IsabelleTranslationSettings.getInstance(); + /** + * Creates a resource controller. Initializes the settings. + * + * @param numberOfInstances the maximum number of Isabelle instances to create at any time + * @param settings {@link IsabelleTranslationSettings} to be used + */ + public IsabelleResourceController(int numberOfInstances, IsabelleTranslationSettings settings) { + this.settings = settings; idleInstances = new LinkedBlockingQueue<>(numberOfInstances); - waitingSolvers = new HashSet<>(); + waitingThreads = new LinkedBlockingQueue<>(); this.numberOfInstances = numberOfInstances; instanceCreatorService = Executors.newFixedThreadPool(numberOfInstances); + takeSemaphore = new Semaphore(1, true); } + /** + * Creates the Isabelle instances. + * + * @throws IOException If instance creation failed. + */ public void init() throws IOException { for (int i = 0; i < numberOfInstances; i++) { if (!isShutdown()) { @@ -57,26 +99,52 @@ public void init() throws IOException { } } - public IsabelleResource getIsabelleResource(IsabelleSolver requestingSolver) throws InterruptedException { - waitingSolvers.add(requestingSolver); - IsabelleResource freeResource = idleInstances.take(); - waitingSolvers.remove(requestingSolver); - return freeResource; + /** + * Tries to acquire a Isabelle instance. Fairness is ensured by a semaphore. + * + * @return an idle Isabelle resource + * @throws InterruptedException if the thread is interrupted while waiting + */ + public IsabelleResource getIsabelleResource() throws InterruptedException { + waitingThreads.add(Thread.currentThread()); + takeSemaphore.acquire(); + try { + return idleInstances.take(); + } finally { + waitingThreads.remove(Thread.currentThread()); + takeSemaphore.release(); + } } + /** + * Calls {@link ExecutorService#shutdownNow()} for the instance creator service thereby stopping + * instance creation. + *

+ * Interrupts all waiting threads. + *

+ * Destroys all idle instances. + */ public void shutdownGracefully() { isShutdown = true; instanceCreatorService.shutdownNow(); - waitingSolvers.forEach((x) -> x.interrupt(IsabelleSolver.ReasonOfInterruption.User)); - waitingSolvers.clear(); + waitingThreads.forEach(Thread::interrupt); + waitingThreads.clear(); idleInstances.forEach(IsabelleResource::destroy); idleInstances.clear(); } - public void returnResource(IsabelleSolver returningSolver, IsabelleResource resource) { + /** + * Adds a resource to the queue. The resource is interrupted via + * {@link IsabelleResource#interrupt()} to ensure it is idle. + *

+ * If the controller is shutdown the resource is destroyed instead. + * + * @param resource the resource to return + */ + public void returnResource(IsabelleResource resource) { assert resource != null; if (isShutdown()) { @@ -90,7 +158,8 @@ public void returnResource(IsabelleSolver returningSolver, IsabelleResource reso try { resource = createIsabelleResource(); } catch (IOException e) { - //Should not occur. If it was possible to create instances during creation, it should be possible now. + // Should not occur. If it was possible to create instances during creation, it + // should be possible now. shutdownGracefully(); LOGGER.error(e.getMessage()); } @@ -100,15 +169,26 @@ public void returnResource(IsabelleSolver returningSolver, IsabelleResource reso idleInstances.offer(resource); } + /** + * Checks if the controller is shutdown. + * + * @return true - controller is shutdown, false - otherwise + */ public boolean isShutdown() { return isShutdown; } + /** + * Creates a new {@link IsabelleResource} via the thread pool used for this purpose. + * + * @return fresh IsabelleResource + * @throws IOException if instance creation failed + */ private IsabelleResource createIsabelleResource() throws IOException { Callable creationTask = () -> { Isabelle isabelleInstance = startIsabelleInstance(); Theory theory = beginTheory(isabelleInstance, settings); - return new IsabelleResource(isabelleInstance, theory); + return new IsabelleResourceImpl(isabelleInstance, theory); }; try { return instanceCreatorService.submit(creationTask).get(); @@ -126,15 +206,22 @@ private IsabelleResource createIsabelleResource() throws IOException { } } + /** + * Starts an Isabelle instance using the Isabelle installation location provided by the user in + * the settings. + * + * @return freshly started Isabelle instance + * @throws IOException if Isabelle could not be found at the location stored in the settings + */ private Isabelle startIsabelleInstance() throws IOException { ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); Isabelle isabelle; try { Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); isabelle = new Isabelle(setup); } catch (Exception e) { LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); @@ -143,44 +230,70 @@ private Isabelle startIsabelleInstance() throws IOException { return isabelle; } + /** + * Creates a theory object for use in solvers. + *

+ * Requires the translation theories to be present. + * + * @param isabelle The Isabelle instance, which creates the theory object + * @param settings Isabelle settings, which show the location of the translation theories + * @return Theory object matching the given isabelle instance + */ private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings settings) { MLFunction3, Theory> begin_theory = - MLValue.compileFunction("fn (path, header, parents) => Resources.begin_theory path header parents", isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); - MLFunction2 header_read = MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter(), Implicits.theoryHeaderConverter()); - - - - TheoryHeader header = header_read.apply(settings.getHeader(), Position.none(isabelle), isabelle, de.unruh.isabelle.mlvalue.Implicits.stringConverter(), Implicits.positionConverter()) + MLValue.compileFunction( + "fn (path, header, parents) => Resources.begin_theory path header parents", + isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLFunction2 header_read = + MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + + + TheoryHeader header = header_read + .apply(settings.getHeader(), Position.none(isabelle), isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = settings.getTranslationPath(); - return begin_theory.apply(topDir, header, header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), new ListConverter<>(Implicits.theoryConverter())) + return begin_theory.apply(topDir, header, + header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } - public record IsabelleResource(Isabelle instance, Theory theory) { - public boolean isDestroyed() { - return instance.isDestroyed(); - } + /** + * A record bundling a given instance to a theory. This is necessary as a theory object is only usable in conjunction with the instance used to create it. + * @param instance the instance + * @param theory the theory + */ + private record IsabelleResourceImpl(Isabelle instance, Theory theory) implements IsabelleResource { - void destroy() { - instance.destroy(); - } + @Override + public boolean isDestroyed() { + return instance.isDestroyed(); + } - private void interruptIntern() throws IsabelleMLException { - instance.executeMLCodeNow("error \"Interrupt\""); - } + @Override + public void destroy() { + instance.destroy(); + } - private void interrupt() { - try { - interruptIntern(); - } catch (IsabelleMLException e) { - //Always throws this due to the way Isabelle is interrupted. - } + private void interruptIntern() throws IsabelleMLException { + instance.executeMLCodeNow("error \"Interrupt\""); + } + + @Override + public void interrupt() { + try { + interruptIntern(); + } catch (IsabelleMLException e) { + // Always throws this due to the way Isabelle is interrupted. } } -} +}} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java index 5835118abcf..604071ba400 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResult.java @@ -1,22 +1,57 @@ +/* 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 org.key_project.isabelletranslation.automation; import java.time.Duration; +/** + * This class stores the result of a {@link IsabelleSolver}. + * This includes computation times and in some cases successful tactics and exceptions. + */ public class IsabelleResult { + /** + * Returns a {@link String} description of the type of this result. + * + * @return description of the type of result this is + */ public String getDescription() { return this.type.getDescription(); } + /** + * Returns the type of result this is + * + * @return the type of result this is + */ public Type getType() { return this.type; } + /** + * Enum containing different types of Results. + */ public enum Type { - SUCCESS ("Success"), - ERROR ("Error"), - TIMEOUT ("Timeout"), + /** + * Successful result. (Proof found) + */ + SUCCESS("Success"), + /** + * Error result. (Encountered exception) + */ + ERROR("Error"), + /** + * Timeout result. (No proof found in time) + */ + TIMEOUT("Timeout"), + /** + * Interrupt result. (Interrupt during proof search) + */ INTERRUPTED("Interrupted"), - UNKNOWN ("Unknown"); + /** + * Unknown result. (Something went wrong, but unknown what did) + */ + UNKNOWN("Unknown"); Type(String description) { this.description = description; @@ -24,56 +59,119 @@ public enum Type { private final String description; + /** + * Returns a {@link String} description of the result type. + * + * @return a {@link String} description of the result type. + */ public String getDescription() { return description; } } - - + /** + * The type of this result + */ private final Type type; + /** + * The computation time for this result. Only set for successful and timeout results. + */ private final Duration computationTime; + /** + * A successful tactic returned by an Isabelle automation method + */ private final String successfulTactic; + /** + * An exception thrown during computation by the solver + */ private final Exception exception; - private IsabelleResult(Type type, Duration computationTime, String successfulTactic, Exception exception) { + private IsabelleResult(Type type, Duration computationTime, String successfulTactic, + Exception exception) { this.type = type; this.computationTime = computationTime; this.successfulTactic = successfulTactic; this.exception = exception; } - public boolean isSuccessful() { - return type == Type.SUCCESS; - } - + /** + * Creates a timeout result. + * + * @param computationTime the time taken for timeout to occur + * @return Isabelle result representing a timeout + */ public static IsabelleResult getTimeoutResult(Duration computationTime) { return new IsabelleResult(Type.TIMEOUT, computationTime, null, null); } + /** + * Returns an error result + * + * @param exception the exception that caused computation to fail + * @return Isabelle result representing an error + */ public static IsabelleResult getErrorResult(Exception exception) { return new IsabelleResult(Type.ERROR, null, null, exception); } - public static IsabelleResult getSuccessResult(String successfulTactic, Duration computationTime) { + /** + * Creates a successful result + * + * @param successfulTactic the successful tactic found by a solver + * @param computationTime time taken for proof search + * @return Isabelle result representing a success + */ + public static IsabelleResult getSuccessResult(String successfulTactic, + Duration computationTime) { return new IsabelleResult(Type.SUCCESS, computationTime, successfulTactic, null); } + /** + * Creates an interrupt result + * + * @return Isabelle result representing an Interrupt + */ public static IsabelleResult getInterruptedResult() { return new IsabelleResult(Type.INTERRUPTED, null, null, null); } + /** + * Creates an unknown result + * + * @return Isabelle result representing an unknown result + */ public static IsabelleResult getUnknownResult() { return new IsabelleResult(Type.UNKNOWN, null, null, null); } + + + /** + * Is this result successful? + * + * @return true - if successful, false - otherwise + */ + public boolean isSuccessful() { + return type == Type.SUCCESS; + } + + /** + * Is this an error result? + * + * @return true - if error, false - otherwise + */ public boolean isError() { return type == Type.ERROR; } + /** + * Is this a timeout result? + * + * @return true - if timeout, false - otherwise + */ public boolean isTimeout() { return type == Type.TIMEOUT; } @@ -82,11 +180,26 @@ public Duration getComputationTime() { return this.computationTime; } + /** + * Getter for exception + * + * @return exception encountered during proving || null if not error result + */ public Exception getException() { return this.exception; } + /** + * Successful proof tactic + * + * @return successful tactic || null if not successful + */ public String getSuccessfulTactic() { return this.successfulTactic; } + + @Override + public String toString() { + return getDescription(); + } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java index 4dfbefdfc60..c389e008da1 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java @@ -1,5 +1,17 @@ +/* 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 org.key_project.isabelletranslation.automation; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.key_project.isabelletranslation.IsabelleTranslationSettings; + import de.unruh.isabelle.control.Isabelle; import de.unruh.isabelle.control.IsabelleMLException; import de.unruh.isabelle.mlvalue.*; @@ -7,7 +19,6 @@ import de.unruh.isabelle.pure.Theory; import de.unruh.isabelle.pure.ToplevelState; import de.unruh.isabelle.pure.Transition; -import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; @@ -17,28 +28,29 @@ import scala.concurrent.Future; import scala.concurrent.duration.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - +/** + * Implementation of {@link IsabelleSolver} using Sledgehammer. + */ public class IsabelleSledgehammerSolver implements IsabelleSolver { + /** + * Needed for UI + */ private final int solverIndex; - private IsabelleResult result; - private IsabelleResourceController.IsabelleResource isabelleResource; + /** + * The result of this solver. + */ + private IsabelleResult result; /** - * The SMT problem that is related to this solver + * */ - private final IsabelleProblem problem; + private IsabelleResource isabelleResource; /** - * stores the reason for interruption if present (e.g. User, Timeout, Exception) + * The problem that is related to this solver */ - private ReasonOfInterruption reasonOfInterruption = ReasonOfInterruption.NoInterruption; + private final IsabelleProblem problem; /** * the state the solver is currently in @@ -56,7 +68,7 @@ public class IsabelleSledgehammerSolver implements IsabelleSolver { private Throwable exception; /** - * The timeout in seconds for this SMT solver run. + * The timeout in seconds for this solver run. */ private int timeout; @@ -70,7 +82,9 @@ public class IsabelleSledgehammerSolver implements IsabelleSolver { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSledgehammerSolver.class); private final Collection listeners; - public IsabelleSledgehammerSolver(IsabelleProblem problem, Collection listeners, int solverIndex, IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { + public IsabelleSledgehammerSolver(IsabelleProblem problem, + Collection listeners, int solverIndex, + IsabelleResourceController resourceController, IsabelleTranslationSettings settings) { this.problem = problem; this.solverIndex = solverIndex; this.listeners = new HashSet<>(); @@ -85,21 +99,11 @@ public int getSolverIndex() { return solverIndex; } - @Override - public ReasonOfInterruption getReasonOfInterruption() { - return reasonOfInterruption; - } - @Override public String name() { return "Isabelle Solver: " + problem.getName(); } - @Override - public String getTranslation() { - return problem.getSequentTranslation(); - } - @Override public IsabelleProblem getProblem() { return problem; @@ -111,29 +115,26 @@ public Throwable getException() { } @Override - public void interrupt(ReasonOfInterruption reason) { - setReasonOfInterruption(reason); - this.result = IsabelleResult.getInterruptedResult(); - if (isabelleResource != null) { - returnResource(); + public void abort() { + // If solver already completed, the interrupt should be ignored + if (setFinalResult(IsabelleResult.getInterruptedResult())) { + handleInterrupt(); } - setSolverState(SolverState.Stopped); } + /** + * Returns the resource used by this solver to the controller. + */ private void returnResource() { if (isabelleResource == null) { return; } - resourceController.returnResource(this, isabelleResource); + resourceController.returnResource(isabelleResource); isabelleResource = null; } private void setSolverState(SolverState solverState) { - this.solverState = solverState; - } - - public void setReasonOfInterruption(ReasonOfInterruption reasonOfInterruption) { - this.reasonOfInterruption = reasonOfInterruption; + this.solverState = solverState; } @Override @@ -156,11 +157,6 @@ public SolverState getState() { return solverState; } - @Override - public boolean isRunning() { - return solverState == SolverState.Running; - } - @Override public String getRawSolverOutput() { return result.getSuccessfulTactic(); @@ -168,7 +164,7 @@ public String getRawSolverOutput() { @Override public String getRawSolverInput() { - return problem.getSequentTranslation(); + return problem.getTranslation(); } @Override @@ -179,25 +175,22 @@ public IsabelleResult getFinalResult() { @Override public IsabelleResult call() throws InterruptedException { - //Ensure there is an active IsabelleInstance + // Ensure there is an active IsabelleInstance setSolverState(SolverState.Preparing); try { - isabelleResource = resourceController.getIsabelleResource(this); + isabelleResource = resourceController.getIsabelleResource(); } catch (InterruptedException e) { return handleInterrupt(); } - notifyProcessStarted(); startTime = Instant.now(); - Isabelle isabelle = isabelleResource.instance(); - LOGGER.info("Parsing theory for: {}", problem.getName()); setSolverState(SolverState.Parsing); - ToplevelState toplevel = ToplevelState.apply(isabelle); + ToplevelState toplevel; try { - toplevel = parseTheory(toplevel, isabelleResource); + toplevel = parseTheory(isabelleResource); } catch (InterruptedException e) { return handleInterrupt(); } catch (IsabelleMLException e) { @@ -208,11 +201,14 @@ public IsabelleResult call() throws InterruptedException { setSolverState(SolverState.Running); try { - this.result = sledgehammer(isabelleResource, toplevel); - computationTime = java.time.Duration.between(startTime, Instant.now()); + if (!setFinalResult(sledgehammer(isabelleResource, toplevel))) { + return this.result; + } } catch (TimeoutException e) { - this.result = IsabelleResult.getTimeoutResult(computationTime); - computationTime = java.time.Duration.between(startTime, Instant.now()); + setComputationTime(); + if (!setFinalResult(IsabelleResult.getTimeoutResult(getComputationTime()))) { + return this.result; + } } catch (InterruptedException e) { return handleInterrupt(); } catch (IsabelleMLException e) { @@ -225,53 +221,91 @@ public IsabelleResult call() throws InterruptedException { return this.result; } - private ToplevelState parseTheory(ToplevelState toplevel, IsabelleResourceController.IsabelleResource resource) throws InterruptedException, IsabelleMLException { - ToplevelState result = toplevel; + /** + * Parse the content of a theory and return the resulting toplevelstate. + * + * @param resource Isabelle resource to use + * @return {@link ToplevelState} of the parsed theory + * @throws InterruptedException If interrupted while parsing + * @throws IsabelleMLException if parsing fails on the side of Isabelle + */ + private ToplevelState parseTheory(IsabelleResource resource) + throws InterruptedException, IsabelleMLException { Isabelle isabelle = resource.instance(); Theory thy0 = resource.theory(); + ToplevelState result = ToplevelState.apply(isabelle); if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } - MLFunction2>> parse_text = MLValue.compileFunction(""" - fn (thy, text) => let - val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text - fun addtext symbols [tr] = - [(tr, implode symbols)] - | addtext _ [] = [] - | addtext symbols (tr::nextTr::trs) = let - val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols - in (tr, implode this) :: addtext rest (nextTr::trs) end - in addtext (Symbol.explode text) transitions end""", isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); + MLFunction2>> parse_text = + MLValue.compileFunction( + """ + fn (thy, text) => let + val transitions = Outer_Syntax.parse_text thy (K thy) Position.start text + fun addtext symbols [tr] = + [(tr, implode symbols)] + | addtext _ [] = [] + | addtext symbols (tr::nextTr::trs) = let + val (this,rest) = Library.chop (Position.distance_of (Toplevel.pos_of tr, Toplevel.pos_of nextTr) |> Option.valOf) symbols + in (tr, implode this) :: addtext rest (nextTr::trs) end + in addtext (Symbol.explode text) transitions end""", + isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), + de.unruh.isabelle.mlvalue.Implicits.stringConverter()))); if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } - MLFunction3 command_exception = MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter(), Implicits.toplevelStateConverter()); + MLFunction3 command_exception = + MLValue.compileFunction("fn (int, tr, st) => Toplevel.command_exception int tr st", + isabelle, + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), + Implicits.transitionConverter(), Implicits.toplevelStateConverter(), + Implicits.toplevelStateConverter()); java.util.List> transitionsAndTexts = new ArrayList<>(); - List> transitionList = parse_text.apply(thy0, getProblem().getSequentTranslation(), isabelle, - Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) - .retrieveNow(new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter())), isabelle); + List> transitionList = + parse_text.apply(thy0, getProblem().getTranslation(), isabelle, + Implicits.theoryConverter(), de.unruh.isabelle.mlvalue.Implicits.stringConverter()) + .retrieveNow( + new ListConverter<>(new Tuple2Converter<>(Implicits.transitionConverter(), + de.unruh.isabelle.mlvalue.Implicits.stringConverter())), + isabelle); transitionList.foreach(transitionsAndTexts::add); for (Tuple2 transitionAndText : transitionsAndTexts) { - //println(s"""Transition: "${text.strip}"""") + // println(s"""Transition: "${text.strip}"""") if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } result = command_exception.apply(Boolean.TRUE, transitionAndText._1(), result, isabelle, - de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), Implicits.transitionConverter(), Implicits.toplevelStateConverter()) - .retrieveNow(Implicits.toplevelStateConverter(), isabelle); + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), + Implicits.transitionConverter(), Implicits.toplevelStateConverter()) + .retrieveNow(Implicits.toplevelStateConverter(), isabelle); } return result; } - - private IsabelleResult sledgehammer(IsabelleResourceController.IsabelleResource resource, ToplevelState toplevel) - throws TimeoutException, InterruptedException, IsabelleMLException { + /** + * Uses sledgehammer to search for a proof + * + * @param resource the resource to use for ML requests + * @param toplevel the toplevelstate of the theory to search a proof for + * @return IsabelleResult + * + * success - proof found + * timeout - timed out during proof search + * interrupt - interrupted during proof search + * error - encountered exception during proof search + * @throws TimeoutException if proof search timed out + * @throws InterruptedException if interrupted during proof search + * @throws IsabelleMLException if Isabelle reported an error + */ + private IsabelleResult sledgehammer(IsabelleResource resource, + ToplevelState toplevel) + throws TimeoutException, InterruptedException, IsabelleMLException { Isabelle isabelle = resource.instance(); Theory thy0 = resource.theory(); @@ -279,68 +313,94 @@ private IsabelleResult sledgehammer(IsabelleResourceController.IsabelleResource String Sledgehammer_Commands = thy0.importMLStructureNow("Sledgehammer_Commands", isabelle); String Sledgehammer_Prover = thy0.importMLStructureNow("Sledgehammer_Prover", isabelle); MLFunction4, scala.collection.immutable.List, Tuple2>>> normal_with_Sledgehammer = - MLValue.compileFunction( - """ - fn (state, thy, adds, dels) => - let - val override = {add=[],del=[],only=false}; - fun go_run (state, thy) = - let - val p_state = Toplevel.proof_of state; - val ctxt = Proof.context_of p_state; - val params =\s""" + Sledgehammer_Commands + """ - .default_params thy - [("timeout",\"""" + (double) timeout + """ - "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; - val results =\s""" - + sledgehammer + """ - .run_sledgehammer params\s""" + Sledgehammer_Prover + """ - .Normal NONE 1 override p_state; - val (result, (outcome, step)) = results; - in - (result, (""" + sledgehammer + """ - .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) - end; - in - Timeout.apply (Time.fromSeconds\s - """ + getTimeout() + ") go_run (state, thy) end", isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); + MLValue.compileFunction( + """ + fn (state, thy, adds, dels) => + let + val override = {add=[],del=[],only=false}; + fun go_run (state, thy) = + let + val p_state = Toplevel.proof_of state; + val ctxt = Proof.context_of p_state; + val params =\s""" + Sledgehammer_Commands + """ + .default_params thy + [("timeout",\"""" + (double) timeout + + """ + "),("verbose","true"),("provers", "cvc4 verit z3 e spass vampire zipperposition")]; + val results =\s""" + + sledgehammer + """ + .run_sledgehammer params\s""" + Sledgehammer_Prover + """ + .Normal NONE 1 override p_state; + val (result, (outcome, step)) = results; + in + (result, (""" + sledgehammer + """ + .short_string_of_sledgehammer_outcome outcome, [YXML.content_of step])) + end; + in + Timeout.apply (Time.fromSeconds\s + """ + getTimeout() + ") go_run (state, thy) end", + isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + (new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), + new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + new ListConverter<>( + de.unruh.isabelle.mlvalue.Implicits.stringConverter()))))); Builder> listBuilder = scala.collection.immutable.List.newBuilder(); scala.collection.immutable.List emptyList = listBuilder.result(); - IsabelleResult result; - Future>>> resultFuture = normal_with_Sledgehammer.apply(toplevel, thy0, emptyList, emptyList, isabelle, Implicits.toplevelStateConverter(), Implicits.theoryConverter(), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), - new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) - .retrieve(new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), new Tuple2Converter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter(), new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), isabelle); - Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); + Future>>> resultFuture = + normal_with_Sledgehammer + .apply(toplevel, thy0, emptyList, emptyList, isabelle, + Implicits.toplevelStateConverter(), Implicits.theoryConverter(), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter()), + new ListConverter<>(de.unruh.isabelle.mlvalue.Implicits.stringConverter())) + .retrieve( + new Tuple2Converter<>( + de.unruh.isabelle.mlvalue.Implicits.booleanConverter(), + new Tuple2Converter<>( + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + new ListConverter<>( + de.unruh.isabelle.mlvalue.Implicits.stringConverter()))), + isabelle); + Tuple2>> resultFutureCollect = + Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); boolean successful = (boolean) resultFutureCollect._1(); - + setComputationTime(); if (successful) { - result = IsabelleResult.getSuccessResult(resultFutureCollect._2()._2().head(), computationTime); + return IsabelleResult.getSuccessResult(resultFutureCollect._2()._2().head(), + getComputationTime()); } else { - result = IsabelleResult.getUnknownResult(); + return IsabelleResult.getUnknownResult(); } - this.result = result; - return this.result; } + /** + * Handles an interrupt encountered during proof search + * + * @return Interrupt result + */ private IsabelleResult handleInterrupt() { - this.result = IsabelleResult.getInterruptedResult(); + setFinalResult(IsabelleResult.getInterruptedResult()); returnResource(); + setComputationTime(); Thread.currentThread().interrupt(); setSolverState(SolverState.Stopped); notifyProcessError(new InterruptedException()); return this.result; } + /** + * Handles an error encountered during proof search + * + * @return error result + */ private IsabelleResult handleIsabelleError(Exception e) { - this.result = IsabelleResult.getErrorResult(e); + setFinalResult(IsabelleResult.getErrorResult(e)); + setComputationTime(); this.exception = e; returnResource(); setSolverState(SolverState.Stopped); @@ -353,6 +413,20 @@ public java.time.Duration getComputationTime() { return computationTime; } + private void setComputationTime() { + if (getStartTime() == null) { + computationTime = java.time.Duration.between(getStartTime(), Instant.now()); + } + } + + private synchronized boolean setFinalResult(IsabelleResult result) { + if (this.result == null) { + this.result = result; + return true; + } + return false; + } + private void notifyProcessStarted() { for (IsabelleSolverListener listener : listeners) { listener.processStarted(this, getProblem()); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java index 65985753ac7..5fc97fa03e5 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolver.java @@ -1,48 +1,110 @@ +/* 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 org.key_project.isabelletranslation.automation; import java.time.Duration; import java.time.Instant; import java.util.concurrent.Callable; +/** + * An Isabelle solver. May use different methods to arrive at the result. + * Implements callable. Thread management must be handled by callers. + */ public interface IsabelleSolver extends Callable { + /** + * UI component index + * + * @return the index corresponding to this solver + */ int getSolverIndex(); - ReasonOfInterruption getReasonOfInterruption(); - - enum ReasonOfInterruption { - User, NoInterruption - } - - enum SolverState{ + /** + * state of the solver + */ + enum SolverState { Waiting, Preparing, Parsing, Running, Stopped } + /** + * Name for the solver instance + * + * @return name of the solver instance + */ String name(); - String getTranslation(); - + /** + * Getter for the problem this solver will work on + * + * @return The problem this solver will work on + */ IsabelleProblem getProblem(); + /** + * Returns the Exception encountered during proof search + * + * @return exception encountered during proof search, if any was encountered. + */ Throwable getException(); - void interrupt(ReasonOfInterruption reason); + /** + * aborts processing + */ + void abort(); + /** + * Getter for start time of the solver + * + * @return Time solver started computing (after preparation) + */ Instant getStartTime(); + /** + * Getter for computation time + * + * @return computation time before solver stopped + */ Duration getComputationTime(); + /** + * Returns the timeout time for solver in seconds + * + * @return timeout time for solver + */ int getTimeout(); + /** + * Sets the timeout value for this solver (in seconds) + * + * @param timeout timeout in seconds (negative values may cause unexpected behavior) + */ void setTimeout(int timeout); + /** + * Getter for current solver state + * + * @return current solver state + */ SolverState getState(); - boolean isRunning(); - + /** + * Raw output of solver + * + * @return raw output of solver + */ String getRawSolverOutput(); + /** + * Raw string of translation theory (not preamble) + * + * @return raw input of solver + */ String getRawSolverInput(); + /** + * The final result of solver. Recommended to be null, prior to solver completion. + * + * @return final result of solver + */ IsabelleResult getFinalResult(); - } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java index d5a4d301b31..e11ca490724 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSolverListener.java @@ -1,307 +1,34 @@ +/* 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 org.key_project.isabelletranslation.automation; -import de.uka.ilkd.key.core.KeYMediator; -import de.uka.ilkd.key.gui.MainWindow; -import de.uka.ilkd.key.gui.colors.ColorSettings; -import de.uka.ilkd.key.proof.Proof; -import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; -import org.key_project.isabelletranslation.gui.IsabelleProgressModel; -import org.key_project.isabelletranslation.gui.ProofApplyUserAction; - -import javax.swing.*; -import java.awt.*; -import java.text.DecimalFormat; -import java.time.Duration; -import java.time.Instant; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; - +/** + * Listener for {@link IsabelleSolver}s. + */ public interface IsabelleSolverListener { + /** + * Solver has started. Called after finishing preparations. + * + * @param solver the solver + * @param problem the problem the solver is working on + */ void processStarted(IsabelleSolver solver, IsabelleProblem problem); + /** + * Solver has encountered an error. + * + * @param solver the solver + * @param problem the problem the solver is working on + * @param e the exception the solver encountered + */ void processError(IsabelleSolver solver, IsabelleProblem problem, Exception e); + /** + * Solver has stopped as planned + * + * @param solver the solver + * @param problem the problem the solver is working on + */ void processStopped(IsabelleSolver solver, IsabelleProblem problem); - - class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { - private static final DecimalFormat remainingTimeFormat = new DecimalFormat("#.#"); - private final Timer timer = new Timer(); - private int finishedCounter = 0; - - private final Proof proof; - - - private final static ColorSettings.ColorProperty RED = - ColorSettings.define("[isabelleDialog]red", "", new Color(180, 43, 43)); - - private final static ColorSettings.ColorProperty GREEN = - ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); - private boolean userStopFlag = false; - - @Override - public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { - timer.cancel(); - - progressModel.setEditable(true); - refreshDialog(); - progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); - } - - @Override - public void launcherStarted(IsabelleLauncher launcher, Collection solvers) { - prepareDialog(solvers, launcher); - - setProgressText(-1); - timer.schedule(new TimerTask() { - @Override - public void run() { - refreshDialog(); - } - }, 0, 10); - } - - @Override - public void launcherPreparationFinished(IsabelleLauncher launcher, Collection solvers) { - setProgressText(0); - } - - protected void stopEvent(IsabelleLauncher launcher) { - userStopFlag = true; - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); - } - - protected void applyEvent(IsabelleLauncher launcher) { - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.NoInterruption); - applyResults(); - progressDialog.dispose(); - } - - private void applyResults() { - KeYMediator mediator = MainWindow.getInstance().getMediator(); - // ensure that the goal closing does not lag the UI - mediator.stopInterface(true); - try { - new ProofApplyUserAction(mediator, proof, solvers).actionPerformed(null); - } finally { - mediator.startInterface(true); - //switch to new open goal - mediator.getSelectionModel().defaultSelection(); - } - } - - private void stopped(IsabelleSolver solver) { - int x = 0; - int y = solver.getSolverIndex(); - - if (!problemProcessed[x][y]) { - finishedCounter++; - progressDialog.setProgress(finishedCounter); - JProgressBar bar = progressDialog.getProgressBar(); - bar.setValue(finishedCounter); - setProgressText(finishedCounter); - problemProcessed[x][y] = true; - } - - IsabelleResult result = solver.getFinalResult(); - - switch (result.getType()) { - case INTERRUPTED: - interrupted(solver, x, y); - break; - case SUCCESS: - successfullyStopped(solver, x, y); - break; - case ERROR: - encounteredError(solver, x, y); - break; - case TIMEOUT: - timedOut(solver, x, y); - break; - default: - unknownStopped(x, y); - break; - } - } - - private void interrupted(IsabelleSolver solver, int x, int y) { - if (userStopFlag) { - progressModel.setProgress(0, x, y); - progressModel.setText("Interrupted by user.", x, y); - } else { - throw new RuntimeException("This position should not be reachable!"); - } - } - - private void successfullyStopped(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(GREEN.get(), x, y); - - String timeInfo = solver.getComputationTime().toMillis() / 1000d + "s"; - - progressModel.setText("Valid (" + timeInfo + ")", x, y); - } - - private void encounteredError(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(RED.get(), x, y); - progressModel.setText("Exception!", x, y); - } - - private void timedOut(IsabelleSolver solver, int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setText("Interrupted by User.", x, y); - } - - private void unknownStopped(int x, int y) { - progressModel.setProgress(0, x, y); - progressModel.setTextColor(Color.BLUE, x, y); - progressModel.setText("Unknown.", x, y); - } - - private void setProgressText(int value) { - JProgressBar bar = progressDialog.getProgressBar(); - if (value == -1) { - bar.setString("Preparing... (this might take a few seconds)"); - bar.setStringPainted(true); - } else if (value == bar.getMaximum()){ - bar.setString("Finished."); - bar.setStringPainted(true); - } else { - bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); - bar.setStringPainted(true); - } - } - - protected void discardEvent(IsabelleLauncher launcher) { - launcher.stopAll(IsabelleSolver.ReasonOfInterruption.User); - progressDialog.dispose(); - } - - public IsabelleLauncherProgressDialogMediator(Proof proof) { - this.proof = proof; - } - - - private static final int RESOLUTION = 1000; - - private Collection solvers; - private IsabelleProgressModel progressModel; - private boolean[][] problemProcessed; - private IsabelleProgressDialog progressDialog; - - private void prepareDialog(Collection solvers, final IsabelleLauncher launcher) { - this.solvers = solvers; - progressModel = new IsabelleProgressModel(); - - String[] captions = new String[solvers.size()]; - - int i = 0; - for (IsabelleSolver solver : solvers) { - captions[i] = solver.getProblem().getName(); - i++; - } - - progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); - problemProcessed = new boolean[1][solvers.size()]; - progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); - - - progressDialog = new IsabelleProgressDialog(progressModel, new IsabelleProgressDialogListenerImpl(launcher), false, - RESOLUTION, solvers.size(), new String[] {}, "", "Isabelle"); - - - SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); - } - - private void refreshDialog() { - for (IsabelleSolver solver : solvers) { - refreshProgressOfSolver(solver); - } - } - - private void refreshProgressOfSolver(IsabelleSolver solver) { - IsabelleSolver.SolverState state = solver.getState(); - switch (state) { - case Preparing -> { - preparing(solver); - } - case Parsing -> { - parsing(solver); - } - case Running -> { - running(solver); - } - case Stopped -> { - stopped(solver); - } - case Waiting -> { - waiting(solver); - } - } - - } - - private void running(IsabelleSolver solver) { - long progress = calculateProgress(solver); - progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); - - float remainingTime = calculateRemainingTime(solver); - progressModel.setText(remainingTimeFormat.format(remainingTime) + " sec.", 0, solver.getSolverIndex()); - } - - private long calculateProgress(IsabelleSolver solver) { - Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); - Instant startTime = solver.getStartTime(); - - return RESOLUTION * (Duration.between(startTime, Instant.now()).toMillis() / maxDuration.toMillis()); - } - - private float calculateRemainingTime(IsabelleSolver solver) { - Instant timeoutTime = solver.getStartTime().plusSeconds(solver.getTimeout()); - return Duration.between(Instant.now(), timeoutTime).toMillis() / 1000f; - } - - private void parsing(IsabelleSolver solver) { - progressModel.setText("Parsing...", 0, solver.getSolverIndex()); - } - - private void waiting(IsabelleSolver solver) { - } - - private void preparing(IsabelleSolver solver) { - progressModel.setText("Preparing...", 0, solver.getSolverIndex()); - } - - private class IsabelleProgressDialogListenerImpl implements IsabelleProgressDialog.IsabelleProgressDialogListener { - - - private final IsabelleLauncher launcher; - - - public IsabelleProgressDialogListenerImpl(IsabelleLauncher launcher) { - super(); - this.launcher = launcher; - } - - @Override - public void infoButtonClicked(int column, int row) { - } - - @Override - public void stopButtonClicked() { - stopEvent(launcher); - } - - @Override - public void applyButtonClicked() { - applyEvent(launcher); - } - - @Override - public void discardButtonClicked() { - discardEvent(launcher); - } - } - } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java index 9788060b2f6..e1631ad3dff 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java @@ -3,13 +3,7 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.gui; -import de.uka.ilkd.key.gui.IssueDialog; -import de.uka.ilkd.key.gui.MainWindow; -import org.key_project.util.java.SwingUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.key_project.isabelletranslation.gui.IsabelleProgressModel.ProcessColumn.ProcessData; - +import java.awt.*; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.plaf.basic.BasicProgressBarUI; @@ -17,32 +11,43 @@ import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; -import java.awt.*; + +import de.uka.ilkd.key.gui.IssueDialog; +import de.uka.ilkd.key.gui.MainWindow; + +import org.key_project.isabelletranslation.gui.IsabelleProgressModel.ProcessColumn.ProcessData; +import org.key_project.util.java.SwingUtil; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Dialog showing launched Isabelle processes and results. + *

+ * Adapted version of {@link de.uka.ilkd.key.gui.smt.ProgressDialog} used for SMT. */ public class IsabelleProgressDialog extends JDialog { - - private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleProgressDialog.class); + /** + * Contains the progress of all solvers. + */ private final ProgressTable table; /** - * Button to apply the results of running the SMT solver. - * May close some open goals if the solver returned unsat. + * Button to apply the results of running the Isabelle solvers. + * May close some open goals if the solvers found proofs. */ private JButton applyButton; /** - * Button to stop the launched SMT solvers. + * Button to stop the launched Isabelle solvers. */ private JButton stopButton; /** - * Scroll pane listing the open goals and the results of running each SMT solver on them. + * Scroll pane listing the open goals and the results of running each Isabelle solver on them. */ private JScrollPane scrollPane; /** - * Overall progress of the SMT solvers (# goals started / total goals). + * Overall progress of the Isabelle solvers (# goals processed / total goals). */ private JProgressBar progressBar; private final IsabelleProgressDialogListener listener; @@ -52,11 +57,11 @@ public class IsabelleProgressDialog extends JDialog { */ public enum Modus { /** - * SMT solvers are running and may be stopped by the user. + * Isabelle solvers are running and may be stopped by the user. */ SOLVERS_RUNNING, /** - * SMT solvers are done (or terminated). Results may be applied by the user. + * Isabelle solvers are done (or terminated). Results may be applied by the user. */ SOLVERS_DONE } @@ -66,6 +71,10 @@ public enum Modus { */ private Modus modus = Modus.SOLVERS_RUNNING; + /** + * Listener interface to interact with this dialog. Used for functionality of stop, apply and + * discard buttons. + */ public interface IsabelleProgressDialogListener extends ProgressTable.ProgressTableListener { void applyButtonClicked(); @@ -74,11 +83,21 @@ public interface IsabelleProgressDialogListener extends ProgressTable.ProgressTa void discardButtonClicked(); } - public IsabelleProgressDialog(IsabelleProgressModel model, IsabelleProgressDialogListener listener, - boolean counterexample, int resolution, int progressBarMax, String[] labelTitles, - String... titles) { + /** + * Creates a new progress dialog. + * + * @param model progress model that is displayed in dialog + * @param listener listener to be used + * @param resolution resolution to be used for progress bars of each solver + * @param progressBarMax the total number of goals + * @param titles titles of the solver types + */ + public IsabelleProgressDialog(IsabelleProgressModel model, + IsabelleProgressDialogListener listener, + boolean counterexample, int resolution, int progressBarMax, + String... titles) { super(MainWindow.getInstance()); - table = new ProgressTable(resolution, listener, labelTitles); + table = new ProgressTable(resolution, listener); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.getTableHeader().setReorderingAllowed(false); table.setModel(model, titles); @@ -118,31 +137,44 @@ public IsabelleProgressDialog(IsabelleProgressModel model, IsabelleProgressDialo setLocationRelativeTo(MainWindow.getInstance()); } + /** + * Updates the progress bar in the dialog. + * + * @param value the new value to set the progress bar to + */ public void setProgress(int value) { getProgressBar().setValue(value); } + /** + * Returns the progress bar or creates a new one, if not already created + * + * @return the progress bar + */ public JProgressBar getProgressBar() { if (progressBar == null) { progressBar = new JProgressBar(); - } - return progressBar; } + /** + * Returns the apply button or creates a new one, if not already created + * + * @return the apply button + */ private JButton getApplyButton() { if (applyButton == null) { applyButton = new JButton("Apply"); applyButton.setToolTipText( - "Apply the results (i.e. close goals if the SMT solver was successful)"); + "Apply the results (i.e. close goals if the Isabelle solver was successful)"); applyButton.setEnabled(false); applyButton.addActionListener(e -> { try { listener.applyButtonClicked(); } catch (Exception exception) { // There may be exceptions during rule application that should not be lost. - LOGGER.error("", exception); + LOGGER.error("Exception during application of Isabelle results:", exception); IssueDialog.showExceptionDialog(this, exception); } }); @@ -150,6 +182,11 @@ private JButton getApplyButton() { return applyButton; } + /** + * Returns the scroll pane or creates a new one, if not already created + * + * @return the scroll pane + */ private JScrollPane getScrollPane() { if (scrollPane == null) { scrollPane = SwingUtil.createScrollPane(table); @@ -157,6 +194,11 @@ private JScrollPane getScrollPane() { return scrollPane; } + /** + * Returns the stop button or creates a new one, if not already created + * + * @return the stop button + */ private JButton getStopButton() { if (stopButton == null) { stopButton = new JButton("Stop"); @@ -172,6 +214,13 @@ private JButton getStopButton() { return stopButton; } + /** + * Switches the modus of the dialog and switches/enables the corresponding buttons. + * RUNNING -> stop button to interrupt (apply unavailable) + * DONE -> discard button to discard results (apply available) + * + * @param m new modus of dialog + */ public void setModus(Modus m) { modus = m; switch (modus) { @@ -192,18 +241,24 @@ public void setModus(Modus m) { } +/** + * The table displaying the progress of solver instances + */ class ProgressTable extends JTable { - - private static final long serialVersionUID = 1L; private static final int NUMBER_OF_VISIBLE_ROWS = 8; + /** + * Basic listener interface for the table to enable info buttons. + * currently not working + */ public interface ProgressTableListener { void infoButtonClicked(int column, int row); } - + /** + * Panel displaying the total progress of all solver instances "x/y instances completed" + */ public static class ProgressPanel extends JPanel { - private static final long serialVersionUID = 1L; private JProgressBar progressBar; private JButton infoButton; @@ -233,25 +288,26 @@ private JButton getInfoButton() { infoButton.setMinimumSize(dim); infoButton.setPreferredSize(dim); infoButton.setMaximumSize(dim); - } return infoButton; } ProgressPanel() { - this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(Box.createVerticalStrut(2)); Box content = Box.createHorizontalBox(); content.add(Box.createHorizontalStrut(2)); content.add(getProgressBar()); content.add(Box.createHorizontalStrut(2)); - //content.add(getInfoButton()); + // content.add(getInfoButton()); content.add(Box.createHorizontalStrut(2)); this.add(content); this.add(Box.createVerticalStrut(2)); } + /** + * @param value the new value of the progress bar + */ public void setValue(int value) { getProgressBar().setValue(value); } @@ -263,22 +319,18 @@ public void setText(String text) { } - private final ProgressPanel progressPanelRenderer = new ProgressPanel(); private ProgressPanel progressPanelEditor; - private class ProgressCellEditor extends AbstractCellEditor implements TableCellEditor { private static final long serialVersionUID = 1L; - @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { - currentEditorCell.x = column; currentEditorCell.y = row; ProcessData data = (ProcessData) value; @@ -287,7 +339,6 @@ public Component getTableCellEditorComponent(JTable table, Object value, boolean } - @Override public Object getCellEditorValue() { return null; @@ -296,7 +347,6 @@ public Object getCellEditorValue() { } - private void prepareProgressPanel(ProgressPanel panel, final ProcessData data) { panel.setValue(data.getProgress()); panel.setText(data.getText()); @@ -311,7 +361,9 @@ protected Color getSelectionForeground() { return data.getSelectedTextColor(); } - protected Color getSelectionBackground() { return data.getTextColor(); } + protected Color getSelectionBackground() { + return data.getTextColor(); + } }); } @@ -328,13 +380,11 @@ protected Color getSelectionForeground() { private final Point currentEditorCell = new Point(); - - public ProgressTable(int resolution, ProgressTableListener listener, String... titles) { + public ProgressTable(int resolution, ProgressTableListener listener) { this.setDefaultRenderer(IsabelleProgressModel.ProcessColumn.class, renderer); this.setDefaultEditor(IsabelleProgressModel.ProcessColumn.class, editor); init(getProgressPanelEditor(), this.getFont(), resolution, listener); init(progressPanelRenderer, this.getFont(), resolution, listener); - } private void init(ProgressPanel panel, Font font, int resolution, @@ -343,8 +393,6 @@ private void init(ProgressPanel panel, Font font, int resolution, panel.progressBar.setMaximum(resolution); panel.infoButton.addActionListener( e -> listener.infoButtonClicked(currentEditorCell.x - 1, currentEditorCell.y)); - - } @@ -364,7 +412,6 @@ public void setModel(IsabelleProgressModel model, String... titles) { } - } @Override @@ -406,7 +453,6 @@ public static void packColumn(JTable table, int vColIndex, int margin) { } - private ProgressPanel getProgressPanelEditor() { if (progressPanelEditor == null) { progressPanelEditor = new ProgressPanel(); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java index 6837f5fbfac..8b6bb7d223d 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java @@ -1,5 +1,11 @@ +/* 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 org.key_project.isabelletranslation.gui; +import java.util.Collection; +import java.util.HashSet; + import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.actions.useractions.UserAction; import de.uka.ilkd.key.proof.Goal; @@ -7,12 +13,10 @@ import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.rule.IBuiltInRuleApp; import de.uka.ilkd.key.smt.SMTRuleApp; + import org.key_project.isabelletranslation.automation.IsabelleProblem; import org.key_project.isabelletranslation.automation.IsabelleSolver; -import java.util.Collection; -import java.util.HashSet; - public class ProofApplyUserAction extends UserAction { private final Collection solvers; @@ -21,11 +25,11 @@ public class ProofApplyUserAction extends UserAction { private final int numberOfGoalsClosed; public ProofApplyUserAction(KeYMediator mediator, Proof proof, - Collection solvers) { + Collection solvers) { super(mediator, proof); this.solvers = solvers; - this.numberOfGoalsClosed = (int) solvers.stream().filter(solver -> - solver.getFinalResult().isSuccessful()).count(); + this.numberOfGoalsClosed = + (int) solvers.stream().filter(solver -> solver.getFinalResult().isSuccessful()).count(); } @Override @@ -45,9 +49,11 @@ protected void apply() { goalsClosed.add(goal); - //TODO SMTRuleApp does not serve any purpose as a SMT exclusive rule. - // The documentation does not suggest it should only be used for SMT, yet the name would suggest this. - // Changing this requires changing parts of the KeY core. This needs a different class, which does not prepend "SMT" to all titles + // TODO SMTRuleApp does not serve any purpose as a SMT exclusive rule. + // The documentation does not suggest it should only be used for SMT, yet the name would + // suggest this. + // Changing this requires changing parts of the KeY core. This needs a different class, + // which does not prepend "SMT" to all titles IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("") .setTitle("Isabelle: " + solver.getFinalResult().getSuccessfulTactic()); app.tryToInstantiate(goal); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java new file mode 100644 index 00000000000..46958c7b7bd --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java @@ -0,0 +1,469 @@ +/* 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 org.key_project.isabelletranslation.gui.controller; + +import java.awt.*; +import java.text.DecimalFormat; +import java.time.Duration; +import java.time.Instant; +import java.util.Collection; +import java.util.Timer; +import java.util.TimerTask; +import javax.swing.*; + +import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.colors.ColorSettings; +import de.uka.ilkd.key.proof.Proof; + +import org.key_project.isabelletranslation.automation.IsabelleLauncher; +import org.key_project.isabelletranslation.automation.IsabelleLauncherListener; +import org.key_project.isabelletranslation.automation.IsabelleResult; +import org.key_project.isabelletranslation.automation.IsabelleSolver; +import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; +import org.key_project.isabelletranslation.gui.IsabelleProgressModel; +import org.key_project.isabelletranslation.gui.ProofApplyUserAction; + +/** + * Updates the {@link IsabelleProgressDialog} for a given {@link IsabelleLauncher}. + */ +public class IsabelleLauncherProgressDialogMediator implements IsabelleLauncherListener { + /** + * The format used to display the remaining time for solver instances. + */ + private static final DecimalFormat remainingTimeFormat = new DecimalFormat("#.#"); + + /** + * The Resolution used for the progress bars in the Isabelle dialog. + */ + private static final int RESOLUTION = 1000; + + /** + * The red color used to display the exception status for solvers + */ + private final static ColorSettings.ColorProperty RED = + ColorSettings.define("[isabelleDialog]red", "", new Color(180, 43, 43)); + + /** + * The green color used to display the valid status for solvers + */ + private final static ColorSettings.ColorProperty GREEN = + ColorSettings.define("[isabelleDialog]green", "", new Color(43, 180, 43)); + + /** + * Timer used to schedule periodic refreshes of the Isabelle dialog. + */ + private final Timer timer = new Timer(); + + /** + * The proof which the launcher is working on. + * Used to close solved goals. + */ + private final Proof proof; + + /** + * Indicates whether a user initiated stop has occured + */ + private boolean userStopFlag = false; + + /** + * The launcher used in conjunction with the dialog. + */ + private final IsabelleLauncher launcher; + + /** + * The number of finished instances. + */ + private int finishedCounter = 0; + + /** + * The solvers started by the launcher + */ + private Collection solvers; + + /** + * The {@link IsabelleProgressModel} associated with the launcher + */ + private IsabelleProgressModel progressModel; + + /** + * Stores which solvers have processed their problem + */ + private boolean[][] finishedSolvers; + + /** + * The dialog used + */ + private IsabelleProgressDialog progressDialog; + + @Override + public void launcherStopped(IsabelleLauncher launcher, + Collection finishedInstances) { + timer.cancel(); + + progressModel.setEditable(true); + refreshDialog(); + progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); + } + + @Override + public void launcherStarted(IsabelleLauncher launcher, Collection solvers) { + prepareDialog(solvers); + + setProgressText(-1); + timer.schedule(new TimerTask() { + @Override + public void run() { + refreshDialog(); + } + }, 0, 10); + } + + @Override + public void launcherPreparationFinished(IsabelleLauncher launcher, + Collection solvers) { + setProgressText(0); + } + + /** + * The event that occurs after the stop button has been pressed in the dialog. + * Uses {@link IsabelleLauncher#stopAll()} to interrupt the + * launcher. + * Also sets the userStopFlag so solver interrupts can be allocated to the user. + */ + protected void stopEvent() { + userStopFlag = true; + launcher.stopAll(); + } + + /** + * The event that occurs after the apply button has been pressed in the dialog. + * Invokes the {@link IsabelleLauncherProgressDialogMediator#applyResults()} to close solved + * goals. + * Then disposes of the dialog. + */ + protected void applyEvent() { + applyResults(); + progressDialog.dispose(); + } + + /** + * Creates a action, which can close the solved goals. + */ + private void applyResults() { + KeYMediator mediator = MainWindow.getInstance().getMediator(); + // ensure that the goal closing does not lag the UI + mediator.stopInterface(true); + try { + new ProofApplyUserAction(mediator, proof, solvers).actionPerformed(null); + } finally { + mediator.startInterface(true); + // switch to new open goal + mediator.getSelectionModel().defaultSelection(); + } + } + + /** + * Updates the dialog for a stopped solver depending on its result. + * + * @param solver The stopped solver. + */ + private void stopped(IsabelleSolver solver) { + int x = 0; + int y = solver.getSolverIndex(); + + if (!finishedSolvers[x][y]) { + finishedCounter++; + progressDialog.setProgress(finishedCounter); + JProgressBar bar = progressDialog.getProgressBar(); + bar.setValue(finishedCounter); + setProgressText(finishedCounter); + finishedSolvers[x][y] = true; + } + + IsabelleResult result = solver.getFinalResult(); + + switch (result.getType()) { + case INTERRUPTED: + interrupted(x, y); + break; + case SUCCESS: + successfullyStopped(solver, x, y); + break; + case ERROR: + encounteredError(x, y); + break; + case TIMEOUT: + timedOut(x, y); + break; + default: + unknownStopped(x, y); + break; + } + } + + /** + * Updates the dialog for an interrupted solver. + * + * @param x The solver type index + * @param y The solver index as reported by {@link IsabelleSolver#getSolverIndex()} + */ + private void interrupted(int x, int y) { + if (userStopFlag) { + progressModel.setProgress(0, x, y); + progressModel.setText("Interrupted by user.", x, y); + } else { + throw new RuntimeException("Solver was interrupted for unknown reasons!"); + } + } + + /** + * Updates the dialog for solver that stopped successfully. + * + * @param x The solver type index + * @param y The solver index as reported by {@link IsabelleSolver#getSolverIndex()} + */ + private void successfullyStopped(IsabelleSolver solver, int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(GREEN.get(), x, y); + + String timeInfo = solver.getComputationTime().toMillis() / 1000d + "s"; + + progressModel.setText("Valid (" + timeInfo + ")", x, y); + } + + /** + * Updates the dialog for solver that encountered an error. + * + * @param x The solver type index + * @param y The solver index as reported by {@link IsabelleSolver#getSolverIndex()} + */ + private void encounteredError(int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(RED.get(), x, y); + progressModel.setText("Exception!", x, y); + } + + /** + * Updates the dialog for solver that timed out. + * + * @param x The solver type index + * @param y The solver index as reported by {@link IsabelleSolver#getSolverIndex()} + */ + private void timedOut(int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setText("Timeout.", x, y); + } + + /** + * Updates the dialog for solver that stopped for unknown reasons. + * + * @param x The solver type index + * @param y The solver index as reported by {@link IsabelleSolver#getSolverIndex()} + */ + private void unknownStopped(int x, int y) { + progressModel.setProgress(0, x, y); + progressModel.setTextColor(Color.BLUE, x, y); + progressModel.setText("Unknown.", x, y); + } + + /** + * Sets the progress text based on the number of solver instances that have processed their + * problem. + * A negative value may be used to indicate the Launcher is still preparing. + * + * @param value The number of solvers that have processed their problem. Negative values + * indicate the launcher is still preparing. + */ + private void setProgressText(int value) { + JProgressBar bar = progressDialog.getProgressBar(); + if (value < 0) { + bar.setString("Preparing... (this might take a few seconds)"); + bar.setStringPainted(true); + } else if (value == bar.getMaximum()) { + bar.setString("Finished."); + bar.setStringPainted(true); + } else { + bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); + bar.setStringPainted(true); + } + } + + /** + * The event that occurs after the discard button was pressed. + * Disposes of the dialog and does nothing else, as the button is only available once the + * launcher has stopped. + */ + protected void discardEvent() { + progressDialog.dispose(); + } + + /** + * Creates a new mediator for the given proof and launcher + * + * @param proof the given proof + * @param launcher the launcher used + */ + public IsabelleLauncherProgressDialogMediator(Proof proof, IsabelleLauncher launcher) { + this.proof = proof; + this.launcher = launcher; + } + + /** + * Prepares the dialog. Opens the dialog. + * Assigns the titles of all solver types to their columns. + * Assigns the titles of all goals to be processed by the launcher. + * + * @param solvers The solvers to be started by the launcher. + */ + private void prepareDialog(Collection solvers) { + this.solvers = solvers; + progressModel = new IsabelleProgressModel(); + + String[] captions = new String[solvers.size()]; + + int i = 0; + for (IsabelleSolver solver : solvers) { + captions[i] = solver.getProblem().getName(); + i++; + } + + progressModel.addColumn(new IsabelleProgressModel.TitleColumn(captions)); + finishedSolvers = new boolean[1][solvers.size()]; + progressModel.addColumn(new IsabelleProgressModel.ProcessColumn(solvers.size())); + + + progressDialog = new IsabelleProgressDialog(progressModel, + new IsabelleProgressDialogListenerImpl(), false, + RESOLUTION, solvers.size(), "", "Isabelle"); + + + SwingUtilities.invokeLater(() -> progressDialog.setVisible(true)); + } + + /** + * Refreshes the progress of all solvers. + */ + private void refreshDialog() { + for (IsabelleSolver solver : solvers) { + refreshProgressOfSolver(solver); + } + } + + /** + * Refreshes the progress of a given solver by calling the requisite method in this class. + * + * @param solver the given solver + */ + private void refreshProgressOfSolver(IsabelleSolver solver) { + IsabelleSolver.SolverState state = solver.getState(); + switch (state) { + case Preparing -> preparing(solver); + case Parsing -> parsing(solver); + case Running -> running(solver); + case Stopped -> stopped(solver); + case Waiting -> waiting(solver); + } + } + + /** + * Updates the dialog for a running solver. + * Updates the progress bar for this solver. + * + * @param solver the running solver + */ + private void running(IsabelleSolver solver) { + long progress = calculateProgress(solver); + progressModel.setProgress((int) progress, 0, solver.getSolverIndex()); + + float remainingTime = calculateRemainingTime(solver); + progressModel.setText(remainingTimeFormat.format(remainingTime) + " sec.", 0, + solver.getSolverIndex()); + } + + /** + * Calculates the amount of progress made as a product of the percentage of the time passed in + * comparison to the timeout duration of the solver and the RESOLUTION of the progress bar. + * + * @param solver The solver whose progress is calculated + * @return The value which reflects the progress made by the solver + */ + private long calculateProgress(IsabelleSolver solver) { + Duration maxDuration = Duration.ofSeconds(solver.getTimeout()); + Instant startTime = solver.getStartTime(); + + return (long) Math.floor(RESOLUTION + * (Duration.between(startTime, Instant.now()).toMillis() + / (double) maxDuration.toMillis())); + } + + /** + * Calculates the time remaining until the timeout of the solver. + * + * @param solver the given solver whose remaining time will be calculated + * @return The remaining time in seconds + */ + private float calculateRemainingTime(IsabelleSolver solver) { + Instant timeoutTime = solver.getStartTime().plusSeconds(solver.getTimeout()); + return Duration.between(Instant.now(), timeoutTime).toMillis() / 1000f; + } + + /** + * Updates the progress bar of a solver which is currently parsing the Isabelle theory for its + * problem. + * + * @param solver the solver whose progress bar will be updated + */ + private void parsing(IsabelleSolver solver) { + progressModel.setText("Parsing...", 0, solver.getSolverIndex()); + } + + /** + * Updates the progress bar of a solver that is waiting to be started. + * + * @param solver the solver whose progress bar will be updated + */ + private void waiting(IsabelleSolver solver) { + } + + /** + * Updates the progress bar of a solver that is currently preparing. + * + * @param solver the solver whose progress bar will be updated + */ + private void preparing(IsabelleSolver solver) { + progressModel.setText("Preparing...", 0, solver.getSolverIndex()); + } + + /** + * Naive implementation of a dialog listener to react to button inputs by the user. + */ + private class IsabelleProgressDialogListenerImpl + implements IsabelleProgressDialog.IsabelleProgressDialogListener { + + + public IsabelleProgressDialogListenerImpl() { + super(); + } + + @Override + public void infoButtonClicked(int column, int row) { + } + + @Override + public void stopButtonClicked() { + stopEvent(); + } + + @Override + public void applyButtonClicked() { + applyEvent(); + } + + @Override + public void discardButtonClicked() { + discardEvent(); + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java similarity index 61% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java index 175de313248..f979493e955 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java @@ -1,27 +1,34 @@ -package org.key_project.isabelletranslation; +/* 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 org.key_project.isabelletranslation.gui.controller; + +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.IssueDialog; import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.PositionedIssueString; import de.uka.ilkd.key.gui.actions.MainWindowAction; import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.rule.IBuiltInRuleApp; -import de.uka.ilkd.key.smt.SMTRuleApp; + +import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.key_project.isabelletranslation.automation.IsabelleLauncher; import org.key_project.isabelletranslation.automation.IsabelleProblem; -import org.key_project.isabelletranslation.automation.IsabelleResult; -import org.key_project.isabelletranslation.automation.IsabelleSolverListener; import org.key_project.isabelletranslation.translation.IllegalFormulaException; import org.key_project.isabelletranslation.translation.IsabelleTranslator; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; - +/** + * Action to translate all open goals. + */ public class TranslateAllAction extends MainWindowAction { private static final Logger LOGGER = LoggerFactory.getLogger(TranslateAllAction.class); @@ -45,7 +52,7 @@ private void generateTranslation() { List translations = new ArrayList<>(); try { - for (Goal goal : mediator.getSelectedProof().openGoals()) { + for (Goal goal : Objects.requireNonNull(mediator.getSelectedProof()).openGoals()) { translations.add(translator.translateProblem(goal)); } } catch (IllegalFormulaException e) { @@ -53,8 +60,6 @@ private void generateTranslation() { return; } - translations.get(0).writeTranslationFiles(settings); - Thread thread = new Thread(() -> { IsabelleLauncher launcher; try { @@ -63,13 +68,21 @@ private void generateTranslation() { throw new RuntimeException(e); } - launcher.addListener(new IsabelleSolverListener.IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); + IsabelleLauncherProgressDialogMediator progressDialogMediator = + new IsabelleLauncherProgressDialogMediator( + mediator.getSelectedProof(), launcher); + + launcher.addListener(progressDialogMediator); try { - launcher.try0ThenSledgehammerAllPooled(translations, settings.getTimeout(), 1); + launcher.launch(translations, settings.getTimeout(), 1); } catch (IOException e) { - throw new RuntimeException(e); + progressDialogMediator.discardEvent(); + PositionedIssueString issueString = new PositionedIssueString( + "Failed to launch Isabelle solvers: " + e.getMessage()); + IssueDialog issueDialog = + new IssueDialog(mainWindow, "Launch failed!", Set.of(issueString), true); + issueDialog.setVisible(true); } - }, "IsabelleControlThread"); thread.start(); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java similarity index 58% rename from keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java rename to keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java index 23e952c0bf7..768c2f15ce6 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java @@ -1,23 +1,29 @@ -package org.key_project.isabelletranslation; +/* 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 org.key_project.isabelletranslation.gui.controller; + +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.actions.MainWindowAction; + +import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.key_project.isabelletranslation.automation.IsabelleLauncher; import org.key_project.isabelletranslation.automation.IsabelleProblem; -import org.key_project.isabelletranslation.automation.IsabelleSolverListener; import org.key_project.isabelletranslation.translation.IllegalFormulaException; import org.key_project.isabelletranslation.translation.IsabelleTranslator; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; - +/** + * Action to translate the selected goal. + */ public class TranslationAction extends MainWindowAction { private static final Logger LOGGER = LoggerFactory.getLogger(TranslationAction.class); @@ -38,6 +44,7 @@ public void actionPerformed(ActionEvent e) { private void generateTranslation() { KeYMediator mediator = getMediator(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); + IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleProblem translation; try { @@ -52,23 +59,24 @@ private void generateTranslation() { list.add(translation); Thread thread = new Thread(() -> { - - IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); - IsabelleLauncher launcher; - try { - launcher = new IsabelleLauncher(settings); - } catch (IOException e) { - throw new RuntimeException(e); - } - - launcher.addListener(new IsabelleSolverListener.IsabelleLauncherProgressDialogMediator(mediator.getSelectedProof())); - try { - launcher.try0ThenSledgehammerAllPooled(list, settings.getTimeout(), 1); - } catch (IOException e) { - throw new RuntimeException(e); - } - - }, "IsabelleLauncherThread"); - thread.start(); + IsabelleLauncher launcher; + try { + launcher = new IsabelleLauncher(settings); + } catch (IOException e) { + throw new RuntimeException(e); + } + + IsabelleLauncherProgressDialogMediator progressDialogMediator = + new IsabelleLauncherProgressDialogMediator( + mediator.getSelectedProof(), launcher); + + launcher.addListener(progressDialogMediator); + try { + launcher.launch(list, settings.getTimeout(), 1); + } catch (IOException e) { + progressDialogMediator.discardEvent(); + } + }, "IsabelleLauncherThread"); + thread.start(); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java index 8e37d1d5249..1e4a4a109f5 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BSumHandler.java @@ -1,23 +1,33 @@ +/* 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 org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.IntegerLDT; -import org.key_project.logic.Term; -import org.key_project.logic.op.Operator; -import org.key_project.logic.op.QuantifiableVariable; -import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.IntegerLDT; + +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; + +/** + * This class handles the translation of the bounded sum function. + * + * @author Nils Buchholz + */ public class BSumHandler implements IsabelleHandler { + /** + * Map of the operators supported by this handler and their respective translation. + */ private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { supportedOperators.clear(); IntegerLDT integerLDT = services.getTypeConverter().getIntegerLDT(); @@ -30,18 +40,12 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { - StringBuilder result = new StringBuilder("("); - result.append(supportedOperators.get(term.op())); - for (QuantifiableVariable bv : term.boundVars()) { - Sort sort = bv.sort(); - result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); - if (trans.isNewSort(sort)) { - trans.addGenericSort(sort); - } - } + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { + StringBuilder result = + QuantifierHandler.makeBoundedVarRef(trans, term, supportedOperators.get(term.op())); result.append("="); - result.append(trans.translate(term.sub(0))).append("..<").append(trans.translate(term.sub(1))).append(". "); + result.append(trans.translate(term.sub(0))).append("..<") + .append(trans.translate(term.sub(1))).append(". "); result.append(trans.translate(term.sub(2))).append(")"); return result; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java index 70059428c03..52447f2a6f0 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/BooleanOpHandler.java @@ -1,23 +1,36 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.BooleanLDT; -import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.Equality; import de.uka.ilkd.key.logic.op.Junctor; -import org.key_project.logic.op.Operator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; +/** + * This class handles the translation of boolean operations and Boolean formulae + * + * @author Nils Buchholz + */ public class BooleanOpHandler implements IsabelleHandler { + /** + * Map of the operators supported by this handler and their respective translation. + */ private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) { BooleanLDT ldt = services.getTypeConverter().getBooleanLDT(); Operator logicFalse = ldt.getFalseConst(); supportedOperators.put(logicFalse, new StringBuilder("False")); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java index 00b93560d94..eeadfc51d55 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.java @@ -1,26 +1,101 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.HeapLDT; +import de.uka.ilkd.key.ldt.JavaDLTheory; +import de.uka.ilkd.key.ldt.LocSetLDT; +import de.uka.ilkd.key.ldt.SeqLDT; import de.uka.ilkd.key.logic.Namespace; import de.uka.ilkd.key.logic.op.JFunction; +import de.uka.ilkd.key.logic.op.SortDependingFunction; + +import org.key_project.logic.Name; import org.key_project.logic.Term; import org.key_project.logic.op.Function; import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.logic.op.SortDependingFunction; -import de.uka.ilkd.key.smt.SMTTranslationException; import org.key_project.logic.op.SortedOperator; +import org.key_project.logic.sort.Sort; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; +import org.jetbrains.annotations.NotNull; +/** + * This class handles the translation of several functions that are already defined in the preamble. + * This prevents the functions being defined twice. + * This class also adds the necessary preamble part to the master handler, which is loaded from the + * "DefinedSymbolsHandler.preamble.xml" file. + * + * @see IsabelleMasterHandler + * + * @author Nils Buchholz + */ public class DefinedSymbolsHandler implements IsabelleHandler { + /** + * Map of the operators supported by this handler and their respective translation. + */ Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { + masterHandler.addPreamblesLocales(handlerSnippets); + masterHandler.addPredefinedSort(JavaDLTheory.ANY, "any"); + + HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); + LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); + SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); + + Namespace sorts = services.getNamespaces().sorts(); + masterHandler.addPredefinedSort( + Objects.requireNonNull(sorts.lookup(new Name("java.lang.Object"))), + "java_lang_Object"); + masterHandler.addPredefinedSort(Objects.requireNonNull(sorts.lookup(new Name("Null"))), + "Null"); + masterHandler.addPredefinedSort(heapLDT.targetSort(), "Heap"); + masterHandler.addPredefinedSort(locSetLDT.targetSort(), "LocSet"); + masterHandler.addPredefinedSort(seqLDT.targetSort(), "Seq"); + + Namespace functionNamespace = services.getNamespaces().functions(); + Map definedFunctions = getDefinedFunctions(); + + Map definedSortDependingFunctions = new HashMap<>(); + definedSortDependingFunctions.put("select", "select"); + definedSortDependingFunctions.put("cast", "cast"); + definedSortDependingFunctions.put("seqGet", "seqGet"); + + for (String name : definedFunctions.keySet()) { + Function function = functionNamespace.lookup(name); + if (function != null) + supportedOperators.put(function, definedFunctions.get(name)); + } + + for (Function function : functionNamespace.elements()) { + if (!(function instanceof SortDependingFunction)) + continue; + String funName = function.name().toString().split("::")[1]; + for (String name : definedSortDependingFunctions.keySet()) { + if (funName.equals(name)) { + supportedOperators.put(function, definedSortDependingFunctions.get(name)); + } + } + } + } + + /** + * Returns the list of predefined functions in the preamble. + * + * @return The list of predefined functions in the preamble. + */ + private static @NotNull Map getDefinedFunctions() { Map definedFunctions = new HashMap<>(); definedFunctions.put("null", "null"); definedFunctions.put("length", "obj_length"); @@ -30,7 +105,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("store", "store"); definedFunctions.put("create", "create"); - //Seq functions + // Seq functions definedFunctions.put("seqLen", "seqLen"); definedFunctions.put("seqIndexOf", "seqIndexOf"); definedFunctions.put("seqGetOutside", "seqGetOutside"); @@ -45,7 +120,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("seqReverse", "seqReverse"); - //LocSet functions + // LocSet functions definedFunctions.put("elementOf", "elementOf"); definedFunctions.put("subset", "subset"); definedFunctions.put("disjoint", "disjoint"); @@ -58,28 +133,7 @@ public void init(IsabelleMasterHandler masterHandler, Services services, Propert definedFunctions.put("allFields", "allFields"); definedFunctions.put("allObjects", "allObjects"); definedFunctions.put("arrayRange", "arrayRange"); - - Map definedSortDependingFunctions = new HashMap<>(); - definedSortDependingFunctions.put("select", "select"); - definedSortDependingFunctions.put("cast", "cast"); - definedSortDependingFunctions.put("seqGet", "seqGet"); - - for (String name : definedFunctions.keySet()) { - Function function = functionNamespace.lookup(name); - if (function != null) - supportedOperators.put(function, definedFunctions.get(name)); - } - - for (Function function : functionNamespace.elements()) { - if (!(function instanceof SortDependingFunction)) - continue; - String funName = function.name().toString().split("::")[1]; - for (String name : definedSortDependingFunctions.keySet()) { - if (funName.equals(name)) { - supportedOperators.put(function, definedSortDependingFunctions.get(name)); - } - } - } + return definedFunctions; } @Override @@ -88,11 +142,13 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { if (term.op() instanceof SortDependingFunction) { - return SortDependingFunctionHandler.getSortDependingFunctionRef(trans, term, (SortDependingFunction) term.op(), - supportedOperators.get(term.op())); + return SortDependingFunctionHandler.getSortDependingFunctionRef(trans, term, + (SortDependingFunction) term.op(), + supportedOperators.get(term.op())); } - return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), supportedOperators.get(term.op())); + return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), + supportedOperators.get(term.op())); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java index afcc30fb20d..58b8d56978b 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/FieldHandler.java @@ -1,33 +1,50 @@ +/* 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 org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Name; -import de.uka.ilkd.key.logic.Namespace; -import org.key_project.logic.Term; -import org.key_project.logic.op.Function; -import org.key_project.logic.op.Operator; -import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.io.IOException; import java.util.Collection; import java.util.HashSet; +import java.util.Objects; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.Namespace; + +import org.key_project.logic.Name; +import org.key_project.logic.Term; +import org.key_project.logic.op.Function; +import org.key_project.logic.op.Operator; +import org.key_project.logic.sort.Sort; + +/** + * This class handles the translation of field values. + * + * @author Nils Buchholz + */ public class FieldHandler implements IsabelleHandler { + /** + * The predefined fields. + */ private final Collection predefinedFields = new HashSet<>(); + /** + * The Field sort. + */ private Sort fieldSort; @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { fieldSort = services.getNamespaces().sorts().lookup("Field"); predefinedFields.add("created"); Namespace sorts = services.getNamespaces().sorts(); - masterHandler.addPredefinedSort(sorts.lookup(new Name("Field")), "Field"); + masterHandler.addPredefinedSort(Objects.requireNonNull(sorts.lookup(new Name("Field"))), + "Field"); } @Override @@ -36,7 +53,7 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); @@ -47,7 +64,7 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr if (predefinedFields.contains(fieldName)) { return new StringBuilder(fieldName); } - trans.addKnownSymbol(term, new StringBuilder(fieldName)); + trans.addSymbolAndDeclaration(term, new StringBuilder(fieldName)); trans.addField((Function) op); } return trans.getKnownSymbol(term); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java index 62276b8a90a..e1826af4196 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InfiniteUnionHandler.java @@ -1,21 +1,34 @@ +/* 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 org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; -import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import de.uka.ilkd.key.java.Services; + +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; + +/** + * This class handles the infiniteUnion function. + * + * @author Nils Buchholz + */ public class InfiniteUnionHandler implements IsabelleHandler { + /** + * Map of the operators supported by this handler and their respective translation. + */ private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { - supportedOperators.put(services.getTypeConverter().getLocSetLDT().getInfiniteUnion(), "infiniteUnion"); + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { + supportedOperators.put(services.getTypeConverter().getLocSetLDT().getInfiniteUnion(), + "infiniteUnion"); } @Override @@ -24,9 +37,12 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Operator op = term.op(); - String arg1 = "{" + trans.translate(term.sub(0)) + "| " + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". True }"; + String arg1 = "{" + + trans.translate(term.sub(0)) + "| " + LogicalVariableHandler.makeVarRef(trans, + term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + + ". True }"; return new StringBuilder("(").append(supportedOperators.get(op)).append(arg1).append(")"); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java index c7c0bcae513..80c3462c61b 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/InstanceOperatorHandler.java @@ -1,24 +1,36 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.Namespace; import de.uka.ilkd.key.logic.op.JFunction; +import de.uka.ilkd.key.logic.op.SortDependingFunction; + import org.key_project.logic.Term; import org.key_project.logic.op.Function; import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.logic.op.SortDependingFunction; -import de.uka.ilkd.key.smt.SMTTranslationException; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; +/** + * This class handles translation of the instance and exactInstance function. + * + * @author Nils Buchholz + */ public class InstanceOperatorHandler implements IsabelleHandler { + /** + * Map of the operators supported by this handler and their respective translation. + */ private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { Namespace functionNamespace = services.getNamespaces().functions(); Map definedSortDependingFunctions = new HashMap<>(); @@ -43,7 +55,7 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { SortDependingFunction op = (SortDependingFunction) term.op(); String functionName = supportedOperators.get(op); String dependingSortTypeName = trans.translateSortName(op.getSortDependingOn()) + "_type"; diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java index 7314293c3fd..aedd6a01eda 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IntegerOpHandler.java @@ -3,23 +3,21 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.IntegerLDT; -import org.key_project.logic.Term; -import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.ldt.IntegerLDT; + +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; + /** - * This SMT translation handler takes care of integer expressions. - *

- * This includes the unary and binary integer operations and relational operations. + * This class handles translation of the integer operators. * - * @author Jonas Schiffl + * @author Nils Buchholz */ public class IntegerOpHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); @@ -27,8 +25,9 @@ public class IntegerOpHandler implements IsabelleHandler { private IntegerLDT integerLDT; @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, - String[] handlerOptions) { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, + String[] handlerOptions) { supportedOperators.clear(); integerLDT = services.getTypeConverter().getIntegerLDT(); @@ -57,11 +56,12 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { List children = trans.translate(term.subs()); Operator op = term.op(); - //negation has a special pattern in Isabelle and thus can't be translated like the other functions + // negation has a special pattern in Isabelle and thus can't be translated like the other + // functions if (op == integerLDT.getNeg()) { return new StringBuilder("(-").append(children.get(0)).append(")"); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java index 88df7fc5296..3b5c9eaa086 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandler.java @@ -3,43 +3,26 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; + import org.key_project.logic.Term; import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.smt.SMTTranslationException; - -import java.io.IOException; -import java.util.Properties; /** - * General interface for routines that translate particular KeY data structures to SMT. - *

- * SMT handlers are loaded via a {@link java.util.ServiceLoader}. - *

- * To implement a new handler, implement this interface and add the classname to a file that - * ServiceLoader reads for SMTHandler. - * - *

Procedure

- *

- * SMT handlers are created using the default constructor without parameters They are always used - * within the same proof, but possibly for several proof obligations. - *

- * After creation, the {@link #init(IsabelleMasterHandler, Services, Properties, String[])} method is called - * that injects the {@link Services} object belonging to the proof. - *

- * During translation, an SMT handler can be asked via {@link #canHandle(Term)} if it can translate - * a term into smt. - *

- * If it returns true, the method {@link #handle(IsabelleMasterHandler, Term)} will be called which returns - * the SMT result in form of an + * This class is a slightly adjusted version of {@link de.uka.ilkd.key.smt.newsmt2.SMTHandler}. It + * largely has the same functionality. * * @author Mattias Ulbrich * @author Jonas Schiffl + * @author Nils Buchholz */ public interface IsabelleHandler { /** - * An enumeration of the possible answers of an handler to the {@link #canHandle(Term)} method. + * An enumeration of the possible answers of a handler to the {@link #canHandle(Term)} method. */ enum Capability { /** @@ -63,16 +46,16 @@ enum Capability { *

* This method may also allocate additional resources that it needs for translation. * - * @param masterHandler the MasterHandler coordinating the other handlers (including the one at - * hand) - * @param services the non-null services object which is relevant for this handler + * @param masterHandler the MasterHandler coordinating the other handlers (including the one at + * hand) + * @param services the non-null services object which is relevant for this handler * @param handlerSnippets the snippets loaded for this handler, null if no snippet property file - * is available for this handler - * @param handlerOptions arbitrary options for the handler to take into account + * is available for this handler + * @param handlerOptions arbitrary options for the handler to take into account * @throws IOException if resources cannot be read. */ void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, - String[] handlerOptions) throws IOException; + String[] handlerOptions) throws IOException; /** * Query if this handler can translate a term. @@ -83,9 +66,9 @@ void init(IsabelleMasterHandler masterHandler, Services services, Properties han * * @param term a non-null term to translate * @return {@link Capability#YES_THIS_OPERATOR} if this handler can successfully translate any - * term with the same toplevel operator, {@link Capability#YES_THIS_INSTANCE} if this - * handler can successfully translate this particular term, {@link Capability#UNABLE} if - * this handler cannot deal with the term. + * term with the same toplevel operator, {@link Capability#YES_THIS_INSTANCE} if this + * handler can successfully translate this particular term, {@link Capability#UNABLE} if + * this handler cannot deal with the term. */ default Capability canHandle(Term term) { return canHandle(term.op()) ? Capability.YES_THIS_OPERATOR : Capability.UNABLE; @@ -98,12 +81,12 @@ default Capability canHandle(Term term) { * * @param op a non-null operator to translate * @return true if this handler can successfully translate all terms with op as toplevel - * operator + * operator */ boolean canHandle(Operator op); /** - * Translate the given term into an SMT SExpression. + * Translate the given term into a StringBuilder. *

* This method will only be called if {@link #canHandle(Term)} returned true for the same term * argument. @@ -112,9 +95,8 @@ default Capability canHandle(Term term) { * to the {@link IsabelleMasterHandler} that it receives. * * @param trans the non-null master handler to which it belongs - * @param term the non-null term to translate - * @return an SExpr representing the term - * @throws SMTTranslationException if the translation fails unexpectedly. + * @param term the non-null term to translate + * @return a StringBuilder containing the translation */ - StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException; + StringBuilder handle(IsabelleMasterHandler trans, Term term); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java index 02c7d47ab4c..1052c5f0ab6 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleHandlerServices.java @@ -3,12 +3,6 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import org.jspecify.annotations.NonNull; -import org.key_project.util.Streams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -19,8 +13,17 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import de.uka.ilkd.key.java.Services; + +import org.jspecify.annotations.NonNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** - * This class provides some infrastructure to the smt translation process. + * Adapted version of the {@link de.uka.ilkd.key.smt.newsmt2.SMTHandlerServices} for the Isabelle + * translation. + *

+ * This class provides some infrastructure to the translation process. *

* In particular, it collects the preamble and the snippets for the handlers such that they need not * be read from disk multiple times. @@ -29,6 +32,7 @@ * * @author Mattias Ulbrich * @author Alicia Appelhagen (load handlers from handler names array instead of ServiceLoader) + * @author Nils Buchholz (adaptation for Isabelle translation) */ public class IsabelleHandlerServices { @@ -48,23 +52,9 @@ public class IsabelleHandlerServices { /** * A map from template handler objects to their smt2 snippets. - *

- * Before removing the ServiceLoader from #getOriginalHandlers, an IdentityHashMap was used - * here. Since the removal of the ServiceLoader leads to snippetMap being modified even after - * creation, concurrent modification by different solver threads becomes possible. Hence, either - * every access to snippetMap needs to be synchronized or it needs to be a ConcurrentHashMap - - * which is not an IdentityHashMap anymore. This should not be a problem as the SMTHandlers - * don't override equals(). */ private final Map snippetMap = new ConcurrentHashMap<>(); - // preamble is volatile since sonarcube tells me the synchronisation scheme - // for loading would be broken otherwise. (MU 2021) - /** - * The smt2 preamble - */ - private volatile String preamble; - /** * lock for synchronisation */ @@ -83,11 +73,11 @@ public static IsabelleHandlerServices getInstance() { } /** - * Load the original/template SMTHandler instances (from the snippetMap) of all handlers + * Load the original/template IsabelleHandler instances (from the snippetMap) of all handlers * specified as arguments. Add fresh handlers to the snippetMap and load the snippets that * belong to these instances if that has not happened yet for any object of a given handler * class. - * + *

* Caution: Do not call this method too often since it may add to the static map of * instances to snippets. *

@@ -97,17 +87,21 @@ public static IsabelleHandlerServices getInstance() { * An empty handlerNames list leads to the usage of the handlers defined by defaultHandlers.txt. * * @param handlerNames a non-null list of non-null strings with class names (s. above) - * @return a fresh collection containing only the original SMTHandlers from the snippetMap's key - * set that match the given handler names. The collection's order matches that of the - * names as well. + * @return a fresh collection containing only the original IsabelleHandlers from the + * snippetMap's key + * set that match the given handler names. The collection's order matches that of the + * names as well. * @throws IOException if loading the snippet Properties for a handler class fails */ - public Collection getTemplateHandlers(String[] handlerNames) throws IOException { + public Collection getTemplateHandlers(String[] handlerNames) + throws IOException { // If handlerNames is empty, use default handlerNames list. if (handlerNames.length == 0) { - InputStream stream = IsabelleHandlerServices.class.getResourceAsStream(DEFAULT_HANDLERS); + InputStream stream = + IsabelleHandlerServices.class.getResourceAsStream(DEFAULT_HANDLERS); + assert stream != null; BufferedReader reader = - new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); handlerNames = reader.lines().toArray(String[]::new); } Collection result = new LinkedList<>(); @@ -134,12 +128,12 @@ public Collection getTemplateHandlers(String[] handlerNames) th } } } catch (ClassNotFoundException e) { - LOGGER.warn(String.format("Could not load IsabelleHandler:%s%s", System.lineSeparator(), - e.getMessage())); + LOGGER.warn("Could not load IsabelleHandler:{}{}", System.lineSeparator(), + e.getMessage()); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException - | IllegalAccessException e) { - LOGGER.warn(String.format("Could not create IsabelleHandler:%s%s", - System.lineSeparator(), e.getMessage())); + | IllegalAccessException e) { + LOGGER.warn("Could not create IsabelleHandler:{}{}", System.lineSeparator(), + e.getMessage()); } } // TODO make sure that the order of handlers in result is the same as the order @@ -151,7 +145,7 @@ public Collection getTemplateHandlers(String[] handlerNames) th // the result collection. private boolean findHandler(Class clazz, Collection result) { Optional handler = - snippetMap.keySet().stream().filter(h -> h.getClass().equals(clazz)).findFirst(); + snippetMap.keySet().stream().filter(h -> h.getClass().equals(clazz)).findFirst(); if (handler.isPresent()) { if (!result.contains(handler.get())) { result.add(handler.get()); @@ -162,20 +156,21 @@ private boolean findHandler(Class clazz, Collection getFreshHandlers(Services services, @NonNull String[] handlerNames, - String[] handlerOptions, IsabelleMasterHandler mh) throws IOException { + String[] handlerOptions, IsabelleMasterHandler mh) throws IOException { List result = new ArrayList<>(); @@ -203,7 +198,8 @@ public List getFreshHandlers(Services services, @NonNull String } /** - * Look up the resource for the snippets of a particular smt handler class. They must be in the + * Look up the resource for the snippets of a particular IsabelleHandler class. They must be in + * the * same package and have the name of the class with ".preamble.xml" attached. * * @param aClass class reference for localisation @@ -222,30 +218,4 @@ private static Properties loadSnippets(Class aClass) throws IOException { } return null; } - - /** - * There is a fixed SMT2lib preamble first sent to the solver. - *

- * Get this preamble. - * - * @return a non-null string, always the same - */ - public String getPreamble() { - try { - if (preamble == null) { - synchronized (handlerModificationLock) { - if (preamble == null) { - // make sure this is only ever read once and everyone - // waits for it. - preamble = Streams.toString( - IsabelleHandlerServices.class.getResourceAsStream("preamble.smt2")); - } - } - } - return preamble; - } catch (IOException e) { - // the caller cannot really deal with exceptions ... - throw new RuntimeException(e); - } - } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java index 970891afb87..0315d70dd37 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleMasterHandler.java @@ -1,63 +1,125 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.*; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; +import de.uka.ilkd.key.logic.sort.ArraySort; +import de.uka.ilkd.key.proof.Goal; + import org.key_project.logic.Term; import org.key_project.logic.op.Function; import org.key_project.logic.op.Operator; import org.key_project.logic.op.SortedOperator; -import de.uka.ilkd.key.logic.sort.ArraySort; import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; import org.key_project.util.collection.ImmutableArray; -import java.io.IOException; -import java.util.*; - +import org.jspecify.annotations.NonNull; + +/** + * This class is responsible for translating the sequent of a given goal. + * It collects all declarations and definitions which need to be added to the translation. + *

+ * The sequent is repeatedly given to the respective {@link IsabelleHandler}, which can translate + * its top most operator. + * + * @author Nils Buchholz + */ public class IsabelleMasterHandler { + /** + * The services object used to obtain the namespace for standard sorts in KeY + */ private final Services services; + /** + * The exceptions thrown by handlers during translation. + */ private final List exceptions = new ArrayList<>(); + /** + * The list of handlers to be used for translation. + */ private final List handlers; + /** + * The preambles added for each of the handlers. + * Currently only two such preambles exist, separating this preamble into multiple preambles is + * a complex undertaking due to various dependencies within it. + */ private final List preambles = new ArrayList<>(); /** - * A list of untranslatable values + * A list of the names of locales that need to be added to the translation locale. + * These can be added by the handler + */ + private final List locales = new ArrayList<>(); + + /** + * A map of operators that were not predefined and their respective translations */ - private final Map unknownValues = new HashMap<>(); + private final Map notPredefinedFunctions = new HashMap<>(); + /** + * A map of predefined sorts and their translations + */ private final Map predefinedSorts = new HashMap<>(); + /** + * A map of sorts that were not predefined and for which a definition needs to be generated in + * the translation theory and their translations. + */ private final Map extraSorts = new HashMap<>(); + /** + * Stores handlers who are able to handle a given operator to avoid searching through the list + * of handlers + */ private final Map handlerMap = new IdentityHashMap<>(); - private final List locales = new ArrayList<>(); - private final Collection constDeclarations = new HashSet<>(); + /** + * The declarations that are added to the locale to introduce variables and functions only found + * on the sequent + */ + private final Collection variableDeclarations = new HashSet<>(); + /** + * A collection of all fields. These require separate storage to add the lemma stating that they + * are separate values. + */ private final Collection newFields = new HashSet<>(); /** - * Create a new handler with the default set of smt handlers. + * Create a new handler with the default set of Isabelle handlers. * - * @param services non-null services - * @param handlerNames fully qualified class names of the handlers to use. If empty, all - * available handlers are used. + * @param services non-null services + * @param handlerNames fully qualified class names of the handlers to use. If empty, all + * available handlers are used. * @param handlerOptions arbitrary String options for the handlers to process * @throws IOException if the handlers cannot be loaded */ public IsabelleMasterHandler(Services services, String[] handlerNames, - String[] handlerOptions) throws IOException { + String[] handlerOptions) throws IOException { this.services = services; - List handlers = IsabelleHandlerServices.getInstance().getFreshHandlers(services, handlerNames, handlerOptions, this); + List handlers = IsabelleHandlerServices.getInstance() + .getFreshHandlers(services, handlerNames, handlerOptions, this); predefinedSorts.put(JavaDLTheory.ANY, new StringBuilder("any")); predefinedSorts.put(JavaDLTheory.FORMULA, new StringBuilder("bool")); this.handlers = handlers; } + /** + * Translates the given term using the handlers. + * + * @param problem the problem to be translated + * @return a string builder containing the translation of the sequent (does not contain the full + * Isabelle theory necessary for proof search. for that see + * {@link IsabelleTranslator#translateProblem(Goal)}) + */ public StringBuilder translate(Term problem) { try { IsabelleHandler cached = handlerMap.get(problem.op()); @@ -69,18 +131,19 @@ public StringBuilder translate(Term problem) { for (IsabelleHandler isabelleHandler : handlers) { IsabelleHandler.Capability response = isabelleHandler.canHandle(problem); switch (response) { - case YES_THIS_INSTANCE -> { - // handle this but do not cache. - return isabelleHandler.handle(this, problem); - } - case YES_THIS_OPERATOR -> { - // handle it and cache it for future instances of the op. - handlerMap.put(problem.op(), isabelleHandler); - return isabelleHandler.handle(this, problem); - } + case YES_THIS_INSTANCE -> { + // handle this but do not cache. + return isabelleHandler.handle(this, problem); + } + case YES_THIS_OPERATOR -> { + // handle it and cache it for future instances of the op. + handlerMap.put(problem.op(), isabelleHandler); + return isabelleHandler.handle(this, problem); + } } } - exceptions.add(new SMTTranslationException("Couldn't translate: \"" + problem.op().name().toString() + "\"")); + exceptions.add(new IllegalFormulaException( + "Couldn't translate: \"" + problem.op().name() + "\"")); return handleAsUnknownValue(problem); } catch (Exception ex) { exceptions.add(ex); @@ -88,6 +151,12 @@ public StringBuilder translate(Term problem) { } } + /** + * Translates multiple terms in the same manner as {@link IsabelleMasterHandler#translate(Term)} + * + * @param terms terms to be translated + * @return a List of StringBuilders containing translations in the same order as the given terms + */ public List translate(ImmutableArray terms) { List result = new LinkedList<>(); for (Term term : terms) { @@ -103,37 +172,45 @@ public List translate(ImmutableArray terms) { * @return a generic translation as unknown value */ private StringBuilder handleAsUnknownValue(Term problem) { - if (unknownValues.containsKey(problem.op())) { - return unknownValues.get(problem.op()); - } - int number = unknownValues.size(); - StringBuilder translation; - StringBuilder abbr = new StringBuilder("unknown_" + problem.op().name().toString()); - var freeVars = problem.freeVars(); - if (freeVars.isEmpty()) { - // simple case: unknown value does not depend on anything else - } else { - // unknown value depends on quantified variables - //TODO implement this + if (notPredefinedFunctions.containsKey(problem.op())) { + return notPredefinedFunctions.get(problem.op()); } - unknownValues.put(problem.op(), abbr); + StringBuilder abbr = new StringBuilder("unknown_" + problem.op().name()); + notPredefinedFunctions.put(problem.op(), abbr); return abbr; } - protected boolean addField(Function field) { - assert (field.sort() == services.getNamespaces().sorts().lookup("Field") && field.arity() == 0); - return newFields.add(unknownValues.get(field)); + /** + * Adds a field value to the newFields collection + * + * @param field a field value + */ + protected void addField(@NonNull Function field) { + assert (field.sort() == services.getNamespaces().sorts().lookup("Field") + && field.arity() == 0); + newFields.add(notPredefinedFunctions.get(field)); } + /** + * Returns the fields not predefined, but found on the sequent. + * + * @return the list of fields found during translation + */ protected Collection getNewFields() { return newFields; } - private void addConstDeclaration(Term term) { + /** + * Adds the necessary line to declare the top-most operator of the given term in the translation + * locale. + * + * @param term the term whose top-most operator is supposed to be introduced + */ + private void addVariableDeclaration(@NonNull Term term) { StringBuilder decl = new StringBuilder(); - assert unknownValues.get(term.op()) != null; + assert notPredefinedFunctions.get(term.op()) != null; decl.append("fixes "); - decl.append(unknownValues.get(term.op())); + decl.append(notPredefinedFunctions.get(term.op())); decl.append("::\""); if (term.op() instanceof SortedOperator) { @@ -156,35 +233,72 @@ private void addConstDeclaration(Term term) { decl.append((translateSortName(term.sort()))); decl.append("\""); } - constDeclarations.add(decl.toString()); + variableDeclarations.add(decl.toString()); } + /** + * Checks whether the given top-most operator of the given term is not predefined + * Used for handlers to check if they need to add a declaration to the translation locale + * + * @param term the term whose top-most operator is + * @return true - the top-most operator is not predefined, false otherwise + */ boolean isNewSymbol(Term term) { - return !unknownValues.containsKey(term.op()); + return !notPredefinedFunctions.containsKey(term.op()); } + /** + * Checks if a given sort has not been defined already. + * + * @param s the sort to check for + * @return true - the sort was not defined yet, false otherwise + */ boolean isNewSort(Sort s) { return (!predefinedSorts.containsKey(s) && !extraSorts.containsKey(s)); } - void addGenericSort(Sort sort) { + /** + * Adds a generic sort to the translation. A generic sort in this context means a sort that is + * not part of the core vocabulary of JFOL as introduced in the KeY book. Examples include java + * class sorts + * + * @param sort the sort to be introduced + */ + void addGenericSort(@NonNull Sort sort) { if (isNewSort(sort)) { - extraSorts.put(sort, new StringBuilder(sort.name().toString().replace("[]", "arr").replace(".", "_"))); + extraSorts.put(sort, + new StringBuilder(sort.name().toString().replace("[]", "arr").replace(".", "_"))); if (sort instanceof ArraySort) { addGenericSort(((ArraySort) sort).elementSort()); } } } + /** + * Adds a preamble to the translation. + * + * @param stringBuilder the preamble in form of a stringbuilder + */ void addPreamble(StringBuilder stringBuilder) { preambles.add(stringBuilder); } + /** + * Returns the list of preambles for the translation + * + * @return the list of preambles + */ List getPreambles() { return preambles; } - String translateSortName(Sort sort) { + /** + * Returns the translation of the given sort. + * + * @param sort sort whose translation is returned + * @return String value containing the translation of the given sort + */ + String translateSortName(@NonNull Sort sort) { if (isNewSort(sort)) { addGenericSort(sort); } @@ -195,6 +309,12 @@ String translateSortName(Sort sort) { } + /** + * Adds the preambles and locales associated with the handlers + * + * @param handlerSnippets the snippets object containing the preambles/locales and their + * contents + */ void addPreamblesLocales(Properties handlerSnippets) { for (Map.Entry entry : handlerSnippets.entrySet()) { String key = (String) entry.getKey(); @@ -207,39 +327,89 @@ void addPreamblesLocales(Properties handlerSnippets) { } } - void addLocale(StringBuilder stringBuilder) { + /** + * Adds a locale name to the translation. This will be included in the translation locale + * + * @param stringBuilder name of the locale + */ + void addLocale(@NonNull StringBuilder stringBuilder) { locales.add(stringBuilder); } + /** + * Returns the list of locales to be added to the translation locale + * + * @return list of locales + */ List getLocales() { return locales; } - void addPredefinedSort(Sort s, String name) { + /** + * Adds a sort to the predefined sorts list. Used by handlers that include their own preamble. + * + * @param s the sort that was predefined + * @param name the name used for the sort in translation + */ + void addPredefinedSort(@NonNull Sort s, String name) { predefinedSorts.put(s, new StringBuilder(name)); } + /** + * Returns the sorts that require a generated declaration in the translation theory. + * + * @return Collection of the sorts that need to be declared in theory + */ Set getExtraSorts() { return extraSorts.keySet(); } - void addKnownSymbol(Term term, StringBuilder s) { - unknownValues.put(term.op(), s); - addConstDeclaration(term); + /** + * Adds the top-most operator of the term to the map containing operators and their + * translations. + * Also adds the necessary declaration line to the list of declarations + * + * @param term the term whose top-most operator is being added + * @param s the translation of the top-most operator + */ + void addSymbolAndDeclaration(Term term, StringBuilder s) { + notPredefinedFunctions.put(term.op(), s); + addVariableDeclaration(term); } + /** + * Returns the translation of a symbol introduced during translation (!not predefined) + * + * @param term the term whose top-most operator will be translated + * @return translation of the top-most operator + */ StringBuilder getKnownSymbol(Term term) { - return unknownValues.get(term.op()); + return notPredefinedFunctions.get(term.op()); } - Collection getConstDeclarations() { - return constDeclarations; + /** + * Returns the declarations that need to be added to the translation locale + * + * @return collection of the declaration lines that need to be added to the translation locale + */ + Collection getVariableDeclarations() { + return variableDeclarations; } + /** + * Returns the set of predefined sorts + * + * @return set of predefined sorts + */ Set getPredefinedSorts() { return predefinedSorts.keySet(); } + /** + * Returns the list of exceptions encountered during translation + * + * @return list of exceptions + */ List getExceptions() { return exceptions; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java index 24b572833d8..304a5adad78 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/IsabelleTranslator.java @@ -1,25 +1,39 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.*; + import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.ldt.JavaDLTheory; 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.sort.ArraySort; -import org.key_project.isabelletranslation.automation.IsabelleProblem; -import org.key_project.isabelletranslation.IsabelleTranslationSettings; -import org.key_project.logic.sort.Sort; import de.uka.ilkd.key.proof.Goal; -import java.io.IOException; -import java.util.*; +import org.key_project.isabelletranslation.IsabelleTranslationSettings; +import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.logic.sort.Sort; +/** + * Translator for Isabelle. + */ public class IsabelleTranslator { - + /** + * Line ending to use in translations + */ private static final String LINE_ENDING = "\n"; + /** + * Services object used to initiate handlers + */ private final Services services; - + /** + * The null sort + */ private final Sort nullSort; public IsabelleTranslator(Services services) { @@ -27,18 +41,29 @@ public IsabelleTranslator(Services services) { nullSort = services.getNamespaces().sorts().lookup("Null"); } + /** + * Translates the given goal. + * + * @param goal goal to translate + * @return IsabelleProblem containing the translation + * @throws IllegalFormulaException if translation fails + */ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaException { Sequent sequent = goal.sequent(); - List antecedents = sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); - List succedents = sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); + List antecedents = + sequent.antecedent().asList().stream().map(SequentFormula::formula).toList(); + List succedents = + sequent.succedent().asList().stream().map(SequentFormula::formula).toList(); IsabelleMasterHandler masterHandler; try { masterHandler = new IsabelleMasterHandler(services, new String[0], new String[0]); } catch (IOException e) { throw new RuntimeException(e); } - List antecedentTranslations = antecedents.stream().map(masterHandler::translate).toList(); - List succedentTranslations = new ArrayList<>(succedents.stream().map(masterHandler::translate).toList()); + List antecedentTranslations = + antecedents.stream().map(masterHandler::translate).toList(); + List succedentTranslations = + new ArrayList<>(succedents.stream().map(masterHandler::translate).toList()); List exceptions = masterHandler.getExceptions(); if (!exceptions.isEmpty()) { @@ -49,86 +74,112 @@ public final IsabelleProblem translateProblem(Goal goal) throws IllegalFormulaEx throw new IllegalFormulaException(message.toString()); } + + // Construction of translation preamble StringBuilder translationPreamble = new StringBuilder(); - translationPreamble.append("theory TranslationPreamble imports Main \"HOL-Combinatorics.List_Permutation\" begin").append(LINE_ENDING); + translationPreamble.append( + "theory TranslationPreamble imports Main \"HOL-Combinatorics.List_Permutation\" begin") + .append(LINE_ENDING); for (StringBuilder preamble : masterHandler.getPreambles()) { translationPreamble.append(LINE_ENDING).append(preamble).append(LINE_ENDING); } translationPreamble.append("end"); - StringBuilder sequentTranslation = new StringBuilder(IsabelleTranslationSettings.getInstance().getHeader()).append(LINE_ENDING); - //TODO make this into a tree structure to avoid excessive looping (over sorts) | sort the implementation queue - Map> sortParentsMap = getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); + // Construct translation theory + StringBuilder translationTheory = + new StringBuilder(IsabelleTranslationSettings.getInstance().getHeader()) + .append(LINE_ENDING); + + // Find the sorts present on sequent to add definitions for sorts not in preamble + Map> sortParentsMap = + getSortsParents(masterHandler.getExtraSorts(), masterHandler.getPredefinedSorts()); Map sortImplemented = new HashMap<>(); sortParentsMap.keySet().forEach((Sort sort) -> sortImplemented.put(sort, false)); masterHandler.getPredefinedSorts().forEach((Sort sort) -> sortImplemented.put(sort, true)); Queue sortImplementationQueue = new LinkedList<>(sortParentsMap.keySet()); - addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(translationTheory, sortImplementationQueue, sortImplemented, + sortParentsMap, masterHandler); - sequentTranslation.append("locale varsAndFunctions"); + + // Construct proof locale + translationTheory.append("locale varsAndFunctions"); List locales = masterHandler.getLocales(); + // used for formatting boolean locale_empty = true; + // add any supplementary locales like integer operation locale if (!locales.isEmpty()) { - sequentTranslation.append(" = "); - sequentTranslation.append(locales.remove(0)); + translationTheory.append(" = "); + translationTheory.append(locales.remove(0)); locale_empty = false; } for (StringBuilder locale : locales) { - sequentTranslation.append(" + ").append(locale); + translationTheory.append(" + ").append(locale); } - Collection constDecls = masterHandler.getConstDeclarations(); - if (!constDecls.isEmpty() && locale_empty) { - sequentTranslation.append(" = "); - sequentTranslation.append(locales.remove(0)); + // Add declarations for variables present on sequent that are not in preamble + Collection variableDeclarations = masterHandler.getVariableDeclarations(); + if (!variableDeclarations.isEmpty() && locale_empty) { + translationTheory.append(" = "); + translationTheory.append(locales.remove(0)); locale_empty = false; - } else if (!constDecls.isEmpty()) { - sequentTranslation.append(" + ").append(LINE_ENDING); + } else if (!variableDeclarations.isEmpty()) { + translationTheory.append(" + ").append(LINE_ENDING); } - for (String constDecl : constDecls) { - sequentTranslation.append(LINE_ENDING).append(constDecl); + for (String variableDecl : variableDeclarations) { + translationTheory.append(LINE_ENDING).append(variableDecl); } - sequentTranslation.append(LINE_ENDING); + translationTheory.append(LINE_ENDING); + // Add assumption, that all field values are distinct. This is based on the KeY book if (!masterHandler.getNewFields().isEmpty()) { - sequentTranslation.append("assumes distinct_fields:"); - sequentTranslation.append(getDistinctFieldLemma(masterHandler.getNewFields())); - sequentTranslation.append(LINE_ENDING); + translationTheory.append("assumes distinct_fields:"); + translationTheory.append(getDistinctFieldLemma(masterHandler.getNewFields())); + translationTheory.append(LINE_ENDING); } - //This did not seem helpful from my testing - //sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); + // This did not seem helpful from my testing, would add the assumption, that all sorts are + // disjunct + // sequentTranslation.append(getDistinctExtraSortsAssumptions(masterHandler)); + + translationTheory.append("begin").append(LINE_ENDING); - sequentTranslation.append("begin").append(LINE_ENDING); - sequentTranslation.append("theorem solve: "); + // Add proof theorem + translationTheory.append("theorem solve: "); for (int i = 0; i < antecedentTranslations.size(); i++) { StringBuilder antecedentFormula = antecedentTranslations.get(i); - sequentTranslation.append(LINE_ENDING).append("assumes antecedent_").append(i).append(":\"").append(antecedentFormula).append("\""); + translationTheory.append(LINE_ENDING).append("assumes antecedent_").append(i) + .append(":\"").append(antecedentFormula).append("\""); } - sequentTranslation.append(LINE_ENDING); - sequentTranslation.append("shows \""); + translationTheory.append(LINE_ENDING); + translationTheory.append("shows \""); if (succedentTranslations.isEmpty()) { - sequentTranslation.append("False"); + translationTheory.append("False"); } else { - sequentTranslation.append(succedentTranslations.get(0)); + translationTheory.append(succedentTranslations.get(0)); } for (int i = 1; i < succedentTranslations.size(); i++) { - StringBuilder succedentFormula = succedentTranslations.get(i); - sequentTranslation.append(LINE_ENDING).append("\\").append(succedentFormula); + translationTheory.append(LINE_ENDING).append("\\").append(succedentFormula); } - sequentTranslation.append("\""); + translationTheory.append("\""); - return new IsabelleProblem(goal, translationPreamble.toString(), sequentTranslation.toString()); + return new IsabelleProblem(goal, translationPreamble.toString(), + translationTheory.toString()); } + /** + * Creates an assumption, that all sorts are disjunct (mod null). + * + * @param masterHandler masterHandler that handled translation + * @return assumption, that sorts are disjunct + */ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler masterHandler) { Set sorts = masterHandler.getExtraSorts(); Queue sortsCheckQueue = new LinkedList<>(sorts); @@ -140,20 +191,27 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas continue; } String sType = masterHandler.translateSortName(s) + "_type"; - String sVal = "(" + masterHandler.translateSortName(s) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + masterHandler.translateSortName(s) + ")"; + String sVal = "(" + masterHandler.translateSortName(s) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + + masterHandler.translateSortName(s) + ")"; for (Sort s2 : sortsCheckQueue) { if (s2 == JavaDLTheory.ANY || s2 == JavaDLTheory.FORMULA) { continue; } if (!s.extendsTrans(s2) && !s2.extendsTrans(s)) { String s2Type = masterHandler.translateSortName(s2) + "_type"; - String s2Val = "(" + masterHandler.translateSortName(s2) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + masterHandler.translateSortName(s2) + ")"; + String s2Val = + "(" + masterHandler.translateSortName(s2) + "\\<^sub>v\\<^sub>a\\<^sub>l::" + + masterHandler.translateSortName(s2) + ")"; if (nullSort.extendsTrans(s) && nullSort.extendsTrans(s2)) { - sortsAssumptions.append("assumes disjointModNull_").append(masterHandler.translateSortName(s)).append("_").append(masterHandler.translateSortName(s2)) - .append(":\"").append(sVal).append(" = ").append(s2Val).append("\\ s=null\"").append(LINE_ENDING); + sortsAssumptions.append("assumes disjointModNull_") + .append(masterHandler.translateSortName(s)).append("_") + .append(masterHandler.translateSortName(s2)) + .append(":\"").append(sVal).append(" = ").append(s2Val) + .append("\\ s=null\"").append(LINE_ENDING); } else { - //Sorts are unrelated. need to add distinctness assumption - sortsAssumptions.append("assumes \"disjointTypes ").append(sType).append(" ").append(s2Type).append("\"").append(LINE_ENDING); + // Sorts are unrelated. need to add distinctness assumption + sortsAssumptions.append("assumes \"disjointTypes ").append(sType) + .append(" ").append(s2Type).append("\"").append(LINE_ENDING); } } } @@ -161,6 +219,12 @@ private StringBuilder getDistinctExtraSortsAssumptions(IsabelleMasterHandler mas return sortsAssumptions; } + /** + * Lemma to show fields are distinct + * + * @param newFields the list of translations of field variables + * @return a lemma stating the distinctness of all field variables + */ private StringBuilder getDistinctFieldLemma(Collection newFields) { if (newFields.isEmpty()) return new StringBuilder(); @@ -174,137 +238,216 @@ private StringBuilder getDistinctFieldLemma(Collection newFields) return distinctFieldLemma; } - private void addSortsDefinitions(StringBuilder sequentTranslation, Queue sortImplementationQueue, Map sortImplemented, - Map> sortParentsMap, IsabelleMasterHandler masterHandler) { + /** + * Adds the definitions for the given sorts to the given translation theory. + * Works recursively using the queue of sorts to be implemented + * + * @param translationTheory {@link StringBuilder} containing the translation theory up to this + * point + * @param sortImplementationQueue queue for the implementation of sorts + * @param sortImplemented Map to check whether a sort has been implemented + * @param sortParentsMap Map, mapping a sort to the set of its parents + * @param masterHandler the masterHandler used during translation + */ + private void addSortsDefinitions(StringBuilder translationTheory, + Queue sortImplementationQueue, Map sortImplemented, + Map> sortParentsMap, IsabelleMasterHandler masterHandler) { if (sortImplementationQueue.isEmpty()) { return; } + // Ensure that a sort is not implemented before its parents + // Instead push it to the end of the queue Sort sort = sortImplementationQueue.poll(); for (Sort parent : sortParentsMap.get(sort)) { if (!sortImplemented.get(parent)) { sortImplementationQueue.add(sort); - addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(translationTheory, sortImplementationQueue, sortImplemented, + sortParentsMap, masterHandler); return; } } + + // Ensure an array sort is not implemented before its elementsort if ((sort instanceof ArraySort) && !sortImplemented.get(((ArraySort) sort).elementSort())) { sortImplementationQueue.add(sort); - addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(translationTheory, sortImplementationQueue, sortImplemented, + sortParentsMap, masterHandler); return; } + + + // Add generated declaration String sortName = masterHandler.translateSortName(sort); String UNIV = sortName + "_UNIV"; - sequentTranslation.append("(* generated declaration for sort: ").append(sort.name().toString()).append(" *)").append(LINE_ENDING); - sequentTranslation.append("lemma ex_").append(UNIV).append(":"); - sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")).append(LINE_ENDING); - sequentTranslation.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); - + translationTheory.append("(* generated declaration for sort: ") + .append(sort.name()).append(" *)").append(LINE_ENDING); + // Lemma showing there is at least one element in this sort + translationTheory.append("lemma ex_").append(UNIV).append(":"); + translationTheory.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), "{bottom}")) + .append(LINE_ENDING); + translationTheory.append(" by simp").append(LINE_ENDING).append(LINE_ENDING); - sequentTranslation.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); + // Introduce the universe of this sort + translationTheory.append("consts").append(LINE_ENDING).append(UNIV).append("::\"any set\"") + .append(LINE_ENDING); + translationTheory.append(LINE_ENDING); - sequentTranslation.append("specification (").append(UNIV).append(") "); - sequentTranslation.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - sequentTranslation.append(" using ex_").append(UNIV).append(" by blast").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); + // Use specification to specify the properties of the universe of this sort (subset of + // parents) + translationTheory.append("specification (").append(UNIV).append(") "); + translationTheory.append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)) + .append(LINE_ENDING); + translationTheory.append(" using ex_").append(UNIV).append(" by blast") + .append(LINE_ENDING); + translationTheory.append(LINE_ENDING); + // Reformulate specification as lemma for easier use by Isabelle String UNIV_spec_lemma_name = UNIV + "_specification"; - sequentTranslation.append("lemma ").append(UNIV_spec_lemma_name).append(":").append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)).append(LINE_ENDING); - sequentTranslation.append(" by (metis (mono_tags, lifting) ").append(UNIV).append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING); + translationTheory.append("lemma ").append(UNIV_spec_lemma_name).append(":") + .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), UNIV)) + .append(LINE_ENDING); + translationTheory.append(" by (metis (mono_tags, lifting) ").append(UNIV) + .append("_def someI_ex ex_").append(UNIV).append(")").append(LINE_ENDING); + translationTheory.append(LINE_ENDING); - sequentTranslation.append("typedef ").append(sortName).append(" = \"").append(UNIV).append("\"").append(LINE_ENDING); + // Defines this sort as a new type in Isabelle based on the established universe + translationTheory.append("typedef ").append(sortName).append(" = \"").append(UNIV) + .append("\"").append(LINE_ENDING); String repName = sortName + "2any"; String absName = "any2" + sortName; - sequentTranslation.append(" morphisms ").append(repName).append(" ").append(absName).append(LINE_ENDING); - sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" by auto").append(LINE_ENDING).append(LINE_ENDING); - - sequentTranslation.append("declare [[coercion ").append(repName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + // Add morphisms that map between the sort and the any sort + translationTheory.append(" morphisms ").append(repName).append(" ").append(absName) + .append(LINE_ENDING); + translationTheory.append(" using ").append(UNIV_spec_lemma_name).append(" by auto") + .append(LINE_ENDING).append(LINE_ENDING); + // Add coercions for Isabelle to use coercive subtyping + translationTheory.append("declare [[coercion ").append(repName).append("]]") + .append(LINE_ENDING).append(LINE_ENDING); + // Repeat properties of type for UNIV constants of Isabelle + // Improves performance and shortens proofs. Used in schema String IsabelleTypeUniverseOfSort = "(UNIV::" + sortName + " set)"; - sequentTranslation.append("lemma ").append(sortName).append("_type_specification[simp]:") - .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), IsabelleTypeUniverseOfSort)) + translationTheory.append("lemma ").append(sortName).append("_type_specification[simp]:") + .append(getUnivSpec(masterHandler, sortParentsMap.get(sort), + IsabelleTypeUniverseOfSort)) .append(LINE_ENDING); - sequentTranslation.append(" using ").append(UNIV_spec_lemma_name).append(" using type_definition.Rep_range type_definition_").append(sortName).append(" by blast").append(LINE_ENDING); - sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); - + translationTheory.append(" using ").append(UNIV_spec_lemma_name) + .append(" using type_definition.Rep_range type_definition_").append(sortName) + .append(" by blast").append(LINE_ENDING); + translationTheory.append(LINE_ENDING).append(LINE_ENDING); + + // extra coercions for all other parent types + // may lead to extra performance if left out, because Isabelle will only need to deal with + // comparisons in any for (Sort parentSort : sortParentsMap.get(sort)) { if (parentSort == JavaDLTheory.ANY) { continue; } String parentSortName = masterHandler.translateSortName(parentSort); String parentSortInj = sortName + "2" + parentSortName; - sequentTranslation.append(LINE_ENDING).append("fun ").append(parentSortInj).append(" where \"").append(parentSortInj) - .append(" x = ").append("any2").append(parentSortName).append(" (").append(repName).append(" x)\"").append(LINE_ENDING); - sequentTranslation.append("declare [[coercion ").append(parentSortInj).append("]]").append(LINE_ENDING).append(LINE_ENDING); + translationTheory.append(LINE_ENDING).append("fun ").append(parentSortInj) + .append(" where \"").append(parentSortInj) + .append(" x = ").append("any2").append(parentSortName).append(" (") + .append(repName).append(" x)\"").append(LINE_ENDING); + translationTheory.append("declare [[coercion ").append(parentSortInj).append("]]") + .append(LINE_ENDING).append(LINE_ENDING); } - sequentTranslation.append("instantiation ").append(sortName).append("::any").append(LINE_ENDING); - sequentTranslation.append("begin").append(LINE_ENDING); + // Instantiation of any typeclass for this sort + // the typeclass provides polymorphisms for the cast functions + translationTheory.append("instantiation ").append(sortName).append("::any") + .append(LINE_ENDING); + translationTheory.append("begin").append(LINE_ENDING); String to_any_fun_Name = "to_any_" + sortName; - sequentTranslation.append("fun ").append(to_any_fun_Name) - .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName).append(" x\"") + translationTheory.append("fun ").append(to_any_fun_Name) + .append(" where \"").append(to_any_fun_Name).append(" x = ").append(repName) + .append(" x\"") .append(LINE_ENDING); String cast_fun_Name = "cast_" + sortName; - sequentTranslation.append("fun ").append(cast_fun_Name) - .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName).append(" x\"") + translationTheory.append("fun ").append(cast_fun_Name) + .append(" where \"").append(cast_fun_Name).append(" x = ").append(absName) + .append(" x\"") .append(LINE_ENDING); - sequentTranslation.append("instance by standard").append(LINE_ENDING); - sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); + translationTheory.append("instance by standard").append(LINE_ENDING); + translationTheory.append("end").append(LINE_ENDING).append(LINE_ENDING); + // coercion of null sort to this sort if (nullSort.extendsTrans(sort)) { String null_to_sort_name = "Null2" + sortName; - sequentTranslation.append("fun ").append(null_to_sort_name).append(" where \"").append(null_to_sort_name) + translationTheory.append("fun ").append(null_to_sort_name).append(" where \"") + .append(null_to_sort_name) .append(" x = ").append(absName).append("(Null2any x)\"").append(LINE_ENDING); - sequentTranslation.append("declare [[coercion Null2").append(sortName).append("]]").append(LINE_ENDING).append(LINE_ENDING); + translationTheory.append("declare [[coercion Null2").append(sortName).append("]]") + .append(LINE_ENDING).append(LINE_ENDING); } + // Instantiation of array typeclass, which provides polymorphism for element type if (sort instanceof ArraySort) { - sequentTranslation.append("instantiation ").append(sortName).append("::array").append(LINE_ENDING); - sequentTranslation.append("begin").append(LINE_ENDING); + translationTheory.append("instantiation ").append(sortName).append("::array") + .append(LINE_ENDING); + translationTheory.append("begin").append(LINE_ENDING); String element_type_name = "element_type_" + sortName; - String elementSortName = masterHandler.translateSortName(((ArraySort) sort).elementSort()); - String elementSortType = "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; - sequentTranslation.append("fun ").append(element_type_name) + String elementSortName = + masterHandler.translateSortName(((ArraySort) sort).elementSort()); + String elementSortType = + "Abs_javaDL_type ((UNIV::" + elementSortName + " set)::any set)"; + translationTheory.append("fun ").append(element_type_name) .append(" where \"").append(element_type_name) .append(" (x::").append(sortName).append(")").append(" = ") .append(elementSortType).append("\"") .append(LINE_ENDING); - sequentTranslation.append("instance by standard").append(LINE_ENDING); - sequentTranslation.append("end").append(LINE_ENDING).append(LINE_ENDING); + translationTheory.append("instance by standard").append(LINE_ENDING); + translationTheory.append("end").append(LINE_ENDING).append(LINE_ENDING); } + // Constant representing the sort as a Abs_javaDL_type value String typeConstName = sortName + "_type"; - sequentTranslation.append("definition \"").append(typeConstName).append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); + translationTheory.append("definition \"").append(typeConstName) + .append(" = Abs_javaDL_type ").append(IsabelleTypeUniverseOfSort).append("\""); - sequentTranslation.append(LINE_ENDING).append(LINE_ENDING); + translationTheory.append(LINE_ENDING).append(LINE_ENDING); sortImplemented.put(sort, true); - addSortsDefinitions(sequentTranslation, sortImplementationQueue, sortImplemented, sortParentsMap, masterHandler); + addSortsDefinitions(translationTheory, sortImplementationQueue, sortImplemented, + sortParentsMap, masterHandler); } - private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, String insert) { - List parentSortNames = new ArrayList<>(parents.stream().map(masterHandler::translateSortName).toList()); + /** + * Creates the statement about the properties of the universe of a sort. Subset of the universes + * of its parents + * + * @param masterHandler masterhandler used during translation + * @param parents parent sorts of the sort + * @param insert name of the universe constant + * @return the statement about the properties of the universe of a sort + */ + private static String getUnivSpec(IsabelleMasterHandler masterHandler, Set parents, + String insert) { + List parentSortNames = + new ArrayList<>(parents.stream().map(masterHandler::translateSortName).toList()); StringBuilder univSpec = new StringBuilder(); if (parentSortNames.isEmpty()) { parentSortNames.add("any"); } - univSpec.append("\"").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(0)).append(" set)"); + univSpec.append("\"").append(insert).append(" \\ (UNIV::") + .append(parentSortNames.get(0)).append(" set)"); for (int i = 1; i < parentSortNames.size(); i++) { - univSpec.append(" \\ ").append(insert).append(" \\ (UNIV::").append(parentSortNames.get(i)).append(" set)"); + univSpec.append(" \\ ").append(insert).append(" \\ (UNIV::") + .append(parentSortNames.get(i)).append(" set)"); } univSpec.append(" \\ bottom \\ ").append(insert).append("\""); return univSpec.toString(); } private static Map> getSortsParents(Set sorts, Set outsideParents) { + // may want to avoid some of the looping over sorts by presorting? HashMap> result = new HashMap<>(); for (Sort sort : sorts) { Set parents = new HashSet<>(); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java index a6699889106..e449fcca253 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java @@ -1,19 +1,27 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.LogicVariable; + +import org.key_project.logic.Term; import org.key_project.logic.op.Operator; import org.key_project.logic.sort.Sort; -import java.util.Properties; - +/** + * Handles the translation of LogicVariables. + */ public class LogicalVariableHandler implements IsabelleHandler { - static final String VAR_PREFIX = "var_"; + static final String VAR_POSTFIX = UninterpretedSymbolsHandler.PREFIX; @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) { } @@ -31,9 +39,18 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) { return makeVarRef(trans, term.toString(), sort); } + /** + * Used to reference a given variable in the translation. + * + * @param trans The master handler used for translation + * @param name intended name of the variable + * @param sort sort of the variable + * @return reference of the given variable in the translation + */ public static StringBuilder makeVarRef(IsabelleMasterHandler trans, String name, Sort sort) { StringBuilder result = new StringBuilder("("); - result.append(VAR_PREFIX).append(name).append("::").append(trans.translateSortName(sort)).append(")"); + result.append(name).append(VAR_POSTFIX).append("::").append(trans.translateSortName(sort)) + .append(")"); return result; } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java index aae07917435..846453b9af5 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/NumberConstantsHandler.java @@ -3,18 +3,17 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.AbstractTermTransformer; + +import org.key_project.logic.Term; import org.key_project.logic.op.Function; import org.key_project.logic.op.Operator; -import java.util.Properties; - /** * This handler is responsible to render number constants Z(3(2(1(#)))) as "123". - *

- * TODO Should that also do character constants (C) with the same machinery? */ public class NumberConstantsHandler implements IsabelleHandler { @@ -22,8 +21,9 @@ public class NumberConstantsHandler implements IsabelleHandler { private Services services; @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, - String[] handlerOptions) { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, + String[] handlerOptions) { this.services = services; numberSymbol = services.getTypeConverter().getIntegerLDT().getNumberSymbol(); } @@ -35,10 +35,12 @@ public boolean canHandle(Operator op) { @Override public StringBuilder handle(IsabelleMasterHandler trans, Term term) { - //TODO This needs an updated AbstractTermTransformer to comply with the new ncore package of KeY + // TODO This needs an updated AbstractTermTransformer to comply with the new ncore package + // of KeY assert (term instanceof de.uka.ilkd.key.logic.Term); - String string = AbstractTermTransformer.convertToDecimalString((de.uka.ilkd.key.logic.Term) term, services); + String string = AbstractTermTransformer + .convertToDecimalString((de.uka.ilkd.key.logic.Term) term, services); return new StringBuilder("(").append(string).append("::int)"); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java index 7efc9fe5470..f9952fd1fe2 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/ObserverFunctionHandler.java @@ -1,20 +1,27 @@ +/* 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 org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; -import de.uka.ilkd.key.logic.op.ObserverFunction; -import org.key_project.logic.op.Operator; -import org.key_project.logic.op.SortedOperator; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.io.IOException; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.op.ObserverFunction; + +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; +import org.key_project.logic.op.SortedOperator; + +/** + * Handles translation of Observer functions. + */ public class ObserverFunctionHandler implements IsabelleHandler { @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { } @@ -24,19 +31,22 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { if (trans.isNewSymbol(term)) { Operator op = term.op(); Matcher m = Pattern.compile("<(.*?)>").matcher(op.name().toString()); String functionName; if (m.find()) { - functionName = op.name().toString().replace("<" + m.group(1) + ">", "_" + m.group(1)) - .replace("::", "_").replace("$", "").replace(".", "_"); + functionName = + op.name().toString().replace("<" + m.group(1) + ">", "_" + m.group(1)) + .replace("::", "_").replace("$", "").replace(".", "_"); } else { - functionName = op.name().toString().replace("::", "_").replace("$", "").replace(".", "_"); + functionName = + op.name().toString().replace("::", "_").replace("$", "").replace(".", "_"); } - trans.addKnownSymbol(term, new StringBuilder(functionName)); + trans.addSymbolAndDeclaration(term, new StringBuilder(functionName)); } - return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), trans.getKnownSymbol(term).toString()); + return UninterpretedSymbolsHandler.getFunctionRef(trans, term, (SortedOperator) term.op(), + trans.getKnownSymbol(term).toString()); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java index bd07032e379..d53e8c030fc 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/PolymorphicHandler.java @@ -3,28 +3,25 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; +import java.util.List; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; import de.uka.ilkd.key.logic.op.Equality; import de.uka.ilkd.key.logic.op.IfThenElse; -import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.smt.SMTTranslationException; -import java.util.List; -import java.util.Properties; +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; /** - * This handler treats polymorphic symbols, in particular if-then-else and equals. - * - * @author Jonas Schiffl + * This handles translation of equals and if-then-else */ public class PolymorphicHandler implements IsabelleHandler { @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, - String[] handlerOptions) { - // nothing to be done - // there are also no snippets. + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, + String[] handlerOptions) { } @Override @@ -33,7 +30,7 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { Operator op = term.op(); StringBuilder result; if (op == Equality.EQUALS) { diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java index 896ef5f7443..0879e50177d 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/QuantifierHandler.java @@ -1,23 +1,30 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.op.Quantifier; + import org.key_project.logic.Term; import org.key_project.logic.op.Operator; import org.key_project.logic.op.QuantifiableVariable; -import de.uka.ilkd.key.logic.op.Quantifier; import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; +/** + * This handles translation of quantifiers. + */ public class QuantifierHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { supportedOperators.put(Quantifier.ALL, "\\"); supportedOperators.put(Quantifier.EX, "\\"); } @@ -28,19 +35,34 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { + StringBuilder result = makeBoundedVarRef(trans, term, supportedOperators.get(term.op())); + result.append(". ("); + result.append(trans.translate(term.sub(0))).append("))"); + return result; + } + + /** + * Makes a reference to a binding variable and the variables it binds + * + * @param trans master handler used for translation + * @param term the term in which the binding variable occurs + * @param name name of the binding variable in translation + * @return a reference to a binding variable and the variables it binds + */ + public static StringBuilder makeBoundedVarRef(IsabelleMasterHandler trans, Term term, + String name) { StringBuilder result = new StringBuilder("("); - result.append(supportedOperators.get(term.op())); + result.append(name); for (QuantifiableVariable bv : term.boundVars()) { Sort sort = bv.sort(); - result.append(" ").append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); + result.append(" ") + .append(LogicalVariableHandler.makeVarRef(trans, bv.name().toString(), sort)); if (trans.isNewSort(sort)) { trans.addGenericSort(sort); } } - result.append(". ("); - result.append(trans.translate(term.sub(0))).append("))"); return result; } -} \ No newline at end of file +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java index c3cd098983d..3a7f2d2a708 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SeqDefHandler.java @@ -1,21 +1,28 @@ +/* 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 org.key_project.isabelletranslation.translation; -import de.uka.ilkd.key.java.Services; -import org.key_project.logic.Term; -import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.smt.SMTTranslationException; - import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import de.uka.ilkd.key.java.Services; + +import org.key_project.logic.Term; +import org.key_project.logic.op.Operator; + +/** + * Handles translation of seqDef function. + */ public class SeqDefHandler implements IsabelleHandler { private final Map supportedOperators = new HashMap<>(); @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { supportedOperators.put(services.getTypeConverter().getSeqLDT().getSeqDef(), "SeqDef"); } @@ -25,12 +32,14 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { - Operator op = term.op(); + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { StringBuilder arg1 = trans.translate(term.sub(0)); StringBuilder arg2 = trans.translate(term.sub(1)); - String arg3 = "(\\" + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), term.boundVars().get(0).sort()) + ". " + - " to_any (" + trans.translate(term.sub(2)) + "))"; + String arg3 = "(\\" + + LogicalVariableHandler.makeVarRef(trans, term.boundVars().get(0).name().toString(), + term.boundVars().get(0).sort()) + + ". " + + " to_any (" + trans.translate(term.sub(2)) + "))"; return new StringBuilder("(seqDef ").append(arg1).append(arg2).append(arg3).append(")"); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java index c051a71cdcc..a02f7a17d10 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/SortDependingFunctionHandler.java @@ -1,20 +1,27 @@ +/* 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 org.key_project.isabelletranslation.translation; +import java.io.IOException; +import java.util.Properties; +import java.util.stream.Collectors; + import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.op.SortDependingFunction; + import org.key_project.logic.Term; import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.logic.op.SortDependingFunction; import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; - -import java.io.IOException; -import java.util.Properties; -import java.util.stream.Collectors; +/** + * Handles translation of sort depending functions + */ public class SortDependingFunctionHandler implements IsabelleHandler { @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, String[] handlerOptions) throws IOException { + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, String[] handlerOptions) throws IOException { } @@ -24,7 +31,7 @@ public boolean canHandle(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { assert term.op() instanceof SortDependingFunction; SortDependingFunction op = (SortDependingFunction) term.op(); Sort dependentSort = op.getSortDependingOn(); @@ -34,8 +41,9 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr } StringBuilder name; if (trans.isNewSymbol(term)) { - name = LogicalVariableHandler.makeVarRef(trans, op.name().toString().split("::")[1], dependentSort); - trans.addKnownSymbol(term, name); + name = LogicalVariableHandler.makeVarRef(trans, op.name().toString().split("::")[1], + dependentSort); + trans.addSymbolAndDeclaration(term, name); } else { name = trans.getKnownSymbol(term); } @@ -43,10 +51,22 @@ public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTr return getSortDependingFunctionRef(trans, term, op, name.toString()); } - static StringBuilder getSortDependingFunctionRef(IsabelleMasterHandler trans, Term term, SortDependingFunction op, String name) { + /** + * Creates a reference to a sort depending function + * + * @param trans master handler used for translation + * @param term term the function occurs in + * @param op the function + * @param name the name of the function in translation + * @return reference to a sort depending function for use in translation + */ + static StringBuilder getSortDependingFunctionRef(IsabelleMasterHandler trans, Term term, + SortDependingFunction op, String name) { StringBuilder ref = new StringBuilder("(").append(name).append("::"); - String parameterTypesDecl = op.argSorts().stream().map(trans::translateSortName).collect(Collectors.joining("=>")); - ref.append(parameterTypesDecl).append("=>").append(trans.translateSortName(op.sort())).append(")"); + String parameterTypesDecl = + op.argSorts().stream().map(trans::translateSortName).collect(Collectors.joining("=>")); + ref.append(parameterTypesDecl).append("=>").append(trans.translateSortName(op.sort())) + .append(")"); return UninterpretedSymbolsHandler.getFunctionRef(trans, term, op, ref.toString()); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java index a7c532d1466..c352c4fb106 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java @@ -3,50 +3,32 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.translation; +import java.util.List; +import java.util.Properties; + import de.uka.ilkd.key.java.Services; -import de.uka.ilkd.key.ldt.HeapLDT; -import de.uka.ilkd.key.ldt.JavaDLTheory; -import de.uka.ilkd.key.ldt.LocSetLDT; -import de.uka.ilkd.key.ldt.SeqLDT; -import org.key_project.logic.Name; -import de.uka.ilkd.key.logic.Namespace; +import de.uka.ilkd.key.logic.op.ProgramVariable; + import org.key_project.logic.Term; import org.key_project.logic.op.Function; import org.key_project.logic.op.Operator; -import de.uka.ilkd.key.logic.op.ProgramVariable; import org.key_project.logic.op.SortedOperator; import org.key_project.logic.sort.Sort; -import de.uka.ilkd.key.smt.SMTTranslationException; - -import java.util.List; -import java.util.Properties; /** * This handler is a fallback handler that introduces a new uninterpreted function symbol with - * prefix "u_". + * prefix in subscript *

* According declarations are added. */ public class UninterpretedSymbolsHandler implements IsabelleHandler { - public final static String PREFIX = "var_"; + public final static String PREFIX = "\\<^sub>v\\<^sub>a\\<^sub>r"; @Override - public void init(IsabelleMasterHandler masterHandler, Services services, Properties handlerSnippets, - String[] handlerOptions) { - masterHandler.addPreamblesLocales(handlerSnippets); - masterHandler.addPredefinedSort(JavaDLTheory.ANY, "any"); - - HeapLDT heapLDT = services.getTypeConverter().getHeapLDT(); - LocSetLDT locSetLDT = services.getTypeConverter().getLocSetLDT(); - SeqLDT seqLDT = services.getTypeConverter().getSeqLDT(); - - Namespace sorts = services.getNamespaces().sorts(); - masterHandler.addPredefinedSort(sorts.lookup(new Name("java.lang.Object")), "java_lang_Object"); - masterHandler.addPredefinedSort(sorts.lookup(new Name("Null")), "Null"); - masterHandler.addPredefinedSort(heapLDT.targetSort(), "Heap"); - masterHandler.addPredefinedSort(locSetLDT.targetSort(), "LocSet"); - masterHandler.addPredefinedSort(seqLDT.targetSort(), "Seq"); + public void init(IsabelleMasterHandler masterHandler, Services services, + Properties handlerSnippets, + String[] handlerOptions) { } @Override @@ -67,19 +49,30 @@ private static boolean bindsVars(Operator op) { } @Override - public StringBuilder handle(IsabelleMasterHandler trans, Term term) throws SMTTranslationException { + public StringBuilder handle(IsabelleMasterHandler trans, Term term) { SortedOperator op = (SortedOperator) term.op(); if (trans.isNewSymbol(term)) { - String name = PREFIX + op.name().toString(); - trans.addKnownSymbol(term, new StringBuilder(name.replace("::", "_").replace(".", "_") - .replace("$", "_").replace("#", "_"))); + String name = PREFIX + op.name(); + trans.addSymbolAndDeclaration(term, + new StringBuilder(name.replace("::", "_").replace(".", "_") + .replace("$", "_").replace("#", "_"))); } String name = trans.getKnownSymbol(term).toString(); return getFunctionRef(trans, term, op, name); } - static StringBuilder getFunctionRef(IsabelleMasterHandler trans, Term term, SortedOperator op, String name) { + /** + * Creates a reference to a function for use in translations. + * + * @param trans master handler used for translation + * @param term the term the function occurs in as the top operator + * @param op the function + * @param name name of the function in translations + * @return a reference to a function for use in translations. + */ + static StringBuilder getFunctionRef(IsabelleMasterHandler trans, Term term, SortedOperator op, + String name) { List children = trans.translate(term.subs()); StringBuilder result = new StringBuilder("("); result.append(name); diff --git a/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.preamble.xml b/keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.preamble.xml similarity index 100% rename from keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.preamble.xml rename to keyext.isabelletranslation/src/main/resources/org/key_project/isabelletranslation/translation/DefinedSymbolsHandler.preamble.xml From f51cf4120d602173a56fe61613385eb36663dce0 Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Thu, 17 Oct 2024 11:30:57 +0200 Subject: [PATCH 240/248] preparing to handle partially translatable proofs --- .../automation/IsabelleLauncher.java | 2 +- .../gui/controller/TranslateAllAction.java | 34 +++++++++++-------- .../gui/controller/TranslationAction.java | 16 +++++---- 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index 1712473c81e..3202f29c256 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -61,7 +61,7 @@ public class IsabelleLauncher implements IsabelleSolverListener { private final LinkedBlockingDeque solverQueue = new LinkedBlockingDeque<>(); - public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) throws IOException { + public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) { this.settings = settings; } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java index f979493e955..2897d184d9f 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java @@ -5,10 +5,7 @@ import java.awt.event.ActionEvent; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import java.util.*; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.IssueDialog; @@ -51,22 +48,31 @@ private void generateTranslation() { IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); List translations = new ArrayList<>(); - try { - for (Goal goal : Objects.requireNonNull(mediator.getSelectedProof()).openGoals()) { + Map translationExceptions = new HashMap<>(); + for (Goal goal : Objects.requireNonNull(mediator.getSelectedProof()).openGoals()) { + try { translations.add(translator.translateProblem(goal)); + } catch (IllegalFormulaException e) { + translationExceptions.put(goal, e); + } + } + if (!translations.isEmpty()) { + Set issueStrings = new HashSet<>(); + for (Goal goal : translationExceptions.keySet()) { + String issueStringBuilder = "Translation failed for this goal:" + + System.lineSeparator() + "Goal: " + + goal.node().serialNr() + " " + + translationExceptions.get(goal).getMessage(); + issueStrings.add(new PositionedIssueString(issueStringBuilder)); } - } catch (IllegalFormulaException e) { - LOGGER.error("Failed to generate translation", e); + IssueDialog issueDialog = + new IssueDialog(mainWindow, "Translations failed!", issueStrings, false); + issueDialog.setVisible(true); return; } Thread thread = new Thread(() -> { - IsabelleLauncher launcher; - try { - launcher = new IsabelleLauncher(IsabelleTranslationSettings.getInstance()); - } catch (IOException e) { - throw new RuntimeException(e); - } + IsabelleLauncher launcher = new IsabelleLauncher(settings); IsabelleLauncherProgressDialogMediator progressDialogMediator = new IsabelleLauncherProgressDialogMediator( diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java index 768c2f15ce6..333d079fa65 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java @@ -7,9 +7,12 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Set; import de.uka.ilkd.key.core.KeYMediator; +import de.uka.ilkd.key.gui.IssueDialog; import de.uka.ilkd.key.gui.MainWindow; +import de.uka.ilkd.key.gui.PositionedIssueString; import de.uka.ilkd.key.gui.actions.MainWindowAction; import org.key_project.isabelletranslation.IsabelleTranslationSettings; @@ -50,7 +53,11 @@ private void generateTranslation() { try { translation = translator.translateProblem(mediator.getSelectedGoal()); } catch (IllegalFormulaException e) { - LOGGER.error("Failed to generate translation", e); + PositionedIssueString issueString = new PositionedIssueString( + "Failed to translate Goal " + mediator.getSelectedGoal().node().serialNr() + ": " + e.getMessage()); + IssueDialog issueDialog = + new IssueDialog(mainWindow, "Translations failed!", Set.of(issueString), false); + issueDialog.setVisible(true); return; } @@ -59,12 +66,7 @@ private void generateTranslation() { list.add(translation); Thread thread = new Thread(() -> { - IsabelleLauncher launcher; - try { - launcher = new IsabelleLauncher(settings); - } catch (IOException e) { - throw new RuntimeException(e); - } + IsabelleLauncher launcher = new IsabelleLauncher(settings); IsabelleLauncherProgressDialogMediator progressDialogMediator = new IsabelleLauncherProgressDialogMediator( From 09c70e9b80fc078b6f4d72dca9c4a4ed995d55ba Mon Sep 17 00:00:00 2001 From: BookWood Date: Sun, 20 Oct 2024 15:44:32 +0200 Subject: [PATCH 241/248] fix interrupts during preparations causing dialog to freeze --- .../automation/IsabelleLauncher.java | 12 ++- .../automation/IsabelleProblem.java | 4 + .../IsabelleResourceController.java | 86 ++++++++++--------- .../IsabelleSledgehammerSolver.java | 19 ++-- .../gui/controller/TranslateAllAction.java | 24 ++++-- 5 files changed, 86 insertions(+), 59 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index 3202f29c256..852c98057d3 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -106,7 +106,13 @@ public void launch(List problems, int timeoutSeconds, notifyLauncherStarted(); - resourceController.init(); + try { + resourceController.init(); + } catch (InterruptedException e) { + stopAll(); + notifyLauncherStopped(); + return; + } notifyPreparationFinished(); LOGGER.info("Setup complete, starting {} problems...", problems.size()); @@ -114,7 +120,7 @@ public void launch(List problems, int timeoutSeconds, try { executorService.invokeAll(solverQueue); } catch (InterruptedException e) { - throw new RuntimeException(e); + stopAll(); } catch (RejectedExecutionException e) { // Launcher has been shutdown before running instances // Nothing to do here, intended behavior @@ -145,7 +151,7 @@ private void notifyPreparationFinished() { * Notifies all listeners that the launcher has started. */ private void notifyLauncherStarted() { - listeners.forEach(listener -> listener.launcherStarted(this, solverQueue)); + listeners.forEach(listener -> listener.launcherStarted(this, new ArrayList<>(solverQueue))); } /** diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java index 5afe9c20bad..9aa64ba6e44 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleProblem.java @@ -135,4 +135,8 @@ public void writeTranslationFiles(IsabelleTranslationSettings settings) throws I public boolean hasTranslation() { return translation != null || preamble != null; } + + public IllegalFormulaException getTranslationException() { + return exception; + } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java index 8839ad5fd46..0ce3291c89b 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java @@ -74,7 +74,7 @@ public class IsabelleResourceController { * Creates a resource controller. Initializes the settings. * * @param numberOfInstances the maximum number of Isabelle instances to create at any time - * @param settings {@link IsabelleTranslationSettings} to be used + * @param settings {@link IsabelleTranslationSettings} to be used */ public IsabelleResourceController(int numberOfInstances, IsabelleTranslationSettings settings) { this.settings = settings; @@ -90,7 +90,7 @@ public IsabelleResourceController(int numberOfInstances, IsabelleTranslationSett * * @throws IOException If instance creation failed. */ - public void init() throws IOException { + public void init() throws IOException, InterruptedException { for (int i = 0; i < numberOfInstances; i++) { if (!isShutdown()) { IsabelleResource newResource = createIsabelleResource(); @@ -157,7 +157,7 @@ public void returnResource(IsabelleResource resource) { if (resource.isDestroyed()) { try { resource = createIsabelleResource(); - } catch (IOException e) { + } catch (IOException | InterruptedException e) { // Should not occur. If it was possible to create instances during creation, it // should be possible now. shutdownGracefully(); @@ -184,7 +184,7 @@ public boolean isShutdown() { * @return fresh IsabelleResource * @throws IOException if instance creation failed */ - private IsabelleResource createIsabelleResource() throws IOException { + private IsabelleResource createIsabelleResource() throws IOException, InterruptedException { Callable creationTask = () -> { Isabelle isabelleInstance = startIsabelleInstance(); Theory theory = beginTheory(isabelleInstance, settings); @@ -196,10 +196,14 @@ private IsabelleResource createIsabelleResource() throws IOException { shutdownGracefully(); throw new RuntimeException(e); } catch (ExecutionException e) { + LOGGER.error("Error during Isabelle setup"); + if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } - LOGGER.error("Error during Isabelle setup"); + if (e.getCause() instanceof InterruptedException) { + throw (InterruptedException) e.getCause(); + } throw new RuntimeException(e); } catch (RejectedExecutionException e) { throw new RuntimeException("Unreachable code during Isabelle instance creation"); @@ -219,9 +223,9 @@ private Isabelle startIsabelleInstance() throws IOException { Isabelle isabelle; try { Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); isabelle = new Isabelle(setup); } catch (Exception e) { LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); @@ -241,59 +245,61 @@ private Isabelle startIsabelleInstance() throws IOException { */ private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings settings) { MLFunction3, Theory> begin_theory = - MLValue.compileFunction( - "fn (path, header, parents) => Resources.begin_theory path header parents", - isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), - new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLValue.compileFunction( + "fn (path, header, parents) => Resources.begin_theory path header parents", + isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); MLFunction2 header_read = - MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), - Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter(), Implicits.theoryHeaderConverter()); TheoryHeader header = header_read .apply(settings.getHeader(), Position.none(isabelle), isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), - Implicits.positionConverter()) + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = settings.getTranslationPath(); return begin_theory.apply(topDir, header, - header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), - new ListConverter<>(Implicits.theoryConverter())) + header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } /** * A record bundling a given instance to a theory. This is necessary as a theory object is only usable in conjunction with the instance used to create it. + * * @param instance the instance - * @param theory the theory + * @param theory the theory */ private record IsabelleResourceImpl(Isabelle instance, Theory theory) implements IsabelleResource { - @Override - public boolean isDestroyed() { - return instance.isDestroyed(); - } + @Override + public boolean isDestroyed() { + return instance.isDestroyed(); + } - @Override - public void destroy() { - instance.destroy(); - } + @Override + public void destroy() { + instance.destroy(); + } - private void interruptIntern() throws IsabelleMLException { - instance.executeMLCodeNow("error \"Interrupt\""); - } + private void interruptIntern() throws IsabelleMLException { + instance.executeMLCodeNow("error \"Interrupt\""); + } - @Override - public void interrupt() { - try { - interruptIntern(); - } catch (IsabelleMLException e) { - // Always throws this due to the way Isabelle is interrupted. + @Override + public void interrupt() { + try { + interruptIntern(); + } catch (IsabelleMLException e) { + // Always throws this due to the way Isabelle is interrupted. + } } } -}} +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java index c389e008da1..0523ac42a34 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java @@ -118,7 +118,7 @@ public Throwable getException() { public void abort() { // If solver already completed, the interrupt should be ignored if (setFinalResult(IsabelleResult.getInterruptedResult())) { - handleInterrupt(); + handleInterrupt(new InterruptedException()); } } @@ -175,12 +175,17 @@ public IsabelleResult getFinalResult() { @Override public IsabelleResult call() throws InterruptedException { + //Return error result, if problem does not have a translation + if (!problem.hasTranslation()) { + return handleIsabelleError(problem.getTranslationException()); + } + // Ensure there is an active IsabelleInstance setSolverState(SolverState.Preparing); try { isabelleResource = resourceController.getIsabelleResource(); } catch (InterruptedException e) { - return handleInterrupt(); + return handleInterrupt(e); } notifyProcessStarted(); @@ -192,7 +197,7 @@ public IsabelleResult call() throws InterruptedException { try { toplevel = parseTheory(isabelleResource); } catch (InterruptedException e) { - return handleInterrupt(); + return handleInterrupt(e); } catch (IsabelleMLException e) { return handleIsabelleError(e); } @@ -210,7 +215,7 @@ public IsabelleResult call() throws InterruptedException { return this.result; } } catch (InterruptedException e) { - return handleInterrupt(); + return handleInterrupt(e); } catch (IsabelleMLException e) { return handleIsabelleError(e); } @@ -383,13 +388,13 @@ fun go_run (state, thy) = * * @return Interrupt result */ - private IsabelleResult handleInterrupt() { + private IsabelleResult handleInterrupt(InterruptedException e) { setFinalResult(IsabelleResult.getInterruptedResult()); returnResource(); setComputationTime(); Thread.currentThread().interrupt(); setSolverState(SolverState.Stopped); - notifyProcessError(new InterruptedException()); + notifyProcessError(e); return this.result; } @@ -414,7 +419,7 @@ public java.time.Duration getComputationTime() { } private void setComputationTime() { - if (getStartTime() == null) { + if (getStartTime() != null) { computationTime = java.time.Duration.between(getStartTime(), Instant.now()); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java index 2897d184d9f..0ba2240e36e 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java @@ -38,37 +38,43 @@ public TranslateAllAction(MainWindow mainWindow) { public void actionPerformed(ActionEvent e) { LOGGER.info("Translating..."); - generateTranslation(); + solveOpenGoals(); } - private void generateTranslation() { + private void solveOpenGoals() { KeYMediator mediator = getMediator(); IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); List translations = new ArrayList<>(); Map translationExceptions = new HashMap<>(); + List untranslatableGoals = new ArrayList<>(); for (Goal goal : Objects.requireNonNull(mediator.getSelectedProof()).openGoals()) { try { translations.add(translator.translateProblem(goal)); } catch (IllegalFormulaException e) { translationExceptions.put(goal, e); + //Add problem without translation + untranslatableGoals.add(goal); } } - if (!translations.isEmpty()) { + if (!translationExceptions.isEmpty()) { Set issueStrings = new HashSet<>(); for (Goal goal : translationExceptions.keySet()) { - String issueStringBuilder = "Translation failed for this goal:" + - System.lineSeparator() + "Goal: " + - goal.node().serialNr() + " " + + String issueStringBuilder = "Translation failed for" + + "Goal " + goal.node().serialNr() + ": " + translationExceptions.get(goal).getMessage(); issueStrings.add(new PositionedIssueString(issueStringBuilder)); } IssueDialog issueDialog = - new IssueDialog(mainWindow, "Translations failed!", issueStrings, false); + new IssueDialog(mainWindow, "Translations failed!", issueStrings, translations.isEmpty()); issueDialog.setVisible(true); - return; + + if (translations.isEmpty()) { + return; + } + untranslatableGoals.forEach(goal -> translations.add(new IsabelleProblem(goal, translationExceptions.get(goal)))); } Thread thread = new Thread(() -> { @@ -89,7 +95,7 @@ private void generateTranslation() { new IssueDialog(mainWindow, "Launch failed!", Set.of(issueString), true); issueDialog.setVisible(true); } - }, "IsabelleControlThread"); + }, "IsabelleLauncherThread"); thread.start(); } } From 12d129f2fc6561acad2203ef2026070e7eb8a99b Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Sun, 20 Oct 2024 18:41:18 +0200 Subject: [PATCH 242/248] now opens launcher when some problems are untranslatable instead of opening issue dialog --- .../automation/IsabelleLauncher.java | 18 +-- .../automation/IsabelleNotFoundException.java | 12 ++ .../IsabelleResourceController.java | 104 +++++++++--------- .../IsabelleSledgehammerSolver.java | 2 +- .../gui/controller/TranslateAllAction.java | 70 +----------- .../gui/controller/TranslationAction.java | 53 +++++---- 6 files changed, 109 insertions(+), 150 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleNotFoundException.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index 852c98057d3..b2fcb1f6e59 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -72,17 +72,21 @@ public IsabelleLauncher(@NonNull IsabelleTranslationSettings settings) { * @param problems The problems for which proof search will be started * @param timeoutSeconds The timeout setting to use for the Isabelle instances * @param instanceCount The number of concurrent Isabelle instances - * @throws IOException If {@link IsabelleResourceController} fails to initiate || translation - * files could not be written + * @throws IOException translation files could not be written + * @throws IsabelleNotFoundException If {@link IsabelleResourceController} fails to initiate */ public void launch(List problems, int timeoutSeconds, - int instanceCount) throws IOException { - if (problems.isEmpty()) { - return; + int instanceCount) throws IOException, IsabelleNotFoundException { + // Ensure the preamble theory file is present, so theory objects can be created. + // If no problems have translations, don't write anything + // All solvers should recognize this and throw an appropriate exception + List problemsWithTranslation = + problems.stream().filter(IsabelleProblem::hasTranslation).toList(); + + if (!problemsWithTranslation.isEmpty()) { + problemsWithTranslation.get(0).writeTranslationFiles(settings); } - // Ensure the preamble theory file is present, so theory objects can be created. - problems.get(0).writeTranslationFiles(settings); IsabelleResourceController resourceController = new IsabelleResourceController(instanceCount, settings); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleNotFoundException.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleNotFoundException.java new file mode 100644 index 00000000000..45854f9c206 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleNotFoundException.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 org.key_project.isabelletranslation.automation; + +import java.io.IOException; + +public class IsabelleNotFoundException extends IOException { + public IsabelleNotFoundException(String message) { + super(message); + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java index 0ce3291c89b..921141f7997 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleResourceController.java @@ -3,7 +3,6 @@ * SPDX-License-Identifier: GPL-2.0-only */ package org.key_project.isabelletranslation.automation; -import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.concurrent.*; @@ -74,7 +73,7 @@ public class IsabelleResourceController { * Creates a resource controller. Initializes the settings. * * @param numberOfInstances the maximum number of Isabelle instances to create at any time - * @param settings {@link IsabelleTranslationSettings} to be used + * @param settings {@link IsabelleTranslationSettings} to be used */ public IsabelleResourceController(int numberOfInstances, IsabelleTranslationSettings settings) { this.settings = settings; @@ -88,9 +87,9 @@ public IsabelleResourceController(int numberOfInstances, IsabelleTranslationSett /** * Creates the Isabelle instances. * - * @throws IOException If instance creation failed. + * @throws IsabelleNotFoundException If instance creation failed. */ - public void init() throws IOException, InterruptedException { + public void init() throws IsabelleNotFoundException, InterruptedException { for (int i = 0; i < numberOfInstances; i++) { if (!isShutdown()) { IsabelleResource newResource = createIsabelleResource(); @@ -157,11 +156,15 @@ public void returnResource(IsabelleResource resource) { if (resource.isDestroyed()) { try { resource = createIsabelleResource(); - } catch (IOException | InterruptedException e) { + } catch (IsabelleNotFoundException e) { // Should not occur. If it was possible to create instances during creation, it // should be possible now. shutdownGracefully(); LOGGER.error(e.getMessage()); + } catch (InterruptedException e) { + shutdownGracefully(); + LOGGER.error(e.getMessage()); + Thread.currentThread().interrupt(); } } else { resource.interrupt(); @@ -182,9 +185,10 @@ public boolean isShutdown() { * Creates a new {@link IsabelleResource} via the thread pool used for this purpose. * * @return fresh IsabelleResource - * @throws IOException if instance creation failed + * @throws IsabelleNotFoundException if instance creation failed */ - private IsabelleResource createIsabelleResource() throws IOException, InterruptedException { + private IsabelleResource createIsabelleResource() + throws IsabelleNotFoundException, InterruptedException { Callable creationTask = () -> { Isabelle isabelleInstance = startIsabelleInstance(); Theory theory = beginTheory(isabelleInstance, settings); @@ -192,17 +196,14 @@ private IsabelleResource createIsabelleResource() throws IOException, Interrupte }; try { return instanceCreatorService.submit(creationTask).get(); - } catch (InterruptedException e) { - shutdownGracefully(); - throw new RuntimeException(e); } catch (ExecutionException e) { LOGGER.error("Error during Isabelle setup"); - if (e.getCause() instanceof IOException) { - throw (IOException) e.getCause(); + if (e.getCause() instanceof IsabelleNotFoundException) { + throw (IsabelleNotFoundException) e.getCause(); } if (e.getCause() instanceof InterruptedException) { - throw (InterruptedException) e.getCause(); + throw (InterruptedException) e.getCause(); } throw new RuntimeException(e); } catch (RejectedExecutionException e) { @@ -215,21 +216,23 @@ private IsabelleResource createIsabelleResource() throws IOException, Interrupte * the settings. * * @return freshly started Isabelle instance - * @throws IOException if Isabelle could not be found at the location stored in the settings + * @throws IsabelleNotFoundException if Isabelle could not be found at the location stored in + * the settings */ - private Isabelle startIsabelleInstance() throws IOException { + private Isabelle startIsabelleInstance() throws IsabelleNotFoundException { ArrayList sessionRoots = new ArrayList<>(); sessionRoots.add(settings.getTranslationPath()); Isabelle isabelle; try { Isabelle.Setup setup = JIsabelle.setupSetLogic("KeYTranslations", - JIsabelle.setupSetSessionRoots(sessionRoots, - JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), - JIsabelle.setup(settings.getIsabellePath())))); + JIsabelle.setupSetSessionRoots(sessionRoots, + JIsabelle.setupSetWorkingDirectory(settings.getTranslationPath(), + JIsabelle.setup(settings.getIsabellePath())))); isabelle = new Isabelle(setup); } catch (Exception e) { LOGGER.error("Can't find Isabelle at {}", settings.getIsabellePath()); - throw new IOException("Can't find Isabelle at " + settings.getIsabellePath()); + throw new IsabelleNotFoundException( + "Can't find Isabelle at " + settings.getIsabellePath()); } return isabelle; } @@ -245,29 +248,29 @@ private Isabelle startIsabelleInstance() throws IOException { */ private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings settings) { MLFunction3, Theory> begin_theory = - MLValue.compileFunction( - "fn (path, header, parents) => Resources.begin_theory path header parents", - isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), - new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); + MLValue.compileFunction( + "fn (path, header, parents) => Resources.begin_theory path header parents", + isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter()), Implicits.theoryConverter()); MLFunction2 header_read = - MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), - Implicits.positionConverter(), Implicits.theoryHeaderConverter()); + MLValue.compileFunction("fn (text,pos) => Thy_Header.read pos text", isabelle, + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter(), Implicits.theoryHeaderConverter()); TheoryHeader header = header_read .apply(settings.getHeader(), Position.none(isabelle), isabelle, - de.unruh.isabelle.mlvalue.Implicits.stringConverter(), - Implicits.positionConverter()) + de.unruh.isabelle.mlvalue.Implicits.stringConverter(), + Implicits.positionConverter()) .retrieveNow(Implicits.theoryHeaderConverter(), isabelle); Path topDir = settings.getTranslationPath(); return begin_theory.apply(topDir, header, - header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, - Implicits.pathConverter(), Implicits.theoryHeaderConverter(), - new ListConverter<>(Implicits.theoryConverter())) + header.imports(isabelle).map((String name) -> Theory.apply(name, isabelle)), isabelle, + Implicits.pathConverter(), Implicits.theoryHeaderConverter(), + new ListConverter<>(Implicits.theoryConverter())) .retrieveNow(Implicits.theoryConverter(), isabelle); } @@ -279,27 +282,26 @@ private static Theory beginTheory(Isabelle isabelle, IsabelleTranslationSettings */ private record IsabelleResourceImpl(Isabelle instance, Theory theory) implements IsabelleResource { - @Override - public boolean isDestroyed() { - return instance.isDestroyed(); - } + @Override + public boolean isDestroyed() { + return instance.isDestroyed(); + } - @Override - public void destroy() { - instance.destroy(); - } + @Override + public void destroy() { + instance.destroy(); + } - private void interruptIntern() throws IsabelleMLException { - instance.executeMLCodeNow("error \"Interrupt\""); - } + private void interruptIntern() throws IsabelleMLException { + instance.executeMLCodeNow("error \"Interrupt\""); + } - @Override - public void interrupt() { - try { - interruptIntern(); - } catch (IsabelleMLException e) { - // Always throws this due to the way Isabelle is interrupted. - } + @Override + public void interrupt() { + try { + interruptIntern(); + } catch (IsabelleMLException e) { + // Always throws this due to the way Isabelle is interrupted. } } -} +}} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java index 0523ac42a34..fb760a07b89 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java @@ -175,7 +175,7 @@ public IsabelleResult getFinalResult() { @Override public IsabelleResult call() throws InterruptedException { - //Return error result, if problem does not have a translation + // Return error result, if problem does not have a translation if (!problem.hasTranslation()) { return handleIsabelleError(problem.getTranslationException()); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java index 0ba2240e36e..45790ae1a04 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslateAllAction.java @@ -4,21 +4,11 @@ package org.key_project.isabelletranslation.gui.controller; import java.awt.event.ActionEvent; -import java.io.IOException; import java.util.*; import de.uka.ilkd.key.core.KeYMediator; -import de.uka.ilkd.key.gui.IssueDialog; import de.uka.ilkd.key.gui.MainWindow; -import de.uka.ilkd.key.gui.PositionedIssueString; import de.uka.ilkd.key.gui.actions.MainWindowAction; -import de.uka.ilkd.key.proof.Goal; - -import org.key_project.isabelletranslation.IsabelleTranslationSettings; -import org.key_project.isabelletranslation.automation.IsabelleLauncher; -import org.key_project.isabelletranslation.automation.IsabelleProblem; -import org.key_project.isabelletranslation.translation.IllegalFormulaException; -import org.key_project.isabelletranslation.translation.IsabelleTranslator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,64 +28,8 @@ public TranslateAllAction(MainWindow mainWindow) { public void actionPerformed(ActionEvent e) { LOGGER.info("Translating..."); - solveOpenGoals(); - } - - - private void solveOpenGoals() { KeYMediator mediator = getMediator(); - IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); - IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); - - List translations = new ArrayList<>(); - Map translationExceptions = new HashMap<>(); - List untranslatableGoals = new ArrayList<>(); - for (Goal goal : Objects.requireNonNull(mediator.getSelectedProof()).openGoals()) { - try { - translations.add(translator.translateProblem(goal)); - } catch (IllegalFormulaException e) { - translationExceptions.put(goal, e); - //Add problem without translation - untranslatableGoals.add(goal); - } - } - if (!translationExceptions.isEmpty()) { - Set issueStrings = new HashSet<>(); - for (Goal goal : translationExceptions.keySet()) { - String issueStringBuilder = "Translation failed for" + - "Goal " + goal.node().serialNr() + ": " + - translationExceptions.get(goal).getMessage(); - issueStrings.add(new PositionedIssueString(issueStringBuilder)); - } - IssueDialog issueDialog = - new IssueDialog(mainWindow, "Translations failed!", issueStrings, translations.isEmpty()); - issueDialog.setVisible(true); - - if (translations.isEmpty()) { - return; - } - untranslatableGoals.forEach(goal -> translations.add(new IsabelleProblem(goal, translationExceptions.get(goal)))); - } - - Thread thread = new Thread(() -> { - IsabelleLauncher launcher = new IsabelleLauncher(settings); - - IsabelleLauncherProgressDialogMediator progressDialogMediator = - new IsabelleLauncherProgressDialogMediator( - mediator.getSelectedProof(), launcher); - - launcher.addListener(progressDialogMediator); - try { - launcher.launch(translations, settings.getTimeout(), 1); - } catch (IOException e) { - progressDialogMediator.discardEvent(); - PositionedIssueString issueString = new PositionedIssueString( - "Failed to launch Isabelle solvers: " + e.getMessage()); - IssueDialog issueDialog = - new IssueDialog(mainWindow, "Launch failed!", Set.of(issueString), true); - issueDialog.setVisible(true); - } - }, "IsabelleLauncherThread"); - thread.start(); + TranslationAction.solveGoals( + Objects.requireNonNull(mediator.getSelectedProof()).openGoals(), mediator, mainWindow); } } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java index 333d079fa65..bd72a249f18 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/TranslationAction.java @@ -5,21 +5,22 @@ import java.awt.event.ActionEvent; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; import de.uka.ilkd.key.core.KeYMediator; import de.uka.ilkd.key.gui.IssueDialog; import de.uka.ilkd.key.gui.MainWindow; import de.uka.ilkd.key.gui.PositionedIssueString; import de.uka.ilkd.key.gui.actions.MainWindowAction; +import de.uka.ilkd.key.proof.Goal; import org.key_project.isabelletranslation.IsabelleTranslationSettings; import org.key_project.isabelletranslation.automation.IsabelleLauncher; +import org.key_project.isabelletranslation.automation.IsabelleNotFoundException; import org.key_project.isabelletranslation.automation.IsabelleProblem; import org.key_project.isabelletranslation.translation.IllegalFormulaException; import org.key_project.isabelletranslation.translation.IsabelleTranslator; +import org.key_project.util.collection.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,31 +41,26 @@ public TranslationAction(MainWindow mainWindow) { public void actionPerformed(ActionEvent e) { LOGGER.info("Translating..."); - generateTranslation(); + KeYMediator mediator = getMediator(); + solveGoals(ImmutableList.of(getMediator().getSelectedGoal()), mediator, mainWindow); } - - private void generateTranslation() { - KeYMediator mediator = getMediator(); - IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); + static void solveGoals(ImmutableList goals, KeYMediator mediator, MainWindow mainWindow) { IsabelleTranslationSettings settings = IsabelleTranslationSettings.getInstance(); + IsabelleTranslator translator = new IsabelleTranslator(mediator.getServices()); - IsabelleProblem translation; - try { - translation = translator.translateProblem(mediator.getSelectedGoal()); - } catch (IllegalFormulaException e) { - PositionedIssueString issueString = new PositionedIssueString( - "Failed to translate Goal " + mediator.getSelectedGoal().node().serialNr() + ": " + e.getMessage()); - IssueDialog issueDialog = - new IssueDialog(mainWindow, "Translations failed!", Set.of(issueString), false); - issueDialog.setVisible(true); - return; + List translations = new ArrayList<>(); + Map translationExceptions = new HashMap<>(); + for (Goal goal : Objects.requireNonNull(goals)) { + try { + translations.add(translator.translateProblem(goal)); + } catch (IllegalFormulaException e) { + translationExceptions.put(goal, e); + // Add problem without translation + translations.add(new IsabelleProblem(goal, translationExceptions.get(goal))); + } } - List list = new ArrayList<>(); - - list.add(translation); - Thread thread = new Thread(() -> { IsabelleLauncher launcher = new IsabelleLauncher(settings); @@ -74,9 +70,20 @@ private void generateTranslation() { launcher.addListener(progressDialogMediator); try { - launcher.launch(list, settings.getTimeout(), 1); + launcher.launch(translations, settings.getTimeout(), 1); + } catch (IsabelleNotFoundException e) { + progressDialogMediator.discardEvent(); + PositionedIssueString issueString = new PositionedIssueString(e.getMessage()); + IssueDialog issueDialog = + new IssueDialog(mainWindow, "Launch failed!", Set.of(issueString), true); + issueDialog.setVisible(true); } catch (IOException e) { + // Couldn't write files progressDialogMediator.discardEvent(); + PositionedIssueString issueString = new PositionedIssueString(e.getMessage()); + IssueDialog issueDialog = + new IssueDialog(mainWindow, "Launch failed!", Set.of(issueString), true); + issueDialog.setVisible(true); } }, "IsabelleLauncherThread"); thread.start(); From 6a4df92bd3e2ddbfdc380a08ce6dd200f0d7eff7 Mon Sep 17 00:00:00 2001 From: BookWood Date: Mon, 21 Oct 2024 18:24:35 +0200 Subject: [PATCH 243/248] changed prefix to postfix to avoid isabelle errors for UninterpretedSymbolsHandler --- .../translation/LogicalVariableHandler.java | 2 +- .../translation/UninterpretedSymbolsHandler.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java index e449fcca253..4ae94f2a301 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/LogicalVariableHandler.java @@ -17,7 +17,7 @@ */ public class LogicalVariableHandler implements IsabelleHandler { - static final String VAR_POSTFIX = UninterpretedSymbolsHandler.PREFIX; + static final String VAR_POSTFIX = UninterpretedSymbolsHandler.POSTFIX; @Override public void init(IsabelleMasterHandler masterHandler, Services services, diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java index c352c4fb106..ea94539be17 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/translation/UninterpretedSymbolsHandler.java @@ -23,7 +23,7 @@ */ public class UninterpretedSymbolsHandler implements IsabelleHandler { - public final static String PREFIX = "\\<^sub>v\\<^sub>a\\<^sub>r"; + public final static String POSTFIX = "\\<^sub>v\\<^sub>a\\<^sub>r"; @Override public void init(IsabelleMasterHandler masterHandler, Services services, @@ -52,7 +52,7 @@ private static boolean bindsVars(Operator op) { public StringBuilder handle(IsabelleMasterHandler trans, Term term) { SortedOperator op = (SortedOperator) term.op(); if (trans.isNewSymbol(term)) { - String name = PREFIX + op.name(); + String name = op.name() + POSTFIX; trans.addSymbolAndDeclaration(term, new StringBuilder(name.replace("::", "_").replace(".", "_") .replace("$", "_").replace("#", "_"))); From edac00df2b2eeee5e5e6d5cad5380c2321d06ca2 Mon Sep 17 00:00:00 2001 From: BookWood Date: Tue, 22 Oct 2024 11:36:05 +0200 Subject: [PATCH 244/248] add information buttons to display solver input, output and exception messages --- .../gui/InformationWindow.java | 98 +++++++++++++++++++ .../gui/IsabelleProgressDialog.java | 21 ++-- ...sabelleLauncherProgressDialogMediator.java | 30 +++++- 3 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/InformationWindow.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/InformationWindow.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/InformationWindow.java new file mode 100644 index 00000000000..0c879c18eef --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/InformationWindow.java @@ -0,0 +1,98 @@ +/* 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 org.key_project.isabelletranslation.gui; + +import java.awt.*; +import java.util.Collection; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.Element; + +import de.uka.ilkd.key.gui.configuration.Config; + +import org.key_project.util.java.StringUtil; + + +/** + * The information window is used to present detailed information about the execution of a solver. + * In particular it presents information about: - the concrete translation that was passed to the + * solver - the translation of the taclets - the messages that were sent between KeY and the + * external solvers. + *

+ * Adaptation of {@link de.uka.ilkd.key.gui.smt.InformationWindow} for Isabelle solvers + */ +public class InformationWindow extends JDialog { + public record Information(String title, String content, String solver) { + } + + private JTabbedPane tabbedPane; + + public InformationWindow(Dialog parent, Collection information, + String title) { + super(parent); + this.setTitle(title); + for (Information el : information) { + getTabbedPane().addTab(el.title, newTab(el)); + } + + setSize(600, 500); + this.getContentPane().add(getTabbedPane()); + this.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); + this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); + this.setLocationRelativeTo(parent); + this.setVisible(true); + } + + private Component newTab(Information information) { + final JTextArea lines = new JTextArea("1"); + final JTextArea content = new JTextArea(); + content.setFont(UIManager.getFont(Config.KEY_FONT_SEQUENT_VIEW)); + lines.setBackground(Color.LIGHT_GRAY); + lines.setEditable(false); + content.setEditable(false); + + content.getDocument().addDocumentListener(new DocumentListener() { + public String getText() { + int caretPosition = content.getDocument().getLength(); + Element root = content.getDocument().getDefaultRootElement(); + StringBuilder text = new StringBuilder("1" + StringUtil.NEW_LINE); + for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) { + text.append(i).append(StringUtil.NEW_LINE); + } + return text.toString(); + } + + @Override + public void changedUpdate(DocumentEvent de) { + lines.setText(getText()); + } + + @Override + public void insertUpdate(DocumentEvent de) { + lines.setText(getText()); + } + + @Override + public void removeUpdate(DocumentEvent de) { + lines.setText(getText()); + } + }); + content.setText(information.content); + content.setCaretPosition(0); + JScrollPane pane = new JScrollPane(); + pane.getViewport().add(content); + pane.setRowHeaderView(lines); + pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + return pane; + } + + + private JTabbedPane getTabbedPane() { + if (tabbedPane == null) { + tabbedPane = new JTabbedPane(); + } + return tabbedPane; + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java index e1631ad3dff..7a189b36d29 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/IsabelleProgressDialog.java @@ -299,7 +299,7 @@ private JButton getInfoButton() { content.add(Box.createHorizontalStrut(2)); content.add(getProgressBar()); content.add(Box.createHorizontalStrut(2)); - // content.add(getInfoButton()); + content.add(getInfoButton()); content.add(Box.createHorizontalStrut(2)); this.add(content); this.add(Box.createVerticalStrut(2)); @@ -325,9 +325,6 @@ public void setText(String text) { private class ProgressCellEditor extends AbstractCellEditor implements TableCellEditor { - private static final long serialVersionUID = 1L; - - @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { @@ -368,20 +365,18 @@ protected Color getSelectionBackground() { } - private final TableCellRenderer renderer = - (table, value, isSelected, hasFocus, row, column) -> { - ProcessData data = (ProcessData) value; - prepareProgressPanel(progressPanelRenderer, data); - return progressPanelRenderer; - }; - - private final TableCellEditor editor = new ProgressCellEditor(); private final Point currentEditorCell = new Point(); public ProgressTable(int resolution, ProgressTableListener listener) { + TableCellRenderer renderer = (table, value, isSelected, hasFocus, row, column) -> { + ProcessData data = (ProcessData) value; + prepareProgressPanel(progressPanelRenderer, data); + return progressPanelRenderer; + }; this.setDefaultRenderer(IsabelleProgressModel.ProcessColumn.class, renderer); + TableCellEditor editor = new ProgressCellEditor(); this.setDefaultEditor(IsabelleProgressModel.ProcessColumn.class, editor); init(getProgressPanelEditor(), this.getFont(), resolution, listener); init(progressPanelRenderer, this.getFont(), resolution, listener); @@ -428,7 +423,7 @@ public static void packColumn(JTable table, int vColIndex, int margin) { TableColumnModel colModel = table.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); - int width = 0; + int width; TableCellRenderer renderer = col.getHeaderRenderer(); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java index 46958c7b7bd..ebb672090df 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java @@ -7,9 +7,8 @@ import java.text.DecimalFormat; import java.time.Duration; import java.time.Instant; -import java.util.Collection; +import java.util.*; import java.util.Timer; -import java.util.TimerTask; import javax.swing.*; import de.uka.ilkd.key.core.KeYMediator; @@ -21,6 +20,7 @@ import org.key_project.isabelletranslation.automation.IsabelleLauncherListener; import org.key_project.isabelletranslation.automation.IsabelleResult; import org.key_project.isabelletranslation.automation.IsabelleSolver; +import org.key_project.isabelletranslation.gui.InformationWindow; import org.key_project.isabelletranslation.gui.IsabelleProgressDialog; import org.key_project.isabelletranslation.gui.IsabelleProgressModel; import org.key_project.isabelletranslation.gui.ProofApplyUserAction; @@ -427,6 +427,11 @@ private void parsing(IsabelleSolver solver) { private void waiting(IsabelleSolver solver) { } + private IsabelleSolver getSolver(int column, int row) { + // This needs to be changed, if different kinds of Isabelle solvers are supported + return solvers.stream().filter(s -> (s.getSolverIndex() == row)).findFirst().orElse(null); + } + /** * Updates the progress bar of a solver that is currently preparing. * @@ -449,6 +454,11 @@ public IsabelleProgressDialogListenerImpl() { @Override public void infoButtonClicked(int column, int row) { + IsabelleSolver solver = getSolver(column, row); + if (solver == null) { + throw new RuntimeException("Something went wrong in Dialog"); + } + showInformation(solver); } @Override @@ -466,4 +476,20 @@ public void discardButtonClicked() { discardEvent(); } } + + private void showInformation(IsabelleSolver solver) { + Collection information = new HashSet<>(); + information.add(new InformationWindow.Information("Translation theory", + solver.getRawSolverInput(), solver.name())); + if (solver.getFinalResult().isError()) { + information.add(new InformationWindow.Information("Exception", + solver.getFinalResult().getException().getMessage(), solver.name())); + } else { + information.add(new InformationWindow.Information("Raw Solver Output", + solver.getRawSolverOutput(), solver.name())); + } + + new InformationWindow(progressDialog, information, + "Information for " + solver.name()); + } } From 3bdb527880bea77759a4cc720a2392fd8a78573a Mon Sep 17 00:00:00 2001 From: Nils Buchholz Date: Wed, 23 Oct 2024 11:23:19 +0200 Subject: [PATCH 245/248] add AbstractExternalSolverRuleApp to allow other external solvers to close goals --- .../main/java/de/uka/ilkd/key/proof/Goal.java | 3 +- .../rule/AbstractExternalSolverRuleApp.java | 178 ++++++++++++++++++ .../java/de/uka/ilkd/key/smt/SMTRuleApp.java | 54 ++---- 3 files changed, 195 insertions(+), 40 deletions(-) create mode 100644 key.core/src/main/java/de/uka/ilkd/key/rule/AbstractExternalSolverRuleApp.java diff --git a/key.core/src/main/java/de/uka/ilkd/key/proof/Goal.java b/key.core/src/main/java/de/uka/ilkd/key/proof/Goal.java index 9885acd6145..5f9bc869cdb 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/proof/Goal.java +++ b/key.core/src/main/java/de/uka/ilkd/key/proof/Goal.java @@ -22,7 +22,6 @@ import de.uka.ilkd.key.rule.*; import de.uka.ilkd.key.rule.inst.SVInstantiations; import de.uka.ilkd.key.rule.merge.MergeRule; -import de.uka.ilkd.key.smt.SMTRuleApp; import de.uka.ilkd.key.strategy.AutomatedRuleApplicationManager; import de.uka.ilkd.key.strategy.QueueRuleApplicationManager; import de.uka.ilkd.key.strategy.Strategy; @@ -627,7 +626,7 @@ public ImmutableList apply(final RuleApp ruleApp) { } else { proof.replace(this, goalList); if (ruleApp instanceof TacletApp tacletApp && tacletApp.taclet().closeGoal() - || ruleApp instanceof SMTRuleApp) { + || ruleApp instanceof AbstractExternalSolverRuleApp) { // the first new goal is the one to be closed proof.closeGoal(goalList.head()); } diff --git a/key.core/src/main/java/de/uka/ilkd/key/rule/AbstractExternalSolverRuleApp.java b/key.core/src/main/java/de/uka/ilkd/key/rule/AbstractExternalSolverRuleApp.java new file mode 100644 index 00000000000..f5c03dd030e --- /dev/null +++ b/key.core/src/main/java/de/uka/ilkd/key/rule/AbstractExternalSolverRuleApp.java @@ -0,0 +1,178 @@ +/* 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.rule; + +import java.util.ArrayList; +import java.util.List; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.*; +import de.uka.ilkd.key.proof.Goal; + +import org.key_project.logic.Name; +import org.key_project.util.collection.ImmutableList; + +/** + * The rule application that is used when a goal is closed by means of an external solver. So far it + * stores the rule that that has been used and a title containing some information for the user. + *

+ * {@link de.uka.ilkd.key.smt.SMTRuleApp} + */ +public abstract class AbstractExternalSolverRuleApp extends AbstractBuiltInRuleApp { + protected final ExternalSolverRule rule; + protected final String title; + protected final String successfulSolverName; + + /** + * Creates a new AbstractExternalSolverRuleApp, + * + * @param rule the ExternalSolverRule to apply + * @param pio the position in the term to apply the rule to + * @param unsatCore an unsat core consisting of the formulas that are needed to prove the goal + * (optional null) + * @param successfulSolverName the name of the solver used to find the proof + * @param title the title of this rule app + */ + protected AbstractExternalSolverRuleApp(ExternalSolverRule rule, PosInOccurrence pio, + ImmutableList unsatCore, + String successfulSolverName, String title) { + super(rule, pio, unsatCore); + this.rule = rule.newRule(); + this.title = title; + this.successfulSolverName = successfulSolverName; + } + + /** + * Gets the title of this rule application + * + * @return title of this application + */ + public String getTitle() { + return title; + } + + /** + * Gets the name of the successful solver + * + * @return name of the successful solver + */ + public String getSuccessfulSolverName() { + return successfulSolverName; + } + + @Override + public BuiltInRule rule() { + return rule; + } + + @Override + public String displayName() { + return title; + } + + /** + * Interface for the rules of external solvers + */ + public interface ExternalSolverRule extends BuiltInRule { + Name name = new Name("ExternalSolverRule"); + + ExternalSolverRule newRule(); + + AbstractExternalSolverRuleApp createApp(String successfulSolverName); + + /** + * Create a new rule application with the given solver name and unsat core. + * + * @param successfulSolverName solver that produced this result + * @param unsatCore formulas required to prove the result + * @return rule application instance + */ + AbstractExternalSolverRuleApp createApp(String successfulSolverName, + ImmutableList unsatCore); + + @Override + AbstractExternalSolverRuleApp createApp(PosInOccurrence pos, TermServices services); + + + @Override + default boolean isApplicable(Goal goal, PosInOccurrence pio) { + return false; + } + + + /** + * Create a new goal (to be closed in {@link Goal#apply(RuleApp)} directly afterwards) + * with the same sequent as the given one. + * + * @param goal the Goal on which to apply ruleApp + * @param services the Services with the necessary information about the java programs + * @param ruleApp the rule application to be executed + * @return a list with an identical goal as the given goal + */ + @Override + default ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) { + if (goal.proof().getInitConfig().getJustifInfo().getJustification(newRule()) == null) { + goal.proof().getInitConfig().registerRule(newRule(), () -> false); + } + return goal.split(1); + } + + @Override + default boolean isApplicableOnSubTerms() { + return false; + } + + @Override + default String displayName() { + return "ExternalSolver"; + } + + @Override + String toString(); + + @Override + default Name name() { + return name; + } + + } + + /** + * Sets the title (needs to create a new instance for this) + * + * @param title new title for rule app + * @return copy of this with the new title + */ + public abstract AbstractExternalSolverRuleApp setTitle(String title); + + @Override + public AbstractExternalSolverRuleApp setIfInsts(ImmutableList ifInsts) { + setMutable(ifInsts); + return this; + } + + /** + * Create a new RuleApp with the same pio (in this case, that will probably be null as the + * AbstractExternalSolver rule is applied to the complete sequent) as this one. + * Add all top level formulas of the goal + * to the RuleApp's ifInsts. + * + * @param goal the goal to instantiate the current RuleApp on + * @return a new RuleApp with the same pio and all top level formulas of the goal as ifInsts + */ + @Override + public AbstractExternalSolverRuleApp tryToInstantiate(Goal goal) { + AbstractExternalSolverRuleApp app = rule.createApp(pio, goal.proof().getServices()); + Sequent seq = goal.sequent(); + List ifInsts = new ArrayList<>(); + for (SequentFormula ante : seq.antecedent()) { + ifInsts.add(new PosInOccurrence(ante, PosInTerm.getTopLevel(), true)); + } + for (SequentFormula succ : seq.succedent()) { + ifInsts.add(new PosInOccurrence(succ, PosInTerm.getTopLevel(), false)); + } + return app.setIfInsts(ImmutableList.fromList(ifInsts)); + } + +} diff --git a/key.core/src/main/java/de/uka/ilkd/key/smt/SMTRuleApp.java b/key.core/src/main/java/de/uka/ilkd/key/smt/SMTRuleApp.java index 9674a9ed1b8..ef4b9b38087 100644 --- a/key.core/src/main/java/de/uka/ilkd/key/smt/SMTRuleApp.java +++ b/key.core/src/main/java/de/uka/ilkd/key/smt/SMTRuleApp.java @@ -9,7 +9,7 @@ import de.uka.ilkd.key.java.Services; import de.uka.ilkd.key.logic.*; import de.uka.ilkd.key.proof.Goal; -import de.uka.ilkd.key.rule.AbstractBuiltInRuleApp; +import de.uka.ilkd.key.rule.AbstractExternalSolverRuleApp; import de.uka.ilkd.key.rule.BuiltInRule; import de.uka.ilkd.key.rule.RuleApp; @@ -17,14 +17,11 @@ import org.key_project.util.collection.ImmutableList; /** - * The rule application that is used when a goal is closed by means of an external solver. So far it + * The rule application that is used when a goal is closed by means of an SMT solver. So far it * stores the rule that that has been used and a title containing some information for the user. */ -public class SMTRuleApp extends AbstractBuiltInRuleApp { - +public class SMTRuleApp extends AbstractExternalSolverRuleApp { public static final SMTRule RULE = new SMTRule(); - private final String title; - private final String successfulSolverName; /** * Create a new rule app without ifInsts (will be null). @@ -37,11 +34,10 @@ public class SMTRuleApp extends AbstractBuiltInRuleApp { this(rule, pio, null, successfulSolverName); } - SMTRuleApp(SMTRule rule, PosInOccurrence pio, ImmutableList unsatCore, + SMTRuleApp(ExternalSolverRule rule, PosInOccurrence pio, + ImmutableList unsatCore, String successfulSolverName) { - super(rule, pio, unsatCore); - this.title = "SMT: " + successfulSolverName; - this.successfulSolverName = successfulSolverName; + super(rule, pio, unsatCore, successfulSolverName, "SMT: " + successfulSolverName); } @Override @@ -49,27 +45,20 @@ public SMTRuleApp replacePos(PosInOccurrence newPos) { return new SMTRuleApp(RULE, newPos, ifInsts, successfulSolverName); } - public String getTitle() { - return title; - } - - public String getSuccessfulSolverName() { - return successfulSolverName; - } - @Override public BuiltInRule rule() { return RULE; } - @Override - public String displayName() { - return title; - } - - public static class SMTRule implements BuiltInRule { + public static class SMTRule implements ExternalSolverRule { public static final Name name = new Name("SMTRule"); + @Override + public ExternalSolverRule newRule() { + return new SMTRule(); + } + + @Override public SMTRuleApp createApp(String successfulSolverName) { return new SMTRuleApp(this, null, successfulSolverName); } @@ -81,6 +70,7 @@ public SMTRuleApp createApp(String successfulSolverName) { * @param unsatCore formulas required to prove the result * @return rule application instance */ + @Override public SMTRuleApp createApp(String successfulSolverName, ImmutableList unsatCore) { return new SMTRuleApp(this, null, unsatCore, successfulSolverName); @@ -91,13 +81,6 @@ public SMTRuleApp createApp(PosInOccurrence pos, TermServices services) { return new SMTRuleApp(this, null, ""); } - - @Override - public boolean isApplicable(Goal goal, PosInOccurrence pio) { - return false; - } - - /** * Create a new goal (to be closed in {@link Goal#apply(RuleApp)} directly afterwards) * with the same sequent as the given one. @@ -115,16 +98,12 @@ public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) return goal.split(1); } - @Override - public boolean isApplicableOnSubTerms() { - return false; - } - @Override public String displayName() { return "SMT"; } + @Override public String toString() { return displayName(); } @@ -133,9 +112,9 @@ public String toString() { public Name name() { return name; } - } + @Override public SMTRuleApp setTitle(String title) { return new SMTRuleApp(RULE, pio, ifInsts, title); } @@ -168,5 +147,4 @@ public SMTRuleApp tryToInstantiate(Goal goal) { } return app.setIfInsts(ImmutableList.fromList(ifInsts)); } - } From 6cccf8e1aaf0085ba298e24e7bc0dfb7a1e4f814 Mon Sep 17 00:00:00 2001 From: BookWood Date: Wed, 23 Oct 2024 13:39:15 +0200 Subject: [PATCH 246/248] resolve differences to main in .gitlab-ci.yml --- .gitlab-ci.yml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f018e29b86c..e53ad22204e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -16,7 +16,7 @@ cache: key: ${CI_COMMIT_REF_SLUG} variables: - GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=2 -Dorg.gradle.configureondemand=true" + GRADLE_OPTS: "-Dorg.gradle.daemon=false -Dorg.gradle.parallel=true -Dorg.gradle.workers.max=2 -Dorg.gradle.configureondemand=true" GIT_DEPTH: 0 before_script: @@ -24,9 +24,6 @@ before_script: # - echo "$CI_BUILD_NAME, $CI_BUILD_REF_NAME $CI_BUILD_STAGE" # debug - export GRADLE_USER_HOME=`pwd`/.gradle - export SONAR_SCANNER_OPTS="-Xmx8G" - - sudo add-apt-repository ppa:cwchien/gradle - - sudo apt-get update - - sudo apt upgrade gradle stages: - primary @@ -48,7 +45,7 @@ compile:classes: - .gradle compile:testClasses: - dependencies: [ "compile:classes" ] + dependencies: ["compile:classes"] stage: secondary image: wadoon/key-test-docker:jdk17 script: @@ -62,7 +59,7 @@ compile:testClasses: - .gradle sonarqube: - dependencies: [ "compile:testClasses" ] + dependencies: ["compile:testClasses"] stage: ternary image: wadoon/key-test-docker:jdk17 allow_failure: true From b6d9b739e6e5ae6ac2dc502e409f2242f6024df3 Mon Sep 17 00:00:00 2001 From: BookWood Date: Wed, 23 Oct 2024 14:54:07 +0200 Subject: [PATCH 247/248] add custom IsabelleRuleApp to close goals --- .../automation/IsabelleLauncher.java | 2 +- .../automation/IsabelleRuleApp.java | 99 +++++++++++++++++++ .../IsabelleSledgehammerSolver.java | 10 +- .../gui/ProofApplyUserAction.java | 10 +- ...sabelleLauncherProgressDialogMediator.java | 14 +-- 5 files changed, 116 insertions(+), 19 deletions(-) create mode 100644 keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java index b2fcb1f6e59..5428bf779b7 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleLauncher.java @@ -207,7 +207,7 @@ public void processStarted(IsabelleSolver solver, IsabelleProblem problem) { if (!solverQueue.remove(solver)) { LOGGER.error( "Something went wrong during Isabelle instance management! Solver \"{}\" was not in queue, but started anyway.", - solver.name()); + solver.name() + ": " + solver.getProblem().getName()); stopAll(); throw new RuntimeException("Something went wrong during Isabelle instance management!"); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java new file mode 100644 index 00000000000..7213eaa1e75 --- /dev/null +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java @@ -0,0 +1,99 @@ +package org.key_project.isabelletranslation.automation; + +import de.uka.ilkd.key.java.Services; +import de.uka.ilkd.key.logic.PosInOccurrence; +import de.uka.ilkd.key.logic.TermServices; +import de.uka.ilkd.key.proof.Goal; +import de.uka.ilkd.key.rule.AbstractBuiltInRuleApp; +import de.uka.ilkd.key.rule.AbstractExternalSolverRuleApp; +import de.uka.ilkd.key.rule.RuleApp; +import org.key_project.logic.Name; +import org.key_project.util.collection.ImmutableList; + +public class IsabelleRuleApp extends AbstractExternalSolverRuleApp { + public static final IsabelleRule RULE = new IsabelleRule(); + + protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, String successfulSolverName, String successfulTactic) { + this(rule, pio, null, successfulSolverName, "Isabelle " + successfulSolverName + ": " + successfulTactic); + } + + protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, ImmutableList ifInsts, String successfulSolverName) { + this(rule, pio, ifInsts, successfulSolverName, "Isabelle: " + successfulSolverName); + } + + private IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, ImmutableList ifInsts, String successfulSolverName, String title) { + super(rule, pio, ifInsts, successfulSolverName, title); + } + + + + @Override + public AbstractExternalSolverRuleApp setTitle(String title) { + return new IsabelleRuleApp(RULE, pio, ifInsts, successfulSolverName, title); + } + + @Override + public AbstractBuiltInRuleApp replacePos(PosInOccurrence newPos) { + return new IsabelleRuleApp(RULE, newPos, successfulSolverName, title); + } + + public static class IsabelleRule implements ExternalSolverRule { + Name name = new Name("IsabelleRule"); + + @Override + public ExternalSolverRule newRule() { + return new IsabelleRule(); + } + + public AbstractExternalSolverRuleApp createApp(String successfulSolverName, String successfulTactic) { + return new IsabelleRuleApp(this, null, successfulSolverName, successfulTactic); + } + + @Override + public AbstractExternalSolverRuleApp createApp(String successfulSolverName) { + return new IsabelleRuleApp(this, null, successfulSolverName, ""); + } + + @Override + public AbstractExternalSolverRuleApp createApp(String successfulSolverName, ImmutableList unsatCore) { + return new IsabelleRuleApp(this, null, unsatCore, successfulSolverName); + } + + @Override + public AbstractExternalSolverRuleApp createApp(PosInOccurrence pos, TermServices services) { + return new IsabelleRuleApp(this, null, "", ""); + } + + /** + * Create a new goal (to be closed in {@link Goal#apply(RuleApp)} directly afterwards) + * with the same sequent as the given one. + * + * @param goal the Goal on which to apply ruleApp + * @param services the Services with the necessary information about the java programs + * @param ruleApp the rule application to be executed + * @return a list with an identical goal as the given goal + */ + @Override + public ImmutableList apply(Goal goal, Services services, RuleApp ruleApp) { + if (goal.proof().getInitConfig().getJustifInfo().getJustification(RULE) == null) { + goal.proof().getInitConfig().registerRule(RULE, () -> false); + } + return goal.split(1); + } + + @Override + public String toString() { + return displayName(); + } + + @Override + public String displayName() { + return "Isabelle"; + } + + @Override + public Name name() { + return name; + } + } +} diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java index fb760a07b89..675d580de08 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleSledgehammerSolver.java @@ -81,6 +81,7 @@ public class IsabelleSledgehammerSolver implements IsabelleSolver { private static final Logger LOGGER = LoggerFactory.getLogger(IsabelleSledgehammerSolver.class); private final Collection listeners; + private String rawOutput; public IsabelleSledgehammerSolver(IsabelleProblem problem, Collection listeners, int solverIndex, @@ -101,7 +102,7 @@ public int getSolverIndex() { @Override public String name() { - return "Isabelle Solver: " + problem.getName(); + return "sledgehammer"; } @Override @@ -159,7 +160,7 @@ public SolverState getState() { @Override public String getRawSolverOutput() { - return result.getSuccessfulTactic(); + return rawOutput; } @Override @@ -373,10 +374,13 @@ fun go_run (state, thy) = Tuple2>> resultFutureCollect = Await.result(resultFuture, Duration.create(getTimeout(), TimeUnit.SECONDS)); + rawOutput = resultFutureCollect._2().toString(); + boolean successful = (boolean) resultFutureCollect._1(); setComputationTime(); if (successful) { - return IsabelleResult.getSuccessResult(resultFutureCollect._2()._2().head(), + String successfulTactic = resultFutureCollect._2()._2().head().split("Try this: ")[1]; + return IsabelleResult.getSuccessResult(successfulTactic, getComputationTime()); } else { return IsabelleResult.getUnknownResult(); diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java index 8b6bb7d223d..24df428533a 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java @@ -12,9 +12,9 @@ import de.uka.ilkd.key.proof.Node; import de.uka.ilkd.key.proof.Proof; import de.uka.ilkd.key.rule.IBuiltInRuleApp; -import de.uka.ilkd.key.smt.SMTRuleApp; import org.key_project.isabelletranslation.automation.IsabelleProblem; +import org.key_project.isabelletranslation.automation.IsabelleRuleApp; import org.key_project.isabelletranslation.automation.IsabelleSolver; public class ProofApplyUserAction extends UserAction { @@ -49,13 +49,7 @@ protected void apply() { goalsClosed.add(goal); - // TODO SMTRuleApp does not serve any purpose as a SMT exclusive rule. - // The documentation does not suggest it should only be used for SMT, yet the name would - // suggest this. - // Changing this requires changing parts of the KeY core. This needs a different class, - // which does not prepend "SMT" to all titles - IBuiltInRuleApp app = SMTRuleApp.RULE.createApp("") - .setTitle("Isabelle: " + solver.getFinalResult().getSuccessfulTactic()); + IBuiltInRuleApp app = IsabelleRuleApp.RULE.createApp(solver.name(), solver.getFinalResult().getSuccessfulTactic()); app.tryToInstantiate(goal); goal.apply(app); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java index ebb672090df..fc093ab3e37 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/controller/IsabelleLauncherProgressDialogMediator.java @@ -102,6 +102,7 @@ public void launcherStopped(IsabelleLauncher launcher, Collection finishedInstances) { timer.cancel(); + setProgressText(finishedInstances.size()); progressModel.setEditable(true); refreshDialog(); progressDialog.setModus(IsabelleProgressDialog.Modus.SOLVERS_DONE); @@ -281,9 +282,6 @@ private void setProgressText(int value) { if (value < 0) { bar.setString("Preparing... (this might take a few seconds)"); bar.setStringPainted(true); - } else if (value == bar.getMaximum()) { - bar.setString("Finished."); - bar.setStringPainted(true); } else { bar.setString("Processed " + value + " of " + bar.getMaximum() + " problems."); bar.setStringPainted(true); @@ -479,17 +477,19 @@ public void discardButtonClicked() { private void showInformation(IsabelleSolver solver) { Collection information = new HashSet<>(); + String informationTitle = solver.name() + ": " + solver.getProblem().getName(); + information.add(new InformationWindow.Information("Translation theory", - solver.getRawSolverInput(), solver.name())); + solver.getRawSolverInput(), informationTitle)); if (solver.getFinalResult().isError()) { information.add(new InformationWindow.Information("Exception", - solver.getFinalResult().getException().getMessage(), solver.name())); + solver.getFinalResult().getException().getMessage(), informationTitle)); } else { information.add(new InformationWindow.Information("Raw Solver Output", - solver.getRawSolverOutput(), solver.name())); + solver.getRawSolverOutput(), informationTitle)); } new InformationWindow(progressDialog, information, - "Information for " + solver.name()); + "Information for " + informationTitle); } } From ee123ff389faf0a0b49c471bdbf5691e01e46fa5 Mon Sep 17 00:00:00 2001 From: BookWood Date: Wed, 23 Oct 2024 14:58:49 +0200 Subject: [PATCH 248/248] applied spotless --- .../automation/IsabelleRuleApp.java | 22 ++++++++++++++----- .../gui/ProofApplyUserAction.java | 3 ++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java index 7213eaa1e75..749ac05d31c 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/automation/IsabelleRuleApp.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 org.key_project.isabelletranslation.automation; import de.uka.ilkd.key.java.Services; @@ -7,21 +10,26 @@ import de.uka.ilkd.key.rule.AbstractBuiltInRuleApp; import de.uka.ilkd.key.rule.AbstractExternalSolverRuleApp; import de.uka.ilkd.key.rule.RuleApp; + import org.key_project.logic.Name; import org.key_project.util.collection.ImmutableList; public class IsabelleRuleApp extends AbstractExternalSolverRuleApp { public static final IsabelleRule RULE = new IsabelleRule(); - protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, String successfulSolverName, String successfulTactic) { - this(rule, pio, null, successfulSolverName, "Isabelle " + successfulSolverName + ": " + successfulTactic); + protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, String successfulSolverName, + String successfulTactic) { + this(rule, pio, null, successfulSolverName, + "Isabelle " + successfulSolverName + ": " + successfulTactic); } - protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, ImmutableList ifInsts, String successfulSolverName) { + protected IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, + ImmutableList ifInsts, String successfulSolverName) { this(rule, pio, ifInsts, successfulSolverName, "Isabelle: " + successfulSolverName); } - private IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, ImmutableList ifInsts, String successfulSolverName, String title) { + private IsabelleRuleApp(IsabelleRule rule, PosInOccurrence pio, + ImmutableList ifInsts, String successfulSolverName, String title) { super(rule, pio, ifInsts, successfulSolverName, title); } @@ -45,7 +53,8 @@ public ExternalSolverRule newRule() { return new IsabelleRule(); } - public AbstractExternalSolverRuleApp createApp(String successfulSolverName, String successfulTactic) { + public AbstractExternalSolverRuleApp createApp(String successfulSolverName, + String successfulTactic) { return new IsabelleRuleApp(this, null, successfulSolverName, successfulTactic); } @@ -55,7 +64,8 @@ public AbstractExternalSolverRuleApp createApp(String successfulSolverName) { } @Override - public AbstractExternalSolverRuleApp createApp(String successfulSolverName, ImmutableList unsatCore) { + public AbstractExternalSolverRuleApp createApp(String successfulSolverName, + ImmutableList unsatCore) { return new IsabelleRuleApp(this, null, unsatCore, successfulSolverName); } diff --git a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java index 24df428533a..5db2e43538a 100644 --- a/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java +++ b/keyext.isabelletranslation/src/main/java/org/key_project/isabelletranslation/gui/ProofApplyUserAction.java @@ -49,7 +49,8 @@ protected void apply() { goalsClosed.add(goal); - IBuiltInRuleApp app = IsabelleRuleApp.RULE.createApp(solver.name(), solver.getFinalResult().getSuccessfulTactic()); + IBuiltInRuleApp app = IsabelleRuleApp.RULE.createApp(solver.name(), + solver.getFinalResult().getSuccessfulTactic()); app.tryToInstantiate(goal); goal.apply(app); }